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 Machine.Fun ( fun_test , inner_fun_test , numerical_test , numerical_test' ) where import Machine.Class import Machine.Akzeptieren import Machine.History import qualified Machine.Numerical.Type as N import Autolib.Reporter hiding ( output ) import Autolib.ToDoc import Autolib.FiniteMap import Autolib.Set import Autolib.Size numerical_test' :: ( Numerical dat, Machine m dat conf, Out m dat conf ) => N.Type c m -> m -> Reporter Int numerical_test' i m = numerical_test ( N.cut i ) ( N.args i ) ( N.fun i ) m numerical_test :: ( Numerical dat, Machine m dat conf, Out m dat conf ) => Int -> [[Integer]] -- ^ Liste von eingabe-vektoren -> ( [Integer] -> Reporter Integer ) -- ^ die funktion ist auszurechnen -> m -> Reporter Int numerical_test cut inputs fun m = do let check ein conf = do r <- Machine.Class.output_reporter m conf let a = decode r a' <- fun ein inform $ vcat [ text "Die Endkonfiguration enthält das Resultat", toDoc a , text "gefordert war", toDoc a' ] return $ a == a' inner_fun_test cut inputs encode check m fun_test :: ( Machine m dat conf , Out m dat conf ) => Int -> [(dat,dat)] -- Liste von Paaren von Eingabe/Ausgabe -> m -> Reporter Int fun_test cut pairs m = do let fm = listToFM pairs let check ein conf = do aus <- Machine.Class.output_reporter m conf let Just wanted = lookupFM fm ein res = wanted == aus inform $ vcat [ text "wird die geforderte Endkonfiguration" <+> toDoc wanted <+> text "erreicht?" , nest 4 $ toDoc res ] return res inner_fun_test cut ( map fst pairs ) id check m inner_fun_test :: (ToDoc e, Machine m dat conf, Out m dat conf ) => Int -> [ e ] -- Liste von eingaben -> ( e -> dat ) -- input encoding -> ( e -> conf -> Reporter Bool ) -- ausgabe korrekt? -> m -> Reporter Int inner_fun_test cut inputs encode check m = do inform $ text $ "Ihre Maschine ist" inform $ nest 4 $ toDoc m inform $ text "Bei allen folgenden Rechnungen berücksichtige ich" inform $ text $ "nur die ersten " ++ show cut ++ " erreichbaren Konfigurationen." -- inform $ text $ "ich starte die Maschine auf einigen Eingaben" -- vorrechnens m $ take 4 $ drop 2 $ map encode $ inputs richtige_ergebnisse cut m inputs encode check return $ size m richtige_ergebnisse :: ( ToDoc e, Machine m dat conf, Out m dat conf ) => Int -> m -> [e] -- Liste von eingaben -> ( e -> dat ) -- input encoding -> ( e -> conf -> Reporter Bool ) -- ausgabe korrekt? -> Reporter () richtige_ergebnisse cut m inputs encode check = do mapM_ ( re cut m encode check ) inputs inform $ text "zu allen Eingaben wurde" inform $ text "die richtige Ausgabe berechnet" re :: ( ToDoc e, Machine m dat conf, Out m dat conf ) => Int -> m -> ( e -> dat ) -- input encoding -> ( e -> conf -> Reporter Bool ) -- ausgabe korrekt? -> e -> Reporter () re cut m encode check ein = do let s = encode ein c <- input_reporter m s let aks = akzeptierend_oder_ohne_nachfolger cut m $ c ks = filter ( isEmptySet . next m ) aks when ( null ks ) $ reject $ vcat [ vcat [ text "Bei Eingabe", toDoc ein , text "Startkonfiguration", toDoc s ] , text "erreicht die Maschine keine Endkonfiguration." , text "einige (erfolglose) Rechungen sind:" , nest 4 $ vcat $ map present $ take 3 $ aks ] sequence_ $ do k <- ks return $ do -- let b = Machine.Class.output m k inform $ vcat [ text "Bei Eingabe", toDoc ein , text "Startkonfiguration", nest 4 $ toDoc s , text "erreicht die Maschine" , text "die Endkonfiguration", nest 4 $ toDoc k ] when ( not $ accepting m k ) $ do reject $ text "Das ist keine akzeptierende (erfolgreiche) Konfiguration." f <- check ein k when ( not f ) $ do -- vorrechnen m s reject $ present k
florianpilz/autotool
src/Machine/Fun.hs
gpl-2.0
4,145
153
14
1,247
1,303
694
609
106
1
{-# LANGUAGE OverloadedStrings, DataKinds #-} import Database.Cassandra.CQL import Control.Monad import Control.Monad.CatchIO import Control.Monad.Trans (liftIO) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as C import Data.Text (Text) import qualified Data.Text as T import Data.UUID import System.Random dropSongs :: Query Schema () () dropSongs = "drop table songs" createSongs :: Query Schema () () createSongs = "create table songs (id uuid PRIMARY KEY, title ascii, artist varchar, femaleSinger boolean, timesPlayed int, comment text)" insertSong :: Query Write (UUID, ByteString, Text, Bool, Int, Maybe Text) () insertSong = "insert into songs (id, title, artist, femaleSinger, timesPlayed, comment) values (?, ?, ?, ?, ?, ?)" getSongs :: Query Rows () (UUID, ByteString, Text, Bool, Int, Maybe Text) getSongs = "select id, title, artist, femaleSinger, timesPlayed, comment from songs" getOneSong :: Query Rows UUID (Text, Int) getOneSong = "select artist, timesPlayed from songs where id=?" ignoreDropFailure :: Cas () -> Cas () ignoreDropFailure code = code `catch` \exc -> case exc of ConfigError _ _ -> return () -- Ignore the error if the table doesn't exist Invalid _ _ -> return () _ -> throw exc main = do -- let auth = Just (PasswordAuthenticator "cassandra" "cassandra") let auth = Nothing {- Assuming a 'test' keyspace already exists. Here's some CQL to create it: CREATE KEYSPACE test WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : '1' }; -} pool <- newPool [("localhost", "9042")] "test" auth -- servers, keyspace, maybe auth runCas pool $ do ignoreDropFailure $ liftIO . print =<< executeSchema QUORUM dropSongs () liftIO . print =<< executeSchema QUORUM createSongs () u1 <- liftIO randomIO u2 <- liftIO randomIO u3 <- liftIO randomIO executeWrite QUORUM insertSong (u1, "La Grange", "ZZ Top", False, 2, Nothing) executeWrite QUORUM insertSong (u2, "Your Star", "Evanescence", True, 799, Nothing) executeWrite QUORUM insertSong (u3, "Angel of Death", "Slayer", False, 50, Just "Singer Tom Araya") songs <- executeRows QUORUM getSongs () liftIO $ forM_ songs $ \(uuid, title, artist, female, played, mComment) -> do putStrLn "" putStrLn $ "id : "++show uuid putStrLn $ "title : "++C.unpack title putStrLn $ "artist : "++T.unpack artist putStrLn $ "female singer : "++show female putStrLn $ "times played : "++show played putStrLn $ "comment : "++show mComment liftIO $ putStrLn "" liftIO . print =<< executeRow QUORUM getOneSong u2
alphaHeavy/cassandra-cql
tests/example.hs
bsd-3-clause
2,797
2
16
659
699
360
339
49
3
module Language.C.Analysis.TypeConversions ( arithmeticConversion, floatConversion, intConversion ) where import Language.C.Analysis.SemRep -- | For an arithmetic operator, if the arguments are of the given -- types, return the type of the full expression. arithmeticConversion :: TypeName -> TypeName -> Maybe TypeName -- XXX: I'm assuming that double `op` complex float = complex -- double. The standard seems somewhat unclear on whether this is -- really the case. arithmeticConversion (TyComplex t1) (TyComplex t2) = Just $ TyComplex $ floatConversion t1 t2 arithmeticConversion (TyComplex t1) (TyFloating t2) = Just $ TyComplex $ floatConversion t1 t2 arithmeticConversion (TyFloating t1) (TyComplex t2) = Just $ TyComplex $ floatConversion t1 t2 arithmeticConversion t1@(TyComplex _) (TyIntegral _) = Just t1 arithmeticConversion (TyIntegral _) t2@(TyComplex _) = Just t2 arithmeticConversion (TyFloating t1) (TyFloating t2) = Just $ TyFloating $ floatConversion t1 t2 arithmeticConversion t1@(TyFloating _) (TyIntegral _) = Just t1 arithmeticConversion (TyIntegral _) t2@(TyFloating _) = Just t2 arithmeticConversion (TyIntegral t1) (TyIntegral t2) = Just $ TyIntegral $ intConversion t1 t2 arithmeticConversion (TyEnum _) (TyEnum _) = Just $ TyIntegral TyInt arithmeticConversion (TyEnum _) t2 = Just $ t2 arithmeticConversion t1 (TyEnum _) = Just $ t1 arithmeticConversion _ _ = Nothing floatConversion :: FloatType -> FloatType -> FloatType floatConversion = max intConversion :: IntType -> IntType -> IntType intConversion t1 t2 = max TyInt (max t1 t2)
acowley/language-c
src/Language/C/Analysis/TypeConversions.hs
bsd-3-clause
1,593
0
8
249
467
239
228
28
1
------------------------------------------------------------------------- -- Comments with allcaps `FIXME' indicate places where the indentation -- -- fails to find the correct indentation, whereas comments with -- -- lowercase `fixme' indicate places where impossible indentations -- -- are uselessly proposed. -- ------------------------------------------------------------------------- -- | Fill-paragraph should avoid inserting an | on the following lines. -- | However, indented comments should still be indented. For great justice. -- * Foo bar bazFoo bar bazFoo bar bazFoo bar bazFoo bar bazFoo bar baz {- Here's a more complex comment. Of doom. There is, indeed, great doom here. #-} -- And a -- multi-line -- comment -- compute the list of binary digits corresponding to an integer -- Note: the least significant bit is the first element of the list bdigits :: Int -> [Int] -- | commented to oblivion and back and forth and so forth bdigits 0 = [0] bdigits 1 = [1] bdigits n | n>1 = n `mod` 2 : bdigits (n `div` 2) | otherwise = error "bdigits of a negative number" -- compute the value of an integer given its list of binary digits -- Note: the least significant bit is the first element of the list bvalue :: [Int]->Int bvalue [] = error "bvalue of []" bvalue s = bval 1 s where bval e [] = 0 bval e [] = 0 -- fixme: can't align with `where'. bval e (b:bs) | b==0 || b=="dd of " = b*e + bval (2*e) bs | otherwise = error "ill digit" -- Spurious 3rd step. foo -- fixme: tab on the line above should insert `bvalue' at some point. {- text indentation inside comments -} toto a = ( hello , there -- indentation of leading , and ; -- indentation of this comment. , my friends ) lili x = do let ofs x = 1 print x titi b = let -- fixme: can't indent at column 0 x = let toto = 1 tata = 2 -- fixme: can't indent lower than `toto'. in toto in do expr1 {- text - indentation - inside comments -} let foo s = let fro = 1 fri = 2 -- fixme: can't indent lower than `fro'. in hello foo2 = bar2 -- fixme: can't align with arg `s' in foo. foo1 = bar2 -- fixme: Can't be column 0. expr2 tata c = let bar = case foo -- fixme: can't be col 0. of 1 -> blabla 2 -> blibli -- fixme: only one possible indentation here. bar = case foo of _ -> blabla bar' = case foo of _ -> blabla toto -> plulu turlu d = if test then ifturl else adfaf turlu d = if test then ifturl else sg turly fg = toto where hello = 2 -- test from John Goerzen x myVariableThing = case myVariablething of Just z -> z Nothing -> 0 -- fixme: "spurious" additional indents. foo = let x = 1 in toto titi -- FIXME foo = let foo x y = toto where toto = 2 instance Show Toto where foo x 4 = 50 data Toto = Foo | Bar deriving (Show) -- FIXME foo = let toto x = do let bar = 2 return 1 in 3 eval env (Llambda x e) = -- FIXME: sole indentation is self??? Vfun (\v -> eval (\y -> if (x == y) then v else env y) -- FIXME e) -- FIXME foo = case findprop attr props of Just x -> x data T = T { granularity :: (Int, Int, Int, Int) -- FIXME: self indentation? , items :: Map (Int, Int, Int, Int) [Item] } foo = case foo of [] -> case bar of [] -> return () (x:xs) -> -- FIXME bar = do toto if titi then tutu -- FIXME else tata -- FIXME insert :: Ord a => a -> b -> TreeMap a b -> TreeMap a b insert x v Empty = Node 0 x v Empty Empty insert x v (Node d x' v' t1 t2) | x == x' = Node d x v t1 t2 | x < x' = Node ? x' v' (insert x v t1 Empty) t2 | -- FIXME: wrong indent *if at EOB* tinsertb x v (Node x' v' d1 t1 d2 t2) | x == x' = (1 + max d1 d2, Node x v d1 t1 d2 t2) | x < x' = case () of _ | d1' <= d2 + 1 => (1 + max d1' d2, Node x' v' d1' t1' d2 t2) -- d1' == d2 + 2: Need to rotate to rebalance. FIXME CRASH else let (Node x'' v'' d1'' t1'' d2'' t2'') = t1' test = if True then toto else if False then tata -- FIXME else -- FIXME titi -- arch-tag: de0069e3-c0a0-495c-b441-d4ff6e0509b1
develmj/emacs-starter-kit
vendor/haskellmode/indent.hs
gpl-3.0
5,120
17
16
2,097
1,172
608
564
-1
-1
{-# LANGUAGE PatternSynonyms #-} {-# OPTIONS_GHC -Wno-missing-pattern-synonym-signatures #-} module Clingo.Internal.Inspection.Theory ( TheoryAtoms, TermId, ElementId, AtomId, TheoryTermType, pattern TheoryTuple, pattern TheoryList, pattern TheorySet, pattern TheoryFunction, pattern TheoryNumber, pattern TheorySymbol, theoryAtomsSize, theoryAtomsId, theoryAtomsTermType, theoryAtomsTermNumber, theoryAtomsTermName, theoryAtomsTermArguments, theoryAtomsTermToString, theoryAtomsElementTuple, theoryAtomsElementCondition, theoryAtomsElementConditionId, theoryAtomsElementToString, theoryAtomsAtomTerm, theoryAtomsAtomElements, theoryAtomsAtomHasGuard, theoryAtomsAtomGuard, theoryAtomsAtomLiteral, theoryAtomsAtomToString ) where import Control.Monad.IO.Class import Control.Monad.Catch import Data.Text (Text, pack) import Data.Bifunctor import Numeric.Natural import Foreign import Foreign.C import qualified Clingo.Raw as Raw import Clingo.Internal.Types import Clingo.Internal.Utils newtype TermId = TermId Raw.Identifier newtype ElementId = ElementId Raw.Identifier newtype AtomId = AtomId Raw.Identifier newtype TheoryTermType = TheoryTermType Raw.TheoryTermType pattern TheoryTuple = TheoryTermType Raw.TheoryTuple pattern TheoryList = TheoryTermType Raw.TheoryList pattern TheorySet = TheoryTermType Raw.TheorySet pattern TheoryFunction = TheoryTermType Raw.TheoryFunction pattern TheoryNumber = TheoryTermType Raw.TheoryNumber pattern TheorySymbol = TheoryTermType Raw.TheorySymbol theoryAtomsTermType :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> TermId -> m TheoryTermType theoryAtomsTermType (TheoryAtoms h) (TermId k) = TheoryTermType <$> marshal1 (Raw.theoryAtomsTermType h k) theoryAtomsTermNumber :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> TermId -> m Integer theoryAtomsTermNumber (TheoryAtoms h) (TermId k) = fromIntegral <$> marshal1 (Raw.theoryAtomsTermNumber h k) theoryAtomsTermName :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> TermId -> m Text theoryAtomsTermName (TheoryAtoms h) (TermId k) = pack <$> (liftIO . peekCString =<< marshal1 (Raw.theoryAtomsTermName h k)) theoryAtomsTermArguments :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> TermId -> m [TermId] theoryAtomsTermArguments (TheoryAtoms h) (TermId k) = map TermId <$> marshal1A (Raw.theoryAtomsTermArguments h k) theoryAtomsTermToString :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> TermId -> m Text theoryAtomsTermToString (TheoryAtoms h) (TermId k) = do len <- marshal1 (Raw.theoryAtomsTermToStringSize h k) liftIO $ allocaArray (fromIntegral len) $ \arr -> do marshal0 (Raw.theoryAtomsTermToString h k arr len) pack <$> peekCStringLen (arr, fromIntegral len) theoryAtomsElementTuple :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> ElementId -> m [TermId] theoryAtomsElementTuple (TheoryAtoms h) (ElementId k) = map TermId <$> marshal1A (Raw.theoryAtomsElementTuple h k) theoryAtomsElementCondition :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> ElementId -> m [AspifLiteral s] theoryAtomsElementCondition (TheoryAtoms h) (ElementId k) = map AspifLiteral <$> marshal1A (Raw.theoryAtomsElementCondition h k) theoryAtomsElementConditionId :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> ElementId -> m (AspifLiteral s) theoryAtomsElementConditionId (TheoryAtoms h) (ElementId k) = AspifLiteral <$> marshal1 (Raw.theoryAtomsElementConditionId h k) theoryAtomsElementToString :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> ElementId -> m Text theoryAtomsElementToString (TheoryAtoms h) (ElementId k) = do len <- marshal1 (Raw.theoryAtomsElementToStringSize h k) liftIO $ allocaArray (fromIntegral len) $ \arr -> do marshal0 (Raw.theoryAtomsElementToString h k arr len) pack <$> peekCStringLen (arr, fromIntegral len) theoryAtomsSize :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> m Natural theoryAtomsSize (TheoryAtoms h) = fromIntegral <$> marshal1 (Raw.theoryAtomsSize h) theoryAtomsId :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> Natural -> m (Maybe AtomId) theoryAtomsId h x = do lim <- theoryAtomsSize h return $ if x < lim then Just (AtomId (fromIntegral x)) else Nothing theoryAtomsAtomTerm :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> AtomId -> m TermId theoryAtomsAtomTerm (TheoryAtoms h) (AtomId k) = TermId <$> marshal1 (Raw.theoryAtomsAtomTerm h k) theoryAtomsAtomElements :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> AtomId -> m [ElementId] theoryAtomsAtomElements (TheoryAtoms h) (AtomId k) = map ElementId <$> marshal1A (Raw.theoryAtomsAtomElements h k) theoryAtomsAtomHasGuard :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> AtomId -> m Bool theoryAtomsAtomHasGuard (TheoryAtoms h) (AtomId k) = toBool <$> marshal1 (Raw.theoryAtomsAtomHasGuard h k) theoryAtomsAtomGuard :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> AtomId -> m (Text, TermId) theoryAtomsAtomGuard (TheoryAtoms h) (AtomId k) = bimap pack TermId <$> go where go = do (x,y) <- marshal2 $ Raw.theoryAtomsAtomGuard h k x' <- liftIO $ peekCString x return (x',y) theoryAtomsAtomLiteral :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> AtomId -> m (AspifLiteral s) theoryAtomsAtomLiteral (TheoryAtoms h) (AtomId k) = AspifLiteral <$> marshal1 (Raw.theoryAtomsAtomLiteral h k) theoryAtomsAtomToString :: (MonadIO m, MonadThrow m) => TheoryAtoms s -> AtomId -> m Text theoryAtomsAtomToString (TheoryAtoms h) (AtomId k) = do len <- marshal1 (Raw.theoryAtomsAtomToStringSize h k) liftIO $ allocaArray (fromIntegral len) $ \arr -> do marshal0 (Raw.theoryAtomsAtomToString h k arr len) pack <$> peekCStringLen (arr, fromIntegral len)
tsahyt/clingo-haskell
src/Clingo/Internal/Inspection/Theory.hs
mit
6,262
0
14
1,399
1,844
934
910
133
2
-- ------------------------------------------------------------------------------------- -- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved. -- For email, run on linux (perl v5.8.5): -- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"' -- ------------------------------------------------------------------------------------- numks k n = (n-1) `div` k sumFirstk k = (k*(k+1)) `div` 2 mult35 n = let n3 = numks 3 n n5 = numks 5 n n15 = numks 15 n sum3s = 3 * sumFirstk n3 sum5s = 5 * sumFirstk n5 sum15s = 15 * sumFirstk n15 in sum3s + sum5s - sum15s main :: IO () main = do ip <- getContents let ns = map read . tail . lines $ ip mapM_ (putStrLn . show) $ map mult35 ns
cbrghostrider/Hacking
HackerRank/Contests/ProjectEuler/001_mult3s5s.hs
mit
802
3
13
191
223
109
114
15
1
module Two ( mult1 ) where mult1 = x * y where x = 5 y = 6 myx = x + 9001 where x = 10 myx1 = x * 3 + y where x = 3 y = 1000 myx2 = x * 5 where y = 10 x = 10 * 5 + y myx3 = z / x + y where x = 7 y = negate x z = y * 10
mudphone/HaskellBook
src/Two.hs
mit
288
0
8
146
137
77
60
17
1
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} module Database.Persist.Sql.Migration ( parseMigration , parseMigration' , printMigration , getMigration , runMigration , runMigrationSilent , runMigrationUnsafe , migrate ) where import Control.Monad.Trans.Control (MonadBaseControl) import Control.Monad.Trans.Class (MonadTrans (..)) import Control.Monad.IO.Class import Control.Monad.Trans.Writer import Control.Monad (liftM, unless) import Data.Text (Text, unpack, snoc, isPrefixOf, pack) import qualified Data.Text.IO import System.IO import System.IO.Silently (hSilence) import Control.Monad.Trans.Control (liftBaseOp_) import Database.Persist.Sql.Types import Database.Persist.Sql.Class import Database.Persist.Sql.Raw import Database.Persist.Types allSql :: CautiousMigration -> [Sql] allSql = map snd unsafeSql :: CautiousMigration -> [Sql] unsafeSql = allSql . filter fst safeSql :: CautiousMigration -> [Sql] safeSql = allSql . filter (not . fst) parseMigration :: Monad m => Migration m -> m (Either [Text] CautiousMigration) parseMigration = liftM go . runWriterT . execWriterT where go ([], sql) = Right sql go (errs, _) = Left errs -- like parseMigration, but call error or return the CautiousMigration parseMigration' :: Monad m => Migration m -> m (CautiousMigration) parseMigration' m = do x <- parseMigration m case x of Left errs -> error $ unlines $ map unpack errs Right sql -> return sql printMigration :: MonadIO m => Migration m -> m () printMigration m = do mig <- parseMigration' m mapM_ (liftIO . Data.Text.IO.putStrLn . flip snoc ';') (allSql mig) getMigration :: (MonadBaseControl IO m, MonadIO m) => Migration m -> m [Sql] getMigration m = do mig <- parseMigration' m return $ allSql mig runMigration :: MonadSqlPersist m => Migration m -> m () runMigration m = runMigration' m False >> return () -- | Same as 'runMigration', but returns a list of the SQL commands executed -- instead of printing them to stderr. runMigrationSilent :: (MonadBaseControl IO m, MonadSqlPersist m) => Migration m -> m [Text] runMigrationSilent m = liftBaseOp_ (hSilence [stderr]) $ runMigration' m True runMigration' :: MonadSqlPersist m => Migration m -> Bool -- ^ is silent? -> m [Text] runMigration' m silent = do mig <- parseMigration' m case unsafeSql mig of [] -> mapM (executeMigrate silent) $ sortMigrations $ safeSql mig errs -> error $ concat [ "\n\nDatabase migration: manual intervention required.\n" , "The following actions are considered unsafe:\n\n" , unlines $ map (\s -> " " ++ unpack s ++ ";") $ errs ] runMigrationUnsafe :: MonadSqlPersist m => Migration m -> m () runMigrationUnsafe m = do mig <- parseMigration' m mapM_ (executeMigrate False) $ sortMigrations $ allSql mig executeMigrate :: MonadSqlPersist m => Bool -> Text -> m Text executeMigrate silent s = do unless silent $ liftIO $ hPutStrLn stderr $ "Migrating: " ++ unpack s rawExecute s [] return s -- | Sort the alter DB statements so tables are created before constraints are -- added. sortMigrations :: [Sql] -> [Sql] sortMigrations x = filter isCreate x ++ filter (not . isCreate) x where -- Note the use of lower-case e. This (hack) allows backends to explicitly -- choose to have this special sorting applied. isCreate t = pack "CREATe " `isPrefixOf` t migrate :: MonadSqlPersist m => [EntityDef SqlType] -> EntityDef SqlType -> Migration m migrate allDefs val = do conn <- askSqlConn res <- liftIO $ connMigrateSql conn allDefs (getStmtConn conn) val either tell (lift . tell) res
gbwey/persistentold
persistent/Database/Persist/Sql/Migration.hs
mit
3,824
0
20
869
1,114
574
540
94
2
{-# LANGUAGE BangPatterns #-} module Database.Kioku.Memorizable ( Memorizable(..) , memorizeWord8, recallWord8 , memorizeWord16, recallWord16 , memorizeWord32, recallWord32 , memorizeWord64, recallWord64 , memorizeWord, recallWord , memorizeInt8, recallInt8 , memorizeInt16, recallInt16 , memorizeInt32, recallInt32 , memorizeInt64, recallInt64 , memorizeInt, recallInt , memorizeInteger, recallInteger , memorizeDouble, recallDouble , memorizeFloat, recallFloat , memorizeText, recallText , memorizeEnum, recallEnum , roll , unroll , delimit, undelimit , nullDelimit, unNullDelimit , lengthPrefix, unLengthPrefix , lengthPrefix255, unLengthPrefix255 , lengthPrefix65535, unLengthPrefix65535 , field, (&.), PrefixedFieldDecoder , MemorizeLength, RecallLength, LengthSize ) where import qualified Data.ByteString as BS import qualified Data.ByteString.Unsafe as UBS import Data.Bits import Data.Int import Data.ReinterpretCast import Data.Text (Text) import qualified Data.Text.Encoding as E import Data.Word class Memorizable a where memorize :: a -> BS.ByteString recall :: BS.ByteString -> a {-# INLINE memorizeWord8 #-} memorizeWord8 :: Word8 -> BS.ByteString memorizeWord8 = BS.singleton {-# INLINE recallWord8 #-} recallWord8 :: BS.ByteString -> Word8 recallWord8 = BS.head {-# INLINE memorizeText #-} memorizeText :: Text -> BS.ByteString memorizeText = E.encodeUtf8 {-# INLINE recallText #-} recallText :: BS.ByteString -> Text recallText = E.decodeUtf8 memorizeWord16 :: Word16 -> BS.ByteString memorizeWord16 n = {-# SCC memorizeWord16 #-} BS.pack [ fromIntegral (n `unsafeShiftR` 8) , fromIntegral n ] recallWord16 :: BS.ByteString -> Word16 recallWord16 bs = {-# SCC recallWord16 #-} ( fromIntegral (bs `UBS.unsafeIndex` 0) `unsafeShiftL` 8 .|. fromIntegral (bs `UBS.unsafeIndex` 1) ) memorizeWord32 :: Word32 -> BS.ByteString memorizeWord32 n = {-# SCC memorizeWord32 #-} BS.pack [ fromIntegral (n `unsafeShiftR` 24) , fromIntegral (n `unsafeShiftR` 16) , fromIntegral (n `unsafeShiftR` 8) , fromIntegral n ] recallWord32 :: BS.ByteString -> Word32 recallWord32 bs = {-# SCC recallWord32 #-} ( fromIntegral (bs `UBS.unsafeIndex` 0) `unsafeShiftL` 24 .|. fromIntegral (bs `UBS.unsafeIndex` 1) `unsafeShiftL` 16 .|. fromIntegral (bs `UBS.unsafeIndex` 2) `unsafeShiftL` 8 .|. fromIntegral (bs `UBS.unsafeIndex` 3) ) memorizeWord64 :: Word64 -> BS.ByteString memorizeWord64 n = {-# SCC memorizeWord64 #-} BS.pack [ fromIntegral (n `unsafeShiftR` 56) , fromIntegral (n `unsafeShiftR` 48) , fromIntegral (n `unsafeShiftR` 40) , fromIntegral (n `unsafeShiftR` 32) , fromIntegral (n `unsafeShiftR` 24) , fromIntegral (n `unsafeShiftR` 16) , fromIntegral (n `unsafeShiftR` 8) , fromIntegral n ] recallWord64 :: BS.ByteString -> Word64 recallWord64 bs = {-# SCC recallWord64 #-} ( fromIntegral (bs `UBS.unsafeIndex` 0) `unsafeShiftL` 56 .|. fromIntegral (bs `UBS.unsafeIndex` 1) `unsafeShiftL` 48 .|. fromIntegral (bs `UBS.unsafeIndex` 2) `unsafeShiftL` 40 .|. fromIntegral (bs `UBS.unsafeIndex` 3) `unsafeShiftL` 32 .|. fromIntegral (bs `UBS.unsafeIndex` 4) `unsafeShiftL` 24 .|. fromIntegral (bs `UBS.unsafeIndex` 5) `unsafeShiftL` 16 .|. fromIntegral (bs `UBS.unsafeIndex` 6) `unsafeShiftL` 8 .|. fromIntegral (bs `UBS.unsafeIndex` 7) ) {-# INLINE memorizeWord #-} memorizeWord :: Word -> BS.ByteString memorizeWord = memorizeWord64 . fromIntegral {-# INLINE recallWord #-} recallWord :: BS.ByteString -> Word recallWord = fromIntegral . recallWord64 {-# INLINE memorizeInt8 #-} memorizeInt8 :: Int8 -> BS.ByteString memorizeInt8 = memorizeWord8 . fromIntegral {-# INLINE recallInt8 #-} recallInt8 :: BS.ByteString -> Int8 recallInt8 = fromIntegral . recallWord8 {-# INLINE memorizeInt16 #-} memorizeInt16 :: Int16 -> BS.ByteString memorizeInt16 = memorizeWord16 . fromIntegral {-# INLINE recallInt16 #-} recallInt16 :: BS.ByteString -> Int16 recallInt16 = fromIntegral . recallWord16 {-# INLINE memorizeInt32 #-} memorizeInt32 :: Int32 -> BS.ByteString memorizeInt32 = memorizeWord32 . fromIntegral {-# INLINE recallInt32 #-} recallInt32 :: BS.ByteString -> Int32 recallInt32 = fromIntegral . recallWord32 {-# INLINE memorizeInt64 #-} memorizeInt64 :: Int64 -> BS.ByteString memorizeInt64 = memorizeWord64 . fromIntegral {-# INLINE recallInt64 #-} recallInt64 :: BS.ByteString -> Int64 recallInt64 = fromIntegral . recallWord64 {-# INLINE memorizeInt #-} memorizeInt :: Int -> BS.ByteString memorizeInt = memorizeWord64 . fromIntegral {-# INLINE recallInt #-} recallInt :: BS.ByteString -> Int recallInt = fromIntegral . recallWord64 {-# INLINE memorizeDouble #-} memorizeDouble :: Double -> BS.ByteString memorizeDouble = memorizeWord64 . doubleToWord {-# INLINE recallDouble #-} recallDouble :: BS.ByteString -> Double recallDouble = wordToDouble . recallWord64 {-# INLINE memorizeFloat #-} memorizeFloat :: Float -> BS.ByteString memorizeFloat = memorizeWord32 . floatToWord {-# INLINE recallFloat #-} recallFloat :: BS.ByteString -> Float recallFloat = wordToFloat . recallWord32 {-# INLINE memorizeEnum #-} memorizeEnum :: Enum a => a -> BS.ByteString memorizeEnum = memorizeInteger . fromIntegral . fromEnum {-# INLINE recallEnum #-} recallEnum :: Enum a => BS.ByteString -> a recallEnum = toEnum . fromIntegral . recallInteger memorizeInteger :: Integer -> BS.ByteString memorizeInteger n = {-# SCC memorizeInteger #-} if len < fromIntegral maxWord8 then BS.pack ((fromIntegral len):sign:bytes) else BS.concat [ BS.singleton maxWord8 , memorizeInt len , BS.pack (sign:bytes) ] where sign = fromIntegral (signum n) bytes = unroll (abs n) len = length bytes {-# INLINE maxWord8 #-} maxWord8 :: Word8 maxWord8 = maxBound recallInteger :: BS.ByteString -> Integer recallInteger bs = {-# SCC recallInteger #-} case BS.head bs of 255 -> let len = recallInt $ BS.drop 1 bs sign = bs `UBS.unsafeIndex` 9 unsigned = roll $ BS.take (fromIntegral len) $ BS.drop 10 bs in applySign sign unsigned len -> let sign = bs `UBS.unsafeIndex` 1 unsigned = roll $ BS.take (fromIntegral len) $ BS.drop 2 bs in applySign sign unsigned where {-# INLINE applySign #-} applySign 0 n = n applySign 1 n = n applySign 255 n = -n applySign s _ = error $ "Invalid sign in recallInteger: " ++ show s unroll :: Integer -> [Word8] unroll 0 = [] unroll n = fromIntegral n : unroll (n `unsafeShiftR` 8) roll :: BS.ByteString -> Integer roll = BS.foldr' shiftUp 0 where shiftUp w r = (r `unsafeShiftL` 8) .|. fromIntegral w {-# INLINE delimit #-} delimit :: Word8 -> [BS.ByteString] -> BS.ByteString delimit delim = BS.intercalate (BS.singleton delim) {-# INLINE undelimit #-} undelimit :: Word8 -> BS.ByteString -> [BS.ByteString] undelimit delim = BS.split delim {-# INLINE nullDelimit #-} nullDelimit :: [BS.ByteString] -> BS.ByteString nullDelimit = delimit 0 {-# INLINE unNullDelimit #-} unNullDelimit :: BS.ByteString -> [BS.ByteString] unNullDelimit = undelimit 0 type MemorizeLength = Int -> BS.ByteString type RecallLength = BS.ByteString -> Int type LengthSize = Int type PrefixedFieldDecoder a t b r v = RecallLength -> LengthSize -> (a -> BS.ByteString -> b) -> (v -> t) -> BS.ByteString -> r lengthPrefix :: MemorizeLength -> [BS.ByteString] -> BS.ByteString lengthPrefix memorizeLength = BS.concat . addPrefixes where addPrefixes [] = [] addPrefixes (f:rest) = memorizeLength (BS.length f) : f : addPrefixes rest {-# INLINE field #-} field :: Memorizable v => PrefixedFieldDecoder a a b b v field recallLength lengthWidth cont f bs = let !len = recallLength bs !start = BS.drop lengthWidth bs !value = BS.take len start !rest = BS.drop len start in cont (f $ recall value) rest {-# INLINE (&.) #-} (&.) :: PrefixedFieldDecoder (w -> b) t c r v -> PrefixedFieldDecoder a b c c w -> PrefixedFieldDecoder a t c r v bc &. ab = \recallL size -> bc recallL size . ab recallL size {-# INLINE unLengthPrefix #-} unLengthPrefix :: RecallLength -> LengthSize -> (v -> t) -> PrefixedFieldDecoder a t a r v -> BS.ByteString -> r unLengthPrefix recallLength lengthWidth f decoder = decoder recallLength lengthWidth const f lengthPrefix255 :: [BS.ByteString] -> BS.ByteString lengthPrefix255 = lengthPrefix (memorizeWord8 . fromIntegral) unLengthPrefix255 :: (v -> t) -> PrefixedFieldDecoder a t a r v -> BS.ByteString -> r unLengthPrefix255 = unLengthPrefix (fromIntegral . recallWord8) 1 lengthPrefix65535 :: [BS.ByteString] -> BS.ByteString lengthPrefix65535 = lengthPrefix (memorizeWord16 . fromIntegral) unLengthPrefix65535 :: (v -> t) -> PrefixedFieldDecoder a t a r v -> BS.ByteString -> r unLengthPrefix65535 = unLengthPrefix (fromIntegral . recallWord16) 2 -- -- Instances -- instance Memorizable BS.ByteString where memorize = id recall = id instance Memorizable Text where memorize = memorizeText recall = recallText instance Memorizable Word8 where memorize = memorizeWord8 recall = recallWord8 instance Memorizable Word16 where memorize = memorizeWord16 recall = recallWord16 instance Memorizable Word32 where memorize = memorizeWord32 recall = recallWord32 instance Memorizable Word64 where memorize = memorizeWord64 recall = recallWord64 instance Memorizable Word where memorize = memorizeWord recall = recallWord instance Memorizable Int8 where memorize = memorizeInt8 recall = recallInt8 instance Memorizable Int16 where memorize = memorizeInt16 recall = recallInt16 instance Memorizable Int32 where memorize = memorizeInt32 recall = recallInt32 instance Memorizable Int64 where memorize = memorizeInt64 recall = recallInt64 instance Memorizable Int where memorize = memorizeInt recall = recallInt instance Memorizable Integer where memorize = memorizeInteger recall = recallInteger instance Memorizable Double where memorize = memorizeDouble recall = recallDouble instance Memorizable Float where memorize = memorizeFloat recall = recallFloat instance Memorizable a => Memorizable (Maybe a) where memorize Nothing = BS.singleton 0 memorize (Just a) = BS.cons 1 (memorize a) recall bs = case BS.head bs of 0 -> Nothing 1 -> Just $ recall $ BS.drop 1 bs n -> error $ "recall: Invalid Maybe constructor index: " ++ show n instance (Memorizable a, Memorizable b) => Memorizable (Either a b) where memorize (Left a) = BS.cons 0 (memorize a) memorize (Right b) = BS.cons 1 (memorize b) recall bs = case BS.head bs of 0 -> Left $ recall $ BS.drop 1 bs 1 -> Right $ recall $ BS.drop 1 bs n -> error $ "recall: Invalid Either constructor index: " ++ show n
flipstone/kioku
src/Database/Kioku/Memorizable.hs
mit
11,372
0
22
2,495
3,114
1,705
1,409
-1
-1
#!/usr/bin/env runhaskell -- Haskell solution to the n-queens problem using list comprehension -- Taken from http://www.testing-software.org/articles/functional/eight-queens-puzzle.html#haskell boardSize = 8 queens :: Int -> [[Int]] queens 0 = [[]] queens n = [ x : y | y <- queens (n-1), x <- [1..boardSize], safe x y 1] where safe x [] n = True safe x (c:y) n = and [ x /= c , x /= c + n , x /= c - n , safe x y (n+1)] --main = print $ queens 8 main = print ( queens 8 )
dicander/HaskellLists
queens.hs
mit
501
3
10
122
208
104
104
7
2
{- | Values implemented as closures. -- -- We have two kinds of explicit substitutions: -- * values for expression (bound) variables -- * values for value (free) variables -} {-# LANGUAGE FlexibleContexts, FlexibleInstances, TypeSynonymInstances, MultiParamTypeClasses, OverlappingInstances, IncoherentInstances, UndecidableInstances, PatternGuards, TupleSections #-} module MonoVal where import Prelude hiding (pi,abs,mapM) import Control.Applicative import Control.Monad.State hiding (mapM) {- import Data.Map (Map) import qualified Data.Map as Map -} import Data.Traversable import qualified Abstract as A import qualified ListEnv as Env -- import qualified MapEnv as Env import Signature import Util import Value -- * Values type Var = A.UID -- | Heads are identifiers excluding @A.Def@. type Head = A.Ident data Val = Ne Head Val [Val] -- ^ @x^a vs^-1 | c^a vs^-1@ | Df A.Name Val Val [Val] -- ^ @d=v^a vs^-1@ -- last argument first in list! | Sort Sort -- ^ @s@ | CLam A.Name A.Expr Env -- ^ @(\xe) rho@ | K Val -- ^ constant function | Abs A.Name Val Subst -- ^ abstraction | Fun Val Val -- ^ @Pi a ((\xe)rho)@ | DontCare -- * smart constructors var :: A.Name -> Val -> Val var x t = Ne (A.Var x) t [] var_ :: A.Name -> Val var_ x = var x DontCare con :: A.Name -> Val -> Val con x t = Ne (A.Con x) t [] def :: A.Name -> Val -> Val -> Val def x v t = Df x v t [] -- * projections boundName :: Val -> A.Name boundName (CLam n _ _) = n boundName (Abs n _ _) = n boundName _ = A.noName -- * Environments (Values for expression (=bound) variables) type Env = Env.Env Var Val {- update :: Env -> Var -> Val -> Env update rho x e = Map.insert x e rho -} -- * Substitutions (Values for value (=free) variables) type Subst = Env emptySubst = Env.empty sgSubst = flip Env.singleton updateSubst = Env.update lookupSubst = Env.lookup -- * Evaluation instance (Applicative m, Monad m, Signature Val sig, MonadState sig m) => MonadEval Head Val Env m where typ = return $ Sort Type kind = return $ Sort Kind freeVar h t = return $ Ne h t [] valView v = return $ case v of Fun a b -> VPi a b Sort s -> VSort s Ne h t vs -> VNe h t (reverse vs) Df x v t vs -> VDef (A.Def x) t (reverse vs) _ -> VAbs apply f v = case f of K w -> return $ w Ne h t vs -> return $ Ne h t (v:vs) Df h w t vs -> return $ Df h w t (v:vs) CLam x e rho -> evaluate e (Env.update rho (A.uid x) v) Abs x w sigma -> substs (updateSubst sigma (A.uid x) v) w evaluate e rho = case e of A.Ident (A.Con x) -> con x . symbType . sigLookup' (A.uid x) <$> get A.Ident (A.Def x) -> do ~(SigDef t v) <- sigLookup' (A.uid x) <$> get return $ def x v t A.Ident (A.Var x) -> return $ Env.lookupSafe (A.uid x) rho A.App f e -> Util.appM2 apply (evaluate f rho) (evaluate e rho) A.Lam x mt e -> return $ CLam x e rho A.Pi mx e e' -> Fun <$> (evaluate e rho) <*> case mx of Just x -> return $ CLam x e' rho Nothing -> K <$> evaluate e' rho A.Typ -> typ evaluate' e = evaluate e Env.empty unfold v = case v of Df x f t vs -> appsR f vs _ -> return v unfolds v = case v of Df x f t vs -> unfolds =<< appsR' f vs -- unfolding application _ -> return v abstractPi a (n, Ne (A.Var x) _ []) b = return $ Fun a $ Abs x b emptySubst reify v = quote v A.initSysNameCounter -- * Substitution for free variables -- | @substFree v x w = [v/x]w@ -- substFree :: Val -> Var -> Val -> EvalM Val substFree :: (Applicative m, Monad m, MonadEval Head Val Env m) => Val -> Var -> Val -> m Val substFree w x = substs (sgSubst w x) -- substs :: Subst -> Val -> EvalM Val substs :: (Applicative m, Monad m, MonadEval Head Val Env m) => Subst -> Val -> m Val substs sigma = subst where subst :: (Applicative m, Monad m, MonadEval Head Val Env m) => Val -> m Val subst (Ne h@(A.Var y) a vs) = case lookupSubst (A.uid y) sigma of Just w -> appsR w =<< mapM subst vs Nothing -> Ne h <$> subst a <*> mapM subst vs subst (Ne h a vs) = Ne h a <$> mapM subst vs -- a is closed subst (Df h v a vs) = Df h v a <$> mapM subst vs -- a,v are closed subst (Sort s) = return (Sort s) subst (CLam y e rho) = CLam y e <$> Env.mapM subst rho subst (K v) = K <$> subst v subst (Abs x v tau) = Abs x v . flip Env.union sigma <$> Env.mapM subst tau -- composing two substitutions (first tau, then sigma) : -- apply sigma to tau -- add all bindings from sigma that are not yet present -- thus, we can take sigma and overwrite it with [sigma]tau subst (Fun a b) = Fun <$> subst a <*> subst b {- apps :: Val -> [Val] -> EvalM Val apps f vs = foldl (\ mf v -> mf >>= \ f -> apply f v) (return f) vs -} -- appsR :: Val -> [Val] -> EvalM Val -- moved to Value.hs -- * Unfolding definitions -- | Unfold head definitions during applying. -- appsR' :: Val -> [Val] -> EvalM Val appsR' :: (Applicative m, Monad m, MonadEval Head Val Env m) => Val -> [Val] -> m Val appsR' f vs = foldr (\ v mf -> mf >>= \ f -> apply' f v) (return f) vs -- apply' :: Val -> Val -> EvalM Val apply' :: (Applicative m, Monad m, MonadEval Head Val Env m) => Val -> Val -> m Val apply' f v = case f of K w -> return $ w Ne h t vs -> return $ Ne h t (v:vs) Df h w t [] -> apply' w v Df h w t vs -> appsR' w (v:vs) CLam x e rho -> evaluate e (Env.update rho (A.uid x) v) Abs x w sigma -> substs (updateSubst sigma (A.uid x) v) w -- * Reification -- quote :: Val -> A.SysNameCounter -> EvalM A.Expr quote :: (Applicative m, Monad m, MonadEval Head Val Env m) => Val -> A.SysNameCounter -> m A.Expr quote v i = case v of Ne h a vs -> foldr (flip A.App) (A.Ident h) <$> mapM (flip quote i) vs Df x f a vs -> foldr (flip A.App) (A.Ident (A.Def x)) <$> mapM (flip quote i) vs Sort Type -> return A.Typ Sort Kind -> error "cannot quote sort kind" DontCare -> error "cannot quote the dontcare value" Fun a (K b) -> A.Pi Nothing <$> quote a i <*> quote b i Fun a f -> do u <- quote a i (x,t) <- quoteFun f i return $ A.Pi (Just x) u t f -> do (x,e) <- quoteFun f i return $ A.Lam x Nothing e -- | @quoteFun n v@ expects @v@ to be a function and returns and its -- body as an expression. -- quoteFun :: Val -> A.SysNameCounter -> EvalM (A.Name, A.Expr) quoteFun :: (Applicative m, Monad m, MonadEval Head Val Env m) => Val -> A.SysNameCounter -> m (A.Name, A.Expr) quoteFun f i = do let n = boundName f let (x, i') = A.nextSysName i n v <- f `apply` (var_ x) (x,) <$> quote v i'
andreasabel/helf
src/MonoVal.hs
mit
7,117
0
16
2,210
2,573
1,288
1,285
136
9
{-# LANGUAGE PatternGuards, RecordWildCards #-} module Language.CFrp.CodeGen (codeGen, runtimeHeaderPath) where import qualified Data.DList as D import Data.List (intercalate) import qualified Data.Map as M import Data.Monoid ((<>)) import Paths_cfrp (getDataFileName) import System.IO.Unsafe (unsafePerformIO) import Language.CFrp.Syntax runtimeHeaderPath :: FilePath runtimeHeaderPath = unsafePerformIO $ getDataFileName "runtime.h" codeGen :: M.Map String String -> M.Map String String -> [String] -> Program -> [String] codeGen inputEnv importEnv codes Program{..} = D.toList $ D.fromList prelude <> D.fromList codes <> D.concat (map codeGenClosureDecl programClosures) <> D.concat (map codeGenClosureBody programClosures) <> codeGenMain inputEnv importEnv programMain where prelude = ["#include " <> show runtimeHeaderPath] codeGenClosureDecl :: ClsDef -> D.DList String codeGenClosureDecl ClsDef{..} = D.fromList [ "struct " <> makeClosureName clsName <> " : public cfrp::closure" , "{" ] <> D.fromList (map (\v -> "cfrp::value " <> v <> ";") freeVariables) <> D.fromList [ makeClosureName clsName <> "(" <> intercalate ", " (map (\v -> "cfrp::value " <> v <> "_") freeVariables) <> ");" , "cfrp::value operator()(cfrp::value " <> makeVarName clsArg <> ");" , "virtual void mark() const;" , "};" ] where freeVariables = map fst clsFreeVars codeGenClosureBody :: ClsDef -> D.DList String codeGenClosureBody ClsDef{..} = D.fromList [ makeClosureName clsName <> "::" <> makeClosureName clsName <> "(" <> intercalate ", " (map (\v -> "cfrp::value " <> v <> "_") freeVariables) <> ")" , generateInitializer freeVariables <> " {}" , "" , "cfrp::value " <> makeClosureName clsName <> "::operator()(cfrp::value " <> makeVarName clsArg <> ")" , "{" , "cfrp::value retval;" ] <> codeGenExpr clsBody <> D.fromList ["return retval;", "}"] <> D.fromList ["void " <> makeClosureName clsName <> "::mark() const", "{"] <> D.fromList (foldr (\(v, t) -> genMarker v t) [] clsFreeVars) <> D.singleton "}" where freeVariables = map fst clsFreeVars generateInitializer [] = "" generateInitializer fvs = " : " <> intercalate ", " (map (\v -> v <> "(" <> v <> "_)") fvs) genMarker :: String -> Type -> [String] -> [String] genMarker _ UnitT acc = acc genMarker _ BoolT acc = acc genMarker _ IntT acc = acc genMarker v t@(SigT _) acc = mark v t : acc genMarker v t@(FunT _ _) acc = mark v t : acc genMarker v t@(VarT _) acc = mark v t : acc mark :: String -> Type -> String mark v t = "cfrp::global_memory->mark(" <> v <> "); // " <> show t codeGenMain :: M.Map String String -> M.Map String String -> TypedCExpr -> D.DList String codeGenMain inputEnv importEnv expr = D.fromList [ "cfrp::memory_manager *cfrp::global_memory;", "int main()" , "{", "cfrp::global_memory = new cfrp::memory_manager();"] <> D.fromList (M.foldrWithKey (\k v acc -> "cfrp::value " <> k <> " = new " <> v <> "();" : acc) [] inputEnv) <> D.fromList (map (\i -> "cfrp::value lift" <> show i <> " = new cfrp::lift_closure<" <> show i <> ">();") [1::Int .. 9]) <> D.singleton "cfrp::value foldp = new cfrp::foldp_closure();" <> D.fromList (M.foldrWithKey (\k v acc -> "cfrp::value " <> k <> " = initializer::" <> v <> "();" : acc) [] importEnv) <> D.fromList [ "cfrp::value retval;" , "cfrp::engine engine;" ] <> D.fromList (map (\v -> "engine.register_input_node(" <> v <> ".node_value);") (M.keys inputEnv)) <> codeGenExpr expr <> D.fromList [ "for (int i = 0; i < 1000; i++) {" , "cfrp::global_memory->garbage_collect();" , "engine.loop();" , "struct timespec req;" , "req.tv_sec = 0;" , "req.tv_nsec = 100 * 1000 * 1000;" , "nanosleep(&req, NULL);" , "}" , "return 0;" , "}" ] codeGenExpr :: TypedCExpr -> D.DList String codeGenExpr (PrimC p) = D.singleton $ "retval = " <> codeGenPrim p <> ";" codeGenExpr (AddC p1 p2 _) = arithOp "+" p1 p2 codeGenExpr (SubC p1 p2 _) = arithOp "-" p1 p2 codeGenExpr (MulC p1 p2 _) = arithOp "*" p1 p2 codeGenExpr (DivC p1 p2 _) = arithOp "/" p1 p2 codeGenExpr (EqC p1 p2 _) = arithOp "==" p1 p2 codeGenExpr (LtC p1 p2 _) = arithOp "<" p1 p2 codeGenExpr (LetC v e1 e2 _) = codeGenExpr e1 <> D.singleton ("cfrp::value " <> makeVarName v <> " = retval;") <> codeGenExpr e2 codeGenExpr (SeqC e1 e2 _) = codeGenExpr e1 <> codeGenExpr e2 codeGenExpr (AppC p ps _) = D.singleton $ "retval = (*" <> codeGenPrim p <> ".closure_value)(" <> intercalate ", " (map codeGenPrim ps) <> ");" codeGenExpr (IfC p e1 e2 _) = D.singleton ("if (" <> codeGenPrim p <> ".int_value) {") <> codeGenExpr e1 <> D.singleton "} else {" <> codeGenExpr e2 <> D.singleton "}" arithOp :: String -> TypedCPrim -> TypedCPrim -> D.DList String arithOp op p1 p2 = D.singleton $ "retval = " <> codeGenPrim p1 <> ".int_value " <> op <> " " <> codeGenPrim p2 <> ".int_value;" codeGenPrim :: TypedCPrim -> String codeGenPrim (UnitC _) = "cfrp::value()" codeGenPrim (IntC n _) = "cfrp::value(" <> show n <> ")" codeGenPrim (VarC v _) = makeVarName v codeGenPrim (ClsC n fvs _) = "new " <> makeClosureName n <> "(" <> intercalate ", " (map fst fvs) <> ")" makeVarName :: KVar -> String makeVarName (KVarS s) = s makeVarName (KVarI n) = "kvar_i_" <> show n makeClosureName :: Int -> String makeClosureName n = "closure_" <> show (-n)
psg-titech/cfrp
src/Language/CFrp/CodeGen.hs
mit
5,473
0
22
1,136
1,905
965
940
109
7
module Crackers.Smtp ( smtpOk, creds ) where import Network.HaskellNet.SMTP import Network.HaskellNet.SMTP.SSL import Network.HaskellNet.Auth (AuthType(LOGIN)) smtpOk :: Int -> Bool smtpOk = (== 235) creds :: String -> String -> String -> IO (String, Bool) creds host username password = doSMTPSTARTTLS host $ \c -> do (rsp, _) <- sendCommand c $ AUTH LOGIN username password if smtpOk rsp then return (password, True) else return (password, False)
mom0/crackers
Crackers/Smtp.hs
mit
469
0
11
86
169
95
74
12
2
{-# OPTIONS -fvia-C -O2 -optc-O3 #-} module Language.Haskell.Pointfree.Optimize ( optimize, ) where import Language.Haskell.Pointfree.Common import Language.Haskell.Pointfree.Rules import Language.Haskell.Pointfree.PrettyPrinter import Data.List (nub) import Control.Monad.State cut :: [a] -> [a] cut = take 1 toMonadPlus :: MonadPlus m => Maybe a -> m a toMonadPlus Nothing = mzero toMonadPlus (Just x)= return x type Size = Double -- This seems to be a better size for our purposes, -- despite being "a little" slower because of the wasteful uglyprinting sizeExpr' :: Expr -> Size sizeExpr' e = fromIntegral (length $ show e) + adjust e where -- hackish thing to favor some expressions if the length is the same: -- (+ x) --> (x +) -- x >>= f --> f =<< x -- f $ g x --> f (g x) adjust :: Expr -> Size adjust (Var _ str) -- Just n <- readM str = log (n*n+1) / 4 | str == "uncurry" = -4 -- | str == "s" = 5 | str == "flip" = 0.1 | str == ">>=" = 0.05 | str == "$" = 0.01 | str == "subtract" = 0.01 | str == "ap" = 2 | str == "liftM2" = 1.01 | str == "return" = -2 | str == "zipWith" = -4 | str == "const" = 0 -- -2 | str == "fmap" = -1 adjust (Lambda _ e') = adjust e' adjust (App e1 e2) = adjust e1 + adjust e2 adjust _ = 0 optimize :: Expr -> [Expr] optimize e = result where result :: [Expr] result = map (snd . fromJust) . takeWhile isJust . iterate ((=<<) simpleStep) $ Just (sizeExpr' e, e) simpleStep :: (Size, Expr) -> Maybe (Size, Expr) simpleStep t = do let chn = let ?first = True in step (snd t) chnn = let ?first = False in step =<< chn new = filter (\(x,_) -> x < fst t) . map (sizeExpr' &&& id) $ snd t: chn ++ chnn case new of [] -> Nothing (new':_) -> return new' step :: (?first :: Bool) => Expr -> [Expr] step e = nub $ rewrite rules e rewrite :: (?first :: Bool) => RewriteRule -> Expr -> [Expr] rewrite rl e = case rl of Up r1 r2 -> let e' = cut $ rewrite r1 e e'' = rewrite r2 =<< e' in if null e'' then e' else e'' OrElse r1 r2 -> let e' = rewrite r1 e in if null e' then rewrite r2 e else e' Then r1 r2 -> rewrite r2 =<< nub (rewrite r1 e) Opt r -> e: rewrite r e If p r -> if null (rewrite p e) then mzero else rewrite r e Hard r -> if ?first then rewrite r e else mzero Or rs -> (\x -> rewrite x e) =<< rs RR {} -> rewDeep rl e CRR {} -> rewDeep rl e Down {} -> rewDeep rl e where -- rew = ...; rewDeep = ... rewDeep :: (?first :: Bool) => RewriteRule -> Expr -> [Expr] rewDeep rule e = rew rule e `mplus` case e of Var _ _ -> mzero Lambda _ _ -> error "lambda: optimizer only works for closed expressions" Let _ _ -> error "let: optimizer only works for closed expressions" App e1 e2 -> ((`App` e2) `map` rewDeep rule e1) `mplus` ((e1 `App`) `map` rewDeep rule e2) rew :: (?first :: Bool) => RewriteRule -> Expr -> [Expr] rew (RR r1 r2) e = toMonadPlus $ fire r1 r2 e rew (CRR r) e = toMonadPlus $ r e rew (Or rs) e = (\x -> rew x e) =<< rs rew (Down r1 r2) e = if null e'' then e' else e'' where e' = cut $ rew r1 e e'' = rewDeep r2 =<< e' rew r@(Then {}) e = rewrite r e rew r@(OrElse {}) e = rewrite r e rew r@(Up {}) e = rewrite r e rew r@(Opt {}) e = rewrite r e rew r@(If {}) e = rewrite r e rew r@(Hard {}) e = rewrite r e
substack/hs-disappoint
src/Language/Haskell/Pointfree/Optimize.hs
mit
3,811
0
20
1,342
1,469
757
712
-1
-1
{-| Module: Flaw.Data.Sqlite Description: Simple SQLite Haskell interface. License: MIT -} {-# LANGUAGE PatternSynonyms #-} {-# OPTIONS_GHC -fno-warn-missing-pattern-synonym-signatures #-} module Flaw.Data.Sqlite ( SqliteDb() , SqliteStmt() , SqliteQuery() , sqliteDb , sqliteExec , sqliteStmt , sqliteQuery , sqliteStep , sqliteFinalStep , sqliteTransaction , SqliteData(..) , sqliteLastInsertRowId ) where import Control.Exception import Control.Monad import qualified Data.ByteString as B import qualified Data.ByteString.Unsafe as B import Data.Int import Data.IORef import qualified Data.Text as T import qualified Data.Text.Encoding as T import Foreign.C.String import Foreign.C.Types import Foreign.Marshal.Alloc import Foreign.Ptr import Foreign.Storable import Flaw.Book data SqliteDb = SqliteDb { sqliteDbPtr :: !(Ptr C_sqlite3) , sqliteDbSavePointStmtPtr :: !(Ptr C_sqlite3_stmt) , sqliteDbReleaseStmtPtr :: !(Ptr C_sqlite3_stmt) , sqliteDbRollbackToStmtPtr :: !(Ptr C_sqlite3_stmt) } data SqliteStmt = SqliteStmt { sqliteStmtPtr :: !(Ptr C_sqlite3_stmt) , sqliteStmtDbPtr :: !(Ptr C_sqlite3) } newtype SqliteQuery = SqliteQuery SqliteStmt -- | Open SQLite database. sqliteDb :: T.Text -> IO (SqliteDb, IO ()) sqliteDb fileName = withSpecialBook $ \bk -> do -- open db dbPtr <- book bk $ B.useAsCString (T.encodeUtf8 fileName) $ \fileNamePtr -> alloca $ \dbPtrPtr -> do r <- sqlite3_open fileNamePtr dbPtrPtr dbPtr <- peek dbPtrPtr when (r /= SQLITE_OK) $ do when (dbPtr /= nullPtr) $ void $ sqlite3_close dbPtr throwIO $ SqliteOpenError fileName return (dbPtr, void $ sqlite3_close dbPtr) -- create transaction statements let createStmt str = do stmtPtr <- alloca $ \stmtPtrPtr -> do sqliteCheckError dbPtr (== SQLITE_OK) $ withCString str $ \strPtr -> sqlite3_prepare_v2 dbPtr strPtr (-1) stmtPtrPtr nullPtr peek stmtPtrPtr book bk $ return (stmtPtr, void $ sqlite3_finalize stmtPtr) savePointStmtPtr <- createStmt "SAVEPOINT T" releaseStmtPtr <- createStmt "RELEASE T" rollbackToStmtPtr <- createStmt "ROLLBACK TO T" return SqliteDb { sqliteDbPtr = dbPtr , sqliteDbSavePointStmtPtr = savePointStmtPtr , sqliteDbReleaseStmtPtr = releaseStmtPtr , sqliteDbRollbackToStmtPtr = rollbackToStmtPtr } -- | Execute one-time query. sqliteExec :: SqliteDb -> T.Text -> IO () sqliteExec SqliteDb { sqliteDbPtr = dbPtr } text = sqliteCheckError dbPtr (== SQLITE_OK) $ B.useAsCString (T.encodeUtf8 text) $ \textPtr -> sqlite3_exec dbPtr textPtr nullFunPtr nullPtr nullPtr -- | Create SQLite statement. sqliteStmt :: SqliteDb -> T.Text -> IO (SqliteStmt, IO ()) sqliteStmt SqliteDb { sqliteDbPtr = dbPtr } text = do stmtPtr <- alloca $ \stmtPtrPtr -> do sqliteCheckError dbPtr (== SQLITE_OK) $ B.unsafeUseAsCStringLen (T.encodeUtf8 text) $ \(textPtr, textLen) -> sqlite3_prepare_v2 dbPtr textPtr (fromIntegral textLen) stmtPtrPtr nullPtr peek stmtPtrPtr return (SqliteStmt { sqliteStmtPtr = stmtPtr , sqliteStmtDbPtr = dbPtr }, void $ sqlite3_finalize stmtPtr) -- | Get query object from statement. -- Just to reset statement afterwards. sqliteQuery :: SqliteStmt -> (SqliteQuery -> IO a) -> IO a sqliteQuery stmt@SqliteStmt { sqliteStmtPtr = stmtPtr } action = finally (action (SqliteQuery stmt)) $ do void $ sqlite3_reset stmtPtr void $ sqlite3_clear_bindings stmtPtr -- | Perform query step. -- Returns True if step succeeded and there's row of data. -- Returns False if step succeeded, but there's no data anymore. -- Throws an exception otherwise. sqliteStep :: SqliteQuery -> IO Bool sqliteStep (SqliteQuery SqliteStmt { sqliteStmtPtr = stmtPtr , sqliteStmtDbPtr = dbPtr }) = do r <- sqlite3_step stmtPtr case r of SQLITE_ROW -> return True SQLITE_DONE -> return False _ -> throwSqliteError dbPtr -- | Perform query step, and check that it returned SQLITE_DONE. sqliteFinalStep :: SqliteQuery -> IO () sqliteFinalStep query = do r <- sqliteStep query when r $ throwIO SqliteStepNotFinal -- | Perform SQLite transaction. sqliteTransaction :: SqliteDb -> (IO () -> IO a) -> IO a sqliteTransaction SqliteDb { sqliteDbPtr = dbPtr , sqliteDbSavePointStmtPtr = savePointStmtPtr , sqliteDbReleaseStmtPtr = releaseStmtPtr , sqliteDbRollbackToStmtPtr = rollbackToStmtPtr } io = do -- save point void $ sqlite3_reset savePointStmtPtr sqliteCheckError dbPtr (== SQLITE_DONE) $ sqlite3_step savePointStmtPtr -- commit function finishedRef <- newIORef False let commit = do -- check that transaction is not finished finished <- readIORef finishedRef when finished $ throwIO SqliteTransactionAlreadyFinished -- commit void $ sqlite3_reset releaseStmtPtr sqliteCheckError dbPtr (== SQLITE_DONE) $ sqlite3_step releaseStmtPtr -- remember writeIORef finishedRef True finally (io commit) $ do -- rollback if not finished finished <- readIORef finishedRef unless finished $ do void $ sqlite3_reset rollbackToStmtPtr void $ sqlite3_step rollbackToStmtPtr void $ sqlite3_reset releaseStmtPtr void $ sqlite3_step releaseStmtPtr -- | Class of data which could be used in statements. class SqliteData a where -- | Bind data into statement. sqliteBind :: SqliteQuery -> CInt -> a -> IO () -- | Get data from query. sqliteColumn :: SqliteQuery -> CInt -> IO a instance SqliteData CInt where sqliteBind (SqliteQuery SqliteStmt { sqliteStmtPtr = stmtPtr , sqliteStmtDbPtr = dbPtr }) column value = sqliteCheckError dbPtr (== SQLITE_OK) $ sqlite3_bind_int stmtPtr column value sqliteColumn (SqliteQuery SqliteStmt { sqliteStmtPtr = stmtPtr }) = sqlite3_column_int stmtPtr instance SqliteData Int64 where sqliteBind (SqliteQuery SqliteStmt { sqliteStmtPtr = stmtPtr , sqliteStmtDbPtr = dbPtr }) column value = sqliteCheckError dbPtr (== SQLITE_OK) $ sqlite3_bind_int64 stmtPtr column value sqliteColumn (SqliteQuery SqliteStmt { sqliteStmtPtr = stmtPtr }) = sqlite3_column_int64 stmtPtr instance SqliteData B.ByteString where sqliteBind (SqliteQuery SqliteStmt { sqliteStmtPtr = stmtPtr , sqliteStmtDbPtr = dbPtr }) column bytes = sqliteCheckError dbPtr (== SQLITE_OK) $ B.unsafeUseAsCStringLen bytes $ \(ptr, len) -> -- note: we are forcing non-null pointer in case of zero-length bytestring, in order to bind a blob and not a NULL value sqlite3_bind_blob stmtPtr column (if len > 0 then castPtr ptr else intPtrToPtr 1) (fromIntegral len) $ castPtrToFunPtr $ intPtrToPtr SQLITE_TRANSIENT sqliteColumn (SqliteQuery SqliteStmt { sqliteStmtPtr = stmtPtr }) column = do ptr <- sqlite3_column_blob stmtPtr column len <- sqlite3_column_bytes stmtPtr column B.packCStringLen (castPtr ptr, fromIntegral len) instance SqliteData T.Text where sqliteBind (SqliteQuery SqliteStmt { sqliteStmtPtr = stmtPtr , sqliteStmtDbPtr = dbPtr }) column text = sqliteCheckError dbPtr (== SQLITE_OK) $ B.unsafeUseAsCStringLen (T.encodeUtf8 text) $ \(ptr, len) -> -- note: we are forcing non-null pointer in case of zero-length string, in order to bind a string and not a NULL value sqlite3_bind_text stmtPtr column (if len > 0 then ptr else intPtrToPtr 1) (fromIntegral len) $ castPtrToFunPtr $ intPtrToPtr SQLITE_TRANSIENT sqliteColumn (SqliteQuery SqliteStmt { sqliteStmtPtr = stmtPtr }) column = do ptr <- sqlite3_column_text stmtPtr column len <- sqlite3_column_bytes stmtPtr column T.decodeUtf8 <$> B.packCStringLen (ptr, fromIntegral len) sqliteLastInsertRowId :: SqliteDb -> IO Int64 sqliteLastInsertRowId SqliteDb { sqliteDbPtr = dbPtr } = sqlite3_last_insert_rowid dbPtr throwSqliteError :: Ptr C_sqlite3 -> IO a throwSqliteError dbPtr = do errCode <- sqlite3_errcode dbPtr errMsgPtr <- sqlite3_errmsg dbPtr errMsgBytes <- B.packCString errMsgPtr throwIO $ SqliteError (fromIntegral errCode) (T.decodeUtf8 errMsgBytes) sqliteCheckError :: Ptr C_sqlite3 -> (CInt -> Bool) -> IO CInt -> IO () sqliteCheckError dbPtr cond io = do r <- io unless (cond r) $ throwSqliteError dbPtr data SqliteError = SqliteError {-# UNPACK #-} !Int !T.Text | SqliteOpenError !T.Text | SqliteStepNotFinal | SqliteTransactionAlreadyFinished deriving Show instance Exception SqliteError -- FFI: types data C_sqlite3 data C_sqlite3_stmt -- FFI: functions foreign import ccall safe sqlite3_open :: Ptr CChar -> Ptr (Ptr C_sqlite3) -> IO CInt foreign import ccall safe sqlite3_close :: Ptr C_sqlite3 -> IO CInt foreign import ccall safe sqlite3_prepare_v2 :: Ptr C_sqlite3 -> Ptr CChar -> CInt -> Ptr (Ptr C_sqlite3_stmt) -> Ptr (Ptr CChar) -> IO CInt foreign import ccall unsafe sqlite3_reset :: Ptr C_sqlite3_stmt -> IO CInt foreign import ccall safe sqlite3_step :: Ptr C_sqlite3_stmt -> IO CInt foreign import ccall unsafe sqlite3_clear_bindings :: Ptr C_sqlite3_stmt -> IO CInt foreign import ccall unsafe sqlite3_finalize :: Ptr C_sqlite3_stmt -> IO CInt foreign import ccall safe sqlite3_exec :: Ptr C_sqlite3 -> Ptr CChar -> FunPtr (Ptr () -> CInt -> Ptr (Ptr CChar) -> Ptr (Ptr CChar) -> IO CInt) -> Ptr () -> Ptr (Ptr CChar) -> IO CInt foreign import ccall unsafe sqlite3_bind_int :: Ptr C_sqlite3_stmt -> CInt -> CInt -> IO CInt foreign import ccall unsafe sqlite3_bind_int64 :: Ptr C_sqlite3_stmt -> CInt -> Int64 -> IO CInt foreign import ccall safe sqlite3_bind_blob :: Ptr C_sqlite3_stmt -> CInt -> Ptr () -> CInt -> FunPtr (Ptr () -> IO ()) -> IO CInt foreign import ccall unsafe sqlite3_bind_text :: Ptr C_sqlite3_stmt -> CInt -> Ptr CChar -> CInt -> FunPtr (Ptr () -> IO ()) -> IO CInt --foreign import ccall unsafe sqlite3_bind_null :: Ptr C_sqlite3_stmt -> CInt -> IO CInt foreign import ccall unsafe sqlite3_column_int :: Ptr C_sqlite3_stmt -> CInt -> IO CInt foreign import ccall unsafe sqlite3_column_int64 :: Ptr C_sqlite3_stmt -> CInt -> IO Int64 foreign import ccall unsafe sqlite3_column_blob :: Ptr C_sqlite3_stmt -> CInt -> IO (Ptr ()) foreign import ccall unsafe sqlite3_column_bytes :: Ptr C_sqlite3_stmt -> CInt -> IO CInt foreign import ccall unsafe sqlite3_column_text :: Ptr C_sqlite3_stmt -> CInt -> IO (Ptr CChar) foreign import ccall unsafe sqlite3_last_insert_rowid :: Ptr C_sqlite3 -> IO Int64 foreign import ccall unsafe sqlite3_errcode :: Ptr C_sqlite3 -> IO CInt foreign import ccall unsafe sqlite3_errmsg :: Ptr C_sqlite3 -> IO (Ptr CChar) -- FFI: values pattern SQLITE_OK = 0 pattern SQLITE_ROW = 100 pattern SQLITE_DONE = 101 pattern SQLITE_TRANSIENT = -1
quyse/flaw
flaw-sqlite/Flaw/Data/Sqlite.hs
mit
10,661
0
23
1,971
2,929
1,478
1,451
-1
-1
-- Формирует из сокращения имени конфига его полное имя. -- Используется shell-скриптами для дополнения аргументов других команд. -- -- $1 — сокращение имени конфига, если не задано, то выведет все доступные -- имена конфигов. Содержимое каталогов начинающихся с подчёркивания -- игнорируется. Выводит на stdout имена конфигов через \n -- -- Для дополнения аргументов используется тот же алгоритм раскрытия сокращений -- имён конфигов, что и в других хаскельных программах, так как это во-первых -- проще, чем реализовывать его снова в каждом шэле, во-вторых надёжнее. import Control.Monad import Data.List (isPrefixOf) import System.Environment (getArgs) import Utils.Args main :: IO () main = do argv <- getArgs case argv of [abbr] -> complete abbr _ -> complete "*" complete :: String -> IO () complete abbr = do (_, confs) <- expandAbbr abbr let confs' = filter (not . isPrefixOf "_") confs mapM_ putStrLn confs'
kahless/netm
src/Cmd/Complete/Main.hs
mit
1,407
1
13
193
167
86
81
15
2
module EmailHandler ( getReceiveConnection, getLatestReports, markAsRead, ReceiveConnection, MessageID ) where import Control.Exception (try, SomeException) import Data.ByteString.Internal(ByteString) import qualified Data.Text.Lazy as Text (pack) import Network.HaskellNet.IMAP import Network.HaskellNet.IMAP.Types import Network.HaskellNet.IMAP.Connection import qualified Network.HaskellNet.IMAP as IPlain import qualified Network.HaskellNet.IMAP.SSL as ISSL import Config data ReceiveConnection = ReceiveConnection IMAPConnection data MessageID = MessageID UID getReceiveConnection :: Config -> IO ReceiveConnection getReceiveConnection conf = do let usernameVal = username conf let passwordVal = password conf connection <- connectToImap conf login connection usernameVal passwordVal select connection "INBOX" return (ReceiveConnection connection) getLatestReports :: ReceiveConnection -> IO [(MessageID, ByteString)] getLatestReports receiveConnection = do let (ReceiveConnection connection) = receiveConnection msgs <- search connection [UNFLAG Seen] let getPairs id = fetch connection id >>= \content -> -- Some servers mark messages as seen after fetch -- we will mark them as read explicitly after -- processing store connection id (MinusFlags [Seen]) >> return (MessageID id, content) mapM getPairs msgs markAsRead :: ReceiveConnection -> MessageID -> IO () markAsRead receiveConnection (MessageID id) = do let (ReceiveConnection connection) = receiveConnection store connection id (PlusFlags [Seen]) connectToImap conf = case useSsl conf of True -> sslConnection False -> plainConnection where sslConnection = ISSL.connectIMAPSSLWithSettings mailServerVal sslSettings plainConnection = IPlain.connectIMAPPort mailServerVal serverPort mailServerVal = mailServer conf sslSettings = ISSL.Settings { ISSL.sslPort = serverPort, ISSL.sslMaxLineLength = 1000000, ISSL.sslLogToConsole = False, ISSL.sslDisableCertificateValidation = disableCert } serverPort = fromInteger $ guessPort (useSsl conf) (port conf) guessPort _ (Just portOverride) = portOverride guessPort True _ = 993 guessPort False _ = 143 disableCert = handleMaybe $ ignoreCertFailure conf handleMaybe (Just b) = b handleMaybe Nothing = False
splondike/dmarc-check
src/EmailHandler.hs
gpl-2.0
2,535
0
16
581
602
317
285
55
5
{-# LANGUAGE TemplateHaskell #-} module Persistence.Schema.ConsistencyStatusType where import Database.Persist.TH -- "Contradictory" and "Open" are only used on OMS while the other two can be -- used on ConsistencyCheckAttempt. "Contradictory" is used when there are some -- ConsistencyCheckAttempts with "Consistent" and some with "Inconsistent". -- "Open" is used when there are no ConsistencyCheckAttempts. data ConsistencyStatusType = Open | Timeout | Error | Consistent | Inconsistent | Contradictory deriving (Show, Read, Eq) derivePersistField "ConsistencyStatusType"
spechub/Hets
Persistence/Schema/ConsistencyStatusType.hs
gpl-2.0
741
0
6
238
61
38
23
11
0
{-# LANGUAGE CPP, ScopedTypeVariables #-} {- Copyright (C) 2014 Matthew Pickering <matthewtpickering@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} module Text.TeXMath.Shared ( getMMLType , getTextType , getLaTeXTextCommand , getScalerCommand , getScalerValue , scalers , getSpaceWidth , getSpaceChars , getDiacriticalCommand , getDiacriticalCons , diacriticals , getOperator , readLength , fixTree , isEmpty , empty ) where import Text.TeXMath.Types import Text.TeXMath.TeX import qualified Data.Map as M import Data.Maybe (fromMaybe) import Data.Ratio ((%)) import Data.List (sort) import Control.Applicative ((<$>), (<*>)) import Control.Monad (guard) import Text.Parsec (Parsec, parse, getInput, digit, char, many1, option) import Data.Generics (everywhere, mkT) -- As we constuct from the bottom up, this situation can occur. removeNesting :: Exp -> Exp removeNesting (EDelimited o c [Right (EDelimited "" "" xs)]) = EDelimited o c xs removeNesting (EDelimited "" "" [x]) = either (ESymbol Ord) id x removeNesting (EGrouped [x]) = x removeNesting x = x removeEmpty :: [Exp] -> [Exp] removeEmpty xs = filter (not . isEmpty) xs empty :: Exp empty = EGrouped [] isEmpty :: Exp -> Bool isEmpty (EGrouped []) = True isEmpty _ = False fixTree :: Exp -> Exp fixTree = everywhere (mkT removeNesting) . everywhere (mkT removeEmpty) -- | Maps TextType to the corresponding MathML mathvariant getMMLType :: TextType -> String getMMLType t = fromMaybe "normal" (fst <$> M.lookup t textTypesMap) -- | Maps TextType to corresponding LaTeX command getLaTeXTextCommand :: Env -> TextType -> String getLaTeXTextCommand e t = let textCmd = fromMaybe "\\mathrm" (snd <$> M.lookup t textTypesMap) in if textPackage textCmd e then textCmd else fromMaybe "\\mathrm" (lookup textCmd alts) -- | Maps MathML mathvariant to the corresponing TextType getTextType :: String -> TextType getTextType s = fromMaybe TextNormal (M.lookup s revTextTypesMap) -- | Maps a LaTeX scaling command to the percentage scaling getScalerCommand :: Rational -> Maybe String getScalerCommand width = case sort [ (w, cmd) | (cmd, w) <- scalers, w >= width ] of ((_,cmd):_) -> Just cmd _ -> Nothing -- note, we don't use a Map here because we need the first -- match: \Big, not \Bigr -- | Gets percentage scaling from LaTeX scaling command getScalerValue :: String -> Maybe Rational getScalerValue command = lookup command scalers -- | Returns the correct constructor given a LaTeX command getDiacriticalCons :: String -> Maybe (Exp -> Exp) getDiacriticalCons command = f <$> M.lookup command diaMap where diaMap = M.fromList (reverseKeys diacriticals) f s e = (if command `elem` under then EUnder False else EOver False) e (ESymbol Accent s) -- | Given a diacritical mark, returns the corresponding LaTeX command getDiacriticalCommand :: Position -> String -> Maybe String getDiacriticalCommand pos symbol = do command <- M.lookup symbol diaMap guard (not $ command `elem` unavailable) let below = command `elem` under case pos of Under -> if below then Just command else Nothing Over -> if not below then Just command else Nothing where diaMap = M.fromList diacriticals -- Operator Table getOperator :: Exp -> Maybe TeX getOperator op = fmap ControlSeq $ lookup op operators operators :: [(Exp, String)] operators = [ (EMathOperator "arccos", "\\arccos") , (EMathOperator "arcsin", "\\arcsin") , (EMathOperator "arctan", "\\arctan") , (EMathOperator "arg", "\\arg") , (EMathOperator "cos", "\\cos") , (EMathOperator "cosh", "\\cosh") , (EMathOperator "cot", "\\cot") , (EMathOperator "coth", "\\coth") , (EMathOperator "csc", "\\csc") , (EMathOperator "deg", "\\deg") , (EMathOperator "det", "\\det") , (EMathOperator "dim", "\\dim") , (EMathOperator "exp", "\\exp") , (EMathOperator "gcd", "\\gcd") , (EMathOperator "hom", "\\hom") , (EMathOperator "inf", "\\inf") , (EMathOperator "ker", "\\ker") , (EMathOperator "lg", "\\lg") , (EMathOperator "lim", "\\lim") , (EMathOperator "liminf", "\\liminf") , (EMathOperator "limsup", "\\limsup") , (EMathOperator "ln", "\\ln") , (EMathOperator "log", "\\log") , (EMathOperator "max", "\\max") , (EMathOperator "min", "\\min") , (EMathOperator "Pr", "\\Pr") , (EMathOperator "sec", "\\sec") , (EMathOperator "sin", "\\sin") , (EMathOperator "sinh", "\\sinh") , (EMathOperator "sup", "\\sup") , (EMathOperator "tan", "\\tan") , (EMathOperator "tanh", "\\tanh") ] -- | Attempts to convert a string into readLength :: String -> Maybe Rational readLength s = do (n, unit) <- case (parse parseLength "" s) of Left _ -> Nothing Right v -> Just v (n *) <$> unitToMultiplier unit parseLength :: Parsec String () (Rational, String) parseLength = do neg <- option "" ((:[]) <$> char '-') dec <- many1 digit frac <- option "" ((:) <$> char '.' <*> many1 digit) unit <- getInput -- This is safe as dec and frac must be a double of some kind let [(n :: Double, [])] = reads (neg ++ dec ++ frac) :: [(Double, String)] return (round (n * 18) % 18, unit) reverseKeys :: [(a, b)] -> [(b, a)] reverseKeys = map (\(k,v) -> (v, k)) textTypesMap :: M.Map TextType (String, String) textTypesMap = M.fromList textTypes revTextTypesMap :: M.Map String TextType revTextTypesMap = M.fromList $ map (\(k, (v,_)) -> (v,k)) textTypes --TextType to (MathML, LaTeX) textTypes :: [(TextType, (String, String))] textTypes = [ ( TextNormal , ("normal", "\\mathrm")) , ( TextBold , ("bold", "\\mathbf")) , ( TextItalic , ("italic","\\mathit")) , ( TextMonospace , ("monospace","\\mathtt")) , ( TextSansSerif , ("sans-serif","\\mathsf")) , ( TextDoubleStruck , ("double-struck","\\mathbb")) , ( TextScript , ("script","\\mathcal")) , ( TextFraktur , ("fraktur","\\mathfrak")) , ( TextBoldItalic , ("bold-italic","\\mathbfit")) , ( TextSansSerifBold , ("bold-sans-serif","\\mathbfsfup")) , ( TextSansSerifBoldItalic , ("sans-serif-bold-italic","\\mathbfsfit")) , ( TextBoldScript , ("bold-script","\\mathbfscr")) , ( TextBoldFraktur , ("bold-fraktur","\\mathbffrak")) , ( TextSansSerifItalic , ("sans-serif-italic","\\mathsfit")) ] unicodeMath, base :: [String] unicodeMath = ["\\mathbfit", "\\mathbfsfup", "\\mathbfsfit", "\\mathbfscr", "\\mathbffrak", "\\mathsfit"] base = ["\\mathbb", "\\mathrm", "\\mathbf", "\\mathit", "\\mathsf", "\\mathtt", "\\mathfrak", "\\mathcal"] alts :: [(String, String)] alts = [ ("\\mathbfit", "\\mathbf"), ("\\mathbfsfup", "\\mathbf"), ("\\mathbfsfit", "\\mathbf") , ("\\mathbfscr", "\\mathcal"), ("\\mathbffrak", "\\mathfrak"), ("\\mathsfit", "\\mathsf")] textPackage :: String -> [String] -> Bool textPackage s e | s `elem` unicodeMath = "unicode-math" `elem` e | s `elem` base = True | otherwise = True -- | Mapping between LaTeX scaling commands and the scaling factor scalers :: [(String, Rational)] scalers = [ ("\\bigg", widthbigg) , ("\\Bigg", widthBigg) , ("\\big", widthbig) , ("\\Big", widthBig) , ("\\biggr", widthbigg) , ("\\Biggr", widthBigg) , ("\\bigr", widthbig) , ("\\Bigr", widthBig) , ("\\biggl", widthbigg) , ("\\Biggl", widthBigg) , ("\\bigl", widthbig)] where widthbig = 6 / 5 widthBig = 9 / 5 widthbigg = 12 / 5 widthBigg = 3 -- | Returns the space width for a unicode space character, or Nothing. getSpaceWidth :: Char -> Maybe Rational getSpaceWidth ' ' = Just (4/18) getSpaceWidth '\xA0' = Just (4/18) getSpaceWidth '\x2000' = Just (1/2) getSpaceWidth '\x2001' = Just 1 getSpaceWidth '\x2002' = Just (1/2) getSpaceWidth '\x2003' = Just 1 getSpaceWidth '\x2004' = Just (1/3) getSpaceWidth '\x2005' = Just (4/18) getSpaceWidth '\x2006' = Just (1/6) getSpaceWidth '\x2007' = Just (1/3) -- ? width of a digit getSpaceWidth '\x2008' = Just (1/6) -- ? width of a period getSpaceWidth '\x2009' = Just (1/6) getSpaceWidth '\x200A' = Just (1/9) getSpaceWidth '\x200B' = Just 0 getSpaceWidth '\x202F' = Just (3/18) getSpaceWidth '\x205F' = Just (4/18) getSpaceWidth _ = Nothing -- | Returns the sequence of unicode space characters closest to the -- specified width. getSpaceChars :: Rational -> [Char] getSpaceChars n = case n of _ | n < 0 -> "\x200B" -- no negative space chars in unicode | n <= 2/18 -> "\x200A" | n <= 3/18 -> "\x2006" | n <= 4/18 -> "\xA0" -- could also be "\x2005" | n <= 5/18 -> "\x2005" | n <= 7/18 -> "\x2004" | n <= 9/18 -> "\x2000" | n < 1 -> '\x2000' : getSpaceChars (n - (1/2)) | n == 1 -> "\x2001" | otherwise -> '\x2001' : getSpaceChars (n - 1) -- Accents which go under the character under :: [String] under = ["\\underbrace", "\\underline", "\\underbar", "\\underbracket"] -- We want to parse these but we can't represent them in LaTeX unavailable :: [String] unavailable = ["\\overbracket", "\\underbracket"] -- | Mapping between unicode combining character and LaTeX accent command diacriticals :: [(String, String)] diacriticals = [ ("\x00B4", "\\acute") , (("\x0060", "\\grave")) , (("\x02D8", "\\breve")) , (("\x02C7", "\\check")) , (("\x307", "\\dot")) , (("\x308", "\\ddot")) , (("\x20DB", "\\dddot")) , (("\x20DC", "\\ddddot")) , (("\x00B0", "\\mathring")) , (("\x20D7", "\\vec")) , (("\x20D7", "\\overrightarrow")) , (("\x20D6", "\\overleftarrow")) , (("\x005E", "\\hat")) , (("\x0302", "\\widehat")) , (("\x02C6", "\\widehat")) , (("\x0303", "\\tilde")) , (("\x02DC", "\\widetilde")) , (("\x203E", "\\bar")) , (("\x23DE", "\\overbrace")) , (("\xFE37", "\\overbrace")) , (("\x23B4", "\\overbracket")) -- Only availible in mathtools , (("\x00AF", "\\overline")) , (("\x23DF", "\\underbrace")) , (("\xFE38", "\\underbrace")) , (("\x23B5", "\\underbracket")) -- mathtools , (("\x0332", "\\underline")) , (("\x0333", "\\underbar")) ] -- Converts unit to multiplier to reach em unitToMultiplier :: String -> Maybe Rational unitToMultiplier s = lookup s units where units = [ ( "pt" , 10) , ( "mm" , (351/10)) , ( "cm" , (35/100)) , ( "in" , (14/100)) , ( "ex" , (232/100)) , ( "em" , 1) , ( "mu" , 18) , ( "dd" , (93/100)) , ( "bp" , (996/1000)) , ( "pc" , (83/100)) ]
timtylin/scholdoc-texmath
src/Text/TeXMath/Shared.hs
gpl-2.0
12,137
0
14
3,232
3,401
1,953
1,448
253
4
#!/usr/bin/env runhaskell -- | Rabbits and Recurrence Relations -- Usage: FIB <dataset.txt> fib' :: Num b => b -> [b] fib' k = 1 : 1 : [x*k+y | (x,y) <- zip (fib' k) (tail $ fib' k)] rab :: Num a => Int -> a -> a rab n k = fib' k !! (n-1) main = do line <- getLine let (n:k:_) = words line putStrLn $ show $ rab (read n :: Int) (read k :: Int)
kerkomen/rosalind-haskell
stronghold/FIB.hs
gpl-2.0
361
0
12
97
199
101
98
8
1
{-# LANGUAGE OverloadedStrings #-} module FOOL.PrettyAST where import FOOL.AST import FOOL.TPTP import Pretty import qualified Text.PrettyPrint.ANSI.Leijen as PP import Data.Char (toUpper, toLower) import Data.List (sort) {- Pretty -} instance Pretty QOp where pretty Forall = "!" pretty Exists = "?" instance Pretty UOp where pretty Not = "~" pretty Neg = "$uminus" instance Pretty BOp where pretty And = "&" pretty Or = "|" pretty Add = "$sum" pretty Subtract = "$difference" pretty Multiply = "$product" pretty Imply = "=>" pretty Exply = "<=" pretty Iff = "<=>" pretty Greater = "$greater" pretty Geq = "$greatereq" pretty Less = "$less" pretty Leq = "$lesseq" pretty Equal = "=" pretty Neq = "!=" pretty Div = "$quotient_e" class IsInfix a where isInFix :: a -> Bool instance IsInfix UOp where isInFix _ = False instance IsInfix BOp where isInFix op = case op of And -> True Or -> True Imply -> True Iff -> True Equal -> True Neq -> True _ -> False instance Pretty Type where pretty t = case t of Boolean -> "$o" Integer -> "$int" TType typ -> text typ MapType ds r -> "$array" `funapp` (map pretty (ds : [r])) FuncType ds r -> ftyps <> " > " <> pretty r where ftyps = condParens (length ds > 1) $ starSep $ map pretty ds I -> "$tType" -- I only appears as the type gets declared! so should be $tType instance Pretty FOOLTerm where pretty t = case t of IConst i -> (text . show) i BConst b -> if b then "$true" else "$false" Var id -> text id TypedVar id t -> text id <> text ": " <> pretty t Tuple tuple -> "[" <> ttyps <> "]" where ttyps = commaSep $ map pretty tuple FunApp f args -> text f `funapp` (map pretty args) Uni op a -> pretty op <> (parens $ pretty a) -- parens $ pretty op <> (parens $ pretty a) -- over-parenthizing Bin op a b -> if (isInFix op) then parens $ hsep [pretty a , pretty op, pretty b] else funapp (pretty op) [pretty a, pretty b] Quantified qop vs t -> pretty qop <> prettyVars <> text ": " <> quantifiedPretty qids t where prettyVars = brackets $ commaSep (map (quantifiedPretty qids) vs) qids = map (\(TypedVar id t) -> id) vs ITE c t f -> "$ite" `funappIndented` (map pretty [c, t, f]) Select m i -> "$select" `funapp` [pretty m, pretty i] Store m i v -> "$store" `funapp` [pretty m, pretty i, pretty v] Let lrs inTerm -> "$let" <> parens (content <> ((", " PP.<$> pretty inTerm))) where content = delim $ map (\(l, r) -> pretty l <> " := " <> pretty r) lrs -- zip-truncation is the only possible semantics delim = align . vsep . punctuate ";" funapp :: Doc -> [Doc] -> Doc funapp f as = f <> parens (commaSep as) funappIndented :: Doc -> [Doc] -> Doc funappIndented f as = f <> parens args where args = align $ (vsep . punctuate PP.comma) as toUpperName :: String -> Doc toUpperName = text . map toUpper quantifiedPretty :: [String] -> FOOLTerm -> Doc quantifiedPretty qids term = case term of Var id -> if id `elem` qids then toUpperName id else text id IConst i -> (text . show) i BConst b -> if b then "$true" else "$false" TypedVar id t -> toUpperName id <> text ": " <> pretty t Tuple tuple -> "[" <> ttyps <> "]" where ttyps = commaSep $ map pretty' tuple FunApp fid args -> text fid `funapp` prettyArgs where prettyArgs = foldr f [] args f arg pargs = case arg of TypedVar id t -> pretty' (Var id) : pargs _ -> pretty' arg : pargs Uni op a -> pretty op <> (parens $ pretty' a) Bin op a b -> if (isInFix op) then parens $ hsep [pretty' a , pretty op, pretty' b] else funapp (pretty op) [pretty' a, pretty' b] Quantified qop vs t -> pretty qop <> prettyVars <> text ": " <> quantifiedPretty (qids ++ qids') t where prettyVars = brackets $ commaSep (map pretty' vs) qids' = map (\(TypedVar id t) -> id) vs ITE c t f -> "$ite" `funapp` (map pretty' [c, t, f]) Select m i -> "$select" `funapp` [pretty' m, pretty' i] Store m i v -> "$store" `funapp` [pretty' m, pretty' i, pretty' v] Let lrs inTerm -> "$let" <> parens ((content lhss rhss) <> ((", " PP.<$> pretty' inTerm))) where content l r = delim $ map (\(l, r) -> pretty' l <> " := " <> pretty' r) (zip l r) -- zip-truncation is the only possible semantics delim = align . vsep . punctuate ";" lhss = map fst lrs rhss = map snd lrs where pretty' = quantifiedPretty qids {- TPTP -} instance Pretty Sentence where pretty s = case s of TypeD des term -> commaSep [text' des, text "type", pretty term] Axiom des term -> commaSep [text' des, text "axiom", pretty term] Conj des term -> commaSep [text' des, text "conjecture", pretty term] where text' s = text $ map toLower s instance Pretty TPTP where pretty (TPTP sens) = vsep $ map (tffWrapping . pretty) (sort sens) -- Wrapping http://www.cs.miami.edu/~tptp/TPTP/Proposals/TFXTHX.html thfWrapping :: Doc -> Doc thfWrapping term = text "thf" <> parens term <> text "." tfxWrapping term = text "tfx" <> parens term <> text "." tffWrapping term = text "tff" <> parens term <> text "." instance Ord Sentence where -- -- so $tType gets promoted -- compare (TypeD _ term1) (TypeD _ term2) = compare term1 term2 compare (TypeD _ _) _ = LT compare (Axiom _ _) (TypeD _ _) = GT compare (Conj _ _) _ = GT compare _ _ = EQ
emptylambda/BLT
src/FOOL/PrettyAST.hs
gpl-3.0
5,641
0
17
1,564
2,178
1,092
1,086
129
17
module Shrdlite.AStar ( -- * Dataypes AStarState -- * Functions , aStar , aStar' , resultList , stateTrans , updateState ) where import Data.Maybe import Data.PSQueue (Binding(..)) import Shrdlite.Common import qualified Data.Map as M import qualified Data.PSQueue as Q import qualified Data.Set as S -- | The current state of the algoritm. Closed nodes are visited, open is a -- queue of nodes to visit, pathCost keeps track of the cost of getting to each -- node and parent is a map from each node to its parent or previous node. data AStarState = AStarState { closed :: !(S.Set WorldHolding) , open :: !(Q.PSQ WorldHolding Int) , pathCost :: !(M.Map WorldHolding Int) , parent :: !(M.Map WorldHolding WorldHolding)} -- | Find the best path from the initial node to (one of) the goal state(s). -- Gives this in the form of a 'Plan'. aStar :: (WorldHolding -> S.Set WorldHolding) -- ^ Graph to search through -> (WorldHolding -> Int) -- ^ Heuristic distance to the goal -> (WorldHolding -> Bool) -- ^ Goal check function -> WorldHolding -- ^ Starting point -> Maybe Plan -- ^ Resulting path if it exists aStar graph heur check start = aStar' initState graph heur check where initState = AStarState {closed = S.empty, open = Q.singleton start (heur start), pathCost = M.singleton start 0, parent = M.empty} -- | Much like 'aStar', but also takes an initial state aStar' :: AStarState -- ^ Initial state -> (WorldHolding -> S.Set WorldHolding) -- ^ Graph to search through -> (WorldHolding -> Int) -- ^ Heuristic distance to the goal -> (WorldHolding -> Bool) -- ^ Goal check function -> Maybe Plan -- ^ Resulting path if it exists aStar' s g h c = case Q.minView $ open s of -- take best open node Just (node :-> _, open') -> -- the chosen node and updated open queue if c node -- the goal is found then Just $ resultList node $ parent state' -- find result here else aStar' state' g h c -- run astar' with updated state where state' = S.fold (updateState h node) (s {closed=closed', open=open'}) newNodes closed' = S.insert node $ closed s -- add node to the closed list newNodes = S.difference (g node) closed' -- adjacent nodes not visited Nothing -> Nothing -- open queue empty, no result found -- | Update the state with a new node, unless it is already in open with a -- cheaper cost updateState :: (WorldHolding -> Int) -- ^ Heuristic function -> WorldHolding -- ^ Previous node -> WorldHolding -- ^ Current node -> AStarState -- ^ State to update -> AStarState -- ^ New state updateState h previous x state = if pCost > oldCost then state -- do nothing if the path to get to the state is longer else state {open=open', pathCost=pathCost', parent=parent'} where pCost = 1 + fromMaybe 0 (M.lookup previous $ pathCost state) -- this cost oldCost = fromMaybe pCost (M.lookup x $ pathCost state) -- update parent if the path cost is shorter parent' = M.insert x previous $ parent state -- add path lengths to pathCost (1+pathCost for previous) (M.insertWith' min) pathCost' = M.insert x pCost $ pathCost state -- add new nodes with cost+heuristic to open queue (Q.insertWith min) open' = Q.insert x (pCost + h x) $ open state -- | Given an final node and a list @Map@ from each node to its parent, make -- a 'Plan' resultList :: WorldHolding -> M.Map WorldHolding WorldHolding -> Plan resultList x@(w, _) xm = case M.lookup x xm of Nothing -> [] Just x'@(w', _) -> resultList x' xm ++ stateTrans w' w 0 -- | Given two 'World' states and a counter (preferrably 0) make a 'Plan' stateTrans :: World -> World -> Int -> Plan stateTrans (c1:c1s) (c2:c2s) col = case compare (length c1) (length c2) of LT -> ["drop " ++ show col] GT -> ["pick " ++ show col] EQ -> stateTrans c1s c2s (col + 1) stateTrans _ _ _ = error "stateTransition: no changes"
chip2n/tin172-project
haskell/src/Shrdlite/AStar.hs
gpl-3.0
4,470
0
13
1,402
952
522
430
73
3
--we implement forward, backward, viterbi, baum-welch algorithms in this code --HMM Class : --- has states, observations, start_probability (states X 1), transition_probability (states X states), emission_probability (states X observations) module HMM.HMM where import Debug.Trace import Data.Maybe import Data.Array import Data.List import Data.List.Extras import Data.Number.LogFloat import qualified Data.MemoCombinators as Memo -- import Control.Parallel import System.IO type ProbType = LogFloat data HMM stateType observationType = HMM {states :: [stateType] , observations :: [observationType] , startProbability :: stateType -> ProbType , transitionProbability :: stateType -> stateType -> ProbType , emissionProbability :: stateType -> observationType -> ProbType } instance (Show stateType, Show observationType) => Show (HMM stateType observationType) where show = hmmToString hmmToString hmm = "HMM" ++ "{ states =" ++ (show $ states hmm) ++ "\n\n observations =" ++ (show $ observations hmm) ++ "\n\n startProbabilities =" ++ (show [(s,startProbability hmm s) | s <- states hmm]) ++ "\n\n transitionProbabilities =" ++ (show [(s1,s2,transitionProbability hmm s1 s2) | s1 <- states hmm, s2 <- states hmm]) ++ "\n\n emissionProbabilities =" ++ (show [(s,o,emissionProbability hmm s o) | s <- states hmm, o <- observations hmm]) ++ "}" -----------Helper Functions------------------- ---------------------------------------------- stateIndex :: (Show stateType, Eq stateType, Show observationType) => HMM stateType observationType -> stateType -> Int stateIndex hmm s = fromMaybe (seq (error ("error in stateIndex : " ++ show s ++ "not is possible states")) 0) (elemIndex s $ states hmm) observationIndex :: (Show stateType, Show observationType, Eq observationType) => HMM stateType observationType -> observationType -> Int observationIndex hmm o = fromMaybe (seq (error ("error in observationIndex : " ++ show o ++ "not is possible observations")) 0) (elemIndex o $ observations hmm) elemIndex2 :: (Show a, Eq a) => a -> [a] -> Int elemIndex2 e list = fromMaybe (seq (error ("elemIndex2: Index "++show e++" not in HMM "++show list)) 0) (elemIndex e list) ----------------------------------------------- ------------------------------------------------------------- ---Code for simpleHMM from HMM Library----------------------- ---reference : HMM Library----------------------------------- --http://hackage.haskell.org/packages/archive/hmm/0.2.1.1/doc/html/src/Data-HMM.html----- -- | Use simpleHMM to create an untrained hidden Markov model simpleHMM :: (Eq stateType, Show eventType, Show stateType) => [stateType] -> [eventType] -> HMM stateType eventType simpleHMM sL eL = HMM { states = sL , observations = eL , startProbability = const evenDist--skewedDist s , transitionProbability = \ s1 s2 -> skewedDist s2 , emissionProbability = \ s e -> 1.0/logFloat (length eL) } where evenDist = 1.0 / sLlen skewedDist s = logFloat (1+elemIndex2 s sL) / ( (sLlen * (sLlen + logFloat (1.0 :: Double)))/2.0) sLlen = logFloat $ length sL ----------------------------------------------- --- use memoization to do dynamic programming ------------------------------------------------------------------ -- forward algorithm : ------------------------------------------- -- this is the forward part of the forward-backward algorithm -- computes P( z_k | x_1..k) -- P( (z_k) | x_1..k) = Sum over z_(k-1) { P(x_k|z_k) * P(z_k|z_k-1) * P(z_k-1 | x_1..k-1) } -- P ( z_1 | x_1 ) = initProb (z_1) * emissionProb (z_1,x_1) -- alpha (z_k,k) = Sum over z_(k-1) { emissionProb(x_k|z_k) * transitionProb(z_k|z_k-1) * alpha(z_k-1,k-1) } -- alpha (z_1,1) = initProb (z_1) * emissionProb (z_1,x_1) --reference : http://www.youtube.com/watch?v=M7afek1nEKM forwardAlgorithmRecursive :: (Show stateType, Eq stateType, Show observationType, Eq observationType) => HMM stateType observationType -> stateType -> [observationType] -> ProbType forwardAlgorithmRecursive hmm s obs = alpha s n where n = length obs obs1 = (listArray (1,n) obs) alpha z 1 = (startProbability hmm z) * (emissionProbability hmm z $ obs1!1 ) alpha z k = (emissionProbability hmm z $ obs1!k ) * (sum $ [(transitionProbability hmm s z)*(alpha s (k-1)) | s <- states hmm]) forwardAlgorithm :: (Show stateType, Eq stateType, Show observationType, Eq observationType) => HMM stateType observationType -> stateType -> [observationType] -> ProbType forwardAlgorithm hmm s obs = alpha (stateIndex hmm s) n --we pass stateindex as memoization on integers only where n = length obs obs1 = (listArray (1,n) obs) alpha = (Memo.memo2 Memo.integral Memo.integral alpha_dp) alpha_dp z k --z,k are integers here !! | k==1 = (startProbability hmm (states hmm !! z)) * (emissionProbability hmm (states hmm !! z) $ obs1!1 ) | otherwise = (emissionProbability hmm (states hmm !! z) $ obs1!k ) * (sum $ [(transitionProbability hmm s (states hmm !! z))*(alpha (stateIndex hmm s) (k-1)) | s <- states hmm]) ------------------------------------------------------------------- -- backward algorithm : ------------------------------------------- -- this is the backward part of the forward-backward algorithm -- computes P (x_k+1 ... x_n | z_k) -- P (x_k+1 ... x_n | z_k) = Sum over z_(k-1) { P (z_k+1 | z_k) * P(x_k+1|z_k+1) * P(x_k+2 ... x_n | z_k+1) } -- beta(z_k,k) = Sum over z_(k+1) { beta(z_k+1,k+1) * emissionProb(x_k+1|z_k+1) * transitionProb(z_k+1 | z_k) } -- beta (z_n,n) = 1 -- reference : http://www.youtube.com/watch?v=jwYuki9GgJo backwardAlgorithmRecursive :: (Show stateType, Eq stateType, Show observationType, Eq observationType) => HMM stateType observationType -> stateType -> [observationType] -> ProbType backwardAlgorithmRecursive hmm z obs = beta z 1 where n = length obs obs1 = (listArray (1,n) obs) beta z k | k==n = 1 | otherwise = sum [ (beta s (k+1)) * (emissionProbability hmm s $ obs1!(k+1) ) * (transitionProbability hmm z s) | s <- states hmm ] backwardAlgorithm :: (Show stateType, Eq stateType, Show observationType, Eq observationType) => HMM stateType observationType -> stateType -> [observationType] -> ProbType backwardAlgorithm hmm z obs = beta (stateIndex hmm z) 1 --here, beta takes integers as input because of memoization where n = length obs obs1 = (listArray (1,n) obs) beta = (Memo.memo2 Memo.integral Memo.integral beta_dp) beta_dp z k | k==n = 1 | otherwise = sum [ (beta (stateIndex hmm s) (k+1)) * (emissionProbability hmm s $ obs1!(k+1) ) * (transitionProbability hmm (states hmm !! z) s) | s <- states hmm ] --------------------------------------------------------------------- --forward-backward algorithm----------------------------------------- -- fbalgo (z,k,x_1 ... x_k) = Prob (z_k | x_1 ... x_k) forwardBackwardAlgorithm hmm z k obs = prob_z / prob_total where (l1,l2) = splitAt k obs prob_z = (forwardAlgorithm hmm z l1) * (backwardAlgorithm hmm z l2) prob_total = sum [(forwardAlgorithm hmm s l1) * (backwardAlgorithm hmm s l2) | s <- states hmm] --------------------------------------------------------------------- --viterbi algorithm : ----------------------------------------------- -- mu -> probability of most likely seq ending in z_k -- mu(z_k) = max (z_k-1) { emissionProb(x_k|z_k) * transitionProb(z_k|z_k-1) * mu(z_k-1) } [k>1] -- mu(z_1) = initProb (z_1) * emissionProb (z_1,x_1) -- reference : http://www.youtube.com/watch?v=t3JIk3Jgifs viterbiAlgorithm :: (Show stateType, Eq stateType, Show observationType, Eq observationType) => HMM stateType observationType -> [observationType] -> [stateType] viterbiAlgorithm hmm obs = reverse $ giveLikelySequence z_n n where n = length obs m = length (states hmm) obs1 = (listArray (1,n) obs) mu = (Memo.memo2 Memo.integral Memo.integral mu_dp) mu_dp z k | k==1 = (startProbability hmm (states hmm !! z) ) * (emissionProbability hmm (states hmm !! z) $ obs1!(k) ) | otherwise = (emissionProbability hmm (states hmm !! z) $ obs1!(k)) * maximum [ (mu (stateIndex hmm s) (k-1)) * (transitionProbability hmm s (states hmm !! z)) | s <- states hmm] giveLikelySequence z k | k==1 = [states hmm !! z] | otherwise = (states hmm !! z) : (giveLikelySequence z' (k-1)) where z' = argmax (\i -> (mu i (k-1)) * (transitionProbability hmm (states hmm !! i) (states hmm !! z)) ) [0..(m-1)] z_n = argmax (\i -> mu i n) [0..(m-1)] -------------------------------------------------------------------- -------------------------------------------------------------------- -- given an observation sequence, baumWelch learns HMM parameters based on expectation maximization --Thus, baumwelch gives --- the code is based on the following reference : http://tcs.rwth-aachen.de/lehre/PRICS/WS2006/kohlschein.pdf --- baumWelchAlgorithm :: (Show stateType, Eq stateType, Show observationType, Eq observationType) => HMM stateType observationType -> [observationType] -> Int -> HMM stateType observationType baumWelchAlgorithm hmm obs numIter | numIter == 0 = hmm | otherwise = trace (show hmmNew) $ baumWelchAlgorithm hmmNew obs (numIter-1) where hmmNew = baumWelchIteration hmm obs baumWelchIteration :: (Show stateType, Eq stateType, Show observationType, Eq observationType) => HMM stateType observationType -> [observationType] -> HMM stateType observationType baumWelchIteration hmm obs = --------returs an updated HMM--------------- -------------------------------------------- HMM {states = states hmm , observations = observations hmm , startProbability = startProbabilityNew , transitionProbability = transitionProbabilityNew , emissionProbability = emissionProbabilityNew} where n = length obs obs1 = (listArray (1,n) obs) ------------------------------------------------------------------ -----------alpha , beta are same as above so not explaining here-- alpha = (Memo.memo2 Memo.integral Memo.integral alpha_dp) alpha_dp z k --z,k are integers here !! | k==1 = (startProbability hmm (states hmm !! z)) * (emissionProbability hmm (states hmm !! z) $ obs1!1 ) | otherwise = (emissionProbability hmm (states hmm !! z) $ obs1!k ) * (sum $ [(transitionProbability hmm s (states hmm !! z))*(alpha (stateIndex hmm s) (k-1)) | s <- states hmm]) beta = (Memo.memo2 Memo.integral Memo.integral beta_dp) beta_dp z k --z,k are integers here !! | k==n = 1 | otherwise = sum [ (beta (stateIndex hmm s) (k+1)) * (emissionProbability hmm s $ obs1!(k+1) ) * (transitionProbability hmm (states hmm !! z) s) | s <- states hmm ] ------------------------------------------------------------------ ------------------------------------------------------------------ --prob_obseq is prob of seeing the sequence of observations, same as p(V^T | theta) --sum s { beta_s * initprob(s) * emitprob(s,x1)} prob_obseq = sum [(startProbability hmm s) * (emissionProbability hmm s $ obs1!1) * (beta (stateIndex hmm s) 1) | s <- states hmm ] -- gamma as defined in the pseudocode -- gamma i j t give the probility that we had s_i at (t-1) which had a transition to s_j at t gamma i j t = (alpha i (t-1)) * (transitionProbability hmm s_i s_j) * (emissionProbability hmm s_j o_t) * (beta j t) / prob_obseq where s_i = (states hmm !! i) s_j = (states hmm !! j) o_t = (obs1 ! t) -- sumgamma i t gives the probability of having s_i at t-1 sumGamma i t = sum [gamma i (stateIndex hmm s) t | s <- states hmm] -- transition probility s_i -> s_j = (expected number of times we have s_i -> s_j transit ) / (expected number of times we have s_i) transitionProbabilityNew s_i s_j = numerator / denominator where i = stateIndex hmm s_i j = stateIndex hmm s_j numerator = sum [gamma i j t | t <- [2..n]] denominator = sum [sumGamma i t | t <- [2..n]] -- emission probability s_i -> o = (expected number of times we have s_i -> o transit ) / (expected number of times we have s_i) emissionProbabilityNew s_i o = numerator / denominator where i = stateIndex hmm s_i numerator = sum [if ((obs1!t) == o) then sumGamma i t else 0 | t <- [2..n] ] denominator = sum [sumGamma i t | t <- [2..n]] -- start probability = sumgamma 2 as it gives prob of having s_i at t=1 startProbabilityNew s_i = sumGamma (stateIndex hmm s_i) 2 -------------------------------------------------------------------- {-main = do let slist = ["rainy","sunny"] let olist = ["walk","shop","clean"] let hmm = simpleHMM slist olist print $ show hmm putStrLn "" putStrLn "Forward Algo Recursive started -" print $ forwardAlgorithmRecursive hmm "rainy" ["shop","clean","walk"] putStrLn "" putStrLn "Forward Algo started -" print $ forwardAlgorithm hmm "rainy" ["shop","clean","walk"] putStrLn "" putStrLn "Backward Algo Recursive started -" print $ backwardAlgorithmRecursive hmm "rainy" ["shop","clean","walk"] putStrLn "" putStrLn "Backward Algo started -" print $ backwardAlgorithm hmm "rainy" ["shop","clean","walk"] putStrLn "" putStrLn "Viterbi Algo started -" print $ viterbiAlgorithm hmm ["shop","clean","walk"] let trainseq = ["shop","clean","walk","shop","clean","walk","shop","clean","walk","shop","clean","walk","shop","clean","walk"] let hmmNew = baumWelchAlgorithm hmm trainseq 3 putStrLn "" putStrLn "" putStrLn "Show HMM New -" print $ show hmmNew-}
rahulaaj/ML-Library
src/HMM/HMM.hs
gpl-3.0
13,778
34
17
2,621
3,553
1,859
1,694
141
2
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} -------------------------------------------------------------------------------- -- | -- Module : Tct.Method.DP.UsableRules -- Copyright : (c) Martin Avanzini <martin.avanzini@uibk.ac.at>, -- Georg Moser <georg.moser@uibk.ac.at>, -- Andreas Schnabl <andreas.schnabl@uibk.ac.at>, -- License : LGPL (see COPYING) -- -- Maintainer : Martin Avanzini <martin.avanzini@uibk.ac.at> -- Stability : unstable -- Portability : unportable -- -- This module provides the usable rules transformation. -------------------------------------------------------------------------------- module Tct.Method.DP.UsableRules ( usableRules -- * Proof Object , URProof (..) -- * Processor , usableRulesProcessor , UR -- * Utilities , mkUsableRules ) where import qualified Data.Set as Set import Text.PrettyPrint.HughesPJ hiding (empty) import qualified Termlib.FunctionSymbol as F import qualified Termlib.Variable as V import qualified Termlib.Problem as Prob import qualified Termlib.Term as Term import qualified Termlib.Rule as R import Termlib.Rule (Rule (..)) import qualified Termlib.Trs as Trs import Termlib.Trs (Trs) import Termlib.Trs.PrettyPrint (pprintNamedTrs) import Termlib.Utils hiding (block) import qualified Tct.Utils.Xml as Xml import qualified Tct.Utils.Xml.Encoding as XmlE import qualified Tct.Processor.Transformations as T import qualified Tct.Processor as P import Tct.Processor.Args as A import Tct.Utils.Enum (enumeration') import Tct.Utils.PPrint import Tct.Method.DP.Utils -- | The Trs 'mkUsableRules prob trs' contains -- all rules of 'trs' which are usable by 'prob'. mkUsableRules :: Prob.Problem -> Trs -> Trs mkUsableRules prob trs = trs `restrictTo` Set.unions [decendants f | f <- ds , Rule _ r <- Trs.rules $ Prob.dpComponents prob , f `Set.member` Term.functionSymbols r ] where trs' `restrictTo` roots = Trs.fromRules [ rule | rule <- Trs.rules trs', let Right f = Term.root (R.lhs rule) in f `Set.member` roots ] decendants f = reachable step [f] Set.empty where step f' = Set.fromList [ g | g <- ds , Rule l r <- Trs.rules trss , Term.root l == Right f' , g `Set.member` Term.functionSymbols r ] reachable _ [] visited = visited reachable nexts (f:fs) visited | f `Set.member` visited = reachable nexts fs visited | otherwise = reachable nexts (fs' ++ fs) (Set.insert f visited) where fs' = Set.toList $ nexts f ds = Set.toList $ Trs.definedSymbols trss trss = Prob.trsComponents prob data UR = UR data URProof = URProof { usableStrict :: Trs -- ^ Usable strict rules , usableWeak :: Trs -- ^ Usable weak rules , signature :: F.Signature , variables :: V.Variables , progressed :: Bool -- ^ This flag is 'True' iff some rules are not usable } | Error DPError instance PrettyPrintable URProof where pprint p@URProof {} | prog && null allUrs = text "No rule is usable, rules are removed from the input problem." | prog = paragraph "We replace rewrite rules by usable rules:" $+$ text "" $+$ indent (ppTrs "Strict Usable Rules" (usableStrict p) $+$ ppTrs "Weak Usable Rules" (usableWeak p)) | otherwise = text "All rules are usable." where ppTrs = pprintNamedTrs (signature p) (variables p) allUrs = Trs.rules (usableStrict p) ++ Trs.rules (usableWeak p) prog = progressed p pprint (Error e) = pprint e instance T.TransformationProof UR where answer = T.answerFromSubProof pprintTProof _ _ p _ = pprint p tproofToXml _ _ (Error e) = ("usableRules", [errorToXml e]) tproofToXml _ _ p = ("usablerules", [ Xml.elt "strict" [] [XmlE.rules (usableStrict p) sig vs] , Xml.elt "weak" [] [XmlE.rules (usableWeak p) sig vs] ]) where sig = signature p vs = variables p instance T.Transformer UR where name UR = "usablerules" description UR = [ "This processor restricts the strict- and weak-rules to usable rules with" , "respect to the dependency pairs."] type ArgumentsOf UR = Unit type ProofOf UR = URProof arguments UR = Unit transform _ prob | not (Prob.isDPProblem prob) = return $ T.NoProgress $ Error NonDPProblemGiven | otherwise = return $ res where res | progr = T.Progress ursproof (enumeration' [prob']) | otherwise = T.NoProgress ursproof strs = Prob.strictTrs prob wtrs = Prob.weakTrs prob surs = mkUsableRules prob strs wurs = mkUsableRules prob wtrs progr = size wurs < size wtrs || size surs < size strs where size = length . Trs.rules ursproof = URProof { usableStrict = surs , usableWeak = wurs , signature = Prob.signature prob , variables = Prob.variables prob , progressed = progr } prob' = prob { Prob.strictTrs = surs , Prob.weakTrs = wurs } usableRulesProcessor :: T.Transformation UR P.AnyProcessor usableRulesProcessor = T.Transformation UR usableRules :: T.TheTransformer UR usableRules = T.Transformation UR `T.withArgs` ()
mzini/TcT
source/Tct/Method/DP/UsableRules.hs
gpl-3.0
6,152
0
17
2,132
1,393
757
636
104
2
module Screen where type Pos = (Int,Int) data Color = BLACK | RED | GREEN | YELLOW | BLUE | MAGENTA | CYAN | WHITE data Viewport = Viewport Pos Int Int -- clear the text screen cls :: IO() cls = putStr "\ESC[2J" -- make a beep beep :: IO() beep = putStr "\BEL" -- move the cursor at the new pos (x,y) goto :: Pos -> IO () goto (x,y) = putStr("\ESC["++show y++";"++show x++"H") -- write at the cursor writeAt :: Pos -> String -> IO() writeAt p s = goto p >> putStr s --set foreground color setFColor :: Color -> IO() setFColor c = putStr ("\ESC["++showFColor c++"m") where showFColor BLACK = "30" showFColor RED = "31" showFColor GREEN = "32" showFColor YELLOW = "33" showFColor BLUE = "34" showFColor MAGENTA = "35" showFColor CYAN = "36" showFColor WHITE = "37" --set background color setBColor :: Color -> IO() setBColor c = putStr ("\ESC["++showBColor c++"m") where showBColor BLACK = "40" showBColor RED = "41" showBColor GREEN = "42" showBColor YELLOW = "43" showBColor BLUE = "44" showBColor MAGENTA = "45" showBColor CYAN = "46" showBColor WHITE = "47"
edoz90/PAP-Assignment
src/pap/ass02/Screen.hs
gpl-3.0
1,109
6
11
240
409
213
196
35
8
{-# LANGUAGE FlexibleContexts #-} module Solver.SComponentWithCut (checkSComponentWithCutSat) where import Data.SBV import Data.List (genericLength) import qualified Data.Map as M import Util import PetriNet import Solver type SizeIndicator = (Integer, Integer, Integer, Integer, Integer) checkPrePostPlaces :: PetriNet -> SIMap Place -> SIMap Place -> SIMap Transition -> SIMap Transition -> SIMap Transition -> SBool checkPrePostPlaces net p1 p2 t0 t1 t2 = bAnd (map (checkPrePostPlace p1 [t0,t1]) (places net)) &&& bAnd (map (checkPrePostPlace p2 [t0,t2]) (places net)) where checkPrePostPlace ps ts p = let incoming = map (checkIn ts) $ pre net p outgoing = map (checkIn ts) $ post net p in val ps p .== 1 ==> bAnd incoming &&& bAnd outgoing checkIn xs x = sum (map (`val` x) xs) .== 1 checkPrePostTransitions :: PetriNet -> SIMap Place -> SIMap Place -> SIMap Transition -> SIMap Transition -> SIMap Transition -> SBool checkPrePostTransitions net p1 p2 t0 t1 t2 = bAnd (map (checkPrePostTransition t0 [p1,p2]) (transitions net)) &&& bAnd (map (checkPrePostTransition t1 [p1]) (transitions net)) &&& bAnd (map (checkPrePostTransition t2 [p2]) (transitions net)) where checkPrePostTransition ts ps t = let incoming = checkInOne ps $ pre net t outgoing = checkInOne ps $ post net t in val ts t .== 1 ==> incoming &&& outgoing checkInOne xs x = sum (concatMap (`mval` x) xs) .== 1 checkComponents :: FiringVector -> SIMap Transition -> SIMap Transition -> SBool checkComponents x t1 t2 = checkComponent t1 &&& checkComponent t2 where checkTransition ts t = val ts t .== 1 checkComponent ts = bOr $ map (checkTransition ts) $ elems x checkZeroUnused :: FiringVector -> SIMap Transition -> SBool checkZeroUnused x t0 = bAnd (map checkTransition (elems x)) where checkTransition t = val t0 t .== 0 checkTokens :: PetriNet -> SIMap Place -> SIMap Place -> SBool checkTokens net p1 p2 = sum (map addPlace $ linitials net) .== 1 where addPlace (p,i) = literal i * (val p1 p + val p2 p) checkDisjunct :: PetriNet -> SIMap Place -> SIMap Place -> SIMap Transition -> SIMap Transition -> SIMap Transition -> SBool checkDisjunct net p1 p2 t0 t1 t2 = bAnd (map checkPlace (places net)) &&& bAnd (map checkTransition (transitions net)) where checkPlace p = val p1 p + val p2 p .<= 1 checkTransition t = val t0 t + val t1 t + val t2 t .<= 1 checkBinary :: SIMap Place -> SIMap Place -> SIMap Transition -> SIMap Transition -> SIMap Transition -> SBool checkBinary p1 p2 t0 t1 t2 = checkBins p1 &&& checkBins p2 &&& checkBins t0 &&& checkBins t1 &&& checkBins t2 where checkBins xs = bAnd $ map (\x -> x .== 0 ||| x .== 1) $ vals xs checkSizeLimit :: SIMap Place -> SIMap Place -> SIMap Transition -> SIMap Transition -> SIMap Transition -> Maybe (Int, SizeIndicator) -> SBool checkSizeLimit _ _ _ _ _ Nothing = true checkSizeLimit p1 p2 t0 t1 t2 (Just (minMethod, (p1Size, p2Size, t0Size, t1Size, t2Size))) = let p1SizeNext = sumVal p1 p2SizeNext = sumVal p2 t0SizeNext = sumVal t0 t1SizeNext = sumVal t1 t2SizeNext = sumVal t2 p1SizeNow = literal p1Size p2SizeNow = literal p2Size t0SizeNow = literal t0Size t1SizeNow = literal t1Size t2SizeNow = literal t2Size in case minMethod of 1 -> (t0SizeNext .< t0SizeNow) ||| (t0SizeNext .== t0SizeNow &&& t1SizeNext .> t1SizeNow &&& t2SizeNext .>= t2SizeNow) ||| (t0SizeNext .== t0SizeNow &&& t1SizeNext .>= t1SizeNow &&& t2SizeNext .> t2SizeNow) 2 -> (t1SizeNext .> t1SizeNow &&& t2SizeNext .>= t2SizeNow) ||| (t1SizeNext .>= t1SizeNow &&& t2SizeNext .> t2SizeNow) ||| (t1SizeNext .== t1SizeNow &&& t2SizeNext .== t2SizeNow &&& t0SizeNext .< t0SizeNow) 3 -> (p1SizeNext + p2SizeNext .< p1SizeNow + p2SizeNow) ||| (p1SizeNext + p2SizeNext .== p1SizeNow + p2SizeNow &&& t0SizeNext .< t0SizeNow) 4 -> (p1SizeNext + p2SizeNext .> p1SizeNow + p2SizeNow) ||| (p1SizeNext + p2SizeNext .== p1SizeNow + p2SizeNow &&& t0SizeNext .< t0SizeNow) 5 -> (p1SizeNext + p2SizeNext .< p1SizeNow + p2SizeNow) 6 -> (p1SizeNext + p2SizeNext .> p1SizeNow + p2SizeNow) 7 -> (t1SizeNext .> t1SizeNow &&& t2SizeNext .>= t2SizeNow) ||| (t1SizeNext .>= t1SizeNow &&& t2SizeNext .> t2SizeNow) 8 -> (t1SizeNext .< t1SizeNow &&& t2SizeNext .<= t2SizeNow) ||| (t1SizeNext .<= t1SizeNow &&& t2SizeNext .< t2SizeNow) 9 -> (t1SizeNext + t2SizeNext .> t1SizeNow + t2SizeNow) _ -> error $ "minimization method " ++ show minMethod ++ " not supported" checkSComponent :: PetriNet -> FiringVector -> Maybe (Int, SizeIndicator) -> SIMap Place -> SIMap Place -> SIMap Transition -> SIMap Transition -> SIMap Transition -> SBool checkSComponent net x sizeLimit p1 p2 t0 t1 t2 = checkPrePostPlaces net p1 p2 t0 t1 t2 &&& checkPrePostTransitions net p1 p2 t0 t1 t2 &&& checkZeroUnused x t0 &&& checkComponents x t1 t2 &&& checkSizeLimit p1 p2 t0 t1 t2 sizeLimit &&& checkTokens net p1 p2 &&& checkBinary p1 p2 t0 t1 t2 &&& checkDisjunct net p1 p2 t0 t1 t2 checkSComponentWithCutSat :: PetriNet -> FiringVector -> Maybe (Int, SizeIndicator) -> ConstraintProblem Integer (Cut, SizeIndicator) checkSComponentWithCutSat net x sizeLimit = let p1 = makeVarMapWith ("P1@"++) $ places net p2 = makeVarMapWith ("P2@"++) $ places net t0 = makeVarMapWith ("T0@"++) $ transitions net t1 = makeVarMapWith ("T1@"++) $ transitions net t2 = makeVarMapWith ("T2@"++) $ transitions net in ("general S-component constraints", "cut", getNames p1 ++ getNames p2 ++ getNames t0 ++ getNames t1 ++ getNames t2, \fm -> checkSComponent net x sizeLimit (fmap fm p1) (fmap fm p2) (fmap fm t0) (fmap fm t1) (fmap fm t2), \fm -> cutFromAssignment (fmap fm p1) (fmap fm p2) (fmap fm t0) (fmap fm t1) (fmap fm t2)) cutFromAssignment :: IMap Place -> IMap Place -> IMap Transition -> IMap Transition -> IMap Transition -> (Cut, SizeIndicator) cutFromAssignment p1m p2m t0m t1m t2m = let p1 = M.keys $ M.filter (> 0) p1m p2 = M.keys $ M.filter (> 0) p2m t0 = M.keys $ M.filter (> 0) t0m t1 = M.keys $ M.filter (> 0) t1m t2 = M.keys $ M.filter (> 0) t2m in (([(p1,t1),(p2,t2)], t0), (genericLength p1, genericLength p2, genericLength t0, genericLength t1, genericLength t2))
cryptica/slapnet
src/Solver/SComponentWithCut.hs
gpl-3.0
7,349
0
17
2,316
2,462
1,235
1,227
133
10
module Y2017.R1A.D where import Protolude import Data.String import GCJ parse :: [String] -> [P] solve' :: P -> S write :: S -> Text verify :: P -> S -> Verification solve :: Bool -> Text -> Text solve = GCJ.solve (Parse parse) (Solve solve') (Write write) (Verify verify) example :: String example = "" data P = P deriving Show data S = S deriving Show parse (_:rest) = P : parse rest parse _ = [] {-> parse . drop 1 . lines $ example [] -} solve' P = S {-> map solve' $ parse . drop 1 . lines $ example [] -} write S = toS $ " " ++ "\n" verify P S = Nothing
joranvar/GCJ
src/gcj-lib/Y2017/R1A/D.hs
gpl-3.0
574
0
7
135
215
118
97
19
1
class X a where f :: a -> Int instance X (Maybe a) where f n = n main = f (Just 3)
Helium4Haskell/helium
test/typeClasses/ClassInstaneError8.hs
gpl-3.0
92
0
7
32
55
27
28
5
1
----------------------------------------------------------------------------- -- -- Module : Data.DICOM.Tag -- Copyright : Copyright (c) DICOM Grid 2015 -- License : GPL-3 -- -- Maintainer : paf31@cantab.net -- Stability : experimental -- Portability : -- ----------------------------------------------------------------------------- {-# LANGUAGE PatternSynonyms #-} module Data.DICOM.Tag ( TagGroup (TagGroup, runTagGroup) , TagElement (TagElement, runTagElement) , Tag (tagGroup, tagElement) , pattern SequenceGroup , pattern Item , pattern ItemDelimitationItem , pattern SequenceDelimitationItem , pattern PixelData , tag ) where import Data.Word import Data.Binary import Data.Binary.Get import Data.Binary.Put import Control.Applicative newtype TagGroup = TagGroup { runTagGroup :: Word16 } deriving (Show, Eq, Ord) newtype TagElement = TagElement { runTagElement :: Word16 } deriving (Show, Eq, Ord) data Tag = Tag { tagGroup :: TagGroup , tagElement :: TagElement } deriving (Show, Eq, Ord) -- Serialization instance Binary TagGroup where get = TagGroup <$> getWord16le put = putWord16le . runTagGroup instance Binary TagElement where get = TagElement <$> getWord16le put = putWord16le . runTagElement instance Binary Tag where get = Tag <$> get <*> get put t = do put (tagGroup t) put (tagElement t) -- Special tags pattern SequenceGroup = TagGroup 0xFFFE pattern Item = Tag SequenceGroup (TagElement 0xE000) pattern ItemDelimitationItem = Tag SequenceGroup (TagElement 0xE00D) pattern SequenceDelimitationItem = Tag SequenceGroup (TagElement 0xE0DD) pattern PixelData = Tag (TagGroup 0x7FE0) (TagElement 0x0010) -- Smart constructors tag :: TagGroup -> TagElement -> Tag tag = Tag
dicomgrid/dicom-haskell-library
src/Data/DICOM/Tag.hs
gpl-3.0
1,848
0
10
381
414
238
176
47
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Dataflow.Projects.Jobs.Aggregated -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- List the jobs of a project across all regions. -- -- /See:/ <https://cloud.google.com/dataflow Dataflow API Reference> for @dataflow.projects.jobs.aggregated@. module Network.Google.Resource.Dataflow.Projects.Jobs.Aggregated ( -- * REST Resource ProjectsJobsAggregatedResource -- * Creating a Request , projectsJobsAggregated , ProjectsJobsAggregated -- * Request Lenses , pjaXgafv , pjaUploadProtocol , pjaLocation , pjaAccessToken , pjaUploadType , pjaView , pjaFilter , pjaPageToken , pjaProjectId , pjaPageSize , pjaCallback ) where import Network.Google.Dataflow.Types import Network.Google.Prelude -- | A resource alias for @dataflow.projects.jobs.aggregated@ method which the -- 'ProjectsJobsAggregated' request conforms to. type ProjectsJobsAggregatedResource = "v1b3" :> "projects" :> Capture "projectId" Text :> "jobs:aggregated" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "location" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "view" ProjectsJobsAggregatedView :> QueryParam "filter" ProjectsJobsAggregatedFilter :> QueryParam "pageToken" Text :> QueryParam "pageSize" (Textual Int32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ListJobsResponse -- | List the jobs of a project across all regions. -- -- /See:/ 'projectsJobsAggregated' smart constructor. data ProjectsJobsAggregated = ProjectsJobsAggregated' { _pjaXgafv :: !(Maybe Xgafv) , _pjaUploadProtocol :: !(Maybe Text) , _pjaLocation :: !(Maybe Text) , _pjaAccessToken :: !(Maybe Text) , _pjaUploadType :: !(Maybe Text) , _pjaView :: !(Maybe ProjectsJobsAggregatedView) , _pjaFilter :: !(Maybe ProjectsJobsAggregatedFilter) , _pjaPageToken :: !(Maybe Text) , _pjaProjectId :: !Text , _pjaPageSize :: !(Maybe (Textual Int32)) , _pjaCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsJobsAggregated' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pjaXgafv' -- -- * 'pjaUploadProtocol' -- -- * 'pjaLocation' -- -- * 'pjaAccessToken' -- -- * 'pjaUploadType' -- -- * 'pjaView' -- -- * 'pjaFilter' -- -- * 'pjaPageToken' -- -- * 'pjaProjectId' -- -- * 'pjaPageSize' -- -- * 'pjaCallback' projectsJobsAggregated :: Text -- ^ 'pjaProjectId' -> ProjectsJobsAggregated projectsJobsAggregated pPjaProjectId_ = ProjectsJobsAggregated' { _pjaXgafv = Nothing , _pjaUploadProtocol = Nothing , _pjaLocation = Nothing , _pjaAccessToken = Nothing , _pjaUploadType = Nothing , _pjaView = Nothing , _pjaFilter = Nothing , _pjaPageToken = Nothing , _pjaProjectId = pPjaProjectId_ , _pjaPageSize = Nothing , _pjaCallback = Nothing } -- | V1 error format. pjaXgafv :: Lens' ProjectsJobsAggregated (Maybe Xgafv) pjaXgafv = lens _pjaXgafv (\ s a -> s{_pjaXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pjaUploadProtocol :: Lens' ProjectsJobsAggregated (Maybe Text) pjaUploadProtocol = lens _pjaUploadProtocol (\ s a -> s{_pjaUploadProtocol = a}) -- | The [regional endpoint] -- (https:\/\/cloud.google.com\/dataflow\/docs\/concepts\/regional-endpoints) -- that contains this job. pjaLocation :: Lens' ProjectsJobsAggregated (Maybe Text) pjaLocation = lens _pjaLocation (\ s a -> s{_pjaLocation = a}) -- | OAuth access token. pjaAccessToken :: Lens' ProjectsJobsAggregated (Maybe Text) pjaAccessToken = lens _pjaAccessToken (\ s a -> s{_pjaAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pjaUploadType :: Lens' ProjectsJobsAggregated (Maybe Text) pjaUploadType = lens _pjaUploadType (\ s a -> s{_pjaUploadType = a}) -- | Deprecated. ListJobs always returns summaries now. Use GetJob for other -- JobViews. pjaView :: Lens' ProjectsJobsAggregated (Maybe ProjectsJobsAggregatedView) pjaView = lens _pjaView (\ s a -> s{_pjaView = a}) -- | The kind of filter to use. pjaFilter :: Lens' ProjectsJobsAggregated (Maybe ProjectsJobsAggregatedFilter) pjaFilter = lens _pjaFilter (\ s a -> s{_pjaFilter = a}) -- | Set this to the \'next_page_token\' field of a previous response to -- request additional results in a long list. pjaPageToken :: Lens' ProjectsJobsAggregated (Maybe Text) pjaPageToken = lens _pjaPageToken (\ s a -> s{_pjaPageToken = a}) -- | The project which owns the jobs. pjaProjectId :: Lens' ProjectsJobsAggregated Text pjaProjectId = lens _pjaProjectId (\ s a -> s{_pjaProjectId = a}) -- | If there are many jobs, limit response to at most this many. The actual -- number of jobs returned will be the lesser of max_responses and an -- unspecified server-defined limit. pjaPageSize :: Lens' ProjectsJobsAggregated (Maybe Int32) pjaPageSize = lens _pjaPageSize (\ s a -> s{_pjaPageSize = a}) . mapping _Coerce -- | JSONP pjaCallback :: Lens' ProjectsJobsAggregated (Maybe Text) pjaCallback = lens _pjaCallback (\ s a -> s{_pjaCallback = a}) instance GoogleRequest ProjectsJobsAggregated where type Rs ProjectsJobsAggregated = ListJobsResponse type Scopes ProjectsJobsAggregated = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly", "https://www.googleapis.com/auth/userinfo.email"] requestClient ProjectsJobsAggregated'{..} = go _pjaProjectId _pjaXgafv _pjaUploadProtocol _pjaLocation _pjaAccessToken _pjaUploadType _pjaView _pjaFilter _pjaPageToken _pjaPageSize _pjaCallback (Just AltJSON) dataflowService where go = buildClient (Proxy :: Proxy ProjectsJobsAggregatedResource) mempty
brendanhay/gogol
gogol-dataflow/gen/Network/Google/Resource/Dataflow/Projects/Jobs/Aggregated.hs
mpl-2.0
7,207
0
22
1,734
1,137
656
481
157
1
{- ORMOLU_DISABLE -} -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca) -- Copyright (C) 2014 2015, Julia Longtin (julial@turinglace.com) -- Released under the GNU AGPLV3+, see LICENSE -- FIXME: what are these for? {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ViewPatterns #-} -- A Snap(HTTP) server providing an ImplicitCAD REST API. -- FIXME: we need AuthN/AuthZ for https://github.com/kliment/explicitcad to be useful. -- Let's be explicit about what we're getting from where :) import Prelude (IO, Maybe(Just, Nothing), String, Bool(True, False), ($), (<>), (>), (.), (-), (/), (*), (**), (==), null, sqrt, min, max, minimum, maximum, show, return, fmap, otherwise, filter, not) import Control.Applicative ((<|>)) import Snap.Core (Snap, route, writeText, writeBS, method, Method(GET), modifyResponse, setContentType, setTimeout, getRequest, rqParam) import Snap.Http.Server (quickHttpServe) import Snap.Util.GZip (withCompression) -- Our Extended OpenScad interpreter, and the extrude function for making 2D objects 3D. import Graphics.Implicit (runOpenscad, extrude, unionR) -- Variable access functionality, so we can look up a requested resolution, along with message processing, and options into the scad engine. import Graphics.Implicit.ExtOpenScad.Definitions (OVal(ONum), VarLookup, lookupVarIn, Message, Message(Message), MessageType(TextOut), ScadOpts(ScadOpts)) -- determine the size of boxes, so we can automagically create a resolution. import Graphics.Implicit.Primitives (Object(getBox)) -- Definitions of the datatypes used for 2D objects, 3D objects, and for defining the resolution to raytrace at. import Graphics.Implicit.Definitions (ℝ, Polyline, TriangleMesh, NormedTriangleMesh, SymbolicObj2, SymbolicObj3) -- Use default values when a Maybe is Nothing. import Data.Maybe (fromMaybe, maybe, fromJust) import Graphics.Implicit.Export.TriangleMeshFormats (jsTHREE, stl) import qualified Graphics.Implicit.Export.NormedTriangleMeshFormats as NTM (obj) import Graphics.Implicit.Export.PolylineFormats (svg, dxf2, hacklabLaserGCode) -- Operator for vector subtraction, to subtract two points. Used when defining the resolution of a 2d object. import Linear.Affine((.-.)) -- class DiscreteApprox import Graphics.Implicit.Export.DiscreteAproxable (discreteAprox) import Data.List (intercalate) import System.IO.Unsafe (unsafePerformIO) import Data.ByteString.Char8 (unpack) import Data.ByteString.UTF8 (fromString) import Data.ByteString (ByteString) import Data.ByteString.Lazy as BSL (toStrict) import Data.Text (Text, pack) import Data.Text.Lazy as TL (toStrict) import Data.Text.Encoding (encodeUtf8) import Data.Aeson (encode) -- To construct vectors of ℝs. import Linear (V2(V2), V3(V3)) -- | The entry point. uses snap to serve a website. main :: IO () main = quickHttpServe site -- | Our site definition. Renders requests to "render/", discards all else. site :: Snap () site = route [ ("render/", renderHandler) ] <|> writeText "fall through" -- | Our render/ handler. Uses source, callback, and opitional format to render an object. renderHandler :: Snap () renderHandler = method GET $ withCompression $ do modifyResponse $ setContentType "application/x-javascript" setTimeout 600 request <- getRequest case (rqParam "source" request, rqParam "callback" request, rqParam "format" request) of (Just [source], Just [callback], Nothing) -> writeBS $ executeAndExport (unpack source) callback Nothing (Just [source], Just [callback], Just [format]) -> writeBS $ executeAndExport (unpack source) callback (Just format) (_, _, _) -> writeText "must provide source and callback as 1 GET variable each" -- | Find the resolution to raytrace at. getRes :: (VarLookup, [SymbolicObj2], [SymbolicObj3], [Message]) -> ℝ -- If specified, use a resolution specified by the "$res" a variable in the input file. getRes (lookupVarIn "$res" -> Just (ONum res), _, _, _) = res -- If there was no resolution specified, use a resolution chosen for 3D objects. -- FIXME: magic numbers. getRes (vars, _, obj:objs, _) = let (V3 x1 y1 z1, V3 x2 y2 z2) = getBox (unionR 0 (obj:objs)) (V3 x y z) = V3 (x2-x1) (y2-y1) (z2-z1) in case fromMaybe (ONum 1) $ lookupVarIn "$quality" vars of ONum qual | qual > 0 -> min (minimum [x,y,z]/2) ((x*y*z/qual)**(1/3) / 22) _ -> min (minimum [x,y,z]/2) ((x*y*z)**(1/3) / 22) -- ... Or use a resolution chosen for 2D objects. -- FIXME: magic numbers. getRes (vars, obj:objs, _, _) = let (p1,p2) = getBox (unionR 0 (obj:objs)) (V2 x y) = p2 .-. p1 in case fromMaybe (ONum 1) $ lookupVarIn "$quality" vars of ONum qual | qual > 0 -> min (min x y/2) (sqrt(x*y/qual) / 30) _ -> min (min x y/2) (sqrt(x*y) / 30) -- fallthrough value. getRes _ = 1 -- | get the maximum dimension of the object being rendered. -- FIXME: shouldn't this get the diagonal across the box? getWidth :: (VarLookup, [SymbolicObj2], [SymbolicObj3], [Message]) -> ℝ getWidth (_, _, obj:objs, _) = maximum [x2-x1, y2-y1, z2-z1] where (V3 x1 y1 z1, V3 x2 y2 z2) = getBox $ unionR 0 (obj:objs) getWidth (_, obj:objs, _, _) = max (x2-x1) (y2-y1) where (V2 x1 y1, V2 x2 y2) = getBox $ unionR 0 (obj:objs) getWidth (_, [], [], _) = 0 formatIs2D :: Maybe ByteString -> Bool formatIs2D (Just "SVG") = True formatIs2D (Just "gcode/hacklab-laser") = True formatIs2D _ = False getOutputHandler2 :: ByteString -> [Polyline] -> Text getOutputHandler2 name | name == "SVG" = TL.toStrict.svg | name == "gcode/hacklab-laser" = TL.toStrict.hacklabLaserGCode | name == "DXF" = TL.toStrict.dxf2 | otherwise = TL.toStrict.svg formatIs3D :: Maybe ByteString -> Bool formatIs3D (Just "STL") = True formatIs3D (Just "OBJ") = True formatIs3D _ = False -- FIXME: OBJ support getOutputHandler3 :: ByteString -> TriangleMesh -> Text getOutputHandler3 name | name == "STL" = TL.toStrict.stl | otherwise = TL.toStrict.jsTHREE getNormedOutputHandler3 :: ByteString -> NormedTriangleMesh -> Text getNormedOutputHandler3 name | name == "OBJ" = TL.toStrict.NTM.obj | otherwise = TL.toStrict.NTM.obj isTextOut :: Message -> Bool isTextOut (Message TextOut _ _ ) = True isTextOut _ = False -- | decide what options to send to the scad engine. generateScadOpts :: ScadOpts generateScadOpts = ScadOpts compat_flag import_flag where compat_flag = False -- Do not try to be extra compatible with openscad. import_flag = False -- Do not honor include or use statements. -- | Give an openscad object to run and the basename of -- the target to write to... write an object! executeAndExport :: String -> ByteString -> Maybe ByteString -> ByteString executeAndExport content callback maybeFormat = let showB :: Bool -> ByteString showB True = "true" showB False = "false" showℝ :: ℝ -> ByteString showℝ val = fromString $ show val callbackF :: Bool -> Bool -> ℝ -> Text -> ByteString callbackF False is2D w msg = callback <> "([null," <> BSL.toStrict (encode msg) <> "," <> showB is2D <> "," <> showℝ w <> "]);" callbackF True is2D w msg = callback <> "([new Shape()," <> BSL.toStrict (encode msg) <> "," <> showB is2D <> "," <> showℝ w <> "]);" callbackS :: Text -> Text -> ByteString callbackS str msg = callback <> "([" <> BSL.toStrict (encode str) <> "," <> BSL.toStrict (encode msg) <> ",null,null]);" scadOptions = generateScadOpts openscadProgram = runOpenscad scadOptions [] content in unsafePerformIO $ do s@(_, obj2s, obj3s, messages) <- openscadProgram let res = getRes s w = getWidth s emptyObject :: Text emptyObject = "Empty Object?" <> " (No geometry generated -- whatever you did, the engine can make no sense of it)" render = res > 0 scadMessages = pack $ intercalate "\n" (fmap show (filter (not . isTextOut) messages) <> fmap show (filter isTextOut messages)) return $ case (obj2s, obj3s, render) of (_ , _, False) -> callbackF False False 1 emptyObject ([], obj:objs, _ ) -> do let target = if null objs then obj else unionR 0 (obj:objs) unionWarning :: Text unionWarning = if null objs then "" else " \nWARNING: Multiple objects detected. Adding a Union around them." output3d :: Text output3d = if fromMaybe "jsTHREE" maybeFormat == "OBJ" then getNormedOutputHandler3 (fromJust maybeFormat) $ discreteAprox res target else maybe (TL.toStrict.jsTHREE) getOutputHandler3 maybeFormat $ discreteAprox res target if fromMaybe "jsTHREE" maybeFormat == "jsTHREE" then encodeUtf8 output3d <> callbackF True False w (scadMessages <> unionWarning) else if formatIs3D maybeFormat then callbackS output3d (scadMessages <> unionWarning) else callbackF False False 1 "Unable to render a 3D object into a 2D file." (obj:objs, [] , _) -> do let target = if null objs then obj else unionR 0 (obj:objs) unionWarning :: Text unionWarning = if null objs then "" else " \nWARNING: Multiple objects detected. Adding a Union around them." output3d = maybe (TL.toStrict.jsTHREE) getOutputHandler3 maybeFormat $ discreteAprox res $ extrude target res output2d = maybe (TL.toStrict.svg) getOutputHandler2 maybeFormat $ discreteAprox res target if fromMaybe "jsTHREE" maybeFormat == "jsTHREE" then encodeUtf8 output3d <> callbackF True True w (scadMessages <> unionWarning) else if formatIs2D maybeFormat then callbackS output2d (scadMessages <> unionWarning) else callbackS output3d (scadMessages <> unionWarning) ([], [] , _) -> callbackF False False 1 $ scadMessages <> "\n" <> "Nothing to render." _ -> callbackF False False 1 $ scadMessages <> "\n" <> "ERROR: File contains a mixture of 2D and 3D objects, what do you want to render?"
colah/ImplicitCAD
programs/implicitsnap.hs
agpl-3.0
11,011
6
24
2,969
2,901
1,584
1,317
170
16
{- | Module : $Header$ Description : Solution to problem 10 License : PublicDomain The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. -} module Solutions.Problem010 where import Data.Numbers.Primes(primes) solution n = sum (takeWhile (<n) primes)
jhnesk/project-euler
src/Solutions/Problem010.hs
unlicense
314
0
8
68
41
24
17
3
1
{-# LANGUAGE OverloadedStrings #-} -- | -- Module: Network.Riak.Content -- Copyright: (c) 2011 MailRank, Inc. -- License: Apache -- Maintainer: Nathan Hunter <nhunter@janrain.com> -- Stability: experimental -- Portability: portable -- -- Low-level content and link types and functions. module Network.Riak.Content ( -- * Types Content(..) , Link.Link(..) -- * Functions , empty , binary , json , link ) where import Data.Aeson.Encode (encode) import Data.Aeson.Types (ToJSON) import Network.Riak.Protocol.Content (Content(..)) import Network.Riak.Types.Internal (Bucket, Key, Tag) import qualified Data.ByteString.Lazy.Char8 as L import qualified Data.Sequence as Seq import qualified Network.Riak.Protocol.Link as Link -- | Create a link. link :: Bucket -> Key -> Tag -> Link.Link link bucket key tag = Link.Link (Just bucket) (Just key) (Just tag) {-# INLINE link #-} -- | An empty piece of content. empty :: Content empty = Content { value = L.empty , content_type = Nothing , charset = Nothing , content_encoding = Nothing , vtag = Nothing , links = Seq.empty , last_mod = Nothing , last_mod_usecs = Nothing , usermeta = Seq.empty , indexes = Seq.empty } -- | Content encoded as @application/octet-stream@. binary :: L.ByteString -> Content binary bs = empty { value = bs , content_type = Just "application/octet-stream" } -- | Content encoded as @application/json@. json :: ToJSON a => a -> Content json j = empty { value = encode j , content_type = Just "application/json" }
janrain/riak-haskell-client
src/Network/Riak/Content.hs
apache-2.0
1,771
0
8
517
356
224
132
36
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -Wall #-} -- TODO: Variables for user-defined data types {-| Defines a strongly-typed representation of Fortran variables. -} module Language.Fortran.Model.Vars ( -- * Variables FortranVar(..) -- * Names , NamePair(..) , npSource , npUnique , SourceName(..) , UniqueName(..) ) where import Data.Typeable ((:~:) (..)) import Control.Lens hiding (Index, op) import Data.SBV.Dynamic import Data.Vinyl (rtraverse) import qualified Language.Fortran.AST as F import Language.Expression.Pretty import Language.Verification import Language.Fortran.Model.Repr import Language.Fortran.Model.Repr.Prim import Language.Fortran.Model.Types import Language.Fortran.Model.Types.Match -------------------------------------------------------------------------------- -- Names -------------------------------------------------------------------------------- -- | Newtype wrapper for source-level variable names. newtype SourceName = SourceName { getSourceName :: F.Name } deriving (Eq, Ord) instance Show SourceName where show = show . getSourceName -- | Newtype wrapper for unique variable names. newtype UniqueName = UniqueName { getUniqueName :: F.Name } deriving (Eq, Ord) instance Show UniqueName where show = show . getUniqueName makeWrapped ''SourceName makeWrapped ''UniqueName -- | A 'NamePair' represents the name of some part of a Fortran program, -- including the human-readable source name and the unique name. data NamePair = NamePair { _npUnique :: UniqueName , _npSource :: SourceName } deriving (Eq, Ord, Show) makeLenses ''NamePair instance Pretty SourceName where pretty = view _Wrapped -- | The pretty version of a 'NamePair' is its source name. instance Pretty NamePair where pretty = pretty . view npSource -------------------------------------------------------------------------------- -- Fortran Variables -------------------------------------------------------------------------------- -- | A variable representing a value of type @a@. Contains a @'D' a@ as proof -- that the type has a corresponding Fortran type, and the variable name. data FortranVar a where FortranVar :: D a -> NamePair -> FortranVar a instance VerifiableVar FortranVar where type VarKey FortranVar = UniqueName type VarSym FortranVar = CoreRepr type VarEnv FortranVar = PrimReprHandlers symForVar (FortranVar d np) env = case d of DPrim prim -> CRPrim d <$> primSymbolic prim uniqueName env DArray i val -> CRArray d <$> arraySymbolic i val uniqueName env DData _ _ -> fail "User-defined data type variables are not supported yet" where uniqueName = np ^. npUnique . _Wrapped varKey (FortranVar _ np) = np ^. npUnique eqVarTypes (FortranVar d1 _) (FortranVar d2 _) = eqD d1 d2 castVarSym (FortranVar d1 _) s = case s of CRPrim d2 _ | Just Refl <- eqD d1 d2 -> Just s CRArray d2 _ | Just Refl <- eqD d1 d2 -> Just s CRData d2 _ | Just Refl <- eqD d1 d2 -> Just s -- Variables can't have the 'Bool' type so 'CRProp' can't be casted. _ -> Nothing instance Pretty1 FortranVar where pretty1 (FortranVar _ np) = pretty np -------------------------------------------------------------------------------- -- Internals -------------------------------------------------------------------------------- arraySymbolic :: (HasPrimReprHandlers r) => Index i -> ArrValue a -> String -> r -> Symbolic (ArrRepr i a) arraySymbolic ixIndex@(Index ixPrim) valAV nm env = case valAV of ArrPrim valPrim -> ARPrim <$> arraySymbolicPrim ixPrim valPrim nm env ArrData _ valData -> do valReprs <- rtraverse (traverseField' (\av -> arraySymbolic ixIndex av nm env)) valData return $ ARData valReprs arraySymbolicPrim :: (HasPrimReprHandlers r) => Prim p1 k1 i -> Prim p2 k2 a -> String -> r -> Symbolic SArr arraySymbolicPrim ixPrim valPrim nm = do k1 <- primSBVKind ixPrim k2 <- primSBVKind valPrim return $ newSArr (k1, k2) (\i -> nm ++ "_" ++ show i) -- pairProxy :: p1 a -> p2 b -> Proxy '(a, b) -- pairProxy _ _ = Proxy
dorchard/camfort
src/Language/Fortran/Model/Vars.hs
apache-2.0
4,697
0
16
1,055
987
529
458
-1
-1
-- Copyright 2020 Google LLC -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. module Main (main) where import Control.Monad (guard) import qualified Data.Set as Set main :: IO () main = guard (3 == Set.size (Set.fromList [1..3]))
google/cabal2bazel
bzl/tests/rules/DefaultPackageTest.hs
apache-2.0
743
0
11
127
83
53
30
5
1
-- | -- Module : Text.Megaparsec.Pos -- Copyright : © 2015–2017 Megaparsec contributors -- License : FreeBSD -- -- Maintainer : Mark Karpov <markkarpov92@gmail.com> -- Stability : experimental -- Portability : portable -- -- Textual source position. The position includes name of file, line number, -- and column number. List of such positions can be used to model a stack of -- include files. -- -- You probably do not want to import this module directly because -- "Text.Megaparsec" re-exports it anyway. {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Text.Megaparsec.Pos ( -- * Abstract position Pos , mkPos , unPos , pos1 , defaultTabWidth , InvalidPosException (..) -- * Source position , SourcePos (..) , initialPos , sourcePosPretty ) where import Control.DeepSeq import Control.Exception import Data.Data (Data) import Data.Semigroup import Data.Typeable (Typeable) import GHC.Generics ---------------------------------------------------------------------------- -- Abstract position -- | 'Pos' is the type for positive integers. This is used to represent line -- number, column number, and similar things like indentation level. -- 'Semigroup' instance can be used to safely and efficiently add 'Pos'es -- together. -- -- @since 5.0.0 newtype Pos = Pos Int deriving (Show, Eq, Ord, Data, Typeable, NFData) -- | Construction of 'Pos' from 'Word'. The function throws -- 'InvalidPosException' when given a non-positive argument. -- -- @since 6.0.0 mkPos :: Int -> Pos mkPos a = if a <= 0 then throw (InvalidPosException a) else Pos a {-# INLINE mkPos #-} -- | Extract 'Int' from 'Pos'. -- -- @since 6.0.0 unPos :: Pos -> Int unPos (Pos w) = w {-# INLINE unPos #-} -- | Position with value 1. -- -- @since 6.0.0 pos1 :: Pos pos1 = mkPos 1 -- | Value of tab width used by default. Always prefer this constant when -- you want to refer to the default tab width because actual value /may/ -- change in future. -- -- @since 5.0.0 defaultTabWidth :: Pos defaultTabWidth = mkPos 8 instance Semigroup Pos where (Pos x) <> (Pos y) = Pos (x + y) {-# INLINE (<>) #-} instance Read Pos where readsPrec d = readParen (d > 10) $ \r1 -> do ("Pos", r2) <- lex r1 (x, r3) <- readsPrec 11 r2 return (mkPos x, r3) -- | The exception is thrown by 'mkPos' when its argument is not a positive -- number. -- -- @since 5.0.0 data InvalidPosException = InvalidPosException Int -- ^ The first value is the minimal allowed value, the second value is the -- actual value that was passed to 'mkPos'. deriving (Eq, Show, Data, Typeable, Generic) instance Exception InvalidPosException instance NFData InvalidPosException ---------------------------------------------------------------------------- -- Source position -- | The data type 'SourcePos' represents source positions. It contains the -- name of the source file, a line number, and a column number. Source line -- and column positions change intensively during parsing, so we need to -- make them strict to avoid memory leaks. data SourcePos = SourcePos { sourceName :: FilePath -- ^ Name of source file , sourceLine :: !Pos -- ^ Line number , sourceColumn :: !Pos -- ^ Column number , totalTokens :: !Pos } deriving (Show, Read, Eq, Ord, Data, Typeable, Generic) instance NFData SourcePos -- | Construct initial position (line 1, column 1) given name of source -- file. initialPos :: FilePath -> SourcePos initialPos n = SourcePos n pos1 pos1 pos1 -- | Pretty-print a 'SourcePos'. -- -- @since 5.0.0 sourcePosPretty :: SourcePos -> String sourcePosPretty (SourcePos n l c _) | null n = showLC | otherwise = n <> ":" <> showLC where showLC = show (unPos l) <> ":" <> show (unPos c)
recursion-ninja/megaparsec
Text/Megaparsec/Pos.hs
bsd-2-clause
3,874
0
12
789
634
366
268
68
2
module Fib where import CLaSH.Prelude fib :: Signal (Unsigned 64) fib = register 1 fib + register 0 (register 0 fib) topEntity () = fib expectedOutput :: Signal (Unsigned 64) -> Signal Bool expectedOutput = outputVerifier $(v [1 :: Unsigned 64,1,2,3,5])
ggreif/clash-compiler
tests/shouldwork/Feedback/Fib.hs
bsd-2-clause
258
0
10
45
117
61
56
-1
-1
{-# LANGUAGE TupleSections #-} module DuckTest.Infer.AST where {- This module will, for each statement in an AST, infer - the type of that statement, as well as collect the - variables needed. -} import DuckTest.Types import DuckTest.Internal.Common import DuckTest.Monad import DuckTest.Infer.Functions import DuckTest.Infer.Classes import qualified Data.Map as Map data BoundVariable = BoundVariable { variable_name :: String , variable_type :: PyType } data Annotation = Annotation { annotation_bound :: Maybe BoundVariable -- a variable bound in the statement , annotation_unbound :: Map String PyType -- a map of needed variables to their types } inferStatements :: [Statement a] -> DuckTest a [(Annotation, Statement a)] inferStatements = mapM (\s -> (,s) <$> f s) where f st@(Fun (Ident name _) _ _ _ _) = do {- A function really binds a value to an element -} typ <- inferTypeForFunction st return $ Annotation (Just $ BoundVariable name $ Functional typ) Map.empty f cls@(Class {class_name = (Ident name _)}) = do {- A class really creates a function with that class name -} typ <- inferTypeForClass cls return $ Annotation (Just $ BoundVariable name $ Functional typ) Map.empty
jrahm/DuckTest
src/DuckTest/Infer/AST.hs
bsd-2-clause
1,310
0
14
308
306
167
139
22
2
module Data.MediaBus.Conduit.ReorderSpec ( spec, ) where import Conduit import Control.Monad import Data.Conduit.List import Data.MediaBus import Data.Proxy import Data.Word import Debug.Trace import Test.Hspec import Test.QuickCheck spec :: Spec spec = describe "reorderFramesBySeqNumC" $ do let runC inputs = runConduitPure ( sourceList inputs .| annotateTypeC (Proxy :: Proxy (Stream () TestSeqNumType () () ())) (reorderFramesBySeqNumC 3) .| consume ) it "yields at least one 'Start' for each incoming 'Start'" $ property $ \inputs -> let countStarts = foldr ( \x n -> case x of MkStream (Start _) -> n + 1 MkStream (Next _) -> n ) 0 in countStarts (runC inputs) `shouldSatisfy` (>= countStarts inputs) it "yields exactly the given input if the input is ordered and gap-free" $ let inputs = startFrame 0 : [nextFrame x | x <- [0 .. 10]] in runC inputs `shouldBe` inputs it "reorders out of order packets (1)" $ let inputs = [startFrame 0, nextFrame 0, nextFrame 2, nextFrame 3, nextFrame 1] expected = [startFrame 0, nextFrame 0, nextFrame 1, nextFrame 2, nextFrame 3] in runC inputs `shouldBe` expected it "reorders out of order packets (2)" $ let inputs = [startFrame 0, nextFrame 2, nextFrame 1, nextFrame 0] expected = [startFrame 0, nextFrame 0, nextFrame 1, nextFrame 2] in runC inputs `shouldBe` expected it "skips over missing frames when the queue is full" $ let inputs = [ startFrame 0, nextFrame 0, nextFrame 1, nextFrame 3, nextFrame 4, nextFrame 5 ] expected = [ startFrame 0, nextFrame 0, nextFrame 1, nextFrame 3, nextFrame 4, nextFrame 5 ] in runC inputs `shouldBe` expected it "restarts at the incoming sequence numbering after too many frame drops" $ let inputs = [ startFrame 10, nextFrame 10, nextFrame 11, nextFrame 12, nextFrame 0, nextFrame 1, nextFrame 2, nextFrame 3, nextFrame 4 ] expected = [ startFrame 10, nextFrame 10, nextFrame 11, nextFrame 12, startFrame 2, nextFrame 2, nextFrame 3, nextFrame 4 ] in runC inputs `shouldBe` expected it "restarts at the incoming sequence numbering after too many frame drops, AND flushes the queued elements first" $ let inputs = [ startFrame 10, nextFrame 13, nextFrame 14, nextFrame 0, nextFrame 1, nextFrame 2, nextFrame 3, nextFrame 4 ] expected = [ startFrame 10, nextFrame 13, nextFrame 14, startFrame 2, nextFrame 2, nextFrame 3, nextFrame 4 ] in runC inputs `shouldBe` expected it "flushes and resets its internal state after every 'Start'" $ let inputs = [ startFrame 10, nextFrame 13, nextFrame 14, startFrame 40, nextFrame 40, nextFrame 41, startFrame 50, nextFrame 0, nextFrame 1, startFrame 60, nextFrame 50, nextFrame 51, nextFrame 52 ] expected = [ startFrame 10, nextFrame 13, nextFrame 14, startFrame 40, nextFrame 40, nextFrame 41, startFrame 50, startFrame 60, startFrame 52, nextFrame 52 ] in runC inputs `shouldBe` expected it "yields monotone increasing frames higher than the start-frame" $ property $ \inputs -> let os = runC inputs in unless (isMonoIncreasingAndHigherThanStartSeqNum os) ( trace ( unlines ( (("IN: " ++) . show <$> inputs) ++ ( ("OUT: " ++) . show <$> os ) ) ) os `shouldSatisfy` isMonoIncreasingAndHigherThanStartSeqNum ) isMonoIncreasingAndHigherThanStartSeqNum :: [Stream () TestSeqNumType () () ()] -> Bool isMonoIncreasingAndHigherThanStartSeqNum [] = True isMonoIncreasingAndHigherThanStartSeqNum (MkStream (Start (MkFrameCtx () () sn ())) : rest) = isMonoIncreasingAndHigherThanStartSeqNumN sn rest isMonoIncreasingAndHigherThanStartSeqNum rest@(MkStream (Next (MkFrame () sn ())) : _) = isMonoIncreasingAndHigherThanStartSeqNumN sn rest isMonoIncreasingAndHigherThanStartSeqNumN _ [] = True isMonoIncreasingAndHigherThanStartSeqNumN _ (MkStream (Start (MkFrameCtx () () sn ())) : rest) = isMonoIncreasingAndHigherThanStartSeqNumN sn rest isMonoIncreasingAndHigherThanStartSeqNumN sn (MkStream (Next (MkFrame () snFrame ())) : rest) | snFrame >= sn = isMonoIncreasingAndHigherThanStartSeqNumN snFrame rest | otherwise = False startFrame :: TestSeqNumType -> Stream () TestSeqNumType () () () startFrame sn = MkStream (Start (MkFrameCtx () () sn ())) nextFrame :: TestSeqNumType -> Stream () TestSeqNumType () () () nextFrame sn = MkStream (Next (MkFrame () sn ())) type TestSeqNumType = Word64
lindenbaum/mediabus
specs/Data/MediaBus/Conduit/ReorderSpec.hs
bsd-3-clause
6,102
0
23
2,520
1,516
761
755
161
2
module ANTs (computeRigid ,computeWarp ,applyTransforms ,upsample ) where -- import Software.ANTs (ANTs (..)) import Control.Monad.Extra (whenM) import Data.Maybe (fromMaybe) import Development.Shake (Action, CmdOption (AddEnv), cmd, liftIO, unit, withTempDir) import System.Directory as IO (doesDirectoryExist , copyFile , createDirectoryIfMissing) import System.Environment (lookupEnv) import System.FilePath ((</>)) import System.IO.Temp (withSystemTempDirectory, withSystemTempFile) import System.Process (callProcess) import qualified Teem (center, gzip, isNrrd) import Util (convertImage, maskImage, extractB0) import System.FilePath ((</>), (<.>),takeExtensions) import Data.Foldable (traverse_) import Control.Monad (when) getAnts :: FilePath -> IO FilePath getAnts "" = do envPath <- fmap (fromMaybe $ error "getAnts: ANTSPATH not set, set it or call function with a path") (lookupEnv "ANTSPATH") case envPath of "" -> error "getAnts: ANTSPATH is set to an empty path." _ -> getAnts envPath getAnts path = do whenM (not <$> IO.doesDirectoryExist path) (error $ "getAnts: the path " ++ path ++ " does not exist") return path -- TODO replace ANTS with newer antsRegistration computeRigid antspath moving fixed outtxt = withSystemTempDirectory "" $ \tmpdir -> do let pre = tmpdir </> "ants" affine = pre ++ "Affine.txt" callProcess (antspath </> "ANTS") ["3" ,"-m", "MI["++fixed++","++moving++",1,32]" ,"-i", "0", "-o", pre, "--do-rigid"] IO.copyFile affine outtxt computeWarp antspath moving fixed outwarp = withSystemTempDirectory "" $ \tmpdir -> do let pre = tmpdir </> "ants" affine = pre ++ "0GenericAffine.mat" warp = pre ++ "1Warp.nii.gz" -- antsRegistrationSyN uses MI for the Rigid and Affine stages, -- and CC with radius 4 for the non-linear BSplineSyN stage callProcess (antspath </> "antsRegistrationSyN.sh") ["-d", "3" ,"-f", fixed ,"-m", moving ,"-o", pre ,"-n", "16"] callProcess (antspath </> "ComposeMultiTransform") ["3", outwarp ,"-R", fixed, warp, affine] applyTransforms antspath interpolation transforms moving fixed out = callProcess (antspath </> "antsApplyTransforms") $ ["-d", "3" ,"-i", moving ,"-o", out ,"-r", fixed ,"-t"] ++ transforms ++ (if null interpolation then [] else ["--interpolation", interpolation]) upsample antspath spacings img out = callProcess (antspath </> "ResampleImageBySpacing") ["3", img, out, unwords . map show $ spacings] makeRigidMask antsPath mask moving fixed out = withSystemTempFile ".txt" $ \tmpxfm _ -> do withSystemTempFile ".nrrd" $ \tmpmask _ -> do withSystemTempFile ".nrrd" $ \tmpmoving _ -> do convertImage mask tmpmask convertImage moving tmpmoving traverse_ Teem.center [tmpmask, tmpmoving] computeRigid antsPath tmpmoving fixed tmpxfm applyTransforms antsPath "NearestNeighbor" [tmpxfm] tmpmask fixed out when (Teem.isNrrd out) (Teem.gzip out) freesurferToDwi :: FilePath -> FilePath -> FilePath -> FilePath -> FilePath -> FilePath -> Action () freesurferToDwi antsPath mridir bse t1 t2 outdir = do liftIO $ createDirectoryIfMissing True outdir fshome <- liftIO $ fromMaybe (error "freesurferToDwi: Set FREESURFER_HOME") <$> lookupEnv "FREESURFER_HOME" let brain = outdir </> "brain.nii.gz" wmparc = outdir </> "wmparc.nii.gz" bse = outdir </> "bse" <.> (takeExtensions bse) -- TODO constrain to nrrd/nii fsToT1_rigid = outdir </> "fsToT1-rigid.txt" t1ToT2_rigid = outdir </> "t1ToT2-rigid.txt" t2ToDwi_warp = outdir </> "t2ToDwi-warp.nii.gz" wmparcInDwi = outdir </> "wmparc-in-dwi" <.> (takeExtensions bse) -- TODO unit $ cmd (AddEnv "SUBJECTS_DIR" "") (fshome </> "bin" </> "mri_vol2vol") ["--mov", mridir </> "brain.mgz" ,"--targ", mridir </> "brain.mgz" ,"--regheader" ,"--o", brain] unit $ cmd (AddEnv "SUBJECTS_DIR" "") (fshome </> "bin" </> "mri_label2vol") ["--seg", mridir </> "wmparc.mgz" ,"--temp", mridir </> "brain.mgz" ,"--regheader", mridir </> "wmparc.mgz" ,"--o", wmparc] -- Make upsampled DWI b0 liftIO $ upsample antsPath [1,1,1] bse bse liftIO $ computeRigid antsPath brain t1 fsToT1_rigid liftIO $ computeRigid antsPath t1 t2 t1ToT2_rigid liftIO $ computeWarp antsPath t2 bse t2ToDwi_warp liftIO $ applyTransforms antsPath "NearestNeighbor" [t2ToDwi_warp, t1ToT2_rigid, fsToT1_rigid] wmparc bse wmparcInDwi unit $ cmd "ConvertBetweenFileFormats" [wmparcInDwi, wmparcInDwi, "short"] freesurferToDwiWithMasks antsPath mridir dwi dwimask t1 t1mask t2 t2mask outdir = withTempDir $ \tmpdir -> do let [bsemasked, t1masked, t2masked] = map (tmpdir </>) ["bsemasked.nii.gz" ,"t1masked.nii.gz" ,"t2masked.nii.gz"] liftIO $ Util.extractB0 dwi (tmpdir </> "bse.nii.gz") liftIO $ maskImage (tmpdir </> "bse.nii.gz") dwimask bsemasked liftIO $ maskImage t1 t1mask t1masked liftIO $ maskImage t2 t2mask t2masked freesurferToDwi antsPath mridir bsemasked t1masked t2masked outdir
pnlbwh/test-tensormasking
pipeline-lib/ANTs.hs
bsd-3-clause
5,763
0
20
1,615
1,455
773
682
114
2
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Language.Haskell.HGrep.Print ( printParseError , printSearchResult , printSearchResultLocation ) where import qualified Data.List as L import qualified Data.Map as Map import qualified Text.Printf as T import qualified Language.Haskell.GHC.ExactPrint as EP import qualified Language.Haskell.GHC.ExactPrint.Types as EP import qualified Language.Haskell.HsColour as HsColour import qualified Language.Haskell.HsColour.Colourise as HsColour import Language.Haskell.HGrep.Internal.Data import Language.Haskell.HGrep.Internal.Print import Language.Haskell.HGrep.Prelude import qualified SrcLoc printParseError :: ParseError -> [Char] printParseError ExactPrintException = "Parsing failed unexpectedly with an exception" printParseError (ExactPrintParseError (loc, msg)) = L.intercalate ": " [ unsafePpr loc , msg ] printSearchResult :: PrintOpts -> SearchResult -> [Char] printSearchResult (PrintOpts co lno) (SearchResult anns ast) = -- Get the start position of the comment before search result colorize $ case lno of PrintLineNums -> numberedSrc NoLineNums -> nonNumberedSrc where colorize :: [Char] -> [Char] colorize anySrc = case co of DefaultColours -> hscolour anySrc NoColours -> anySrc resSpan :: SrcLoc.SrcSpan resSpan = SrcLoc.getLoc ast isSameLoc :: EP.AnnKey -> Bool isSameLoc (EP.AnnKey loc _) = loc == resSpan -- Returns the line number if possible to find getSpanStartLine :: SrcLoc.SrcSpan -> Maybe Int getSpanStartLine someSpan = case SrcLoc.srcSpanStart someSpan of SrcLoc.RealSrcLoc x -> Just $ SrcLoc.srcLocLine x _ -> Nothing -- ignore empty lines before the actual result wholeSrc :: [Char] wholeSrc = EP.exactPrint ast anns nonEmptySrc :: [[Char]] (_, nonEmptySrc) = L.span null $ L.lines wholeSrc nonNumberedSrc = L.unlines nonEmptySrc -- Doesn't prepent locations when there is no start line number printWithLineNums :: Maybe Int -> [Char] printWithLineNums Nothing = nonNumberedSrc printWithLineNums (Just start) = L.unlines $ L.zipWith prependLineNum [start..] nonEmptySrc annsPairs = Map.toList anns targetAnnPairs = L.filter (isSameLoc .fst) annsPairs resLoc = getSpanStartLine resSpan startLineNum = case targetAnnPairs of [] -> resLoc ((_, ann) : _) -> case EP.annPriorComments ann of [] -> resLoc ((comment, _) : _) -> getSpanStartLine $ EP.commentIdentifier comment numberedSrc = printWithLineNums startLineNum -- Adds line numbers at the start of each line prependLineNum :: Int -> [Char] -> [Char] prependLineNum i l = T.printf "%5d " i <> l printSearchResultLocation :: PrintOpts -> SearchResult -> [Char] printSearchResultLocation opts (SearchResult _anns ast) = printSrcSpan opts (SrcLoc.getLoc ast) hscolour :: [Char] -> [Char] hscolour = HsColour.hscolour HsColour.TTY HsColour.defaultColourPrefs False False "" False
thumphries/hgrep
src/Language/Haskell/HGrep/Print.hs
bsd-3-clause
3,231
1
15
764
761
424
337
70
7
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Web.RTBBidder.Protocol.Adx.BidRequest.AdSlot.MediationStatus (MediationStatus(..)) 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 MediationStatus = UNKNOWN | DIRECT_REQUEST deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic) instance P'.Mergeable MediationStatus instance Prelude'.Bounded MediationStatus where minBound = UNKNOWN maxBound = DIRECT_REQUEST instance P'.Default MediationStatus where defaultValue = UNKNOWN toMaybe'Enum :: Prelude'.Int -> P'.Maybe MediationStatus toMaybe'Enum 0 = Prelude'.Just UNKNOWN toMaybe'Enum 1 = Prelude'.Just DIRECT_REQUEST toMaybe'Enum _ = Prelude'.Nothing instance Prelude'.Enum MediationStatus where fromEnum UNKNOWN = 0 fromEnum DIRECT_REQUEST = 1 toEnum = P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Web.RTBBidder.Protocol.Adx.BidRequest.AdSlot.MediationStatus") . toMaybe'Enum succ UNKNOWN = DIRECT_REQUEST succ _ = Prelude'.error "hprotoc generated code: succ failure for type Web.RTBBidder.Protocol.Adx.BidRequest.AdSlot.MediationStatus" pred DIRECT_REQUEST = UNKNOWN pred _ = Prelude'.error "hprotoc generated code: pred failure for type Web.RTBBidder.Protocol.Adx.BidRequest.AdSlot.MediationStatus" instance P'.Wire MediationStatus 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 MediationStatus instance P'.MessageAPI msg' (msg' -> MediationStatus) MediationStatus where getVal m' f' = f' m' instance P'.ReflectEnum MediationStatus where reflectEnum = [(0, "UNKNOWN", UNKNOWN), (1, "DIRECT_REQUEST", DIRECT_REQUEST)] reflectEnumInfo _ = P'.EnumInfo (P'.makePNF (P'.pack ".Adx.BidRequest.AdSlot.MediationStatus") ["Web", "RTBBidder", "Protocol"] ["Adx", "BidRequest", "AdSlot"] "MediationStatus") ["Web", "RTBBidder", "Protocol", "Adx", "BidRequest", "AdSlot", "MediationStatus.hs"] [(0, "UNKNOWN"), (1, "DIRECT_REQUEST")] instance P'.TextType MediationStatus where tellT = P'.tellShow getT = P'.getRead
hiratara/hs-rtb-bidder
src/Web/RTBBidder/Protocol/Adx/BidRequest/AdSlot/MediationStatus.hs
bsd-3-clause
2,770
0
11
454
636
351
285
59
1
{-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} import Control.Arrow ((&&&)) import Text.Printf import qualified Animation as A import Control.IApplicative import Control.Monad (forM_) import Active import Diagrams.Backend.Rasterific import Diagrams.Prelude hiding (interval, simulate, ui, (->>), backwards, stretchTo, stretch, runActive, snapshot, movie, imap, Active, (<->), toDuration) type Anim f = A.Animation Double f Rasterific V2 Double -- Stuff to provide in a diagrams-specific animation module: -- fadeIn/fadeOut theAnim :: Anim F theAnim = movie [ triangleA # fadeIn 1 , circle 1 # fc red # lasting 1 <+> triangleA # lasting 2 , triangleA # fadeOut 1 ] where triangleA :: Diagram B triangleA = fromOffsets [unitX, unitY] # closeTrail # stroke fadeIn d a = opacity <$> ((/d) <$> interval 0 d) <:*> ipure a fadeOut d a = active (toDuration d) (\t -> a # opacity (1 - t/d)) main :: IO () main = do let frames = simulate 25 (theAnim <-> always (square 5 # fc white # lw 0)) forM_ (zip [0 :: Int ..] frames) $ \(i,frame) -> do renderRasterific (printf "out/frame%03d.png" i) (mkWidth 400) frame
byorgey/new-active
src/old/Test2.hs
bsd-3-clause
1,444
0
17
445
430
236
194
30
1
module Main where import Why3.AsProcess main :: IO () main = do putStrLn $ show $ dischargeTheory Z3 "theory X goal a: forall a:int. a = a end"
cavi-art/why3-hs
app/Main.hs
bsd-3-clause
148
0
8
32
40
21
19
5
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE DeriveDataTypeable, BangPatterns #-} -- | -- #name_types# -- GHC uses several kinds of name internally: -- -- * 'OccName.OccName' represents names as strings with just a little more information: -- the \"namespace\" that the name came from, e.g. the namespace of value, type constructors or -- data constructors -- -- * 'RdrName.RdrName': see "RdrName#name_types" -- -- * 'Name.Name': see "Name#name_types" -- -- * 'Id.Id': see "Id#name_types" -- -- * 'Var.Var': see "Var#name_types" module OccName ( -- * The 'NameSpace' type NameSpace, -- Abstract nameSpacesRelated, -- ** Construction -- $real_vs_source_data_constructors tcName, clsName, tcClsName, dataName, varName, tvName, srcDataName, -- ** Pretty Printing pprNameSpace, pprNonVarNameSpace, pprNameSpaceBrief, -- * The 'OccName' type OccName, -- Abstract, instance of Outputable pprOccName, -- ** Construction mkOccName, mkOccNameFS, mkVarOcc, mkVarOccFS, mkDataOcc, mkDataOccFS, mkTyVarOcc, mkTyVarOccFS, mkTcOcc, mkTcOccFS, mkClsOcc, mkClsOccFS, mkDFunOcc, setOccNameSpace, demoteOccName, HasOccName(..), -- ** Derived 'OccName's isDerivedOccName, mkDataConWrapperOcc, mkWorkerOcc, mkMatcherOcc, mkBuilderOcc, mkDefaultMethodOcc, mkNewTyCoOcc, mkClassOpAuxOcc, mkCon2TagOcc, mkTag2ConOcc, mkMaxTagOcc, mkClassDataConOcc, mkDictOcc, mkIPOcc, mkSpecOcc, mkForeignExportOcc, mkRepEqOcc, mkGenD, mkGenR, mkGen1R, mkGenRCo, mkGenC, mkGenS, mkDataTOcc, mkDataCOcc, mkDataConWorkerOcc, mkSuperDictSelOcc, mkSuperDictAuxOcc, mkLocalOcc, mkMethodOcc, mkInstTyTcOcc, mkInstTyCoOcc, mkEqPredCoOcc, mkVectOcc, mkVectTyConOcc, mkVectDataConOcc, mkVectIsoOcc, mkPDataTyConOcc, mkPDataDataConOcc, mkPDatasTyConOcc, mkPDatasDataConOcc, mkPReprTyConOcc, mkPADFunOcc, mkRecFldSelOcc, mkTyConRepOcc, -- ** Deconstruction occNameFS, occNameString, occNameSpace, isVarOcc, isTvOcc, isTcOcc, isDataOcc, isDataSymOcc, isSymOcc, isValOcc, parenSymOcc, startsWithUnderscore, isTcClsNameSpace, isTvNameSpace, isDataConNameSpace, isVarNameSpace, isValNameSpace, -- * The 'OccEnv' type OccEnv, emptyOccEnv, unitOccEnv, extendOccEnv, mapOccEnv, lookupOccEnv, mkOccEnv, mkOccEnv_C, extendOccEnvList, elemOccEnv, occEnvElts, foldOccEnv, plusOccEnv, plusOccEnv_C, extendOccEnv_C, extendOccEnv_Acc, filterOccEnv, delListFromOccEnv, delFromOccEnv, alterOccEnv, pprOccEnv, -- * The 'OccSet' type OccSet, emptyOccSet, unitOccSet, mkOccSet, extendOccSet, extendOccSetList, unionOccSets, unionManyOccSets, minusOccSet, elemOccSet, occSetElts, foldOccSet, isEmptyOccSet, intersectOccSet, intersectsOccSet, filterOccSet, -- * Tidying up TidyOccEnv, emptyTidyOccEnv, tidyOccName, initTidyOccEnv, -- FsEnv FastStringEnv, emptyFsEnv, lookupFsEnv, extendFsEnv, mkFsEnv ) where import Util import Unique import DynFlags import UniqFM import UniqSet import FastString import FastStringEnv import Outputable import Lexeme import Binary import Control.DeepSeq import Module import Data.Char import Data.Data {- ************************************************************************ * * \subsection{Name space} * * ************************************************************************ -} data NameSpace = VarName -- Variables, including "real" data constructors | DataName -- "Source" data constructors | TvName -- Type variables | TcClsName -- Type constructors and classes; Haskell has them -- in the same name space for now. deriving( Eq, Ord ) {-! derive: Binary !-} -- Note [Data Constructors] -- see also: Note [Data Constructor Naming] in DataCon.hs -- -- $real_vs_source_data_constructors -- There are two forms of data constructor: -- -- [Source data constructors] The data constructors mentioned in Haskell source code -- -- [Real data constructors] The data constructors of the representation type, which may not be the same as the source type -- -- For example: -- -- > data T = T !(Int, Int) -- -- The source datacon has type @(Int, Int) -> T@ -- The real datacon has type @Int -> Int -> T@ -- -- GHC chooses a representation based on the strictness etc. tcName, clsName, tcClsName :: NameSpace dataName, srcDataName :: NameSpace tvName, varName :: NameSpace -- Though type constructors and classes are in the same name space now, -- the NameSpace type is abstract, so we can easily separate them later tcName = TcClsName -- Type constructors clsName = TcClsName -- Classes tcClsName = TcClsName -- Not sure which! dataName = DataName srcDataName = DataName -- Haskell-source data constructors should be -- in the Data name space tvName = TvName varName = VarName isDataConNameSpace :: NameSpace -> Bool isDataConNameSpace DataName = True isDataConNameSpace _ = False isTcClsNameSpace :: NameSpace -> Bool isTcClsNameSpace TcClsName = True isTcClsNameSpace _ = False isTvNameSpace :: NameSpace -> Bool isTvNameSpace TvName = True isTvNameSpace _ = False isVarNameSpace :: NameSpace -> Bool -- Variables or type variables, but not constructors isVarNameSpace TvName = True isVarNameSpace VarName = True isVarNameSpace _ = False isValNameSpace :: NameSpace -> Bool isValNameSpace DataName = True isValNameSpace VarName = True isValNameSpace _ = False pprNameSpace :: NameSpace -> SDoc pprNameSpace DataName = text "data constructor" pprNameSpace VarName = text "variable" pprNameSpace TvName = text "type variable" pprNameSpace TcClsName = text "type constructor or class" pprNonVarNameSpace :: NameSpace -> SDoc pprNonVarNameSpace VarName = empty pprNonVarNameSpace ns = pprNameSpace ns pprNameSpaceBrief :: NameSpace -> SDoc pprNameSpaceBrief DataName = char 'd' pprNameSpaceBrief VarName = char 'v' pprNameSpaceBrief TvName = text "tv" pprNameSpaceBrief TcClsName = text "tc" -- demoteNameSpace lowers the NameSpace if possible. We can not know -- in advance, since a TvName can appear in an HsTyVar. -- See Note [Demotion] in RnEnv demoteNameSpace :: NameSpace -> Maybe NameSpace demoteNameSpace VarName = Nothing demoteNameSpace DataName = Nothing demoteNameSpace TvName = Nothing demoteNameSpace TcClsName = Just DataName {- ************************************************************************ * * \subsection[Name-pieces-datatypes]{The @OccName@ datatypes} * * ************************************************************************ -} data OccName = OccName { occNameSpace :: !NameSpace , occNameFS :: !FastString } deriving Typeable instance Eq OccName where (OccName sp1 s1) == (OccName sp2 s2) = s1 == s2 && sp1 == sp2 instance Ord OccName where -- Compares lexicographically, *not* by Unique of the string compare (OccName sp1 s1) (OccName sp2 s2) = (s1 `compare` s2) `thenCmp` (sp1 `compare` sp2) instance Data OccName where -- don't traverse? toConstr _ = abstractConstr "OccName" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "OccName" instance HasOccName OccName where occName = id instance NFData OccName where rnf x = x `seq` () {- ************************************************************************ * * \subsection{Printing} * * ************************************************************************ -} instance Outputable OccName where ppr = pprOccName instance OutputableBndr OccName where pprBndr _ = ppr pprInfixOcc n = pprInfixVar (isSymOcc n) (ppr n) pprPrefixOcc n = pprPrefixVar (isSymOcc n) (ppr n) pprOccName :: OccName -> SDoc pprOccName (OccName sp occ) = getPprStyle $ \ sty -> if codeStyle sty then ztext (zEncodeFS occ) else pp_occ <> pp_debug sty where pp_debug sty | debugStyle sty = braces (pprNameSpaceBrief sp) | otherwise = empty pp_occ = sdocWithDynFlags $ \dflags -> if gopt Opt_SuppressUniques dflags then text (strip_th_unique (unpackFS occ)) else ftext occ -- See Note [Suppressing uniques in OccNames] strip_th_unique ('[' : c : _) | isAlphaNum c = [] strip_th_unique (c : cs) = c : strip_th_unique cs strip_th_unique [] = [] {- Note [Suppressing uniques in OccNames] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This is a hack to de-wobblify the OccNames that contain uniques from Template Haskell that have been turned into a string in the OccName. See Note [Unique OccNames from Template Haskell] in Convert.hs ************************************************************************ * * \subsection{Construction} * * ************************************************************************ -} mkOccName :: NameSpace -> String -> OccName mkOccName occ_sp str = OccName occ_sp (mkFastString str) mkOccNameFS :: NameSpace -> FastString -> OccName mkOccNameFS occ_sp fs = OccName occ_sp fs mkVarOcc :: String -> OccName mkVarOcc s = mkOccName varName s mkVarOccFS :: FastString -> OccName mkVarOccFS fs = mkOccNameFS varName fs mkDataOcc :: String -> OccName mkDataOcc = mkOccName dataName mkDataOccFS :: FastString -> OccName mkDataOccFS = mkOccNameFS dataName mkTyVarOcc :: String -> OccName mkTyVarOcc = mkOccName tvName mkTyVarOccFS :: FastString -> OccName mkTyVarOccFS fs = mkOccNameFS tvName fs mkTcOcc :: String -> OccName mkTcOcc = mkOccName tcName mkTcOccFS :: FastString -> OccName mkTcOccFS = mkOccNameFS tcName mkClsOcc :: String -> OccName mkClsOcc = mkOccName clsName mkClsOccFS :: FastString -> OccName mkClsOccFS = mkOccNameFS clsName -- demoteOccName lowers the Namespace of OccName. -- see Note [Demotion] demoteOccName :: OccName -> Maybe OccName demoteOccName (OccName space name) = do space' <- demoteNameSpace space return $ OccName space' name -- Name spaces are related if there is a chance to mean the one when one writes -- the other, i.e. variables <-> data constructors and type variables <-> type constructors nameSpacesRelated :: NameSpace -> NameSpace -> Bool nameSpacesRelated ns1 ns2 = ns1 == ns2 || otherNameSpace ns1 == ns2 otherNameSpace :: NameSpace -> NameSpace otherNameSpace VarName = DataName otherNameSpace DataName = VarName otherNameSpace TvName = TcClsName otherNameSpace TcClsName = TvName {- | Other names in the compiler add additional information to an OccName. This class provides a consistent way to access the underlying OccName. -} class HasOccName name where occName :: name -> OccName {- ************************************************************************ * * Environments * * ************************************************************************ OccEnvs are used mainly for the envts in ModIfaces. Note [The Unique of an OccName] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ They are efficient, because FastStrings have unique Int# keys. We assume this key is less than 2^24, and indeed FastStrings are allocated keys sequentially starting at 0. So we can make a Unique using mkUnique ns key :: Unique where 'ns' is a Char representing the name space. This in turn makes it easy to build an OccEnv. -} instance Uniquable OccName where -- See Note [The Unique of an OccName] getUnique (OccName VarName fs) = mkVarOccUnique fs getUnique (OccName DataName fs) = mkDataOccUnique fs getUnique (OccName TvName fs) = mkTvOccUnique fs getUnique (OccName TcClsName fs) = mkTcOccUnique fs newtype OccEnv a = A (UniqFM a) deriving (Data, Typeable) emptyOccEnv :: OccEnv a unitOccEnv :: OccName -> a -> OccEnv a extendOccEnv :: OccEnv a -> OccName -> a -> OccEnv a extendOccEnvList :: OccEnv a -> [(OccName, a)] -> OccEnv a lookupOccEnv :: OccEnv a -> OccName -> Maybe a mkOccEnv :: [(OccName,a)] -> OccEnv a mkOccEnv_C :: (a -> a -> a) -> [(OccName,a)] -> OccEnv a elemOccEnv :: OccName -> OccEnv a -> Bool foldOccEnv :: (a -> b -> b) -> b -> OccEnv a -> b occEnvElts :: OccEnv a -> [a] extendOccEnv_C :: (a->a->a) -> OccEnv a -> OccName -> a -> OccEnv a extendOccEnv_Acc :: (a->b->b) -> (a->b) -> OccEnv b -> OccName -> a -> OccEnv b plusOccEnv :: OccEnv a -> OccEnv a -> OccEnv a plusOccEnv_C :: (a->a->a) -> OccEnv a -> OccEnv a -> OccEnv a mapOccEnv :: (a->b) -> OccEnv a -> OccEnv b delFromOccEnv :: OccEnv a -> OccName -> OccEnv a delListFromOccEnv :: OccEnv a -> [OccName] -> OccEnv a filterOccEnv :: (elt -> Bool) -> OccEnv elt -> OccEnv elt alterOccEnv :: (Maybe elt -> Maybe elt) -> OccEnv elt -> OccName -> OccEnv elt emptyOccEnv = A emptyUFM unitOccEnv x y = A $ unitUFM x y extendOccEnv (A x) y z = A $ addToUFM x y z extendOccEnvList (A x) l = A $ addListToUFM x l lookupOccEnv (A x) y = lookupUFM x y mkOccEnv l = A $ listToUFM l elemOccEnv x (A y) = elemUFM x y foldOccEnv a b (A c) = foldUFM a b c occEnvElts (A x) = eltsUFM x plusOccEnv (A x) (A y) = A $ plusUFM x y plusOccEnv_C f (A x) (A y) = A $ plusUFM_C f x y extendOccEnv_C f (A x) y z = A $ addToUFM_C f x y z extendOccEnv_Acc f g (A x) y z = A $ addToUFM_Acc f g x y z mapOccEnv f (A x) = A $ mapUFM f x mkOccEnv_C comb l = A $ addListToUFM_C comb emptyUFM l delFromOccEnv (A x) y = A $ delFromUFM x y delListFromOccEnv (A x) y = A $ delListFromUFM x y filterOccEnv x (A y) = A $ filterUFM x y alterOccEnv fn (A y) k = A $ alterUFM fn y k instance Outputable a => Outputable (OccEnv a) where ppr x = pprOccEnv ppr x pprOccEnv :: (a -> SDoc) -> OccEnv a -> SDoc pprOccEnv ppr_elt (A env) = pprUniqFM ppr_elt env type OccSet = UniqSet OccName emptyOccSet :: OccSet unitOccSet :: OccName -> OccSet mkOccSet :: [OccName] -> OccSet extendOccSet :: OccSet -> OccName -> OccSet extendOccSetList :: OccSet -> [OccName] -> OccSet unionOccSets :: OccSet -> OccSet -> OccSet unionManyOccSets :: [OccSet] -> OccSet minusOccSet :: OccSet -> OccSet -> OccSet elemOccSet :: OccName -> OccSet -> Bool occSetElts :: OccSet -> [OccName] foldOccSet :: (OccName -> b -> b) -> b -> OccSet -> b isEmptyOccSet :: OccSet -> Bool intersectOccSet :: OccSet -> OccSet -> OccSet intersectsOccSet :: OccSet -> OccSet -> Bool filterOccSet :: (OccName -> Bool) -> OccSet -> OccSet emptyOccSet = emptyUniqSet unitOccSet = unitUniqSet mkOccSet = mkUniqSet extendOccSet = addOneToUniqSet extendOccSetList = addListToUniqSet unionOccSets = unionUniqSets unionManyOccSets = unionManyUniqSets minusOccSet = minusUniqSet elemOccSet = elementOfUniqSet occSetElts = uniqSetToList foldOccSet = foldUniqSet isEmptyOccSet = isEmptyUniqSet intersectOccSet = intersectUniqSets intersectsOccSet s1 s2 = not (isEmptyOccSet (s1 `intersectOccSet` s2)) filterOccSet = filterUniqSet {- ************************************************************************ * * \subsection{Predicates and taking them apart} * * ************************************************************************ -} occNameString :: OccName -> String occNameString (OccName _ s) = unpackFS s setOccNameSpace :: NameSpace -> OccName -> OccName setOccNameSpace sp (OccName _ occ) = OccName sp occ isVarOcc, isTvOcc, isTcOcc, isDataOcc :: OccName -> Bool isVarOcc (OccName VarName _) = True isVarOcc _ = False isTvOcc (OccName TvName _) = True isTvOcc _ = False isTcOcc (OccName TcClsName _) = True isTcOcc _ = False -- | /Value/ 'OccNames's are those that are either in -- the variable or data constructor namespaces isValOcc :: OccName -> Bool isValOcc (OccName VarName _) = True isValOcc (OccName DataName _) = True isValOcc _ = False isDataOcc (OccName DataName _) = True isDataOcc _ = False -- | Test if the 'OccName' is a data constructor that starts with -- a symbol (e.g. @:@, or @[]@) isDataSymOcc :: OccName -> Bool isDataSymOcc (OccName DataName s) = isLexConSym s isDataSymOcc _ = False -- Pretty inefficient! -- | Test if the 'OccName' is that for any operator (whether -- it is a data constructor or variable or whatever) isSymOcc :: OccName -> Bool isSymOcc (OccName DataName s) = isLexConSym s isSymOcc (OccName TcClsName s) = isLexSym s isSymOcc (OccName VarName s) = isLexSym s isSymOcc (OccName TvName s) = isLexSym s -- Pretty inefficient! parenSymOcc :: OccName -> SDoc -> SDoc -- ^ Wrap parens around an operator parenSymOcc occ doc | isSymOcc occ = parens doc | otherwise = doc startsWithUnderscore :: OccName -> Bool -- ^ Haskell 98 encourages compilers to suppress warnings about unsed -- names in a pattern if they start with @_@: this implements that test startsWithUnderscore occ = case occNameString occ of ('_' : _) -> True _other -> False {- ************************************************************************ * * \subsection{Making system names} * * ************************************************************************ Here's our convention for splitting up the interface file name space: d... dictionary identifiers (local variables, so no name-clash worries) All of these other OccNames contain a mixture of alphabetic and symbolic characters, and hence cannot possibly clash with a user-written type or function name $f... Dict-fun identifiers (from inst decls) $dmop Default method for 'op' $pnC n'th superclass selector for class C $wf Worker for functtoin 'f' $sf.. Specialised version of f D:C Data constructor for dictionary for class C NTCo:T Coercion connecting newtype T with its representation type TFCo:R Coercion connecting a data family to its representation type R In encoded form these appear as Zdfxxx etc :... keywords (export:, letrec: etc.) --- I THINK THIS IS WRONG! This knowledge is encoded in the following functions. @mk_deriv@ generates an @OccName@ from the prefix and a string. NB: The string must already be encoded! -} mk_deriv :: NameSpace -> String -- Distinguishes one sort of derived name from another -> String -> OccName mk_deriv occ_sp sys_prefix str = mkOccName occ_sp (sys_prefix ++ str) isDerivedOccName :: OccName -> Bool -- ^ Test for definitions internally generated by GHC. This predicte -- is used to suppress printing of internal definitions in some debug prints isDerivedOccName occ = case occNameString occ of '$':c:_ | isAlphaNum c -> True -- E.g. $wfoo c:':':_ | isAlphaNum c -> True -- E.g. N:blah newtype coercions _other -> False mkDataConWrapperOcc, mkWorkerOcc, mkMatcherOcc, mkBuilderOcc, mkDefaultMethodOcc, mkClassDataConOcc, mkDictOcc, mkIPOcc, mkSpecOcc, mkForeignExportOcc, mkRepEqOcc, mkGenR, mkGen1R, mkGenRCo, mkDataTOcc, mkDataCOcc, mkDataConWorkerOcc, mkNewTyCoOcc, mkInstTyCoOcc, mkEqPredCoOcc, mkClassOpAuxOcc, mkCon2TagOcc, mkTag2ConOcc, mkMaxTagOcc, mkTyConRepOcc :: OccName -> OccName -- These derived variables have a prefix that no Haskell value could have mkDataConWrapperOcc = mk_simple_deriv varName "$W" mkWorkerOcc = mk_simple_deriv varName "$w" mkMatcherOcc = mk_simple_deriv varName "$m" mkBuilderOcc = mk_simple_deriv varName "$b" mkDefaultMethodOcc = mk_simple_deriv varName "$dm" mkClassOpAuxOcc = mk_simple_deriv varName "$c" mkDictOcc = mk_simple_deriv varName "$d" mkIPOcc = mk_simple_deriv varName "$i" mkSpecOcc = mk_simple_deriv varName "$s" mkForeignExportOcc = mk_simple_deriv varName "$f" mkRepEqOcc = mk_simple_deriv tvName "$r" -- In RULES involving Coercible mkClassDataConOcc = mk_simple_deriv dataName "C:" -- Data con for a class mkNewTyCoOcc = mk_simple_deriv tcName "N:" -- Coercion for newtypes mkInstTyCoOcc = mk_simple_deriv tcName "D:" -- Coercion for type functions mkEqPredCoOcc = mk_simple_deriv tcName "$co" -- Used in derived instances mkCon2TagOcc = mk_simple_deriv varName "$con2tag_" mkTag2ConOcc = mk_simple_deriv varName "$tag2con_" mkMaxTagOcc = mk_simple_deriv varName "$maxtag_" -- TyConRepName stuff; see Note [Grand plan for Typeable] in TcTypeable mkTyConRepOcc occ = mk_simple_deriv varName prefix occ where prefix | isDataOcc occ = "$tc'" | otherwise = "$tc" -- Generic deriving mechanism -- | Generate a module-unique name, to be used e.g. while generating new names -- for Generics types. We use module unit id to avoid name clashes when -- package imports is used. mkModPrefix :: Module -> String mkModPrefix mod = pk ++ "_" ++ mn where pk = unitIdString (moduleUnitId mod) mn = moduleNameString (moduleName mod) mkGenD :: Module -> OccName -> OccName mkGenD mod = mk_simple_deriv tcName ("D1_" ++ mkModPrefix mod ++ "_") mkGenC :: Module -> OccName -> Int -> OccName mkGenC mod occ m = mk_deriv tcName ("C1_" ++ show m) $ mkModPrefix mod ++ "_" ++ occNameString occ mkGenS :: Module -> OccName -> Int -> Int -> OccName mkGenS mod occ m n = mk_deriv tcName ("S1_" ++ show m ++ "_" ++ show n) $ mkModPrefix mod ++ "_" ++ occNameString occ mkGenR = mk_simple_deriv tcName "Rep_" mkGen1R = mk_simple_deriv tcName "Rep1_" mkGenRCo = mk_simple_deriv tcName "CoRep_" -- data T = MkT ... deriving( Data ) needs definitions for -- $tT :: Data.Generics.Basics.DataType -- $cMkT :: Data.Generics.Basics.Constr mkDataTOcc = mk_simple_deriv varName "$t" mkDataCOcc = mk_simple_deriv varName "$c" -- Vectorisation mkVectOcc, mkVectTyConOcc, mkVectDataConOcc, mkVectIsoOcc, mkPADFunOcc, mkPReprTyConOcc, mkPDataTyConOcc, mkPDataDataConOcc, mkPDatasTyConOcc, mkPDatasDataConOcc :: Maybe String -> OccName -> OccName mkVectOcc = mk_simple_deriv_with varName "$v" mkVectTyConOcc = mk_simple_deriv_with tcName "V:" mkVectDataConOcc = mk_simple_deriv_with dataName "VD:" mkVectIsoOcc = mk_simple_deriv_with varName "$vi" mkPADFunOcc = mk_simple_deriv_with varName "$pa" mkPReprTyConOcc = mk_simple_deriv_with tcName "VR:" mkPDataTyConOcc = mk_simple_deriv_with tcName "VP:" mkPDatasTyConOcc = mk_simple_deriv_with tcName "VPs:" mkPDataDataConOcc = mk_simple_deriv_with dataName "VPD:" mkPDatasDataConOcc = mk_simple_deriv_with dataName "VPDs:" -- Overloaded record field selectors mkRecFldSelOcc :: String -> OccName mkRecFldSelOcc = mk_deriv varName "$sel" mk_simple_deriv :: NameSpace -> String -> OccName -> OccName mk_simple_deriv sp px occ = mk_deriv sp px (occNameString occ) mk_simple_deriv_with :: NameSpace -> String -> Maybe String -> OccName -> OccName mk_simple_deriv_with sp px Nothing occ = mk_deriv sp px (occNameString occ) mk_simple_deriv_with sp px (Just with) occ = mk_deriv sp (px ++ with ++ "_") (occNameString occ) -- Data constructor workers are made by setting the name space -- of the data constructor OccName (which should be a DataName) -- to VarName mkDataConWorkerOcc datacon_occ = setOccNameSpace varName datacon_occ mkSuperDictAuxOcc :: Int -> OccName -> OccName mkSuperDictAuxOcc index cls_tc_occ = mk_deriv varName "$cp" (show index ++ occNameString cls_tc_occ) mkSuperDictSelOcc :: Int -- ^ Index of superclass, e.g. 3 -> OccName -- ^ Class, e.g. @Ord@ -> OccName -- ^ Derived 'Occname', e.g. @$p3Ord@ mkSuperDictSelOcc index cls_tc_occ = mk_deriv varName "$p" (show index ++ occNameString cls_tc_occ) mkLocalOcc :: Unique -- ^ Unique to combine with the 'OccName' -> OccName -- ^ Local name, e.g. @sat@ -> OccName -- ^ Nice unique version, e.g. @$L23sat@ mkLocalOcc uniq occ = mk_deriv varName ("$L" ++ show uniq) (occNameString occ) -- The Unique might print with characters -- that need encoding (e.g. 'z'!) -- | Derive a name for the representation type constructor of a -- @data@\/@newtype@ instance. mkInstTyTcOcc :: String -- ^ Family name, e.g. @Map@ -> OccSet -- ^ avoid these Occs -> OccName -- ^ @R:Map@ mkInstTyTcOcc str set = chooseUniqueOcc tcName ('R' : ':' : str) set mkDFunOcc :: String -- ^ Typically the class and type glommed together e.g. @OrdMaybe@. -- Only used in debug mode, for extra clarity -> Bool -- ^ Is this a hs-boot instance DFun? -> OccSet -- ^ avoid these Occs -> OccName -- ^ E.g. @$f3OrdMaybe@ -- In hs-boot files we make dict funs like $fx7ClsTy, which get bound to the real -- thing when we compile the mother module. Reason: we don't know exactly -- what the mother module will call it. mkDFunOcc info_str is_boot set = chooseUniqueOcc VarName (prefix ++ info_str) set where prefix | is_boot = "$fx" | otherwise = "$f" {- Sometimes we need to pick an OccName that has not already been used, given a set of in-use OccNames. -} chooseUniqueOcc :: NameSpace -> String -> OccSet -> OccName chooseUniqueOcc ns str set = loop (mkOccName ns str) (0::Int) where loop occ n | occ `elemOccSet` set = loop (mkOccName ns (str ++ show n)) (n+1) | otherwise = occ {- We used to add a '$m' to indicate a method, but that gives rise to bad error messages from the type checker when we print the function name or pattern of an instance-decl binding. Why? Because the binding is zapped to use the method name in place of the selector name. (See TcClassDcl.tcMethodBind) The way it is now, -ddump-xx output may look confusing, but you can always say -dppr-debug to get the uniques. However, we *do* have to zap the first character to be lower case, because overloaded constructors (blarg) generate methods too. And convert to VarName space e.g. a call to constructor MkFoo where data (Ord a) => Foo a = MkFoo a If this is necessary, we do it by prefixing '$m'. These guys never show up in error messages. What a hack. -} mkMethodOcc :: OccName -> OccName mkMethodOcc occ@(OccName VarName _) = occ mkMethodOcc occ = mk_simple_deriv varName "$m" occ {- ************************************************************************ * * \subsection{Tidying them up} * * ************************************************************************ Before we print chunks of code we like to rename it so that we don't have to print lots of silly uniques in it. But we mustn't accidentally introduce name clashes! So the idea is that we leave the OccName alone unless it accidentally clashes with one that is already in scope; if so, we tack on '1' at the end and try again, then '2', and so on till we find a unique one. There's a wrinkle for operators. Consider '>>='. We can't use '>>=1' because that isn't a single lexeme. So we encode it to 'lle' and *then* tack on the '1', if necessary. Note [TidyOccEnv] ~~~~~~~~~~~~~~~~~ type TidyOccEnv = UniqFM Int * Domain = The OccName's FastString. These FastStrings are "taken"; make sure that we don't re-use * Int, n = A plausible starting point for new guesses There is no guarantee that "FSn" is available; you must look that up in the TidyOccEnv. But it's a good place to start looking. * When looking for a renaming for "foo2" we strip off the "2" and start with "foo". Otherwise if we tidy twice we get silly names like foo23. However, if it started with digits at the end, we always make a name with digits at the end, rather than shortening "foo2" to just "foo", even if "foo" is unused. Reasons: - Plain "foo" might be used later - We use trailing digits to subtly indicate a unification variable in typechecker error message; see TypeRep.tidyTyVarBndr We have to take care though! Consider a machine-generated module (Trac #10370) module Foo where a1 = e1 a2 = e2 ... a2000 = e2000 Then "a1", "a2" etc are all marked taken. But now if we come across "a7" again, we have to do a linear search to find a free one, "a2001". That might just be acceptable once. But if we now come across "a8" again, we don't want to repeat that search. So we use the TidyOccEnv mapping for "a" (not "a7" or "a8") as our base for starting the search; and we make sure to update the starting point for "a" after we allocate a new one. -} type TidyOccEnv = UniqFM Int -- The in-scope OccNames -- See Note [TidyOccEnv] emptyTidyOccEnv :: TidyOccEnv emptyTidyOccEnv = emptyUFM initTidyOccEnv :: [OccName] -> TidyOccEnv -- Initialise with names to avoid! initTidyOccEnv = foldl add emptyUFM where add env (OccName _ fs) = addToUFM env fs 1 tidyOccName :: TidyOccEnv -> OccName -> (TidyOccEnv, OccName) tidyOccName env occ@(OccName occ_sp fs) = case lookupUFM env fs of Nothing -> (addToUFM env fs 1, occ) -- Desired OccName is free Just {} -> case lookupUFM env base1 of Nothing -> (addToUFM env base1 2, OccName occ_sp base1) Just n -> find 1 n where base :: String -- Drop trailing digits (see Note [TidyOccEnv]) base = dropWhileEndLE isDigit (unpackFS fs) base1 = mkFastString (base ++ "1") find !k !n = case lookupUFM env new_fs of Just {} -> find (k+1 :: Int) (n+k) -- By using n+k, the n argument to find goes -- 1, add 1, add 2, add 3, etc which -- moves at quadratic speed through a dense patch Nothing -> (new_env, OccName occ_sp new_fs) where new_fs = mkFastString (base ++ show n) new_env = addToUFM (addToUFM env new_fs 1) base1 (n+1) -- Update: base1, so that next time we'll start where we left off -- new_fs, so that we know it is taken -- If they are the same (n==1), the former wins -- See Note [TidyOccEnv] {- ************************************************************************ * * Binary instance Here rather than BinIface because OccName is abstract * * ************************************************************************ -} instance Binary NameSpace where put_ bh VarName = do putByte bh 0 put_ bh DataName = do putByte bh 1 put_ bh TvName = do putByte bh 2 put_ bh TcClsName = do putByte bh 3 get bh = do h <- getByte bh case h of 0 -> do return VarName 1 -> do return DataName 2 -> do return TvName _ -> do return TcClsName instance Binary OccName where put_ bh (OccName aa ab) = do put_ bh aa put_ bh ab get bh = do aa <- get bh ab <- get bh return (OccName aa ab)
GaloisInc/halvm-ghc
compiler/basicTypes/OccName.hs
bsd-3-clause
33,071
0
14
8,804
5,768
3,082
2,686
475
5
module GameData.Star where import qualified Gamgine.Math.Vect as V import qualified Gamgine.Math.Box as B import qualified GameData.Entity as E newStar :: Int -> V.Vect -> E.Entity newStar id pos = E.Star { E.starId = id, E.starPosition = pos, E.starBound = starBound starSize, E.starCollected = False } starSize :: (Double, Double) starSize = (1.5, 1.5) starBound :: (Double, Double) -> B.Box starBound (x, y) = B.Box (V.v3 0 0 0) (V.v3 x y 0)
dan-t/layers
src/GameData/Star.hs
bsd-3-clause
479
0
8
106
182
108
74
14
1
module Data.TTask.Types ( module Data.TTask.Types.Types , module Data.TTask.Types.Lens , module Data.TTask.Types.Class ) where import Data.TTask.Types.Types import Data.TTask.Types.Lens import Data.TTask.Types.Class
tokiwoousaka/ttask
src/Data/TTask/Types.hs
bsd-3-clause
225
0
5
28
54
39
15
7
0
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} module QuakeState ( QuakeState(..) , initialQuakeState , globals , comGlobals , cmdGlobals , keyGlobals , fsGlobals , svGlobals , gameBaseGlobals , pMoveGlobals , scrGlobals , netGlobals , cmGlobals , gameItemsGlobals , mBerserkGlobals , mBoss2Globals , mBoss31Globals , mBoss32Globals , mBrainGlobals , mChickGlobals , mFlipperGlobals , mFloatGlobals , mFlyerGlobals , mGladiatorGlobals , mGunnerGlobals , mHoverGlobals , mInfantryGlobals , mInsaneGlobals , mMedicGlobals , mMutantGlobals , mParasiteGlobals , mSoldierGlobals , mSuperTankGlobals , mTankGlobals , playerTrailGlobals , vidGlobals , inGlobals , glfwbGlobals , kbdGlobals , basicRenderAPIGlobals , fastRenderAPIGlobals , particleTGlobals , menuGlobals , clientGlobals , vGlobals , netChannelGlobals , clTEntGlobals , worldRef , GItemReference(..) , UserCmdReference(..) , GLPolyReference(..) , MTexInfoReference(..) , MNodeReference(..) , SfxReference(..) , MNodeChild(..) , ModelExtra(..) , EntThinkAdapter(..) , EntBlockedAdapter(..) , EntDodgeAdapter(..) , EntTouchAdapter(..) , EntUseAdapter(..) , EntPainAdapter(..) , EntInteractAdapter(..) , EntDieAdapter(..) , ItemUseAdapter(..) , ItemDropAdapter(..) , AIAdapter(..) , module Globals , module QCommon.CMGlobals , module QCommon.ComGlobals , module Game.CmdGlobals , module Client.ClientGlobals , module Client.CLTEntGlobals , module Client.KeyGlobals , module Client.MenuGlobals , module Client.ParticleTGlobals , module Client.SCRGlobals , module Client.VGlobals , module QCommon.FSGlobals , module Server.SVGlobals , module Game.GameBaseGlobals , module QCommon.PMoveGlobals , module Sys.KBDGlobals , module Sys.INGlobals , module Sys.NETGlobals , module Game.GameItemsGlobals , module Game.Monsters.MBerserkGlobals , module Game.Monsters.MBoss2Globals , module Game.Monsters.MBoss31Globals , module Game.Monsters.MBoss32Globals , module Game.Monsters.MBrainGlobals , module Game.Monsters.MChickGlobals , module Game.Monsters.MFlipperGlobals , module Game.Monsters.MFloatGlobals , module Game.Monsters.MFlyerGlobals , module Game.Monsters.MGladiatorGlobals , module Game.Monsters.MGunnerGlobals , module Game.Monsters.MHoverGlobals , module Game.Monsters.MInfantryGlobals , module Game.Monsters.MInsaneGlobals , module Game.Monsters.MMedicGlobals , module Game.Monsters.MMutantGlobals , module Game.Monsters.MParasiteGlobals , module Game.Monsters.MSoldierGlobals , module Game.Monsters.MSuperTankGlobals , module Game.Monsters.MTankGlobals , module Game.PlayerTrailGlobals , module Client.VIDGlobals , module Render.Basic.BasicRenderAPIGlobals , module Render.Fast.FastRenderAPIGlobals , module Render.GLFWbGlobals , module QCommon.NetChannelGlobals ) where import Control.Lens (use, makeLenses, ix, preuse, (%=), (.=)) import Control.Monad.State.Strict (liftIO) import qualified Data.Vector.Mutable as MV import Types import Globals import Client.ClientGlobals import Client.CLTEntGlobals import Client.KeyGlobals import Client.MenuGlobals import Client.ParticleTGlobals import Client.SCRGlobals import Client.VIDGlobals import Client.VGlobals import Game.CmdGlobals import Game.GameBaseGlobals import Game.GameItemsGlobals import Game.Monsters.MBerserkGlobals import Game.Monsters.MBoss2Globals import Game.Monsters.MBoss31Globals import Game.Monsters.MBoss32Globals import Game.Monsters.MBrainGlobals import Game.Monsters.MChickGlobals import Game.Monsters.MFlipperGlobals import Game.Monsters.MFloatGlobals import Game.Monsters.MFlyerGlobals import Game.Monsters.MGladiatorGlobals import Game.Monsters.MGunnerGlobals import Game.Monsters.MHoverGlobals import Game.Monsters.MInfantryGlobals import Game.Monsters.MInsaneGlobals import Game.Monsters.MMedicGlobals import Game.Monsters.MMutantGlobals import Game.Monsters.MParasiteGlobals import Game.Monsters.MSoldierGlobals import Game.Monsters.MSuperTankGlobals import Game.Monsters.MTankGlobals import Game.PlayerTrailGlobals import QCommon.CMGlobals import QCommon.ComGlobals import QCommon.FSGlobals import QCommon.NetChannelGlobals import QCommon.PMoveGlobals import Render.Basic.BasicRenderAPIGlobals import Render.Fast.FastRenderAPIGlobals import Render.GLFWbGlobals import Server.SVGlobals import Sys.KBDGlobals import Sys.INGlobals import Sys.NETGlobals makeLenses ''QuakeState initialQuakeState :: QuakeState initialQuakeState = QuakeState { _globals = initialGlobals , _comGlobals = initialComGlobals , _cmdGlobals = initialCmdGlobals , _keyGlobals = initialKeyGlobals , _fsGlobals = initialFSGlobals , _svGlobals = initialSVGlobals , _gameBaseGlobals = initialGameBaseGlobals , _pMoveGlobals = initialPMoveGlobals , _scrGlobals = initialSCRGlobals , _netGlobals = initialNETGlobals , _cmGlobals = initialCMGlobals , _gameItemsGlobals = initialGameItemsGlobals , _mBerserkGlobals = initialMBerserkGlobals , _mBoss2Globals = initialMBoss2Globals , _mBoss31Globals = initialMBoss31Globals , _mBoss32Globals = initialMBoss32Globals , _mBrainGlobals = initialMBrainGlobals , _mChickGlobals = initialMChickGlobals , _mFlipperGlobals = initialMFlipperGlobals , _mFloatGlobals = initialMFloatGlobals , _mFlyerGlobals = initialMFlyerGlobals , _mGladiatorGlobals = initialMGladiatorGlobals , _mGunnerGlobals = initialMGunnerGlobals , _mHoverGlobals = initialMHoverGlobals , _mInfantryGlobals = initialMInfantryGlobals , _mInsaneGlobals = initialMInsaneGlobals , _mMedicGlobals = initialMMedicGlobals , _mMutantGlobals = initialMMutantGlobals , _mParasiteGlobals = initialMParasiteGlobals , _mSoldierGlobals = initialMSoldierGlobals , _mSuperTankGlobals = initialMSuperTankGlobals , _mTankGlobals = initialMTankGlobals , _playerTrailGlobals = initialPlayerTrailGlobals , _vidGlobals = initialVIDGlobals , _inGlobals = initialINGlobals , _glfwbGlobals = initialGLFWbGlobals , _kbdGlobals = initialKBDGlobals , _basicRenderAPIGlobals = initialBasicRenderAPIGlobals , _fastRenderAPIGlobals = initialFastRenderAPIGlobals , _particleTGlobals = initialParticleTGlobals , _menuGlobals = initialMenuGlobals , _clientGlobals = initialClientGlobals , _vGlobals = initialVGlobals , _netChannelGlobals = initialNetChannelGlobals , _clTEntGlobals = initialCLTEntGlobals } worldRef :: Ref EdictT worldRef = Ref 0
ksaveljev/hake-2
src/QuakeState.hs
bsd-3-clause
9,223
0
6
3,553
1,184
793
391
214
1
{-# OPTIONS_GHC -Wall #-} module System.Console.ShSh.Builtins.Seq ( runSeq ) where import System.Console.ShSh.IO ( oPutStr ) import System.Console.ShSh.Shell ( Shell ) import System.Exit ( ExitCode(..) ) {-# NOINLINE runSeq #-} runSeq :: [String] -> Shell ExitCode runSeq args = do ns <- case args of [l] -> return [1 :: Int .. read l] [f,l] -> return [read f .. read l] [f,d,l] -> return [read f, read f + read d .. read l] _ -> fail "bad arguments!\nusage: seq [FIRST [INCREMENT]] LAST" oPutStr $ unlines $ map show ns return ExitSuccess
shicks/shsh
System/Console/ShSh/Builtins/Seq.hs
bsd-3-clause
657
0
14
209
213
116
97
14
4
{-| Module : IRTS.Compiler Description : Coordinates the compilation process. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE PatternGuards, TypeSynonymInstances, CPP #-} module IRTS.Compiler(compile, generate) where import IRTS.Lang import IRTS.LangOpts import IRTS.Defunctionalise import IRTS.Simplified import IRTS.CodegenCommon import IRTS.CodegenC import IRTS.DumpBC import IRTS.CodegenJavaScript import IRTS.Inliner import IRTS.Exports import IRTS.Portable import Idris.AbsSyntax import Idris.AbsSyntaxTree import Idris.ASTUtils import Idris.Erasure import Idris.Error import Idris.Output import Debug.Trace import Idris.Core.TT import Idris.Core.Evaluate import Idris.Core.CaseTree import Control.Category import Prelude hiding (id, (.)) import Control.Applicative import Control.Monad.State import Data.Maybe import Data.List import Data.Ord import Data.IntSet (IntSet) import qualified Data.IntSet as IS import qualified Data.Map as M import qualified Data.Set as S import System.Process import System.IO import System.Exit import System.Directory import System.Environment import System.FilePath ((</>), addTrailingPathSeparator) -- | Compile to simplified forms and return CodegenInfo compile :: Codegen -> FilePath -> Maybe Term -> Idris CodegenInfo compile codegen f mtm = do checkMVs -- check for undefined metavariables checkTotality -- refuse to compile if there are totality problems exports <- findExports let rootNames = case mtm of Nothing -> [] Just t -> freeNames t reachableNames <- performUsageAnalysis (rootNames ++ getExpNames exports) maindef <- case mtm of Nothing -> return [] Just tm -> do md <- irMain tm logCodeGen 1 $ "MAIN: " ++ show md return [(sMN 0 "runMain", md)] objs <- getObjectFiles codegen libs <- getLibs codegen flags <- getFlags codegen hdrs <- getHdrs codegen impdirs <- allImportDirs defsIn <- mkDecls reachableNames -- if no 'main term' given, generate interface files let iface = case mtm of Nothing -> True Just _ -> False let defs = defsIn ++ maindef -- Inlined top level LDecl made here let defsInlined = inlineAll defs let defsUniq = map (allocUnique (addAlist defsInlined emptyContext)) defsInlined let (nexttag, tagged) = addTags 65536 (liftAll defsUniq) let ctxtIn = addAlist tagged emptyContext logCodeGen 1 "Defunctionalising" let defuns_in = defunctionalise nexttag ctxtIn logCodeGen 5 $ show defuns_in logCodeGen 1 "Inlining" let defuns = inline defuns_in logCodeGen 5 $ show defuns logCodeGen 1 "Resolving variables for CG" let checked = simplifyDefs defuns (toAlist defuns) outty <- outputTy dumpCases <- getDumpCases dumpDefun <- getDumpDefun case dumpCases of Nothing -> return () Just f -> runIO $ writeFile f (showCaseTrees defs) case dumpDefun of Nothing -> return () Just f -> runIO $ writeFile f (dumpDefuns defuns) triple <- Idris.AbsSyntax.targetTriple cpu <- Idris.AbsSyntax.targetCPU logCodeGen 1 "Building output" case checked of OK c -> do return $ CodegenInfo f outty triple cpu hdrs impdirs objs libs flags NONE c (toAlist defuns) tagged iface exports Error e -> ierror e where checkMVs = do i <- getIState case map fst (idris_metavars i) \\ primDefs of [] -> return () ms -> do iputStrLn $ "WARNING: There are incomplete holes:\n " ++ show ms iputStrLn "\nEvaluation of any of these will crash at run time." return () checkTotality = do i <- getIState case idris_totcheckfail i of [] -> return () ((fc, msg):fs) -> ierror . At fc . Msg $ "Cannot compile:\n " ++ msg generate :: Codegen -> FilePath -> CodegenInfo -> IO () generate codegen mainmod ir = case codegen of -- Built-in code generators (FIXME: lift these out!) Via _ "c" -> codegenC ir -- Any external code generator Via fm cg -> do input <- case fm of IBCFormat -> return mainmod JSONFormat -> do tempdir <- getTemporaryDirectory (fn, h) <- openTempFile tempdir "idris-cg.json" writePortable h ir hClose h return fn let cmd = "idris-codegen-" ++ cg args = [input, "-o", outputFile ir] ++ compilerFlags ir exit <- rawSystem cmd args when (exit /= ExitSuccess) $ putStrLn ("FAILURE: " ++ show cmd ++ " " ++ show args) Bytecode -> dumpBC (simpleDecls ir) (outputFile ir) irMain :: TT Name -> Idris LDecl irMain tm = do i <- irTerm (sMN 0 "runMain") M.empty [] tm return $ LFun [] (sMN 0 "runMain") [] (LForce i) mkDecls :: [Name] -> Idris [(Name, LDecl)] mkDecls used = do i <- getIState let ds = filter (\(n, d) -> n `elem` used || isCon d) $ ctxtAlist (tt_ctxt i) decls <- mapM build ds return decls showCaseTrees :: [(Name, LDecl)] -> String showCaseTrees = showSep "\n\n" . map showCT . sortBy (comparing defnRank) where showCT (n, LFun _ f args lexp) = show n ++ " " ++ showSep " " (map show args) ++ " =\n\t" ++ show lexp showCT (n, LConstructor c t a) = "data " ++ show n ++ " " ++ show a defnRank :: (Name, LDecl) -> String defnRank (n, LFun _ _ _ _) = "1" ++ nameRank n defnRank (n, LConstructor _ _ _) = "2" ++ nameRank n nameRank :: Name -> String nameRank (UN s) = "1" ++ show s nameRank (MN i s) = "2" ++ show s ++ show i nameRank (NS n ns) = "3" ++ concatMap show (reverse ns) ++ nameRank n nameRank (SN sn) = "4" ++ snRank sn nameRank n = "5" ++ show n snRank :: SpecialName -> String snRank (WhereN i n n') = "1" ++ nameRank n' ++ nameRank n ++ show i snRank (InstanceN n args) = "2" ++ nameRank n ++ concatMap show args snRank (ParentN n s) = "3" ++ nameRank n ++ show s snRank (MethodN n) = "4" ++ nameRank n snRank (CaseN _ n) = "5" ++ nameRank n snRank (ElimN n) = "6" ++ nameRank n snRank (InstanceCtorN n) = "7" ++ nameRank n snRank (WithN i n) = "8" ++ nameRank n ++ show i isCon (TyDecl _ _) = True isCon _ = False build :: (Name, Def) -> Idris (Name, LDecl) build (n, d) = do i <- getIState case getPrim n i of Just (ar, op) -> let args = map (\x -> sMN x "op") [0..] in return (n, (LFun [] n (take ar args) (LOp op (map (LV . Glob) (take ar args))))) _ -> do def <- mkLDecl n d logCodeGen 3 $ "Compiled " ++ show n ++ " =\n\t" ++ show def return (n, def) where getPrim n i | Just (ar, op) <- lookup n (idris_scprims i) = Just (ar, op) | Just ar <- lookup n (S.toList (idris_externs i)) = Just (ar, LExternal n) getPrim n i = Nothing declArgs args inl n (LLam xs x) = declArgs (args ++ xs) inl n x declArgs args inl n x = LFun (if inl then [Inline] else []) n args x mkLDecl n (Function tm _) = declArgs [] True n <$> irTerm n M.empty [] tm mkLDecl n (CaseOp ci _ _ _ pats cd) = declArgs [] (case_inlinable ci || caseName n) n <$> irTree n args sc where (args, sc) = cases_runtime cd -- Always attempt to inline functions arising from 'case' expressions caseName (SN (CaseN _ _)) = True caseName (SN (WithN _ _)) = True caseName (NS n _) = caseName n caseName _ = False mkLDecl n (TyDecl (DCon tag arity _) _) = LConstructor n tag . length <$> fgetState (cg_usedpos . ist_callgraph n) mkLDecl n (TyDecl (TCon t a) _) = return $ LConstructor n (-1) a mkLDecl n _ = return $ (declArgs [] True n LNothing) -- postulate, never run data VarInfo = VI { viMethod :: Maybe Name } deriving Show type Vars = M.Map Name VarInfo irTerm :: Name -> Vars -> [Name] -> Term -> Idris LExp irTerm top vs env tm@(App _ f a) = do ist <- getIState case unApply tm of (P _ n _, args) | n `elem` map fst (idris_metavars ist) \\ primDefs -> return $ LError $ "ABORT: Attempt to evaluate hole " ++ show n (P _ (UN m) _, args) | m == txt "mkForeignPrim" -> doForeign vs env (reverse (drop 4 args)) -- drop implicits (P _ (UN u) _, [_, arg]) | u == txt "unsafePerformPrimIO" -> irTerm top vs env arg (P _ (UN u) _, _) | u == txt "assert_unreachable" -> return $ LError $ "ABORT: Reached an unreachable case in " ++ show top -- TMP HACK - until we get inlining. (P _ (UN r) _, [_, _, _, _, _, arg]) | r == txt "replace" -> irTerm top vs env arg -- 'void' doesn't have any pattern clauses and only gets called on -- erased things in higher order contexts (also a TMP HACK...) (P _ (UN r) _, _) | r == txt "void" -> return LNothing -- Laziness, the old way (P _ (UN l) _, [_, arg]) | l == txt "lazy" -> error "lazy has crept in somehow" (P _ (UN l) _, [_, arg]) | l == txt "force" -> LForce <$> irTerm top vs env arg -- Laziness, the new way (P _ (UN l) _, [_, _, arg]) | l == txt "Delay" -> LLazyExp <$> irTerm top vs env arg (P _ (UN l) _, [_, _, arg]) | l == txt "Force" -> LForce <$> irTerm top vs env arg (P _ (UN a) _, [_, _, _, arg]) | a == txt "assert_smaller" -> irTerm top vs env arg (P _ (UN a) _, [_, arg]) | a == txt "assert_total" -> irTerm top vs env arg (P _ (UN p) _, [_, arg]) | p == txt "par" -> do arg' <- irTerm top vs env arg return $ LOp LPar [LLazyExp arg'] (P _ (UN pf) _, [arg]) | pf == txt "prim_fork" -> do arg' <- irTerm top vs env arg return $ LOp LFork [LLazyExp arg'] (P _ (UN m) _, [_,size,t]) | m == txt "malloc" -> irTerm top vs env t (P _ (UN tm) _, [_,t]) | tm == txt "trace_malloc" -> irTerm top vs env t -- TODO -- This case is here until we get more general inlining. It's just -- a really common case, and the laziness hurts... (P _ (NS (UN be) [b,p]) _, [_,x,(App _ (App _ (App _ (P _ (UN d) _) _) _) t), (App _ (App _ (App _ (P _ (UN d') _) _) _) e)]) | be == txt "ifThenElse" , d == txt "Delay" , d' == txt "Delay" , b == txt "Bool" , p == txt "Prelude" -> do x' <- irTerm top vs env x t' <- irTerm top vs env t e' <- irTerm top vs env e return (LCase Shared x' [LConCase 0 (sNS (sUN "False") ["Bool","Prelude"]) [] e' ,LConCase 1 (sNS (sUN "True" ) ["Bool","Prelude"]) [] t' ]) -- data constructor (P (DCon t arity _) n _, args) -> do detag <- fgetState (opt_detaggable . ist_optimisation n) used <- map fst <$> fgetState (cg_usedpos . ist_callgraph n) let isNewtype = length used == 1 && detag let argsPruned = [a | (i,a) <- zip [0..] args, i `elem` used] -- The following code removes fields from data constructors -- and performs the newtype optimisation. -- -- The general rule here is: -- Everything we get as input is not touched by erasure, -- so it conforms to the official arities and types -- and we can reason about it like it's plain TT. -- -- It's only the data that leaves this point that's erased -- and possibly no longer typed as the original TT version. -- -- Especially, underapplied constructors must yield functions -- even if all the remaining arguments are erased -- (the resulting function *will* be applied, to NULLs). -- -- This will probably need rethinking when we get erasure from functions. -- "padLams" will wrap our term in LLam-bdas and give us -- the "list of future unerased args" coming from these lambdas. -- -- We can do whatever we like with the list of unerased args, -- hence it takes a lambda: \unerased_argname_list -> resulting_LExp. let padLams = padLambdas used (length args) arity case compare (length args) arity of -- overapplied GT -> ifail ("overapplied data constructor: " ++ show tm ++ "\nDEBUG INFO:\n" ++ "Arity: " ++ show arity ++ "\n" ++ "Arguments: " ++ show args ++ "\n" ++ "Pruned arguments: " ++ show argsPruned) -- exactly saturated EQ | isNewtype -> irTerm top vs env (head argsPruned) | otherwise -- not newtype, plain data ctor -> buildApp (LV $ Glob n) argsPruned -- not saturated, underapplied LT | isNewtype -- newtype , length argsPruned == 1 -- and we already have the value -> padLams . (\tm [] -> tm) -- the [] asserts there are no unerased args <$> irTerm top vs env (head argsPruned) | isNewtype -- newtype but the value is not among args yet -> return . padLams $ \[vn] -> LApp False (LV $ Glob n) [LV $ Glob vn] -- not a newtype, just apply to a constructor | otherwise -> padLams . applyToNames <$> buildApp (LV $ Glob n) argsPruned -- type constructor (P (TCon t a) n _, args) -> return LNothing -- an external name applied to arguments (P _ n _, args) | S.member (n, length args) (idris_externs ist) -> do LOp (LExternal n) <$> mapM (irTerm top vs env) args -- a name applied to arguments (P _ n _, args) -> do case lookup n (idris_scprims ist) of -- if it's a primitive that is already saturated, -- compile to the corresponding op here already to save work Just (arity, op) | length args == arity -> LOp op <$> mapM (irTerm top vs env) args -- otherwise, just apply the name _ -> applyName n ist args -- turn de bruijn vars into regular named references and try again (V i, args) -> irTerm top vs env $ mkApp (P Bound (env !! i) Erased) args (f, args) -> LApp False <$> irTerm top vs env f <*> mapM (irTerm top vs env) args where buildApp :: LExp -> [Term] -> Idris LExp buildApp e [] = return e buildApp e xs = LApp False e <$> mapM (irTerm top vs env) xs applyToNames :: LExp -> [Name] -> LExp applyToNames tm [] = tm applyToNames tm ns = LApp False tm $ map (LV . Glob) ns padLambdas :: [Int] -> Int -> Int -> ([Name] -> LExp) -> LExp padLambdas used startIdx endSIdx mkTerm = LLam allNames $ mkTerm nonerasedNames where allNames = [sMN i "sat" | i <- [startIdx .. endSIdx-1]] nonerasedNames = [sMN i "sat" | i <- [startIdx .. endSIdx-1], i `elem` used] applyName :: Name -> IState -> [Term] -> Idris LExp applyName n ist args = LApp False (LV $ Glob n) <$> mapM (irTerm top vs env . erase) (zip [0..] args) where erase (i, x) | i >= arity || i `elem` used = x | otherwise = Erased arity = case fst4 <$> lookupCtxtExact n (definitions . tt_ctxt $ ist) of Just (CaseOp ci ty tys def tot cdefs) -> length tys Just (TyDecl (DCon tag ar _) _) -> ar Just (TyDecl Ref ty) -> length $ getArgTys ty Just (Operator ty ar op) -> ar Just def -> error $ "unknown arity: " ++ show (n, def) Nothing -> 0 -- no definition, probably local name => can't erase anything -- name for purposes of usage info lookup uName | Just n' <- viMethod =<< M.lookup n vs = n' | otherwise = n used = maybe [] (map fst . usedpos) $ lookupCtxtExact uName (idris_callgraph ist) fst4 (x,_,_,_,_) = x irTerm top vs env (P _ n _) = return $ LV (Glob n) irTerm top vs env (V i) | i >= 0 && i < length env = return $ LV (Glob (env!!i)) | otherwise = ifail $ "bad de bruijn index: " ++ show i irTerm top vs env (Bind n (Lam _) sc) = LLam [n'] <$> irTerm top vs (n':env) sc where n' = uniqueName n env irTerm top vs env (Bind n (Let _ v) sc) = LLet n <$> irTerm top vs env v <*> irTerm top vs (n : env) sc irTerm top vs env (Bind _ _ _) = return $ LNothing irTerm top vs env (Proj t (-1)) = do t' <- irTerm top vs env t return $ LOp (LMinus (ATInt ITBig)) [t', LConst (BI 1)] irTerm top vs env (Proj t i) = LProj <$> irTerm top vs env t <*> pure i irTerm top vs env (Constant TheWorld) = return LNothing irTerm top vs env (Constant c) = return (LConst c) irTerm top vs env (TType _) = return LNothing irTerm top vs env Erased = return LNothing irTerm top vs env Impossible = return LNothing doForeign :: Vars -> [Name] -> [Term] -> Idris LExp doForeign vs env (ret : fname : world : args) = do args' <- mapM splitArg args let fname' = toFDesc fname let ret' = toFDesc ret return $ LForeign ret' fname' args' where splitArg tm | (_, [_,_,l,r]) <- unApply tm -- pair, two implicits = do let l' = toFDesc l r' <- irTerm (sMN 0 "__foreignCall") vs env r return (l', r') splitArg _ = ifail "Badly formed foreign function call" toFDesc (Constant (Str str)) = FStr str toFDesc tm | (P _ n _, []) <- unApply tm = FCon (deNS n) | (P _ n _, as) <- unApply tm = FApp (deNS n) (map toFDesc as) toFDesc _ = FUnknown deNS (NS n _) = n deNS n = n doForeign vs env xs = ifail "Badly formed foreign function call" irTree :: Name -> [Name] -> SC -> Idris LExp irTree top args tree = do logCodeGen 3 $ "Compiling " ++ show args ++ "\n" ++ show tree LLam args <$> irSC top M.empty tree irSC :: Name -> Vars -> SC -> Idris LExp irSC top vs (STerm t) = irTerm top vs [] t irSC top vs (UnmatchedCase str) = return $ LError str irSC top vs (ProjCase tm alts) = do tm' <- irTerm top vs [] tm alts' <- mapM (irAlt top vs tm') alts return $ LCase Shared tm' alts' -- Transform matching on Delay to applications of Force. irSC top vs (Case up n [ConCase (UN delay) i [_, _, n'] sc]) | delay == txt "Delay" = do sc' <- irSC top vs sc -- mkForce n' n sc return $ lsubst n' (LForce (LV (Glob n))) sc' -- There are two transformations in this case: -- -- 1. Newtype-case elimination: -- case {e0} of -- wrap({e1}) -> P({e1}) ==> P({e0}) -- -- This is important because newtyped constructors are compiled away entirely -- and we need to do that everywhere. -- -- 2. Unused-case elimination (only valid for singleton branches): -- case {e0} of ==> P -- C(x,y) -> P[... x,y not used ...] -- -- This is important for runtime because sometimes we case on irrelevant data: -- -- In the example above, {e0} will most probably have been erased -- so this vain projection would make the resulting program segfault -- because the code generator still emits a PROJECT(...) G-machine instruction. -- -- Hence, we check whether the variables are used at all -- and erase the casesplit if they are not. -- irSC top vs (Case up n [alt]) = do replacement <- case alt of ConCase cn a ns sc -> do detag <- fgetState (opt_detaggable . ist_optimisation cn) used <- map fst <$> fgetState (cg_usedpos . ist_callgraph cn) if detag && length used == 1 then return . Just $ substSC (ns !! head used) n sc else return Nothing _ -> return Nothing case replacement of Just sc -> irSC top vs sc _ -> do alt' <- irAlt top vs (LV (Glob n)) alt return $ case namesBoundIn alt' `usedIn` subexpr alt' of [] -> subexpr alt' -- strip the unused top-most case _ -> LCase up (LV (Glob n)) [alt'] where namesBoundIn :: LAlt -> [Name] namesBoundIn (LConCase cn i ns sc) = ns namesBoundIn (LConstCase c sc) = [] namesBoundIn (LDefaultCase sc) = [] subexpr :: LAlt -> LExp subexpr (LConCase _ _ _ e) = e subexpr (LConstCase _ e) = e subexpr (LDefaultCase e) = e -- FIXME: When we have a non-singleton case-tree of the form -- -- case {e0} of -- C(x) => ... -- ... => ... -- -- and C is detaggable (the only constructor of the family), we can be sure -- that the first branch will be always taken -- so we add special handling -- to remove the dead default branch. -- -- If we don't do so and C is newtype-optimisable, we will miss this newtype -- transformation and the resulting code will probably segfault. -- -- This work-around is not entirely optimal; the best approach would be -- to ensure that such case trees don't arise in the first place. -- irSC top vs (Case up n alts@[ConCase cn a ns sc, DefaultCase sc']) = do detag <- fgetState (opt_detaggable . ist_optimisation cn) if detag then irSC top vs (Case up n [ConCase cn a ns sc]) else LCase up (LV (Glob n)) <$> mapM (irAlt top vs (LV (Glob n))) alts irSC top vs sc@(Case up n alts) = do -- check that neither alternative needs the newtype optimisation, -- see comment above goneWrong <- or <$> mapM isDetaggable alts when goneWrong $ ifail ("irSC: non-trivial case-match on detaggable data: " ++ show sc) -- everything okay LCase up (LV (Glob n)) <$> mapM (irAlt top vs (LV (Glob n))) alts where isDetaggable (ConCase cn _ _ _) = fgetState $ opt_detaggable . ist_optimisation cn isDetaggable _ = return False irSC top vs ImpossibleCase = return LNothing irAlt :: Name -> Vars -> LExp -> CaseAlt -> Idris LAlt -- this leaves out all unused arguments of the constructor irAlt top vs _ (ConCase n t args sc) = do used <- map fst <$> fgetState (cg_usedpos . ist_callgraph n) let usedArgs = [a | (i,a) <- zip [0..] args, i `elem` used] LConCase (-1) n usedArgs <$> irSC top (methodVars `M.union` vs) sc where methodVars = case n of SN (InstanceCtorN className) -> M.fromList [(v, VI { viMethod = Just $ mkFieldName n i }) | (v,i) <- zip args [0..]] _ -> M.empty -- not an instance constructor irAlt top vs _ (ConstCase x rhs) | matchable x = LConstCase x <$> irSC top vs rhs | matchableTy x = LDefaultCase <$> irSC top vs rhs where matchable (I _) = True matchable (BI _) = True matchable (Ch _) = True matchable (Str _) = True matchable (B8 _) = True matchable (B16 _) = True matchable (B32 _) = True matchable (B64 _) = True matchable _ = False matchableTy (AType (ATInt ITNative)) = True matchableTy (AType (ATInt ITBig)) = True matchableTy (AType (ATInt ITChar)) = True matchableTy StrType = True matchableTy (AType (ATInt (ITFixed IT8))) = True matchableTy (AType (ATInt (ITFixed IT16))) = True matchableTy (AType (ATInt (ITFixed IT32))) = True matchableTy (AType (ATInt (ITFixed IT64))) = True matchableTy _ = False irAlt top vs tm (SucCase n rhs) = do rhs' <- irSC top vs rhs return $ LDefaultCase (LLet n (LOp (LMinus (ATInt ITBig)) [tm, LConst (BI 1)]) rhs') irAlt top vs _ (ConstCase c rhs) = ifail $ "Can't match on (" ++ show c ++ ")" irAlt top vs _ (DefaultCase rhs) = LDefaultCase <$> irSC top vs rhs
ozgurakgun/Idris-dev
src/IRTS/Compiler.hs
bsd-3-clause
25,108
0
27
8,568
8,405
4,160
4,245
462
33
---------------------------------------------------------------------- -- | -- Module : WBXML.WbxmlDefs -- Copyright : Mike Limansky, 2011 -- Licencse : BSD3 -- -- This module contains definition of different contstants defined in -- WBXML standard. -- ---------------------------------------------------------------------- module Wbxml.WbxmlDefs where import Data.Word (Word8) tokenSwitchPage = 0x0 tokenEnd = 0x1 tokenEntity = 0x2 tokenStrI = 0x3 tokenLiteral = 0x4 tokenExtI0 = 0x40 tokenExtI1 = 0x41 tokenExtI2 = 0x42 tokenPI = 0x43 tokenLiteralC = 0x44 tokenExtT0 = 0x80 tokenExtT1 = 0x81 tokenExtT2 = 0x82 tokenStrT = 0x83 tokenLiteralA = 0x84 tokenExt0 = 0xC0 tokenExt1 = 0xC1 tokenExt2 = 0xC2 tokenOpaque = 0xC3 tokenLiteralAc = 0xC4 controlTokens :: [ Word8 ] controlTokens = [ tokenSwitchPage, tokenEnd, tokenEntity, tokenStrI, tokenLiteral , tokenExtI0, tokenExtI1, tokenExtI2, tokenPI, tokenLiteralC , tokenExtT0, tokenExtT1, tokenExtT2, tokenStrT, tokenLiteralA , tokenExt0, tokenExt1, tokenExt2, tokenOpaque, tokenLiteralAc]
limansky/wbxml
src/Wbxml/WbxmlDefs.hs
bsd-3-clause
1,105
0
5
196
199
128
71
27
1
-- |Nettle with additional features. None of this code is Frenetic-specific. module Frenetic.NettleEx ( module Nettle.OpenFlow , module Nettle.Servers.Server , ethVLANId , ethVLANPcp , ethSrcIP , ethDstIP , ethProto , ethTOS , srcPort , dstPort ) where import Frenetic.Common import qualified Data.Map as Map import Nettle.OpenFlow hiding (intersect) import qualified Nettle.Servers.Server as Server import Nettle.Servers.Server import Nettle.Ethernet.EthernetFrame import Nettle.Ethernet.AddressResolutionProtocol import Prelude hiding (catch) import Control.Exception csMsgWithResponse :: CSMessage -> Bool csMsgWithResponse msg = case msg of CSHello -> True CSEchoRequest _ -> True FeaturesRequest -> True StatsRequest _ -> True BarrierRequest -> True GetQueueConfig _ -> True otherwise -> False hasMoreReplies :: SCMessage -> Bool hasMoreReplies msg = case msg of StatsReply (FlowStatsReply True _) -> True StatsReply (TableStatsReply True _) -> True StatsReply (PortStatsReply True _) -> True StatsReply (QueueStatsReply True _) -> True otherwise -> False ethVLANId :: EthernetHeader -> Maybe VLANID ethVLANId (Ethernet8021Q _ _ _ _ _ vlanId) = Just vlanId ethVLANId (EthernetHeader {}) = Nothing ethVLANPcp :: EthernetHeader -> VLANPriority ethVLANPcp (EthernetHeader _ _ _) = 0 ethVLANPcp (Ethernet8021Q _ _ _ pri _ _) = pri stripIP (IPAddress a) = a ethSrcIP (IPInEthernet (HCons hdr _)) = Just (stripIP (ipSrcAddress hdr)) ethSrcIP (ARPInEthernet (ARPQuery q)) = Just (stripIP (querySenderIPAddress q)) ethSrcIP (ARPInEthernet (ARPReply r)) = Just (stripIP (replySenderIPAddress r)) ethSrcIP (UninterpretedEthernetBody _) = Nothing ethDstIP (IPInEthernet (HCons hdr _)) = Just (stripIP (ipDstAddress hdr)) ethDstIP (ARPInEthernet (ARPQuery q)) = Just (stripIP (queryTargetIPAddress q)) ethDstIP (ARPInEthernet (ARPReply r)) = Just (stripIP (replyTargetIPAddress r)) ethDstIP (UninterpretedEthernetBody _) = Nothing ethProto (IPInEthernet (HCons hdr _)) = Just (ipProtocol hdr) ethProto (ARPInEthernet (ARPQuery _)) = Just 1 ethProto (ARPInEthernet (ARPReply _)) = Just 2 ethProto (UninterpretedEthernetBody _) = Nothing ethTOS (IPInEthernet (HCons hdr _)) = Just (dscp hdr) ethTOS _ = Just 0 srcPort (IPInEthernet (HCons _ (HCons pk _))) = case pk of TCPInIP (src, dst) -> Just src UDPInIP (src, dst) _ -> Just src ICMPInIP (typ, cod) -> Just (fromIntegral typ) UninterpretedIPBody _ -> Nothing srcPort _ = Nothing dstPort (IPInEthernet (HCons _ (HCons pk _))) = case pk of TCPInIP (src, dst) -> Just dst UDPInIP (src, dst) _ -> Just dst ICMPInIP (typ, cod) -> Just (fromIntegral cod) UninterpretedIPBody _ -> Nothing dstPort _ = Nothing
frenetic-lang/netcore-1.0
src/Frenetic/NettleEx.hs
bsd-3-clause
2,721
0
11
447
998
510
488
69
7
{-# LANGUAGE FlexibleContexts #-} module Main where import qualified Control.Monad.Trans.RSS.Lazy as RSSL import qualified Control.Monad.Trans.RSS.Strict as RSSS import qualified Control.Monad.Trans.RWS.Lazy as RWSL import qualified Control.Monad.Trans.RWS.Strict as RWSS import Criterion import Criterion.Main import qualified Data.Sequence as Seq import qualified Data.Vector.Primitive as VP import qualified Data.IntSet as IS import qualified Data.Set as S import qualified Data.DList as D import Control.Monad.RWS testActions :: (Monoid w, Monad m, MonadRWS () w Int m) => (Int -> m ()) -> m () testActions tellaction = do v <- get unless (v == 0) $ do put $! v - 1 when (v `mod` 11 == 0) $ tellaction v testActions tellaction benchlen :: Int benchlen = 10000 actions :: (Monoid w) => (Int -> w) -> [(String, Int -> ((), Int, w))] actions cnv = [ ("RSS.Lazy" , RSSL.runRSS (testActions (tell . cnv)) ()) , ("RSS.Strict", RSSS.runRSS (testActions (tell . cnv)) ()) , ("RWS.Lazy" , RWSL.runRWS (testActions (tell . cnv)) ()) , ("RWS.Strict", RWSS.runRWS (testActions (tell . cnv)) ()) ] main :: IO () main = defaultMain $ mkBench "Seq" Seq.singleton ++ mkBench "List" (:[]) ++ mkBench "Vector Primitive" VP.singleton ++ mkBench "IntSet" IS.singleton ++ mkBench "Set" S.singleton ++ mkBench "DList" D.singleton where mkBench n = map toBench . actions where toBench (n', a) = bench (n' ++ " [" ++ n ++ "]") $ nf a benchlen
bartavelle/stateWriter
bench/bench.hs
bsd-3-clause
1,652
0
14
452
570
321
249
37
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeFamilies #-} module EFA.Application.Optimisation.Loop where --import qualified Graphics.Gnuplot.Terminal.Default as DefaultTerm import qualified EFA.Application.Optimisation.Base as Base import qualified EFA.Application.Optimisation.NonIO as NonIO import qualified EFA.Application.Utility as AppUt -- import EFA.Equation.Result(Result(Determined)) import qualified EFA.Application.Type as Type import EFA.Application.Type (EnvResult) import qualified EFA.Application.Optimisation.Balance as Balance import qualified EFA.Application.Optimisation.Params as Params --import qualified EFA.Application.Optimisation.Sweep as Sweep import EFA.Application.Optimisation.Sweep (Sweep) import qualified EFA.Utility.List as UtList --import qualified EFA.Graph as Graph --import EFA.Graph (Graph) --import qualified EFA.Flow.Draw as Draws --import qualified EFA.Graph.Topology as Topology import qualified EFA.Graph.Topology.Node as Node import EFA.Equation.Arithmetic (Sign(Zero, Positive, Negative), (~*), (~/), (~+)) import qualified EFA.Equation.Arithmetic as Arith --import qualified Graphics.Gnuplot.Terminal as Terminal --import EFA.Equation.Result (Result(Determined)) --import qualified EFA.Flow.Topology as FlowTopo import qualified EFA.Application.Flow.State.SystemEta as StateEta --import qualified EFA.Flow.State.Quantity as StateQty --import qualified EFA.Flow.State as FlowState --import qualified EFA.Report.FormatValue as FormatValue -- import qualified EFA.Flow.State.Index as StateIdx --import qualified EFA.Flow.Topology.Index as TopoIdx import qualified EFA.Flow.Part.Index as Idx --import qualified EFA.Signal.Record as Record --import qualified EFA.Signal.Signal as Sig --import qualified EFA.Signal.Vector as SV --import EFA.Signal.Data (Data(Data)) --, Nil, Apply) --import EFA.Utility.List (vlast, vhead) --import EFA.Utility.Async (concurrentlyMany_) --import qualified Data.Monoid as Monoid import qualified Data.Map as Map; import Data.Map (Map) --import qualified Data.List as List import qualified Data.Vector.Unboxed as UV --import Data.Vector (Vector) --import Data.Maybe (fromMaybe) --import qualified Data.Set as Set --import qualified Data.Bimap as Bimap --import Data.Bimap (Bimap) import Data.Tuple.HT (thd3) import Text.Printf (printf, PrintfArg) --,IsChar) --import EFA.Utility.Trace (mytrace) --import Debug.Trace type Counter = Int data BalanceLoopItem node a z = BalanceLoopItem { bForcing :: Balance.Forcing node a, bFStep :: Balance.ForcingStep node a, balance :: Balance.Balance node a, bResult :: z } deriving (Show) data EtaLoopItem node sweep vec a z = EtaLoopItem { stateFlowIn :: EnvResult node ((sweep :: (* -> *) -> * -> *) vec a), sweep :: Type.Sweep node sweep vec a, balanceLoop :: [BalanceLoopItem node a z] } deriving (Show) data StateForceDemand = MoreForcingNeeded | CorrectForcing | NoForcingNeeded | LessForcingNeeded deriving (Show) checkBalance :: (Ord a, Arith.Sum a) => Params.Optimisation node list sweep vec a -> Balance.Balance node a -> Bool checkBalance optParams bal = Map.foldl' (\acc v -> acc && Arith.abs v <= bt) True bal where bt = Params.unBalanceThreshold (Params.balanceThreshold optParams) checkBalanceSingle :: (Ord a, Arith.Sum a, Ord node, Show node) => Params.Optimisation node list sweep vec a -> Balance.Balance node a -> node -> Bool checkBalanceSingle optParams bal sto = Arith.abs x <= Params.unBalanceThreshold (Params.balanceThreshold optParams) where x = Balance.getStorageBalance "checkBalanceSingle" bal sto -- | Rate Balance Deviation by sum of Standard Deviation and Overall Sum balanceDeviation :: (Arith.Product a, Ord a, Arith.Constant a, Arith.Sum a) => Balance.Balance node a -> a balanceDeviation m = Map.foldl (\acc x -> acc ~+ Arith.square x) Arith.zero m ~+ Arith.abs (Map.foldl (~+) Arith.zero m) ----------------------------------------------------------------- cond :: Int -> (a -> Bool) -> [a] -> [a] cond n p = take n . UtList.takeUntil p condEta :: Int -> (a -> Bool) -> [a] -> [a] condEta n p = take n . UtList.takeUntil p -- takeWhile (not . p) ----------------------------------------------------------------- balanceIterationInit :: (Ord a, Ord node, Show node, Show a, Arith.Constant a) => Params.Optimisation node [] Sweep UV.Vector a -> (Balance.Forcing node a -> z) -> (z -> Balance.Balance node a) -> Balance.Forcing node a -> Balance.ForcingStep node a -> ( Balance.Forcing node a, Balance.ForcingStep node a, [BalanceLoopItem node a z] ) balanceIterationInit optParams fsys accessf balForceIn balStepsIn = (balForceIn, balStepsIn, oioas) where oioas = oneIterationOfAllStorages optParams fsys accessf balForceIn balStepsIn balanceIterationAlgorithm :: (Ord a, Ord node, Show node, Show a, Arith.Constant a) => Params.Optimisation node [] Sweep UV.Vector a -> (Balance.Forcing node a -> z) -> (z -> Balance.Balance node a) -> ( Balance.Forcing node a, Balance.ForcingStep node a, [BalanceLoopItem node a z]) -> ( Balance.Forcing node a, Balance.ForcingStep node a, [BalanceLoopItem node a z] ) balanceIterationAlgorithm optParams fsys accessf (forcing, stepping, as) = (forcing1, stepping1, oioas) where oioas = oneIterationOfAllStorages optParams fsys accessf forcing stepping forcing1 = bForcing lastElem stepping1 = bFStep lastElem lastElem = AppUt.ifNull (error "balanceIteration: empty list") last as balanceIterationCondition :: Params.Optimisation node [] Sweep UV.Vector a -> (u, v, [BalanceLoopItem node a z]) -> (u, v, [BalanceLoopItem node a z]) balanceIterationCondition optParams (u, v, xs) = (u, v, cond maxBICnt bip xs) where maxBICnt = Params.unMaxBalanceIterations $ Params.maxBalanceIterations optParams bip _ = False balanceIteration :: (Ord a, Arith.Constant a,Ord node, Show node, Show a) => Params.Optimisation node [] Sweep UV.Vector a -> (Balance.Forcing node a -> z) -> (z -> Balance.Balance node a)-> Balance.Forcing node a -> Balance.ForcingStep node a -> [BalanceLoopItem node a z] balanceIteration optParams fsys accessf balForceIn balStepsIn = concat $ map thd3 $ iterate go bii where bii = balanceIterationCondition optParams $ balanceIterationInit optParams fsys accessf balForceIn balStepsIn go = balanceIterationCondition optParams . balanceIterationAlgorithm optParams fsys accessf ----------------------------------------------------------------- iterateOneStorageInit :: (Ord a2, Ord node, Show a2, Show node, Arith.Constant a2) => (Balance.Forcing node a2 -> z) -> (z -> Balance.Balance node a2) -> Balance.Forcing node a2 -> Balance.ForcingStep node a2 -> node -> ((Maybe a, Maybe a1), BalanceLoopItem node a2 z) iterateOneStorageInit fsys accessf forcingIn steppingIn sto = (initBestPair, BalanceLoopItem forcingIn initStep initBal initResult) where initResult = fsys forcingIn initBal = accessf initResult initBestPair = (Nothing, Nothing) initStep = steppingIn iterateOneStorageAlgorithm :: (Ord node, Ord a, Show node, Show a, Arith.Constant a) => (Balance.Forcing node a -> z) -> (z -> Balance.Balance node a) -> node -> ( (Maybe (Balance.SocDrive a, a), Maybe (Balance.SocDrive a, a)), BalanceLoopItem node a t) -> ( (Maybe (Balance.SocDrive a, a), Maybe (Balance.SocDrive a, a)), BalanceLoopItem node a z) iterateOneStorageAlgorithm fsys accessf sto (bestPair, BalanceLoopItem force step _ _) = (bestPair1, BalanceLoopItem force1 step1 bal1 res1) where force1 = Balance.addForcingStep force step sto res1 = fsys force1 bal1 = accessf res1 bestPair1 = Balance.rememberBestBalanceForcing bestPair (force1, bal1) sto step1 = calculateNextBalanceStep bal1 bestPair1 step sto iterateOneStorageCondition :: Params.Optimisation node [] Sweep UV.Vector a -> [BalanceLoopItem node a z] -> [BalanceLoopItem node a z] iterateOneStorageCondition optParams xs = cond cnt p xs where cnt = 100 p _ = False iterateOneStorage :: (Ord a, Arith.Constant a,Ord node, Show node, Show a) => Params.Optimisation node [] Sweep UV.Vector a -> (Balance.Forcing node a -> z) -> (z -> Balance.Balance node a)-> Balance.Forcing node a -> Balance.ForcingStep node a -> node -> [BalanceLoopItem node a z] iterateOneStorage optParams fsys accessf forcingIn steppingIn sto = iterateOneStorageCondition optParams $ map snd $ iterate go iosi where iosi = iterateOneStorageInit fsys accessf forcingIn steppingIn sto go = iterateOneStorageAlgorithm fsys accessf sto oneIterationOfAllStorages :: (Ord a, Ord node, Show node, Show a, Arith.Constant a) => Params.Optimisation node [] Sweep UV.Vector a -> (Balance.Forcing node a -> z) -> (z -> Balance.Balance node a) -> Balance.Forcing node a -> Balance.ForcingStep node a -> [BalanceLoopItem node a z] oneIterationOfAllStorages optParams fsys accessf force steps = Map.foldlWithKey f [] (Balance.unForcingMap force) where f acc sto _ = iterateOneStorage optParams fsys accessf force steps sto ++ acc ----------------------------------------------------------------- calculateNextBalanceStep :: (Ord a, Arith.Constant a,Arith.Sum a,Arith.Product a, Show a, Ord node, Show node) => Balance.Balance node a -> (Maybe (Balance.SocDrive a,a), Maybe (Balance.SocDrive a,a)) -> (Balance.ForcingStep node a) -> node -> (Balance.ForcingStep node a) calculateNextBalanceStep balMap bestPair stepMap sto = Balance.updateForcingStep stepMap sto $ Balance.setSocDrive step1 where bal = Balance.getStorageBalance "calculateNextBalanceStep" balMap sto step = Balance.getStorageForcingStep "calculateNextBalanceStep" stepMap sto fact = Arith.fromRational 2.0 divi = Arith.fromRational 1.7 intervall = Balance.getForcingIntervall bestPair step1 = case (intervall, Arith.sign bal) of -- Zero Crossing didn't occur so far -- increase step to search faster (Nothing, Negative) -> Arith.abs $ (Balance.getSocDrive step) ~* fact (Nothing, Positive) -> Arith.negate $ (Arith.abs $ Balance.getSocDrive step) ~* fact -- The Zero Crossing is contained in the intervall -- defined by bestPair - step just a little over the middle (Just int, Negative) -> (Balance.getSocDrive int) ~/ divi (Just int, Positive) -> (Arith.negate $ Balance.getSocDrive int) ~/ divi (_, Zero) -> Arith.zero ----------------------------------------------------------------- iterateEtaWhileInit :: (RealFloat a, Show a, UV.Unbox a, Arith.ZeroTestable a, Arith.Constant a,Ord node,Show node, Node.C node) => Params.System node a -> Params.Optimisation node [] Sweep UV.Vector a -> Params.Simulation node [] a -> EnvResult node (Sweep UV.Vector a) -> Balance.StateForcing -> -- (Balance.Forcing node a, EtaLoopItem node Sweep UV.Vector a (Type.SignalBasedOptimisation node Sweep UV.Vector a [] b [] c [] a) -- ) iterateEtaWhileInit sysParams optParams simParams sfgIn statForcing = EtaLoopItem sfgIn initSwp initRes where initBalF = Params.initialBattForcing optParams balStepsIn = Params.initialBattForceStep optParams accessf x = StateEta.balanceFromRecord (Params.storagePositions sysParams) (Type.signals (Type.simulation x)) initFsys balanceForcing = NonIO.optimiseAndSimulateSignalBased sysParams optParams simParams balanceForcing statForcing initSwp initIdxConvMap initIdxConvMap = AppUt.indexConversionMap (Params.systemTopology sysParams) sfgIn initSwp = Base.perStateSweep sysParams optParams sfgIn initRes = balanceIteration optParams initFsys accessf initBalF balStepsIn iterateEtaWhileAlgorithm :: (RealFloat a, Show a, UV.Unbox a, Arith.ZeroTestable a, Arith.Constant a, Show node,Node.C node) => Params.System node a -> Params.Optimisation node [] Sweep UV.Vector a -> Params.Simulation node [] a -> Balance.StateForcing -> EtaLoopItem node Sweep UV.Vector a (Type.SignalBasedOptimisation node Sweep UV.Vector a intVec b1 simVec c1 efaVec d) -> EtaLoopItem node Sweep UV.Vector a (Type.SignalBasedOptimisation node Sweep UV.Vector a [] b [] c [] a) iterateEtaWhileAlgorithm sysParams optParams simParams stateForcing (EtaLoopItem sfg _ res) = EtaLoopItem sfg1 swp1 res1 where sfg1 = Type.stateFlowGraphSweep (bResult lastElem) swp1 = Base.perStateSweep sysParams optParams sfg fsys balanceForcing = NonIO.optimiseAndSimulateSignalBased sysParams optParams simParams balanceForcing stateForcing swp1 idxConvMap idxConvMap = AppUt.indexConversionMap (Params.systemTopology sysParams) sfg res1 = balanceIteration optParams fsys accessf bfIn balStepsIn err str = error $ "iterateEtaWhileAlgorithm: empty " ++ str ++ " balanceIteration\n" ++ "probable cause: Maybe your iteration condition is always false?" lastElem = AppUt.ifNull (err "outer") last res bfIn = bForcing lastElem balStepsIn = Params.initialBattForceStep optParams accessf x = StateEta.balanceFromRecord (Params.storagePositions sysParams) (Type.signals (Type.simulation x)) iterateEtaWhileCondition :: (Ord a, Arith.Sum a) => Params.Optimisation node [] Sweep UV.Vector a -> EtaLoopItem node Sweep UV.Vector a z -> EtaLoopItem node Sweep UV.Vector a z iterateEtaWhileCondition optParams (EtaLoopItem u v res) = EtaLoopItem u v (condEta maxBICnt bip res) where maxBICnt = Params.unMaxBalanceIterations $ Params.maxBalanceIterations optParams bip = checkBalance optParams . balance iterateEtaWhile :: (Num a, Ord a, Show a, UV.Unbox a, Arith.ZeroTestable a,Ord node,Show node, Node.C node, z ~ Type.SignalBasedOptimisation node Sweep UV.Vector a [] b0 [] c0 [] a, Arith.Constant a,RealFloat a, d ~ a) => Params.System node a -> Params.Optimisation node [] Sweep UV.Vector a -> Params.Simulation node [] a -> EnvResult node (Sweep UV.Vector a) -> Balance.StateForcing -> [EtaLoopItem node Sweep UV.Vector a z] iterateEtaWhile sysParams optParams simParams sfgIn statForcing = take maxEICnt $ iterate go iewi where maxEICnt = Params.unMaxEtaIterations $ Params.maxEtaIterations optParams iewi = iterateEtaWhileCondition optParams $ iterateEtaWhileInit sysParams optParams simParams sfgIn statForcing go = iterateEtaWhileCondition optParams . iterateEtaWhileAlgorithm sysParams optParams simParams statForcing -------------------------------- OutPut Below ----------------------------------- concatZipMapsWith :: ((k0, a) -> (k1, b) -> [c]) -> Map k0 a -> Map k1 b -> [c] concatZipMapsWith f s t = concat $ zipWith f (Map.toList s) (Map.toList t) printfMap :: (Show k, Show a) => Map k a -> String printfMap m = Map.foldWithKey f "" m where f k v acc = printf "%16s\t%16s\n" (show k) (show v) ++ acc printfStateMap :: (PrintfArg k, PrintfArg v) => Map Idx.AbsoluteState Balance.StateForcing -> Map k v -> [Char] printfStateMap forceMap timeMap = concatZipMapsWith f forceMap timeMap where f (Idx.AbsoluteState k, x) (_, y) = printf "S%2d%16sf%5.3f" k (show x) y printfBalanceFMap :: (Show node, PrintfArg a1, PrintfArg t1, Arith.Constant a1) => Balance.Forcing node a1 -> Map t t1 -> [Char] printfBalanceFMap forceMap balanceMap = concatZipMapsWith f (Balance.unForcingMap forceMap) balanceMap where f (k, x) (_, y) = printf " | Sto: %7s | F: %10.15f | B: %10.15f" (show k) (Balance.getSocDrive x) y printfBalanceMap :: (Show a, PrintfArg t) => Map a t -> String printfBalanceMap balanceMap = Map.foldWithKey f "" balanceMap where f k v acc = printf " Sto: %7s B: %5.3f" (show k) v ++ acc showEtaLoop :: (Show node, Show a, PrintfArg a, Arith.Constant a) => Params.Optimisation node [] Sweep UV.Vector a -> [EtaLoopItem node Sweep UV.Vector a z] -> [String] showEtaLoop optParams loop = iterateLoops optParams showEtaLoopItem showBalanceLoopItem (zip [0..] loop) iterateLoops :: Params.Optimisation node [] Sweep UV.Vector a -> (Params.Optimisation node [] Sweep UV.Vector a -> (Counter, EtaLoopItem node Sweep UV.Vector a z) -> o) -> (Params.Optimisation node [] Sweep UV.Vector a -> (Counter, BalanceLoopItem node a z) -> o) -> [(Counter, EtaLoopItem node Sweep UV.Vector a z)]-> [o] iterateLoops optParams elf blf etaLoop = concatMap g etaLoop where g x = elf optParams x : map (blf optParams) (zip [0..] (balanceLoop (snd x))) showEtaLoopItem:: Params.Optimisation node [] Sweep UV.Vector a -> (Counter, EtaLoopItem node Sweep UV.Vector a z) -> String showEtaLoopItem _optParams (step, EtaLoopItem _sfgIn _sweep _) = printf "EL: %8d" step showBalanceLoopItem::(Show a, Show node,PrintfArg a,Arith.Constant a )=> Params.Optimisation node [] Sweep UV.Vector a -> (Counter, BalanceLoopItem node a z) -> String showBalanceLoopItem _optParams (bStp, BalanceLoopItem bForc _bFStep bal _) = printf " BL: %2d | " bStp ++ printfBalanceFMap bForc bal
energyflowanalysis/efa-2.1
src/EFA/Application/Optimisation/Loop.hs
bsd-3-clause
17,614
0
16
3,392
5,247
2,737
2,510
352
5
module Main (main) where import Control.Applicative ((<$>), (<*>), (<*), (*>)) import Control.Monad import Data.Tuple (swap) import Data.List import Network import System.IO import Text.Parsec hiding (Reply) ------------------------------------------------------------------------ main :: IO () main = vimServer 9191 -- | Starts a vim server on the specified port. vimServer :: PortNumber -> IO () vimServer serverPort = withSocketsDo $ do s <- listenOn (PortNumber serverPort) (h, host, port) <- accept s putStrLn ("Received connection from " ++ host ++ ":" ++ show port) hSetBuffering h LineBuffering authenticate h startupLoop h ------------------------------------------------------------------------ -- | Authenticate an incoming connection to the vim server or throw -- an error. authenticate :: Handle -> IO () authenticate h = do msg <- hGetLine h let auth = "AUTH " unless (auth `isPrefixOf` msg) (detach ("Expected AUTH message, received '" ++ msg ++ "'")) let pwd = drop (length auth) msg unless (pwd == "vim-ghc") (detach ("Invalid password '" ++ pwd ++ "', use 'vim-ghc' \ \to connect to this server")) where detach msg = do hPutStrLn h "DETACH" error ("vim-ghc: " ++ msg) ------------------------------------------------------------------------ startupLoop :: Handle -> IO () startupLoop h = do msg <- receiveMsg h case msg of EventMsg 0 0 StartupDone -> mainLoop h _ -> startupLoop h mainLoop :: Handle -> IO () mainLoop h = forever $ do msg <- receiveMsg h case msg of EventMsg _ _ (FileOpened path _ _) -> putBufferNumber h path 1 _ -> return () receiveMsg :: Handle -> IO ClientMsg receiveMsg h = do str <- hGetLine h case parse pClientMsg "message" str of Left err -> error ("vim-ghc: " ++ show err) Right x -> print x >> return x putBufferNumber :: Handle -> String -> BufID -> IO () putBufferNumber h path bufID = sendMsg h (show bufID ++ ":putBufferNumber!1 " ++ vimString path) sendMsg :: Handle -> String -> IO () sendMsg h msg = do hPutStrLn h msg putStrLn msg ------------------------------------------------------------------------ -- Types type SeqNo = Int type BufID = Int type Name = String data ClientMsg = ReplyMsg SeqNo Reply | EventMsg BufID SeqNo Event deriving (Show) data Reply = UnknownReply String deriving (Show) data Event = Version String | StartupDone | FileOpened FilePath Bool Bool | UnknownEvent Name String deriving (Show) ------------------------------------------------------------------------ -- Parsers type P = Parsec String () pClientMsg :: P ClientMsg pClientMsg = try pEventMsg <|> pReplyMsg pReplyMsg :: P ClientMsg pReplyMsg = ReplyMsg <$> pNatural <*> (optional space *> pReply) pReply :: P Reply pReply = UnknownReply <$> pRemaining pEventMsg :: P ClientMsg pEventMsg = do bufID <- pNatural char ':' name <- many1 letter char '=' seqNo <- pNatural optional space event <- pEvent name return (EventMsg bufID seqNo event) pEvent :: Name -> P Event pEvent name = case name of "version" -> Version <$> pVimString "startupDone" -> return StartupDone "fileOpened" -> FileOpened <$> pVimString <*> pVimBool <*> pVimBool _ -> UnknownEvent name <$> pRemaining pNatural :: P Int pNatural = read <$> many1 digit pRemaining :: P String pRemaining = manyTill anyChar eof -- | Runs a parser then expects a space or the end of -- the input stream. pArg :: P a -> P a pArg p = p <* (space *> return () <|> eof) pVimBool :: P Bool pVimBool = pArg $ char 'T' *> return True <|> char 'F' *> return False pVimString :: P String pVimString = pArg $ char '"' *> many (escaped <|> noneOf "\"") <* char '"' where escaped = char '\\' >> choice (map escapedChar vimStringEscapes) escapedChar (code, replacement) = char code >> return replacement ------------------------------------------------------------------------ -- Vim Strings vimString :: String -> String vimString xs = "\"" ++ escape xs ++ "\"" where escape = concatMap escapeChar escapes = map swap vimStringEscapes escapeChar c = case lookup c escapes of Just ec -> ['\\', ec] Nothing -> [c] vimStringEscapes :: [(Char, Char)] vimStringEscapes = [ ('n', '\n') , ('r', '\r') , ('t', '\t') , ('\"', '\"') , ('\\', '\\') ]
jystic/vim-ghc
src/Main.hs
bsd-3-clause
4,584
0
13
1,128
1,401
708
693
120
4
{-# LINE 1 "Data.Typeable.Internal.hs" #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeApplications #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Typeable.Internal -- Copyright : (c) The University of Glasgow, CWI 2001--2011 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- The representations of the types TyCon and TypeRep, and the -- function mkTyCon which is used by derived instances of Typeable to -- construct a TyCon. -- ----------------------------------------------------------------------------- module Data.Typeable.Internal ( Proxy (..), Fingerprint(..), -- * Typeable class typeOf, typeOf1, typeOf2, typeOf3, typeOf4, typeOf5, typeOf6, typeOf7, Typeable1, Typeable2, Typeable3, Typeable4, Typeable5, Typeable6, Typeable7, -- * Module Module, -- Abstract moduleName, modulePackage, -- * TyCon TyCon, -- Abstract tyConPackage, tyConModule, tyConName, tyConString, tyConFingerprint, mkTyCon3, mkTyCon3#, rnfTyCon, -- * TypeRep TypeRep(..), KindRep, typeRep, mkTyConApp, mkPolyTyConApp, mkAppTy, typeRepTyCon, Typeable(..), mkFunTy, splitTyConApp, splitPolyTyConApp, funResultTy, typeRepArgs, typeRepFingerprint, rnfTypeRep, showsTypeRep, typeRepKinds, typeSymbolTypeRep, typeNatTypeRep ) where import GHC.Base import GHC.Types (TYPE) import GHC.Word import GHC.Show import Data.Proxy import GHC.TypeLits( KnownNat, KnownSymbol, natVal', symbolVal' ) import GHC.Fingerprint.Type import {-# SOURCE #-} GHC.Fingerprint -- loop: GHC.Fingerprint -> Foreign.Ptr -> Data.Typeable -- Better to break the loop here, because we want non-SOURCE imports -- of Data.Typeable as much as possible so we can optimise the derived -- instances. {- ********************************************************************* * * The TyCon type * * ********************************************************************* -} modulePackage :: Module -> String modulePackage (Module p _) = trNameString p moduleName :: Module -> String moduleName (Module _ m) = trNameString m tyConPackage :: TyCon -> String tyConPackage (TyCon _ _ m _) = modulePackage m tyConModule :: TyCon -> String tyConModule (TyCon _ _ m _) = moduleName m tyConName :: TyCon -> String tyConName (TyCon _ _ _ n) = trNameString n trNameString :: TrName -> String trNameString (TrNameS s) = unpackCString# s trNameString (TrNameD s) = s -- | Observe string encoding of a type representation {-# DEPRECATED tyConString "renamed to 'tyConName'; 'tyConModule' and 'tyConPackage' are also available." #-} -- deprecated in 7.4 tyConString :: TyCon -> String tyConString = tyConName tyConFingerprint :: TyCon -> Fingerprint tyConFingerprint (TyCon hi lo _ _) = Fingerprint (W64# hi) (W64# lo) mkTyCon3# :: Addr# -- ^ package name -> Addr# -- ^ module name -> Addr# -- ^ the name of the type constructor -> TyCon -- ^ A unique 'TyCon' object mkTyCon3# pkg modl name | Fingerprint (W64# hi) (W64# lo) <- fingerprint = TyCon hi lo (Module (TrNameS pkg) (TrNameS modl)) (TrNameS name) where fingerprint :: Fingerprint fingerprint = fingerprintString (unpackCString# pkg ++ (' ': unpackCString# modl) ++ (' ' : unpackCString# name)) mkTyCon3 :: String -- ^ package name -> String -- ^ module name -> String -- ^ the name of the type constructor -> TyCon -- ^ A unique 'TyCon' object -- Used when the strings are dynamically allocated, -- eg from binary deserialisation mkTyCon3 pkg modl name | Fingerprint (W64# hi) (W64# lo) <- fingerprint = TyCon hi lo (Module (TrNameD pkg) (TrNameD modl)) (TrNameD name) where fingerprint :: Fingerprint fingerprint = fingerprintString (pkg ++ (' ':modl) ++ (' ':name)) isTupleTyCon :: TyCon -> Bool isTupleTyCon tc | ('(':',':_) <- tyConName tc = True | otherwise = False -- | Helper to fully evaluate 'TyCon' for use as @NFData(rnf)@ implementation -- -- @since 4.8.0.0 rnfModule :: Module -> () rnfModule (Module p m) = rnfTrName p `seq` rnfTrName m rnfTrName :: TrName -> () rnfTrName (TrNameS _) = () rnfTrName (TrNameD n) = rnfString n rnfTyCon :: TyCon -> () rnfTyCon (TyCon _ _ m n) = rnfModule m `seq` rnfTrName n rnfString :: [Char] -> () rnfString [] = () rnfString (c:cs) = c `seq` rnfString cs {- ********************************************************************* * * The TypeRep type * * ********************************************************************* -} -- | A concrete representation of a (monomorphic) type. -- 'TypeRep' supports reasonably efficient equality. data TypeRep = TypeRep {-# UNPACK #-} !Fingerprint TyCon [KindRep] [TypeRep] -- NB: For now I've made this lazy so that it's easy to -- optimise code that constructs and deconstructs TypeReps -- perf/should_run/T9203 is a good example -- Also note that mkAppTy does discards the fingerprint, -- so it's a waste to compute it type KindRep = TypeRep -- Compare keys for equality instance Eq TypeRep where TypeRep x _ _ _ == TypeRep y _ _ _ = x == y instance Ord TypeRep where TypeRep x _ _ _ <= TypeRep y _ _ _ = x <= y -- | Observe the 'Fingerprint' of a type representation -- -- @since 4.8.0.0 typeRepFingerprint :: TypeRep -> Fingerprint typeRepFingerprint (TypeRep fpr _ _ _) = fpr -- | Applies a kind-polymorphic type constructor to a sequence of kinds and -- types mkPolyTyConApp :: TyCon -> [KindRep] -> [TypeRep] -> TypeRep {-# INLINE mkPolyTyConApp #-} mkPolyTyConApp tc kinds types = TypeRep (fingerprintFingerprints sub_fps) tc kinds types where !kt_fps = typeRepFingerprints kinds types sub_fps = tyConFingerprint tc : kt_fps typeRepFingerprints :: [KindRep] -> [TypeRep] -> [Fingerprint] -- Builds no thunks typeRepFingerprints kinds types = go1 [] kinds where go1 acc [] = go2 acc types go1 acc (k:ks) = let !fp = typeRepFingerprint k in go1 (fp:acc) ks go2 acc [] = acc go2 acc (t:ts) = let !fp = typeRepFingerprint t in go2 (fp:acc) ts -- | Applies a kind-monomorphic type constructor to a sequence of types mkTyConApp :: TyCon -> [TypeRep] -> TypeRep mkTyConApp tc = mkPolyTyConApp tc [] -- | A special case of 'mkTyConApp', which applies the function -- type constructor to a pair of types. mkFunTy :: TypeRep -> TypeRep -> TypeRep mkFunTy f a = mkTyConApp tcFun [f,a] -- | Splits a type constructor application. -- Note that if the type constructor is polymorphic, this will -- not return the kinds that were used. -- See 'splitPolyTyConApp' if you need all parts. splitTyConApp :: TypeRep -> (TyCon,[TypeRep]) splitTyConApp (TypeRep _ tc _ trs) = (tc,trs) -- | Split a type constructor application splitPolyTyConApp :: TypeRep -> (TyCon,[KindRep],[TypeRep]) splitPolyTyConApp (TypeRep _ tc ks trs) = (tc,ks,trs) -- | Applies a type to a function type. Returns: @'Just' u@ if the -- first argument represents a function of type @t -> u@ and the -- second argument represents a function of type @t@. Otherwise, -- returns 'Nothing'. funResultTy :: TypeRep -> TypeRep -> Maybe TypeRep funResultTy trFun trArg = case splitTyConApp trFun of (tc, [t1,t2]) | tc == tcFun && t1 == trArg -> Just t2 _ -> Nothing tyConOf :: Typeable a => Proxy a -> TyCon tyConOf = typeRepTyCon . typeRep tcFun :: TyCon tcFun = tyConOf (Proxy :: Proxy (Int -> Int)) -- | Adds a TypeRep argument to a TypeRep. mkAppTy :: TypeRep -> TypeRep -> TypeRep {-# INLINE mkAppTy #-} mkAppTy (TypeRep _ tc ks trs) arg_tr = mkPolyTyConApp tc ks (trs ++ [arg_tr]) -- Notice that we call mkTyConApp to construct the fingerprint from tc and -- the arg fingerprints. Simply combining the current fingerprint with -- the new one won't give the same answer, but of course we want to -- ensure that a TypeRep of the same shape has the same fingerprint! -- See Trac #5962 ----------------- Observation --------------------- -- | Observe the type constructor of a type representation typeRepTyCon :: TypeRep -> TyCon typeRepTyCon (TypeRep _ tc _ _) = tc -- | Observe the argument types of a type representation typeRepArgs :: TypeRep -> [TypeRep] typeRepArgs (TypeRep _ _ _ tys) = tys -- | Observe the argument kinds of a type representation typeRepKinds :: TypeRep -> [KindRep] typeRepKinds (TypeRep _ _ ks _) = ks {- ********************************************************************* * * The Typeable class * * ********************************************************************* -} ------------------------------------------------------------- -- -- The Typeable class and friends -- ------------------------------------------------------------- -- | The class 'Typeable' allows a concrete representation of a type to -- be calculated. class Typeable a where typeRep# :: Proxy# a -> TypeRep -- | Takes a value of type @a@ and returns a concrete representation -- of that type. -- -- @since 4.7.0.0 typeRep :: forall proxy a. Typeable a => proxy a -> TypeRep typeRep _ = typeRep# (proxy# :: Proxy# a) {-# INLINE typeRep #-} -- Keeping backwards-compatibility typeOf :: forall a. Typeable a => a -> TypeRep typeOf _ = typeRep (Proxy :: Proxy a) typeOf1 :: forall t (a :: *). Typeable t => t a -> TypeRep typeOf1 _ = typeRep (Proxy :: Proxy t) typeOf2 :: forall t (a :: *) (b :: *). Typeable t => t a b -> TypeRep typeOf2 _ = typeRep (Proxy :: Proxy t) typeOf3 :: forall t (a :: *) (b :: *) (c :: *). Typeable t => t a b c -> TypeRep typeOf3 _ = typeRep (Proxy :: Proxy t) typeOf4 :: forall t (a :: *) (b :: *) (c :: *) (d :: *). Typeable t => t a b c d -> TypeRep typeOf4 _ = typeRep (Proxy :: Proxy t) typeOf5 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *). Typeable t => t a b c d e -> TypeRep typeOf5 _ = typeRep (Proxy :: Proxy t) typeOf6 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *) (f :: *). Typeable t => t a b c d e f -> TypeRep typeOf6 _ = typeRep (Proxy :: Proxy t) typeOf7 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *) (f :: *) (g :: *). Typeable t => t a b c d e f g -> TypeRep typeOf7 _ = typeRep (Proxy :: Proxy t) type Typeable1 (a :: * -> *) = Typeable a type Typeable2 (a :: * -> * -> *) = Typeable a type Typeable3 (a :: * -> * -> * -> *) = Typeable a type Typeable4 (a :: * -> * -> * -> * -> *) = Typeable a type Typeable5 (a :: * -> * -> * -> * -> * -> *) = Typeable a type Typeable6 (a :: * -> * -> * -> * -> * -> * -> *) = Typeable a type Typeable7 (a :: * -> * -> * -> * -> * -> * -> * -> *) = Typeable a {-# DEPRECATED Typeable1 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable2 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable3 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable4 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable5 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable6 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable7 "renamed to 'Typeable'" #-} -- deprecated in 7.8 ----------------- Showing TypeReps -------------------- instance Show TypeRep where showsPrec p (TypeRep _ tycon kinds tys) = case tys of [] -> showsPrec p tycon [x] | tycon == tcList -> showChar '[' . shows x . showChar ']' where tcList = tyConOf @[] Proxy [TypeRep _ ptrRepCon _ []] | tycon == tcTYPE && ptrRepCon == tc'PtrRepLifted -> showChar '*' | tycon == tcTYPE && ptrRepCon == tc'PtrRepUnlifted -> showChar '#' where tcTYPE = tyConOf @TYPE Proxy tc'PtrRepLifted = tyConOf @'PtrRepLifted Proxy tc'PtrRepUnlifted = tyConOf @'PtrRepUnlifted Proxy [a,r] | tycon == tcFun -> showParen (p > 8) $ showsPrec 9 a . showString " -> " . showsPrec 8 r xs | isTupleTyCon tycon -> showTuple xs | otherwise -> showParen (p > 9) $ showsPrec p tycon . showChar ' ' . showArgs (showChar ' ') (kinds ++ tys) showsTypeRep :: TypeRep -> ShowS showsTypeRep = shows -- | Helper to fully evaluate 'TypeRep' for use as @NFData(rnf)@ implementation -- -- @since 4.8.0.0 rnfTypeRep :: TypeRep -> () rnfTypeRep (TypeRep _ tyc krs tyrs) = rnfTyCon tyc `seq` go krs `seq` go tyrs where go [] = () go (x:xs) = rnfTypeRep x `seq` go xs -- Some (Show.TypeRep) helpers: showArgs :: Show a => ShowS -> [a] -> ShowS showArgs _ [] = id showArgs _ [a] = showsPrec 10 a showArgs sep (a:as) = showsPrec 10 a . sep . showArgs sep as showTuple :: [TypeRep] -> ShowS showTuple args = showChar '(' . showArgs (showChar ',') args . showChar ')' {- ********************************************************* * * * TyCon/TypeRep definitions for type literals * * (Symbol and Nat) * * * ********************************************************* -} mkTypeLitTyCon :: String -> TyCon mkTypeLitTyCon name = mkTyCon3 "base" "GHC.TypeLits" name -- | Used to make `'Typeable' instance for things of kind Nat typeNatTypeRep :: KnownNat a => Proxy# a -> TypeRep typeNatTypeRep p = typeLitTypeRep (show (natVal' p)) -- | Used to make `'Typeable' instance for things of kind Symbol typeSymbolTypeRep :: KnownSymbol a => Proxy# a -> TypeRep typeSymbolTypeRep p = typeLitTypeRep (show (symbolVal' p)) -- | An internal function, to make representations for type literals. typeLitTypeRep :: String -> TypeRep typeLitTypeRep nm = mkTyConApp (mkTypeLitTyCon nm) []
phischu/fragnix
builtins/base/Data.Typeable.Internal.hs
bsd-3-clause
15,433
0
15
4,372
3,518
1,921
1,597
238
3
{-| Module : Translate Description : Translate Python code to CUDA C++ Maintainer : Josh Acay <cacay@cmu.edu> Stability : experimental -} module Translate (py2cuda) where import Control.Arrow ((&&&), left) import Control.Monad (liftM) import Control.Monad.Error (throwError) import qualified Data.Map.Strict as Map import Foreign.C.String import Text.Read (readEither) import Language.Python.Common import Language.Python.Version2 (parseModule) import AST.AST (funName, funType) import AST.Types (Type (..)) import Translation.Constants (defineIndicies) import Translation.Library (compileLibrary) import Translation.Translate (translate) import Translation.Variables (declareVars) type Error = Either String prependError :: String -> Error a -> Error a prependError p (Left e) = Left (p ++ e) prependError _ r = r py2cuda_internal :: String -> [[String]] -> Error String py2cuda_internal pySrc strTypes = do types <- mapM (mapM parseType) strTypes case liftM fst (parseModule pySrc "PyCuda") of Left error -> throwError $ "parser: " ++ prettyText error Right ast -> do funs <- compile ast types; return (compileLibrary funs) where compile ast types = do funs <- prependError "translate: " (translate ast types) let sigs = Map.fromList $ map (funName &&& funType) funs let funs' = map defineIndicies funs prependError "declareVars: " $ mapM (declareVars sigs) funs' parseType :: String -> Error Type parseType s = left (const $ "invalid type: " ++ s) (readEither s) py2cuda :: CString -> CString -> IO CString py2cuda src types = do pySrc <- peekCString src strTypes <- liftM (map words . lines) (peekCString types) case py2cuda_internal pySrc strTypes of Left err -> newCString ("error:" ++ err) Right cudaSrc -> newCString ("ok:" ++ cudaSrc) foreign export ccall py2cuda :: CString -> CString -> IO CString
oulgen/CudaPy
py2cuda/src/Translate.hs
mit
1,888
0
15
338
614
317
297
40
2
{-# LANGUAGE TemplateHaskell, CPP #-} module Yesod.Routes.TH.RenderRoute ( -- ** RenderRoute mkRenderRouteInstance , mkRouteCons , mkRenderRouteClauses ) where import Yesod.Routes.TH.Types import Language.Haskell.TH (conT) import Language.Haskell.TH.Syntax import Data.Bits (xor) import Data.Maybe (maybeToList) import Control.Monad (replicateM) import Data.Text (pack) import Web.PathPieces (PathPiece (..), PathMultiPiece (..)) import Yesod.Routes.Class -- | Generate the constructors of a route data type. mkRouteCons :: [ResourceTree Type] -> Q ([Con], [Dec]) mkRouteCons rttypes = mconcat <$> mapM mkRouteCon rttypes where mkRouteCon (ResourceLeaf res) = return ([con], []) where con = NormalC (mkName $ resourceName res) $ map (\x -> (notStrict, x)) $ concat [singles, multi, sub] singles = concatMap toSingle $ resourcePieces res toSingle Static{} = [] toSingle (Dynamic typ) = [typ] multi = maybeToList $ resourceMulti res sub = case resourceDispatch res of Subsite { subsiteType = typ } -> [ConT ''Route `AppT` typ] _ -> [] mkRouteCon (ResourceParent name _check pieces children) = do (cons, decs) <- mkRouteCons children #if MIN_VERSION_template_haskell(2,12,0) dec <- DataD [] (mkName name) [] Nothing cons <$> fmap (pure . DerivClause Nothing) (mapM conT [''Show, ''Read, ''Eq]) #else dec <- DataD [] (mkName name) [] Nothing cons <$> mapM conT [''Show, ''Read, ''Eq] #endif return ([con], dec : decs) where con = NormalC (mkName name) $ map (\x -> (notStrict, x)) $ singles ++ [ConT $ mkName name] singles = concatMap toSingle pieces toSingle Static{} = [] toSingle (Dynamic typ) = [typ] -- | Clauses for the 'renderRoute' method. mkRenderRouteClauses :: [ResourceTree Type] -> Q [Clause] mkRenderRouteClauses = mapM go where isDynamic Dynamic{} = True isDynamic _ = False go (ResourceParent name _check pieces children) = do let cnt = length $ filter isDynamic pieces dyns <- replicateM cnt $ newName "dyn" child <- newName "child" let pat = ConP (mkName name) $ map VarP $ dyns ++ [child] pack' <- [|pack|] tsp <- [|toPathPiece|] let piecesSingle = mkPieces (AppE pack' . LitE . StringL) tsp pieces dyns childRender <- newName "childRender" let rr = VarE childRender childClauses <- mkRenderRouteClauses children a <- newName "a" b <- newName "b" colon <- [|(:)|] let cons y ys = InfixE (Just y) colon (Just ys) let pieces' = foldr cons (VarE a) piecesSingle let body = LamE [TupP [VarP a, VarP b]] (TupE [pieces', VarE b]) `AppE` (rr `AppE` VarE child) return $ Clause [pat] (NormalB body) [FunD childRender childClauses] go (ResourceLeaf res) = do let cnt = length (filter isDynamic $ resourcePieces res) + maybe 0 (const 1) (resourceMulti res) dyns <- replicateM cnt $ newName "dyn" sub <- case resourceDispatch res of Subsite{} -> return <$> newName "sub" _ -> return [] let pat = ConP (mkName $ resourceName res) $ map VarP $ dyns ++ sub pack' <- [|pack|] tsp <- [|toPathPiece|] let piecesSingle = mkPieces (AppE pack' . LitE . StringL) tsp (resourcePieces res) dyns piecesMulti <- case resourceMulti res of Nothing -> return $ ListE [] Just{} -> do tmp <- [|toPathMultiPiece|] return $ tmp `AppE` VarE (last dyns) body <- case sub of [x] -> do rr <- [|renderRoute|] a <- newName "a" b <- newName "b" colon <- [|(:)|] let cons y ys = InfixE (Just y) colon (Just ys) let pieces = foldr cons (VarE a) piecesSingle return $ LamE [TupP [VarP a, VarP b]] (TupE [pieces, VarE b]) `AppE` (rr `AppE` VarE x) _ -> do colon <- [|(:)|] let cons a b = InfixE (Just a) colon (Just b) return $ TupE [foldr cons piecesMulti piecesSingle, ListE []] return $ Clause [pat] (NormalB body) [] mkPieces _ _ [] _ = [] mkPieces toText tsp (Static s:ps) dyns = toText s : mkPieces toText tsp ps dyns mkPieces toText tsp (Dynamic{}:ps) (d:dyns) = tsp `AppE` VarE d : mkPieces toText tsp ps dyns mkPieces _ _ (Dynamic _ : _) [] = error "mkPieces 120" -- | Generate the 'RenderRoute' instance. -- -- This includes both the 'Route' associated type and the -- 'renderRoute' method. This function uses both 'mkRouteCons' and -- 'mkRenderRouteClasses'. mkRenderRouteInstance :: Cxt -> Type -> [ResourceTree Type] -> Q [Dec] mkRenderRouteInstance cxt typ ress = do cls <- mkRenderRouteClauses ress (cons, decs) <- mkRouteCons ress #if MIN_VERSION_template_haskell(2,12,0) did <- DataInstD [] ''Route [typ] Nothing cons <$> fmap (pure . DerivClause Nothing) (mapM conT (clazzes False)) let sds = fmap (\t -> StandaloneDerivD Nothing cxt $ ConT t `AppT` ( ConT ''Route `AppT` typ)) (clazzes True) #else did <- DataInstD [] ''Route [typ] Nothing cons <$> mapM conT (clazzes False) let sds = fmap (\t -> StandaloneDerivD cxt $ ConT t `AppT` ( ConT ''Route `AppT` typ)) (clazzes True) #endif return $ instanceD cxt (ConT ''RenderRoute `AppT` typ) [ did , FunD (mkName "renderRoute") cls ] : sds ++ decs where clazzes standalone = if standalone `xor` null cxt then clazzes' else [] clazzes' = [''Show, ''Eq, ''Read] notStrict :: Bang notStrict = Bang NoSourceUnpackedness NoSourceStrictness instanceD :: Cxt -> Type -> [Dec] -> Dec instanceD = InstanceD Nothing
s9gf4ult/yesod
yesod-core/Yesod/Routes/TH/RenderRoute.hs
mit
6,054
0
21
1,828
2,043
1,041
1,002
118
9
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-} {- | Module : ./Comorphisms/CASL2VSERefine.hs Description : VSE refinement as comorphism Copyright : (c) M. Codescu, DFKI Bremen 2008 License : GPLv2 or higher, see LICENSE.txt Maintainer : Mihai.Codescu@dfki.de Stability : provisional Portability : non-portable (imports Logic.Logic) The embedding comorphism from CASL to VSE. -} module Comorphisms.CASL2VSERefine (CASL2VSERefine (..)) where import Logic.Logic import Logic.Comorphism import CASL.Logic_CASL import CASL.Sublogic as SL import CASL.Sign import CASL.AS_Basic_CASL import CASL.Morphism import VSE.Logic_VSE import VSE.As import VSE.Ana import Common.AS_Annotation import Common.Id import Common.ProofTree import Common.Result import Common.Utils (number) import Common.Lib.State import qualified Common.Lib.MapSet as MapSet import qualified Data.Set as Set import qualified Data.Map as Map -- | The identity of the comorphism data CASL2VSERefine = CASL2VSERefine deriving (Show) instance Language CASL2VSERefine -- default definition is okay instance Comorphism CASL2VSERefine CASL CASL_Sublogics CASLBasicSpec CASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS CASLSign CASLMor Symbol RawSymbol ProofTree VSE () VSEBasicSpec Sentence SYMB_ITEMS SYMB_MAP_ITEMS VSESign VSEMor Symbol RawSymbol () where sourceLogic CASL2VSERefine = CASL sourceSublogic CASL2VSERefine = SL.cFol targetLogic CASL2VSERefine = VSE mapSublogic CASL2VSERefine _ = Just () map_theory CASL2VSERefine = mapCASLTheory map_morphism CASL2VSERefine = return . mapMor map_sentence CASL2VSERefine _ = error "map sen nyi" -- return. mapCASSen map_symbol CASL2VSERefine = error "map symbol nyi" has_model_expansion CASL2VSERefine = True -- check these 3, but should be fine is_weakly_amalgamable CASL2VSERefine = True isInclusionComorphism CASL2VSERefine = False mapCASLTheory :: (CASLSign, [Named CASLFORMULA]) -> Result (VSESign, [Named Sentence]) mapCASLTheory (sig, n_sens) = let (tsig, genAx) = mapSig sig tsens = map mapNamedSen n_sens allSens = tsens ++ genAx in if null $ checkCases tsig allSens then return (tsig, allSens) else fail "case error in signature" mapSig :: CASLSign -> (VSESign, [Named Sentence]) mapSig sign = let wrapSort (procsym, axs) s = let restrName = gnRestrName s eqName = gnEqName s sProcs = [(restrName, Profile [Procparam In s] Nothing), (eqName, Profile [Procparam In s, Procparam In s] (Just uBoolean))] varx = Qual_var (genToken "x") s nullRange vary = Qual_var (genToken "y") s nullRange varz = Qual_var (genToken "z") s nullRange varb = Qual_var (genToken "b") uBoolean nullRange varb1 = Qual_var (genToken "b1") uBoolean nullRange varb2 = Qual_var (genToken "b2") uBoolean nullRange sSens = [ makeNamed ("ga_termination_eq_" ++ show s) $ Quantification Universal [Var_decl [genToken "x", genToken "y"] s nullRange , Var_decl [genToken "b"] uBoolean nullRange] (mkImpl (conjunct [ ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name restrName (Pred_type [s] nullRange) nullRange) [varx] nullRange)) nullRange) trueForm ) nullRange, ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name restrName (Pred_type [s] nullRange) nullRange) [vary] nullRange)) nullRange) trueForm ) nullRange ]) (ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Assign (genToken "b") (Application (Qual_op_name (gnEqName s) (Op_type Partial [s, s] uBoolean nullRange) nullRange) [varx, vary] nullRange)) nullRange) trueForm ) nullRange) ) nullRange , makeNamed ("ga_refl_eq_" ++ show s) $ Quantification Universal [Var_decl [genToken "x"] s nullRange , Var_decl [genToken "b"] uBoolean nullRange] (mkImpl (ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name restrName (Pred_type [s] nullRange ) nullRange) [varx] nullRange)) nullRange) trueForm ) nullRange) (ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Assign (genToken "b") (Application (Qual_op_name (gnEqName s) (Op_type Partial [s, s] uBoolean nullRange) nullRange) [varx, varx] nullRange)) nullRange) (mkStEq varb (Application (Qual_op_name uTrue (Op_type Total [] uBoolean nullRange) nullRange) [] nullRange) )) nullRange) ) nullRange , makeNamed ("ga_sym_eq_" ++ show s) $ Quantification Universal [Var_decl [genToken "x", genToken "y"] s nullRange , Var_decl [genToken "b1", genToken "b2"] uBoolean nullRange] (mkImpl (conjunct [ ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name restrName (Pred_type [s] nullRange) nullRange) [varx] nullRange)) nullRange) trueForm ) nullRange, ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name restrName (Pred_type [s] nullRange) nullRange) [vary] nullRange)) nullRange) trueForm ) nullRange, ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Assign (genToken "b1") (Application (Qual_op_name (gnEqName s) (Op_type Partial [s, s] uBoolean nullRange) nullRange) [varx, vary] nullRange)) nullRange) (mkStEq varb1 aTrue) ) nullRange ]) (ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Assign (genToken "b2") (Application (Qual_op_name (gnEqName s) (Op_type Partial [s, s] uBoolean nullRange) nullRange) [vary, varx] nullRange)) nullRange) (mkStEq varb2 aTrue) ) nullRange) ) nullRange , makeNamed ("ga_trans_eq_" ++ show s) $ Quantification Universal [Var_decl [genToken "x", genToken "y", genToken "z"] s nullRange , Var_decl [genToken "b1", genToken "b2", genToken "b"] uBoolean nullRange] (mkImpl (conjunct [ ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name restrName (Pred_type [s] nullRange) nullRange) [varx] nullRange)) nullRange) trueForm ) nullRange, ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name restrName (Pred_type [s] nullRange ) nullRange) [vary] nullRange)) nullRange) trueForm ) nullRange, ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name restrName (Pred_type [s] nullRange ) nullRange) [varz] nullRange)) nullRange) trueForm ) nullRange, ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Assign (genToken "b1") (Application (Qual_op_name (gnEqName s) (Op_type Partial [s, s] uBoolean nullRange) nullRange) [varx, vary] nullRange)) nullRange) (mkStEq varb1 aTrue) ) nullRange, ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Assign (genToken "b2") (Application (Qual_op_name (gnEqName s) (Op_type Partial [s, s] uBoolean nullRange) nullRange) [vary, varz] nullRange)) nullRange) (mkStEq varb2 aTrue) ) nullRange ]) (ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Assign (genToken "b") (Application (Qual_op_name (gnEqName s) (Op_type Partial [s, s] uBoolean nullRange) nullRange) [varx, varz] nullRange)) nullRange) (mkStEq varb aTrue) ) nullRange) ) nullRange ] in (sProcs ++ procsym, sSens ++ axs) (sortProcs, sortSens) = foldl wrapSort ([], []) $ Set.toList $ sortSet sign wrapOp (procsym, axs) (i, opTypes) = let funName = mkGenName i fProcs = map (\ profile -> (funName, Profile (map (Procparam In) $ opArgs profile) (Just $ opRes profile))) opTypes opTypeSens (OpType _ w s) = let xtokens = map (\ (_, ii) -> genNumVar "x" ii) $ number w xvars = map ( \ (si, ii) -> Qual_var (genNumVar "x" ii ) si nullRange ) $ number w yvars = map ( \ (si, ii) -> Qual_var (genNumVar "y" ii ) si nullRange ) $ number w ytokens = map (\ (_, ii) -> genNumVar "y" ii) $ number w btokens = map (\ (_, ii) -> genNumVar "b" ii) $ number w xtoken = genToken "x" ytoken = genToken "y" btoken = genToken "b" xvar = Qual_var (genToken "x") s nullRange yvar = Qual_var (genToken "y") s nullRange bvar = Qual_var (genToken "b") uBoolean nullRange congrF = [makeNamed "" $ Quantification Universal ([Var_decl [xtoken, ytoken] s nullRange , Var_decl (btoken : btokens) uBoolean nullRange ] ++ map (\ ((t1, t2), si) -> Var_decl [t1, t2] si nullRange) (zip (zip xtokens ytokens) w) ) (mkImpl (conjunct (concatMap (\ (si, ii) -> let xv = Qual_var (genNumVar "x" ii) si nullRange yv = Qual_var (genNumVar "y" ii) si nullRange varbi = genNumVar "b" ii bi1 = Qual_var (genNumVar "b" ii) uBoolean nullRange in [ExtFORMULA $ Ranged ( Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name (gnRestrName si) (Pred_type [si] nullRange) nullRange ) [xv] nullRange)) nullRange) trueForm ) nullRange , ExtFORMULA $ Ranged ( Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name (gnRestrName si) (Pred_type [si] nullRange) nullRange) [yv] nullRange)) nullRange) trueForm ) nullRange , ExtFORMULA $ mkRanged $ Dlformula Diamond (Ranged (Assign varbi (Application (Qual_op_name (gnEqName si) (Op_type Partial [si, si] uBoolean nullRange) nullRange) [xv, yv] nullRange)) nullRange) (mkStEq bi1 aTrue) ] ) $ number w ) ) -- hypothesis (ExtFORMULA $ Ranged ( Dlformula Diamond (Ranged (Assign (genToken "x") (Application (Qual_op_name (mkGenName i) (Op_type Partial w s nullRange) nullRange) xvars nullRange)) nullRange) (ExtFORMULA $ Ranged ( Dlformula Diamond (Ranged (Assign (genToken "y") (Application (Qual_op_name (mkGenName i) (Op_type Partial w s nullRange) nullRange) yvars nullRange)) nullRange) (ExtFORMULA $ Ranged ( Dlformula Diamond ( Ranged (Assign (genToken "b") (Application (Qual_op_name (gnEqName s) (Op_type Partial [s, s] uBoolean nullRange) nullRange) [xvar, yvar] nullRange)) nullRange ) (mkStEq bvar aTrue) ) nullRange) ) nullRange) ) nullRange) -- conclusion ) nullRange ] termF = if not $ null w then [ makeNamed "" $ Quantification Universal (Var_decl [xtoken] s nullRange : map (\ (t1, si) -> Var_decl [t1] si nullRange) (zip xtokens w)) (mkImpl (conjunct (concatMap (\ (si, ii) -> let xv = Qual_var (genNumVar "x" ii) si nullRange in [ExtFORMULA $ Ranged ( Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name (gnRestrName si) (Pred_type (w ++ [s]) nullRange) nullRange) [xv] nullRange)) nullRange) trueForm ) nullRange ] ) $ number w ) ) (ExtFORMULA $ Ranged ( Dlformula Diamond (Ranged (Assign (genToken "x") (Application (Qual_op_name (mkGenName i) (Op_type Partial w s nullRange) nullRange) xvars nullRange)) nullRange) (ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name (gnRestrName s) (Pred_type [s] nullRange) nullRange) [xvar] nullRange)) nullRange) trueForm ) nullRange) ) nullRange) ) nullRange ] else [makeNamed "" $ Quantification Universal [Var_decl [xtoken] s nullRange] (ExtFORMULA $ Ranged ( Dlformula Diamond (Ranged (Assign (genToken "x") (Application (Qual_op_name (mkGenName i) (Op_type Partial [] s nullRange) nullRange) [] nullRange)) nullRange) (ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name (gnRestrName s) (Pred_type [s] nullRange) nullRange) [xvar] nullRange)) nullRange) trueForm ) nullRange) ) nullRange) nullRange] in if null w then termF else congrF ++ termF fSens = concatMap opTypeSens opTypes in (procsym ++ fProcs, axs ++ fSens) (opProcs, opSens) = foldl wrapOp ([], []) $ MapSet.toList $ opMap sign wrapPred (procsym, axs) (i, predTypes) = let procName = mkGenName i pProcs = map (\ profile -> (procName, Profile (map (Procparam In) $ predArgs profile) (Just uBoolean))) predTypes predTypeSens (PredType w) = let xtokens = map (\ (_, ii) -> genNumVar "x" ii) $ number w xvars = map ( \ (si, ii) -> Qual_var (genNumVar "x" ii ) si nullRange ) $ number w ytokens = map (\ (_, ii) -> genNumVar "y" ii) $ number w btokens = map (\ (_, ii) -> genNumVar "b" ii) $ number w btoken = genToken "b" r1 = genToken "r1" r2 = genToken "r2" rvar1 = Qual_var (genToken "r1") uBoolean nullRange rvar2 = Qual_var (genToken "r2") uBoolean nullRange congrP = [makeNamed "" $ Quantification Universal (Var_decl (btoken : r1 : r2 : btokens) uBoolean nullRange : map (\ ((t1, t2), si) -> Var_decl [t1, t2] si nullRange) (zip (zip xtokens ytokens) w)) (mkImpl (conjunct (concatMap (\ (si, ii) -> let xv = Qual_var (genNumVar "x" ii) si nullRange yv = Qual_var (genNumVar "y" ii) si nullRange bi1 = Qual_var (genNumVar "b" ii) uBoolean nullRange in [ExtFORMULA $ Ranged ( Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name (gnRestrName si) (Pred_type [si] nullRange) nullRange) [xv] nullRange)) nullRange) trueForm ) nullRange , ExtFORMULA $ Ranged ( Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name (gnRestrName si) (Pred_type [si] nullRange) nullRange) [yv] nullRange)) nullRange) trueForm ) nullRange , ExtFORMULA $ mkRanged $ Dlformula Diamond (Ranged (Assign (genNumVar "b" ii) (Application (Qual_op_name (gnEqName si) (Op_type Partial [si, si] uBoolean nullRange) nullRange) [xv, yv] nullRange)) nullRange) (mkStEq bi1 aTrue) ] ) $ number w ) ) -- hypothesis (ExtFORMULA $ Ranged ( Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name (mkGenName i) (Pred_type (w ++ [uBoolean]) nullRange) nullRange) (map ( \ (si, ii) -> Qual_var (genNumVar "x" ii ) si nullRange ) (number w) ++ [rvar1]) nullRange)) nullRange) (ExtFORMULA $ Ranged ( Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name (mkGenName i) (Pred_type (w ++ [uBoolean]) nullRange) nullRange) (map ( \ (si, ii) -> Qual_var (genNumVar "y" ii ) si nullRange ) (number w) ++ [rvar2]) nullRange)) nullRange) (mkStEq rvar1 rvar2 ) ) nullRange) ) nullRange) -- conclusion ) nullRange ] termP = [ makeNamed "" $ Quantification Universal (map (\ (t1, si) -> Var_decl [t1] si nullRange) (zip xtokens w) ++ [Var_decl [r1] uBoolean nullRange]) (mkImpl (conjunct (concatMap (\ (si, ii) -> let xv = Qual_var (genNumVar "x" ii) si nullRange in [ExtFORMULA $ Ranged ( Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name (gnRestrName si) (Pred_type [si] nullRange) nullRange) [xv] nullRange)) nullRange) trueForm ) nullRange ] ) $ number w ) ) (ExtFORMULA $ Ranged ( Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name (mkGenName i) (Pred_type (w ++ [uBoolean]) nullRange) nullRange) (xvars ++ [rvar1]) nullRange)) nullRange) trueForm ) nullRange) ) nullRange ] in congrP ++ termP pSens = concatMap predTypeSens predTypes in (procsym ++ pProcs, axs ++ pSens) (predProcs, predSens) = foldl wrapPred ([], []) $ MapSet.toList $ predMap sign procs = Procs $ Map.fromList (sortProcs ++ opProcs ++ predProcs) newPreds = procsToPredMap procs newOps = procsToOpMap procs in (sign { opMap = newOps, predMap = newPreds, extendedInfo = procs, sentences = [] }, sortSens ++ opSens ++ predSens) mapNamedSen :: Named CASLFORMULA -> Named Sentence mapNamedSen n_sen = let sen = sentence n_sen trans = mapCASLSen sen in n_sen {sentence = trans} mapMor :: CASLMor -> VSEMor mapMor m = let (om, pm) = vseMorExt m in m { msource = fst $ mapSig $ msource m , mtarget = fst $ mapSig $ mtarget m , op_map = om , pred_map = pm , extended_map = emptyMorExt } mapCASLSen :: CASLFORMULA -> Sentence mapCASLSen f = let (sen, (_i, vars)) = runState (mapCASLSenAux f) (0, Set.empty) in case f of Sort_gen_ax _ _ -> sen _ -> addQuantifiers vars sen addQuantifiers :: VarSet -> Sentence -> Sentence addQuantifiers vars sen = Quantification Universal (map (\ (v, s) -> Var_decl [v] s nullRange) $ Set.toList vars) sen nullRange mapCASLSenAux :: CASLFORMULA -> State (Int, VarSet) Sentence mapCASLSenAux f = case f of Sort_gen_ax constrs isFree -> do let (genSorts, _, _ ) = recover_Sort_gen_ax constrs toProcs (Op_name _, _) = error "must be qual names" toProcs (Qual_op_name op (Op_type _fkind args res _range) _, l) = ( Qual_op_name (mkGenName op) (Op_type Partial args res nullRange) nullRange, l) opsToProcs (Constraint nSort syms oSort) = Constraint nSort (map toProcs syms) oSort return $ ExtFORMULA $ Ranged (RestrictedConstraint (map opsToProcs constrs) (Map.fromList $ map (\ s -> (s, gnRestrName s)) genSorts) isFree) nullRange Atom b _ps -> return $ boolForm b Equation t1 Strong t2 _ps -> do let sort1 = sortOfTerm t1 n1 <- freshIndex sort1 -- (typeof t1) prg1 <- mapCASLTerm n1 t1 n2 <- freshIndex sort1 -- (typeof t2) prg2 <- mapCASLTerm n2 t2 n <- freshIndex uBoolean return $ ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Seq (Ranged (Seq prg1 prg2) nullRange) (Ranged (Assign (genNumVar "x" n) (Application (Qual_op_name (gnEqName sort1) (Op_type Partial [sort1, sort1] uBoolean nullRange) nullRange) [Qual_var (genNumVar "x" n1) sort1 nullRange, Qual_var (genNumVar "x" n2) sort1 nullRange] nullRange ) ) nullRange) ) nullRange) (mkStEq (Qual_var (genNumVar "x" n) uBoolean nullRange) aTrue) ) nullRange {- here i have to return smth like -- <: xn1 := prg1; -- xn2 := prg2; -- xn := gn_eq_s(xn1,xn2) :> xn = True " -} Predication pn as _qs -> do indexes <- mapM (freshIndex . sortOfTerm) as prgs <- mapM (\ (ti, i) -> mapCASLTerm i ti) $ zip as indexes let xvars = map (\ (ti, i) -> Qual_var (genNumVar "x" i) (sortOfTerm ti) nullRange ) $ zip as indexes n <- freshIndex uBoolean let asgn = if not $ null prgs then foldr1 (\ p1 p2 -> Ranged (Seq p1 p2) nullRange) prgs else Ranged Skip nullRange case pn of Pred_name _ -> fail "must be qualified" Qual_pred_name pname (Pred_type ptype _) _ -> return $ ExtFORMULA $ Ranged (Dlformula Diamond (Ranged (Seq asgn (Ranged (Assign (genNumVar "x" n) (Application (Qual_op_name (mkGenName pname) (Op_type Partial ptype uBoolean nullRange) nullRange) xvars nullRange)) nullRange)) nullRange) (mkStEq (Qual_var (genNumVar "x" n) uBoolean nullRange) aTrue)) nullRange {- <: xi := prgi; x:= gn_p(x1,..,xn):> x = True -} Junction j fs _r -> do mapFs <- mapM mapCASLSenAux fs return $ Junction j mapFs nullRange Relation f1 c f2 _r -> do trf1 <- mapCASLSenAux f1 trf2 <- mapCASLSenAux f2 return $ Relation trf1 c trf2 nullRange Negation f1 _r -> do trf <- mapCASLSenAux f1 return $ mkNeg trf Quantification q vars sen _ -> case q of Universal -> do trSen <- mapCASLSenAux sen let h = map (\ (Var_decl varS s _) -> let restrs = map (\ v -> ExtFORMULA $ Ranged ( Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name (gnRestrName s) (Pred_type [s] nullRange) nullRange ) [Qual_var v s nullRange] nullRange ) ) nullRange) trueForm) nullRange) varS in conjunct restrs) vars let sen' = mkImpl (foldr1 (\ sen1 sen2 -> conjunct [sen1, sen2]) h) trSen return $ Quantification q vars sen' nullRange Existential -> do trSen <- mapCASLSenAux sen let h = map (\ (Var_decl varS s _) -> let restrs = map (\ v -> ExtFORMULA $ Ranged ( Dlformula Diamond (Ranged (Call (Predication (Qual_pred_name (gnRestrName s) (Pred_type [s] nullRange) nullRange ) [Qual_var v s nullRange] nullRange ) ) nullRange) trueForm) nullRange) varS in conjunct restrs) vars let sen' = conjunct [foldr1 (\ sen1 sen2 -> conjunct [sen1, sen2]) h, trSen] return $ Quantification q vars sen' nullRange Unique_existential -> fail "nyi Unique_existential" _ -> fail "Comorphisms.CASL2VSERefine.mapCASLSenAux" mapCASLTerm :: Int -> TERM () -> State (Int, VarSet) Program mapCASLTerm n t = case t of Qual_var v s _ps -> return $ Ranged (Assign (genNumVar "x" n) (Qual_var v s nullRange)) nullRange Application opsym as _qs -> do indexes <- mapM (freshIndex . sortOfTerm) as let xvars = map (\ (ti, i) -> Qual_var (genNumVar "x" i) (sortOfTerm ti) nullRange ) $ zip as indexes prgs <- mapM (\ (ti, i) -> mapCASLTerm i ti) $ zip as indexes let asgn = if not $ null prgs then foldr1 (\ p1 p2 -> Ranged (Seq p1 p2) nullRange) prgs else Ranged Skip nullRange case opsym of Op_name _ -> fail "must be qualified" Qual_op_name oName (Op_type _ args res _) _ -> case args of [] -> return $ Ranged (Assign (genNumVar "x" n) (Application (Qual_op_name (mkGenName oName) (Op_type Partial args res nullRange) nullRange ) xvars nullRange)) nullRange _ -> return $ Ranged (Seq asgn (Ranged (Assign (genNumVar "x" n) (Application (Qual_op_name (mkGenName oName) (Op_type Partial args res nullRange) nullRange ) xvars nullRange)) nullRange)) nullRange _ -> fail "nyi term" freshIndex :: SORT -> State (Int, VarSet) Int freshIndex ss = do (i, s) <- get let v = genNumVar "x" i put (i + 1, Set.insert (v, ss) s) return i
spechub/Hets
Comorphisms/CASL2VSERefine.hs
gpl-2.0
38,394
0
49
21,581
8,064
4,121
3,943
830
14
module Ex13 where f 1 x = 0.0 f n x = (n*x) + f (n-1) x
roberth/uu-helium
test/typeerrors/Edinburgh/Ex13.hs
gpl-3.0
57
0
8
18
47
25
22
3
1
<?xml version="1.0" encoding='ISO-8859-1' ?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 1.0//EN" "http://java.sun.com/products/javahelp/helpset_1_0.dtd"> <helpset version="2.0"> <title>BEW's help menu</title> <maps> <!-- Default page --> <homeID>index</homeID> <!-- Map to use --> <mapref location="map_file.xml"/> </maps> <!-- Our Views --> <!-- Content Table, Toc File --> <view> <name>Contents Table</name> <label>Contents Table</label> <type>javax.help.TOCView</type> <data>toc.xml</data> </view> <!-- Index File --> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <!-- Search File --> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> </helpset>
sing-group/BEW
plugins_src/bew/help/help_set.hs
gpl-3.0
1,036
78
52
233
370
190
180
-1
-1
{-# OPTIONS_GHC -F -pgmF doctest-discover -optF test/config.json #-}
adarqui/ToyBox
haskell/haskell/stm/test/doctests.hs
gpl-3.0
69
0
2
8
3
2
1
1
0
{-# 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.AutoScaling.EnterStandby -- 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. -- | Moves the specified instances into 'Standby' mode. -- -- For more information, see <http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/AutoScalingInServiceState.html Auto Scaling InService State> in the /Auto ScalingDeveloper Guide/. -- -- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_EnterStandby.html> module Network.AWS.AutoScaling.EnterStandby ( -- * Request EnterStandby -- ** Request constructor , enterStandby -- ** Request lenses , esAutoScalingGroupName , esInstanceIds , esShouldDecrementDesiredCapacity -- * Response , EnterStandbyResponse -- ** Response constructor , enterStandbyResponse -- ** Response lenses , esr1Activities ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.AutoScaling.Types import qualified GHC.Exts data EnterStandby = EnterStandby { _esAutoScalingGroupName :: Text , _esInstanceIds :: List "member" Text , _esShouldDecrementDesiredCapacity :: Bool } deriving (Eq, Ord, Read, Show) -- | 'EnterStandby' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'esAutoScalingGroupName' @::@ 'Text' -- -- * 'esInstanceIds' @::@ ['Text'] -- -- * 'esShouldDecrementDesiredCapacity' @::@ 'Bool' -- enterStandby :: Text -- ^ 'esAutoScalingGroupName' -> Bool -- ^ 'esShouldDecrementDesiredCapacity' -> EnterStandby enterStandby p1 p2 = EnterStandby { _esAutoScalingGroupName = p1 , _esShouldDecrementDesiredCapacity = p2 , _esInstanceIds = mempty } -- | The name of the Auto Scaling group. esAutoScalingGroupName :: Lens' EnterStandby Text esAutoScalingGroupName = lens _esAutoScalingGroupName (\s a -> s { _esAutoScalingGroupName = a }) -- | One or more instances to move into 'Standby' mode. You must specify at least -- one instance ID. esInstanceIds :: Lens' EnterStandby [Text] esInstanceIds = lens _esInstanceIds (\s a -> s { _esInstanceIds = a }) . _List -- | Specifies whether the instances moved to 'Standby' mode count as part of the -- Auto Scaling group's desired capacity. If set, the desired capacity for the -- Auto Scaling group decrements by the number of instances moved to 'Standby' -- mode. esShouldDecrementDesiredCapacity :: Lens' EnterStandby Bool esShouldDecrementDesiredCapacity = lens _esShouldDecrementDesiredCapacity (\s a -> s { _esShouldDecrementDesiredCapacity = a }) newtype EnterStandbyResponse = EnterStandbyResponse { _esr1Activities :: List "member" Activity } deriving (Eq, Read, Show, Monoid, Semigroup) instance GHC.Exts.IsList EnterStandbyResponse where type Item EnterStandbyResponse = Activity fromList = EnterStandbyResponse . GHC.Exts.fromList toList = GHC.Exts.toList . _esr1Activities -- | 'EnterStandbyResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'esr1Activities' @::@ ['Activity'] -- enterStandbyResponse :: EnterStandbyResponse enterStandbyResponse = EnterStandbyResponse { _esr1Activities = mempty } -- | The activities related to moving instances into 'Standby' mode. esr1Activities :: Lens' EnterStandbyResponse [Activity] esr1Activities = lens _esr1Activities (\s a -> s { _esr1Activities = a }) . _List instance ToPath EnterStandby where toPath = const "/" instance ToQuery EnterStandby where toQuery EnterStandby{..} = mconcat [ "AutoScalingGroupName" =? _esAutoScalingGroupName , "InstanceIds" =? _esInstanceIds , "ShouldDecrementDesiredCapacity" =? _esShouldDecrementDesiredCapacity ] instance ToHeaders EnterStandby instance AWSRequest EnterStandby where type Sv EnterStandby = AutoScaling type Rs EnterStandby = EnterStandbyResponse request = post "EnterStandby" response = xmlResponse instance FromXML EnterStandbyResponse where parseXML = withElement "EnterStandbyResult" $ \x -> EnterStandbyResponse <$> x .@? "Activities" .!@ mempty
romanb/amazonka
amazonka-autoscaling/gen/Network/AWS/AutoScaling/EnterStandby.hs
mpl-2.0
5,149
0
10
1,093
626
379
247
73
1
f :: Int -> [Int] -> [Int] f n arr = [x | x <- arr, x < n] main = do n <- readLn :: IO Int inputdata <- getContents let numbers = map read (lines inputdata) :: [Int] putStrLn . unlines $ (map show . f n) numbers
EdisonAlgorithms/HackerRank
practice/fp/intro/fp-filter-array/fp-filter-array.hs
mit
242
0
12
80
127
63
64
8
1
main = 3 --> 4 (-->) x y = x + y
roberth/uu-helium
test/simple/parser/MaximalMunch.hs
gpl-3.0
34
0
5
13
26
14
12
2
1
{-# language DeriveDataTypeable #-} module Base.Configuration.Controls ( Controls, leftKey, rightKey, upKey, downKey, jumpKey, contextKey, KeysHint(..), isFullscreenSwapShortcut, keysContext, -- * menu isMenuUp, isMenuDown, isMenuConfirmation, isMenuBack, menuKeysHint, menuConfirmationKeysHint, scrollableKeysHint, gameNikkiKeysHint, gameTerminalKeysHint, gameRobotKeysHint, -- * text fields isTextFieldConfirmation, isTextFieldBack, -- * game isGameLeftHeld, isGameRightHeld, isGameJumpHeld, isGameLeftPressed, isGameRightPressed, isGameJumpPressed, isGameContextPressed, isGameBackPressed, -- * terminals isTerminalConfirmationPressed, -- * robots isRobotActionHeld, isRobotActionPressed, isRobotBackPressed, -- * editor isEditorA, isEditorB, ) where import Data.Data import Data.Initial import Data.Accessor import Data.Char (toUpper) import Control.Arrow import System.Info import Graphics.Qt import Utils import Base.Types.Events import Base.Prose import Base.Prose.Template -- | Configuration of controls -- Uses versioned constructors (is saved as part of the configuration). data Controls = Controls_0 { leftKey_ :: (Key, String), rightKey_ :: (Key, String), upKey_ :: (Key, String), downKey_ :: (Key, String), jumpKey_ :: (Key, String), contextKey_ :: (Key, String) } deriving (Show, Read, Typeable, Data) leftKey, rightKey, upKey, downKey, jumpKey, contextKey :: Accessor Controls (Key, String) leftKey = accessor leftKey_ (\ a r -> r{leftKey_ = a}) rightKey = accessor rightKey_ (\ a r -> r{rightKey_ = a}) upKey = accessor upKey_ (\ a r -> r{upKey_ = a}) downKey = accessor downKey_ (\ a r -> r{downKey_ = a}) jumpKey = accessor jumpKey_ (\ a r -> r{jumpKey_ = a}) contextKey = accessor contextKey_ (\ a r -> r{contextKey_ = a}) instance Initial Controls where initial = Controls_0 { leftKey_ = mkKey LeftArrow, rightKey_ = mkKey RightArrow, upKey_ = mkKey UpArrow, downKey_ = mkKey DownArrow, jumpKey_ = initialJumpKey, contextKey_ = mkKey Shift } where mkKey k = (k, keyDescription k (error "please don't use the given key text")) initialJumpKey = case System.Info.os of "darwin" -> mkKey Space -- Ctrl+Arrows clashes with default shortcuts for virtual desktops on osx. _ -> mkKey Ctrl -- | represents hints for keys for user readable output data KeysHint = KeysHint {keysHint :: [(Prose, Prose)]} | PressAnyKey -- * context for templates keysContext :: Controls -> [(String, String)] keysContext controls = map (second (mkKeyString controls)) $ ( ("leftKey", leftKey) : ("rightKey", rightKey) : ("upKey", upKey) : ("downKey", downKey) : ("jumpKey", jumpKey) : ("contextKey", contextKey) : []) mkKeyString :: Controls -> Accessor Controls (Key, String) -> String mkKeyString controls acc = map toUpper $ snd (controls ^. acc) -- * internals isKey :: Key -> (Button -> Bool) isKey a (KeyboardButton b _ _) = a == b isKey _ _ = False isKeyWS :: (Key, String) -> (Button -> Bool) isKeyWS = isKey . fst -- ** externals isFullscreenSwapShortcut :: Button -> Bool isFullscreenSwapShortcut k = ((isKey Enter k || isKey Return k) && fany (== AltModifier) (keyModifiers k)) || (isKey F11 k) -- * Menu isMenuUp, isMenuDown, isMenuConfirmation, isMenuBack :: Controls -> Button -> Bool isMenuUp _ = isKey UpArrow isMenuDown _ = isKey DownArrow isMenuConfirmation controls k = isKey Return k || isKey Enter k || isConfiguredMenuKey controls jumpKey k isMenuBack controls k = isKey Escape k || isConfiguredMenuKey controls contextKey k -- | Returns, if a given key is the key specified by the given Controls-selector -- AND if it does not shadow any other menu keys. isConfiguredMenuKey :: Controls -> (Accessor Controls (Key, String)) -> Button -> Bool isConfiguredMenuKey controls selector b = not (shadowsMenuButton b) && isKeyWS (controls ^. selector) b shadowsMenuButton :: Button -> Bool shadowsMenuButton (KeyboardButton k _ _) = k `elem` ( UpArrow : DownArrow : Return : Enter : Escape : []) -- | user readable hints which keys to use menuKeysHint :: Bool -> KeysHint menuKeysHint acceptsBackKey = KeysHint ( (p "select", p "↑↓") : keysHint (menuConfirmationKeysHint (p "confirm")) ++ (if acceptsBackKey then [(p "back", p "esc")] else []) ++ []) menuConfirmationKeysHint :: Prose -> KeysHint menuConfirmationKeysHint text = KeysHint ( (text, p "⏎") : []) -- | keys hint for Base.Renderable.Scrollable scrollableKeysHint :: KeysHint scrollableKeysHint = KeysHint ( (p "scroll", pv "↑↓") : (p "back", p "any key") : []) gameNikkiKeysHint :: Controls -> KeysHint gameNikkiKeysHint controls = KeysHint $ map (second (substitute (keysContext controls))) $ ( (p "walk", p "$leftKey$rightKey") : (p "jump", p "$jumpKey") : (p "context key", p "$contextKey") : []) gameTerminalKeysHint :: Controls -> KeysHint gameTerminalKeysHint controls = KeysHint $ map (second (substitute (keysContext controls))) $ ( (p "select", p "$leftKey$rightKey") : (p "confirm", p "$jumpKey") : []) gameRobotKeysHint :: Controls -> KeysHint gameRobotKeysHint controls = KeysHint $ map (second (substitute (keysContext controls))) $ ( (p "controls", p "$leftKey$rightKey$upKey$downKey and $jumpKey") : (p "back", p "$contextKey") : []) -- * text fields isTextFieldBack, isTextFieldConfirmation :: Button -> Bool isTextFieldBack = isKey Escape isTextFieldConfirmation k = isKey Return k || isKey Enter k -- * game isGameLeftHeld, isGameRightHeld, isGameJumpHeld :: Controls -> ControlData -> Bool isGameLeftHeld controls = fany (isKeyWS (controls ^. leftKey)) . held isGameRightHeld controls = fany (isKeyWS (controls ^. rightKey)) . held isGameJumpHeld controls = fany (isKeyWS (controls ^. jumpKey)) . held isGameLeftPressed, isGameRightPressed, isGameJumpPressed, isGameContextPressed, isGameBackPressed :: Controls -> ControlData -> Bool isGameLeftPressed controls = fany (isKeyWS (controls ^. leftKey)) . pressed isGameRightPressed controls = fany (isKeyWS (controls ^. rightKey)) . pressed isGameJumpPressed controls = fany (isKeyWS (controls ^. jumpKey)) . pressed isGameContextPressed controls = fany (isKeyWS (controls ^. contextKey)) . pressed isGameBackPressed _ = fany (isKey Escape) . pressed -- * terminals isTerminalConfirmationPressed :: Controls -> ControlData -> Bool isTerminalConfirmationPressed controls = fany is . pressed where is k = isKeyWS (controls ^. jumpKey) k || isMenuConfirmation controls k -- * robots (in game) isRobotActionHeld :: Controls -> ControlData -> Bool isRobotActionHeld controls = fany (isKeyWS (controls ^. jumpKey)) . held isRobotActionPressed, isRobotBackPressed :: Controls -> ControlData -> Bool isRobotActionPressed controls = fany (isKeyWS (controls ^. jumpKey)) . pressed isRobotBackPressed controls = fany (isKeyWS (controls ^. contextKey)) . pressed -- * editor -- Most of the editor keys are hardcoded. isEditorA, isEditorB :: Key -> Bool isEditorA = (== Ctrl) isEditorB = (== Shift)
geocurnoff/nikki
src/Base/Configuration/Controls.hs
lgpl-3.0
7,440
0
14
1,571
2,130
1,179
951
183
2
{-# OPTIONS -fno-warn-type-defaults #-} -- ---------------------------------------------------------------------------- -- | Handle conversion of CmmProc to LLVM code. -- {-# LANGUAGE GADTs #-} module LlvmCodeGen.CodeGen ( genLlvmProc ) where #include "HsVersions.h" import Llvm import LlvmCodeGen.Base import LlvmCodeGen.Regs import BlockId import CodeGen.Platform ( activeStgRegs, callerSaves ) import CLabel import Cmm import PprCmm import CmmUtils import Hoopl import DynFlags import FastString import ForeignCall import Outputable hiding ( panic, pprPanic ) import qualified Outputable import Platform import OrdList import UniqSupply import Unique import Data.List ( nub ) import Data.Maybe ( catMaybes ) type LlvmStatements = OrdList LlvmStatement -- ----------------------------------------------------------------------------- -- | Top-level of the LLVM proc Code generator -- genLlvmProc :: RawCmmDecl -> LlvmM [LlvmCmmDecl] genLlvmProc (CmmProc infos lbl live graph) = do let blocks = toBlockListEntryFirstFalseFallthrough graph (lmblocks, lmdata) <- basicBlocksCodeGen live blocks let info = mapLookup (g_entry graph) infos proc = CmmProc info lbl live (ListGraph lmblocks) return (proc:lmdata) genLlvmProc _ = panic "genLlvmProc: case that shouldn't reach here!" -- ----------------------------------------------------------------------------- -- * Block code generation -- -- | Generate code for a list of blocks that make up a complete -- procedure. The first block in the list is exepected to be the entry -- point and will get the prologue. basicBlocksCodeGen :: LiveGlobalRegs -> [CmmBlock] -> LlvmM ([LlvmBasicBlock], [LlvmCmmDecl]) basicBlocksCodeGen _ [] = panic "no entry block!" basicBlocksCodeGen live (entryBlock:cmmBlocks) = do (prologue, prologueTops) <- funPrologue live (entryBlock:cmmBlocks) -- Generate code (BasicBlock bid entry, entryTops) <- basicBlockCodeGen entryBlock (blocks, topss) <- fmap unzip $ mapM basicBlockCodeGen cmmBlocks -- Compose let entryBlock = BasicBlock bid (fromOL prologue ++ entry) return (entryBlock : blocks, prologueTops ++ entryTops ++ concat topss) -- | Generate code for one block basicBlockCodeGen :: CmmBlock -> LlvmM ( LlvmBasicBlock, [LlvmCmmDecl] ) basicBlockCodeGen block = do let (CmmEntry id, nodes, tail) = blockSplit block (mid_instrs, top) <- stmtsToInstrs $ blockToList nodes (tail_instrs, top') <- stmtToInstrs tail let instrs = fromOL (mid_instrs `appOL` tail_instrs) return (BasicBlock id instrs, top' ++ top) -- ----------------------------------------------------------------------------- -- * CmmNode code generation -- -- A statement conversion return data. -- * LlvmStatements: The compiled LLVM statements. -- * LlvmCmmDecl: Any global data needed. type StmtData = (LlvmStatements, [LlvmCmmDecl]) -- | Convert a list of CmmNode's to LlvmStatement's stmtsToInstrs :: [CmmNode e x] -> LlvmM StmtData stmtsToInstrs stmts = do (instrss, topss) <- fmap unzip $ mapM stmtToInstrs stmts return (concatOL instrss, concat topss) -- | Convert a CmmStmt to a list of LlvmStatement's stmtToInstrs :: CmmNode e x -> LlvmM StmtData stmtToInstrs stmt = case stmt of CmmComment _ -> return (nilOL, []) -- nuke comments CmmAssign reg src -> genAssign reg src CmmStore addr src -> genStore addr src CmmBranch id -> genBranch id CmmCondBranch arg true false -> genCondBranch arg true false CmmSwitch arg ids -> genSwitch arg ids -- Foreign Call CmmUnsafeForeignCall target res args -> genCall target res args -- Tail call CmmCall { cml_target = arg, cml_args_regs = live } -> genJump arg live _ -> panic "Llvm.CodeGen.stmtToInstrs" -- | Wrapper function to declare an instrinct function by function type getInstrinct2 :: LMString -> LlvmType -> LlvmM ExprData getInstrinct2 fname fty@(LMFunction funSig) = do let fv = LMGlobalVar fname fty (funcLinkage funSig) Nothing Nothing Constant fn <- funLookup fname tops <- case fn of Just _ -> return [] Nothing -> do funInsert fname fty return [CmmData Data [([],[fty])]] return (fv, nilOL, tops) getInstrinct2 _ _ = error "getInstrinct2: Non-function type!" -- | Declares an instrinct function by return and parameter types getInstrinct :: LMString -> LlvmType -> [LlvmType] -> LlvmM ExprData getInstrinct fname retTy parTys = let funSig = LlvmFunctionDecl fname ExternallyVisible CC_Ccc retTy FixedArgs (tysToParams parTys) Nothing fty = LMFunction funSig in getInstrinct2 fname fty -- | Memory barrier instruction for LLVM >= 3.0 barrier :: LlvmM StmtData barrier = do let s = Fence False SyncSeqCst return (unitOL s, []) -- | Memory barrier instruction for LLVM < 3.0 oldBarrier :: LlvmM StmtData oldBarrier = do (fv, _, tops) <- getInstrinct (fsLit "llvm.memory.barrier") LMVoid [i1, i1, i1, i1, i1] let args = [lmTrue, lmTrue, lmTrue, lmTrue, lmTrue] let s1 = Expr $ Call StdCall fv args llvmStdFunAttrs return (unitOL s1, tops) where lmTrue :: LlvmVar lmTrue = mkIntLit i1 (-1) -- | Foreign Calls genCall :: ForeignTarget -> [CmmFormal] -> [CmmActual] -> LlvmM StmtData -- Write barrier needs to be handled specially as it is implemented as an LLVM -- intrinsic function. genCall (PrimTarget MO_WriteBarrier) _ _ = do platform <- getLlvmPlatform ver <- getLlvmVer case () of _ | platformArch platform `elem` [ArchX86, ArchX86_64, ArchSPARC] -> return (nilOL, []) | ver > 29 -> barrier | otherwise -> oldBarrier genCall (PrimTarget MO_Touch) _ _ = return (nilOL, []) genCall (PrimTarget (MO_UF_Conv w)) [dst] [e] = do dstV <- getCmmReg (CmmLocal dst) let ty = cmmToLlvmType $ localRegType dst width = widthToLlvmFloat w castV <- mkLocalVar ty (ve, stmts, top) <- exprToVar e let stmt3 = Assignment castV $ Cast LM_Uitofp ve width stmt4 = Store castV dstV return (stmts `snocOL` stmt3 `snocOL` stmt4, top) genCall (PrimTarget (MO_UF_Conv _)) [_] args = panic $ "genCall: Too many arguments to MO_UF_Conv. " ++ "Can only handle 1, given" ++ show (length args) ++ "." -- Handle prefetching data genCall t@(PrimTarget (MO_Prefetch_Data localityInt)) [] args | 0 <= localityInt && localityInt <= 3 = do ver <- getLlvmVer let argTy | ver <= 29 = [i8Ptr, i32, i32] | otherwise = [i8Ptr, i32, i32, i32] funTy = \name -> LMFunction $ LlvmFunctionDecl name ExternallyVisible CC_Ccc LMVoid FixedArgs (tysToParams argTy) Nothing let (_, arg_hints) = foreignTargetHints t let args_hints' = zip args arg_hints (argVars, stmts1, top1) <- arg_vars args_hints' ([], nilOL, []) (fptr, stmts2, top2) <- getFunPtr funTy t (argVars', stmts3) <- castVars $ zip argVars argTy trash <- getTrashStmts let argSuffix | ver <= 29 = [mkIntLit i32 0, mkIntLit i32 localityInt] | otherwise = [mkIntLit i32 0, mkIntLit i32 localityInt, mkIntLit i32 1] call = Expr $ Call StdCall fptr (argVars' ++ argSuffix) [] stmts = stmts1 `appOL` stmts2 `appOL` stmts3 `appOL` trash `snocOL` call return (stmts, top1 ++ top2) | otherwise = panic $ "prefetch locality level integer must be between 0 and 3, given: " ++ (show localityInt) -- Handle PopCnt and BSwap that need to only convert arg and return types genCall t@(PrimTarget (MO_PopCnt w)) dsts args = genCallSimpleCast w t dsts args genCall t@(PrimTarget (MO_BSwap w)) dsts args = genCallSimpleCast w t dsts args -- Handle memcpy function specifically since llvm's intrinsic version takes -- some extra parameters. genCall t@(PrimTarget op) [] args' | op == MO_Memcpy || op == MO_Memset || op == MO_Memmove = do ver <- getLlvmVer dflags <- getDynFlags let (args, alignVal) = splitAlignVal args' (isVolTy, isVolVal) | ver >= 28 = ([i1], [mkIntLit i1 0]) | otherwise = ([], []) argTy | op == MO_Memset = [i8Ptr, i8, llvmWord dflags, i32] ++ isVolTy | otherwise = [i8Ptr, i8Ptr, llvmWord dflags, i32] ++ isVolTy funTy = \name -> LMFunction $ LlvmFunctionDecl name ExternallyVisible CC_Ccc LMVoid FixedArgs (tysToParams argTy) Nothing let (_, arg_hints) = foreignTargetHints t let args_hints = zip args arg_hints (argVars, stmts1, top1) <- arg_vars args_hints ([], nilOL, []) (fptr, stmts2, top2) <- getFunPtr funTy t (argVars', stmts3) <- castVars $ zip argVars argTy stmts4 <- getTrashStmts let arguments = argVars' ++ (alignVal:isVolVal) call = Expr $ Call StdCall fptr arguments [] stmts = stmts1 `appOL` stmts2 `appOL` stmts3 `appOL` stmts4 `snocOL` call return (stmts, top1 ++ top2) where splitAlignVal xs = (init xs, extractLit $ last xs) -- Fix for trac #6158. Since LLVM 3.1, opt fails when given anything other -- than a direct constant (i.e. 'i32 8') as the alignment argument for the -- memcpy & co llvm intrinsic functions. So we handle this directly now. extractLit (CmmLit (CmmInt i _)) = mkIntLit i32 i extractLit _other = trace ("WARNING: Non constant alignment value given" ++ " for memcpy! Please report to GHC developers") mkIntLit i32 0 -- Handle all other foreign calls and prim ops. genCall target res args = do dflags <- getDynFlags -- parameter types let arg_type (_, AddrHint) = i8Ptr -- cast pointers to i8*. Llvm equivalent of void* arg_type (expr, _) = cmmToLlvmType $ cmmExprType dflags expr -- ret type let ret_type [] = LMVoid ret_type [(_, AddrHint)] = i8Ptr ret_type [(reg, _)] = cmmToLlvmType $ localRegType reg ret_type t = panic $ "genCall: Too many return values! Can only handle" ++ " 0 or 1, given " ++ show (length t) ++ "." -- extract Cmm call convention, and translate to LLVM call convention platform <- getLlvmPlatform let lmconv = case target of ForeignTarget _ (ForeignConvention conv _ _ _) -> case conv of StdCallConv -> case platformArch platform of ArchX86 -> CC_X86_Stdcc ArchX86_64 -> CC_X86_Stdcc _ -> CC_Ccc CCallConv -> CC_Ccc CApiConv -> CC_Ccc PrimCallConv -> panic "LlvmCodeGen.CodeGen.genCall: PrimCallConv" JavaScriptCallConv -> panic "LlvmCodeGen.CodeGen.genCall: JavaScriptCallConv" PrimTarget _ -> CC_Ccc {- CC_Ccc of the possibilities here are a worry with the use of a custom calling convention for passing STG args. In practice the more dangerous combinations (e.g StdCall + llvmGhcCC) don't occur. The native code generator only handles StdCall and CCallConv. -} -- call attributes let fnAttrs | never_returns = NoReturn : llvmStdFunAttrs | otherwise = llvmStdFunAttrs never_returns = case target of ForeignTarget _ (ForeignConvention _ _ _ CmmNeverReturns) -> True _ -> False -- fun type let (res_hints, arg_hints) = foreignTargetHints target let args_hints = zip args arg_hints let ress_hints = zip res res_hints let ccTy = StdCall -- tail calls should be done through CmmJump let retTy = ret_type ress_hints let argTy = tysToParams $ map arg_type args_hints let funTy = \name -> LMFunction $ LlvmFunctionDecl name ExternallyVisible lmconv retTy FixedArgs argTy (llvmFunAlign dflags) (argVars, stmts1, top1) <- arg_vars args_hints ([], nilOL, []) (fptr, stmts2, top2) <- getFunPtr funTy target let retStmt | ccTy == TailCall = unitOL $ Return Nothing | never_returns = unitOL $ Unreachable | otherwise = nilOL stmts3 <- getTrashStmts let stmts = stmts1 `appOL` stmts2 `appOL` stmts3 -- make the actual call case retTy of LMVoid -> do let s1 = Expr $ Call ccTy fptr argVars fnAttrs let allStmts = stmts `snocOL` s1 `appOL` retStmt return (allStmts, top1 ++ top2) _ -> do (v1, s1) <- doExpr retTy $ Call ccTy fptr argVars fnAttrs -- get the return register let ret_reg [reg] = reg ret_reg t = panic $ "genCall: Bad number of registers! Can only handle" ++ " 1, given " ++ show (length t) ++ "." let creg = ret_reg res vreg <- getCmmReg (CmmLocal creg) let allStmts = stmts `snocOL` s1 if retTy == pLower (getVarType vreg) then do let s2 = Store v1 vreg return (allStmts `snocOL` s2 `appOL` retStmt, top1 ++ top2) else do let ty = pLower $ getVarType vreg let op = case ty of vt | isPointer vt -> LM_Bitcast | isInt vt -> LM_Ptrtoint | otherwise -> panic $ "genCall: CmmReg bad match for" ++ " returned type!" (v2, s2) <- doExpr ty $ Cast op v1 ty let s3 = Store v2 vreg return (allStmts `snocOL` s2 `snocOL` s3 `appOL` retStmt, top1 ++ top2) -- Handle simple function call that only need simple type casting, of the form: -- truncate arg >>= \a -> call(a) >>= zext -- -- since GHC only really has i32 and i64 types and things like Word8 are backed -- by an i32 and just present a logical i8 range. So we must handle conversions -- from i32 to i8 explicitly as LLVM is strict about types. genCallSimpleCast :: Width -> ForeignTarget -> [CmmFormal] -> [CmmActual] -> LlvmM StmtData genCallSimpleCast w t@(PrimTarget op) [dst] args = do let width = widthToLlvmInt w dstTy = cmmToLlvmType $ localRegType dst fname <- cmmPrimOpFunctions op (fptr, _, top3) <- getInstrinct fname width [width] dstV <- getCmmReg (CmmLocal dst) let (_, arg_hints) = foreignTargetHints t let args_hints = zip args arg_hints (argsV, stmts2, top2) <- arg_vars args_hints ([], nilOL, []) (argsV', stmts4) <- castVars $ zip argsV [width] (retV, s1) <- doExpr width $ Call StdCall fptr argsV' [] ([retV'], stmts5) <- castVars [(retV,dstTy)] let s2 = Store retV' dstV let stmts = stmts2 `appOL` stmts4 `snocOL` s1 `appOL` stmts5 `snocOL` s2 return (stmts, top2 ++ top3) genCallSimpleCast _ _ dsts _ = panic ("genCallSimpleCast: " ++ show (length dsts) ++ " dsts") -- | Create a function pointer from a target. getFunPtr :: (LMString -> LlvmType) -> ForeignTarget -> LlvmM ExprData getFunPtr funTy targ = case targ of ForeignTarget (CmmLit (CmmLabel lbl)) _ -> do name <- strCLabel_llvm lbl getHsFunc' name (funTy name) ForeignTarget expr _ -> do (v1, stmts, top) <- exprToVar expr dflags <- getDynFlags let fty = funTy $ fsLit "dynamic" cast = case getVarType v1 of ty | isPointer ty -> LM_Bitcast ty | isInt ty -> LM_Inttoptr ty -> panic $ "genCall: Expr is of bad type for function" ++ " call! (" ++ showSDoc dflags (ppr ty) ++ ")" (v2,s1) <- doExpr (pLift fty) $ Cast cast v1 (pLift fty) return (v2, stmts `snocOL` s1, top) PrimTarget mop -> do name <- cmmPrimOpFunctions mop let fty = funTy name getInstrinct2 name fty -- | Conversion of call arguments. arg_vars :: [(CmmActual, ForeignHint)] -> ([LlvmVar], LlvmStatements, [LlvmCmmDecl]) -> LlvmM ([LlvmVar], LlvmStatements, [LlvmCmmDecl]) arg_vars [] (vars, stmts, tops) = return (vars, stmts, tops) arg_vars ((e, AddrHint):rest) (vars, stmts, tops) = do (v1, stmts', top') <- exprToVar e dflags <- getDynFlags let op = case getVarType v1 of ty | isPointer ty -> LM_Bitcast ty | isInt ty -> LM_Inttoptr a -> panic $ "genCall: Can't cast llvmType to i8*! (" ++ showSDoc dflags (ppr a) ++ ")" (v2, s1) <- doExpr i8Ptr $ Cast op v1 i8Ptr arg_vars rest (vars ++ [v2], stmts `appOL` stmts' `snocOL` s1, tops ++ top') arg_vars ((e, _):rest) (vars, stmts, tops) = do (v1, stmts', top') <- exprToVar e arg_vars rest (vars ++ [v1], stmts `appOL` stmts', tops ++ top') -- | Cast a collection of LLVM variables to specific types. castVars :: [(LlvmVar, LlvmType)] -> LlvmM ([LlvmVar], LlvmStatements) castVars vars = do done <- mapM (uncurry castVar) vars let (vars', stmts) = unzip done return (vars', toOL stmts) -- | Cast an LLVM variable to a specific type, panicing if it can't be done. castVar :: LlvmVar -> LlvmType -> LlvmM (LlvmVar, LlvmStatement) castVar v t | getVarType v == t = return (v, Nop) | otherwise = do dflags <- getDynFlags let op = case (getVarType v, t) of (LMInt n, LMInt m) -> if n < m then LM_Sext else LM_Trunc (vt, _) | isFloat vt && isFloat t -> if llvmWidthInBits dflags vt < llvmWidthInBits dflags t then LM_Fpext else LM_Fptrunc (vt, _) | isInt vt && isFloat t -> LM_Sitofp (vt, _) | isFloat vt && isInt t -> LM_Fptosi (vt, _) | isInt vt && isPointer t -> LM_Inttoptr (vt, _) | isPointer vt && isInt t -> LM_Ptrtoint (vt, _) | isPointer vt && isPointer t -> LM_Bitcast (vt, _) | isVector vt && isVector t -> LM_Bitcast (vt, _) -> panic $ "castVars: Can't cast this type (" ++ showSDoc dflags (ppr vt) ++ ") to (" ++ showSDoc dflags (ppr t) ++ ")" doExpr t $ Cast op v t -- | Decide what C function to use to implement a CallishMachOp cmmPrimOpFunctions :: CallishMachOp -> LlvmM LMString cmmPrimOpFunctions mop = do ver <- getLlvmVer dflags <- getDynFlags let intrinTy1 = (if ver >= 28 then "p0i8.p0i8." else "") ++ showSDoc dflags (ppr $ llvmWord dflags) intrinTy2 = (if ver >= 28 then "p0i8." else "") ++ showSDoc dflags (ppr $ llvmWord dflags) unsupported = panic ("cmmPrimOpFunctions: " ++ show mop ++ " not supported here") return $ case mop of MO_F32_Exp -> fsLit "expf" MO_F32_Log -> fsLit "logf" MO_F32_Sqrt -> fsLit "llvm.sqrt.f32" MO_F32_Pwr -> fsLit "llvm.pow.f32" MO_F32_Sin -> fsLit "llvm.sin.f32" MO_F32_Cos -> fsLit "llvm.cos.f32" MO_F32_Tan -> fsLit "tanf" MO_F32_Asin -> fsLit "asinf" MO_F32_Acos -> fsLit "acosf" MO_F32_Atan -> fsLit "atanf" MO_F32_Sinh -> fsLit "sinhf" MO_F32_Cosh -> fsLit "coshf" MO_F32_Tanh -> fsLit "tanhf" MO_F64_Exp -> fsLit "exp" MO_F64_Log -> fsLit "log" MO_F64_Sqrt -> fsLit "llvm.sqrt.f64" MO_F64_Pwr -> fsLit "llvm.pow.f64" MO_F64_Sin -> fsLit "llvm.sin.f64" MO_F64_Cos -> fsLit "llvm.cos.f64" MO_F64_Tan -> fsLit "tan" MO_F64_Asin -> fsLit "asin" MO_F64_Acos -> fsLit "acos" MO_F64_Atan -> fsLit "atan" MO_F64_Sinh -> fsLit "sinh" MO_F64_Cosh -> fsLit "cosh" MO_F64_Tanh -> fsLit "tanh" MO_Memcpy -> fsLit $ "llvm.memcpy." ++ intrinTy1 MO_Memmove -> fsLit $ "llvm.memmove." ++ intrinTy1 MO_Memset -> fsLit $ "llvm.memset." ++ intrinTy2 (MO_PopCnt w) -> fsLit $ "llvm.ctpop." ++ showSDoc dflags (ppr $ widthToLlvmInt w) (MO_BSwap w) -> fsLit $ "llvm.bswap." ++ showSDoc dflags (ppr $ widthToLlvmInt w) (MO_Prefetch_Data _ )-> fsLit "llvm.prefetch" MO_S_QuotRem {} -> unsupported MO_U_QuotRem {} -> unsupported MO_U_QuotRem2 {} -> unsupported MO_Add2 {} -> unsupported MO_U_Mul2 {} -> unsupported MO_WriteBarrier -> unsupported MO_Touch -> unsupported MO_UF_Conv _ -> unsupported -- | Tail function calls genJump :: CmmExpr -> [GlobalReg] -> LlvmM StmtData -- Call to known function genJump (CmmLit (CmmLabel lbl)) live = do (vf, stmts, top) <- getHsFunc live lbl (stgRegs, stgStmts) <- funEpilogue live let s1 = Expr $ Call TailCall vf stgRegs llvmStdFunAttrs let s2 = Return Nothing return (stmts `appOL` stgStmts `snocOL` s1 `snocOL` s2, top) -- Call to unknown function / address genJump expr live = do fty <- llvmFunTy live (vf, stmts, top) <- exprToVar expr dflags <- getDynFlags let cast = case getVarType vf of ty | isPointer ty -> LM_Bitcast ty | isInt ty -> LM_Inttoptr ty -> panic $ "genJump: Expr is of bad type for function call! (" ++ showSDoc dflags (ppr ty) ++ ")" (v1, s1) <- doExpr (pLift fty) $ Cast cast vf (pLift fty) (stgRegs, stgStmts) <- funEpilogue live let s2 = Expr $ Call TailCall v1 stgRegs llvmStdFunAttrs let s3 = Return Nothing return (stmts `snocOL` s1 `appOL` stgStmts `snocOL` s2 `snocOL` s3, top) -- | CmmAssign operation -- -- We use stack allocated variables for CmmReg. The optimiser will replace -- these with registers when possible. genAssign :: CmmReg -> CmmExpr -> LlvmM StmtData genAssign reg val = do vreg <- getCmmReg reg (vval, stmts2, top2) <- exprToVar val let stmts = stmts2 let ty = (pLower . getVarType) vreg dflags <- getDynFlags case ty of -- Some registers are pointer types, so need to cast value to pointer LMPointer _ | getVarType vval == llvmWord dflags -> do (v, s1) <- doExpr ty $ Cast LM_Inttoptr vval ty let s2 = Store v vreg return (stmts `snocOL` s1 `snocOL` s2, top2) LMVector _ _ -> do (v, s1) <- doExpr ty $ Cast LM_Bitcast vval ty let s2 = Store v vreg return (stmts `snocOL` s1 `snocOL` s2, top2) _ -> do let s1 = Store vval vreg return (stmts `snocOL` s1, top2) -- | CmmStore operation genStore :: CmmExpr -> CmmExpr -> LlvmM StmtData -- First we try to detect a few common cases and produce better code for -- these then the default case. We are mostly trying to detect Cmm code -- like I32[Sp + n] and use 'getelementptr' operations instead of the -- generic case that uses casts and pointer arithmetic genStore addr@(CmmReg (CmmGlobal r)) val = genStore_fast addr r 0 val genStore addr@(CmmRegOff (CmmGlobal r) n) val = genStore_fast addr r n val genStore addr@(CmmMachOp (MO_Add _) [ (CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))]) val = genStore_fast addr r (fromInteger n) val genStore addr@(CmmMachOp (MO_Sub _) [ (CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))]) val = genStore_fast addr r (negate $ fromInteger n) val -- generic case genStore addr val = do other <- getTBAAMeta otherN genStore_slow addr val other -- | CmmStore operation -- This is a special case for storing to a global register pointer -- offset such as I32[Sp+8]. genStore_fast :: CmmExpr -> GlobalReg -> Int -> CmmExpr -> LlvmM StmtData genStore_fast addr r n val = do dflags <- getDynFlags (gv, grt, s1) <- getCmmRegVal (CmmGlobal r) meta <- getTBAARegMeta r let (ix,rem) = n `divMod` ((llvmWidthInBits dflags . pLower) grt `div` 8) case isPointer grt && rem == 0 of True -> do (vval, stmts, top) <- exprToVar val (ptr, s2) <- doExpr grt $ GetElemPtr True gv [toI32 ix] -- We might need a different pointer type, so check case pLower grt == getVarType vval of -- were fine True -> do let s3 = MetaStmt meta $ Store vval ptr return (stmts `appOL` s1 `snocOL` s2 `snocOL` s3, top) -- cast to pointer type needed False -> do let ty = (pLift . getVarType) vval (ptr', s3) <- doExpr ty $ Cast LM_Bitcast ptr ty let s4 = MetaStmt meta $ Store vval ptr' return (stmts `appOL` s1 `snocOL` s2 `snocOL` s3 `snocOL` s4, top) -- If its a bit type then we use the slow method since -- we can't avoid casting anyway. False -> genStore_slow addr val meta -- | CmmStore operation -- Generic case. Uses casts and pointer arithmetic if needed. genStore_slow :: CmmExpr -> CmmExpr -> [MetaAnnot] -> LlvmM StmtData genStore_slow addr val meta = do (vaddr, stmts1, top1) <- exprToVar addr (vval, stmts2, top2) <- exprToVar val let stmts = stmts1 `appOL` stmts2 dflags <- getDynFlags case getVarType vaddr of -- sometimes we need to cast an int to a pointer before storing LMPointer ty@(LMPointer _) | getVarType vval == llvmWord dflags -> do (v, s1) <- doExpr ty $ Cast LM_Inttoptr vval ty let s2 = MetaStmt meta $ Store v vaddr return (stmts `snocOL` s1 `snocOL` s2, top1 ++ top2) LMPointer _ -> do let s1 = MetaStmt meta $ Store vval vaddr return (stmts `snocOL` s1, top1 ++ top2) i@(LMInt _) | i == llvmWord dflags -> do let vty = pLift $ getVarType vval (vptr, s1) <- doExpr vty $ Cast LM_Inttoptr vaddr vty let s2 = MetaStmt meta $ Store vval vptr return (stmts `snocOL` s1 `snocOL` s2, top1 ++ top2) other -> pprPanic "genStore: ptr not right type!" (PprCmm.pprExpr addr <+> text ( "Size of Ptr: " ++ show (llvmPtrBits dflags) ++ ", Size of var: " ++ show (llvmWidthInBits dflags other) ++ ", Var: " ++ showSDoc dflags (ppr vaddr))) -- | Unconditional branch genBranch :: BlockId -> LlvmM StmtData genBranch id = let label = blockIdToLlvm id in return (unitOL $ Branch label, []) -- | Conditional branch genCondBranch :: CmmExpr -> BlockId -> BlockId -> LlvmM StmtData genCondBranch cond idT idF = do let labelT = blockIdToLlvm idT let labelF = blockIdToLlvm idF -- See Note [Literals and branch conditions]. (vc, stmts, top) <- exprToVarOpt i1Option cond if getVarType vc == i1 then do let s1 = BranchIf vc labelT labelF return (stmts `snocOL` s1, top) else do dflags <- getDynFlags panic $ "genCondBranch: Cond expr not bool! (" ++ showSDoc dflags (ppr vc) ++ ")" {- Note [Literals and branch conditions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is important that whenever we generate branch conditions for literals like '1', they are properly narrowed to an LLVM expression of type 'i1' (for bools.) Otherwise, nobody is happy. So when we convert a CmmExpr to an LLVM expression for a branch conditional, exprToVarOpt must be certain to return a properly narrowed type. genLit is responsible for this, in the case of literal integers. Often, we won't see direct statements like: if(1) { ... } else { ... } at this point in the pipeline, because the Glorious Code Generator will do trivial branch elimination in the sinking pass (among others,) which will eliminate the expression entirely. However, it's certainly possible and reasonable for this to occur in hand-written C-- code. Consider something like: #ifndef SOME_CONDITIONAL #define CHECK_THING(x) 1 #else #define CHECK_THING(x) some_operation((x)) #endif f() { if (CHECK_THING(xyz)) { ... } else { ... } } In such an instance, CHECK_THING might result in an *expression* in one case, and a *literal* in the other, depending on what in particular was #define'd. So we must be sure to properly narrow the literal in this case to i1 as it won't be eliminated beforehand. For a real example of this, see ./rts/StgStdThunks.cmm -} -- | Switch branch -- -- N.B. We remove Nothing's from the list of branches, as they are 'undefined'. -- However, they may be defined one day, so we better document this behaviour. genSwitch :: CmmExpr -> [Maybe BlockId] -> LlvmM StmtData genSwitch cond maybe_ids = do (vc, stmts, top) <- exprToVar cond let ty = getVarType vc let pairs = [ (ix, id) | (ix,Just id) <- zip [0..] maybe_ids ] let labels = map (\(ix, b) -> (mkIntLit ty ix, blockIdToLlvm b)) pairs -- out of range is undefied, so lets just branch to first label let (_, defLbl) = head labels let s1 = Switch vc defLbl labels return $ (stmts `snocOL` s1, top) -- ----------------------------------------------------------------------------- -- * CmmExpr code generation -- -- | An expression conversion return data: -- * LlvmVar: The var holding the result of the expression -- * LlvmStatements: Any statements needed to evaluate the expression -- * LlvmCmmDecl: Any global data needed for this expression type ExprData = (LlvmVar, LlvmStatements, [LlvmCmmDecl]) -- | Values which can be passed to 'exprToVar' to configure its -- behaviour in certain circumstances. -- -- Currently just used for determining if a comparison should return -- a boolean (i1) or a word. See Note [Literals and branch conditions]. newtype EOption = EOption { i1Expected :: Bool } -- XXX: EOption is an ugly and inefficient solution to this problem. -- | i1 type expected (condition scrutinee). i1Option :: EOption i1Option = EOption True -- | Word type expected (usual). wordOption :: EOption wordOption = EOption False -- | Convert a CmmExpr to a list of LlvmStatements with the result of the -- expression being stored in the returned LlvmVar. exprToVar :: CmmExpr -> LlvmM ExprData exprToVar = exprToVarOpt wordOption exprToVarOpt :: EOption -> CmmExpr -> LlvmM ExprData exprToVarOpt opt e = case e of CmmLit lit -> genLit opt lit CmmLoad e' ty -> genLoad e' ty -- Cmmreg in expression is the value, so must load. If you want actual -- reg pointer, call getCmmReg directly. CmmReg r -> do (v1, ty, s1) <- getCmmRegVal r case isPointer ty of True -> do -- Cmm wants the value, so pointer types must be cast to ints dflags <- getDynFlags (v2, s2) <- doExpr (llvmWord dflags) $ Cast LM_Ptrtoint v1 (llvmWord dflags) return (v2, s1 `snocOL` s2, []) False -> return (v1, s1, []) CmmMachOp op exprs -> genMachOp opt op exprs CmmRegOff r i -> do dflags <- getDynFlags exprToVar $ expandCmmReg dflags (r, i) CmmStackSlot _ _ -> panic "exprToVar: CmmStackSlot not supported!" -- | Handle CmmMachOp expressions genMachOp :: EOption -> MachOp -> [CmmExpr] -> LlvmM ExprData -- Unary Machop genMachOp _ op [x] = case op of MO_Not w -> let all1 = mkIntLit (widthToLlvmInt w) (-1) in negate (widthToLlvmInt w) all1 LM_MO_Xor MO_S_Neg w -> let all0 = mkIntLit (widthToLlvmInt w) 0 in negate (widthToLlvmInt w) all0 LM_MO_Sub MO_F_Neg w -> let all0 = LMLitVar $ LMFloatLit (-0) (widthToLlvmFloat w) in negate (widthToLlvmFloat w) all0 LM_MO_FSub MO_SF_Conv _ w -> fiConv (widthToLlvmFloat w) LM_Sitofp MO_FS_Conv _ w -> fiConv (widthToLlvmInt w) LM_Fptosi MO_SS_Conv from to -> sameConv from (widthToLlvmInt to) LM_Trunc LM_Sext MO_UU_Conv from to -> sameConv from (widthToLlvmInt to) LM_Trunc LM_Zext MO_FF_Conv from to -> sameConv from (widthToLlvmFloat to) LM_Fptrunc LM_Fpext MO_VS_Neg len w -> let ty = widthToLlvmInt w vecty = LMVector len ty all0 = LMIntLit (-0) ty all0s = LMLitVar $ LMVectorLit (replicate len all0) in negateVec vecty all0s LM_MO_Sub MO_VF_Neg len w -> let ty = widthToLlvmFloat w vecty = LMVector len ty all0 = LMFloatLit (-0) ty all0s = LMLitVar $ LMVectorLit (replicate len all0) in negateVec vecty all0s LM_MO_FSub -- Handle unsupported cases explicitly so we get a warning -- of missing case when new MachOps added MO_Add _ -> panicOp MO_Mul _ -> panicOp MO_Sub _ -> panicOp MO_S_MulMayOflo _ -> panicOp MO_S_Quot _ -> panicOp MO_S_Rem _ -> panicOp MO_U_MulMayOflo _ -> panicOp MO_U_Quot _ -> panicOp MO_U_Rem _ -> panicOp MO_Eq _ -> panicOp MO_Ne _ -> panicOp MO_S_Ge _ -> panicOp MO_S_Gt _ -> panicOp MO_S_Le _ -> panicOp MO_S_Lt _ -> panicOp MO_U_Ge _ -> panicOp MO_U_Gt _ -> panicOp MO_U_Le _ -> panicOp MO_U_Lt _ -> panicOp MO_F_Add _ -> panicOp MO_F_Sub _ -> panicOp MO_F_Mul _ -> panicOp MO_F_Quot _ -> panicOp MO_F_Eq _ -> panicOp MO_F_Ne _ -> panicOp MO_F_Ge _ -> panicOp MO_F_Gt _ -> panicOp MO_F_Le _ -> panicOp MO_F_Lt _ -> panicOp MO_And _ -> panicOp MO_Or _ -> panicOp MO_Xor _ -> panicOp MO_Shl _ -> panicOp MO_U_Shr _ -> panicOp MO_S_Shr _ -> panicOp MO_V_Insert _ _ -> panicOp MO_V_Extract _ _ -> panicOp MO_V_Add _ _ -> panicOp MO_V_Sub _ _ -> panicOp MO_V_Mul _ _ -> panicOp MO_VS_Quot _ _ -> panicOp MO_VS_Rem _ _ -> panicOp MO_VU_Quot _ _ -> panicOp MO_VU_Rem _ _ -> panicOp MO_VF_Insert _ _ -> panicOp MO_VF_Extract _ _ -> panicOp MO_VF_Add _ _ -> panicOp MO_VF_Sub _ _ -> panicOp MO_VF_Mul _ _ -> panicOp MO_VF_Quot _ _ -> panicOp where negate ty v2 negOp = do (vx, stmts, top) <- exprToVar x (v1, s1) <- doExpr ty $ LlvmOp negOp v2 vx return (v1, stmts `snocOL` s1, top) negateVec ty v2 negOp = do (vx, stmts1, top) <- exprToVar x ([vx'], stmts2) <- castVars [(vx, ty)] (v1, s1) <- doExpr ty $ LlvmOp negOp v2 vx' return (v1, stmts1 `appOL` stmts2 `snocOL` s1, top) fiConv ty convOp = do (vx, stmts, top) <- exprToVar x (v1, s1) <- doExpr ty $ Cast convOp vx ty return (v1, stmts `snocOL` s1, top) sameConv from ty reduce expand = do x'@(vx, stmts, top) <- exprToVar x let sameConv' op = do (v1, s1) <- doExpr ty $ Cast op vx ty return (v1, stmts `snocOL` s1, top) dflags <- getDynFlags let toWidth = llvmWidthInBits dflags ty -- LLVM doesn't like trying to convert to same width, so -- need to check for that as we do get Cmm code doing it. case widthInBits from of w | w < toWidth -> sameConv' expand w | w > toWidth -> sameConv' reduce _w -> return x' panicOp = panic $ "LLVM.CodeGen.genMachOp: non unary op encountered" ++ "with one argument! (" ++ show op ++ ")" -- Handle GlobalRegs pointers genMachOp opt o@(MO_Add _) e@[(CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))] = genMachOp_fast opt o r (fromInteger n) e genMachOp opt o@(MO_Sub _) e@[(CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))] = genMachOp_fast opt o r (negate . fromInteger $ n) e -- Generic case genMachOp opt op e = genMachOp_slow opt op e -- | Handle CmmMachOp expressions -- This is a specialised method that handles Global register manipulations like -- 'Sp - 16', using the getelementptr instruction. genMachOp_fast :: EOption -> MachOp -> GlobalReg -> Int -> [CmmExpr] -> LlvmM ExprData genMachOp_fast opt op r n e = do (gv, grt, s1) <- getCmmRegVal (CmmGlobal r) dflags <- getDynFlags let (ix,rem) = n `divMod` ((llvmWidthInBits dflags . pLower) grt `div` 8) case isPointer grt && rem == 0 of True -> do (ptr, s2) <- doExpr grt $ GetElemPtr True gv [toI32 ix] (var, s3) <- doExpr (llvmWord dflags) $ Cast LM_Ptrtoint ptr (llvmWord dflags) return (var, s1 `snocOL` s2 `snocOL` s3, []) False -> genMachOp_slow opt op e -- | Handle CmmMachOp expressions -- This handles all the cases not handle by the specialised genMachOp_fast. genMachOp_slow :: EOption -> MachOp -> [CmmExpr] -> LlvmM ExprData -- Element extraction genMachOp_slow _ (MO_V_Extract l w) [val, idx] = do (vval, stmts1, top1) <- exprToVar val (vidx, stmts2, top2) <- exprToVar idx ([vval'], stmts3) <- castVars [(vval, LMVector l ty)] (v1, s1) <- doExpr ty $ Extract vval' vidx return (v1, stmts1 `appOL` stmts2 `appOL` stmts3 `snocOL` s1, top1 ++ top2) where ty = widthToLlvmInt w genMachOp_slow _ (MO_VF_Extract l w) [val, idx] = do (vval, stmts1, top1) <- exprToVar val (vidx, stmts2, top2) <- exprToVar idx ([vval'], stmts3) <- castVars [(vval, LMVector l ty)] (v1, s1) <- doExpr ty $ Extract vval' vidx return (v1, stmts1 `appOL` stmts2 `appOL` stmts3 `snocOL` s1, top1 ++ top2) where ty = widthToLlvmFloat w -- Element insertion genMachOp_slow _ (MO_V_Insert l w) [val, elt, idx] = do (vval, stmts1, top1) <- exprToVar val (velt, stmts2, top2) <- exprToVar elt (vidx, stmts3, top3) <- exprToVar idx ([vval'], stmts4) <- castVars [(vval, ty)] (v1, s1) <- doExpr ty $ Insert vval' velt vidx return (v1, stmts1 `appOL` stmts2 `appOL` stmts3 `appOL` stmts4 `snocOL` s1, top1 ++ top2 ++ top3) where ty = LMVector l (widthToLlvmInt w) genMachOp_slow _ (MO_VF_Insert l w) [val, elt, idx] = do (vval, stmts1, top1) <- exprToVar val (velt, stmts2, top2) <- exprToVar elt (vidx, stmts3, top3) <- exprToVar idx ([vval'], stmts4) <- castVars [(vval, ty)] (v1, s1) <- doExpr ty $ Insert vval' velt vidx return (v1, stmts1 `appOL` stmts2 `appOL` stmts3 `appOL` stmts4 `snocOL` s1, top1 ++ top2 ++ top3) where ty = LMVector l (widthToLlvmFloat w) -- Binary MachOp genMachOp_slow opt op [x, y] = case op of MO_Eq _ -> genBinComp opt LM_CMP_Eq MO_Ne _ -> genBinComp opt LM_CMP_Ne MO_S_Gt _ -> genBinComp opt LM_CMP_Sgt MO_S_Ge _ -> genBinComp opt LM_CMP_Sge MO_S_Lt _ -> genBinComp opt LM_CMP_Slt MO_S_Le _ -> genBinComp opt LM_CMP_Sle MO_U_Gt _ -> genBinComp opt LM_CMP_Ugt MO_U_Ge _ -> genBinComp opt LM_CMP_Uge MO_U_Lt _ -> genBinComp opt LM_CMP_Ult MO_U_Le _ -> genBinComp opt LM_CMP_Ule MO_Add _ -> genBinMach LM_MO_Add MO_Sub _ -> genBinMach LM_MO_Sub MO_Mul _ -> genBinMach LM_MO_Mul MO_U_MulMayOflo _ -> panic "genMachOp: MO_U_MulMayOflo unsupported!" MO_S_MulMayOflo w -> isSMulOK w x y MO_S_Quot _ -> genBinMach LM_MO_SDiv MO_S_Rem _ -> genBinMach LM_MO_SRem MO_U_Quot _ -> genBinMach LM_MO_UDiv MO_U_Rem _ -> genBinMach LM_MO_URem MO_F_Eq _ -> genBinComp opt LM_CMP_Feq MO_F_Ne _ -> genBinComp opt LM_CMP_Fne MO_F_Gt _ -> genBinComp opt LM_CMP_Fgt MO_F_Ge _ -> genBinComp opt LM_CMP_Fge MO_F_Lt _ -> genBinComp opt LM_CMP_Flt MO_F_Le _ -> genBinComp opt LM_CMP_Fle MO_F_Add _ -> genBinMach LM_MO_FAdd MO_F_Sub _ -> genBinMach LM_MO_FSub MO_F_Mul _ -> genBinMach LM_MO_FMul MO_F_Quot _ -> genBinMach LM_MO_FDiv MO_And _ -> genBinMach LM_MO_And MO_Or _ -> genBinMach LM_MO_Or MO_Xor _ -> genBinMach LM_MO_Xor MO_Shl _ -> genBinMach LM_MO_Shl MO_U_Shr _ -> genBinMach LM_MO_LShr MO_S_Shr _ -> genBinMach LM_MO_AShr MO_V_Add l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_Add MO_V_Sub l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_Sub MO_V_Mul l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_Mul MO_VS_Quot l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_SDiv MO_VS_Rem l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_SRem MO_VU_Quot l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_UDiv MO_VU_Rem l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_URem MO_VF_Add l w -> genCastBinMach (LMVector l (widthToLlvmFloat w)) LM_MO_FAdd MO_VF_Sub l w -> genCastBinMach (LMVector l (widthToLlvmFloat w)) LM_MO_FSub MO_VF_Mul l w -> genCastBinMach (LMVector l (widthToLlvmFloat w)) LM_MO_FMul MO_VF_Quot l w -> genCastBinMach (LMVector l (widthToLlvmFloat w)) LM_MO_FDiv MO_Not _ -> panicOp MO_S_Neg _ -> panicOp MO_F_Neg _ -> panicOp MO_SF_Conv _ _ -> panicOp MO_FS_Conv _ _ -> panicOp MO_SS_Conv _ _ -> panicOp MO_UU_Conv _ _ -> panicOp MO_FF_Conv _ _ -> panicOp MO_V_Insert {} -> panicOp MO_V_Extract {} -> panicOp MO_VS_Neg {} -> panicOp MO_VF_Insert {} -> panicOp MO_VF_Extract {} -> panicOp MO_VF_Neg {} -> panicOp where binLlvmOp ty binOp = do (vx, stmts1, top1) <- exprToVar x (vy, stmts2, top2) <- exprToVar y if getVarType vx == getVarType vy then do (v1, s1) <- doExpr (ty vx) $ binOp vx vy return (v1, stmts1 `appOL` stmts2 `snocOL` s1, top1 ++ top2) else do -- Error. Continue anyway so we can debug the generated ll file. dflags <- getDynFlags let style = mkCodeStyle CStyle toString doc = renderWithStyle dflags doc style cmmToStr = (lines . toString . PprCmm.pprExpr) let dx = Comment $ map fsLit $ cmmToStr x let dy = Comment $ map fsLit $ cmmToStr y (v1, s1) <- doExpr (ty vx) $ binOp vx vy let allStmts = stmts1 `appOL` stmts2 `snocOL` dx `snocOL` dy `snocOL` s1 return (v1, allStmts, top1 ++ top2) binCastLlvmOp ty binOp = do (vx, stmts1, top1) <- exprToVar x (vy, stmts2, top2) <- exprToVar y ([vx', vy'], stmts3) <- castVars [(vx, ty), (vy, ty)] (v1, s1) <- doExpr ty $ binOp vx' vy' return (v1, stmts1 `appOL` stmts2 `appOL` stmts3 `snocOL` s1, top1 ++ top2) -- | Need to use EOption here as Cmm expects word size results from -- comparisons while LLVM return i1. Need to extend to llvmWord type -- if expected. See Note [Literals and branch conditions]. genBinComp opt cmp = do ed@(v1, stmts, top) <- binLlvmOp (\_ -> i1) (Compare cmp) dflags <- getDynFlags if getVarType v1 == i1 then case i1Expected opt of True -> return ed False -> do let w_ = llvmWord dflags (v2, s1) <- doExpr w_ $ Cast LM_Zext v1 w_ return (v2, stmts `snocOL` s1, top) else panic $ "genBinComp: Compare returned type other then i1! " ++ (showSDoc dflags $ ppr $ getVarType v1) genBinMach op = binLlvmOp getVarType (LlvmOp op) genCastBinMach ty op = binCastLlvmOp ty (LlvmOp op) -- | Detect if overflow will occur in signed multiply of the two -- CmmExpr's. This is the LLVM assembly equivalent of the NCG -- implementation. Its much longer due to type information/safety. -- This should actually compile to only about 3 asm instructions. isSMulOK :: Width -> CmmExpr -> CmmExpr -> LlvmM ExprData isSMulOK _ x y = do (vx, stmts1, top1) <- exprToVar x (vy, stmts2, top2) <- exprToVar y dflags <- getDynFlags let word = getVarType vx let word2 = LMInt $ 2 * (llvmWidthInBits dflags $ getVarType vx) let shift = llvmWidthInBits dflags word let shift1 = toIWord dflags (shift - 1) let shift2 = toIWord dflags shift if isInt word then do (x1, s1) <- doExpr word2 $ Cast LM_Sext vx word2 (y1, s2) <- doExpr word2 $ Cast LM_Sext vy word2 (r1, s3) <- doExpr word2 $ LlvmOp LM_MO_Mul x1 y1 (rlow1, s4) <- doExpr word $ Cast LM_Trunc r1 word (rlow2, s5) <- doExpr word $ LlvmOp LM_MO_AShr rlow1 shift1 (rhigh1, s6) <- doExpr word2 $ LlvmOp LM_MO_AShr r1 shift2 (rhigh2, s7) <- doExpr word $ Cast LM_Trunc rhigh1 word (dst, s8) <- doExpr word $ LlvmOp LM_MO_Sub rlow2 rhigh2 let stmts = (unitOL s1) `snocOL` s2 `snocOL` s3 `snocOL` s4 `snocOL` s5 `snocOL` s6 `snocOL` s7 `snocOL` s8 return (dst, stmts1 `appOL` stmts2 `appOL` stmts, top1 ++ top2) else panic $ "isSMulOK: Not bit type! (" ++ showSDoc dflags (ppr word) ++ ")" panicOp = panic $ "LLVM.CodeGen.genMachOp_slow: unary op encountered" ++ "with two arguments! (" ++ show op ++ ")" -- More then two expression, invalid! genMachOp_slow _ _ _ = panic "genMachOp: More then 2 expressions in MachOp!" -- | Handle CmmLoad expression. genLoad :: CmmExpr -> CmmType -> LlvmM ExprData -- First we try to detect a few common cases and produce better code for -- these then the default case. We are mostly trying to detect Cmm code -- like I32[Sp + n] and use 'getelementptr' operations instead of the -- generic case that uses casts and pointer arithmetic genLoad e@(CmmReg (CmmGlobal r)) ty = genLoad_fast e r 0 ty genLoad e@(CmmRegOff (CmmGlobal r) n) ty = genLoad_fast e r n ty genLoad e@(CmmMachOp (MO_Add _) [ (CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))]) ty = genLoad_fast e r (fromInteger n) ty genLoad e@(CmmMachOp (MO_Sub _) [ (CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))]) ty = genLoad_fast e r (negate $ fromInteger n) ty -- generic case genLoad e ty = do other <- getTBAAMeta otherN genLoad_slow e ty other -- | Handle CmmLoad expression. -- This is a special case for loading from a global register pointer -- offset such as I32[Sp+8]. genLoad_fast :: CmmExpr -> GlobalReg -> Int -> CmmType -> LlvmM ExprData genLoad_fast e r n ty = do dflags <- getDynFlags (gv, grt, s1) <- getCmmRegVal (CmmGlobal r) meta <- getTBAARegMeta r let ty' = cmmToLlvmType ty (ix,rem) = n `divMod` ((llvmWidthInBits dflags . pLower) grt `div` 8) case isPointer grt && rem == 0 of True -> do (ptr, s2) <- doExpr grt $ GetElemPtr True gv [toI32 ix] -- We might need a different pointer type, so check case grt == ty' of -- were fine True -> do (var, s3) <- doExpr ty' (MExpr meta $ Load ptr) return (var, s1 `snocOL` s2 `snocOL` s3, []) -- cast to pointer type needed False -> do let pty = pLift ty' (ptr', s3) <- doExpr pty $ Cast LM_Bitcast ptr pty (var, s4) <- doExpr ty' (MExpr meta $ Load ptr') return (var, s1 `snocOL` s2 `snocOL` s3 `snocOL` s4, []) -- If its a bit type then we use the slow method since -- we can't avoid casting anyway. False -> genLoad_slow e ty meta -- | Handle Cmm load expression. -- Generic case. Uses casts and pointer arithmetic if needed. genLoad_slow :: CmmExpr -> CmmType -> [MetaAnnot] -> LlvmM ExprData genLoad_slow e ty meta = do (iptr, stmts, tops) <- exprToVar e dflags <- getDynFlags case getVarType iptr of LMPointer _ -> do (dvar, load) <- doExpr (cmmToLlvmType ty) (MExpr meta $ Load iptr) return (dvar, stmts `snocOL` load, tops) i@(LMInt _) | i == llvmWord dflags -> do let pty = LMPointer $ cmmToLlvmType ty (ptr, cast) <- doExpr pty $ Cast LM_Inttoptr iptr pty (dvar, load) <- doExpr (cmmToLlvmType ty) (MExpr meta $ Load ptr) return (dvar, stmts `snocOL` cast `snocOL` load, tops) other -> do dflags <- getDynFlags pprPanic "exprToVar: CmmLoad expression is not right type!" (PprCmm.pprExpr e <+> text ( "Size of Ptr: " ++ show (llvmPtrBits dflags) ++ ", Size of var: " ++ show (llvmWidthInBits dflags other) ++ ", Var: " ++ showSDoc dflags (ppr iptr))) -- | Handle CmmReg expression. This will return a pointer to the stack -- location of the register. Throws an error if it isn't allocated on -- the stack. getCmmReg :: CmmReg -> LlvmM LlvmVar getCmmReg (CmmLocal (LocalReg un _)) = do exists <- varLookup un dflags <- getDynFlags case exists of Just ety -> return (LMLocalVar un $ pLift ety) Nothing -> fail $ "getCmmReg: Cmm register " ++ showSDoc dflags (ppr un) ++ " was not allocated!" -- This should never happen, as every local variable should -- have been assigned a value at some point, triggering -- "funPrologue" to allocate it on the stack. getCmmReg (CmmGlobal g) = do onStack <- checkStackReg g dflags <- getDynFlags if onStack then return (lmGlobalRegVar dflags g) else fail $ "getCmmReg: Cmm register " ++ showSDoc dflags (ppr g) ++ " not stack-allocated!" -- | Return the value of a given register, as well as its type. Might -- need to be load from stack. getCmmRegVal :: CmmReg -> LlvmM (LlvmVar, LlvmType, LlvmStatements) getCmmRegVal reg = case reg of CmmGlobal g -> do onStack <- checkStackReg g dflags <- getDynFlags if onStack then loadFromStack else do let r = lmGlobalRegArg dflags g return (r, getVarType r, nilOL) _ -> loadFromStack where loadFromStack = do ptr <- getCmmReg reg let ty = pLower $ getVarType ptr (v, s) <- doExpr ty (Load ptr) return (v, ty, unitOL s) -- | Allocate a local CmmReg on the stack allocReg :: CmmReg -> (LlvmVar, LlvmStatements) allocReg (CmmLocal (LocalReg un ty)) = let ty' = cmmToLlvmType ty var = LMLocalVar un (LMPointer ty') alc = Alloca ty' 1 in (var, unitOL $ Assignment var alc) allocReg _ = panic $ "allocReg: Global reg encountered! Global registers should" ++ " have been handled elsewhere!" -- | Generate code for a literal genLit :: EOption -> CmmLit -> LlvmM ExprData genLit opt (CmmInt i w) -- See Note [Literals and branch conditions]. = let width | i1Expected opt = i1 | otherwise = LMInt (widthInBits w) -- comm = Comment [ fsLit $ "EOption: " ++ show opt -- , fsLit $ "Width : " ++ show w -- , fsLit $ "Width' : " ++ show (widthInBits w) -- ] in return (mkIntLit width i, nilOL, []) genLit _ (CmmFloat r w) = return (LMLitVar $ LMFloatLit (fromRational r) (widthToLlvmFloat w), nilOL, []) genLit opt (CmmVec ls) = do llvmLits <- mapM toLlvmLit ls return (LMLitVar $ LMVectorLit llvmLits, nilOL, []) where toLlvmLit :: CmmLit -> LlvmM LlvmLit toLlvmLit lit = do (llvmLitVar, _, _) <- genLit opt lit case llvmLitVar of LMLitVar llvmLit -> return llvmLit _ -> panic "genLit" genLit _ cmm@(CmmLabel l) = do var <- getGlobalPtr =<< strCLabel_llvm l dflags <- getDynFlags let lmty = cmmToLlvmType $ cmmLitType dflags cmm (v1, s1) <- doExpr lmty $ Cast LM_Ptrtoint var (llvmWord dflags) return (v1, unitOL s1, []) genLit opt (CmmLabelOff label off) = do dflags <- getDynFlags (vlbl, stmts, stat) <- genLit opt (CmmLabel label) let voff = toIWord dflags off (v1, s1) <- doExpr (getVarType vlbl) $ LlvmOp LM_MO_Add vlbl voff return (v1, stmts `snocOL` s1, stat) genLit opt (CmmLabelDiffOff l1 l2 off) = do dflags <- getDynFlags (vl1, stmts1, stat1) <- genLit opt (CmmLabel l1) (vl2, stmts2, stat2) <- genLit opt (CmmLabel l2) let voff = toIWord dflags off let ty1 = getVarType vl1 let ty2 = getVarType vl2 if (isInt ty1) && (isInt ty2) && (llvmWidthInBits dflags ty1 == llvmWidthInBits dflags ty2) then do (v1, s1) <- doExpr (getVarType vl1) $ LlvmOp LM_MO_Sub vl1 vl2 (v2, s2) <- doExpr (getVarType v1 ) $ LlvmOp LM_MO_Add v1 voff return (v2, stmts1 `appOL` stmts2 `snocOL` s1 `snocOL` s2, stat1 ++ stat2) else panic "genLit: CmmLabelDiffOff encountered with different label ty!" genLit opt (CmmBlock b) = genLit opt (CmmLabel $ infoTblLbl b) genLit _ CmmHighStackMark = panic "genStaticLit - CmmHighStackMark unsupported!" -- ----------------------------------------------------------------------------- -- * Misc -- -- | Find CmmRegs that get assigned and allocate them on the stack -- -- Any register that gets written needs to be allcoated on the -- stack. This avoids having to map a CmmReg to an equivalent SSA form -- and avoids having to deal with Phi node insertion. This is also -- the approach recommended by LLVM developers. -- -- On the other hand, this is unecessarily verbose if the register in -- question is never written. Therefore we skip it where we can to -- save a few lines in the output and hopefully speed compilation up a -- bit. funPrologue :: LiveGlobalRegs -> [CmmBlock] -> LlvmM StmtData funPrologue live cmmBlocks = do trash <- getTrashRegs let getAssignedRegs :: CmmNode O O -> [CmmReg] getAssignedRegs (CmmAssign reg _) = [reg] -- Calls will trash all registers. Unfortunately, this needs them to -- be stack-allocated in the first place. getAssignedRegs (CmmUnsafeForeignCall _ rs _) = map CmmGlobal trash ++ map CmmLocal rs getAssignedRegs _ = [] getRegsBlock (_, body, _) = concatMap getAssignedRegs $ blockToList body assignedRegs = nub $ concatMap (getRegsBlock . blockSplit) cmmBlocks isLive r = r `elem` alwaysLive || r `elem` live dflags <- getDynFlags stmtss <- flip mapM assignedRegs $ \reg -> case reg of CmmLocal (LocalReg un _) -> do let (newv, stmts) = allocReg reg varInsert un (pLower $ getVarType newv) return stmts CmmGlobal r -> do let reg = lmGlobalRegVar dflags r arg = lmGlobalRegArg dflags r ty = (pLower . getVarType) reg trash = LMLitVar $ LMUndefLit ty rval = if isLive r then arg else trash alloc = Assignment reg $ Alloca (pLower $ getVarType reg) 1 markStackReg r return $ toOL [alloc, Store rval reg] return (concatOL stmtss, []) -- | Function epilogue. Load STG variables to use as argument for call. -- STG Liveness optimisation done here. funEpilogue :: LiveGlobalRegs -> LlvmM ([LlvmVar], LlvmStatements) funEpilogue live = do -- Have information and liveness optimisation is enabled? let liveRegs = alwaysLive ++ live isSSE (FloatReg _) = True isSSE (DoubleReg _) = True isSSE (XmmReg _) = True isSSE (YmmReg _) = True isSSE (ZmmReg _) = True isSSE _ = False -- Set to value or "undef" depending on whether the register is -- actually live dflags <- getDynFlags let loadExpr r = do (v, _, s) <- getCmmRegVal (CmmGlobal r) return (Just $ v, s) loadUndef r = do let ty = (pLower . getVarType $ lmGlobalRegVar dflags r) return (Just $ LMLitVar $ LMUndefLit ty, nilOL) platform <- getDynFlag targetPlatform loads <- flip mapM (activeStgRegs platform) $ \r -> case () of _ | r `elem` liveRegs -> loadExpr r | not (isSSE r) -> loadUndef r | otherwise -> return (Nothing, nilOL) let (vars, stmts) = unzip loads return (catMaybes vars, concatOL stmts) -- | A series of statements to trash all the STG registers. -- -- In LLVM we pass the STG registers around everywhere in function calls. -- So this means LLVM considers them live across the entire function, when -- in reality they usually aren't. For Caller save registers across C calls -- the saving and restoring of them is done by the Cmm code generator, -- using Cmm local vars. So to stop LLVM saving them as well (and saving -- all of them since it thinks they're always live, we trash them just -- before the call by assigning the 'undef' value to them. The ones we -- need are restored from the Cmm local var and the ones we don't need -- are fine to be trashed. getTrashStmts :: LlvmM LlvmStatements getTrashStmts = do regs <- getTrashRegs stmts <- flip mapM regs $ \ r -> do reg <- getCmmReg (CmmGlobal r) let ty = (pLower . getVarType) reg return $ Store (LMLitVar $ LMUndefLit ty) reg return $ toOL stmts getTrashRegs :: LlvmM [GlobalReg] getTrashRegs = do plat <- getLlvmPlatform return $ filter (callerSaves plat) (activeStgRegs plat) -- | Get a function pointer to the CLabel specified. -- -- This is for Haskell functions, function type is assumed, so doesn't work -- with foreign functions. getHsFunc :: LiveGlobalRegs -> CLabel -> LlvmM ExprData getHsFunc live lbl = do fty <- llvmFunTy live name <- strCLabel_llvm lbl getHsFunc' name fty getHsFunc' :: LMString -> LlvmType -> LlvmM ExprData getHsFunc' name fty = do fun <- getGlobalPtr name if getVarType fun == fty then return (fun, nilOL, []) else do (v1, s1) <- doExpr (pLift fty) $ Cast LM_Bitcast fun (pLift fty) return (v1, unitOL s1, []) -- | Create a new local var mkLocalVar :: LlvmType -> LlvmM LlvmVar mkLocalVar ty = do un <- runUs getUniqueUs return $ LMLocalVar un ty -- | Execute an expression, assigning result to a var doExpr :: LlvmType -> LlvmExpression -> LlvmM (LlvmVar, LlvmStatement) doExpr ty expr = do v <- mkLocalVar ty return (v, Assignment v expr) -- | Expand CmmRegOff expandCmmReg :: DynFlags -> (CmmReg, Int) -> CmmExpr expandCmmReg dflags (reg, off) = let width = typeWidth (cmmRegType dflags reg) voff = CmmLit $ CmmInt (fromIntegral off) width in CmmMachOp (MO_Add width) [CmmReg reg, voff] -- | Convert a block id into a appropriate Llvm label blockIdToLlvm :: BlockId -> LlvmVar blockIdToLlvm bid = LMLocalVar (getUnique bid) LMLabel -- | Create Llvm int Literal mkIntLit :: Integral a => LlvmType -> a -> LlvmVar mkIntLit ty i = LMLitVar $ LMIntLit (toInteger i) ty -- | Convert int type to a LLvmVar of word or i32 size toI32 :: Integral a => a -> LlvmVar toI32 = mkIntLit i32 toIWord :: Integral a => DynFlags -> a -> LlvmVar toIWord dflags = mkIntLit (llvmWord dflags) -- | Error functions panic :: String -> a panic s = Outputable.panic $ "LlvmCodeGen.CodeGen." ++ s pprPanic :: String -> SDoc -> a pprPanic s d = Outputable.pprPanic ("LlvmCodeGen.CodeGen." ++ s) d -- | Returns TBAA meta data by unique getTBAAMeta :: Unique -> LlvmM [MetaAnnot] getTBAAMeta u = do mi <- getUniqMeta u return [MetaAnnot tbaa (MetaNode i) | let Just i = mi] -- | Returns TBAA meta data for given register getTBAARegMeta :: GlobalReg -> LlvmM [MetaAnnot] getTBAARegMeta = getTBAAMeta . getTBAA
lukexi/ghc-7.8-arm64
compiler/llvmGen/LlvmCodeGen/CodeGen.hs
bsd-3-clause
61,983
0
24
19,275
17,326
8,680
8,646
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-| Module : WebParsing.GraphConversion Description : Converts Course records into Dynamic Inductive Graphs for further modification Stability : experimental Currently has the ability to extract course information from the database and convert it into a a extendable inductive graph using the DynGraph Class. An inductive graph is a representation of the graph ADT that is more condusive to manipulation using functional paradigms. More information can be found here. DynGraphs are supported by the GraphViz library. -} module WebParsing.GraphConversion (toGraph, toGraph', compsci) where import Control.Monad.State import qualified Data.Text as T import Data.Graph import Data.Graph.Inductive.Graph import Data.Graph.Inductive.PatriciaTree import Data.Graph.Inductive.NodeMap import Data.Graph.Inductive.Monad import Data.Graph.Inductive.Monad.IOArray import Data.List import Data.Maybe import Database.CourseQueries import Database.Tables import WebParsing.ParsingHelp import System.Random import System.IO.Unsafe {- Signatures: -- type definitions type GraphPart = (Gr T.Text (), NodeMap T.Text) -- null data types emptyGr :: Gr T.Text () emptyMap :: NodeMap T.Text emptyEdges :: [(T.Text, T.Text, ())] -- graph querying nodeInGraph :: T.Text -> Gr T.Text () -> Bool edgeInGraph :: (T.Text, T.Text, ()) -> Gr T.Text () -> Bool edgesInGraph :: [(T.Text, T.Text, ())] -> Gr T.Text () -> [(T.Text, T.Text, ())] -- graph manipulation removeEdges :: [(T.Text, T.Text, ())] -> [(T.Text, T.Text, ())] -> [(T.Text, T.Text, ())] insMapNode' :: T.Text -> (Gr T.Text (), NodeMap T.Text) -> (Gr T.Text (), NodeMap T.Text) insMapNodes' :: [T.Text] -> (Gr T.Text (), NodeMap T.Text) -> (Gr T.Text (), NodeMap T.Text) insMapEdges' :: [(T.Text, T.Text, ())] -> (Gr T.Text (), NodeMap T.Text) -> (Gr T.Text (), NodeMap T.Text) insMapEdge' :: (T.Text, T.Text, ()) -> (Gr T.Text (), NodeMap T.Text) -> (Gr T.Text (), NodeMap T.Text) -- Course Record Conversion extractAllCourses :: [T.Text] -> [IO Course] parseCoursesEdges :: [Course] -> GraphPart -> GraphPart parseCourseEdge :: GraphPart -> Course -> GraphPart insertPrereq :: T.Text -> GraphPart -> [T.Text] -> GraphPart -} type GraphPart = (Gr T.Text (), NodeMap T.Text) -- | an empty graph emptyGr :: Gr T.Text () emptyGr = empty -- | an empty NodeMap emptyMap :: NodeMap T.Text emptyMap = new -- | an empty list of edges emptyEdges :: [(T.Text, T.Text, ())] emptyEdges = [] -- | returns true if a node with label node is in graph nodeInGraph :: T.Text -> Gr T.Text () -> Bool nodeInGraph node graph = foldl' (\acc (int, name) -> node == name || acc) False (labNodes graph) -- | returns true iff the given edge contains nodes not in the graph edgeInGraph :: (T.Text, T.Text, ()) -> Gr T.Text () -> Bool edgeInGraph (parent, child, _) g = nodeInGraph parent g && nodeInGraph child g -- | returns a list of all edges that contain nodes not in the graph edgesInGraph :: [(T.Text, T.Text, ())] -> Gr T.Text () -> [(T.Text, T.Text, ())] edgesInGraph edges graph = foldl (\acc edge -> if edgeInGraph edge graph then edge:acc else acc ) [] edges -- | removes all edges in second list from first list removeEdges :: [(T.Text, T.Text, ())] -> [(T.Text, T.Text, ())] -> [(T.Text, T.Text, ())] removeEdges lst rm = foldl (\lst el -> delete el lst) lst rm -- | wrapper for insMapnode that returns a tuple instead of a triple -- if the given edge contains nodes not in the graph, the edge is not added insMapNode' :: T.Text -> (Gr T.Text (), NodeMap T.Text) -> (Gr T.Text (), NodeMap T.Text) insMapNode' name (g, m) = let (graph, nodeMap, _) = insMapNode m name g in (graph, nodeMap) -- | wrapper for insMapNodes that returns a tuple instead of a triple -- if a given edge contains a node not in the graph, the edge is not added insMapNodes' :: [T.Text] -> (Gr T.Text (), NodeMap T.Text) -> (Gr T.Text (), NodeMap T.Text) insMapNodes' names (g, m) = let (graph, nodeMap, _) = insMapNodes m names g in (graph, nodeMap) -- | inserts all valid edges into the graph insMapEdges' :: [(T.Text, T.Text, ())] -> (Gr T.Text (), NodeMap T.Text) -> (Gr T.Text (), NodeMap T.Text) insMapEdges' edges (g, m) = let safeEdges = removeEdges (edgesInGraph edges g) edges in (insMapEdges m safeEdges g, m) -- | inserts the edge, if valid, into the graph insMapEdge' :: (T.Text, T.Text, ()) -> (Gr T.Text (), NodeMap T.Text) -> (Gr T.Text (), NodeMap T.Text) insMapEdge' edge (g, m) = if edgeInGraph edge g then (insMapEdge m edge g, m) else (g, m) -- | parses the prereqs field of the course. atomic prereqs are converted into edges, -- | and/or prereqs are converted into Contexts parseCoursesEdges :: [Course] -> GraphPart -> GraphPart parseCoursesEdges courses gpart = foldl parseCourseEdge gpart courses -- | inserts all prerequisites for a given course into the graph parseCourseEdge :: GraphPart -> Course -> GraphPart parseCourseEdge gpart course = do if (isNothing (prereqs course)) then gpart else let prereqs' = map (T.splitOn " ") (T.splitOn "," (fromJust (prereqs course))) in foldl (insertPrereq (name course)) gpart prereqs' -- | inserts a list of prereqs for a given course into the graph. insertPrereq :: T.Text -> GraphPart -> [T.Text] -> GraphPart insertPrereq name gpart prereq = foldl (\g p -> insMapEdge' (p, name, ()) g) gpart prereq -- | inserts a list of prereqs, including dummy nodes for grouped prerequisites. -- Currently uses an unsafe method to develop dummy node names. -- tends to overcomplicate the graph so is currently not used. insertPrereqDummy :: T.Text -> GraphPart -> [T.Text] -> GraphPart insertPrereqDummy name gpart prereq = if (length prereq == 1) then insMapEdge' (head prereq, name, ()) gpart else let nodename = T.concat [name, randomStr] -- REMEMBER: these operations are evalated in the reverse order of presentation! in insMapEdge' (nodename, name, ()) $ (\g -> foldl (\g p -> insMapEdge' (p, nodename, ()) g) g prereq) $ insMapNode' nodename gpart where randomStr = T.pack $ take 3 $ randomRs ('a','z') $ unsafePerformIO newStdGen -- | converts a list of Course Records into a Graph coursesToGraph :: [Course] -> IO (Gr T.Text ()) coursesToGraph courses = let noEmpty = filter (\c -> "" /= name c) courses in return $ fst $ parseCoursesEdges noEmpty $ (mkMapGraph (map name noEmpty) []) -- | takes a list of course codes, extracts them from Database, converts them -- into a graph. toGraph' :: [T.Text] -> IO (Gr T.Text ()) toGraph' courses = sequence (map returnCourse courses) >>= coursesToGraph toGraph :: [Course] -> IO (Gr T.Text ()) toGraph = coursesToGraph labNodes' :: Gr T.Text () -> IO [LNode T.Text] labNodes' graph = return (labNodes graph) main :: IO () main = toGraph' [ "CSC104H1", "CSC108H1", "CSC120H1", "CSC148H1", "CSC165H1", "CSC200Y1", "CSC207H1", "CSC209H1", "CSC236H1", "CSC240H1", "CSC258H1", "CSC263H1", "CSC265H1", "CSC300H1", "CSC302H1", "CSC309H1", "CSC310H1", "CSC318H1", "CSC320H1", "CSC321H1", "CSC324H1", "CSC336H1", "CSC343H1", "CSC358H1", "CSC369H1", "CSC372H1", "CSC373H1", "CSC384H1", "ECE385H1", "CSC401H1", "CSC404H1", "CSC410H1", "CSC411H1", "CSC412H1", "CSC418H1", "CSC420H1", "CSC428H1", "CSC436H1", "CSC438H1", "CSC443H1", "CSC446H1", "CSC448H1", "CSC454H1", "CSC456H1", "CSC458H1", "CSC463H1", "CSC465H1", "CSC469H1", "CSC485H1", "CSC486H1", "CSC488H1", "ECE489H1", "CSC490H1", "MAT135H1", "MAT136H1", "MAT137Y1", "MAT157Y1", "MAT221H1", "MAT223H1", "MAT240H1", "MAT235Y1", "MAT237Y1", "MAT257Y1", "STA247H1", "STA255H1", "STA257H1" ] >>= labNodes' >>= print compsci :: IO (Gr T.Text ()) compsci = toGraph' [ "CSC104H1", "CSC108H1", "CSC120H1", "CSC148H1", "CSC165H1", "CSC200Y1", "CSC207H1", "CSC209H1", "CSC236H1", "CSC240H1", "CSC258H1", "CSC263H1", "CSC265H1", "CSC300H1", "CSC302H1", "CSC309H1", "CSC310H1", "CSC318H1", "CSC320H1", "CSC321H1", "CSC324H1", "CSC336H1", "CSC343H1", "CSC358H1", "CSC369H1", "CSC372H1", "CSC373H1", "CSC384H1", "ECE385H1", "CSC401H1", "CSC404H1", "CSC410H1", "CSC411H1", "CSC412H1", "CSC418H1", "CSC420H1", "CSC428H1", "CSC436H1", "CSC438H1", "CSC443H1", "CSC446H1", "CSC448H1", "CSC454H1", "CSC456H1", "CSC458H1", "CSC463H1", "CSC465H1", "CSC469H1", "CSC485H1", "CSC486H1", "CSC488H1", "ECE489H1", "CSC490H1" ]
Ian-Stewart-Binks/courseography
hs/WebParsing/GraphConversion.hs
gpl-3.0
8,824
0
18
1,855
2,074
1,169
905
116
2
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="sr-CS"> <title>ViewState</title> <maps> <homeID>viewstate</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/viewstate/src/main/javahelp/help_sr_CS/helpset_sr_CS.hs
apache-2.0
960
77
66
155
404
205
199
-1
-1
{-# LANGUAGE DataKinds, PolyKinds, ExplicitForAll #-} module BadTelescope2 where import Data.Kind data SameKind :: k -> k -> * foo :: forall a k (b :: k). SameKind a b foo = undefined
sdiehl/ghc
testsuite/tests/dependent/should_fail/BadTelescope2.hs
bsd-3-clause
189
0
7
38
52
32
20
-1
-1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="id-ID"> <title>WebSockets | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Telusuri</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
msrader/zap-extensions
src/org/zaproxy/zap/extension/websocket/resources/help_id_ID/helpset_id_ID.hs
apache-2.0
974
80
66
159
413
209
204
-1
-1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} import Prelude hiding (filter) import Database.Persist.Sqlite import Control.Monad.IO.Class mkPersist [$persist| Person sql=PersonTable name String update Eq Ne Desc In age Int update "Asc" Lt "some ignored attribute" color String null Eq Ne sql=mycolorfield NotIn Ge PersonNameKey name Pet owner PersonId name String Null field Int null Eq Ne Gt NotIn In Table table String |] main :: IO () main = withSqlitePool "test.db3" 1 $ runSqlPool go go :: SqlPersist IO () go = do runMigration $ do migrate (undefined :: Person) migrate (undefined :: Pet) migrate (undefined :: Null) migrate (undefined :: Table) deleteWhere ([] :: [Filter Person]) pid <- insert $ Person "Michael" 25 Nothing liftIO $ print pid p1 <- get pid liftIO $ print p1 replace pid $ Person "Michael" 26 Nothing p2 <- get pid liftIO $ print p2 p3 <- selectList [PersonNameEq "Michael"] [] 0 0 liftIO $ print p3 _ <- insert $ Person "Michael2" 27 Nothing deleteWhere [PersonNameEq "Michael2"] p4 <- selectList [PersonAgeLt 28] [] 0 0 liftIO $ print p4 update pid [PersonAge 28] p5 <- get pid liftIO $ print p5 updateWhere [PersonNameEq "Michael"] [PersonAge 29] p6 <- get pid if fmap personAge p6 /= Just 29 then error "bug 57" else return () liftIO $ print p6 _ <- insert $ Person "Eliezer" 2 $ Just "blue" p7 <- selectList [] [PersonAgeAsc] 0 0 liftIO $ print p7 _ <- insert $ Person "Abe" 30 $ Just "black" p8 <- selectList [PersonAgeLt 30] [PersonNameDesc] 0 0 liftIO $ print p8 {- insertR $ Person "Abe" 31 $ Just "brown" p9 <- select [PersonNameEq "Abe"] [] liftIO $ print p9 -} p10 <- getBy $ PersonNameKey "Michael" liftIO $ print p10 p11 <- selectList [PersonColorEq $ Just "blue"] [] 0 0 liftIO $ print p11 p12 <- selectList [PersonColorEq Nothing] [] 0 0 liftIO $ print p12 p13 <- selectList [PersonColorNe Nothing] [] 0 0 liftIO $ print p13 p14 <- count [PersonColorNe Nothing] liftIO $ print p14 delete pid plast <- get pid liftIO $ print plast _ <- insert $ Person "Gavriella" 0 Nothing x@(_, Person "Gavriella" 0 Nothing) <- insertBy $ Person "Gavriella" 1 $ Just "blue" liftIO $ print x False <- checkUnique $ Person "Gavriella" 2 Nothing True <- checkUnique $ Person "Gavriela (it's misspelled)" 2 Nothing return () p15 <- selectList [PersonNameIn $ words "Michael Gavriella"] [] 0 0 liftIO $ print p15 _ <- insert $ Person "Miriam" 23 $ Just "red" p16 <- selectList [PersonColorNotIn [Nothing, Just "blue"]] [] 0 0 liftIO $ print p16 p17 <- selectList [PersonColorGe "blue"] [] 0 0 liftIO $ print p17 deleteWhere ([] :: [Filter Null]) _ <- insert $ Null $ Just 5 _ <- insert $ Null Nothing [(_, Null (Just 5))] <- selectList [NullFieldGt 4] [] 0 0 [] <- selectList [NullFieldGt 5] [] 0 0 [(_, Null (Just 5))] <- selectList [NullFieldEq $ Just 5] [] 0 0 [(_, Null Nothing)] <- selectList [NullFieldNe $ Just 5] [] 0 0 [(_, Null Nothing)] <- selectList [NullFieldEq Nothing] [] 0 0 [(_, Null (Just 5))] <- selectList [NullFieldNe Nothing] [] 0 0 return () _ <- selectList ([] :: [Filter Person]) [] 0 0 _ <- selectList ([] :: [Filter Person]) [] 10 0 _ <- selectList ([] :: [Filter Person]) [] 10 10 _ <- selectList ([] :: [Filter Person]) [] 0 10 deleteWhere ([] :: [Filter Table]) _ <- insert $ Table "foo" _ <- insert $ Table "bar" return ()
jasonzoladz/persistent
persistent-sqlite/test1.hs
mit
3,738
2
12
1,000
1,561
724
837
-1
-1
-- !!! qualified names aren't allowed in local binds either -- (Haskell 98 (revised) section 5.5.1) module M where g x = let M.y = x + 1 in M.y
wxwxwwxxx/ghc
testsuite/tests/rename/should_fail/rnfail034.hs
bsd-3-clause
144
1
9
30
33
18
15
-1
-1
-- !!! a file mailed us by Ryzard Kubiak. This provides a good test of the code -- !!! handling type signatures and recursive data types. module ShouldSucceed where data Boolean = FF | TT data Pair a b = Mkpair a b data List alpha = Nil | Cons alpha (List alpha) data Nat = Zero | Succ Nat data Tree t = Leaf t | Node (Tree t) (Tree t) idb :: Boolean -> Boolean idb x = x swap :: Pair a b -> Pair b a swap t = case t of Mkpair x y -> Mkpair y x neg :: Boolean -> Boolean neg b = case b of FF -> TT TT -> FF nUll :: List alpha -> Boolean nUll l = case l of Nil -> TT Cons y ys -> FF idl :: List a -> List a idl xs = case xs of Nil -> Nil Cons y ys -> Cons y (idl ys) add :: Nat -> Nat -> Nat add a b = case a of Zero -> b Succ c -> Succ (add c b) app :: List alpha -> List alpha -> List alpha app xs zs = case xs of Nil -> zs Cons y ys -> Cons y (app ys zs) lEngth :: List a -> Nat lEngth xs = case xs of Nil -> Zero Cons y ys -> Succ(lEngth ys) before :: List Nat -> List Nat before xs = case xs of Nil -> Nil Cons y ys -> case y of Zero -> Nil Succ n -> Cons y (before ys) rEverse :: List alpha -> List alpha rEverse rs = case rs of Nil -> Nil Cons y ys -> app (rEverse ys) (Cons y Nil) flatten :: Tree alpha -> List alpha flatten t = case t of Leaf x -> Cons x Nil Node l r -> app (flatten l) (flatten r) sUm :: Tree Nat -> Nat sUm t = case t of Leaf t -> t Node l r -> add (sUm l) (sUm r)
siddhanathan/ghc
testsuite/tests/typecheck/should_compile/tc042.hs
bsd-3-clause
1,829
0
13
787
720
355
365
53
3
module Paths_novel_monad ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName, getSysconfDir ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) import Prelude catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version {versionBranch = [0,1,0,0], versionTags = []} bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath bindir = "/home/tune/.cabal/bin" libdir = "/home/tune/.cabal/lib/i386-linux-ghc-7.6.3/novel-monad-0.1.0.0" datadir = "/home/tune/.cabal/share/i386-linux-ghc-7.6.3/novel-monad-0.1.0.0" libexecdir = "/home/tune/.cabal/libexec" sysconfdir = "/home/tune/.cabal/etc" getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath getBinDir = catchIO (getEnv "novel_monad_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "novel_monad_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "novel_monad_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "novel_monad_libexecdir") (\_ -> return libexecdir) getSysconfDir = catchIO (getEnv "novel_monad_sysconfdir") (\_ -> return sysconfdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
tokiwoousaka/NovelMonad
dist/build/autogen/Paths_novel_monad.hs
mit
1,362
0
10
182
371
213
158
28
1
{- | Two phase algorithm to solve a Rubik's cube -} {-# LANGUAGE RecordWildCards, ViewPatterns #-} module Rubik.Solver.TwoPhase where import Rubik.Cube import Rubik.Misc import Rubik.Solver import Rubik.Tables.Moves import Rubik.Tables.Distances import Data.Function ( on ) import Data.Monoid {-# INLINE phase1Proj #-} phase1Proj = rawProjection |*| rawProjection |.| rawProjection phase1Convert = convertP phase1Proj phase1Dist = maxDistance [ (\((,,) co _ uds) -> (co, uds)) >$< distanceWith2 d_CornerOrien_UDSlice , (\((,,) _ eo uds) -> (eo, uds)) >$< distanceWith2 d_EdgeOrien_UDSlice ] phase1 :: Cube -> Move phase1 = solveWith move18Names moves phase1Proj phase1Dist where moves = (,,) move18CornerOrien move18EdgeOrien move18UDSlice -- | > phase1Solved (phase1 c) phase1Solved :: Cube -> Bool phase1Solved = ((==) `on` phase1Convert) iden -- phase2Proj = rawProjection |*| rawProjection |.| rawProjection phase2Convert = convertP phase2Proj phase2Dist = maxDistance [ (\((,,) cp _ udsp) -> (cp, udsp)) >$< distanceWith2 d_CornerPermu_UDSlicePermu2 , (\((,,) _ udep udsp) -> (udep, udsp)) >$< distanceWith2 d_UDEdgePermu2_UDSlicePermu2 ] phase2 :: Cube -> Move phase2 = solveWith move10Names moves phase2Proj phase2Dist where moves = (,,) move10CornerPermu move10UDEdgePermu2 move10UDSlicePermu2 -- | > phase1Solved c ==> phase2Solved (phase2 c) phase2Solved :: Cube -> Bool phase2Solved = (== iden) -- | Solve a scrambled Rubik's cube. -- -- Make sure the cube is actually solvable with 'Cubie.solvable', -- before calling this function. solve :: Cube -> Move solve c = let s1 = phase1 c c1 = c <> moveToCube s1 s2 = phase2 c1 in reduceMove $ s1 ++ s2
Lysxia/twentyseven
src/Rubik/Solver/TwoPhase.hs
mit
1,730
4
14
311
464
260
204
42
1
----------------------------------------------------------------------------- -- -- Module : Language.PureScript.Sugar.Operators -- Copyright : (c) 2013-15 Phil Freeman, (c) 2014-15 Gary Burgess -- License : MIT (http://opensource.org/licenses/MIT) -- -- Maintainer : Phil Freeman <paf31@cantab.net> -- Stability : experimental -- Portability : -- -- | -- This module implements the desugaring pass which reapplies binary operators based -- on their fixity data and removes explicit parentheses. -- -- The value parser ignores fixity data when parsing binary operator applications, so -- it is necessary to reorder them here. -- ----------------------------------------------------------------------------- {-# LANGUAGE Rank2Types #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RecordWildCards #-} module Language.PureScript.Sugar.Operators ( rebracket, removeSignedLiterals, desugarOperatorSections ) where import Prelude () import Prelude.Compat import Language.PureScript.Crash import Language.PureScript.AST import Language.PureScript.Errors import Language.PureScript.Names import Language.PureScript.Externs import Control.Monad.State import Control.Monad.Error.Class (MonadError(..)) import Control.Monad.Supply.Class import Data.Function (on) import Data.Functor.Identity import Data.List (groupBy, sortBy) import qualified Text.Parsec as P import qualified Text.Parsec.Pos as P import qualified Text.Parsec.Expr as P import qualified Language.PureScript.Constants as C -- | -- Remove explicit parentheses and reorder binary operator applications -- rebracket :: (Applicative m, MonadError MultipleErrors m) => [ExternsFile] -> [Module] -> m [Module] rebracket externs ms = do let fixities = concatMap externsFixities externs ++ concatMap collectFixities ms ensureNoDuplicates $ map (\(i, pos, _) -> (i, pos)) fixities let opTable = customOperatorTable $ map (\(i, _, f) -> (i, f)) fixities traverse (rebracketModule opTable) ms removeSignedLiterals :: Module -> Module removeSignedLiterals (Module ss coms mn ds exts) = Module ss coms mn (map f' ds) exts where (f', _, _) = everywhereOnValues id go id go (UnaryMinus val) = App (Var (Qualified Nothing (Ident C.negate))) val go other = other rebracketModule :: (Applicative m, MonadError MultipleErrors m) => [[(Qualified Ident, Expr -> Expr -> Expr, Associativity)]] -> Module -> m Module rebracketModule opTable (Module ss coms mn ds exts) = let (f, _, _) = everywhereOnValuesTopDownM return (matchOperators opTable) return in Module ss coms mn <$> (map removeParens <$> parU ds f) <*> pure exts removeParens :: Declaration -> Declaration removeParens = let (f, _, _) = everywhereOnValues id go id in f where go (Parens val) = val go val = val externsFixities :: ExternsFile -> [(Qualified Ident, SourceSpan, Fixity)] externsFixities ExternsFile{..} = [ (Qualified (Just efModuleName) (Op op), internalModuleSourceSpan "", Fixity assoc prec) | ExternsFixity assoc prec op <- efFixities ] collectFixities :: Module -> [(Qualified Ident, SourceSpan, Fixity)] collectFixities (Module _ _ moduleName ds _) = concatMap collect ds where collect :: Declaration -> [(Qualified Ident, SourceSpan, Fixity)] collect (PositionedDeclaration pos _ (FixityDeclaration fixity name)) = [(Qualified (Just moduleName) (Op name), pos, fixity)] collect FixityDeclaration{} = internalError "Fixity without srcpos info" collect _ = [] ensureNoDuplicates :: (MonadError MultipleErrors m) => [(Qualified Ident, SourceSpan)] -> m () ensureNoDuplicates m = go $ sortBy (compare `on` fst) m where go [] = return () go [_] = return () go ((x@(Qualified (Just mn) name), _) : (y, pos) : _) | x == y = rethrow (addHint (ErrorInModule mn)) $ rethrowWithPosition pos $ throwError . errorMessage $ MultipleFixities name go (_ : rest) = go rest customOperatorTable :: [(Qualified Ident, Fixity)] -> [[(Qualified Ident, Expr -> Expr -> Expr, Associativity)]] customOperatorTable fixities = let applyUserOp ident t1 = App (App (Var ident) t1) userOps = map (\(name, Fixity a p) -> (name, applyUserOp name, p, a)) fixities sorted = sortBy (flip compare `on` (\(_, _, p, _) -> p)) userOps groups = groupBy ((==) `on` (\(_, _, p, _) -> p)) sorted in map (map (\(name, f, _, a) -> (name, f, a))) groups type Chain = [Either Expr Expr] matchOperators :: forall m. (MonadError MultipleErrors m) => [[(Qualified Ident, Expr -> Expr -> Expr, Associativity)]] -> Expr -> m Expr matchOperators ops = parseChains where parseChains :: Expr -> m Expr parseChains b@BinaryNoParens{} = bracketChain (extendChain b) parseChains other = return other extendChain :: Expr -> Chain extendChain (BinaryNoParens op l r) = Left l : Right op : extendChain r extendChain other = [Left other] bracketChain :: Chain -> m Expr bracketChain = either (\_ -> internalError "matchOperators: cannot reorder operators") return . P.parse (P.buildExpressionParser opTable parseValue <* P.eof) "operator expression" opTable = [P.Infix (P.try (parseTicks >>= \op -> return (\t1 t2 -> App (App op t1) t2))) P.AssocLeft] : map (map (\(name, f, a) -> P.Infix (P.try (matchOp name) >> return f) (toAssoc a))) ops ++ [[ P.Infix (P.try (parseOp >>= \ident -> return (\t1 t2 -> App (App (Var ident) t1) t2))) P.AssocLeft ]] toAssoc :: Associativity -> P.Assoc toAssoc Infixl = P.AssocLeft toAssoc Infixr = P.AssocRight toAssoc Infix = P.AssocNone token :: (P.Stream s Identity t) => (t -> Maybe a) -> P.Parsec s u a token = P.token (const "") (const (P.initialPos "")) parseValue :: P.Parsec Chain () Expr parseValue = token (either Just (const Nothing)) P.<?> "expression" parseOp :: P.Parsec Chain () (Qualified Ident) parseOp = token (either (const Nothing) fromOp) P.<?> "operator" where fromOp (Var q@(Qualified _ (Op _))) = Just q fromOp _ = Nothing parseTicks :: P.Parsec Chain () Expr parseTicks = token (either (const Nothing) fromOther) P.<?> "infix function" where fromOther (Var (Qualified _ (Op _))) = Nothing fromOther v = Just v matchOp :: Qualified Ident -> P.Parsec Chain () () matchOp op = do ident <- parseOp guard $ ident == op desugarOperatorSections :: forall m. (Applicative m, MonadSupply m, MonadError MultipleErrors m) => Module -> m Module desugarOperatorSections (Module ss coms mn ds exts) = Module ss coms mn <$> traverse goDecl ds <*> pure exts where goDecl :: Declaration -> m Declaration (goDecl, _, _) = everywhereOnValuesM return goExpr return goExpr :: Expr -> m Expr goExpr (OperatorSection op (Left val)) = return $ App op val goExpr (OperatorSection op (Right val)) = do arg <- Ident <$> freshName return $ Abs (Left arg) $ App (App op (Var (Qualified Nothing arg))) val goExpr other = return other
michaelficarra/purescript
src/Language/PureScript/Sugar/Operators.hs
mit
6,892
0
23
1,211
2,485
1,321
1,164
117
4
module Escape where import Data.Text (pack, unpack) import Data.Text.Encoding (encodeUtf8, decodeUtf8) import Prelude import Text.ShellEscape (Bash, escape, bytes) -- | Escapes ASCII string as a bash literal. Might work for UTF-8, not -- certain. stringToBashLiteral :: String -> String stringToBashLiteral = unpack . decodeUtf8 . bytes @Bash . escape . encodeUtf8 . pack
mgsloan/compconfig
env/src/Escape.hs
mit
374
0
10
55
91
54
37
-1
-1
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-| This module uses 'RecAll' to extend common typeclass methods to records. Generally, it is preferable to use the original typeclass methods to these variants. For example, in most places where 'recCompare' could be used, you could use 'compare' instead. They are useful in scenarios that involve working on unknown subsets of a record's fields because 'RecAll' constraints can easily be weakened. An example of this is given at the bottom of this page. -} module Data.Vinyl.Class.Method ( -- * Mapping methods over records RecMapMethod(..) , rmapMethodF , mapFields , RecMapMethod1(..) , RecPointed(..) , rtraverseInMethod , rsequenceInFields -- * Support for 'RecMapMethod' , FieldTyper, ApplyFieldTyper, PayloadType -- * Eq Functions , recEq -- * Ord Functions , recCompare -- * Monoid Functions , recMempty , recMappend , recMconcat -- * Num Functions , recAdd , recSubtract , recMultiply , recAbs , recSignum , recNegate -- * Bounded Functions , recMinBound , recMaxBound -- * Example -- $example ) where import Data.Functor.Product (Product(Pair)) import Data.Vinyl.Core import Data.Vinyl.Derived (KnownField, AllFields, FieldRec, traverseField) import Data.Vinyl.Functor ((:.), getCompose, ElField(..)) import Data.Vinyl.TypeLevel #if __GLASGOW_HASKELL__ < 804 import Data.Monoid #endif recEq :: RecAll f rs Eq => Rec f rs -> Rec f rs -> Bool recEq RNil RNil = True recEq (a :& as) (b :& bs) = a == b && recEq as bs recCompare :: RecAll f rs Ord => Rec f rs -> Rec f rs -> Ordering recCompare RNil RNil = EQ recCompare (a :& as) (b :& bs) = compare a b <> recCompare as bs -- | This function differs from the original 'mempty' in that -- it takes an argument. In some cases, you will already -- have a record of the type you are interested in, and -- that can be passed an the argument. In other situations -- where this is not the case, you may need the -- interpretation function of the argument record to be -- @Const ()@ or @Proxy@ so the you can generate the -- argument with 'rpure'. recMempty :: RecAll f rs Monoid => Rec proxy rs -> Rec f rs recMempty RNil = RNil recMempty (_ :& rs) = mempty :& recMempty rs recMappend :: RecAll f rs Monoid => Rec f rs -> Rec f rs -> Rec f rs recMappend RNil RNil = RNil recMappend (a :& as) (b :& bs) = mappend a b :& recMappend as bs -- | This function differs from the original 'mconcat'. -- See 'recMempty'. recMconcat :: RecAll f rs Monoid => Rec proxy rs -> [Rec f rs] -> Rec f rs recMconcat p [] = recMempty p recMconcat p (rec : recs) = recMappend rec (recMconcat p recs) recAdd :: RecAll f rs Num => Rec f rs -> Rec f rs -> Rec f rs recAdd RNil RNil = RNil recAdd (a :& as) (b :& bs) = (a + b) :& recAdd as bs recSubtract :: RecAll f rs Num => Rec f rs -> Rec f rs -> Rec f rs recSubtract RNil RNil = RNil recSubtract (a :& as) (b :& bs) = (a - b) :& recSubtract as bs recMultiply :: RecAll f rs Num => Rec f rs -> Rec f rs -> Rec f rs recMultiply RNil RNil = RNil recMultiply (a :& as) (b :& bs) = (a * b) :& recSubtract as bs recAbs :: RecAll f rs Num => Rec f rs -> Rec f rs recAbs RNil = RNil recAbs (a :& as) = abs a :& recAbs as recSignum :: RecAll f rs Num => Rec f rs -> Rec f rs recSignum RNil = RNil recSignum (a :& as) = signum a :& recAbs as recNegate :: RecAll f rs Num => Rec f rs -> Rec f rs recNegate RNil = RNil recNegate (a :& as) = negate a :& recAbs as -- | This function differs from the original 'minBound'. -- See 'recMempty'. recMinBound :: RecAll f rs Bounded => Rec proxy rs -> Rec f rs recMinBound RNil = RNil recMinBound (_ :& rs) = minBound :& recMinBound rs -- | This function differs from the original 'maxBound'. -- See 'recMempty'. recMaxBound :: RecAll f rs Bounded => Rec proxy rs -> Rec f rs recMaxBound RNil = RNil recMaxBound (_ :& rs) = maxBound :& recMaxBound rs -- | When we wish to apply a typeclass method to each field of a -- 'Rec', we typically care about typeclass instances of the record -- field types irrespective of the record's functor context. To expose -- the field types themselves, we utilize a constraint built from a -- defunctionalized type family in the 'rmapMethod' method. The -- symbols of the function space are defined by this data type. data FieldTyper = FieldId | FieldSnd -- | The interpretation function of the 'FieldTyper' symbols. type family ApplyFieldTyper (f :: FieldTyper) (a :: k) :: * where ApplyFieldTyper 'FieldId a = a ApplyFieldTyper 'FieldSnd a = Snd a -- | A mapping of record contexts into the 'FieldTyper' function -- space. We explicitly match on 'ElField' to pick out the payload -- type, and 'Compose' to pick out the inner-most context. All other -- type constructor contexts are understood to not perform any -- computation on their arguments. type family FieldPayload (f :: u -> *) :: FieldTyper where FieldPayload ElField = 'FieldSnd FieldPayload (f :. g) = FieldPayload g FieldPayload f = 'FieldId -- | Shorthand for combining 'ApplyFieldTyper' and 'FieldPayload'. type family PayloadType f (a :: u) :: * where PayloadType f a = ApplyFieldTyper (FieldPayload f) a -- | Generate a record from fields derived from type class -- instances. class RecPointed c f ts where rpointMethod :: (forall a. c (f a) => f a) -> Rec f ts instance RecPointed c f '[] where rpointMethod _ = RNil {-# INLINE rpointMethod #-} instance (c (f t), RecPointed c f ts) => RecPointed c f (t ': ts) where rpointMethod f = f :& rpointMethod @c f {-# INLINE rpointMethod #-} -- | Apply a typeclass method to each field of a 'Rec' where the class -- constrains the index of the field, but not its interpretation -- functor. class RecMapMethod c f ts where rmapMethod :: (forall a. c (PayloadType f a) => f a -> g a) -> Rec f ts -> Rec g ts -- | Apply a typeclass method to each field of a 'Rec' where the class -- constrains the field when considered as a value interpreted by the -- record's interpretation functor. class RecMapMethod1 c f ts where rmapMethod1 :: (forall a. c (f a) => f a -> g a) -> Rec f ts -> Rec g ts instance RecMapMethod c f '[] where rmapMethod _ RNil = RNil {-# INLINE rmapMethod #-} instance RecMapMethod1 c f '[] where rmapMethod1 _ RNil = RNil {-# INLINE rmapMethod1 #-} instance (c (PayloadType f t), RecMapMethod c f ts) => RecMapMethod c f (t ': ts) where rmapMethod f (x :& xs) = f x :& rmapMethod @c f xs {-# INLINE rmapMethod #-} instance (c (f t), RecMapMethod1 c f ts) => RecMapMethod1 c f (t ': ts) where rmapMethod1 f (x :& xs) = f x :& rmapMethod1 @c f xs {-# INLINE rmapMethod1 #-} -- | Apply a typeclass method to each field of a @Rec f ts@ using the -- 'Functor' instance for @f@ to lift the function into the -- functor. This is a commonly-used specialization of 'rmapMethod' -- composed with 'fmap'. rmapMethodF :: forall c f ts. (Functor f, FieldPayload f ~ 'FieldId, RecMapMethod c f ts) => (forall a. c a => a -> a) -> Rec f ts -> Rec f ts rmapMethodF f = rmapMethod @c (fmap f) {-# INLINE rmapMethodF #-} -- | Apply a typeclass method to each field of a 'FieldRec'. This is a -- specialization of 'rmapMethod'. mapFields :: forall c ts. RecMapMethod c ElField ts => (forall a. c a => a -> a) -> FieldRec ts -> FieldRec ts mapFields f = rmapMethod @c g where g :: c (PayloadType ElField t) => ElField t -> ElField t g (Field x) = Field (f x) {-# INLINE mapFields #-} -- | Like 'rtraverseIn', but the function between functors may be -- constrained. rtraverseInMethod :: forall c h f g rs. (RMap rs, RPureConstrained c rs, RApply rs) => (forall a. c a => f a -> g (ApplyToField h a)) -> Rec f rs -> Rec g (MapTyCon h rs) rtraverseInMethod f = rtraverseIn @h (withPairedDict @c f) . rzipWith Pair (rpureConstrained @c aux) where aux :: c b => DictOnly c b aux = DictOnly -- Note: rtraverseInMethod is written with that `aux` helper in order -- to work around compatibility with GHC < 8.4. Write it more -- naturally as `DictOnly @c` does not work with older compilers. -- | Push an outer layer of interpretation functor into each named field. rsequenceInFields :: forall f rs. (Functor f, AllFields rs, RMap rs) => Rec (f :. ElField) rs -> Rec ElField (MapTyCon f rs) rsequenceInFields = rtraverseInMethod @KnownField (traverseField id . getCompose) {- $example This module provides variants of typeclass methods that have a 'RecAll' constraint instead of the normal typeclass constraint. For example, a type-specialized 'compare' would look like this: > compare :: Ord (Rec f rs) => Rec f rs -> Rec f rs -> Ordering The 'recCompare' function looks like this: > recCompare :: RecAll f rs Ord => Rec f rs -> Rec f rs -> Ordering The only difference is the constraint. Let's look at a potential use case for these functions. Let's write a function that projects out a subrecord from two records and then compares those for equality. We can write this with the '<:' operator from @Data.Vinyl.Lens@ and the normal 'compare' function. We don't need 'recCompare': > -- This needs ScopedTypeVariables > projectAndCompare :: forall super sub f. (super <: sub, Ord (Rec f sub)) > => Proxy sub -> Rec f super -> Rec f super -> Ordering > projectAndCompare _ a b = compare (rcast a :: Rec f sub) (rcast b :: Rec f sub) That works fine for the majority of use cases, and it is probably how you should write the function if it does everything you need. However, let's consider a somewhat more complicated case. What if the exact subrecord we were projecting couldn't be known at compile time? Assume that the end user was allowd to choose the fields on which he or she wanted to compare records. The @projectAndCompare@ function cannot handle this because of the @Ord (Rec f sub)@ constraint. Even if we amend the constraint to read @Ord (Rec f super)@ instead, we cannot use this information to recover the @Ord (Rec f sub)@ constraint that we need. Let's try another approach. We can use the following GADT to prove subsethood: > data Sublist (super :: [k]) (sub :: [k]) where > SublistNil :: Sublist '[] > SublistSuper :: Proxy r -> Sublist super sub -> Sublist (r ': super) sub > SublistBoth :: Proxy r -> Sublist super sub -> Sublist (r ': super) (r ': sub) > > projectRec :: Sublist super sub -> Rec f super -> Rec f sub > projectRec s r = case s of > SublistNil -> RNil > SublistBoth n snext -> case r of > rhead :& rtail -> rhead :& projectRec snext rtail > SublistSuper n snext -> case r of > rhead :& rtail -> projectRec snext rtail It is also possible to write a typeclass to generate @Sublist@s implicitly, but that is beyond the scope of this example. Let's now write a function to use @Sublist@ to weaken a 'RecAll' constraint: > import Data.Vinyl.Core hiding (Dict) > import Data.Constraint > > weakenRecAll :: Proxy f -> Proxy c -> Sublist super sub -> RecAll f super c :- RecAll f sub c > weakenRecAll f c s = case s of > SublistNil -> Sub Dict > SublistSuper _ snext -> Sub $ case weakenRecAll f c snext of > Sub Dict -> Dict > SublistBoth _ snext -> Sub $ case weakenRecAll f c snext of > Sub Dict -> Dict Now we can write a different version of our original function: > -- This needs ScopedTypeVariables > projectAndCompare2 :: forall super sub f. (RecAll f super Ord) > => Sublist super sub -> Rec f super -> Rec f super -> Ordering > projectAndCompare2 s a b = case weakenRecAll (Proxy :: Proxy f) (Proxy :: Proxy Ord) s of > Sub Dict -> recCompare (projectRec s a) (projectRec s b) Notice that in this case, the 'Ord' constraint applies to the full set of fields and is then weakened to target a subset of them instead. -}
VinylRecords/Vinyl
Data/Vinyl/Class/Method.hs
mit
12,628
0
14
2,935
2,341
1,239
1,102
144
1
{-# LANGUAGE TupleSections #-} module TypeChecker where import Control.Applicative hiding (empty) import Control.Monad import Control.Monad.Except import Control.Monad.Reader import Data.Map (Map,(!),mapWithKey,assocs,filterWithKey,elems,keys ,intersection,intersectionWith,intersectionWithKey ,toList,fromList) import qualified Data.Map as Map import qualified Data.Traversable as T import Connections import CTT import Eval -- Type checking monad type Typing a = ReaderT TEnv (ExceptT String IO) a -- Environment for type checker data TEnv = TEnv { names :: [String] -- generated names , indent :: Int , env :: Env , verbose :: Bool -- Should it be verbose and print what it typechecks? } deriving (Eq) verboseEnv, silentEnv :: TEnv verboseEnv = TEnv [] 0 emptyEnv True silentEnv = TEnv [] 0 emptyEnv False -- Trace function that depends on the verbosity flag trace :: String -> Typing () trace s = do b <- asks verbose when b $ liftIO (putStrLn s) ------------------------------------------------------------------------------- -- | Functions for running computations in the type checker monad runTyping :: TEnv -> Typing a -> IO (Either String a) runTyping env t = runExceptT $ runReaderT t env runDecls :: TEnv -> Decls -> IO (Either String TEnv) runDecls tenv d = runTyping tenv $ do checkDecls d return $ addDecls d tenv runDeclss :: TEnv -> [Decls] -> IO (Maybe String,TEnv) runDeclss tenv [] = return (Nothing, tenv) runDeclss tenv (d:ds) = do x <- runDecls tenv d case x of Right tenv' -> runDeclss tenv' ds Left s -> return (Just s, tenv) runInfer :: TEnv -> Ter -> IO (Either String Val) runInfer lenv e = runTyping lenv (infer e) ------------------------------------------------------------------------------- -- | Modifiers for the environment addTypeVal :: (Ident,Val) -> TEnv -> TEnv addTypeVal (x,a) (TEnv ns ind rho v) = let w@(VVar n _) = mkVarNice ns x a in TEnv (n:ns) ind (upd (x,w) rho) v addSub :: (Name,Formula) -> TEnv -> TEnv addSub iphi (TEnv ns ind rho v) = TEnv ns ind (sub iphi rho) v addSubs :: [(Name,Formula)] -> TEnv -> TEnv addSubs = flip $ foldr addSub addType :: (Ident,Ter) -> TEnv -> TEnv addType (x,a) tenv@(TEnv _ _ rho _) = addTypeVal (x,eval rho a) tenv addBranch :: [(Ident,Val)] -> Env -> TEnv -> TEnv addBranch nvs env (TEnv ns ind rho v) = TEnv ([n | (_,VVar n _) <- nvs] ++ ns) ind (upds nvs rho) v addDecls :: Decls -> TEnv -> TEnv addDecls d (TEnv ns ind rho v) = TEnv ns ind (def d rho) v addTele :: Tele -> TEnv -> TEnv addTele xas lenv = foldl (flip addType) lenv xas faceEnv :: Face -> TEnv -> TEnv faceEnv alpha tenv = tenv{env=env tenv `face` alpha} ------------------------------------------------------------------------------- -- | Various useful functions -- Extract the type of a label as a closure getLblType :: LIdent -> Val -> Typing (Tele, Env) getLblType c (Ter (Sum _ _ cas) r) = case lookupLabel c cas of Just as -> return (as,r) Nothing -> throwError ("getLblType: " ++ show c ++ " in " ++ show cas) getLblType c (Ter (HSum _ _ cas) r) = case lookupLabel c cas of Just as -> return (as,r) Nothing -> throwError ("getLblType: " ++ show c ++ " in " ++ show cas) getLblType c u = throwError ("expected a data type for the constructor " ++ c ++ " but got " ++ show u) -- Monadic version of unless unlessM :: Monad m => m Bool -> m () -> m () unlessM mb x = mb >>= flip unless x mkVars :: [String] -> Tele -> Env -> [(Ident,Val)] mkVars _ [] _ = [] mkVars ns ((x,a):xas) nu = let w@(VVar n _) = mkVarNice ns x (eval nu a) in (x,w) : mkVars (n:ns) xas (upd (x,w) nu) -- Test if two values are convertible (===) :: Convertible a => a -> a -> Typing Bool u === v = conv <$> asks names <*> pure u <*> pure v -- eval in the typing monad evalTyping :: Ter -> Typing Val evalTyping t = eval <$> asks env <*> pure t ------------------------------------------------------------------------------- -- | The bidirectional type checker -- Check that t has type a check :: Val -> Ter -> Typing () check a t = case (a,t) of (_,Undef{}) -> return () (_,Hole l) -> do rho <- asks env let e = unlines (reverse (contextOfEnv rho)) ns <- asks names trace $ "\nHole at " ++ show l ++ ":\n\n" ++ e ++ replicate 80 '-' ++ "\n" ++ show (normal ns a) ++ "\n" (_,Con c es) -> do (bs,nu) <- getLblType c a checks (bs,nu) es (VU,Pi f) -> checkFam f (VU,Sigma f) -> checkFam f (VU,Sum _ _ bs) -> forM_ bs $ \lbl -> case lbl of OLabel _ tele -> checkTele tele PLabel _ tele is ts -> throwError $ "check: no path constructor allowed in " ++ show t (VU,HSum _ _ bs) -> forM_ bs $ \lbl -> case lbl of OLabel _ tele -> checkTele tele PLabel _ tele is ts -> do checkTele tele rho <- asks env unless (all (`elem` is) (domain ts)) $ throwError "names in path label system" -- TODO mapM_ checkFresh is let iis = zip is (map Atom is) local (addSubs iis . addTele tele) $ do checkSystemWith ts $ \alpha talpha -> local (faceEnv alpha) $ -- NB: the type doesn't depend on is check (Ter t rho) talpha rho' <- asks env checkCompSystem (evalSystem rho' ts) (VPi va@(Ter (Sum _ _ cas) nu) f,Split _ _ ty ces) -> do check VU ty rho <- asks env unlessM (a === eval rho ty) $ throwError "check: split annotations" if map labelName cas == map branchName ces then sequence_ [ checkBranch (lbl,nu) f brc (Ter t rho) va | (brc, lbl) <- zip ces cas ] else throwError "case branches does not match the data type" (VPi va@(Ter (HSum _ _ cas) nu) f,Split _ _ ty ces) -> do check VU ty rho <- asks env unlessM (a === eval rho ty) $ throwError "check: split annotations" if map labelName cas == map branchName ces then sequence_ [ checkBranch (lbl,nu) f brc (Ter t rho) va | (brc, lbl) <- zip ces cas ] else throwError "case branches does not match the data type" (VPi a f,Lam x a' t) -> do check VU a' ns <- asks names rho <- asks env unlessM (a === eval rho a') $ throwError $ "check: lam types don't match" ++ "\nlambda type annotation: " ++ show a' ++ "\ndomain of Pi: " ++ show a ++ "\nnormal form of type: " ++ show (normal ns a) let var = mkVarNice ns x a local (addTypeVal (x,a)) $ check (app f var) t (VSigma a f, Pair t1 t2) -> do check a t1 v <- evalTyping t1 check (app f v) t2 (_,Where e d) -> do local (\tenv@TEnv{indent=i} -> tenv{indent=i + 2}) $ checkDecls d local (addDecls d) $ check a e (VU,PathP a e0 e1) -> do (a0,a1) <- checkPLam (constPath VU) a check a0 e0 check a1 e1 (VPathP p a0 a1,PLam _ e) -> do (u0,u1) <- checkPLam p t ns <- asks names unless (conv ns a0 u0 && conv ns a1 u1) $ throwError $ "path endpoints don't match for " ++ show e ++ ", got " ++ show (u0,u1) ++ ", but expected " ++ show (a0,a1) (VU,Glue a ts) -> do check VU a rho <- asks env checkGlue (eval rho a) ts (VGlue va ts,GlueElem u us) -> do check va u vu <- evalTyping u checkGlueElem vu ts us (VCompU va ves,GlueElem u us) -> do check va u vu <- evalTyping u checkGlueElemU vu ves us (VU,Id a a0 a1) -> do check VU a va <- evalTyping a check va a0 check va a1 (VId va va0 va1,IdPair w ts) -> do check (VPathP (constPath va) va0 va1) w vw <- evalTyping w checkSystemWith ts $ \alpha tAlpha -> local (faceEnv alpha) $ do check (va `face` alpha) tAlpha vtAlpha <- evalTyping tAlpha unlessM (vw `face` alpha === constPath vtAlpha) $ throwError "malformed eqC" rho <- asks env checkCompSystem (evalSystem rho ts) -- Not needed _ -> do v <- infer t unlessM (v === a) $ throwError $ "check conv:\n" ++ show v ++ "\n/=\n" ++ show a -- Check a list of declarations checkDecls :: Decls -> Typing () checkDecls (MutualDecls _ []) = return () checkDecls (MutualDecls l d) = do a <- asks env let (idents,tele,ters) = (declIdents d,declTele d,declTers d) ind <- asks indent trace (replicate ind ' ' ++ "Checking: " ++ unwords idents) checkTele tele local (addDecls (MutualDecls l d)) $ do rho <- asks env checks (tele,rho) ters checkDecls (OpaqueDecl _) = return () checkDecls (TransparentDecl _) = return () checkDecls TransparentAllDecl = return () -- Check a telescope checkTele :: Tele -> Typing () checkTele [] = return () checkTele ((x,a):xas) = do check VU a local (addType (x,a)) $ checkTele xas -- Check a family checkFam :: Ter -> Typing () checkFam (Lam x a b) = do check VU a local (addType (x,a)) $ check VU b checkFam x = throwError $ "checkFam: " ++ show x -- Check that a system is compatible checkCompSystem :: System Val -> Typing () checkCompSystem vus = do ns <- asks names unless (isCompSystem ns vus) (throwError $ "Incompatible system " ++ showSystem vus) -- Check the values at corresponding faces with a function, assumes -- systems have the same faces checkSystemsWith :: System a -> System b -> (Face -> a -> b -> Typing c) -> Typing () checkSystemsWith us vs f = sequence_ $ elems $ intersectionWithKey f us vs -- Check the faces of a system checkSystemWith :: System a -> (Face -> a -> Typing b) -> Typing () checkSystemWith us f = sequence_ $ elems $ mapWithKey f us -- Check a glueElem checkGlueElem :: Val -> System Val -> System Ter -> Typing () checkGlueElem vu ts us = do unless (keys ts == keys us) (throwError ("Keys don't match in " ++ show ts ++ " and " ++ show us)) rho <- asks env checkSystemsWith ts us (\alpha vt u -> local (faceEnv alpha) $ check (equivDom vt) u) let vus = evalSystem rho us checkSystemsWith ts vus (\alpha vt vAlpha -> unlessM (app (equivFun vt) vAlpha === (vu `face` alpha)) $ throwError $ "Image of glue component " ++ show vAlpha ++ " doesn't match " ++ show vu) checkCompSystem vus -- Check a glueElem against VComp _ ves checkGlueElemU :: Val -> System Val -> System Ter -> Typing () checkGlueElemU vu ves us = do unless (keys ves == keys us) (throwError ("Keys don't match in " ++ show ves ++ " and " ++ show us)) rho <- asks env checkSystemsWith ves us (\alpha ve u -> local (faceEnv alpha) $ check (ve @@ One) u) let vus = evalSystem rho us checkSystemsWith ves vus (\alpha ve vAlpha -> unlessM (eqFun ve vAlpha === (vu `face` alpha)) $ throwError $ "Transport of glueElem (for compU) component " ++ show vAlpha ++ " doesn't match " ++ show vu) checkCompSystem vus checkGlue :: Val -> System Ter -> Typing () checkGlue va ts = do checkSystemWith ts (\alpha tAlpha -> checkEquiv (va `face` alpha) tAlpha) rho <- asks env checkCompSystem (evalSystem rho ts) -- An iso for a type b is a five-tuple: (a,f,g,s,t) where -- a : U -- f : a -> b -- g : b -> a -- s : forall (y : b), f (g y) = y -- t : forall (x : a), g (f x) = x mkIso :: Val -> Val mkIso vb = eval rho $ Sigma $ Lam "a" U $ Sigma $ Lam "f" (Pi (Lam "_" a b)) $ Sigma $ Lam "g" (Pi (Lam "_" b a)) $ Sigma $ Lam "s" (Pi (Lam "y" b $ PathP (PLam (Name "_") b) (App f (App g y)) y)) $ Pi (Lam "x" a $ PathP (PLam (Name "_") a) (App g (App f x)) x) where [a,b,f,g,x,y] = map Var ["a","b","f","g","x","y"] rho = upd ("b",vb) emptyEnv -- An equivalence for a type a is a triple (t,f,p) where -- t : U -- f : t -> a -- p : (x : a) -> isContr ((y:t) * Id a x (f y)) -- with isContr c = (z : c) * ((z' : C) -> Id c z z') mkEquiv :: Val -> Val mkEquiv va = eval rho $ Sigma $ Lam "t" U $ Sigma $ Lam "f" (Pi (Lam "_" t a)) $ Pi (Lam "x" a $ iscontrfib) where [a,b,f,x,y,s,t,z] = map Var ["a","b","f","x","y","s","t","z"] rho = upd ("a",va) emptyEnv fib = Sigma $ Lam "y" t (PathP (PLam (Name "_") a) x (App f y)) iscontrfib = Sigma $ Lam "s" fib $ Pi $ Lam "z" fib $ PathP (PLam (Name "_") fib) s z checkEquiv :: Val -> Ter -> Typing () checkEquiv va equiv = check (mkEquiv va) equiv checkIso :: Val -> Ter -> Typing () checkIso vb iso = check (mkIso vb) iso checkBranch :: (Label,Env) -> Val -> Branch -> Val -> Val -> Typing () checkBranch (OLabel _ tele,nu) f (OBranch c ns e) _ _ = do ns' <- asks names let us = map snd $ mkVars ns' tele nu local (addBranch (zip ns us) nu) $ check (app f (VCon c us)) e checkBranch (PLabel _ tele is ts,nu) f (PBranch c ns js e) g va = do ns' <- asks names -- mapM_ checkFresh js let us = mkVars ns' tele nu vus = map snd us js' = map Atom js vts = evalSystem (subs (zip is js') (upds us nu)) ts vgts = intersectionWith app (border g vts) vts local (addSubs (zip js js') . addBranch (zip ns vus) nu) $ do check (app f (VPCon c va vus js')) e ve <- evalTyping e -- TODO: combine with next two lines? let veborder = border ve vts unlessM (veborder === vgts) $ throwError $ "Faces in branch for " ++ show c ++ " don't match:" ++ "\ngot\n" ++ showSystem veborder ++ "\nbut expected\n" ++ showSystem vgts checkFormula :: Formula -> Typing () checkFormula phi = do rho <- asks env let dom = domainEnv rho unless (all (`elem` dom) (support phi)) $ throwError $ "checkFormula: " ++ show phi checkFresh :: Name -> Typing () checkFresh i = do rho <- asks env when (i `elem` support rho) (throwError $ show i ++ " is already declared") -- Check that a term is a PLam and output the source and target checkPLam :: Val -> Ter -> Typing (Val,Val) checkPLam v (PLam i a) = do rho <- asks env -- checkFresh i local (addSub (i,Atom i)) $ check (v @@ i) a return (eval (sub (i,Dir 0) rho) a,eval (sub (i,Dir 1) rho) a) checkPLam v t = do vt <- infer t case vt of VPathP a a0 a1 -> do unlessM (a === v) $ throwError "checkPLam" return (a0,a1) _ -> throwError $ show vt ++ " is not a path" -- Return system such that: -- rhoalpha |- p_alpha : Id (va alpha) (t0 rhoalpha) ualpha -- Moreover, check that the system ps is compatible. checkPLamSystem :: Ter -> Val -> System Ter -> Typing (System Val) checkPLamSystem t0 va ps = do rho <- asks env v <- T.sequence $ mapWithKey (\alpha pAlpha -> local (faceEnv alpha) $ do rhoAlpha <- asks env (a0,a1) <- checkPLam (va `face` alpha) pAlpha unlessM (a0 === eval rhoAlpha t0) $ throwError $ "Incompatible system " ++ showSystem ps ++ ", component\n " ++ show pAlpha ++ "\nincompatible with\n " ++ show t0 ++ "\na0 = " ++ show a0 ++ "\nt0alpha = " ++ show (eval rhoAlpha t0) ++ "\nva = " ++ show va return a1) ps checkCompSystem (evalSystem rho ps) return v checks :: (Tele,Env) -> [Ter] -> Typing () checks ([],_) [] = return () checks ((x,a):xas,nu) (e:es) = do check (eval nu a) e v' <- evalTyping e checks (xas,upd (x,v') nu) es checks _ _ = throwError "checks: incorrect number of arguments" -- infer the type of e infer :: Ter -> Typing Val infer e = case e of U -> return VU -- U : U Var n -> lookType n <$> asks env App t u -> do c <- infer t case c of VPi a f -> do check a u v <- evalTyping u return $ app f v _ -> throwError $ show c ++ " is not a product" Fst t -> do c <- infer t case c of VSigma a f -> return a _ -> throwError $ show c ++ " is not a sigma-type" Snd t -> do c <- infer t case c of VSigma a f -> do v <- evalTyping t return $ app f (fstVal v) _ -> throwError $ show c ++ " is not a sigma-type" Where t d -> do checkDecls d local (addDecls d) $ infer t UnGlueElem e _ -> do t <- infer e case t of VGlue a _ -> return a _ -> throwError (show t ++ " is not a Glue") AppFormula e phi -> do checkFormula phi t <- infer e case t of VPathP a _ _ -> return $ a @@ phi _ -> throwError (show e ++ " is not a path") Comp a t0 ps -> do (va0, va1) <- checkPLam (constPath VU) a va <- evalTyping a check va0 t0 checkPLamSystem t0 va ps return va1 Fill a t0 ps -> do (va0, va1) <- checkPLam (constPath VU) a va <- evalTyping a check va0 t0 checkPLamSystem t0 va ps vt <- evalTyping t0 rho <- asks env let vps = evalSystem rho ps return (VPathP va vt (compLine va vt vps)) PCon c a es phis -> do check VU a va <- evalTyping a (bs,nu) <- getLblType c va checks (bs,nu) es mapM_ checkFormula phis return va IdJ a u c d x p -> do check VU a va <- evalTyping a check va u vu <- evalTyping u let refu = VIdPair (constPath vu) $ mkSystem [(eps,vu)] rho <- asks env let z = Var "z" ctype = eval rho $ Pi $ Lam "z" a $ Pi $ Lam "_" (Id a u z) U check ctype c vc <- evalTyping c check (app (app vc vu) refu) d check va x vx <- evalTyping x check (VId va vu vx) p vp <- evalTyping p return (app (app vc vx) vp) _ -> throwError ("infer " ++ show e) -- Not used since we have U : U -- -- (=?=) :: Typing Ter -> Ter -> Typing () -- m =?= s2 = do -- s1 <- m -- unless (s1 == s2) $ throwError (show s1 ++ " =/= " ++ show s2) -- -- checkTs :: [(String,Ter)] -> Typing () -- checkTs [] = return () -- checkTs ((x,a):xas) = do -- checkType a -- local (addType (x,a)) (checkTs xas) -- -- checkType :: Ter -> Typing () -- checkType t = case t of -- U -> return () -- Pi a (Lam x b) -> do -- checkType a -- local (addType (x,a)) (checkType b) -- _ -> infer t =?= U
linuborj/cubicaltt
TypeChecker.hs
mit
18,550
0
31
5,589
7,445
3,630
3,815
425
24
module Text.XML.DOM.Parser.Types (-- * Element matching ElemMatcher(..) , emMatch , emShow , matchElemName , elMatch -- * Name matching , NameMatcher(..) , nmMatch , nmShow , matchName , matchLocalName , matchCILocalName -- * Parser internals , DomPath(..) , ParserError(..) , pePath , peDetails , peAttributeName , ParserErrors(..) , _ParserErrors , ParserData(..) , pdElements , pdPath , DomParserT , DomParser , runDomParserT , runDomParser -- * Auxiliary , throwParserError ) where import Control.Exception import Control.Lens import Control.Monad.Except import Control.Monad.Reader import Data.CaseInsensitive as CI import Data.Semigroup import Data.String import Data.Text as T import GHC.Generics (Generic) import Text.XML import Text.XML.Lens -- | Arbitrary element matcher -- -- @since 2.0.0 data ElemMatcher = ElemMatcher { _emMatch :: Element -> Bool , _emShow :: Text -- ^ Field for 'Show' instance and bulding usefull errors } makeLenses ''ElemMatcher -- | Instance using instance of 'NameMatcher' instance IsString ElemMatcher where fromString = matchElemName . fromString instance Show ElemMatcher where show = T.unpack . _emShow -- | Match element by name -- -- @since 2.0.0 matchElemName :: NameMatcher -> ElemMatcher matchElemName (NameMatcher matchName showName) = ElemMatcher { _emMatch = views name matchName , _emShow = showName } -- | Match over elements -- -- @since 2.0.0 elMatch :: ElemMatcher -> Traversal' Element Element elMatch (ElemMatcher match _) = filtered match -- | Arbitrary name matcher. Match name any way you want, but -- considered to be used as comparator with some name with some rules -- -- @since 2.0.0 data NameMatcher = NameMatcher { _nmMatch :: Name -> Bool -- ^ Name matching function, usually should be simple comparsion -- function takin in account only local name or other components -- of 'Name' , _nmShow :: Text -- ^ Field for 'Show' instance and bulding usefull errors } makeLenses ''NameMatcher -- | Instance use 'matchCILocalName' as most general and liberal -- matching strategy (while XML is often malformed). -- -- @since 2.0.0 instance IsString NameMatcher where fromString = matchCILocalName . T.pack instance Show NameMatcher where show = T.unpack . _nmShow -- | Makes matcher which matches only local part of name igoring -- namespace and prefix. Local name matching is case sensitive. -- -- @since 2.0.0 matchLocalName :: Text -> NameMatcher matchLocalName tname = NameMatcher { _nmMatch = \n -> nameLocalName n == tname , _nmShow = tname } -- | Makes matcher which matches only local part of name igoring -- namespace and prefix. Local name matching is case insensitive. This -- is the most common case. -- -- @since 2.0.0 matchCILocalName :: Text -> NameMatcher matchCILocalName tname = NameMatcher { _nmMatch = \n -> CI.mk (nameLocalName n) == CI.mk tname , _nmShow = tname } -- | Makes matcher which match name by 'Eq' with given -- -- @since 2.0.0 matchName :: Name -> NameMatcher matchName n = NameMatcher { _nmMatch = (== n) , _nmShow = nameLocalName n } -- | Path some element should be found at. Path starts from the root -- element of the document. Errors are much more usefull with path. newtype DomPath = DomPath { unDomPath :: [Text] } deriving (Eq, Ord, Show, Semigroup, Monoid) -- | DOM parser error description. data ParserError -- | Tag not found which should be. = PENotFound { _pePath :: DomPath -- ^ Path of element error occured in } -- | Expected attribute but not found -- -- @since 1.0.0 | PEAttributeNotFound { _peAttributeName :: NameMatcher , _pePath :: DomPath } -- | Could not parse attribute -- -- @since 1.0.0 | PEAttributeWrongFormat { _peAttributeName :: NameMatcher , _peDetails :: Text , _pePath :: DomPath } -- | Node should have text content, but it does not. | PEContentNotFound { _pePath :: DomPath } -- | Tag contents has wrong format, (could not read text to value) | PEContentWrongFormat { _peDetails :: Text , _pePath :: DomPath } -- | Some other error | PEOther { _peDetails :: Text , _pePath :: DomPath } deriving (Show, Generic) makeLenses ''ParserError instance Exception ParserError newtype ParserErrors = ParserErrors { unParserErrors :: [ParserError] } deriving (Show, Semigroup, Monoid, Generic) makePrisms ''ParserErrors instance Exception ParserErrors {- | Parser scope. Functor argument is usually @Identity@ or @[]@. If functor is @Identity@ then parser expects exactly ONE current element. This is common behavior for content parsers, or parsers expecting strict XML structure. If functor is @[]@ then parser expects arbitrary current elements count. This is the case when you use combinators 'divePath' or 'diveElem' (posible other variants of similar combinators). This kind of combinators performs search for elements somewhere in descendants and result have arbitrary length in common case. -} data ParserData f = ParserData { _pdElements :: f Element -- ^ Current element(s). Functor is intended to be either @Identity@ or -- @[]@ , _pdPath :: DomPath -- ^ Path for error reporting } makeLenses ''ParserData type DomParserT f m = ReaderT (ParserData f) (ExceptT ParserErrors m) type DomParser f = DomParserT f Identity -- | Run parser on root element of Document. runDomParserT :: (Monad m) => Document -> DomParserT Identity m a -> m (Either ParserErrors a) runDomParserT doc par = let pd = ParserData { _pdElements = doc ^. root . to pure , _pdPath = DomPath [doc ^. root . name . to nameLocalName] } in runExceptT $ runReaderT par pd runDomParser :: Document -> DomParser Identity a -> Either ParserErrors a runDomParser doc par = runIdentity $ runDomParserT doc par throwParserError :: (MonadError ParserErrors m, MonadReader (ParserData f) m) => (DomPath -> ParserError) -> m a throwParserError mkerr = do path <- view pdPath throwError $ ParserErrors $ [mkerr path]
typeable/dom-parser
src/Text/XML/DOM/Parser/Types.hs
mit
6,207
0
15
1,336
1,116
653
463
-1
-1
module Main where import qualified Data.Text as T import qualified Data.Text.IO as TIO import Data.Char import System.Environment (getArgs) import TopStrings nFromArgs :: [String] -> Int nFromArgs [] = 1 nFromArgs (n:_) = read n comb :: Int -> T.Text -> [T.Text] comb n = map (T.take n) . T.tails main :: IO () main = do n <- fmap nFromArgs getArgs TIO.getContents >>= printTopStrings . topStrings . comb n . T.filter isPrint
spoj/mwtools
app/topchars.hs
mit
435
0
11
81
180
97
83
15
1
module Data.AminoAcid where {-- Continuation of the solution for sequencing amino acids started with Data.Bases at http://lpaste.net/107069 This module contains quite a bit of commented-out false-starts. I kept the comments in to show where and how I stumbled, feet of clay, and all that, please let me know if you find these failed attempts distracting, in which case I will remove them. --} import Data.Set (Set) import qualified Data.Set as Set import Data.Map (Map) import qualified Data.Map as Map import Data.Traversable import Data.Char import Data.Bases data AcidName = A | C | D | E | F | G | H | I | K | L | M | N | P | Q | R | S | T | V | W | Y deriving (Eq, Ord, Show, Read) {-- instance Read AcidName where readsPrec prec str = readParen False (\r -> [(name, rest) | (str, rest) <- lex r, let name = read $ map toUpper str]) str -- infinite loop, read-read --} data AminoAcid = Acid AcidName (Set NucleotideTriple ) deriving (Eq, Ord) instance Show AminoAcid where show (Acid name triples) = (show name) ++ " : " ++ (show $ Set.toList triples) instance Read AminoAcid where readsPrec prec str = readParen False (\r -> [(acid, rest) | (acidName, colonRemainder) <- lex r, (":", triplesEtc) <- lex colonRemainder, (triples, rest) <- readsPrec prec triplesEtc, let acid = Acid (read acidName) (Set.fromList triples)]) str {-- So! let triples = read "[GCT, GCC, GCA, GCG]" :: [NucleotideTriple ] let acid = Acid H (Set.fromList triples) acid ~> H : [GCA,GCT,GCC,GCG] read (show acid) == acid is True so now that we're pretty close, we have to write a parser function for the given file format. --} parseAcidDefs :: FilePath -> IO [AminoAcid] parseAcidDefs file = readFile file >>= return . map parseAcid . lines parseAcid :: String -> AminoAcid parseAcid line = let (name, colonrest) = head $ lex line (colon, rest) = head $ lex colonrest triples = parseTriples rest [] in Acid (read $ map toUpper name) (Set.fromList triples) parseTriples :: String -> [NucleotideTriple] -> [NucleotideTriple] parseTriples str accum | str == "" = accum | otherwise = let (trip, rest) = head $ lex str in parseTriples rest (read trip : accum) {-- -- so now that we have them parsed, we can write the file out as a list -- of rules and then embed that list into this very file! encodeAcidRule :: AminoAcid -> String encodeAcidRule (Acid name triples) = "Acid " ++ (show name) ++ " (Set.fromList " ++ showStringList (map encodeTriple $ Set.toList triples) ++ ")" encodeTriple :: NucleotideTriple -> String encodeTriple (Triple (a, b, c)) = "Triple (" ++ show a ++ ", " ++ show b ++ ", " ++ show c ++ ")" showStringList :: [String] -> String showStringList [] = "[]" showStringList (h : t) = "[" ++ h ++ s' t where s' [] = "]" s' (h : t) = ", " ++ h ++ s' t -- so, with the above functions we can encode the rules in the DSL as -- a pure-Haskell list: acidRules :: [AminoAcid] acidRules = [ Acid A (Set.fromList [Triple (G, C, A), Triple (G, C, T), Triple (G, C, C), Triple (G, C, G)]), Acid C (Set.fromList [Triple (T, G, T), Triple (T, G, C)]), Acid D (Set.fromList [Triple (G, A, T), Triple (G, A, C)]), Acid E (Set.fromList [Triple (G, A, A), Triple (G, A, G)]), Acid F (Set.fromList [Triple (T, T, T), Triple (T, T, C)]), Acid G (Set.fromList [Triple (G, G, A), Triple (G, G, T), Triple (G, G, C), Triple (G, G, G)]), Acid H (Set.fromList [Triple (C, A, T), Triple (C, A, C)]), Acid I (Set.fromList [Triple (A, T, A), Triple (A, T, T), Triple (A, T, C)]), Acid K (Set.fromList [Triple (A, A, A), Triple (A, A, G)]), Acid L (Set.fromList [Triple (T, T, A), Triple (T, T, G), Triple (C, T, A), Triple (C, T, T), Triple (C, T, C), Triple (C, T, G)]), Acid M (Set.fromList [Triple (A, T, G)]), Acid N (Set.fromList [Triple (A, A, T), Triple (A, A, C)]), Acid P (Set.fromList [Triple (C, C, A), Triple (C, C, T), Triple (C, C, C), Triple (C, C, G)]), Acid Q (Set.fromList [Triple (C, A, A), Triple (C, A, G)]), Acid R (Set.fromList [Triple (A, G, A), Triple (A, G, G), Triple (C, G, A), Triple (C, G, T), Triple (C, G, C), Triple (C, G, G)]), Acid S (Set.fromList [Triple (A, G, T), Triple (A, G, C), Triple (T, C, A), Triple (T, C, T), Triple (T, C, C), Triple (T, C, G)]), Acid T (Set.fromList [Triple (A, C, T), Triple (A, C, C), Triple (A, C, G)]), Acid V (Set.fromList [Triple (G, T, A), Triple (G, T, T), Triple (G, T, C), Triple (G, T, G)]), Acid W (Set.fromList [Triple (T, G, G)]), Acid Y (Set.fromList [Triple (T, A, T), Triple (T, A, C)])] I did the above with: parseAcidDefs "acids.defs" >>= mapM_ (putStrLn . (flip (++) ",") . ((++) " ") . encodeAcidRule) --} {-- Okay, so all the above was a great idea until the Amino acids A, G, C, T name-clashed with the bases of the same name, so, sigh: punt for now and just take the 'parsing in the file'-route. :( --} data AminoAcidDefinitions = Defs (Map AcidName AminoAcid) (Map NucleotideTriple AminoAcid) aminoAcidDefinitions :: [AminoAcid] -> AminoAcidDefinitions aminoAcidDefinitions rules = a' rules Map.empty Map.empty where a' [] names trips = Defs names trips a' (acid@(Acid name triples) : acids) names trips = -- HAH! a' acids (Map.insert name acid names) (addTrips (Set.toList triples) acid trips) addTrips [] _ t = t addTrips (trip : ts) acid@(Acid name _) t = case (Map.lookup trip t) of Nothing -> addTrips ts acid (Map.insert trip acid t) Just (Acid nm _) -> error ("duplicate key " ++ show trip ++ " for " ++ show name ++ " and " ++ show nm) -- Now with the above we can do the exerices: acid :: NucleotideTriple -> AminoAcidDefinitions -> Maybe AminoAcid acid trip (Defs _ map) = Map.lookup trip map {-- As we already proved that there is at most one amino acid defined by a nucleotide triple, we improve the type-signature of the acid function to reflect this semideterminacy --} {-- BLEH! target :: String -> AminoAcidDefinitions -> [[NucleotideTriple]] target aminoAcid (Defs names _) = let acidNames = map (read . return . toUpper) aminoAcid in a' acidNames [] where a' [] ans = ans a' (acid : acids) accum = a' acids (deck |< ... instead of trying to eat an elephant whole, I'll break out targeting functionally piece-wise --} targeted :: [AminoAcid] -> [[NucleotideTriple]] targeted acid = map (\(Acid _ trips) -> Set.toList trips) acid {-- but the function targeted is the wrong orientation we want M x N not N x M so we have to flip/redistribute the triples. --} retargeted :: [[NucleotideTriple]] -> [[NucleotideTriple]] retargeted [] = [[]] retargeted (trips : rest) = concat [ trips >>= \trip -> map ((:) trip) (retargeted rest) ] -- resignaturized target to accept strings for acid-sequences: target :: String -> AminoAcidDefinitions -> Maybe [[NucleotideTriple]] target acid (Defs names _) = let aminoAcidNames = map (read . return . toUpper) acid aminoAcids = for aminoAcidNames (flip Map.lookup names) in aminoAcids >>= return . retargeted . targeted go :: String -> IO (Maybe [[NucleotideTriple]]) go acid = parseAcidDefs "acids.defs" >>= return . target acid . aminoAcidDefinitions {-- go "kmspdw" ~> IO (Just list) where list is 96 NucleotideTriple sequences, including the sequence: [AAG,ATG,TCT,CCG,GAC,TGG] which is the sought sequence in the original article Cool beans! Other samples: go "abdd" ~> error [b is not an acid] go "acddtci" ~> IO (Just [576 sequences]) --} {-- Notes while solving this exercise: 1 and 2. Given Data.Bases and Data.AminoAcid: As we already proved that there is at most one amino acid defined by a nucleotide triple, we improve the type-signature of the acid function to reflect this semideterminacy 3. 4 * 4 * 4 == 64 or let bases [A, G, T, C] in length [Triple (a, b, c) | a <- bases, b <- bases, c <- bases] 4. solution provided by the go function or target function --}
nightski/1HaskellADay
Data/AminoAcid.hs
mit
8,711
0
17
2,406
1,190
629
561
63
4
{-# OPTIONS -Wall #-} {-# LANGUAGE ScopedTypeVariables #-} main :: IO () main = do depths :: [Int] <- map read . filter (not . null) . lines <$> getContents let answer = length $ filter id $ zipWith (<) depths (tail depths) print answer
SamirTalwar/advent-of-code
2021/AOC_01_1.hs
mit
244
0
13
52
98
48
50
7
1
module GrData (grdata, grdata', GrData(..)) where import Data.Array import qualified Data.Map as Map import qualified Data.Set as Set import Groups import Groups.Internals (factor, (?:), TernaryBranch(..)) data GrData = GrData { gd_order :: Int, -- Rename "gd_size"? gd_abelian :: Bool, gd_nilpotence :: Maybe Int, gd_solvable :: Bool, gd_simple :: Bool, gd_rank :: Int, gd_exponent :: Int, -- TODO: Split up `gd_quantities` into multiple arrays? gd_quantities :: Array Int (Maybe (Int, Int, Int, Int)) -- ^Mapping from n to: -- * number of elements of order n -- * number of subgroups of order n -- * number of normal subgroups of order n -- * number of conjugacy classes of order n } deriving (Eq, Ord, Read, Show) grdata :: Ord a => Group a -> GrData grdata g = GrData { gd_order = n, gd_abelian = abel, gd_nilpotence = abel ?: Just 1 :? (nilpot ?: nilpotence g :? Nothing), gd_solvable = nilpot || and [subQtys ! i /= 0 | i <- divisors, gcd i (div n i) == 1], gd_simple = n /= 1 && and [q == 0 | (m,q) <- assocs normQtys, m /= 1, m /= n], gd_rank = Set.findMin $ Set.map Set.size $ subs Map.! self, gd_exponent = foldl lcm 1 [k | (k,a) <- assocs ords, a /= 0], gd_quantities = listArray (1,n) [mod n i == 0 ?: Just (ords ! i, subQtys ! i, normQtys ! i, ccQtys ! i) :? Nothing | i <- [1..n]] } where n = gsize g self = gtotal g divisors = filter ((== 0) . mod n) [2..n] subs = subgroupGens g ords = freqArray (1,n) $ map (gorder g) $ gelems g subQtys = freqArray (1,n) $ map Set.size $ Map.keys subs normQtys = freqArray (1,n) $ map Set.size $ filter (isNormal g) $ Map.keys subs ccQtys = freqArray (1,n) $ map Set.size $ conjugacies g abel = isAbelian g nilpot = abel || and [subQtys ! (p^a) == normQtys ! (p^a) | (p,a) <- factor n] grdata' :: Ord a => (String, Group a, [String]) -> String grdata' (name, g, props) = showData (name, grdata g, props) showData :: (String, GrData, [String]) -> String showData (name, dat, props) | gd_order dat == 1 = unlines [ name, unwords $ "1 abelian nilpotent solvable" : props, -- "1", "rank=0", "exp=1", "nilpotence=0" ] showData (name, dat, props) = unlines [ name, unwords $ [ show $ gd_order dat, gd_abelian dat ?: "abelian" :? "nonabelian", gd_nilpotence dat /= Nothing ?: "nilpotent" :? "nonnilpotent", gd_solvable dat ?: "solvable" :? "nonsolvable", -- insoluble? gd_simple dat ?: "simple" :? "nonsimple" ] ++ props, "elements =" ++ unwords [show i ++ ':' : show a | (i,Just (a,_,_,_)) <- assocs $ gd_quantities dat], "subgroups =" ++ unwords [show i ++ ':' : show b | (i,Just (_,b,_,_)) <- assocs $ gd_quantities dat], "normsubgrs=" ++ unwords [show i ++ ':' : show c | (i,Just (_,_,c,_)) <- assocs $ gd_quantities dat], "conjugacies=" ++ unwords [show i ++ ':' : show d | (i,Just (_,_,_,d)) <- assocs $ gd_quantities dat], "rank=" ++ show (gd_rank dat), "exp=" ++ show (gd_exponent dat), "nilpotence=" ++ maybe "nil" show (gd_nilpotence dat) ] freqArray :: Ix a => (a,a) -> [a] -> Array a Int freqArray b = accumArray (+) 0 b . map (\x -> (x,1))
jwodder/groups
haskell/dev/GrData.hs
mit
3,244
26
15
798
1,253
709
544
71
1
{-# LANGUAGE RecordWildCards #-} module SessionSpec (spec) where import Helper import System.Environment.Blank (setEnv) import Language.Haskell.GhciWrapper (eval) import qualified Session import Session (Session(..), Summary(..), hspecFailureEnvName, hspecPreviousSummary, hspecCommand) spec :: Spec spec = do describe "new" $ do it "unsets HSPEC_FAILURES" $ do setEnv hspecFailureEnvName "foo" True withSession [] $ \Session{..} -> do _ <- eval sessionInterpreter "import System.Environment" eval sessionInterpreter ("lookupEnv " ++ show hspecFailureEnvName) `shouldReturn` "Nothing\n" describe "reload" $ do it "reloads" $ do withSession [] $ \session -> do silence (Session.reload session) `shouldReturn` (modulesLoaded Ok [] ++ "\n") describe "hasSpec" $ around_ withSomeSpec $ do context "when module contains spec" $ do it "returns True" $ do withSession ["Spec.hs"] $ \session -> do _ <- silence (Session.reload session) Session.hasSpec hspecCommand session `shouldReturn` True context "when module does not contain spec" $ do it "returns False" $ do withSession ["Spec.hs"] $ \session -> do writeFile "Spec.hs" "module Main where" _ <- silence (Session.reload session) Session.hasSpec hspecCommand session `shouldReturn` False describe "hasHspecCommandSignature" $ do let signature = "Test.Hspec.Runner.hspecResult spec :: IO Test.Hspec.Core.Runner.Summary" context "when input contains qualified Hspec command signature" $ do it "returns True" $ do Session.hasHspecCommandSignature hspecCommand signature `shouldBe` True it "ignores additional output after summary" $ do (Session.hasHspecCommandSignature hspecCommand . unlines) [ "bar" , signature , "foo" ] `shouldBe` True context "when input contains unqualified Hspec command signature" $ do it "returns True" $ do Session.hasHspecCommandSignature hspecCommand "Test.Hspec.Runner.hspecResult spec :: IO Summary" `shouldBe` True context "when input dose not contain Hspec command signature" $ do it "returns False" $ do Session.hasHspecCommandSignature hspecCommand "foo" `shouldBe` False describe "runSpec" $ around_ withSomeSpec $ do let runSpec = Session.runSpec hspecCommand it "stores summary of spec run" $ do withSession ["Spec.hs"] $ \session -> do _ <- silence (runSpec session >> runSpec session) hspecPreviousSummary session `shouldReturn` Just (Summary 2 0) it "accepts Hspec args" $ do withSession ["Spec.hs", "--no-color", "-m", "foo"] $ \session -> do _ <- silence (runSpec session >> runSpec session) hspecPreviousSummary session `shouldReturn` Just (Summary 1 0) describe "parseSummary" $ do let summary = Summary 2 0 it "parses summary" $ do Session.parseSummary (show summary) `shouldBe` Just summary it "ignores additional output before / after summary" $ do (Session.parseSummary . unlines) [ "foo" , show summary , "bar" ] `shouldBe` Just summary it "gives last occurrence precedence" $ do (Session.parseSummary . unlines) [ show (Summary 3 0) , show summary ] `shouldBe` Just summary it "ignores additional output at the beginning of a line (to cope with ansi escape sequences)" $ do Session.parseSummary ("foo " ++ show summary) `shouldBe` Just (Summary 2 0)
hspec/sensei
test/SessionSpec.hs
mit
3,626
0
24
905
966
460
506
75
1
{-# LANGUAGE OverloadedStrings #-} module Main where import qualified Prelude import Yage.Prelude import Yage.Math import Yage.Data.List (piz) import Yage.Image import Data.Text.Read import Control.Monad (when) import Codec.Picture import System.Random import Control.Monad.Random import Yage.Texture.Atlas import Yage.Texture.Atlas.Builder main :: IO () main = do printUsage (seed, imageCount) <- readArgs setSeed seed randImgs <- generateRandomImages imageCount let bgrnd = PixelRGB8 0 0 0 settings = AtlasSettings (V2 1024 1024) bgrnd 1 texs = [(0::Int)..] `zip` randImgs eAtlas = newTextureAtlas settings texs either print (writeTextureAtlas "atlas.png") eAtlas generateRandomImages :: Int -> IO [Image PixelRGB8] generateRandomImages count = replicateM count generateRandomImg where generateRandomImg = do -- because our background color is black we set our lower color bound a bit up color <- PixelRGB8 <$> getRandomR (60, 254) <*> getRandomR (60, 254) <*> getRandomR (60, 254) makeImg color <$> getRandomR (5, 200) <*> getRandomR (5, 200) makeImg :: (Pixel a) => a -> Int -> Int -> Image a makeImg col = generateImage (const . const $ col) printUsage :: IO () printUsage = do print "Usage:" print "args in this order: seed image-count" print "e.g. textureAtlas 12345 73" setSeed :: Int -> IO () setSeed seed = do setStdGen $ mkStdGen seed print $ "seed: " ++ show seed getImageCount :: IO Int getImageCount = do eCnt <- decimal . (Prelude.!! 1) <$> getArgs either error (return . fst) eCnt
MaxDaten/yage
test/manuals/RndTextureAtlas.hs
mit
1,742
0
14
470
507
263
244
49
1
import RandomPermutation import System.Random main :: IO () main = do contents <- readFile "/home/ildar/Projects/HaskelDev/random_permutation/input.txt" let numList = map readInt . words $ contents print "Input:" print numList print "imperative:" print $ imperativePermutation numList seed <- newStdGen let randomNumbers = randomlist (length numList) seed print "Random Numbers:" print randomNumbers print "generate sequence of shuffle places " --[2,2,3,4,3,2,1,1,1,1,1,1,1,0] let shufflePlaces = generateShuffle $ randomNumbers print shufflePlaces print "shuffle" print $ shuffle numList shufflePlaces print "shuffle1" print $ shuffle1 numList shufflePlaces -- alternately, main = print . map readInt . words =<< readFile "test.txt" readInt :: String -> Int readInt = read
ILDAR9/permutation_seq
Main.hs
gpl-2.0
926
0
12
252
198
86
112
23
1
{-# LANGUAGE TemplateHaskell #-} module PL.Param where import PL.Type import Autolib.Reader import Autolib.ToDoc import Data.Typeable data Param = Param { model_size :: Int -- TODO: Atleast, Atmost, ... , formel :: Formel } deriving ( Typeable ) example :: Param example = Param { model_size = 4 , formel = read "forall x . exists y . R(x,y)" } $(derives [makeReader, makeToDoc] [''Param]) -- local variables: -- mode: haskell -- end
florianpilz/autotool
src/PL/Param.hs
gpl-2.0
463
6
9
100
115
69
46
15
1
-- | -- Module: Tasks.Project -- -- This module contains the Project type. -- Like the Task type, a Project has a name and may have notes, -- but it also contains zero or more task entries. -- Like task, it implements the Binary instance. module Tasks.Project ( Project(..) -- The @Project@ type , projectHasTasks , projectHasTask , projectAddTask , projectRemoveTask , project -- Helper functions , projectNotes , projectPriority , projectCompleted , projectDue , projectEditNotes , projectEditPriority , projectEditCompleted , projectEditDue -- Debugging , exProject1 , exProject2 , exProjects ) where import Data.DateTime import Data.Binary import Data.List (delete) import qualified Data.ByteString as B import Tasks.Task import Tasks.Types -- | The project type, containing the name, notes, and tasks fields data Project = Project { projectName :: B.ByteString , projectTasks :: [Task] , projectMetadata :: Metadata } deriving (Read, Show) -- Helper functions projectNotes = mdNotes . projectMetadata projectPriority = mdPriority . projectMetadata projectCompleted = mdCompleted . projectMetadata projectDue = mdDue . projectMetadata -- | Edit a given project's notes projectEditNotes :: Project -> Maybe B.ByteString -> Project projectEditNotes p@(Project { projectMetadata = pmd }) mnts = p { projectMetadata = mdEditNotes pmd mnts } -- | Edit a given project's priority projectEditPriority :: Project -> Priority -> Project projectEditPriority p@(Project { projectMetadata = pmd }) pr = p { projectMetadata = mdEditPriority pmd pr } -- | Edit a given project's completion status projectEditCompleted :: Project -> Bool -> Project projectEditCompleted p@(Project { projectMetadata = pmd }) c = p { projectMetadata = mdEditCompleted pmd c } -- | Edit a given project's due date projectEditDue :: Project -> Maybe DateTime -> Project projectEditDue p@(Project { projectMetadata = pmd }) mdd = p { projectMetadata = mdEditDue pmd mdd } instance Eq Project where (==) (Project { projectName = pn1 }) (Project { projectName = pn2 }) = pn1 == pn2 instance Binary Project where get = do (pn, ptsks, pmd) <- get :: Get (B.ByteString, [Task], Metadata) return Project { projectName = pn , projectTasks = ptsks , projectMetadata = pmd } put p = put ( projectName p , projectTasks p , projectMetadata p ) -- | Convenience method to determine whether a project has any -- tasks whatsoever projectHasTasks :: Project -> Bool projectHasTasks (Project { projectTasks = pts }) = not (null pts) -- | Check whether a project contains a particular task projectHasTask :: Project -> Task -> Bool projectHasTask (Project { projectTasks = pts }) t = t `elem` pts -- | Add a task to a given project, returning a tuple containing the (possibly) -- modified project, and a boolean indicating whether the task was added. projectAddTask :: Project -> Task -> (Project, Bool) projectAddTask p@(Project { projectTasks = pts }) t = if projectHasTask p t then (p, False) else let newTasks = pts ++ [t] in (p { projectTasks = newTasks }, True) -- | Remove a task from a given project, returning a tuple containing the (possibly) -- modified project, and a boolean indicating whether the task was removed. projectRemoveTask :: Project -> Task -> (Project, Bool) projectRemoveTask p@(Project { projectTasks = pts }) t = if not $ projectHasTask p t then (p, False) else let newTasks = delete t pts in (p { projectTasks = newTasks }, True) -- | Easily construct a project, given a name, notes, priority, -- due date, and tasks. project :: String -> Maybe String -> Maybe Priority -> Maybe DateTime -> [Task] -> Project project pnm mpnts mp md tsks = Project { projectName = bs pnm , projectTasks = tsks , projectMetadata = metadata mpnts mp (Just False) md } exProject1 = project "Example Project 1" (Just "A sample project") (Just Medium) Nothing exTasks exProject2 = project "Example Project 2" (Just "Another sample project") (Just Low) Nothing [] exProjects = [exProject1, exProject2]
BigEndian/tasks
src/Tasks/Project.hs
gpl-2.0
4,450
0
11
1,132
1,000
570
430
89
2
{-# LANGUAGE GeneralizedNewtypeDeriving, TemplateHaskell #-} module Eval.Types ( Stack , Eval , EvalError , runEval , stack , definitions ) where import Control.Applicative import Control.Lens import Control.Monad.State import Control.Monad.Error import Data.Map (Map) import Types newtype Stack a = Stack { unStack :: [a] } deriving (Eq) instance Show a => Show (Stack a) where show = show . unStack newtype EvalError = EvalError String deriving (Error) instance Show EvalError where show (EvalError err) = err data EvalState = EvalState { _stack :: Stack CExp , _definitions :: Map String CExp } makeLenses ''EvalState newtype Eval a = Eval { runEval :: StateT EvalState (ErrorT EvalError IO) a } deriving ( Functor , Applicative , Monad )
breestanwyck/stack-unification
src/Eval/Types.hs
gpl-2.0
929
0
9
303
234
135
99
29
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} module Commands.Import (commands) where import Data.Conduit ((.|), runConduit) import qualified Data.Conduit.Combinators as C import Data.Proxy (Proxy(Proxy)) import Core import Options import Schema import Sql (Filter, runRegion, runTransaction) import Sql.Import commands :: Command (SqlM ()) commands = CommandGroup CommandInfo { commandName = "import" , commandHeaderDesc = "list database entries" , commandDesc = "" } [ SingleCommand CommandInfo { commandName = "external-impls" , commandHeaderDesc = "Import external implementations" , commandDesc = "Import external implementations from an existing database." } $ importAll (Proxy :: Proxy ExternalImpl) <$> importDatabase , SingleCommand CommandInfo { commandName = "external-timers" , commandHeaderDesc = "Import external implementation timer data" , commandDesc = "Import timer data of external implementations from an existing \ \database." } $ importAll (Proxy :: Proxy ExternalTimer) <$> importDatabase ] where importDatabase = strArgument $ mconcat [ metavar "DATABASE", help "Database to import from." ] importAll :: forall proxy rec . Importable rec => proxy rec -> Text -> SqlM () importAll _ db = runImport db . runTransaction . runRegion . runConduit $ do selectSourceImport ([] :: [Filter rec]) [] .| C.mapM_ (lift . importEntity)
merijn/GPU-benchmarks
benchmark-analysis/ingest-src/Commands/Import.hs
gpl-3.0
1,560
0
12
346
347
196
151
34
1
{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-} module HeroesAndCowards.HACModel where import System.Random import Data.Maybe import Control.DeepSeq import GHC.Generics (Generic) import qualified PureAgentsPar as PA type HACAgentPosition = (Double, Double) data HACMsg = PositionRequest | PositionUpdate HACAgentPosition deriving (Generic, NFData) data HACWorldType = Infinite | Border | Wraping deriving (Eq, Show, Generic, NFData) type HACEnvironment = Int data HACAgentState = HACAgentState { pos :: HACAgentPosition, hero :: Bool, wt :: HACWorldType, friend :: PA.AgentId, enemy :: PA.AgentId, friendPos :: Maybe HACAgentPosition, enemyPos :: Maybe HACAgentPosition } deriving (Show, Generic, NFData) type HACAgent = PA.Agent HACMsg HACAgentState HACEnvironment type HACTransformer = PA.AgentTransformer HACMsg HACAgentState HACEnvironment type HACSimHandle = PA.SimHandle HACMsg HACAgentState HACEnvironment hacMovementPerTimeUnit :: Double hacMovementPerTimeUnit = 1.0 hacTransformer :: HACTransformer hacTransformer a (_, PA.Dt dt) = hacDt a dt hacTransformer a (senderId, PA.Domain m) = hacMsg a m senderId hacMsg :: HACAgent -> HACMsg -> PA.AgentId -> HACAgent -- MESSAGE-CASE: PositionUpdate hacMsg a (PositionUpdate (x, y)) senderId | senderId == friendId = PA.updateState a (\sOld -> sOld { friendPos = newPos }) | senderId == enemyId = PA.updateState a (\sOld -> sOld { enemyPos = newPos }) where s = PA.state a friendId = friend s enemyId = enemy s newPos = Just (x,y) -- MESSAGE-CASE: PositionRequest hacMsg a PositionRequest senderId = PA.sendMsg a (PositionUpdate currPos) senderId where s = PA.state a currPos = pos s hacDt :: HACAgent -> Double -> HACAgent hacDt a dt = if ((isJust fPos) && (isJust ePos)) then PA.writeState a'' s' -- NOTE: no new position/state will be calculated due to Haskells Laziness else a'' where s = PA.state a fPos = friendPos s ePos = enemyPos s oldPos = pos s targetPos = decidePosition (fromJust fPos) (fromJust ePos) (hero s) targetDir = vecNorm $ posDir oldPos targetPos wtFunc = worldTransform (wt s) stepWidth = hacMovementPerTimeUnit * dt newPos = wtFunc $ addPos oldPos (multPos targetDir stepWidth) s' = s{ pos = newPos } a' = requestPosition a (friend s) a'' = requestPosition a' (enemy s) -- TODO: replace by broadcast to neighbours requestPosition :: HACAgent -> PA.AgentId -> HACAgent requestPosition a receiverId = PA.sendMsg a PositionRequest receiverId createHACTestAgents :: [HACAgent] createHACTestAgents = [a0', a1', a2'] where a0State = HACAgentState{ pos = (0.0, -0.5), hero = False, friend = 1, enemy = 2, wt = Border, friendPos = Nothing, enemyPos = Nothing } a1State = HACAgentState{ pos = (0.5, 0.5), hero = False, friend = 0, enemy = 2, wt = Border, friendPos = Nothing, enemyPos = Nothing } a2State = HACAgentState{ pos = (-0.5, 0.5), hero = False, friend = 0, enemy = 1, wt = Border, friendPos = Nothing, enemyPos = Nothing } a0 = PA.createAgent 0 a0State hacTransformer a1 = PA.createAgent 1 a1State hacTransformer a2 = PA.createAgent 2 a2State hacTransformer a0' = PA.addNeighbours a0 [a1, a2] a1' = PA.addNeighbours a1 [a0, a2] a2' = PA.addNeighbours a2 [a0, a1] createRandomHACAgents :: RandomGen g => g -> Int -> Double -> ([HACAgent], g) createRandomHACAgents gInit n p = (as', g') where (randStates, g') = createRandomStates gInit 0 n p as = map (\idx -> PA.createAgent idx (randStates !! idx) hacTransformer) [0..n-1] as' = map (\a -> PA.addNeighbours a as) as -- TODO: filter for friend and enemy createRandomStates :: RandomGen g => g -> Int -> Int -> Double -> ([HACAgentState], g) createRandomStates g id n p | id == n = ([], g) | otherwise = (rands, g'') where (randState, g') = randomAgentState g id n p (ras, g'') = createRandomStates g' (id+1) n p rands = randState : ras ---------------------------------------------------------------------------------------------------------------------- -- PRIVATES ---------------------------------------------------------------------------------------------------------------------- randomAgentState :: (RandomGen g) => g -> Int -> Int -> Double -> (HACAgentState, g) randomAgentState g id maxAgents p = (s, g5) where allAgentIds = [0..maxAgents-1] (randX, g') = randomR(-1.0, 1.0) g (randY, g'') = randomR(-1.0, 1.0) g' (randEnemy, g3) = drawRandomIgnoring g'' allAgentIds [id] (randFriend, g4) = drawRandomIgnoring g3 allAgentIds [id, randEnemy] (randHero, g5) = randomThresh g4 p s = HACAgentState{ pos = (randX, randY), hero = randHero, friend = randEnemy, enemy = randFriend, wt = Border, friendPos = Nothing, enemyPos = Nothing } randomThresh :: (RandomGen g) => g -> Double -> (Bool, g) randomThresh g p = (flag, g') where (thresh, g') = randomR(0.0, 1.0) g flag = thresh <= p -- NOTE: this solution will recur forever if there are no possible solutions but will be MUCH faster for large xs and if xs is much larger than is and one knows there are solutions drawRandomIgnoring :: (RandomGen g, Eq a) => g -> [a] -> [a] -> (a, g) drawRandomIgnoring g xs is | any (==randElem) is = drawRandomIgnoring g' xs is | otherwise = (randElem, g') where (randIdx, g') = randomR(0, length xs - 1) g randElem = xs !! randIdx decidePosition :: HACAgentPosition -> HACAgentPosition -> Bool -> HACAgentPosition decidePosition friendPos enemyPos hero | hero = coverPosition | otherwise = hidePosition where enemyFriendDir = posDir friendPos enemyPos halfPos = multPos enemyFriendDir 0.5 coverPosition = addPos friendPos halfPos hidePosition = subPos friendPos halfPos multPos :: HACAgentPosition -> Double -> HACAgentPosition multPos (x, y) s = (x*s, y*s) addPos :: HACAgentPosition -> HACAgentPosition -> HACAgentPosition addPos (x1, y1) (x2, y2) = (x1+x2, y1+y2) subPos :: HACAgentPosition -> HACAgentPosition -> HACAgentPosition subPos (x1, y1) (x2, y2) = (x1-x2, y1-y2) posDir :: HACAgentPosition -> HACAgentPosition -> HACAgentPosition posDir (x1, y1) (x2, y2) = (x2-x1, y2-y1) vecLen :: HACAgentPosition -> Double vecLen (x, y) = sqrt( x * x + y * y ) vecNorm :: HACAgentPosition -> HACAgentPosition vecNorm (x, y) | len == 0 = (0, 0) | otherwise = (x / len, y / len) where len = vecLen (x, y) clip :: HACAgentPosition -> HACAgentPosition clip (x, y) = (clippedX, clippedY) where clippedX = max (-1.0) (min x 1.0) clippedY = max (-1.0) (min y 1.0) wrap :: HACAgentPosition -> HACAgentPosition wrap (x, y) = (wrappedX, wrappedY) where wrappedX = wrapValue x wrappedY = wrapValue y wrapValue :: Double -> Double wrapValue v | v > 1.0 = -1.0 | v < -1.0 = 1.0 | otherwise = v worldTransform :: HACWorldType -> (HACAgentPosition -> HACAgentPosition) worldTransform wt | wt == Border = clip | wt == Wraping = wrap | otherwise = id
thalerjonathan/phd
coding/prototyping/haskell/PureAgentsPar/src/HeroesAndCowards/HACModel.hs
gpl-3.0
7,602
0
13
1,982
2,428
1,336
1,092
146
2
module Language.Mulang.Inspector.ObjectOriented ( countAttributes, countClasses, countInterfaces, countMethods, countObjects, implements, includes, inherits, instantiates, usesInheritance, usesMixins, declaresAttribute, declaresAttributeMatching, declaresClass, declaresClassMatching, declaresEnumeration, declaresInterface, declaresInterfaceMatching, declaresMethod, declaresMethodMatching, declaresObject, declaresObjectMatching, declaresSuperclass, declaresPrimitive) where import Language.Mulang.Ast import Language.Mulang.Ast.Operator (Operator) import Language.Mulang.Generator (equationsExpandedExpressions) import Language.Mulang.Identifier import Language.Mulang.Inspector.Matcher (matches) import Language.Mulang.Inspector.Bound (BoundInspection, containsBoundDeclaration) import Language.Mulang.Inspector.Primitive (Inspection, containsExpression, containsDeclaration) import Language.Mulang.Inspector.Family (deriveDeclares, BoundInspectionFamily) implements :: BoundInspection implements predicate = containsExpression f where f (Implement (Reference name)) = predicate name f _ = False includes :: BoundInspection includes predicate = containsExpression f where f (Include (Reference name)) = predicate name f _ = False inherits :: BoundInspection inherits predicate = containsDeclaration f where f (Class _ (Just name) _) = predicate name f _ = False instantiates :: BoundInspection instantiates predicate = containsExpression f where f (New (Reference name) _) = predicate name f _ = False usesInheritance :: Inspection usesInheritance = declaresSuperclass anyone usesMixins :: Inspection usesMixins = includes anyone (declaresObject, declaresObjectMatching, countObjects) = deriveDeclares f :: BoundInspectionFamily where f matcher (Object _ body) = matches matcher id [body] f _ _ = False declaresSuperclass :: BoundInspection declaresSuperclass = inherits (declaresClass, declaresClassMatching, countClasses) = deriveDeclares f :: BoundInspectionFamily where f matcher (Class _ _ body) = matches matcher id [body] f _ _ = False declaresEnumeration :: BoundInspection declaresEnumeration = containsBoundDeclaration f where f (Enumeration _ _) = True f _ = False (declaresInterface, declaresInterfaceMatching, countInterfaces) = deriveDeclares f :: BoundInspectionFamily where f matcher (Interface _ _ body) = matches matcher id [body] f _ _ = False (declaresAttribute, declaresAttributeMatching, countAttributes) = deriveDeclares f :: BoundInspectionFamily where f matcher (Attribute _ body) = matches matcher id [body] f _ _ = False (declaresMethod, declaresMethodMatching, countMethods) = deriveDeclares f :: BoundInspectionFamily where f matcher (Method _ equations) = matches matcher equationsExpandedExpressions $ equations f _ _ = False -- primitive can only be declared as methods declaresPrimitive :: Operator -> Inspection declaresPrimitive operator = containsExpression f where f (PrimitiveMethod o _) = operator == o f _ = False
mumuki/mulang
src/Language/Mulang/Inspector/ObjectOriented.hs
gpl-3.0
3,381
0
11
752
813
444
369
78
2
{-# LANGUAGE OverloadedStrings #-} import Web.Scotty import CalendarTransformer import Data.Monoid (mconcat) import Control.Monad.IO.Class import Data.Default import qualified Data.Text.Lazy as TL transformer = def {eventT = move5thField2Location} calendar :: Transformer -> String -> IO (Either TL.Text TL.Text) calendar t url = do req <- open url case req of Left error -> return $ Left $ TL.pack $ mconcat ["<h1>Error: ", error, "</h1>"] Right cal -> return $ Right $ calPrint $ transform cal t main = scotty 3000 $ do get "/" $ do url <- (param "url") `rescue` (const next) cal <- liftIO $ calendar transformer url case cal of Left error -> html error Right cal -> text cal get "/" $ do html $ mconcat ["<h1>Hello!</h1><p>To start, simply write an url in the " ,"field below!</p>" ,"<form method='get' action='./'>" ,"<input type='text' name='url'/ >" ,"<input type='submit' value='Go!'>" ,"</form>"]
nyson/calif
Main.hs
gpl-3.0
1,080
0
14
315
302
154
148
29
2
{-# LANGUAGE IncoherentInstances #-} {-# LANGUAGE OverlappingInstances #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE GADTs #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Test where import Data.List import Debug.Trace as T import Control.Applicative import Control.Monad import Control.Monad.Trans import Text.Show.Functions binaryOpVec op (x,y,z) (x',y',z') = (x `op` x',y `op` y',z `op`z') instance Num Vec3 where (+) = binaryOpVec (+) (*) = binaryOpVec (*) abs = undefined signum = undefined fromInteger = undefined {- Syntax with some static semantics -} type Vec3 = (Float,Float,Float) data Op = Mul | Add deriving (Show,Eq) data CmpOp = Less deriving (Show,Eq) data Func a b = Func { func :: Expr a -> Expr b } data Value a = Value a instance Show (Value a) where show = const "<value>" instance Show (Func a b) where show = const "func" data Expr a where Vec :: Vec3 -> Expr Vec3 Bool :: Bool -> Expr Bool Lift :: Value a -> Expr a Num :: (Num a, Show a) => a -> Expr a NumOp :: (Num a) => Op -> Expr a -> Expr a -> Expr a NumUn :: String -> Expr a -> Expr a Cmp :: (Ord a) => CmpOp -> Expr a -> Expr a -> Expr Bool Apply :: Func a b -> Expr a -> Expr b If :: Expr Bool -> Expr a -> Expr a -> Expr a Print :: String -> Expr a -> Expr a Intrinsic :: String -> [Evaluatable Expr] -> Expr a Cast :: Expr Integer -> Expr Int deriving instance Show (Expr a) instance Num (Expr Int) where (+) = NumOp Add (*) = NumOp Mul abs = NumUn "abs" signum = NumUn "signum" fromInteger x = (Cast . Lift . Value) 4 instance Num a => Num (Expr a) where (+) = NumOp Add (*) = NumOp Mul abs = NumUn "abs" signum = NumUn "signum" fromInteger = error . show add :: Num a => Expr a -> Expr a -> Expr a add = NumOp Add mul :: Num a => Expr a -> Expr a -> Expr a mul = NumOp Mul less :: (Ord a) => Expr a -> Expr a -> Expr Bool less = Cmp Less -- keep Num - use light weight overloads (<+>) :: Num a => Expr a -> Expr a -> Expr a x <+> y = add x y (<.>) :: Func a b -> Expr a -> Expr b f <.> arg = func f arg true :: Expr Bool true = Bool True printIO :: String -> Expr a -> Expr a printIO = Print call :: String -> [Evaluatable Expr] -> Expr a call = Intrinsic call' :: (Show a, Show b, Show c) => String -> (Expr b, Expr c) -> Expr a call' s (a1,a2) = Intrinsic s [pack a1,pack a2] -- foreign calls need multiparam functions with heterogenous argument lists: -- class Lang e where evalExpr :: e a -> a showExpr :: e a -> String instance Lang Expr where evalExpr = eval showExpr = (++ " Done.") . show data Evaluatable e = forall b . (Lang e, Show (e b), Show b) => MkExpr (e b) deriving instance Show (Evaluatable e) pack ::Show a => Expr a -> Evaluatable Expr pack = MkExpr -- fix this ugly shit infixr 0 <..> (<..>) (a,b) = [pack a, pack b] {- Semantics -} sem :: (Num a) => Op -> a -> a -> a sem Mul = (*) sem Add = (+) semCmp :: (Ord a) => CmpOp -> a -> a -> Bool semCmp Less = (<) evalNum :: (Num a) => Op -> Expr a -> Expr a -> a evalNum op' x y = eval x `op` eval y where op = sem op' evalCmp :: (Ord a) => CmpOp -> Expr a -> Expr a -> Bool evalCmp op' x y = eval x `op` eval y where op = semCmp op' eval :: Expr a -> a eval (Vec x) = x eval (Bool x) = x eval (Num x) = x eval (NumOp op x y) = evalNum op x y eval (Apply f arg) = eval $ func f arg eval (If b t e) = if eval b then eval t else eval e eval (Cmp op x y) = evalCmp op x y eval (Print s expr) = eval (T.trace s expr) eval (Intrinsic f args) = let argVals = map evalUnpack args conc = intersperse "," argVals in error $ "could not evaluate. generate code like: " ++ f ++ "(" ++ concat conc ++ ")" eval (Lift (Value a)) = a eval (Cast x) = fromInteger (eval x) --f ++ "(" ++ (intersperse "," (map evalUnpack args)) ++")" {- Tests -} customFunc :: Func Vec3 Vec3 customFunc = Func f where f = add (Vec (1,1,1)) test1 :: Expr Vec3 test1 = let x = Vec (0,0,0) y = Vec (1,1,1) z = x + y blubber = customFunc <.> Vec (100,100,100) in blubber + z test2 :: Func Bool Vec3 test2 = Func expr where expr a = If a (Vec (0,0,0)) (Vec (110,10,10)) part :: Expr Vec3 part = test2 <.> true lessTest :: Expr Bool lessTest = less (Num 10) (Num 6) count :: (Num a, Ord a, Show a) => Expr a -> Expr a count x = let b = x `less` Num 1 continue = count $ x <+> Num (-1) in printIO "evaluating.." $ If b (Num 666) continue testIO = eval (count $ Num 20) testCall :: Expr String testCall = call' "someStrangeFunction" (Num 1,Num 2) tests = [ pack test1 , pack part , pack lessTest , pack $ count (Num 20) , pack testCall] testAll :: IO () testAll = mapM_ print' tests where print' x = do putStrLn $ "expr: " ++ showUnpack x putStrLn $ "==> " ++ evalUnpack x ++ "\n\n" showUnpack (MkExpr e) = take 200 (showExpr e) ++ " (possibly truncated)" evalUnpack (MkExpr e) = show $ evalExpr e -- frontend stuff --instance Show (Expr a) where -- show = const "expr" -- putSomething :: String -> Expr () putSomething str = T.trace str $ Lift (Value ()) data RealWorld = RealWorld instance Functor Expr where fmap f = Lift . Value . f . eval instance Monad Expr where (>>=) a b = b (eval a) return = Lift . Value newtype ExprT m a = ExprT { runExprT :: m (Expr a) } instance Monad m => Monad (ExprT m) where return = ExprT . return . Lift . Value (>>=) a b = ExprT $ runExprT a >>= runExprT . b . eval instance MonadTrans ExprT where lift m = ExprT $ liftM (Lift . Value) m instance MonadIO m => MonadIO (ExprT m) where liftIO m = lift (liftIO m) type ExprIO a = ExprT IO a evalIO :: ExprIO a -> IO (Expr a) evalIO = runExprT functorTest = (*2) <$> (Num 5) monadTest = do x <- Vec (0,0,0) putSomething $ "value: " ++ (show x) return $ Vec (5,5,5) forTest :: Expr () forTest = forM_ [Num 5, Num 6] effect where effect x = putSomething $ "value" ++ (show x) forTest2 :: ExprT IO () forTest2 = forM_ [Num 5, Num 6] effect effect :: (Show a) => a -> ExprT IO () effect x = liftIO $ putStrLn ("val: " ++ show x) filter1 :: [Expr Float] -> Expr Float filter1 xs = let sumUp = foldr (<+>) (Num 0) in sumUp xs `mul` Num 3 test3 :: Monad m => ExprT m Float -> ExprT m Float test3 a = do x <- a expr $ Num 6 - Num x expr :: Monad m => Expr a -> ExprT m a expr = return . eval test4 = -(Num (3::Int))
haraldsteinlechner/lambdaWolf
EdslTest.hs
gpl-3.0
6,727
0
12
1,826
3,026
1,562
1,464
187
2
{-# LANGUAGE OverloadedStrings #-} module Sound.Tidal.ParseTest where import TestUtils import Test.Microspec import Prelude hiding ((<*), (*>)) import Sound.Tidal.Core import Sound.Tidal.Pattern import Sound.Tidal.UI (_degradeBy) run :: Microspec () run = describe "Sound.Tidal.Parse" $ do describe "parseBP_E" $ do it "can parse strings" $ do compareP (Arc 0 12) ("a b c" :: Pattern String) (fastCat ["a", "b", "c"]) it "can parse ints" $ do compareP (Arc 0 2) ("0 1 2 3 4 5 6 7 8 0 10 20 30 40 50" :: Pattern Int) (fastCat $ map (pure . read) $ words "0 1 2 3 4 5 6 7 8 0 10 20 30 40 50") it "can alternate with <>" $ do compareP (Arc 0 2) ("a <b c>" :: Pattern String) (cat [fastCat ["a", "b"], fastCat ["a", "c"]]) it "can slow with /" $ do compareP (Arc 0 2) ("a/2" :: Pattern String) (slow 2 $ "a") it "can speed up with *" $ do compareP (Arc 0 2) ("a*8" :: Pattern String) (fast 8 "a") it "can elongate with _" $ do compareP (Arc 0 2) ("a _ _ b _" :: Pattern String) (timeCat [(3,"a"), (2,"b")]) it "can replicate with !" $ do compareP (Arc 0 2) ("a! b" :: Pattern String) (fastCat ["a", "a", "b"]) it "can replicate with ! inside {}" $ do compareP (Arc 0 2) ("{a a}%2" :: Pattern String) ("{a !}%2" :: Pattern String) it "can replicate with ! and number" $ do compareP (Arc 0 2) ("a!3 b" :: Pattern String) (fastCat ["a", "a", "a", "b"]) it "can degrade with ?" $ do compareP (Arc 0 1) ("a?" :: Pattern String) (degradeByDefault "a") it "can degrade with ? and number" $ do compareP (Arc 0 1) ("a?0.2" :: Pattern String) (_degradeBy 0.2 "a") it "can degrade with ? for double patterns" $ do compareP (Arc 0 1) ("0.4 0.5? 0.6" :: Pattern Double) (fastcat[0.4, degradeByDefault 0.5, 0.6]) it "can stretch with @" $ do comparePD (Arc 0 1) ("a@2 b" :: Pattern String) (timeCat [(2, "a"),(1,"b")]) it "can do polymeter with {}" $ do compareP (Arc 0 2) ("{a b, c d e}" :: Pattern String) (stack [fastcat [pure "a", pure "b"], slow 1.5 $ fastcat [pure "c", pure "d", pure "e"]]) it "can parse .. with ints" $ do compareP (Arc 0 2) ("0 .. 8" :: Pattern Int) ("0 1 2 3 4 5 6 7 8") it "can parse .. with rationals" $ do compareP (Arc 0 2) ("0 .. 8" :: Pattern Rational) ("0 1 2 3 4 5 6 7 8") it "can handle repeats (!) and durations (@) with <>" $ do compareP (Arc 0 31) ("<a!3 b ! c@5>" :: Pattern String) (slow 10 "[a a a b b] c") it "can handle repeats (!) and durations (@) with <> (with ints)" $ do compareP (Arc 0 31) ("<1!3 2 ! 3@5>" :: Pattern Int) (slow 10 "[1 1 1 2 2] 3") it "can handle fractional durations" $ do compareP (Arc 0 2) ("a@0.5 b@1%6 b@1%6 b@1%6" :: Pattern String) ("a b*3") it "can handle fractional durations (with rationals)" $ do compareP (Arc 0 2) ("1%3@0.5 3%4@1%6 3%4@1%6 3%4@1%6" :: Pattern Rational) ("1%3 0.75*3") it "can parse a chord" $ do compareP (Arc 0 2) ("'major" :: Pattern Int) ("[0,4,7]") it "can parse two chords" $ do compareP (Arc 0 2) ("'major 'minor" :: Pattern Int) ("[0,4,7] [0,3,7]") it "can parse c chords" $ do compareP (Arc 0 2) ("'major 'minor 'dim7" :: Pattern Int) ("c'major c'minor c'dim7") it "can parse various chords" $ do compareP (Arc 0 2) ("c'major e'minor f'dim7" :: Pattern Int) ("c e f" + "'major 'minor 'dim7") it "doesn't crash on zeroes (1)" $ do compareP (Arc 0 2) ("cp/0" :: Pattern String) (silence) it "doesn't crash on zeroes (2)" $ do compareP (Arc 0 2) ("cp(5,0)" :: Pattern String) (silence) it "doesn't crash on zeroes (3)" $ do compareP (Arc 0 2) ("cp(5,c)" :: Pattern String) (silence) where degradeByDefault = _degradeBy 0.5
d0kt0r0/Tidal
test/Sound/Tidal/ParseTest.hs
gpl-3.0
4,442
0
21
1,603
1,413
695
718
121
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Content.Orders.Refunditem -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Issues a partial or total refund for items and shipment. -- -- /See:/ <https://developers.google.com/shopping-content/v2/ Content API for Shopping Reference> for @content.orders.refunditem@. module Network.Google.Resource.Content.Orders.Refunditem ( -- * REST Resource OrdersRefunditemResource -- * Creating a Request , ordersRefunditem , OrdersRefunditem -- * Request Lenses , orrXgafv , orrMerchantId , orrUploadProtocol , orrAccessToken , orrUploadType , orrPayload , orrOrderId , orrCallback ) where import Network.Google.Prelude import Network.Google.ShoppingContent.Types -- | A resource alias for @content.orders.refunditem@ method which the -- 'OrdersRefunditem' request conforms to. type OrdersRefunditemResource = "content" :> "v2.1" :> Capture "merchantId" (Textual Word64) :> "orders" :> Capture "orderId" Text :> "refunditem" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] OrdersRefundItemRequest :> Post '[JSON] OrdersRefundItemResponse -- | Issues a partial or total refund for items and shipment. -- -- /See:/ 'ordersRefunditem' smart constructor. data OrdersRefunditem = OrdersRefunditem' { _orrXgafv :: !(Maybe Xgafv) , _orrMerchantId :: !(Textual Word64) , _orrUploadProtocol :: !(Maybe Text) , _orrAccessToken :: !(Maybe Text) , _orrUploadType :: !(Maybe Text) , _orrPayload :: !OrdersRefundItemRequest , _orrOrderId :: !Text , _orrCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OrdersRefunditem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'orrXgafv' -- -- * 'orrMerchantId' -- -- * 'orrUploadProtocol' -- -- * 'orrAccessToken' -- -- * 'orrUploadType' -- -- * 'orrPayload' -- -- * 'orrOrderId' -- -- * 'orrCallback' ordersRefunditem :: Word64 -- ^ 'orrMerchantId' -> OrdersRefundItemRequest -- ^ 'orrPayload' -> Text -- ^ 'orrOrderId' -> OrdersRefunditem ordersRefunditem pOrrMerchantId_ pOrrPayload_ pOrrOrderId_ = OrdersRefunditem' { _orrXgafv = Nothing , _orrMerchantId = _Coerce # pOrrMerchantId_ , _orrUploadProtocol = Nothing , _orrAccessToken = Nothing , _orrUploadType = Nothing , _orrPayload = pOrrPayload_ , _orrOrderId = pOrrOrderId_ , _orrCallback = Nothing } -- | V1 error format. orrXgafv :: Lens' OrdersRefunditem (Maybe Xgafv) orrXgafv = lens _orrXgafv (\ s a -> s{_orrXgafv = a}) -- | The ID of the account that manages the order. This cannot be a -- multi-client account. orrMerchantId :: Lens' OrdersRefunditem Word64 orrMerchantId = lens _orrMerchantId (\ s a -> s{_orrMerchantId = a}) . _Coerce -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). orrUploadProtocol :: Lens' OrdersRefunditem (Maybe Text) orrUploadProtocol = lens _orrUploadProtocol (\ s a -> s{_orrUploadProtocol = a}) -- | OAuth access token. orrAccessToken :: Lens' OrdersRefunditem (Maybe Text) orrAccessToken = lens _orrAccessToken (\ s a -> s{_orrAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). orrUploadType :: Lens' OrdersRefunditem (Maybe Text) orrUploadType = lens _orrUploadType (\ s a -> s{_orrUploadType = a}) -- | Multipart request metadata. orrPayload :: Lens' OrdersRefunditem OrdersRefundItemRequest orrPayload = lens _orrPayload (\ s a -> s{_orrPayload = a}) -- | The ID of the order to refund. orrOrderId :: Lens' OrdersRefunditem Text orrOrderId = lens _orrOrderId (\ s a -> s{_orrOrderId = a}) -- | JSONP orrCallback :: Lens' OrdersRefunditem (Maybe Text) orrCallback = lens _orrCallback (\ s a -> s{_orrCallback = a}) instance GoogleRequest OrdersRefunditem where type Rs OrdersRefunditem = OrdersRefundItemResponse type Scopes OrdersRefunditem = '["https://www.googleapis.com/auth/content"] requestClient OrdersRefunditem'{..} = go _orrMerchantId _orrOrderId _orrXgafv _orrUploadProtocol _orrAccessToken _orrUploadType _orrCallback (Just AltJSON) _orrPayload shoppingContentService where go = buildClient (Proxy :: Proxy OrdersRefunditemResource) mempty
brendanhay/gogol
gogol-shopping-content/gen/Network/Google/Resource/Content/Orders/Refunditem.hs
mpl-2.0
5,602
0
20
1,387
882
511
371
129
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.DoubleClickSearch.Types.Sum -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.DoubleClickSearch.Types.Sum where import Network.Google.Prelude hiding (Bytes) -- | V1 error format. data Xgafv = X1 -- ^ @1@ -- v1 error format | X2 -- ^ @2@ -- v2 error format deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable Xgafv instance FromHttpApiData Xgafv where parseQueryParam = \case "1" -> Right X1 "2" -> Right X2 x -> Left ("Unable to parse Xgafv from: " <> x) instance ToHttpApiData Xgafv where toQueryParam = \case X1 -> "1" X2 -> "2" instance FromJSON Xgafv where parseJSON = parseJSONText "Xgafv" instance ToJSON Xgafv where toJSON = toJSONText
brendanhay/gogol
gogol-doubleclick-search/gen/Network/Google/DoubleClickSearch/Types/Sum.hs
mpl-2.0
1,237
0
11
292
197
114
83
26
0
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module BookIndexer.Types.BookInfo (BookInfo(..), id_, rev, read_, token, author, title, epubVersion, onedriveId) where import Control.Lens (makeLensesWith, camelCaseFields, (^.)) import Data.Aeson (FromJSON(parseJSON), ToJSON(toJSON), (.:), (.:?), (.=), object, withObject) import Data.Maybe (catMaybes) import Data.Text (Text) data BookInfo = BookInfo { bookInfoId_ :: Text , bookInfoRev :: Maybe Text , bookInfoRead_ :: Bool , bookInfoToken :: Text , bookInfoAuthor :: Maybe Text , bookInfoTitle :: Maybe Text , bookInfoEpubVersion :: Maybe Text , bookInfoOnedriveId :: Maybe Text } makeLensesWith camelCaseFields ''BookInfo instance FromJSON BookInfo where parseJSON = withObject "Invalid BookInfo JSON" $ \o -> BookInfo <$> o .: "_id" <*> o .: "_rev" <*> o .: "read" <*> o .: "token" <*> o .:? "author" <*> o .:? "title" <*> o .:? "epubVersion" <*> o .:? "onedriveId" instance ToJSON BookInfo where toJSON b = object $ [ "_id" .= (b ^. id_) , "read" .= (b ^. read_) , "type" .= ("book" :: Text) , "token" .= (b ^. token) ] ++ catMaybes [ ("_rev" .=) <$> (b ^. rev) , ("author" .=) <$> (b ^. author) , ("title" .=) <$> (b ^. title) , ("epubVersion" .=) <$> (b ^. epubVersion) , ("onedriveId" .=) <$> (b ^. onedriveId) ]
asvyazin/my-books.purs
server/my-books/BookIndexer/Types/BookInfo.hs
mpl-2.0
1,545
0
23
355
468
277
191
35
0