code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE NoImplicitPrelude #-} module UtilSpec (spec) where import Import import Util import Test.Hspec import Test.Hspec.QuickCheck spec :: Spec spec = do describe "plus2" $ do it "basic check" $ plus2 0 `shouldBe` 2 it "overflow" $ plus2 maxBound `shouldBe` minBound + 1 prop "minus 2" $ \i -> plus2 i - 2 `shouldBe` i
haroldcarr/learn-haskell-coq-ml-etc
haskell/course/2018-06-roman-gonzales-rock-solid-haskell-services-lambdaconf/hc/test/UtilSpec.hs
unlicense
341
0
14
71
117
62
55
12
1
-- A Functor is any data type that defines how fmap [alias ($)]applies to it -- Maybe is a Functor, Applicative Functor and Monad instance Functor Maybe where fmap f (Just a) = Just (f a) fmap f Nothing = Nothing -- Control.Applicative defines <*>, which knows how to apply a function wrapped in a context to a value wrapped in a context --class (Functor f) => Applicative f where -- pure :: a -> f a -- (<*>) :: f (a -> b) -> f a -> f b -- instance Applicative Maybe where pure = Just Nothing <*> = Nothing (Just f) <*> a = fmap f a -- Monads are applicative functor supporting bind operation (>>=) class Monad M a where return :: a -> M a (>>==) :: M a -> (a -> M b) -> M b (>>) :: M a -> M b -> M b fail :: String -> M a fail message = error message instance Monad Maybe where return x = Just x Nothing >>= f = Nothing Just x >>= f = f x fail _ = Nothing
dongarerahul/edx-haskell
FunctorToMonad.hs
apache-2.0
896
0
11
226
254
126
128
-1
-1
module Main where import Tokenizer import Types import Grammar import FP_ParserGen -- Touching this file leaves you at your own devices import ASTBuilder import Checker import CodeGen import Simulation import System.FilePath main :: IO() main = do putStrLn "What file do you want to run? Please provide the relative path excluding the extension." fileName <- getLine :: IO String putStrLn "How many Sprockells do you want to use to run this file?" sprockells <- getLine :: IO String putStrLn $ "Running: " ++ fileName ++ ".shl" putStrLn $ "On " ++ sprockells ++ " Sprockells" file <- readFile $ fileName ++ ".shl" sysTest $ replicate (read sprockells :: Int) $ codeGen' (read sprockells :: Int) $ checker $ pTreeToAst $ parse grammar Program $ toTokenList $ tokenizer file
wouwouwou/2017_module_8
src/haskell/PP-project-2016/Main.hs
apache-2.0
880
0
16
235
195
98
97
27
1
{-# LANGUAGE OverloadedStrings #-} module Actions.LoginScreen.Login.Handler (handler) where import qualified Data.Text.Lazy as TL import qualified Text.Digestive as D import Web.Scotty (redirect) import Text.Digestive.Scotty (runForm) import App (Action, PGPool, runQuery) import Auth (doLoginAction) import qualified Model.User as U import qualified Persistence.User as U import qualified Page import Actions.FormUtils (addError, emailFormlet, passwordFormlet) import Actions.LoginScreen.LoginScreen (LoginForm, LoginRequest(..), formView) import qualified Actions.Main.Url as Main {-# ANN module ("HLint: ignore Use camelCase" :: String) #-} {-# ANN module ("HLint: ignore Redundant do" :: String) #-} form :: Monad m => LoginForm m form = LoginRequest <$> "email" D..: emailFormlet Nothing <*> "password" D..: passwordFormlet Nothing handler :: PGPool -> Action handler pool = do f <- runForm "loginForm" form case f of (v, Nothing) -> Page.render (formView v) Page.defaultPageConfig (v, Just loginReq) -> do mUser <- runQuery pool $ U.getUserByEmail (U.Email $ TL.fromStrict $ lr_email loginReq) case mUser of Nothing -> do let v2 = addError v "email" "Email not registered" Page.render (formView v2) Page.defaultPageConfig Just user -> if not (U.u_registration_confirmed user) then do let v2 = addError v "email" "Email registration has not been confirmed." Page.render (formView v2) Page.defaultPageConfig else if not $ U.authUser (U.Password $ TL.fromStrict $ lr_password loginReq) user then do let v2 = addError v "password" "Incorrect password." Page.render (formView v2) Page.defaultPageConfig else doLoginAction pool user $ redirect $ TL.pack Main.url
DataStewardshipPortal/ds-wizard
DSServer/app/Actions/LoginScreen/Login/Handler.hs
apache-2.0
1,859
0
22
416
503
269
234
38
5
{- let w = "white" let b = "blue" let o = "orange" let g = "green" let r = "red" let y = "yellow" let u = "up" let d = "down" let f = "front" let x = "back" let l = "left" let t = "right" let colors = ("white", "blue", "orange", "green", "red", "yellow") let sides = ("up", "down", "front", "back", "left", "right") let axes = ("x", "y", "z") let side_order = (u, d, f, x, l, t) -- let positions = ( (u, f, l), (u, x, l), (u, f, t), (u, x, t), (d, f, l), (d, x, l), (d, f, t), (d, x, t), (u, f), (u, x), (u, l), (u, t), (d, f), (d, x), (d, l), (d, t)) -} capital :: String -> String capital "" = "Empty string, whoops!" capital all@(x:xs) = "The first letter of " ++ all ++ " is " ++ [x]
gijzelaerr/HasSolved
main.hs
apache-2.0
700
0
8
167
52
28
24
3
1
{-# LANGUAGE CPP #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS -fno-warn-unused-top-binds #-} -- for lenses module Pos.WorkMode ( WorkMode , MinWorkMode -- * Actual modes , RealMode , RealModeContext(..) , EmptyMempoolExt ) where import Universum import Control.Lens (makeLensesWith) import qualified Control.Monad.Reader as Mtl import Pos.Chain.Block (HasSlogContext (..), HasSlogGState (..)) import Pos.Chain.Delegation (DelegationVar) import Pos.Chain.Ssc (SscMemTag, SscState) import Pos.Chain.Update (UpdateConfiguration) import Pos.Context (HasNodeContext (..), HasPrimaryKey (..), HasSscContext (..), NodeContext) import Pos.Core.JsonLog (CanJsonLog (..)) import Pos.Core.Reporting (HasMisbehaviorMetrics (..)) import Pos.Core.Slotting (HasSlottingVar (..), MonadSlotsData) import Pos.DB (MonadGState (..), NodeDBs) import Pos.DB.Block (MonadBListener (..), dbGetSerBlockRealDefault, dbGetSerBlundRealDefault, dbGetSerUndoRealDefault, dbPutSerBlundsRealDefault, onApplyBlocksStub, onRollbackBlocksStub) import Pos.DB.Class (MonadDB (..), MonadDBRead (..)) import Pos.DB.DB (gsAdoptedBVDataDefault) import Pos.DB.Rocks (dbDeleteDefault, dbGetDefault, dbIterSourceDefault, dbPutDefault, dbWriteBatchDefault) import Pos.DB.Txp (GenericTxpLocalData, MempoolExt, MonadTxpLocal (..), TxpHolderTag, txNormalize, txProcessTransaction) import Pos.Infra.Network.Types (HasNodeType (..), getNodeTypeDefault) import Pos.Infra.Reporting (MonadReporting (..), Reporter (..)) import Pos.Infra.Shutdown (HasShutdownContext (..)) import Pos.Infra.Slotting.Class (MonadSlots (..)) import Pos.Infra.Slotting.Impl (currentTimeSlottingSimple, getCurrentSlotBlockingSimple, getCurrentSlotInaccurateSimple, getCurrentSlotSimple) import Pos.Infra.Util.JsonLog.Events (HasJsonLogConfig (..), JsonLogConfig, jsonLogDefault) import Pos.Util.Lens (postfixLFields) import Pos.Util.LoggerName (HasLoggerName' (..), askLoggerNameDefault, modifyLoggerNameDefault) import Pos.Util.UserSecret (HasUserSecret (..)) import Pos.Util.Util (HasLens (..)) import Pos.Util.Wlog (HasLoggerName (..), LoggerName) import Pos.WorkMode.Class (MinWorkMode, WorkMode) data RealModeContext ext = RealModeContext { rmcNodeDBs :: !NodeDBs , rmcSscState :: !SscState , rmcTxpLocalData :: !(GenericTxpLocalData ext) , rmcDelegationVar :: !DelegationVar , rmcJsonLogConfig :: !JsonLogConfig , rmcLoggerName :: !LoggerName , rmcNodeContext :: !NodeContext , rmcReporter :: !(Reporter IO) -- ^ How to do reporting. It's in here so that we can have -- 'MonadReporting (RealMode ext)' in the mean-time, until we -- re-architecht the reporting system so that it's not built-in to the -- application's monad. , rmcUpdateConfiguration :: !UpdateConfiguration } type EmptyMempoolExt = () type RealMode ext = Mtl.ReaderT (RealModeContext ext) IO makeLensesWith postfixLFields ''RealModeContext instance HasLens NodeDBs (RealModeContext ext) NodeDBs where lensOf = rmcNodeDBs_L instance HasLens UpdateConfiguration (RealModeContext ext) UpdateConfiguration where lensOf = rmcUpdateConfiguration_L instance HasLens NodeContext (RealModeContext ext) NodeContext where lensOf = rmcNodeContext_L instance HasLens SscMemTag (RealModeContext ext) SscState where lensOf = rmcSscState_L instance HasLens TxpHolderTag (RealModeContext ext) (GenericTxpLocalData ext) where lensOf = rmcTxpLocalData_L instance HasLens DelegationVar (RealModeContext ext) DelegationVar where lensOf = rmcDelegationVar_L instance HasNodeType (RealModeContext ext) where getNodeType = getNodeTypeDefault @() instance {-# OVERLAPPABLE #-} HasLens tag NodeContext r => HasLens tag (RealModeContext ext) r where lensOf = rmcNodeContext_L . lensOf @tag instance HasSscContext (RealModeContext ext) where sscContext = rmcNodeContext_L . sscContext instance HasPrimaryKey (RealModeContext ext) where primaryKey = rmcNodeContext_L . primaryKey instance HasMisbehaviorMetrics (RealModeContext ext) where misbehaviorMetrics = rmcNodeContext_L . misbehaviorMetrics instance HasUserSecret (RealModeContext ext) where userSecret = rmcNodeContext_L . userSecret instance HasShutdownContext (RealModeContext ext) where shutdownContext = rmcNodeContext_L . shutdownContext instance HasSlottingVar (RealModeContext ext) where slottingTimestamp = rmcNodeContext_L . slottingTimestamp slottingVar = rmcNodeContext_L . slottingVar instance HasSlogContext (RealModeContext ext) where slogContext = rmcNodeContext_L . slogContext instance HasSlogGState (RealModeContext ext) where slogGState = slogContext . scGState instance HasNodeContext (RealModeContext ext) where nodeContext = rmcNodeContext_L instance HasLoggerName' (RealModeContext ext) where loggerName = rmcLoggerName_L instance HasJsonLogConfig (RealModeContext ext) where jsonLogConfig = rmcJsonLogConfig_L instance {-# OVERLAPPING #-} HasLoggerName (RealMode ext) where askLoggerName = askLoggerNameDefault modifyLoggerName = modifyLoggerNameDefault instance {-# OVERLAPPING #-} CanJsonLog (RealMode ext) where jsonLog = jsonLogDefault instance MonadSlotsData ctx (RealMode ext) => MonadSlots ctx (RealMode ext) where getCurrentSlot = getCurrentSlotSimple getCurrentSlotBlocking = getCurrentSlotBlockingSimple getCurrentSlotInaccurate = getCurrentSlotInaccurateSimple currentTimeSlotting = currentTimeSlottingSimple instance MonadGState (RealMode ext) where gsAdoptedBVData = gsAdoptedBVDataDefault instance MonadDBRead (RealMode ext) where dbGet = dbGetDefault dbIterSource = dbIterSourceDefault dbGetSerBlock = dbGetSerBlockRealDefault dbGetSerUndo = dbGetSerUndoRealDefault dbGetSerBlund = dbGetSerBlundRealDefault instance MonadDB (RealMode ext) where dbPut = dbPutDefault dbWriteBatch = dbWriteBatchDefault dbDelete = dbDeleteDefault dbPutSerBlunds = dbPutSerBlundsRealDefault instance MonadBListener (RealMode ext) where onApplyBlocks = onApplyBlocksStub onRollbackBlocks nm _ blunds = onRollbackBlocksStub nm blunds type instance MempoolExt (RealMode ext) = ext instance MonadTxpLocal (RealMode ()) where txpNormalize = txNormalize txpProcessTx = txProcessTransaction instance MonadReporting (RealMode ext) where report rt = Mtl.ask >>= liftIO . flip runReporter rt . rmcReporter
input-output-hk/cardano-sl
lib/src/Pos/WorkMode.hs
apache-2.0
7,136
0
11
1,562
1,437
839
598
-1
-1
-- Based on Examples from HUnit user's guide module KakuroTest where import Test.HUnit import Kakuro foo :: Int -> (Int, Int) foo x = (1, x) partA :: Int -> IO (Int, Int) partA v = return (v+2, v+3) partB :: Int -> IO Bool partB v = return (v > 5) test1 :: Test test1 = TestCase (assertEqual "for (foo 3)," (1,2) (foo 3)) test2 :: Test test2 = TestCase (do (x,y) <- partA 3 assertEqual "for the first result of partA," 5 x b <- partB y assertBool ("(partB " ++ show y ++ ") failed") b) tests :: Test tests = TestList [TestLabel "test1" test1, TestLabel "test2" test2] tests' :: Test tests' = test [ "test1" ~: "(foo 3)" ~: (1,2) ~=? (foo 3), "test2" ~: do (x, y) <- partA 3 assertEqual "for the first result of partA," 5 x partB y @? "(partB " ++ show y ++ ") failed" ] main :: IO Counts main = do putStrLn $ show $ permuteAll [v, v] 6 putStrLn (draw Empty) putStrLn (draw (Across 9)) putStrLn (draw (DownAcross 9 9)) putStrLn (draw v) putStrLn (draw (vv [1, 3, 5, 9])) putStrLn (drawGrid grid1) putStrLn (drawGrid (solveGrid grid1)) putStrLn $ drawGrid $ solver grid1 runTestTT tests runTestTT tests'
gavilancomun/kakuro-haskell
KakuroTest.hs
apache-2.0
1,322
0
13
430
530
264
266
36
1
{-# LANGUAGE OverloadedStrings #-} {- Copyright 2019 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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 ErrorSanitizer (rewriteErrors) where import Data.List import Data.Text (Text) import RegexShim (replace) rewriteStages :: [(Text, Text)] rewriteStages = [ ("\8216", "") , ("\8217", "") , ("warning: ([a-zA-Z,0-9 ]*)\\[-Wdefer[a-z-]*\\]", "error: \\1") , (" \\[-W[a-z-]*\\]", "") , ("IO action main", "variable program") , ("main IO action", "variable") , ("exported by", "defined in") , ("bound at program[.]hs", "defined at program.hs") , ("module Main", "your code") , ("main\\:Main", "your code") , ("[ ]*\8226 Possible cause: [(].*[)] is applied to too many arguments\n", "") , ("[ ]*except perhaps to import instances from [A-Za-z0-9.]*\n", "") , ("[ ]*To import instances alone, use: import [A-Za-z0-9.]*[(][)]\n", "") , ("^([ ]*(\8226 )?)(.*[Nn]ot in scope: .* :: Text)", "\\1\\3\n\\1Perhaps you meant to put quotation marks around this text.") , ("is applied to too few arguments", "is missing arguments") , ("is applied to too many arguments", "is a value, but a function is needed here.") , ("Couldn't match expected type Text\\s*with actual type GHC.Types.Char", "Text requires double quotes, rather than single.") , ("[ ]*Perhaps you intended to use TemplateHaskell or TemplateHaskellQuotes\n", "") , ("(program.hs:[0-9]*:1:(.|\n )*) [(]possibly incorrect indentation or mismatched brackets[)]", "\\1\n \8226 If this line continues the previous definition, indent it." <> "\n \8226 Otherwise, are you missing a parenthesis on the previous line)?") , (" [(]possibly incorrect indentation or mismatched brackets[)]", "\n \8226 Are you missing a parenthesis?") , ("In the Template Haskell quotation '.*'", "Use double quotes around text values.") , ("[ ]+\8226 In ([^\n\8226]|\n )+\n", "") , ("(( |\n)*)base-[0-9.]*:GHC\\.Stack\\.Types\\.HasCallStack =>( |\n)*", " ") , ("When checking that:\\s*[^\n]*\\s*is more polymorphic than:\\s*[^\n]*(\n\\s*)?", "") , ("Perhaps you need a 'let' in a 'do' block[?][ \t\n]*e.g. '[^']*' instead of '[^']*'", "An equation does not fit here. Is this line indented incorrectly?") , ("[pP]arse error on input import\n", "Parse error\n Import statements belong at the beginning of your code.\n") , ("\\[GHC\\.Types\\.Char\\] -> ", "\n") , ("base(-[0-9.]*)?\\:.*( |\n)*->( |\n)*", "\n") , ("integer-gmp(-[0-9\\.]*)?:(.|\n)*->( |\n)*", "") , ("GHC\\.[A-Za-z.]*(\\s|\n)*->( |\n)*", "") , ("at src/[A-Za-z0-9\\/.:]*", "") , ("\\[GHC\\.Types\\.Char\\]", "") , ("codeworld-base[-.:_A-Za-z0-9]*", "the standard library") , ("Main\\.", "") , ("main :: t", "program") , ("Prelude\\.", "") , ("\\bBool\\b", "Truth") , ("IO \\(\\)", "Program") , ("IO [a-z][a-zA-Z0-9_]*", "Program") , ("[ ]*Perhaps you intended to use TemplateHaskell\n", "") , ("imported from [^)\n]*", "defined in the standard library") , ("( |\n)*[(]and originally defined in [^)]*[)]", "") , ("the first argument", "the argument(s)") , ("[ ]*The function [a-zA-Z0-9_]* is applied to [a-z0-9]* arguments,\n", "") , ("[ ]*but its type .* has only .*\n", "") , ("A data constructor of that name is in scope; did you mean DataKinds\\?", "That name refers to a value, not a type.") , ("type constructor or class", "type") , ("Illegal tuple section: use TupleSections", "This tuple is missing a value, or has an extra comma.") , ("in string/character literal", "in text literal") , ("lexical error in text literal at end of input", "Missing the end quotation mark for a Text value.") , ("lexical error in text literal at character '\\\\n'", "Missing the end quotation mark for a Text value.") , ("lexical error at character '\\\\822[01]'", "Smart quotes are not allowed.") , ("[(]main[)]", "program") , ("\\bmain\\b", "program") , ("a pattern binding", "the definition") , ("Use -v to see a list of the files searched for\\.", "") , ("Could not load module", "Could not find module") , ("[ ]*It is a member of the hidden package [^\n]*\n", "") , ("[ ]*You can run :set [^\n]*\n", "") , ("[ ]*[(]Note: this unloads all the modules in the current scope[.][)]\n", "") , ("^ Where: [^\n]*rigid type variable[^\n]*\n( [^\n]*\n)*", "") , (" \8226 Relevant bindings include\n( [^\n]*\n)*", "") , (" \8226 Relevant bindings include [^\n]*\n", "") , (" Valid hole fits include", " \8226 Valid hole fits include") , ("^[ ]+with [^\n]+@[^\n]+\n", "") , ("[(]Some hole fits suppressed; use -fmax-valid-hole-fits=N or -fno-max-valid-hole-fits[)]", "...") , ("CallStack \\(from HasCallStack\\):", "When evaluating:") , (", called at program.hs:", ", used at program.hs:") , ("module header, import declaration\n or top-level declaration expected.", "An equation was expected here.\n Are you missing the equal sign?") , ("forall( [a-z0-9]+)*[.] ", "") , ("^<<loop>>$", "Stuck because your code contains a circular definition.") , ("\n\\s+\n", "\n") ] rewriteErrors :: Text -> Text rewriteErrors output = foldl' applyStage output rewriteStages where applyStage s (pattern, sub) = replace pattern sub s
alphalambda/codeworld
codeworld-error-sanitizer/src/ErrorSanitizer.hs
apache-2.0
5,996
0
8
1,280
754
493
261
98
1
{-# LANGUAGE Arrows #-} {- | An experiment in using Haskell Arrows, see <http://www.haskell.org/arrows/>, to automagically compute Lipschitz constants of maps. Something like this can also be used to compute derivatives of functions. Here we use floats, but later we intend to replace them with exact reals. -} module Data.Reals.Lipschitz where import Control.Category import Control.Arrow -- | Locally Lipshitz maps from @a@ to @b@ data Lipschitz a b = Lipschitz { scaling :: a -> Float, apply :: a -> b } instance Category Lipschitz where id = Lipschitz { scaling = const 1.0, apply = (\x -> x) } g . f = Lipschitz { scaling = (\x -> scaling f x * scaling g (apply f x)), apply = (\x -> apply g (apply f x)) } instance Arrow Lipschitz where arr f = Lipschitz { scaling = const infinity, apply = f } where infinity = 1.0 / 0.0 first f = Lipschitz { scaling = (\(x, _) -> scaling f x), apply = (\(x,y) -> (apply f x, y)) } second f = Lipschitz { scaling = (\(_, y) -> scaling f y), apply = (\(x,y) -> (x, apply f y)) } f *** g = Lipschitz { scaling = (\(x,y) -> max (scaling f x) (scaling g y)), apply = (\(x,y) -> (apply f x, apply g y)) } f &&& g = Lipschitz { scaling = (\x -> max (scaling f x) (scaling g x)), apply = (\x -> (apply f x, apply g x)) }
comius/haskell-fast-reals
src/Data/Reals/Lipschitz.hs
bsd-2-clause
1,463
0
13
460
509
289
220
20
0
module Aws.Sqs.Commands.Message where import Aws.Core import Aws.Sqs.Core import Control.Applicative import Control.Monad.Trans.Resource (MonadThrow) import Data.Maybe import Text.XML.Cursor (($/), ($//), (&/), (&|)) import qualified Data.ByteString.Char8 as B import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Text.XML.Cursor as Cu data SendMessage = SendMessage{ smMessage :: T.Text, smQueueName :: QueueName }deriving (Show) data SendMessageResponse = SendMessageResponse{ smrMD5OfMessageBody :: T.Text, smrMessageId :: MessageId } deriving (Show) instance ResponseConsumer r SendMessageResponse where type ResponseMetadata SendMessageResponse = SqsMetadata responseConsumer _ = sqsXmlResponseConsumer parse where parse el = do md5 <- force "Missing MD5 Signature" $ el $// Cu.laxElement "MD5OfMessageBody" &/ Cu.content mid <- force "Missing Message Id" $ el $// Cu.laxElement "MessageId" &/ Cu.content return SendMessageResponse { smrMD5OfMessageBody = md5, smrMessageId = MessageId mid } -- | ServiceConfiguration: 'SqsConfiguration' instance SignQuery SendMessage where type ServiceConfiguration SendMessage = SqsConfiguration signQuery SendMessage {..} = sqsSignQuery SqsQuery { sqsQueueName = Just smQueueName, sqsQuery = [("Action", Just "SendMessage"), ("MessageBody", Just $ TE.encodeUtf8 smMessage )]} instance Transaction SendMessage SendMessageResponse instance AsMemoryResponse SendMessageResponse where type MemoryResponse SendMessageResponse = SendMessageResponse loadToMemory = return data DeleteMessage = DeleteMessage{ dmReceiptHandle :: ReceiptHandle, dmQueueName :: QueueName }deriving (Show) data DeleteMessageResponse = DeleteMessageResponse{ } deriving (Show) instance ResponseConsumer r DeleteMessageResponse where type ResponseMetadata DeleteMessageResponse = SqsMetadata responseConsumer _ = sqsXmlResponseConsumer parse where parse _ = do return DeleteMessageResponse {} -- | ServiceConfiguration: 'SqsConfiguration' instance SignQuery DeleteMessage where type ServiceConfiguration DeleteMessage = SqsConfiguration signQuery DeleteMessage {..} = sqsSignQuery SqsQuery { sqsQueueName = Just dmQueueName, sqsQuery = [("Action", Just "DeleteMessage"), ("ReceiptHandle", Just $ TE.encodeUtf8 $ printReceiptHandle dmReceiptHandle )]} instance Transaction DeleteMessage DeleteMessageResponse instance AsMemoryResponse DeleteMessageResponse where type MemoryResponse DeleteMessageResponse = DeleteMessageResponse loadToMemory = return data ReceiveMessage = ReceiveMessage { rmVisibilityTimeout :: Maybe Int , rmAttributes :: [MessageAttribute] , rmMaxNumberOfMessages :: Maybe Int , rmQueueName :: QueueName } deriving (Show) data Message = Message { mMessageId :: T.Text , mReceiptHandle :: ReceiptHandle , mMD5OfBody :: T.Text , mBody :: T.Text , mAttributes :: [(MessageAttribute,T.Text)] } deriving(Show) data ReceiveMessageResponse = ReceiveMessageResponse { rmrMessages :: [Message] } deriving (Show) readMessageAttribute :: MonadThrow m => Cu.Cursor -> m (MessageAttribute,T.Text) readMessageAttribute cursor = do name <- force "Missing Name" $ cursor $/ Cu.laxElement "Name" &/ Cu.content value <- force "Missing Value" $ cursor $/ Cu.laxElement "Value" &/ Cu.content parsedName <- parseMessageAttribute name return (parsedName, value) readMessage :: Cu.Cursor -> [Message] readMessage cursor = do mid :: T.Text <- force "Missing Message Id" $ cursor $// Cu.laxElement "MessageId" &/ Cu.content rh <- force "Missing Reciept Handle" $ cursor $// Cu.laxElement "ReceiptHandle" &/ Cu.content md5 <- force "Missing MD5 Signature" $ cursor $// Cu.laxElement "MD5OfBody" &/ Cu.content body <- force "Missing Body" $ cursor $// Cu.laxElement "Body" &/ Cu.content let attributes :: [(MessageAttribute, T.Text)] = concat $ cursor $// Cu.laxElement "Attribute" &| readMessageAttribute return Message{ mMessageId = mid, mReceiptHandle = ReceiptHandle rh, mMD5OfBody = md5, mBody = body, mAttributes = attributes} formatMAttributes :: [MessageAttribute] -> [(B.ByteString, Maybe B.ByteString)] formatMAttributes attrs = case length attrs of 0 -> [] 1 -> [("AttributeName", Just $ B.pack $ show $ attrs !! 0)] _ -> zipWith (\ x y -> ((B.concat ["AttributeName.", B.pack $ show $ y]), Just $ TE.encodeUtf8 $ printMessageAttribute x) ) attrs [1 :: Integer ..] instance ResponseConsumer r ReceiveMessageResponse where type ResponseMetadata ReceiveMessageResponse = SqsMetadata responseConsumer _ = sqsXmlResponseConsumer parse where parse el = do let messages = concat $ el $// Cu.laxElement "Message" &| readMessage return ReceiveMessageResponse{ rmrMessages = messages } -- | ServiceConfiguration: 'SqsConfiguration' instance SignQuery ReceiveMessage where type ServiceConfiguration ReceiveMessage = SqsConfiguration signQuery ReceiveMessage {..} = sqsSignQuery SqsQuery { sqsQueueName = Just rmQueueName, sqsQuery = [("Action", Just "ReceiveMessage")] ++ catMaybes[("VisibilityTimeout",) <$> case rmVisibilityTimeout of Just x -> Just $ Just $ B.pack $ show x Nothing -> Nothing, ("MaxNumberOfMessages",) <$> case rmMaxNumberOfMessages of Just x -> Just $ Just $ B.pack $ show x Nothing -> Nothing] ++ formatMAttributes rmAttributes} instance Transaction ReceiveMessage ReceiveMessageResponse instance AsMemoryResponse ReceiveMessageResponse where type MemoryResponse ReceiveMessageResponse = ReceiveMessageResponse loadToMemory = return data ChangeMessageVisibility = ChangeMessageVisibility { cmvReceiptHandle :: ReceiptHandle, cmvVisibilityTimeout :: Int, cmvQueueName :: QueueName }deriving (Show) data ChangeMessageVisibilityResponse = ChangeMessageVisibilityResponse{ } deriving (Show) instance ResponseConsumer r ChangeMessageVisibilityResponse where type ResponseMetadata ChangeMessageVisibilityResponse = SqsMetadata responseConsumer _ = sqsXmlResponseConsumer parse where parse _ = do return ChangeMessageVisibilityResponse{} -- | ServiceConfiguration: 'SqsConfiguration' instance SignQuery ChangeMessageVisibility where type ServiceConfiguration ChangeMessageVisibility = SqsConfiguration signQuery ChangeMessageVisibility {..} = sqsSignQuery SqsQuery { sqsQueueName = Just cmvQueueName, sqsQuery = [("Action", Just "ChangeMessageVisibility"), ("ReceiptHandle", Just $ TE.encodeUtf8 $ printReceiptHandle cmvReceiptHandle), ("VisibilityTimeout", Just $ B.pack $ show cmvVisibilityTimeout)]} instance Transaction ChangeMessageVisibility ChangeMessageVisibilityResponse instance AsMemoryResponse ChangeMessageVisibilityResponse where type MemoryResponse ChangeMessageVisibilityResponse = ChangeMessageVisibilityResponse loadToMemory = return
RayRacine/aws
Aws/Sqs/Commands/Message.hs
bsd-3-clause
8,219
2
19
2,361
1,773
955
818
-1
-1
{-# LANGUAGE Arrows, TupleSections, OverloadedStrings #-} module Scoutess.DataFlow where import Control.Applicative ((<$>)) import Control.Arrow import Control.Monad (when, forM_) import Control.Monad.Error import Control.Monad.Trans import Control.Monad.Trans.Maybe import Control.Monad.Writer import Data.Either (partitionEithers) import Data.Maybe (catMaybes, fromJust, fromMaybe, isNothing) import Data.Monoid import qualified Data.Set as S import Data.Text (Text) import qualified Data.Text as T import System.Exit (ExitCode(..)) import System.Process (readProcessWithExitCode) import System.Directory (createDirectoryIfMissing, doesDirectoryExist, doesFileExist, removeDirectoryRecursive, removeFile) import System.FilePath ((</>),(<.>)) import Scoutess.Core import Scoutess.Service.LocalHackage.Core import Scoutess.Service.Source.Fetch (fetchSrc, fetchSrcs, fetchVersion, fetchVersions) import Scoutess.Types import Distribution.Simple.Configure (getPersistBuildConfig) -- standard build standard :: Scoutess SourceSpec SourceSpec -- ^ sourceFilter -> Scoutess VersionSpec VersionSpec -- ^ versionFilter -> Scoutess (SourceSpec, TargetSpec, Maybe PriorRun) BuildReport standard sourceFilter versionFilter = proc (sourceSpec, targetSpec, mPriorRun) -> do let locations = mkLocations (tsTmpDir targetSpec) (tsGhcPath targetSpec) initializeSandbox -< (targetSpec, locations) availableVersions <- fetchVersionSpec sourceFilter -< (sourceSpec, locations) consideredVersions <- versionFilter -< availableVersions buildSpec <- produceBuildSpec -< (targetSpec, consideredVersions, mPriorRun, locations) buildSources <- getSources -< (buildSpec, locations) index <- updateLocalHackage -< (buildSpec, buildSources, locations) buildReport <- build -< (buildSpec, targetSource buildSources, index, locations) -- () <- haddock -< (buildSpec, targetSource buildSources, index, locations) returnA -< buildReport -- | Clear the local hackage, ensure that the temp directory exists and is empty, and create an empty packageDB. initializeSandbox :: Scoutess (TargetSpec, Locations) () initializeSandbox = withComponent "initialize" $ \(targetSpec, locations) -> do liftIO $ clearLocalHackage (lLocalHackage locations) let emptyDirs = [] -- [lTmpDir locations] forM_ emptyDirs $ \filePath -> liftIO $ do dirExists <- doesDirectoryExist filePath when dirExists $ removeDirectoryRecursive filePath createDirectoryIfMissing True filePath {- let packageDB = lPackageDB locations packageDBExists <- liftIO $ doesDirectoryExist packageDB when packageDBExists $ liftIO (removeDirectoryRecursive packageDB) (exitCode, out, err) <- liftIO $ readProcessWithExitCode "ghc-pkg" ["init", packageDB] [] report (T.unlines [ "Calling ghc-pkg init returned:" , "ExitCode:", T.pack (show exitCode) , "StdOut:" , T.pack out , "StdErr:" , T.pack err]) -} let sandboxDir = lSandboxDir locations (exitCode, out, err) <- liftIO $ readProcessWithExitCode "cabal" ["sandbox", "init", "--sandbox", sandboxDir] [] report (T.unlines [ "Calling ghc-pkg init returned:" , "ExitCode:", T.pack (show exitCode) , "StdOut:" , T.pack out , "StdErr:" , T.pack err ]) componentFinish (exitCode == ExitSuccess) () -- when (exitCode /= ExitSuccess) componentFatal -- | Fetch the available versions from the 'SourceSpec', take the target's 'VersionInfo' -- and then return the filtered set in a 'VersionSpec' fetchVersionSpec :: Scoutess SourceSpec SourceSpec -> Scoutess (SourceSpec, Locations) VersionSpec fetchVersionSpec sourceFilter = withComponent "fetchVersionSpec" $ \(sourceSpec, locations) -> do filteredSources <- fst <$> (liftIO (runScoutess sourceFilter sourceSpec)) when (isNothing filteredSources) $ do report "The sourceFilter failed" mzero let filteredSources' = S.toList . ssLocations . fromJust $ filteredSources (exceptions, versionSpecs) <- liftIO $ fetchVersions (lSourceConfig locations) filteredSources' let combined = mconcat versionSpecs versionsErr = case exceptions of [] -> "" _ -> "Fetching the versions gave these exceptions: " <> T.unlines (map sourceErrorMsg exceptions) report versionsErr return (True, combined) findTargets :: VersionSpec -> TargetSpec -> [Maybe VersionInfo] findTargets versionSpec targetSpec = map findTarget (S.toList $ tsTargets targetSpec) where findTarget :: Target -> Maybe VersionInfo findTarget target = findVersion (tName target) (tVersion target) (tLocation target) versionSpec -- | Given the packages we can build from, ask cabal install to work out the dependency graph for us -- by creating a package index for all fetchable versions (even though we don't actually have -- any of the sources yet). produceBuildSpec :: Scoutess (TargetSpec, VersionSpec, Maybe PriorRun, Locations) BuildSpec produceBuildSpec = withComponent "produceBuildSpec" $ \(targetSpec, versionSpec, mPriorRun, locations) -> do let configFile = lTmpDir locations </> "config" sandboxDir = lPackageDB locations fakeRepo = lTmpDir locations </> "fakeRepo" ghcPath = lGhcPath locations liftIO $ createPackageIndexWith const versionSpec fakeRepo -- XXX: 'const' will just pick packages with the highest SourceLocation liftIO $ writeFile configFile ("local-repo: " <> fakeRepo) let versionInfos = catMaybes $ findTargets versionSpec targetSpec -- XXX: shouldn't just discard failures targetCabals <- liftIO $ mapM (writeCabal (lTmpDir locations)) versionInfos let cabalArgs = [-- "--config-file=" <> configFile "-v" , "--package-db=clear" , "--with-compiler=" <> ghcPath -- ,"--package-db=global" -- THIS IS TEMPORARY! See <http://hackage.haskell.org/trac/ghc/ticket/5977> -- ,"--package-db=" <> sandboxDir , "--dry-run" , "install"] ++ targetCabals (exitCode, stdOut, stdErr) <- liftIO $ readProcessWithExitCode "cabal" cabalArgs [] let deps = parseDependencies stdOut `findIn` (vsVersions versionSpec) -- TODO: we still need to build if we need to produce docs (What about checking for up-to-date docs?) {- toBuild' pr = not (prTarget pr == targetInfo && S.toList (prDependencies pr) == deps) toBuild = maybe True toBuild' mPriorRun -} output = T.pack $ unlines [ "Calling cabal install --dry-run returned:" , "ExitCode:", show exitCode, "StdOut:", stdOut, "StdErr:", stdErr] success = exitCode == ExitSuccess report output guard success componentPass $ BuildSpec { bsTargetSpec = targetSpec , bsTargetInfo = versionInfos , bsDependencies = deps , bsToBuild = True } -- FIXME: calculate if we really need to run -- | Fetch the sources for the target and its dependencies getSources :: Scoutess (BuildSpec, Locations) BuildSources getSources = withComponent "getSources" $ \(buildSpec, locations) -> do let sourceConfig = lSourceConfig locations depVersionInfos = bsDependencies buildSpec targetVersionInfos = bsTargetInfo buildSpec {- eTargetSources <- mapM (fetchSrc sourceConfig) targetVersionInfos when (isLeft eTargetSource) $ do report $ "Unable to fetch the target source with error:\n" <> sourceErrorMsg (fromLeft eTargetSource) mzero let targetSource' = fromRight eTargetSource -} (exceptions', targetSources) <- fetchSrcs sourceConfig targetVersionInfos (exceptions, depSources') <- fetchSrcs sourceConfig depVersionInfos let depSourceReport = case exceptions of [] -> "" _ -> "fetching the sources gave these exceptions:\n" <> T.unlines (map sourceErrorMsg exceptions) report depSourceReport componentPass $ BuildSources targetSources depSources' where isLeft (Left _) = True isLeft _ = False fromLeft (Left l) = l fromRight (Right r) = r -- | Add all the sources to the local hackage index specified by the buildSpec updateLocalHackage :: Scoutess (BuildSpec, BuildSources, Locations) LocalHackageIndex updateLocalHackage = withComponent "updateLocalHackage" $ \(buildSpec, buildSources, locations) -> do let localHackage = lLocalHackage locations tmpDir = lTmpDir locations indexPath = tmpDir </> "00-index.tar" allSources = targetSource buildSources ++ depSources buildSources liftIO $ addPackages allSources localHackage index <- liftIO $ generateIndexSelectively (Just (map siVersionInfo allSources)) localHackage indexPath componentPass index -- | Given a directive of what to build and the location of the target package, -- call /cabal install/ build :: Scoutess (BuildSpec, [SourceInfo], LocalHackageIndex, Locations) BuildReport build = withComponent "build" $ \(buildSpec, targetSourceInfos, _, locations) -> do let targetSpec = bsTargetSpec buildSpec sandboxDir = lPackageDB locations installDir = sandboxDir configFile = lTmpDir locations </> "config" -- logLocation = lTmpDir locations </> "cabal-sandbox" </> "logs" </> "build.log" targetSourcePaths = map siPath targetSourceInfos mTargetCabals <- liftIO $ mapM findCabalFile targetSourcePaths when (any isNothing mTargetCabals) $ do report $ "Couldn't find the target's cabal file in: " -- FIXME <> T.pack targetSourcePath mzero let targetCabals = catMaybes mTargetCabals configExists <- liftIO $ doesFileExist configFile when configExists (liftIO $ removeFile configFile) liftIO . writeFile configFile $ unlines [ "local-repo: " <> hackageDir (lLocalHackage locations) ] -- , "build-summary: " <> logLocation ] let cabalArgs = [-- "--config-file=" <> configFile -- ,"--package-db=clear" -- ,"--package-db=global" -- THIS IS TEMPORARY TOO: <http://hackage.haskell.org/trac/ghc/ticket/5977> -- ,"--package-db=" <> sandboxDir -- ,"--prefix=" <> installDir "-v" , "--package-db=clear" , "--with-compiler=" <> (lGhcPath locations) ,"install" ] ++ targetCabals -- <> map T.unpack (tsCustomCabalArgs targetSpec) (exitCode, out, err) <- liftIO $ readProcessWithExitCode "cabal" cabalArgs [] let output = T.pack $ unlines [ "Calling cabal install returned:" , "ExitCode:", show exitCode, "StdOut:", out, "StdErr:", err] report output -- logExists <- liftIO $ doesFileExist logLocation -- TODO: do we need the log if we have the LocalBuildInfo? {- cabalLog <- if logExists then lift . lift $ readFile logLocation else do report $ "The log file was not found (but should have been) at " <> T.pack logLocation return "" -} guard (exitCode == ExitSuccess) -- FIXME: this is failing because the sandbox puts things in a different path -- localBuildInfos <- liftIO $ mapM (\targetSourcePath -> getPersistBuildConfig (targetSourcePath </> "dist")) targetSourcePaths componentPass $ BuildReport buildSpec [] -- localBuildInfos -- | Given a directive of what to build and the location of the target package, -- call /cabal install/ haddock :: Scoutess (BuildSpec, [SourceInfo], LocalHackageIndex, Locations) () haddock = withComponent "haddock-standalone" $ \(buildSpec, targetSourceInfos, _, locations) -> do let targetSpec = bsTargetSpec buildSpec sandboxDir = lPackageDB locations installDir = sandboxDir configFile = tsTmpDir targetSpec </> "config" -- logLocation = tsTmpDir targetSpec </> "cabal-sandbox" </> "logs" </> "build.log" targetSourcePaths = map siPath targetSourceInfos {- mTargetCabals <- liftIO $ mapM findCabalFile targetSourcePaths when (isNothing mTargetCabal) $ do report $ "Couldn't find the target's cabal file in: " <> T.pack targetSourcePath mzero let targetCabal = fromJust mTargetCabal configExists <- liftIO $ doesFileExist configFile when configExists (liftIO $ removeFile configFile) -} liftIO . writeFile configFile $ unlines [ "local-repo: " <> hackageDir (lLocalHackage locations) ] -- , "build-summary: " <> logLocation ] let args = [ "--package-db=" <> "_scoutess-build/cabal-sandbox/x86_64-linux-ghc-7.6.3-packages.conf.d" , "-o", "doc-html" ] ++ targetSourcePaths {- ["--config-file=" <> configFile ,"install" ,targetCabal ,"--package-db=clear" ,"--package-db=global" -- THIS IS TEMPORARY TOO: <http://hackage.haskell.org/trac/ghc/ticket/5977> ,"--package-db=" <> sandboxDir ,"--prefix=" <> installDir ] <> map T.unpack (tsCustomCabalArgs targetSpec) -} report $ mconcat $ map T.pack ("standalone-standalone":args) (exitCode, out, err) <- liftIO $ readProcessWithExitCode "standalone-haddock" args [] let output = T.pack $ unlines [ "Calling standalone-haddock returned:" , "ExitCode:", show exitCode, "StdOut:", out, "StdErr:", err] report output {- logExists <- liftIO $ doesFileExist logLocation -- TODO: do we need the log if we have the LocalBuildInfo? cabalLog <- if logExists then lift . lift $ readFile logLocation else do report $ "The log file was not found (but should have been) at " <> T.pack logLocation return "" guard (exitCode == ExitSuccess) -} -- localBuildInfos <- liftIO $ mapM (\targetSourcePath -> getPersistBuildConfig (targetSourcePath </> "dist")) targetSourcePaths componentPass ()
cartazio/scoutess
Scoutess/DataFlow.hs
bsd-3-clause
14,517
1
18
3,604
2,416
1,274
1,142
176
3
module Client255.Printer ( printTweet ) where import qualified Data.Text.IO as T import Client255.Type printTweet :: Tweet -> IO () printTweet t = do T.putStr $ (screenName . user) t putStr $ " [" ++ (show . tweetId) t ++ "] " T.putStrLn $ text t
c000/twitter-client255
Client255/Printer.hs
bsd-3-clause
269
0
11
67
103
54
49
9
1
module Scheme.Evaluator.Micro ( module Scheme.Evaluator.Eval, microGEnv, evalCar, evalCdr, evalCons, evalPair, evalSet, evalSetCar, evalSetCdr, evalEq, evalApply, evalQuote, evalIf, evalLambda, evalDef, evalY, evalDefMacro, ) where import Scheme.Evaluator.Eval import Scheme.DataType.Error.Eval import Scheme.LISP as L import qualified Data.Map as M -- for debug import Debug.Trace -------------------------------------------------- -- GEnv -------------------------------------------------- microGEnv :: GEnv microGEnv = M.fromList [ ("#t", true) , ("#f", false) , ("car", RFUNC "car" evalCar) , ("cdr", RFUNC "cdr" evalCdr) , ("cons", WAFUNC "cons" evalCons) , ("list?", WAFUNC "list?" evalList) , ("pair?", WAFUNC "pair?" evalPair) , ("eq?", AFUNC "eq?" evalEq) , ("set!", SYNT "set!" evalSet) , ("set-car!", SYNT "set-car!" evalSetCar) , ("set-cdr!", SYNT "set-cdr!" evalSetCdr) , ("apply", SYNT "apply" evalApply) , ("quote", SYNT "quote" evalQuote) , ("if", SYNT "if" evalIf) , ("define", SYNT "define" evalDef) , ("let", SYNT "let" evalLet) , ("define-macro", SYNT "define-macro" evalDefMacro) , ("lambda", SYNT "lambda" evalLambda) , ("lambda-macro", SYNT "lambda-macro" evalLambdaMacro) -- macro , ("quasiquote", SYNT "quasiquote" evalQuasiQuote) , ("unquote", SYNT "unquote" evalUnQuote) , ("unquote-splicing", SYNT "unquote-splicing" evalUnQuoteSplicing) -- combinator , ("Y", SYNT "Y" evalY) -- Y-combinator , ("P", SYNT "P" evalP) -- P-combinator , ("Q", SYNT "Q" evalQ) -- Q-combinator ] ---------------------------------------------------------------------------------------------------------------- -- Quasi-Quote ---------------------------------------------------------------------------------------------------------------- -- quasiquote evalQuasiQuote :: Synt evalQuasiQuote (CELL macro NIL _) = do code <- compileQQ macro (*:) $ RETURN code where compileQQ :: Expr -> Scm Expr compileQQ c@(CELL (SYM "unquote" _) x msp) = localMSP msp $ do case x of CELL expr NIL _ -> weekactual expr e -> throwEvalError $ INVALIDForm $ show c compileQQ c@(CELL (CELL (SYM "unquote-splicing" _) x msp) d msp') = localMSP msp $ do case x of CELL expr NIL _ -> do a <- weekactual expr d <- localMSP msp' $ compileQQ d if L.isNil d then (*:) a else if L.isList a && L.isCell d then (*:) $ L.append a d else throwEvalError $ INVALIDForm $ show c e -> throwEvalError $ INVALIDForm $ show (cell (sym "unquote-splicing") e) compileQQ c@(CELL (SYM "unquote-splicing" _) x msp) = localMSP msp $ throwEvalError $ INVALIDForm $ show c compileQQ c@(CELL (SYM "quasiquote" _) x msp) = localMSP msp $ x >- (evalQuasiQuote >=> catchVoid) -- (*:) c compileQQ c@(CELL a d msp) = localMSP msp $ CELL |$> compileQQ a |*> compileQQ d |* msp compileQQ e = (*:) e evalQuasiQuote e = throwEvalError $ INVALIDForm $ show e -- unquote evalUnQuote :: Synt evalUnQuote (CELL _ _ _) = throwEvalError $ strMsg "unquote appeared outside quasiquote" evalUnQuote e = throwEvalError $ INVALIDForm $ show e -- quasiquote evalUnQuoteSplicing :: Synt evalUnQuoteSplicing (CELL _ _ _) = throwEvalError $ strMsg "unquote-splicing appeared outside quasiquote" evalUnQuoteSplicing e = throwEvalError $ INVALIDForm $ show e ---------------------------------------------------------------------------------------------------------------- -- Reference Function ---------------------------------------------------------------------------------------------------------------- evalCar :: RFunc evalCar (CELL (CELL a _ _) NIL _) = (*:) a evalCar (CELL r@(REF _) NIL msp) = do x <- r >- unREF case x of CELL a@(REF _) _ _ -> (*:) a CELL a d msp -> do ref <- newVarRef (Ve a) let v = REF ref writeREF r (CELL v d msp) (*:) v _     -> evalCar (CELL x NIL msp) evalCar c@(CELL _ NIL _) = throwEvalError $ WRONGTypeArg $ show (cell (sym "car") c) evalCar c@(CELL _ _ _) = throwEvalError $ WRONGNumArgs $ show (cell (sym "car") c) evalCar e = throwEvalError $ INVALIDForm $ show (cell (sym "car") e) evalCdr :: RFunc evalCdr (CELL (CELL _ d _) NIL _) = (*:) d evalCdr (CELL r@(REF _) NIL msp) = do x <- r >- unREF case x of CELL _ d@(REF _) _  -> (*:) d CELL a d msp -> do ref <- newVarRef (Ve d) let v = REF ref writeREF r (CELL a v msp) (*:) v _     -> evalCdr (CELL x NIL msp) evalCdr c@(CELL _ NIL _) = throwEvalError $ WRONGTypeArg $ show (cell (sym "cdr") c) evalCdr c@(CELL _ _ _) = throwEvalError $ WRONGNumArgs $ show (cell (sym "cdr") c) evalCdr e = throwEvalError $ INVALIDForm $ show (cell (sym "cdr") e) evalCons :: WAFunc evalCons (CELL a (CELL x NIL _) _) = (*:) $ CELL a x Nothing evalCons c@(CELL a NIL _) = throwEvalError $ WRONGNumArgs $ show (cell (sym "cons") c) evalCons c@(CELL a (CELL x _ _) _) = throwEvalError $ WRONGNumArgs $ show (cell (sym "cons") c) evalCons c@(CELL _ _ _) = throwEvalError $ WRONGTypeArg $ show (cell (sym "cons") c) evalCons e = throwEvalError $ INVALIDForm $ show (cell (sym "cons") e) -- -- Set: These functions work well only on lazy evaluation. -- -- set! evalSet :: Synt evalSet (CELL x (CELL v NIL _) _) = do x <- x >- reference v <- v >- actual case x of r@(REF _) -> writeREF x v _ -> (*:) () (*:) VOID evalSet e = throwEvalError $ INVALIDForm $ show (cell (sym "set") e) -- set-car! evalSetCar :: Synt evalSetCar (CELL x e@(CELL _ NIL _) msp) = evalSet (CELL (cell (sym "car") (cell x nil)) e msp) evalSetCar e = throwEvalError $ INVALIDForm $ show (cell (sym "set-car!") e) -- set-cdr! evalSetCdr :: Synt evalSetCdr (CELL x e@(CELL _ NIL _) msp) = evalSet (CELL (cell (sym "cdr") (cell x nil)) e msp) evalSetCdr e = throwEvalError $ INVALIDForm $ show (cell (sym "set-cdr!") e) ---------------------------------------------------------------------------------------------------------------- -- Week Actual Function ---------------------------------------------------------------------------------------------------------------- -- list? evalList :: WAFunc evalList (CELL (CELL _ NIL _) NIL _) = (*:) true evalList (CELL _ NIL _) = (*:) false evalList e = throwEvalError $ INVALIDForm $ show (cell (sym "list?") e) -- pair? evalPair :: WAFunc evalPair (CELL (CELL _ _ _) NIL _) = (*:) true evalPair (CELL _ _ _) = (*:) false evalPair e = throwEvalError $ INVALIDForm $ show (cell (sym "pair?") e) ---------------------------------------------------------------------------------------------------------------- -- Actual Function ---------------------------------------------------------------------------------------------------------------- -- eq? evalEq :: AFunc evalEq (CELL x (CELL y NIL _) _) | x == y = (*:) true | otherwise = (*:) false evalEq e = throwEvalError $ INVALIDForm $ show (cell (sym "eq?") e) ---------------------------------------------------------------------------------------------------------------- -- Syntax ---------------------------------------------------------------------------------------------------------------- -- apply evalApply :: Synt evalApply (CELL func args@(CELL _ _ _) _) = do func' <- actual func args' <- L.mapM actual args eagerApply func' (unCELL args') where unCELL :: Expr -> Expr unCELL (CELL x NIL _) = x unCELL (CELL x xs msp) = CELL x (unCELL xs) msp unCELL e = e evalApply e = throwEvalError $ INVALIDForm $ show (cell (sym "apply") e) -- quote evalQuote :: Synt evalQuote (CELL expr NIL _) = (*:) $ RETURN expr evalQuote e = throwEvalError $ INVALIDForm $ show (cell (sym "quote") e) -- if evalIf :: Synt evalIf (CELL pred (CELL thenForm rest _) _) = do v <- actual pred -- must be actual if v /= false -- (v == true) shall fail. then thenForm >- (force >=> thisEval) else case rest of CELL elseForm _ _ -> elseForm >- (force >=> thisEval) _ -> (*:) $ RETURN false evalIf e = throwEvalError $ INVALIDForm $ show (cell (sym "If") e) -- define evalDef :: Synt -- (define <name> <value>) or -- (define <func-name> (lambda (<formal-parameters>) <body>)) evalDef (CELL s@(SYM name _) (CELL expr NIL _) _) = ((*:) $ RETURN s) << do mlenv <- askMLEnv case mlenv of Nothing -> do mv <- lookupGEnv name case mv of Nothing -> do v <- thisEval expr >>= catchVoid pushGEnv name v Just _ -> throwEvalError $ MULTDecl name Just lenv -> do v <- thisEval expr >>= catchVoid pushLEnv name v lenv -- (define (<func-name> <formal-parameters>) <body>) evalDef (CELL (CELL s@(SYM _ _) args _) body msp) = do let expr = CELL (SYM "lambda" Nothing) (CELL args body Nothing) Nothing evalDef (CELL s (CELL expr NIL Nothing) msp) evalDef e = throwEvalError $ INVALIDForm $ show (cell (sym "define") e) -- let evalLet :: Synt evalLet c@(CELL pairs seq msp) = do (parms, args) <- L.foldrM toTuple (NIL, NIL) pairs thisEval $ CELL (CELL (SYM "lambda" Nothing) (CELL parms seq Nothing) Nothing) args msp where toTuple (CELL parm@(SYM name _) (CELL arg NIL _) _) (params, args) = (*:) (cell parm params, cell arg args) toTuple e _ = throwEvalError $ strMsg $ "invalid let form: expected symbol-and-expression pair, but detected "++ show e evalLet e = throwEvalError $ INVALIDForm $ show (cell (sym "let") e) -- define-macro evalDefMacro :: Synt evalDefMacro (CELL s@(SYM name _) (CELL l@(CELL lsym@(SYM "lambda" sp') lbody sp) NIL _) _) = ((*:) $ RETURN s) << do mv <- lookupGEnv name case mv of Nothing -> do let l' = CELL (sym "lambda-macro") lbody sp v <- thisEval l' >>= catchVoid pushGEnv name v Just _ -> throwEvalError $ MULTDecl name evalDefMacro e = throwEvalError $ INVALIDForm $ show (cell (sym "define-macro") e) -- lambda evalLambda :: Synt evalLambda e = do mlenv <- askMLEnv (*:) $ RETURN $ CLOS e mlenv -- lambda-macro evalLambdaMacro :: Synt evalLambdaMacro e = do mlenv <- askMLEnv (*:) $ RETURN $ CLOSM e mlenv -- Y: Y-combinator; for recursion evalY :: Synt evalY (CELL x NIL _) = thisEval $ cell y (cell x nil) where -- (lambda (g) -- ((lambda (s) (g (lambda x (apply (s s) x)))) -- (lambda (s) (g (lambda x (apply (s s) x))))))) y = (CELL (SYM "lambda" Nothing) (CELL (CELL (SYM "g" Nothing) NIL Nothing) (CELL (CELL (CELL (SYM "lambda" Nothing) (CELL (CELL (SYM "s" Nothing) NIL Nothing) (CELL (CELL (SYM "g" Nothing) (CELL (CELL (SYM "lambda" Nothing) (CELL (SYM "x" Nothing) (CELL (CELL (SYM "apply" Nothing) (CELL (CELL (SYM "s" Nothing) (CELL (SYM "s" Nothing) NIL Nothing) Nothing) (CELL (SYM "x" Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) NIL Nothing) Nothing) Nothing) (CELL (CELL (SYM "lambda" Nothing) (CELL (CELL (SYM "s" Nothing) NIL Nothing) (CELL (CELL (SYM "g" Nothing) (CELL (CELL (SYM "lambda" Nothing) (CELL (SYM "x" Nothing) (CELL (CELL (SYM "apply" Nothing) (CELL (CELL (SYM "s" Nothing) (CELL (SYM "s" Nothing) NIL Nothing) Nothing) (CELL (SYM "x" Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) NIL Nothing) Nothing) Nothing) evalY e = throwEvalError $ INVALIDForm $ show (cell (sym "Y") e) -- P: P-combinator; for mutual recursion evalP :: Synt evalP (CELL e1 (CELL e2 NIL _) _) = thisEval $ cell p (cell e1 (cell e2 nil)) where -- (lambda (g h) -- ((lambda (s t) -- (s s t)) -- (lambda (s t) -- (g (lambda x (apply (s s t) x)) -- (lambda x (apply (t s t) x)))) -- (lambda (s t) -- (h (lambda x (apply (s s t) x)) -- (lambda x (apply (t s t) x)))))) p = (CELL (SYM "lambda" Nothing) (CELL (CELL (SYM "g" Nothing) (CELL (SYM "h" Nothing) NIL Nothing) Nothing) (CELL (CELL (CELL (SYM "lambda" Nothing) (CELL (CELL (SYM "s" Nothing) (CELL (SYM "t" Nothing) NIL Nothing) Nothing) (CELL (CELL (SYM "s" Nothing) (CELL (SYM "s" Nothing) (CELL (SYM "t" Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) (CELL (CELL (SYM "lambda" Nothing) (CELL (CELL (SYM "s" Nothing) (CELL (SYM "t" Nothing) NIL Nothing) Nothing) (CELL (CELL (SYM "g" Nothing) (CELL (CELL (SYM "lambda" Nothing) (CELL (SYM "x" Nothing) (CELL (CELL (SYM "apply" Nothing) (CELL (CELL (SYM "s" Nothing) (CELL (SYM "s" Nothing) (CELL (SYM "t" Nothing) NIL Nothing) Nothing) Nothing) (CELL (SYM "x" Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) (CELL (CELL (SYM "lambda" Nothing) (CELL (SYM "x" Nothing) (CELL (CELL (SYM "apply" Nothing) (CELL (CELL (SYM "t" Nothing) (CELL (SYM "s" Nothing) (CELL (SYM "t" Nothing) NIL Nothing) Nothing) Nothing) (CELL (SYM "x" Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) (CELL (CELL (SYM "lambda" Nothing) (CELL (CELL (SYM "s" Nothing) (CELL (SYM "t" Nothing) NIL Nothing) Nothing) (CELL (CELL (SYM "h" Nothing) (CELL (CELL (SYM "lambda" Nothing) (CELL (SYM "x" Nothing) (CELL (CELL (SYM "apply" Nothing) (CELL (CELL (SYM "s" Nothing) (CELL (SYM "s" Nothing) (CELL (SYM "t" Nothing) NIL Nothing) Nothing) Nothing) (CELL (SYM "x" Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) (CELL (CELL (SYM "lambda" Nothing) (CELL (SYM "x" Nothing) (CELL (CELL (SYM "apply" Nothing) (CELL (CELL (SYM "t" Nothing) (CELL (SYM "s" Nothing) (CELL (SYM "t" Nothing) NIL Nothing) Nothing) Nothing) (CELL (SYM "x" Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) evalP e = throwEvalError $ INVALIDForm $ show (cell (sym "P") e) -- Q: Q-combinator; for mutual recursion evalQ :: Synt evalQ (CELL e1 (CELL e2 NIL _) _) = thisEval $ cell q (cell e1 (cell e2 nil)) where -- (lambda (g h) -- ((lambda (s t) -- (t s t)) -- (lambda (s t) -- (g (lambda x (apply (s s t) x)) -- (lambda x (apply (t s t) x)))) -- (lambda (s t) -- (h (lambda x (apply (s s t) x)) -- (lambda x (apply (t s t) x)))))) q = (CELL (SYM "lambda" Nothing) (CELL (CELL (SYM "g" Nothing) (CELL (SYM "h" Nothing) NIL Nothing) Nothing) (CELL (CELL (CELL (SYM "lambda" Nothing) (CELL (CELL (SYM "s" Nothing) (CELL (SYM "t" Nothing) NIL Nothing) Nothing) (CELL (CELL (SYM "t" Nothing) (CELL (SYM "s" Nothing) (CELL (SYM "t" Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) (CELL (CELL (SYM "lambda" Nothing) (CELL (CELL (SYM "s" Nothing) (CELL (SYM "t" Nothing) NIL Nothing) Nothing) (CELL (CELL (SYM "g" Nothing) (CELL (CELL (SYM "lambda" Nothing) (CELL (SYM "x" Nothing) (CELL (CELL (SYM "apply" Nothing) (CELL (CELL (SYM "s" Nothing) (CELL (SYM "s" Nothing) (CELL (SYM "t" Nothing) NIL Nothing) Nothing) Nothing) (CELL (SYM "x" Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) (CELL (CELL (SYM "lambda" Nothing) (CELL (SYM "x" Nothing) (CELL (CELL (SYM "apply" Nothing) (CELL (CELL (SYM "t" Nothing) (CELL (SYM "s" Nothing) (CELL (SYM "t" Nothing) NIL Nothing) Nothing) Nothing) (CELL (SYM "x" Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) (CELL (CELL (SYM "lambda" Nothing) (CELL (CELL (SYM "s" Nothing) (CELL (SYM "t" Nothing) NIL Nothing) Nothing) (CELL (CELL (SYM "h" Nothing) (CELL (CELL (SYM "lambda" Nothing) (CELL (SYM "x" Nothing) (CELL (CELL (SYM "apply" Nothing) (CELL (CELL (SYM "s" Nothing) (CELL (SYM "s" Nothing) (CELL (SYM "t" Nothing) NIL Nothing) Nothing) Nothing) (CELL (SYM "x" Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) (CELL (CELL (SYM "lambda" Nothing) (CELL (SYM "x" Nothing) (CELL (CELL (SYM "apply" Nothing) (CELL (CELL (SYM "t" Nothing) (CELL (SYM "s" Nothing) (CELL (SYM "t" Nothing) NIL Nothing) Nothing) Nothing) (CELL (SYM "x" Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) NIL Nothing) Nothing) Nothing) evalQ e = throwEvalError $ INVALIDForm $ show (cell (sym "Q") e)
ocean0yohsuke/Scheme
src/Scheme/Evaluator/Micro.hs
bsd-3-clause
25,277
0
48
12,106
6,666
3,390
3,276
319
10
{- Copyright (c) 2008 David Roundy All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} {-# OPTIONS_GHC -fomit-interface-pragmas #-} module Distribution.Franchise.VersionControl ( patchLevel, autoVersion, autoPatchVersion, autoDist, releaseDescription, releaseName ) where import Control.Monad ( when ) import Distribution.Franchise.ConfigureState import Distribution.Franchise.Util import Distribution.Franchise.Buildable ( simpleTarget, distclean ) import Distribution.Franchise.ReleaseType ( ReleaseType(..), releaseFile, releaseUnknown ) import Distribution.Franchise.Darcs ( inDarcs, darcsRelease, darcsPatchLevel, darcsDist ) import Distribution.Franchise.Git ( inGit, gitRelease, gitPatchLevel ) import Distribution.Franchise.GhcState ( version, getVersion ) data VC a = VC { darcs :: C a, git :: C a, none :: C a, panic :: a } inVC :: VC a -> C a inVC j = do ind <- inDarcs if ind then darcs j `catchC` \_ -> donone else do ing <- inGit if ing then git j `catchC` \_ -> donone else donone where donone = none j `catchC` \_ -> return $ panic j -- | Return the version name that would be set by 'autoVersion'. -- Useful if you want to use 'defineAs' to create the output of -- --version with a 'ReleaseType' that differs from how you have -- 'autoVersion' configured. releaseName :: ReleaseType -> C String releaseName t = withRootdir $ inVC $ VC (writeit darcsRelease) (writeit gitRelease) readV (releaseUnknown t) where readV = do x:_ <- words `fmap` cat (releaseFile t) return x writeit rel = do x <- rel t distclean [releaseFile t] writeF (releaseFile t) x return x patchLevel :: ReleaseType -> C Int patchLevel t = withRootdir $ inVC $ VC (writeit darcsPatchLevel) (writeit gitPatchLevel) readL (-1) where writeit rel = do x <- rel t distclean [releaseFile t++"PatchLevel"] writeF (releaseFile t++"PatchLevel") (show x) return x readL = do [(i,"")] <- reads `fmap` cat (releaseFile t++"PatchLevel") return i releaseTargets :: C () releaseTargets = inVC $ VC inv inv inn () where inv = do distclean [releaseFile Numbered, releaseFile NumberedPreRc, releaseFile AnyTag, releaseFile Numbered++"PatchLevel", releaseFile NumberedPreRc++"PatchLevel", releaseFile AnyTag++"PatchLevel"] simpleTarget (releaseFile Numbered) $ releaseName Numbered simpleTarget (releaseFile NumberedPreRc) $ releaseName NumberedPreRc simpleTarget (releaseFile AnyTag) $ releaseName AnyTag simpleTarget (releaseFile Numbered++"PatchLevel") $ patchLevel Numbered simpleTarget (releaseFile NumberedPreRc++"PatchLevel") $ patchLevel NumberedPreRc simpleTarget (releaseFile AnyTag++"PatchLevel") $ patchLevel AnyTag inn = do nobrainer $ releaseFile Numbered nobrainer $ releaseFile NumberedPreRc nobrainer $ releaseFile AnyTag nobrainer $ releaseFile Numbered ++ "PatchLevel" nobrainer $ releaseFile NumberedPreRc ++ "PatchLevel" nobrainer $ releaseFile AnyTag ++ "PatchLevel" nobrainer f = whenC (isFile f) $ simpleTarget f $ return () -- | Determine the version based on a reversion control system. -- Currently only @git@ and @darcs@ are supported. The 'ReleaseType' -- argument determines how the version is determined. autoVersion :: ReleaseType -> C String autoVersion t = do releaseTargets vers <- releaseName t oldversion <- getVersion when (oldversion /= vers) $ do version vers putS $ "version is now "++vers return vers -- | This is like 'autoVersion', but the number of patches since the -- latest release is then added to the version, so if there have been -- 10 patches since the 1.0.0 release, this would give a version of -- 1.0.0.10. autoPatchVersion :: ReleaseType -> C String autoPatchVersion t = do releaseTargets r <- releaseName t p <- patchLevel t let vers = if p == 0 || p == -1 then r else r++'.':show p oldversion <- getVersion when (oldversion /= vers) $ do version vers putS $ "version is now "++vers return vers -- | Return a user-friendly name of the release, similar to the output -- of 'autoPatchVersion', but with the number of patches since release -- written in English instead of as a number. Its use is similar to -- 'releaseName'. releaseDescription :: ReleaseType -> C String releaseDescription t = do r <- releaseName t l <- patchLevel t return $ case l of 0 -> r 1 -> r++" + one patch" _ -> r++" + "++show l++" patches" -- | Create a 'distribution tarball'. This currently only works in -- darcs repositories, but could be extended to also work under git or -- other revision control systems. The tarball directory is -- originally created as a repository, then the specified targets are -- built (e.g. this could be documentation that tarball users -- shouldn't have to build), and then the \"distclean\" target is -- built, which should remove anything that you don't want in the -- tarball (and automatically includes the \"clean\" target). autoDist :: String -- ^ base name of tarball (e.g. \"franchise\") -> [String] -- ^ list of targets to be built inside tarball -> C String -- ^ returns name of tarball. autoDist dn tocopy = withRootdir $ inVC $ VC (darcsDist dn tocopy) (fail "autoDist doesn't work in git.") (fail "autoDist requires version control.") (fail "autoDist requires darcs.")
droundy/franchise
Distribution/Franchise/VersionControl.hs
bsd-3-clause
8,251
0
14
2,770
1,330
667
663
105
3
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.EXT.GeometryShader4 -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.EXT.GeometryShader4 ( -- * Extension Support glGetEXTGeometryShader4, gl_EXT_geometry_shader4, -- * Enums pattern GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT, pattern GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT, pattern GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_EXT, pattern GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT, pattern GL_GEOMETRY_INPUT_TYPE_EXT, pattern GL_GEOMETRY_OUTPUT_TYPE_EXT, pattern GL_GEOMETRY_SHADER_EXT, pattern GL_GEOMETRY_VERTICES_OUT_EXT, pattern GL_LINES_ADJACENCY_EXT, pattern GL_LINE_STRIP_ADJACENCY_EXT, pattern GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT, pattern GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_EXT, pattern GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_EXT, pattern GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT, pattern GL_MAX_GEOMETRY_VARYING_COMPONENTS_EXT, pattern GL_MAX_VARYING_COMPONENTS_EXT, pattern GL_MAX_VERTEX_VARYING_COMPONENTS_EXT, pattern GL_PROGRAM_POINT_SIZE_EXT, pattern GL_TRIANGLES_ADJACENCY_EXT, pattern GL_TRIANGLE_STRIP_ADJACENCY_EXT, -- * Functions glProgramParameteriEXT ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
haskell-opengl/OpenGLRaw
src/Graphics/GL/EXT/GeometryShader4.hs
bsd-3-clause
1,595
0
5
177
152
100
52
28
0
{-# LANGUAGE GADTs #-} {-# LANGUAGE QuasiQuotes #-} module Test.BigOh.Fit.R where import Data.Ix import Data.Monoid import Data.Vector.SEXP import qualified Foreign.R as R import Language.R.HExp import Language.R.Instance as R import Language.R.QQ import Test.BigOh.Fit.Base import Test.BigOh.Plot data Order = Constant | LogN | Linear | NLogN | Quadratic | Cubic | Quartic deriving (Show, Eq, Ord, Bounded, Enum, Ix) knownOrders :: [Order] knownOrders = [minBound..maxBound] lm :: Order -> [Point] -> IO Double lm order points = let (xs, ys) = unzip points in R.runRegion $ do it <- lm' order xs ys R.unSomeSEXP it $ \it' -> case hexp it' of Real v -> headM v Int v -> fromIntegral <$> headM v _ -> error "R result isn't a number" lm' :: Order -> [Double] -> [Double] -> R s (R.SomeSEXP s) lm' order x y = do [r| x = x_hs |] [r| y = y_hs |] case order of Constant -> [r|summary(lm(y ~ 1))$adj.r.squared|] LogN -> [r|summary(lm(y ~ I(log(x))))$adj.r.squared|] NLogN -> [r|summary(lm(y ~ I(x * log(x))))$adj.r.squared|] Linear -> [r|summary(lm(y ~ I(x)))$adj.r.squared|] Quadratic -> [r|summary(lm(y ~ I(x^2) + I(x)))$adj.r.squared|] Cubic -> [r|summary(lm(y ~ I(x^3) + I(x^2) + I(x)))$adj.r.squared|] Quartic -> [r|summary(lm(y ~ I(x^4) + I(x^3) + I(x^2) + I(x)))$adj.r.squared|] pretty :: Order -> String pretty Constant = "1" pretty LogN = "log n" pretty Linear = "n" pretty NLogN = "n log n" pretty Quadratic = "n" <> superscript 2 pretty Cubic = "n" <> superscript 3 pretty Quartic = "n" <> superscript 4
tranma/big-oh
src/Test/BigOh/Fit/R.hs
bsd-3-clause
1,894
0
16
630
493
278
215
54
7
------------------------------------------------------------------------------- -- | -- Module : Generator.Printer.Util -- Copyright : (c) 2016 Michael Carpenter -- License : BSD3 -- Maintainer : Michael Carpenter <oldmanmike.dev@gmail.com> -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------- module Generator.Printer.Util ( docFieldNames , docFieldTypes , docDataTypeName ) where import qualified Data.Text.Lazy as TL import Generator.Printer.Types import Generator.Types import Text.PrettyPrint.Leijen.Text docFieldNames :: Maybe [Field] -> Doc docFieldNames maybeFields = case maybeFields of Just fields -> hsep (fmap (text . fieldName) fields) Nothing -> empty docFieldTypes :: Maybe [Field] -> Doc docFieldTypes maybeFields = case maybeFields of Just fields -> hsep (fmap (docFieldType . fieldType) fields) Nothing -> empty docDataTypeName :: PacketDirection -> ProtocolState -> Doc docDataTypeName d s = string (TL.pack (show d ++ show s ++ "Packet"))
oldmanmike/hs-minecraft-protocol
generate/src/Generator/Printer/Util.hs
bsd-3-clause
1,150
0
12
230
226
126
100
20
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} module Web.Trello where import qualified Data.Text as T import Data.Aeson import GHC.Generics import Servant import Web.Trello.Card import Control.Monad.Trans.Either import Servant.Client type Key = T.Text type AuthToken = T.Text type AuthParams a = QueryParam "key" Key :> QueryParam "token" AuthToken :> a type TrelloAPI = "1" :> "cards" :> ReqBody '[JSON] NewCard :> AuthParams (Post '[JSON] Card) data Position = Top | Bottom | Int deriving (Show) -- in Google Translate, he implements Show and ToText instead, then toJSON = String . toText instance ToJSON Position where toJSON position = case position of Top -> toJSON ("top" :: T.Text) Bottom -> toJSON ("bottom" :: T.Text) n -> toJSON n data NewCard = NewCard { name :: T.Text -- optional when copying, added anyway , desc :: Maybe T.Text -- length 0-16384 , pos :: Maybe Position , due :: Maybe T.Text -- TODO replace with an api-compliant date type , idList :: T.Text -- id of list being added to , idMembers :: Maybe T.Text , idLabels :: Maybe T.Text , urlSource :: Maybe T.Text -- http://, https:// or null , fileSource :: Maybe T.Text , idCardSource :: Maybe T.Text , keepFromSource :: Maybe T.Text } deriving (Show, Generic) instance ToJSON NewCard trelloAPI :: Proxy TrelloAPI trelloAPI = Proxy createCard :: NewCard -> Maybe Key -> Maybe AuthToken -> EitherT ServantError IO Card createCard = client trelloAPI (BaseUrl Https "api.trello.com" 443)
nicklawls/lessons
src/Web/Trello.hs
bsd-3-clause
1,815
0
12
498
427
239
188
49
1
{-# LANGUAGE TemplateHaskell #-} module Main where import Test.Framework.TH (defaultMainGenerator) import Test.HUnit import Test.Framework.Providers.HUnit (testCase) import Test.QuickCheck import Test.Framework.Providers.QuickCheck2 (testProperty) import qualified Data.List as List import Euler.Problem12 (firstTriangleNumberOverNDivisors, triangleNumbers, numDivisors, hasNumDivisorsGreaterThan, hasProductGreaterThan, countDuplicates) main = $(defaultMainGenerator) case_over_5_divisors = firstTriangleNumberOverNDivisors 5 @?= 28 case_seventh_triangle_number = triangleNumbers !! (7 - 1) @?= 28 {- Make sure the triangle numbers are as they are defined. -} prop_triangle_numbers (Positive n) = triangleNumbers !! (fromInteger n - 1) == sum [1..n] --- numDivisors -- 1: 1 case_numDivisors_1 = numDivisors 1 @?= 1 -- 3: 1,3 case_numDivisors_3 = numDivisors 3 @?= 2 -- 6: 1,2,3,6 case_numDivisors_6 = numDivisors 6 @?= 4 -- 10: 1,2,5,10 case_numDivisors_10 = numDivisors 10 @?= 4 -- 28: 1,2,4,7,14,28 case_numDivisors_28 = numDivisors 28 @?= 6 {- Check our optimized implementation. -} prop_countDuplicates = forAll (listOf $ choose (1 :: Int, 3)) $ \xs -> countDuplicates xs == [toInteger $ length ys | ys <- List.group xs] prop_numDivisors_optimization (Positive n) (Positive t) = t `hasNumDivisorsGreaterThan` n == (numDivisors t > n) prop_productGreaterThan_optimization (Positive n) = forAll (listOf $ arbitrary `suchThat` (> (0 :: Integer))) $ \xs -> xs `hasProductGreaterThan` n == (product xs > n)
FranklinChen/project-euler-haskell
Test/Test12.hs
bsd-3-clause
1,680
0
12
365
409
230
179
41
1
module Astro.Orbit.Interpolate where import qualified Prelude import Control.Applicative import Numeric.Units.Dimensional.Prelude import Numeric.Units.Dimensional.LinearAlgebra import Astro.Orbit.Types import Astro.Time import Astro.Time.At import Astro.Util.Cyclic import Astro.Orbit.MEOE import Astro.Trajectory (Datum) -- dimensional (TODO: move?) -- ------------------------- -- Interpolate. linearPolate :: Fractional a => (Quantity d a, Quantity dy a) -> (Quantity d a, Quantity dy a) -> Quantity d a -> Quantity dy a linearPolate (x0,y0) (x1,y1) x = linearPolate0 y0 (x1-x0,y1) (x-x0) -- Polate assuming y0 corresponds to x0 = 0. linearPolate0 :: Fractional a => Quantity dy a -> (Quantity d a, Quantity dy a) -> Quantity d a -> Quantity dy a --linearPolate0 y0 (x1,y1) x = y0 + x / x1 * (y1 - y0) linearPolate0 y0 (x1,y1) x = y0 + linearPolate00 (x1,y1-y0) x -- Polate assuming x0 = 0 and y0 = 0. linearPolate00 :: Fractional a => (Quantity d a, Quantity dy a) -> Quantity d a -> Quantity dy a -- linearPolate00 (_ , _ ) _0 = _0 -- TODO good to have in case x1 is zero (degenerate)? -- linearPolate00 (_0, _ ) _ = error "Degenerate polation" -- TODO good to have in case x1 is zero (degenerate)? linearPolate00 (x1, y1) x = x / x1 * y1 -- dimensional-vectors (TODO: move?) -- --------------------------------- -- Interpolate vector. linearPolateVec :: Fractional a -- (Div d d DOne, Fractional a) => (Quantity d a, Vec ds n a) -> (Quantity d a, Vec ds n a) -> Quantity d a -> Vec ds n a linearPolateVec (x0,v0) (x1,v1) x = linearPolateVec0 v0 (x1-x0,v1) (x-x0) -- Polate assuming v0 corresponds to x0 = 0. linearPolateVec0 :: Fractional a -- (Div d d DOne, Fractional a) => Vec ds n a -> (Quantity d a, Vec ds n a) -> Quantity d a -> Vec ds n a --linearPolateVec0 v0 (x1,v1) x = v0 >+< scaleVec1 (x / x1) (v1 >-< v0) linearPolateVec0 v0 (x1,v1) x = v0 >+< linearPolateVec00 (x1, v1 >-< v0) x -- Polate assuming x0 = 0 and v0 = {0}. linearPolateVec00 :: Fractional a -- (Div d d DOne, Fractional a) => (Quantity d a, Vec ds n a) -> Quantity d a -> Vec ds n a linearPolateVec00 (x1,v1) x = scaleVec (x / x1) v1 -- Depend on astro -- --------------- -- | Interpolate or extrapolate linearly. linearPolateT :: Fractional a -- (Mul DOne d d, Fractional a) => At t a (Quantity d a) -> At t a (Quantity d a) -> E t a -> Quantity d a linearPolateT (x0`At`t0) (x1`At`t1) t = linearPolate0 x0 (d t1,x1) (d t) where d = (`diffEpoch` t0) -- Interpolate vector as function of time. linearPolateVecT :: Fractional a => At t a (Vec ds n a) -> At t a (Vec ds n a) -> E t a -> Vec ds n a linearPolateVecT (v0`At`t0) (v1`At`t1) t = linearPolateVec0 v0 (d t1,v1) (d t) where d = (`diffEpoch` t0) -- ================================================================== -- | Interpolate two MEOEs with mean anomaly. In interpolating mean -- anomaly the orbital period is taken into account to ensure proper -- interpolation. -- NOTE: this does not work for hyperbolic orbits, and probably not -- when t1 and t0 are separated by more than one (or a half?) orbital -- period? linearPolateMEOEm :: RealFloat a => Datum t a -> Datum t a -> E t a -> MEOE Mean a linearPolateMEOEm m0 m1 t = MEOE (linearPolateT (mu <$> m0) (mu <$> m1') t) (linearPolateT (p <$> m0) (p <$> m1') t) (linearPolateT (f <$> m0) (f <$> m1') t) (linearPolateT (g <$> m0) (g <$> m1') t) (linearPolateT (h <$> m0) (h <$> m1') t) (linearPolateT (k <$> m0) (k <$> m1') t) (Long $ linearPolateT (long . longitude <$> m0) (long . longitude <$> m1') t) where m1' = (\m -> m { longitude = Long l1' }) <$> m1 l0 = long . longitude <$> m0 l1 = long . longitude <$> m1 l1' = adjustCyclicT l0 l1 period tau period = (meoeOrbitalPeriod (value m0) + meoeOrbitalPeriod (value m1)) / _2
bjornbm/astro
src/Astro/Orbit/Interpolate.hs
bsd-3-clause
4,044
0
12
995
1,289
689
600
59
1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.KHR.TextureCompressionASTCLDR -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/KHR/texture_compression_astc_ldr.txt KHR_texture_compression_astc_ldr> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.KHR.TextureCompressionASTCLDR ( -- * Enums gl_COMPRESSED_RGBA_ASTC_10x10_KHR, gl_COMPRESSED_RGBA_ASTC_10x5_KHR, gl_COMPRESSED_RGBA_ASTC_10x6_KHR, gl_COMPRESSED_RGBA_ASTC_10x8_KHR, gl_COMPRESSED_RGBA_ASTC_12x10_KHR, gl_COMPRESSED_RGBA_ASTC_12x12_KHR, gl_COMPRESSED_RGBA_ASTC_4x4_KHR, gl_COMPRESSED_RGBA_ASTC_5x4_KHR, gl_COMPRESSED_RGBA_ASTC_5x5_KHR, gl_COMPRESSED_RGBA_ASTC_6x5_KHR, gl_COMPRESSED_RGBA_ASTC_6x6_KHR, gl_COMPRESSED_RGBA_ASTC_8x5_KHR, gl_COMPRESSED_RGBA_ASTC_8x6_KHR, gl_COMPRESSED_RGBA_ASTC_8x8_KHR, gl_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR, gl_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR, gl_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR, gl_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR, gl_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR, gl_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR, gl_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR, gl_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR, gl_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR, gl_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR, gl_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR, gl_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR, gl_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR, gl_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR ) where import Graphics.Rendering.OpenGL.Raw.Tokens
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/KHR/TextureCompressionASTCLDR.hs
bsd-3-clause
1,791
0
4
159
118
85
33
30
0
{-# LANGUAGE CPP #-} module Distribution.Compat.Filesystem.Portable (pathCoerceToDirectory, pathCoerceToFile, pathIsAbsolute, pathIsRelative, pathIsDirectory, pathIsFile, (</>)) where #ifdef VERSION_unix import {-# SOURCE #-} Distribution.Compat.Filesystem.Posix #else import Distribution.Compat.Filesystem.Windows #endif pathCoerceToDirectory :: FilePath -> FilePath pathCoerceToDirectory "" = ['.', pathSeparator] pathCoerceToDirectory path = if elem (last path) pathSeparators then path else path ++ [pathSeparator] pathCoerceToFile :: FilePath -> FilePath pathCoerceToFile "" = "." pathCoerceToFile path = if pathIsDirectory path then init path else path pathIsAbsolute :: FilePath -> Bool pathIsAbsolute "" = False pathIsAbsolute (c:_) = elem c pathSeparators pathIsRelative :: FilePath -> Bool pathIsRelative = not . pathIsAbsolute pathIsDirectory :: FilePath -> Bool pathIsDirectory "" = True pathIsDirectory path = elem (last path) pathSeparators pathIsFile :: FilePath -> Bool pathIsFile = not . pathIsDirectory (</>) :: FilePath -> FilePath -> FilePath parent </> child = if pathIsRelative child then pathCoerceToDirectory parent ++ child else child
IreneKnapp/Faction
libfaction/Distribution/Compat/Filesystem/Portable.hs
bsd-3-clause
1,227
0
8
208
294
164
130
37
2
{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-} module WSC.Main where import Control.Monad.Error import Control.Monad.State import System.Console.CmdArgs.Implicit import System.Exit import Text.Groom import Text.Printf import WSC.AST as AST import WSC.Arity import WSC.Driver import WSC.Parser (parseFile) data WSCFlags = WSCFlags { printAst :: Bool , printSymTable :: Bool , file :: FilePath , outfile :: FilePath } deriving (Eq, Show, Data, Typeable) flags = WSCFlags { printAst = False &= name "print-ast" &= help "Print the AST." , printSymTable = False &= name "print-symtable" &= help "Print the symbol table." , file = def &= args &= typFile , outfile = def &= typFile &= help "Destination of output file." } &= program "wsc" &= summary "Winchester STG Compiler v0.0, (c) Dylan Lukes 2012" driver :: WSCDriver String AST.Prog ExitCode driver = let run = do args <- io $ cmdArgs flags parseFile (file args) when (printAst args) $ get >>= (\x -> io (putStrLn . groom $ x)) -- resolveArities return ExitSuccess in catchError run $ \e -> do io $ print e return (ExitFailure (-1)) main = do -- this undefined will be promptly replaced by `put' r <- evalStateT (runErrorT (runWSCDriver driver)) undefined case r of Left err -> do printf "Unhandled error in driver: %s" (show err) exitFailure Right ec -> exitWith ec
DylanLukes/Winchester-STG-Compiler
WSC/Main.hs
bsd-3-clause
1,523
0
17
402
431
224
207
55
2
{-| CRUD functionality for 'Document's. -} module Database.OrgMode.Internal.Query.Document where import Database.Esqueleto import qualified Database.Persist as P import Database.OrgMode.Internal.Import import Database.OrgMode.Internal.Types import qualified Database.OrgMode.Internal.Query.Heading as HeadingQ ------------------------------------------------------------------------------- -- * Creation {-| Creates a new document in the database with the given name and body text. -} add :: (MonadIO m) => Text -- ^ Name of the document -> Text -- ^ Body text -> ReaderT SqlBackend m (Key Document) -- ^ Key of the new document add name text = P.insert (Document name text) ------------------------------------------------------------------------------- -- * Retrieval {-| Retrieves a 'Document' with given ID from database. -} get :: (MonadIO m) => Key Document -> ReaderT SqlBackend m (Maybe Document) get = P.get {-| Retrieves all 'Document's from the database. ASC sorted by name. -} getAll :: (MonadIO m) => ReaderT SqlBackend m [Entity Document] getAll = P.selectList [] [P.Asc DocumentName] ------------------------------------------------------------------------------- -- * Deletion {-| Deletes all 'Documents's by given list of IDs. Deletes all 'Heading's of each document too, and the 'Heading's metadata too. See 'HeadingQ.deleteByDocuments' for more information. -} deleteByIds :: (MonadIO m) => [Key Document] -> ReaderT SqlBackend m () deleteByIds docIds = do HeadingQ.deleteByDocuments docIds delete $ from $ \(doc) -> do where_ $ in_ (doc ^. DocumentId) (valList docIds) return ()
rzetterberg/orgmode-sql
lib/Database/OrgMode/Internal/Query/Document.hs
bsd-3-clause
1,756
0
14
365
310
173
137
22
1
module Data.OrdPSQ.Tests ( tests ) where import Data.List (isInfixOf) import Test.Framework (Test) import Test.Framework.Providers.HUnit (testCase) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.HUnit (Assertion, assert) import Data.OrdPSQ.Internal import Data.PSQ.Class.Gen () import Data.PSQ.Tests.Util -------------------------------------------------------------------------------- -- Index of tests -------------------------------------------------------------------------------- tests :: [Test] tests = [ testCase "showElem" test_showElem , testCase "showLTree" test_showLTree , testCase "invalidLTree" test_invalidLTree , testCase "balanceErrors" test_balanceErrors , testProperty "toAscList" prop_toAscList ] -------------------------------------------------------------------------------- -- Tests the result of 'moduleError' for internal issues -------------------------------------------------------------------------------- assertModuleError :: String -> String -> a -> Assertion assertModuleError fun msg = assertErrorCall $ \e -> do assert $ fun `isInfixOf` e assert $ msg `isInfixOf` e -------------------------------------------------------------------------------- -- HUnit tests -------------------------------------------------------------------------------- test_showElem :: Assertion test_showElem = assert $ length (coverShowInstance (E 0 0 'A' :: Elem Int Int Char)) > 0 test_showLTree :: Assertion test_showLTree = do assert $ length (coverShowInstance t1) > 0 assert $ length (coverShowInstance t2) > 0 assert $ length (coverShowInstance t3) > 0 where t1, t2, t3 :: LTree Int Int Char t1 = Start t2 = LLoser 1 e Start 0 Start t3 = RLoser 1 e Start 0 Start e = E 0 0 'A' test_invalidLTree :: Assertion test_invalidLTree = do assertModuleError "left" "empty" (left (Start :: LTree Int Int Char)) assertModuleError "right" "empty" (right (Start :: LTree Int Int Char)) assertModuleError "maxKey" "empty" (maxKey (empty :: OrdPSQ Int Int Char)) test_balanceErrors :: Assertion test_balanceErrors = do assertModuleError "lsingleLeft" msg (lsingleLeft 0 0 'A' nil 0 nil) assertModuleError "rsingleLeft" msg (rsingleLeft 0 0 'A' nil 0 nil) assertModuleError "lsingleRight" msg (lsingleRight 0 0 'A' nil 0 nil) assertModuleError "rsingleRight" msg (rsingleRight 0 0 'A' nil 0 nil) assertModuleError "ldoubleLeft" msg (ldoubleLeft 0 0 'A' nil 0 nil) assertModuleError "rdoubleLeft" msg (rdoubleLeft 0 0 'A' nil 0 nil) assertModuleError "ldoubleRight" msg (ldoubleRight 0 0 'A' nil 0 nil) assertModuleError "rdoubleRight" msg (rdoubleRight 0 0 'A' nil 0 nil) where nil = Start :: LTree Int Int Char msg = "malformed" -------------------------------------------------------------------------------- -- QuickCheck properties -------------------------------------------------------------------------------- prop_toAscList :: OrdPSQ Int Int Char -> Bool prop_toAscList t = isUniqueSorted [k | (k, _, _) <- toAscList t] where isUniqueSorted (x : y : zs) = x < y && isUniqueSorted (y : zs) isUniqueSorted [_] = True isUniqueSorted [] = True
meiersi/psqueues-old
tests/Data/OrdPSQ/Tests.hs
bsd-3-clause
3,479
0
11
774
850
445
405
56
3
{-# LANGUAGE CPP #-} #if defined(__GLASGOW_HASKELL__) && (__GLASGOW_HASKELL__ >= 702) {-# LANGUAGE Trustworthy #-} #endif {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} -- These extensions are only for MTL stuff where it is required {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- | This module contains various helper functions and instances for -- using 'Iter's of different 'Monad's together in the same pipeline. -- For example, as-is the following code is illegal: -- -- @ --iter1 :: 'Iter' String IO Bool --iter1 = ... -- --iter2 :: 'Iter' String ('StateT' MyState IO) () --iter2 = do ... -- s <- iter1 -- ILLEGAL: iter1 is in wrong monad -- ... -- @ -- -- You can't invoke @iter1@ from within @iter2@ because the 'Iter' -- type is wrapped around a different 'Monad' in each case. However, -- the function 'liftI' exactly solves this problem: -- -- @ -- s <- liftI iter1 -- @ -- -- Conversely, you may be in a 'Monad' like @'Iter' String IO@ and -- need to invoke a computation that requires some other monad -- functionality, such as a reader. There are a number of -- iteratee-specific runner functions that help you run other -- 'MonadTrans' transformers inside the 'Iter' monad. These typically -- use the names of the runner functions in the mtl library, but with -- an @I@ appended--for instance 'runReaderTI', 'runStateTI', -- 'runWriterTI'. Here's a fuller example of adapting the inner -- 'Iter' 'Monad'. The example also illustrates that @'Iter' t m@ is -- member any mtl classes (such as 'MonadReader' and 'MonadState') -- that @m@ is. -- -- @ --iter1 :: Iter String ('ReaderT' MyState IO) Bool --iter1 = do -- s <- 'ask' -- liftIO $ ('putStrLn' ('show' s) >> return True) -- ``catch`` \('SomeException' _) -> return False -- --iter2 :: Iter String ('StateT' MyState IO) () --iter2 = do -- s <- 'get' -- ok <- 'liftI' $ 'runReaderTI' iter1 s -- if ok then return () else fail \"iter1 failed\" -- @ module Data.IterIO.Trans (-- * Adapters for Iters of mtl transformers liftI, liftIterIO , runContTI, runErrorTI, runListTI, runReaderTI , runRWSI, runRWSLI, runStateTI, runStateTLI , runWriterTI, runWriterTLI -- * Functions for building new monad adapters , adaptIter, adaptIterM -- * Iter-specific state monad transformer , IterStateT(..), runIterStateT , iget, igets, iput, imodify ) where import Control.Monad.Cont import Control.Monad.Error import Control.Monad.List import Control.Monad.Reader import Control.Monad.RWS.Strict import Control.Monad.State.Strict import Control.Monad.Writer.Strict import qualified Control.Monad.RWS.Lazy as Lazy import qualified Control.Monad.State.Lazy as Lazy import qualified Control.Monad.Writer.Lazy as Lazy import Data.IterIO.Iter -- -- IterStateT monad -- -- | @IterStateT@ is a variant of the 'StateT' monad transformer -- specifically designed for use inside 'Iter's. The 'IterStateT' -- Monad itself is the same as 'StateT'. However, the 'runIterStateT' -- function works differently from 'runStateT'--it returns an 'IterR' -- and the result state separately. The advantage of this approach is -- that you can still recover the state at the point of the excaption -- even after an 'IterFail' or 'InumFail' condition. newtype IterStateT s m a = IterStateT (s -> m (a, s)) instance (Monad m) => Monad (IterStateT s m) where return a = IterStateT $ \s -> return (a, s) (IterStateT mf) >>= k = IterStateT $ \s -> do (a, s') <- mf s let (IterStateT kf) = k a kf $! s' fail = IterStateT . const . fail instance MonadTrans (IterStateT s) where lift m = IterStateT $ \s -> m >>= \a -> return (a, s) instance (MonadIO m) => MonadIO (IterStateT s m) where liftIO = lift . liftIO -- | Runs an @'IterStateT' s m@ computation on some state @s@. -- Returns the result ('IterR') of the 'Iter' and the state of @s@ as -- a pair. Pulls residual input up to the enclosing 'Iter' monad (as -- with @'pullupResid'@ in "Data.IterIO.Inum"). runIterStateT :: (ChunkData t, Monad m) => Iter t (IterStateT s m) a -> s -> Iter t m (IterR t m a, s) runIterStateT i0 s0 = Iter $ adapt s0 . runIter i0 where adapt s (IterM (IterStateT f)) = IterM $ liftM (uncurry $ flip adapt) (f s) adapt s r = stepR' r (adapt s) $ Done (setResid r mempty, s) (getResid r) -- | Returns the state in an @'Iter' t ('IterStateT' s m)@ monad. -- Analogous to @'get'@ for a @'StateT' s m@ monad. iget :: (Monad m) => Iter t (IterStateT s m) s iget = lift $ IterStateT $ \s -> return (s, s) -- | Returns a particular field of the 'IterStateT' state, analogous -- to @'gets'@ for @'StateT'@. igets :: (Monad m) => (s -> a) -> Iter t (IterStateT s m) a igets f = liftM f iget -- | Sets the 'IterStateT' state. Analogous to @'put'@ for -- @'StateT'@. iput :: (Monad m) => s -> Iter t (IterStateT s m) () iput s = lift $ IterStateT $ \_ -> return ((), s) -- | Modifies the 'IterStateT' state. Analogous to @'modify'@ for -- @'StateT'@. imodify :: (Monad m) => (s -> s) -> Iter t (IterStateT s m) () imodify f = lift $ IterStateT $ \s -> return ((), f s) -- -- Adapter utility functions -- -- | Adapt an 'Iter' from one monad to another. This function is the -- lowest-level monad adapter function, upon which all of the other -- adapters are built. @adaptIter@ requires two functions as -- arguments. One adapts the result to a new type (if required). The -- second adapts monadic computations from one monad to the other. -- For example, 'liftI' could be implemented as: -- -- @ -- liftI :: ('MonadTrans' t, Monad m, Monad (t m), 'ChunkData' s) => -- 'Iter' s m a -> 'Iter' s (t m) a -- liftI = adaptIter 'id' (\\m -> 'lift' ('lift' m) >>= liftI) -- @ -- -- Here @'lift' ('lift' m)@ executes a computation @m@ of type @m -- ('Iter' s m a)@ from within the @'Iter' s (t m)@ monad. The -- result, of type @'Iter' s m a@, can then be fed back into -- @liftI@ recursively. -- -- Note that in general a computation adapters must invoke the outer -- adapter function recursively. @adaptIter@ is designed this way -- because the result adapter function may need to change. An example -- is 'runStateTI', which could be implemented as follows: -- -- > runStateTI :: (ChunkData t, Monad m) => -- > Iter t (StateT s m) a -> s -> Iter t m (a, s) -- > runStateTI iter s = adaptIter adaptResult adaptComputation iter -- > where adaptResult a = (a, s) -- > adaptComputation m = do (r', s') <- lift (runStateT m s) -- > runStateTI r' s' -- -- Here, after executing 'runStateT', the state may be modified. -- Thus, @adaptComputation@ invokes @runStateTI@ recursively with the -- modified state, @s'@, to ensure that subsequent 'IterM' -- computations will be run on the latest state, and that eventually -- @adaptResult@ will pair the result @a@ with the newest state. adaptIter :: (ChunkData t, Monad m1) => (a -> b) -- ^ How to adapt result values -> (m1 (Iter t m1 a) -> Iter t m2 b) -- ^ How to adapt computations -> Iter t m1 a -- ^ Input computation -> Iter t m2 b -- ^ Output computation adaptIter f mf i = Iter $ check . runIter i where check (IterM m) = runIter (mf $ liftM (Iter . runIterR) m) mempty check r = stepR' r check $ fmapR f r -- | Simplified adapter function to translate 'Iter' computations from -- one monad to another. This only works on monads @m@ for which -- running @m a@ returns a result of type @a@. For more complex -- scenarios (such as 'ListT' or 'StateT'), you need to use the more -- general 'adaptIter'. -- -- As an example, the 'liftIterIO' function is implemented as follows: -- -- @ -- liftIterIO :: (ChunkData t, 'MonadIO' m) => Iter t IO a -> Iter t m a -- liftIterIO = adaptIterM 'liftIO' -- @ adaptIterM :: (ChunkData t, Monad m1, Monad m2) => (m1 (Iter t m1 a) -> m2 (Iter t m1 a)) -- ^ Conversion function -> Iter t m1 a -- ^ 'Iter' of input monad -> Iter t m2 a -- ^ Returns 'Iter' of output monad adaptIterM f = adapt where adapt = adaptIter id $ lift . f >=> adapt -- | Run an @'Iter' s m@ computation from witin the @'Iter' s (t m)@ -- monad, where @t@ is a 'MonadTrans'. liftI :: (MonadTrans t, Monad m, Monad (t m), ChunkData s) => Iter s m a -> Iter s (t m) a liftI = adaptIterM lift -- | Run an @'Iter' t IO@ computation from within an @'Iter' t m@ -- monad where @m@ is in class 'MonadIO'. liftIterIO :: (ChunkData t, MonadIO m) => Iter t IO a -> Iter t m a liftIterIO = adaptIterM liftIO -- -- mtl runner functions -- -- | The type signature says it all. Just a slightly optimized -- version of @joinlift = join . lift@. joinlift :: (Monad m) => m (Iter t m a) -> Iter t m a joinlift m = Iter $ \c -> IterM $ m >>= \i -> return $ runIter i c -- | Turn a computation of type @'Iter' t ('ContT' ('Iter' t m a) m) -- a@ into one of type @'Iter' t m a@. Note the continuation has to -- return type @'Iter' t m a@ and not @a@ so that runContTI can call -- itself recursively. runContTI :: (ChunkData t, Monad m) => Iter t (ContT (Iter t m a) m) a -> Iter t m a runContTI = adaptIter id adapt where adapt m = joinlift $ runContT m $ return . runContTI -- adapt :: ContT (Iter t m a) m (Iter t (ContT (Iter t m a) m) a) -- -> Iter t m a -- | Run a computation of type @'Iter' t ('ErrorT' e m)@ from within -- the @'Iter' t m@ monad. This function is here for completeness, -- but please consider using 'throwI' instead, since the 'Iter' monad -- already has built-in exception handling and it's best to have a -- single, uniform approach to error reporting. runErrorTI :: (Monad m, ChunkData t, Error e) => Iter t (ErrorT e m) a -> Iter t m (Either e a) runErrorTI = adaptIter Right $ lift . runErrorT >=> next where next (Left e) = return $ Left e next (Right iter) = runErrorTI iter -- | Run an @'Iter' t ('ListT' m)@ computation from within the @'Iter' -- t m@ monad. runListTI :: (Monad m, ChunkData t) => Iter t (ListT m) a -> Iter t m [a] runListTI = adaptIter (: []) $ lift . runListT >=> liftM concat . runListTI . sequence -- | Run an @'Iter' t ('ReaderT' r m)@ computation from within the -- @'Iter' t m@ monad. runReaderTI :: (ChunkData t, Monad m) => Iter t (ReaderT r m) a -> r -> Iter t m a runReaderTI m r = adaptIterM (flip runReaderT r) m -- | Run an @'Iter' t ('RWST' r w s m)@ computation from within the -- @'Iter' t m@ monad. runRWSI :: (ChunkData t, Monoid w, Monad m) => Iter t (RWST r w s m) a -- ^ Computation to transform -> r -- ^ Reader State -> s -- ^ Mutable State -> Iter t m (a, s, w) -- ^ Returns result, mutable state, writer runRWSI iter0 r s0 = doRWS mempty s0 iter0 where doRWS w s = adaptIter (\a -> (a, s, w)) $ \m -> do (iter, s', w') <- lift $ runRWST m r s doRWS (mappend w w') s' iter -- | Run an @'Iter' t ('Lazy.RWST' r w s m)@ computation from within -- the @'Iter' t m@ monad. Just like 'runRWSI', execpt this function -- is for /Lazy/ 'Lazy.RWST' rather than strict 'RWST'. runRWSLI :: (ChunkData t, Monoid w, Monad m) => Iter t (Lazy.RWST r w s m) a -- ^ Computation to transform -> r -- ^ Reader State -> s -- ^ Mutable State -> Iter t m (a, s, w) -- ^ Returns result, mutable state, writer runRWSLI iter0 r s0 = doRWS mempty s0 iter0 where doRWS w s = adaptIter (\a -> (a, s, w)) $ \m -> do (iter, s', w') <- lift $ Lazy.runRWST m r s doRWS (mappend w w') s' iter -- | Run an @'Iter' t ('StateT' m)@ computation from within the -- @'Iter' t m@ monad. runStateTI :: (ChunkData t, Monad m) => Iter t (StateT s m) a -> s -> Iter t m (a, s) runStateTI iter0 s0 = adaptIter (\a -> (a, s0)) adapt iter0 where adapt m = lift (runStateT m s0) >>= uncurry runStateTI -- | Run an @'Iter' t ('Lazy.StateT' m)@ computation from within the -- @'Iter' t m@ monad. Just like 'runStateTI', except this function -- works on /Lazy/ 'Lazy.StateT' rather than strict 'StateT'. runStateTLI :: (ChunkData t, Monad m) => Iter t (Lazy.StateT s m) a -> s -> Iter t m (a, s) runStateTLI iter0 s0 = adaptIter (\a -> (a, s0)) adapt iter0 where adapt m = lift (Lazy.runStateT m s0) >>= uncurry runStateTLI -- | Run an @'Iter' t ('WriterT' w m)@ computation from within the -- @'Iter' t m@ monad. runWriterTI :: (ChunkData t, Monoid w, Monad m) => Iter t (WriterT w m) a -> Iter t m (a, w) runWriterTI = doW mempty where doW w = adaptIter (\a -> (a, w)) $ lift . runWriterT >=> \(iter, w') -> doW (mappend w w') iter -- | Run an @'Iter' t ('Lazy.WriterT' w m)@ computation from within -- the @'Iter' t m@ monad. This is the same as 'runWriterT' but for -- the /Lazy/ 'Lazy.WriterT', rather than the strict one. runWriterTLI :: (ChunkData t, Monoid w, Monad m) => Iter t (Lazy.WriterT w m) a -> Iter t m (a, w) runWriterTLI = doW mempty where doW w = adaptIter (\a -> (a, w)) $ lift . Lazy.runWriterT >=> \(iter, w') -> doW (mappend w w') iter -- -- Below this line, we use FlexibleInstances and UndecidableInstances, -- but only because this is required by mtl. -- instance (ChunkData t, MonadCont m) => MonadCont (Iter t m) where callCC f = joinlift $ (callCC $ \cc -> return $ f (icont cc)) where icont cc a = Iter $ \c -> IterM $ cc (Iter $ \_ -> Done a c) instance (Error e, MonadError e m, ChunkData t) => MonadError e (Iter t m) where throwError = lift . throwError catchError m0 h = adaptIter id (joinlift . runm) m0 where runm m = do r <- catchError (liftM Right m) (return . Left . h) case r of Right iter -> return $ catchError iter h Left iter -> return iter instance (MonadReader r m, ChunkData t) => MonadReader r (Iter t m) where ask = lift ask local f = adaptIterM $ local f instance (MonadState s m, ChunkData t) => MonadState s (Iter t m) where get = lift get put = lift . put instance (Monoid w, MonadWriter w m, ChunkData t) => MonadWriter w (Iter t m) where tell = lift . tell listen = adapt mempty where adapt w = adaptIter (\a -> (a, w)) $ lift . listen >=> \(iter, w') -> adapt (mappend w w') iter pass m = do ((a, f), w) <- adapt mempty m tell (f w) return a where adapt w = adaptIter (\af -> (af, w)) $ lift . censor (const mempty) . listen >=> \(i, w') -> adapt (mappend w w') i -- -- and instances for IterStateT (which are identical to StateT) -- unIterStateT :: IterStateT s m a -> (s -> m (a, s)) unIterStateT (IterStateT f) = f instance (MonadCont m) => MonadCont (IterStateT s m) where callCC f = IterStateT $ \s -> callCC $ \c -> unIterStateT (f (\a -> IterStateT $ \s' -> c (a, s'))) s instance (MonadError e m) => MonadError e (IterStateT s m) where throwError = lift . throwError catchError m h = IterStateT $ \s -> unIterStateT m s `catchError` \e -> unIterStateT (h e) s instance (MonadReader r m) => MonadReader r (IterStateT s m) where ask = lift ask local f m = IterStateT $ \s -> local f (unIterStateT m s) instance (MonadWriter w m) => MonadWriter w (IterStateT s m) where tell = lift . tell listen m = IterStateT $ \s -> do ((a, s'), w) <- listen (unIterStateT m s) return ((a, w), s') pass m = IterStateT $ \s -> pass $ do ((a, f), s') <- unIterStateT m s return ((a, s'), f)
scslab/iterIO
Data/IterIO/Trans.hs
bsd-3-clause
16,688
0
18
4,740
3,793
2,065
1,728
-1
-1
{-| Module : Idris.REPL Description : Entry Point for the Idris REPL and CLI. License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE CPP, DeriveFunctor, FlexibleInstances, MultiParamTypeClasses, PatternGuards #-} module Idris.REPL ( idemodeStart , startServer , runClient , process , replSettings , repl , proofs ) where import Idris.AbsSyntax import Idris.Apropos (apropos, aproposModules) import Idris.ASTUtils import Idris.Colours hiding (colourise) import Idris.Completion import Idris.Core.Constraints import Idris.Core.Evaluate import Idris.Core.Execute (execute) import Idris.Core.TT import Idris.Core.Unify import Idris.Core.WHNF import Idris.Coverage import Idris.Delaborate import Idris.Docs hiding (Doc) import Idris.Docstrings (overview, renderDocTerm, renderDocstring) import Idris.Elab.Clause import Idris.Elab.Term import Idris.Elab.Value import Idris.ElabDecls import Idris.Error import Idris.ErrReverse import Idris.Help import Idris.IBC import qualified Idris.IdeMode as IdeMode import Idris.IdrisDoc import Idris.Info import Idris.Inliner import Idris.Interactive import Idris.ModeCommon import Idris.Output import Idris.Parser hiding (indent) import Idris.Prover import Idris.REPL.Browse (namesInNS, namespacesInNS) import Idris.REPL.Commands import Idris.REPL.Parser import Idris.Termination import Idris.TypeSearch (searchByType) import Idris.WhoCalls import IRTS.Compiler import Util.DynamicLinker import Util.Net (listenOnLocalhost, listenOnLocalhostAnyPort) import Util.Pretty hiding ((</>)) import Util.System import Version_idris (gitHash) import Prelude hiding (id, (.), (<$>)) import Control.Category import Control.Concurrent import Control.Concurrent.Async (race) import Control.Concurrent.MVar import Control.DeepSeq import qualified Control.Exception as X import Control.Monad import Control.Monad.Trans (lift) import Control.Monad.Trans.Except (ExceptT, runExceptT) import Control.Monad.Trans.State.Strict (StateT, evalStateT, execStateT, get, put) import Data.Char import Data.Either (partitionEithers) import Data.List hiding (group) import Data.List.Split (splitOn) import Data.Maybe import qualified Data.Set as S import qualified Data.Text as T import Data.Version import Network import System.Console.Haskeline as H import System.Directory import System.Environment import System.Exit import System.FilePath (addExtension, dropExtension, splitExtension, takeDirectory, takeExtension, (<.>), (</>)) import System.FSNotify (watchDir, withManager) import System.FSNotify.Devel (allEvents, doAllEvents) import System.IO import System.Process import Text.Trifecta.Result (ErrInfo(..), Result(..)) -- | Run the REPL repl :: IState -- ^ The initial state -> [FilePath] -- ^ The loaded modules -> FilePath -- ^ The file to edit (with :e) -> InputT Idris () repl orig mods efile = -- H.catch do let quiet = opt_quiet (idris_options orig) i <- lift getIState let colour = idris_colourRepl i let theme = idris_colourTheme i let mvs = idris_metavars i let prompt = if quiet then "" else showMVs colour theme mvs ++ let str = mkPrompt mods ++ ">" in (if colour && not isWindows then colourisePrompt theme str else str) ++ " " x <- H.catch (H.withInterrupt $ getInputLine prompt) (ctrlC (return $ Just "")) case x of Nothing -> do lift $ when (not quiet) (iputStrLn "Bye bye") return () Just input -> -- H.catch do ms <- H.catch (H.withInterrupt $ lift $ processInput input orig mods efile) (ctrlC (return (Just mods))) case ms of Just mods -> let efile' = fromMaybe efile (listToMaybe mods) in repl orig mods efile' Nothing -> return () -- ctrlC) -- ctrlC where ctrlC :: InputT Idris a -> SomeException -> InputT Idris a ctrlC act e = do lift $ iputStrLn (show e) act -- repl orig mods showMVs c thm [] = "" showMVs c thm ms = "Holes: " ++ show' 4 c thm (map fst ms) ++ "\n" show' 0 c thm ms = let l = length ms in "... ( + " ++ show l ++ " other" ++ if l == 1 then ")" else "s)" show' n c thm [m] = showM c thm m show' n c thm (m : ms) = showM c thm m ++ ", " ++ show' (n - 1) c thm ms showM c thm n = if c then colouriseFun thm (show n) else show n -- | Run the REPL server startServer :: PortNumber -> IState -> [FilePath] -> Idris () startServer port orig fn_in = do tid <- runIO $ forkIO (serverLoop port) return () where serverLoop port = withSocketsDo $ do sock <- listenOnLocalhost port loop fn orig { idris_colourRepl = False } sock fn = fromMaybe "" (listToMaybe fn_in) loop fn ist sock = do (h,_,_) <- accept sock hSetEncoding h utf8 cmd <- hGetLine h let isth = case idris_outputmode ist of RawOutput _ -> ist {idris_outputmode = RawOutput h} IdeMode n _ -> ist {idris_outputmode = IdeMode n h} (ist', fn) <- processNetCmd orig isth h fn cmd hClose h loop fn ist' sock processNetCmd :: IState -> IState -> Handle -> FilePath -> String -> IO (IState, FilePath) processNetCmd orig i h fn cmd = do res <- case parseCmd i "(net)" cmd of Failure (ErrInfo err _) -> return (Left (Msg " invalid command")) Success (Right c) -> runExceptT $ evalStateT (processNet fn c) i Success (Left err) -> return (Left (Msg err)) case res of Right x -> return x Left err -> do hPutStrLn h (show err) return (i, fn) where processNet fn Reload = processNet fn (Load fn Nothing) processNet fn (Load f toline) = -- The $!! here prevents a space leak on reloading. -- This isn't a solution - but it's a temporary stopgap. -- See issue #2386 do putIState $!! orig { idris_options = idris_options i , idris_colourTheme = idris_colourTheme i , idris_colourRepl = False } setErrContext True setOutH h setQuiet True setVerbose False mods <- loadInputs [f] toline ist <- getIState return (ist, f) processNet fn c = do process fn c ist <- getIState return (ist, fn) setOutH :: Handle -> Idris () setOutH h = do ist <- getIState putIState $ case idris_outputmode ist of RawOutput _ -> ist {idris_outputmode = RawOutput h} IdeMode n _ -> ist {idris_outputmode = IdeMode n h} -- | Run a command on the server on localhost runClient :: Maybe PortNumber -> String -> IO () runClient port str = withSocketsDo $ do let port' = fromMaybe defaultPort port res <- X.try (connectTo "localhost" $ PortNumber port') case res of Right h -> do hSetEncoding h utf8 hPutStrLn h str resp <- hGetResp "" h putStr resp hClose h Left err -> do connectionError err exitWith (ExitFailure 1) where hGetResp acc h = do eof <- hIsEOF h if eof then return acc else do l <- hGetLine h hGetResp (acc ++ l ++ "\n") h connectionError :: X.SomeException -> IO () connectionError _ = putStrLn "Unable to connect to a running Idris repl" initIdemodeSocket :: IO Handle initIdemodeSocket = do (sock, port) <- listenOnLocalhostAnyPort putStrLn $ show port (h, _, _) <- accept sock hSetEncoding h utf8 return h -- | Run the IdeMode idemodeStart :: Bool -> IState -> [FilePath] -> Idris () idemodeStart s orig mods = do h <- runIO $ if s then initIdemodeSocket else return stdout setIdeMode True h i <- getIState case idris_outputmode i of IdeMode n h -> do runIO $ hPutStrLn h $ IdeMode.convSExp "protocol-version" IdeMode.ideModeEpoch n case mods of a:_ -> runIdeModeCommand h n i "" [] (IdeMode.LoadFile a Nothing) _ -> return () idemode h orig mods idemode :: Handle -> IState -> [FilePath] -> Idris () idemode h orig mods = do idrisCatch (do let inh = if h == stdout then stdin else h len' <- runIO $ IdeMode.getLen inh len <- case len' of Left err -> ierror err Right n -> return n l <- runIO $ IdeMode.getNChar inh len "" (sexp, id) <- case IdeMode.parseMessage l of Left err -> ierror err Right (sexp, id) -> return (sexp, id) i <- getIState putIState $ i { idris_outputmode = (IdeMode id h) } idrisCatch -- to report correct id back! (do let fn = fromMaybe "" (listToMaybe mods) case IdeMode.sexpToCommand sexp of Just cmd -> runIdeModeCommand h id orig fn mods cmd Nothing -> iPrintError "did not understand" ) (\e -> do iPrintError $ show e)) (\e -> do iPrintError $ show e) idemode h orig mods -- | Run IDEMode commands runIdeModeCommand :: Handle -- ^^ The handle for communication -> Integer -- ^^ The continuation ID for the client -> IState -- ^^ The original IState -> FilePath -- ^^ The current open file -> [FilePath] -- ^^ The currently loaded modules -> IdeMode.IdeModeCommand -- ^^ The command to process -> Idris () runIdeModeCommand h id orig fn mods (IdeMode.Interpret cmd) = do c <- colourise i <- getIState case parseCmd i "(input)" cmd of Failure (ErrInfo err _) -> iPrintError $ show (fixColour False err) Success (Right (Prove mode n')) -> idrisCatch (do process fn (Prove mode n') isetPrompt (mkPrompt mods) case idris_outputmode i of IdeMode n h -> -- signal completion of proof to ide runIO . hPutStrLn h $ IdeMode.convSExp "return" (IdeMode.SymbolAtom "ok", "") n _ -> return ()) (\e -> do ist <- getIState isetPrompt (mkPrompt mods) case idris_outputmode i of IdeMode n h -> runIO . hPutStrLn h $ IdeMode.convSExp "abandon-proof" "Abandoned" n _ -> return () iRenderError $ pprintErr ist e) Success (Right cmd) -> idrisCatch (idemodeProcess fn cmd) (\e -> getIState >>= iRenderError . flip pprintErr e) Success (Left err) -> iPrintError err runIdeModeCommand h id orig fn mods (IdeMode.REPLCompletions str) = do (unused, compls) <- replCompletion (reverse str, "") let good = IdeMode.SexpList [IdeMode.SymbolAtom "ok", IdeMode.toSExp (map replacement compls, reverse unused)] runIO . hPutStrLn h $ IdeMode.convSExp "return" good id runIdeModeCommand h id orig fn mods (IdeMode.LoadFile filename toline) = -- The $!! here prevents a space leak on reloading. -- This isn't a solution - but it's a temporary stopgap. -- See issue #2386 do i <- getIState clearErr putIState $!! orig { idris_options = idris_options i, idris_outputmode = (IdeMode id h) } mods <- loadInputs [filename] toline isetPrompt (mkPrompt mods) -- Report either success or failure i <- getIState case (errSpan i) of Nothing -> let msg = maybe (IdeMode.SexpList [IdeMode.SymbolAtom "ok", IdeMode.SexpList []]) (\fc -> IdeMode.SexpList [IdeMode.SymbolAtom "ok", IdeMode.toSExp fc]) (idris_parsedSpan i) in runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id Just x -> iPrintError $ "didn't load " ++ filename idemode h orig mods runIdeModeCommand h id orig fn mods (IdeMode.TypeOf name) = case splitName name of Left err -> iPrintError err Right n -> process "(idemode)" (Check (PRef (FC "(idemode)" (0,0) (0,0)) [] n)) runIdeModeCommand h id orig fn mods (IdeMode.DocsFor name w) = case parseConst orig name of Success c -> process "(idemode)" (DocStr (Right c) (howMuch w)) Failure _ -> case splitName name of Left err -> iPrintError err Right n -> process "(idemode)" (DocStr (Left n) (howMuch w)) where howMuch IdeMode.Overview = OverviewDocs howMuch IdeMode.Full = FullDocs runIdeModeCommand h id orig fn mods (IdeMode.CaseSplit line name) = process fn (CaseSplitAt False line (sUN name)) runIdeModeCommand h id orig fn mods (IdeMode.AddClause line name) = process fn (AddClauseFrom False line (sUN name)) runIdeModeCommand h id orig fn mods (IdeMode.AddProofClause line name) = process fn (AddProofClauseFrom False line (sUN name)) runIdeModeCommand h id orig fn mods (IdeMode.AddMissing line name) = process fn (AddMissing False line (sUN name)) runIdeModeCommand h id orig fn mods (IdeMode.MakeWithBlock line name) = process fn (MakeWith False line (sUN name)) runIdeModeCommand h id orig fn mods (IdeMode.MakeCaseBlock line name) = process fn (MakeCase False line (sUN name)) runIdeModeCommand h id orig fn mods (IdeMode.ProofSearch r line name hints depth) = doProofSearch fn False r line (sUN name) (map sUN hints) depth runIdeModeCommand h id orig fn mods (IdeMode.MakeLemma line name) = case splitName name of Left err -> iPrintError err Right n -> process fn (MakeLemma False line n) runIdeModeCommand h id orig fn mods (IdeMode.Apropos a) = process fn (Apropos [] a) runIdeModeCommand h id orig fn mods (IdeMode.GetOpts) = do ist <- getIState let opts = idris_options ist let impshow = opt_showimp opts let errCtxt = opt_errContext opts let options = (IdeMode.SymbolAtom "ok", [(IdeMode.SymbolAtom "show-implicits", impshow), (IdeMode.SymbolAtom "error-context", errCtxt)]) runIO . hPutStrLn h $ IdeMode.convSExp "return" options id runIdeModeCommand h id orig fn mods (IdeMode.SetOpt IdeMode.ShowImpl b) = do setImpShow b let msg = (IdeMode.SymbolAtom "ok", b) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id runIdeModeCommand h id orig fn mods (IdeMode.SetOpt IdeMode.ErrContext b) = do setErrContext b let msg = (IdeMode.SymbolAtom "ok", b) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id runIdeModeCommand h id orig fn mods (IdeMode.Metavariables cols) = do ist <- getIState let mvs = reverse $ map fst (idris_metavars ist) \\ primDefs let ppo = ppOptionIst ist -- splitMvs is a list of pairs of names and their split types let splitMvs = mapSnd (splitPi ist) (mvTys ist mvs) -- mvOutput is the pretty-printed version ready for conversion to SExpr let mvOutput = map (\(n, (hs, c)) -> (n, hs, c)) $ mapPair show (\(hs, c, pc) -> let bnd = [ n | (n,_,_) <- hs ] in let bnds = inits bnd in (map (\(bnd, h) -> processPremise ist bnd h) (zip bnds hs), render ist bnd c pc)) splitMvs runIO . hPutStrLn h $ IdeMode.convSExp "return" (IdeMode.SymbolAtom "ok", mvOutput) id where mapPair f g xs = zip (map (f . fst) xs) (map (g . snd) xs) mapSnd f xs = zip (map fst xs) (map (f . snd) xs) -- | Split a function type into a pair of premises, conclusion. -- Each maintains both the original and delaborated versions. splitPi :: IState -> Type -> ([(Name, Type, PTerm)], Type, PTerm) splitPi ist (Bind n (Pi _ t _) rest) = let (hs, c, pc) = splitPi ist rest in ((n, t, delabTy' ist [] t False False True):hs, c, delabTy' ist [] c False False True) splitPi ist tm = ([], tm, delabTy' ist [] tm False False True) -- | Get the types of a list of metavariable names mvTys :: IState -> [Name] -> [(Name, Type)] mvTys ist = mapSnd vToP . mapMaybe (flip lookupTyNameExact (tt_ctxt ist)) -- | Show a type and its corresponding PTerm in a format suitable -- for the IDE - that is, pretty-printed and annotated. render :: IState -> [Name] -> Type -> PTerm -> (String, SpanList OutputAnnotation) render ist bnd t pt = let prettyT = pprintPTerm (ppOptionIst ist) (zip bnd (repeat False)) [] (idris_infixes ist) pt in displaySpans . renderPretty 0.9 cols . fmap (fancifyAnnots ist True) . annotate (AnnTerm (zip bnd (take (length bnd) (repeat False))) t) $ prettyT -- | Juggle the bits of a premise to prepare for output. processPremise :: IState -> [Name] -- ^ the names to highlight as bound -> (Name, Type, PTerm) -> (String, String, SpanList OutputAnnotation) processPremise ist bnd (n, t, pt) = let (out, spans) = render ist bnd t pt in (show n , out, spans) runIdeModeCommand h id orig fn mods (IdeMode.WhoCalls n) = case splitName n of Left err -> iPrintError err Right n -> do calls <- whoCalls n ist <- getIState let msg = (IdeMode.SymbolAtom "ok", map (\ (n,ns) -> (pn ist n, map (pn ist) ns)) calls) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id where pn ist = displaySpans . renderPretty 0.9 1000 . fmap (fancifyAnnots ist True) . prettyName True True [] runIdeModeCommand h id orig fn mods (IdeMode.CallsWho n) = case splitName n of Left err -> iPrintError err Right n -> do calls <- callsWho n ist <- getIState let msg = (IdeMode.SymbolAtom "ok", map (\ (n,ns) -> (pn ist n, map (pn ist) ns)) calls) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id where pn ist = displaySpans . renderPretty 0.9 1000 . fmap (fancifyAnnots ist True) . prettyName True True [] runIdeModeCommand h id orig fn modes (IdeMode.BrowseNS ns) = case splitOn "." ns of [] -> iPrintError "No namespace provided" ns -> do underNSs <- fmap (map $ concat . intersperse ".") $ namespacesInNS ns names <- namesInNS ns if null underNSs && null names then iPrintError "Invalid or empty namespace" else do ist <- getIState underNs <- mapM pn names let msg = (IdeMode.SymbolAtom "ok", (underNSs, underNs)) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id where pn n = do ctxt <- getContext ist <- getIState return $ displaySpans . renderPretty 0.9 1000 . fmap (fancifyAnnots ist True) $ prettyName True False [] n <> case lookupTyExact n ctxt of Just t -> space <> colon <> space <> align (group (pprintDelab ist t)) Nothing -> empty runIdeModeCommand h id orig fn modes (IdeMode.TermNormalise bnd tm) = do ctxt <- getContext ist <- getIState let tm' = normaliseAll ctxt [] tm ptm = annotate (AnnTerm bnd tm') (pprintPTerm (ppOptionIst ist) bnd [] (idris_infixes ist) (delab ist tm')) msg = (IdeMode.SymbolAtom "ok", displaySpans . renderPretty 0.9 80 . fmap (fancifyAnnots ist True) $ ptm) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id runIdeModeCommand h id orig fn modes (IdeMode.TermShowImplicits bnd tm) = ideModeForceTermImplicits h id bnd True tm runIdeModeCommand h id orig fn modes (IdeMode.TermNoImplicits bnd tm) = ideModeForceTermImplicits h id bnd False tm runIdeModeCommand h id orig fn modes (IdeMode.TermElab bnd tm) = do ist <- getIState let ptm = annotate (AnnTerm bnd tm) (pprintTT (map fst bnd) tm) msg = (IdeMode.SymbolAtom "ok", displaySpans . renderPretty 0.9 70 . fmap (fancifyAnnots ist True) $ ptm) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id runIdeModeCommand h id orig fn mods (IdeMode.PrintDef name) = case splitName name of Left err -> iPrintError err Right n -> process "(idemode)" (PrintDef n) runIdeModeCommand h id orig fn modes (IdeMode.ErrString e) = do ist <- getIState let out = displayS . renderPretty 1.0 60 $ pprintErr ist e msg = (IdeMode.SymbolAtom "ok", IdeMode.StringAtom $ out "") runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id runIdeModeCommand h id orig fn modes (IdeMode.ErrPPrint e) = do ist <- getIState let (out, spans) = displaySpans . renderPretty 0.9 80 . fmap (fancifyAnnots ist True) $ pprintErr ist e msg = (IdeMode.SymbolAtom "ok", out, spans) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id runIdeModeCommand h id orig fn modes IdeMode.GetIdrisVersion = let idrisVersion = (versionBranch getIdrisVersionNoGit, if not (null gitHash) then [gitHash] else []) msg = (IdeMode.SymbolAtom "ok", idrisVersion) in runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id -- | Show a term for IDEMode with the specified implicitness ideModeForceTermImplicits :: Handle -> Integer -> [(Name, Bool)] -> Bool -> Term -> Idris () ideModeForceTermImplicits h id bnd impl tm = do ist <- getIState let expl = annotate (AnnTerm bnd tm) (pprintPTerm ((ppOptionIst ist) { ppopt_impl = impl }) bnd [] (idris_infixes ist) (delab ist tm)) msg = (IdeMode.SymbolAtom "ok", displaySpans . renderPretty 0.9 80 . fmap (fancifyAnnots ist True) $ expl) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id splitName :: String -> Either String Name splitName s = case reverse $ splitOn "." s of [] -> Left ("Didn't understand name '" ++ s ++ "'") [n] -> Right . sUN $ unparen n (n:ns) -> Right $ sNS (sUN (unparen n)) ns where unparen "" = "" unparen ('(':x:xs) | last xs == ')' = init (x:xs) unparen str = str idemodeProcess :: FilePath -> Command -> Idris () idemodeProcess fn Warranty = process fn Warranty idemodeProcess fn Help = process fn Help idemodeProcess fn (ChangeDirectory f) = do process fn (ChangeDirectory f) dir <- runIO $ getCurrentDirectory iPrintResult $ "changed directory to " ++ dir idemodeProcess fn (ModImport f) = process fn (ModImport f) idemodeProcess fn (Eval t) = process fn (Eval t) idemodeProcess fn (NewDefn decls) = do process fn (NewDefn decls) iPrintResult "defined" idemodeProcess fn (Undefine n) = process fn (Undefine n) idemodeProcess fn (ExecVal t) = process fn (ExecVal t) idemodeProcess fn (Check (PRef x hls n)) = process fn (Check (PRef x hls n)) idemodeProcess fn (Check t) = process fn (Check t) idemodeProcess fn (Core t) = process fn (Core t) idemodeProcess fn (DocStr n w) = process fn (DocStr n w) idemodeProcess fn Universes = process fn Universes idemodeProcess fn (Defn n) = do process fn (Defn n) iPrintResult "" idemodeProcess fn (TotCheck n) = process fn (TotCheck n) idemodeProcess fn (DebugInfo n) = do process fn (DebugInfo n) iPrintResult "" idemodeProcess fn (Search ps t) = process fn (Search ps t) idemodeProcess fn (Spec t) = process fn (Spec t) -- RmProof and AddProof not supported! idemodeProcess fn (ShowProof n') = process fn (ShowProof n') idemodeProcess fn (WHNF t) = process fn (WHNF t) --idemodeProcess fn TTShell = process fn TTShell -- need some prove mode! idemodeProcess fn (TestInline t) = process fn (TestInline t) idemodeProcess fn (Execute t) = do process fn (Execute t) iPrintResult "" idemodeProcess fn (Compile codegen f) = do process fn (Compile codegen f) iPrintResult "" idemodeProcess fn (LogLvl i) = do process fn (LogLvl i) iPrintResult "" idemodeProcess fn (Pattelab t) = process fn (Pattelab t) idemodeProcess fn (Missing n) = process fn (Missing n) idemodeProcess fn (DynamicLink l) = do process fn (DynamicLink l) iPrintResult "" idemodeProcess fn ListDynamic = do process fn ListDynamic iPrintResult "" idemodeProcess fn Metavars = process fn Metavars idemodeProcess fn (SetOpt ErrContext) = do process fn (SetOpt ErrContext) iPrintResult "" idemodeProcess fn (UnsetOpt ErrContext) = do process fn (UnsetOpt ErrContext) iPrintResult "" idemodeProcess fn (SetOpt ShowImpl) = do process fn (SetOpt ShowImpl) iPrintResult "" idemodeProcess fn (UnsetOpt ShowImpl) = do process fn (UnsetOpt ShowImpl) iPrintResult "" idemodeProcess fn (SetOpt ShowOrigErr) = do process fn (SetOpt ShowOrigErr) iPrintResult "" idemodeProcess fn (UnsetOpt ShowOrigErr) = do process fn (UnsetOpt ShowOrigErr) iPrintResult "" idemodeProcess fn (SetOpt x) = process fn (SetOpt x) idemodeProcess fn (UnsetOpt x) = process fn (UnsetOpt x) idemodeProcess fn (CaseSplitAt False pos str) = process fn (CaseSplitAt False pos str) idemodeProcess fn (AddProofClauseFrom False pos str) = process fn (AddProofClauseFrom False pos str) idemodeProcess fn (AddClauseFrom False pos str) = process fn (AddClauseFrom False pos str) idemodeProcess fn (AddMissing False pos str) = process fn (AddMissing False pos str) idemodeProcess fn (MakeWith False pos str) = process fn (MakeWith False pos str) idemodeProcess fn (MakeCase False pos str) = process fn (MakeCase False pos str) idemodeProcess fn (DoProofSearch False r pos str xs) = process fn (DoProofSearch False r pos str xs) idemodeProcess fn (SetConsoleWidth w) = do process fn (SetConsoleWidth w) iPrintResult "" idemodeProcess fn (SetPrinterDepth d) = do process fn (SetPrinterDepth d) iPrintResult "" idemodeProcess fn (Apropos pkg a) = do process fn (Apropos pkg a) iPrintResult "" idemodeProcess fn (WhoCalls n) = process fn (WhoCalls n) idemodeProcess fn (CallsWho n) = process fn (CallsWho n) idemodeProcess fn (PrintDef n) = process fn (PrintDef n) idemodeProcess fn (PPrint fmt n tm) = process fn (PPrint fmt n tm) idemodeProcess fn _ = iPrintError "command not recognized or not supported" -- | The prompt consists of the currently loaded modules, or "Idris" if there are none mkPrompt [] = "Idris" mkPrompt [x] = "*" ++ dropExtension x mkPrompt (x:xs) = "*" ++ dropExtension x ++ " " ++ mkPrompt xs -- | Determine whether a file uses literate syntax lit f = case splitExtension f of (_, ".lidr") -> True _ -> False reload :: IState -> [FilePath] -> Idris (Maybe [FilePath]) reload orig inputs = do i <- getIState -- The $!! here prevents a space leak on reloading. -- This isn't a solution - but it's a temporary stopgap. -- See issue #2386 putIState $!! orig { idris_options = idris_options i , idris_colourTheme = idris_colourTheme i , imported = imported i } clearErr fmap Just $ loadInputs inputs Nothing watch :: IState -> [FilePath] -> Idris (Maybe [FilePath]) watch orig inputs = do resp <- runIO $ do let dirs = nub $ map takeDirectory inputs inputSet <- fmap S.fromList $ mapM canonicalizePath inputs signal <- newEmptyMVar withManager $ \mgr -> do forM_ dirs $ \dir -> watchDir mgr dir (allEvents $ flip S.member inputSet) (doAllEvents $ putMVar signal) race getLine (takeMVar signal) case resp of Left _ -> return (Just inputs) -- canceled, so nop Right _ -> reload orig inputs >> watch orig inputs processInput :: String -> IState -> [FilePath] -> FilePath -> Idris (Maybe [FilePath]) processInput cmd orig inputs efile = do i <- getIState let opts = idris_options i let quiet = opt_quiet opts let fn = fromMaybe "" (listToMaybe inputs) c <- colourise case parseCmd i "(input)" cmd of Failure (ErrInfo err _) -> do iputStrLn $ show (fixColour c err) return (Just inputs) Success (Right Reload) -> reload orig inputs Success (Right Watch) -> if null inputs then do iputStrLn "No loaded files to watch." return (Just inputs) else do iputStrLn efile iputStrLn $ "Watching for .idr changes in " ++ show inputs ++ ", press enter to cancel." watch orig inputs Success (Right (Load f toline)) -> -- The $!! here prevents a space leak on reloading. -- This isn't a solution - but it's a temporary stopgap. -- See issue #2386 do putIState $!! orig { idris_options = idris_options i , idris_colourTheme = idris_colourTheme i } clearErr mod <- loadInputs [f] toline return (Just mod) Success (Right (ModImport f)) -> do clearErr fmod <- loadModule f (IBC_REPL True) return (Just (inputs ++ maybe [] (:[]) fmod)) Success (Right Edit) -> do -- takeMVar stvar edit efile orig return (Just inputs) Success (Right Proofs) -> do proofs orig return (Just inputs) Success (Right Quit) -> do when (not quiet) (iputStrLn "Bye bye") return Nothing Success (Right cmd ) -> do idrisCatch (process fn cmd) (\e -> do msg <- showErr e ; iputStrLn msg) return (Just inputs) Success (Left err) -> do runIO $ putStrLn err return (Just inputs) resolveProof :: Name -> Idris Name resolveProof n' = do i <- getIState ctxt <- getContext n <- case lookupNames n' ctxt of [x] -> return x [] -> return n' ns -> ierror (CantResolveAlts ns) return n removeProof :: Name -> Idris () removeProof n = do i <- getIState let proofs = proof_list i let ps = filter ((/= n) . fst) proofs putIState $ i { proof_list = ps } edit :: FilePath -> IState -> Idris () edit "" orig = iputStrLn "Nothing to edit" edit f orig = do i <- getIState env <- runIO getEnvironment let editor = getEditor env let line = case errSpan i of Just l -> '+' : show (fst (fc_start l)) Nothing -> "" let cmdLine = intercalate " " [editor, line, fixName f] runIO $ system cmdLine clearErr -- The $!! here prevents a space leak on reloading. -- This isn't a solution - but it's a temporary stopgap. -- See issue #2386 putIState $!! orig { idris_options = idris_options i , idris_colourTheme = idris_colourTheme i } loadInputs [f] Nothing -- clearOrigPats iucheck return () where getEditor env | Just ed <- lookup "EDITOR" env = ed | Just ed <- lookup "VISUAL" env = ed | otherwise = "vi" fixName file | map toLower (takeExtension file) `elem` [".lidr", ".idr"] = quote file | otherwise = quote $ addExtension file "idr" where quoteChar = if isWindows then '"' else '\'' quote s = [quoteChar] ++ s ++ [quoteChar] proofs :: IState -> Idris () proofs orig = do i <- getIState let ps = proof_list i case ps of [] -> iputStrLn "No proofs available" _ -> iputStrLn $ "Proofs:\n\t" ++ (show $ map fst ps) insertScript :: String -> [String] -> [String] insertScript prf [] = "\n---------- Proofs ----------" : "" : [prf] insertScript prf (p@"---------- Proofs ----------" : "" : xs) = p : "" : prf : xs insertScript prf (x : xs) = x : insertScript prf xs process :: FilePath -> Command -> Idris () process fn Help = iPrintResult displayHelp process fn Warranty = iPrintResult warranty process fn (ChangeDirectory f) = do runIO $ setCurrentDirectory f return () process fn (ModImport f) = do fmod <- loadModule f (IBC_REPL True) case fmod of Just pr -> isetPrompt pr Nothing -> iPrintError $ "Can't find import " ++ f process fn (Eval t) = withErrorReflection $ do logParser 5 $ show t getIState >>= flip warnDisamb t (tm, ty) <- elabREPL (recinfo (fileFC "toplevel")) ERHS t ctxt <- getContext let tm' = perhapsForce $ normaliseBlocking ctxt [] [sUN "foreign", sUN "prim_read", sUN "prim_write"] tm let ty' = perhapsForce $ normaliseAll ctxt [] ty -- Add value to context, call it "it" updateContext (addCtxtDef (sUN "it") (Function ty' tm')) ist <- getIState logParser 3 $ "Raw: " ++ show (tm', ty') logParser 10 $ "Debug: " ++ showEnvDbg [] tm' let tmDoc = pprintDelab ist tm' -- errReverse to make type more readable tyDoc = pprintDelab ist (errReverse ist ty') iPrintTermWithType tmDoc tyDoc where perhapsForce tm | termSmallerThan 100 tm = force tm | otherwise = tm process fn (NewDefn decls) = do logParser 3 ("Defining names using these decls: " ++ show (showDecls verbosePPOption decls)) mapM_ defineName namedGroups where namedGroups = groupBy (\d1 d2 -> getName d1 == getName d2) decls getName :: PDecl -> Maybe Name getName (PTy docs argdocs syn fc opts name _ ty) = Just name getName (PClauses fc opts name (clause:clauses)) = Just (getClauseName clause) getName (PData doc argdocs syn fc opts dataDecl) = Just (d_name dataDecl) getName (PInterface doc syn fc constraints name nfc parms parmdocs fds decls _ _) = Just name getName _ = Nothing -- getClauseName is partial and I am not sure it's used safely! -- trillioneyes getClauseName (PClause fc name whole with rhs whereBlock) = name getClauseName (PWith fc name whole with rhs pn whereBlock) = name defineName :: [PDecl] -> Idris () defineName (tyDecl@(PTy docs argdocs syn fc opts name _ ty) : decls) = do elabDecl EAll info tyDecl elabClauses info fc opts name (concatMap getClauses decls) setReplDefined (Just name) defineName [PClauses fc opts _ [clause]] = do let pterm = getRHS clause (tm,ty) <- elabVal info ERHS pterm ctxt <- getContext let tm' = force (normaliseAll ctxt [] tm) let ty' = force (normaliseAll ctxt [] ty) updateContext (addCtxtDef (getClauseName clause) (Function ty' tm')) setReplDefined (Just $ getClauseName clause) defineName (PClauses{} : _) = tclift $ tfail (Msg "Only one function body is allowed without a type declaration.") -- fixity and syntax declarations are ignored by elabDecls, so they'll have to be handled some other way defineName (PFix fc fixity strs : defns) = do fmodifyState idris_fixities (map (Fix fixity) strs ++) unless (null defns) $ defineName defns defineName (PSyntax _ syntax:_) = do i <- get put (addReplSyntax i syntax) defineName decls = do elabDecls (toplevelWith fn) (map fixClauses decls) setReplDefined (getName (head decls)) getClauses (PClauses fc opts name clauses) = clauses getClauses _ = [] getRHS :: PClause -> PTerm getRHS (PClause fc name whole with rhs whereBlock) = rhs getRHS (PWith fc name whole with rhs pn whereBlock) = rhs getRHS (PClauseR fc with rhs whereBlock) = rhs getRHS (PWithR fc with rhs pn whereBlock) = rhs setReplDefined :: Maybe Name -> Idris () setReplDefined Nothing = return () setReplDefined (Just n) = do oldState <- get fmodifyState repl_definitions (n:) -- the "name" field of PClauses seems to always be MN 2 "__", so we need to -- retrieve the actual name from deeper inside. -- This should really be a full recursive walk through the structure of PDecl, but -- I think it should work this way and I want to test sooner. Also lazy. fixClauses :: PDecl' t -> PDecl' t fixClauses (PClauses fc opts _ css@(clause:cs)) = PClauses fc opts (getClauseName clause) css fixClauses (PImplementation doc argDocs syn fc constraints pnames acc opts cls nfc parms pextra ty implName decls) = PImplementation doc argDocs syn fc constraints pnames acc opts cls nfc parms pextra ty implName (map fixClauses decls) fixClauses decl = decl info = recinfo (fileFC "toplevel") process fn (Undefine names) = undefine names where undefine :: [Name] -> Idris () undefine [] = do allDefined <- idris_repl_defs `fmap` get undefine' allDefined [] -- Keep track of which names you've removed so you can -- print them out to the user afterward undefine names = undefine' names [] undefine' [] list = do iRenderResult $ printUndefinedNames list return () undefine' (n:names) already = do allDefined <- idris_repl_defs `fmap` get if n `elem` allDefined then do undefinedJustNow <- undefClosure n undefine' names (undefinedJustNow ++ already) else do tclift $ tfail $ Msg ("Can't undefine " ++ show n ++ " because it wasn't defined at the repl") undefine' names already undefOne n = do fputState (ctxt_lookup n . known_terms) Nothing -- for now just assume it's an interface. Eventually we'll want some kind of -- smart detection of exactly what kind of name we're undefining. fputState (ctxt_lookup n . known_interfaces) Nothing fmodifyState repl_definitions (delete n) undefClosure n = do replDefs <- idris_repl_defs `fmap` get callGraph <- whoCalls n let users = case lookup n callGraph of Just ns -> nub ns Nothing -> fail ("Tried to undefine nonexistent name" ++ show n) undefinedJustNow <- concat `fmap` mapM undefClosure users undefOne n return (nub (n : undefinedJustNow)) process fn (ExecVal t) = do ctxt <- getContext ist <- getIState (tm, ty) <- elabVal (recinfo (fileFC "toplevel")) ERHS t -- let tm' = normaliseAll ctxt [] tm let ty' = normaliseAll ctxt [] ty res <- execute tm let (resOut, tyOut) = (prettyIst ist (delab ist res), prettyIst ist (delab ist ty')) iPrintTermWithType resOut tyOut process fn (Check (PRef _ _ n)) = do ctxt <- getContext ist <- getIState let ppo = ppOptionIst ist case lookupNames n ctxt of ts@(t:_) -> case lookup t (idris_metavars ist) of Just (_, i, _, _, _) -> iRenderResult . fmap (fancifyAnnots ist True) $ showMetavarInfo ppo ist n i Nothing -> iPrintFunTypes [] n (map (\n -> (n, pprintDelabTy ist n)) ts) [] -> iPrintError $ "No such variable " ++ show n where showMetavarInfo ppo ist n i = case lookupTy n (tt_ctxt ist) of (ty:_) -> let ty' = normaliseC (tt_ctxt ist) [] ty in putTy ppo ist i [] (delab ist (errReverse ist ty')) putTy :: PPOption -> IState -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation putTy ppo ist 0 bnd sc = putGoal ppo ist bnd sc putTy ppo ist i bnd (PPi _ n _ t sc) = let current = case n of MN _ _ -> text "" UN nm | ('_':'_':_) <- str nm -> text "" _ -> text " " <> bindingOf n False <+> colon <+> align (tPretty bnd ist t) <> line in current <> putTy ppo ist (i-1) ((n,False):bnd) sc putTy ppo ist _ bnd sc = putGoal ppo ist ((n,False):bnd) sc putGoal ppo ist bnd g = text "--------------------------------------" <$> annotate (AnnName n Nothing Nothing Nothing) (text $ show n) <+> colon <+> align (tPretty bnd ist g) tPretty bnd ist t = pprintPTerm (ppOptionIst ist) bnd [] (idris_infixes ist) t process fn (Check t) = do (tm, ty) <- elabREPL (recinfo (fileFC "toplevel")) ERHS t ctxt <- getContext ist <- getIState let ppo = ppOptionIst ist ty' = if opt_evaltypes (idris_options ist) then normaliseC ctxt [] ty else ty case tm of TType _ -> iPrintTermWithType (prettyIst ist (PType emptyFC)) type1Doc _ -> iPrintTermWithType (pprintDelab ist tm) (pprintDelab ist ty') process fn (Core t) = case t of PRef _ _ n -> do ist <- getIState case lookupDef n (tt_ctxt ist) of [CaseOp _ _ _ _ _ _] -> pprintDef True n >>= iRenderResult . vsep _ -> coreTerm t t -> coreTerm t where coreTerm t = do (tm, ty) <- elabREPL (recinfo (fileFC "toplevel")) ERHS t iPrintTermWithType (pprintTT [] tm) (pprintTT [] ty) process fn (DocStr (Left n) w) | UN ty <- n, ty == T.pack "Type" = getIState >>= iRenderResult . pprintTypeDoc | otherwise = do ist <- getIState let docs = lookupCtxtName n (idris_docstrings ist) ++ map (\(n,d)-> (n, (d, []))) (lookupCtxtName (modDocN n) (idris_moduledocs ist)) case docs of [] -> iPrintError $ "No documentation for " ++ show n ns -> do toShow <- mapM (showDoc ist) ns iRenderResult (vsep toShow) where showDoc ist (n, d) = do doc <- getDocs n w return $ pprintDocs ist doc modDocN (NS (UN n) ns) = NS modDocName (n:ns) modDocN (UN n) = NS modDocName [n] modDocN _ = sMN 1 "NotFoundForSure" process fn (DocStr (Right c) _) -- constants only have overviews = do ist <- getIState iRenderResult $ pprintConstDocs ist c (constDocs c) process fn Universes = do i <- getIState let cs = idris_constraints i let cslist = S.toAscList cs -- iputStrLn $ showSep "\n" (map show cs) iputStrLn $ showSep "\n" (map show cslist) let n = length cslist iputStrLn $ "(" ++ show n ++ " constraints)" case ucheck cs of Error e -> iPrintError $ pshow i e OK _ -> iPrintResult "Universes OK" process fn (Defn n) = do i <- getIState let head = text "Compiled patterns:" <$> text (show (lookupDef n (tt_ctxt i))) let defs = case lookupCtxt n (idris_patdefs i) of [] -> empty [(d, _)] -> text "Original definiton:" <$> vsep (map (printCase i) d) let tot = case lookupTotal n (tt_ctxt i) of [t] -> showTotal t i _ -> empty iRenderResult $ vsep [head, defs, tot] where printCase i (_, lhs, rhs) = let i' = i { idris_options = (idris_options i) { opt_showimp = True } } in text (showTm i' (delab i lhs)) <+> text "=" <+> text (showTm i' (delab i rhs)) process fn (TotCheck n) = do i <- getIState case lookupNameTotal n (tt_ctxt i) of [] -> iPrintError $ "Unknown operator " ++ show n ts -> do ist <- getIState c <- colourise let ppo = ppOptionIst ist let showN n = annotate (AnnName n Nothing Nothing Nothing) . text $ showName (Just ist) [] ppo False n iRenderResult . vsep . map (\(n, t) -> hang 4 $ showN n <+> text "is" <+> showTotal t i) $ ts process fn (DebugUnify l r) = do (ltm, _) <- elabVal (recinfo (fileFC "toplevel")) ERHS l (rtm, _) <- elabVal (recinfo (fileFC "toplevel")) ERHS r ctxt <- getContext case unify ctxt [] (ltm, Nothing) (rtm, Nothing) [] [] [] [] of OK ans -> iputStrLn (show ans) Error e -> iputStrLn (show e) process fn (DebugInfo n) = do i <- getIState let oi = lookupCtxtName n (idris_optimisation i) when (not (null oi)) $ iputStrLn (show oi) let si = lookupCtxt n (idris_statics i) when (not (null si)) $ iputStrLn (show si) let di = lookupCtxt n (idris_datatypes i) when (not (null di)) $ iputStrLn (show di) let imps = lookupCtxt n (idris_implicits i) when (not (null imps)) $ iputStrLn (show imps) let d = lookupDefAcc n False (tt_ctxt i) when (not (null d)) $ iputStrLn $ "Definition: " ++ (show (head d)) let cg = lookupCtxtName n (idris_callgraph i) i <- getIState let cg' = lookupCtxtName n (idris_callgraph i) sc <- checkSizeChange n iputStrLn $ "Size change: " ++ show sc let fn = lookupCtxtName n (idris_fninfo i) when (not (null cg')) $ do iputStrLn "Call graph:\n" iputStrLn (show cg') when (not (null fn)) $ iputStrLn (show fn) process fn (Search pkgs t) = searchByType pkgs t process fn (CaseSplitAt updatefile l n) = caseSplitAt fn updatefile l n process fn (AddClauseFrom updatefile l n) = addClauseFrom fn updatefile l n process fn (AddProofClauseFrom updatefile l n) = addProofClauseFrom fn updatefile l n process fn (AddMissing updatefile l n) = addMissing fn updatefile l n process fn (MakeWith updatefile l n) = makeWith fn updatefile l n process fn (MakeCase updatefile l n) = makeCase fn updatefile l n process fn (MakeLemma updatefile l n) = makeLemma fn updatefile l n process fn (DoProofSearch updatefile rec l n hints) = doProofSearch fn updatefile rec l n hints Nothing process fn (Spec t) = do (tm, ty) <- elabVal (recinfo (fileFC "toplevel")) ERHS t ctxt <- getContext ist <- getIState let tm' = simplify ctxt [] {- (idris_statics ist) -} tm iPrintResult (show (delab ist tm')) process fn (RmProof n') = do i <- getIState n <- resolveProof n' let proofs = proof_list i case lookup n proofs of Nothing -> iputStrLn "No proof to remove" Just _ -> do removeProof n insertMetavar n iputStrLn $ "Removed proof " ++ show n where insertMetavar :: Name -> Idris () insertMetavar n = do i <- getIState let ms = idris_metavars i putIState $ i { idris_metavars = (n, (Nothing, 0, [], False, False)) : ms } process fn' (AddProof prf) = do fn <- do let fn'' = takeWhile (/= ' ') fn' ex <- runIO $ doesFileExist fn'' let fnExt = fn'' <.> "idr" exExt <- runIO $ doesFileExist fnExt if ex then return fn'' else if exExt then return fnExt else ifail $ "Neither \""++fn''++"\" nor \""++fnExt++"\" exist" let fb = fn ++ "~" runIO $ copyFile fn fb -- make a backup in case something goes wrong! prog <- runIO $ readSource fb i <- getIState let proofs = proof_list i n' <- case prf of Nothing -> case proofs of [] -> ifail "No proof to add" ((x, _) : _) -> return x Just nm -> return nm n <- resolveProof n' case lookup n proofs of Nothing -> iputStrLn "No proof to add" Just (mode, prf) -> do let script = if mode then showRunElab (lit fn) n prf else showProof (lit fn) n prf let prog' = insertScript script ls runIO $ writeSource fn (unlines prog') removeProof n iputStrLn $ "Added proof " ++ show n where ls = (lines prog) process fn (ShowProof n') = do i <- getIState n <- resolveProof n' let proofs = proof_list i case lookup n proofs of Nothing -> iPrintError "No proof to show" Just (m, p) -> iPrintResult $ if m then showRunElab False n p else showProof False n p process fn (Prove mode n') = do ctxt <- getContext ist <- getIState let ns = lookupNames n' ctxt let metavars = mapMaybe (\n -> do c <- lookup n (idris_metavars ist); return (n, c)) ns n <- case metavars of [] -> ierror (Msg $ "Cannot find metavariable " ++ show n') [(n, (_,_,_,False,_))] -> return n [(_, (_,_,_,_,False))] -> ierror (Msg "Can't prove this hole as it depends on other holes") [(_, (_,_,_,True,_))] -> ierror (Msg "Declarations not solvable using prover") ns -> ierror (CantResolveAlts (map fst ns)) prover (toplevelWith fn) mode (lit fn) n -- recheck totality i <- getIState totcheck (fileFC "(input)", n) mapM_ (\ (f,n) -> setTotality n Unchecked) (idris_totcheck i) mapM_ checkDeclTotality (idris_totcheck i) warnTotality process fn (WHNF t) = do (tm, ty) <- elabVal (recinfo (fileFC "toplevel")) ERHS t ctxt <- getContext ist <- getIState let tm' = whnf ctxt [] tm let tmArgs' = whnfArgs ctxt [] tm iPrintResult $ "WHNF: " ++ (show (delab ist tm')) iPrintResult $ "WHNF args: " ++ (show (delab ist tmArgs')) process fn (TestInline t) = do (tm, ty) <- elabVal (recinfo (fileFC "toplevel")) ERHS t ctxt <- getContext ist <- getIState let tm' = inlineTerm ist tm c <- colourise iPrintResult (showTm ist (delab ist tm')) process fn (Execute tm) = idrisCatch (do ist <- getIState (m, _) <- elabVal (recinfo (fileFC "toplevel")) ERHS (elabExec fc tm) (tmpn, tmph) <- runIO $ tempfile "" runIO $ hClose tmph t <- codegen -- gcc adds .exe when it builds windows programs progName <- return $ if isWindows then tmpn ++ ".exe" else tmpn ir <- compile t tmpn (Just m) runIO $ generate t (fst (head (idris_imported ist))) ir case idris_outputmode ist of RawOutput h -> do runIO $ rawSystem progName [] return () IdeMode n h -> runIO . hPutStrLn h $ IdeMode.convSExp "run-program" tmpn n) (\e -> getIState >>= iRenderError . flip pprintErr e) where fc = fileFC "main" process fn (Compile codegen f) | map toLower (takeExtension f) `elem` [".idr", ".lidr", ".idc"] = iPrintError $ "Invalid filename for compiler output \"" ++ f ++"\"" | otherwise = do opts <- getCmdLine let iface = Interface `elem` opts let mainname = sNS (sUN "main") ["Main"] m <- if iface then return Nothing else do (m', _) <- elabVal (recinfo (fileFC "compiler")) ERHS (PApp fc (PRef fc [] (sUN "run__IO")) [pexp $ PRef fc [] mainname]) return (Just m') ir <- compile codegen f m i <- getIState runIO $ generate codegen (fst (head (idris_imported i))) ir where fc = fileFC "main" process fn (LogLvl i) = setLogLevel i process fn (LogCategory cs) = setLogCats cs -- Elaborate as if LHS of a pattern (debug command) process fn (Pattelab t) = do (tm, ty) <- elabVal (recinfo (fileFC "toplevel")) ELHS t iPrintResult $ show tm ++ "\n\n : " ++ show ty process fn (Missing n) = do i <- getIState ppOpts <- fmap ppOptionIst getIState case lookupCtxt n (idris_patdefs i) of [] -> iPrintError $ "Unknown name " ++ show n [(_, tms)] -> iRenderResult (vsep (map (pprintPTerm ppOpts [] [] (idris_infixes i)) tms)) _ -> iPrintError "Ambiguous name" process fn (DynamicLink l) = do i <- getIState let importdirs = opt_importdirs (idris_options i) lib = trim l handle <- lift . lift $ tryLoadLib importdirs lib case handle of Nothing -> iPrintError $ "Could not load dynamic lib \"" ++ l ++ "\"" Just x -> do let libs = idris_dynamic_libs i if x `elem` libs then do logParser 1 ("Tried to load duplicate library " ++ lib_name x) return () else putIState $ i { idris_dynamic_libs = x:libs } where trim = reverse . dropWhile isSpace . reverse . dropWhile isSpace process fn ListDynamic = do i <- getIState iputStrLn "Dynamic libraries:" showLibs $ idris_dynamic_libs i where showLibs [] = return () showLibs ((Lib name _):ls) = do iputStrLn $ "\t" ++ name; showLibs ls process fn Metavars = do ist <- getIState let mvs = map fst (idris_metavars ist) \\ primDefs case mvs of [] -> iPrintError "No global holes to solve" _ -> iPrintResult $ "Global holes:\n\t" ++ show mvs process fn NOP = return () process fn (SetOpt ErrContext) = setErrContext True process fn (UnsetOpt ErrContext) = setErrContext False process fn (SetOpt ShowImpl) = setImpShow True process fn (UnsetOpt ShowImpl) = setImpShow False process fn (SetOpt ShowOrigErr) = setShowOrigErr True process fn (UnsetOpt ShowOrigErr) = setShowOrigErr False process fn (SetOpt AutoSolve) = setAutoSolve True process fn (UnsetOpt AutoSolve) = setAutoSolve False process fn (SetOpt NoBanner) = setNoBanner True process fn (UnsetOpt NoBanner) = setNoBanner False process fn (SetOpt WarnReach) = fmodifyState opts_idrisCmdline $ nub . (WarnReach:) process fn (UnsetOpt WarnReach) = fmodifyState opts_idrisCmdline $ delete WarnReach process fn (SetOpt EvalTypes) = setEvalTypes True process fn (UnsetOpt EvalTypes) = setEvalTypes False process fn (SetOpt DesugarNats) = setDesugarNats True process fn (UnsetOpt DesugarNats) = setDesugarNats False process fn (SetOpt _) = iPrintError "Not a valid option" process fn (UnsetOpt _) = iPrintError "Not a valid option" process fn (SetColour ty c) = setColour ty c process fn ColourOn = do ist <- getIState putIState $ ist { idris_colourRepl = True } process fn ColourOff = do ist <- getIState putIState $ ist { idris_colourRepl = False } process fn ListErrorHandlers = do ist <- getIState iPrintResult $ case idris_errorhandlers ist of [] -> "No registered error handlers" handlers -> "Registered error handlers: " ++ (concat . intersperse ", " . map show) handlers process fn (SetConsoleWidth w) = setWidth w process fn (SetPrinterDepth d) = setDepth d process fn (Apropos pkgs a) = do orig <- getIState when (not (null pkgs)) $ iputStrLn $ "Searching packages: " ++ showSep ", " pkgs mapM_ loadPkgIndex pkgs ist <- getIState let mods = aproposModules ist (T.pack a) let names = apropos ist (T.pack a) let aproposInfo = [ (n, delabTy ist n, fmap (overview . fst) (lookupCtxtExact n (idris_docstrings ist))) | n <- sort names, isUN n ] if (not (null mods)) || (not (null aproposInfo)) then iRenderResult $ vsep (map (\(m, d) -> text "Module" <+> text m <$> ppD ist d <> line) mods) <$> vsep (map (prettyDocumentedIst ist) aproposInfo) else iRenderError $ text "No results found" where isUN (UN _) = True isUN (NS n _) = isUN n isUN _ = False ppD ist = renderDocstring (renderDocTerm (pprintDelab ist) (normaliseAll (tt_ctxt ist) [])) process fn (WhoCalls n) = do calls <- whoCalls n ist <- getIState iRenderResult . vsep $ map (\(n, ns) -> text "Callers of" <+> prettyName True True [] n <$> indent 1 (vsep (map ((text "*" <+>) . align . prettyName True True []) ns))) calls process fn (CallsWho n) = do calls <- callsWho n ist <- getIState iRenderResult . vsep $ map (\(n, ns) -> prettyName True True [] n <+> text "calls:" <$> indent 1 (vsep (map ((text "*" <+>) . align . prettyName True True []) ns))) calls process fn (Browse ns) = do underNSs <- namespacesInNS ns names <- namesInNS ns if null underNSs && null names then iPrintError "Invalid or empty namespace" else do ist <- getIState iRenderResult $ text "Namespaces:" <$> indent 2 (vsep (map (text . showSep ".") underNSs)) <$> text "Names:" <$> indent 2 (vsep (map (\n -> prettyName True False [] n <+> colon <+> (group . align $ pprintDelabTy ist n)) names)) -- IdrisDoc process fn (MakeDoc s) = do istate <- getIState let names = words s parse n | Success x <- runparser (fmap fst name) istate fn n = Right x parse n = Left n (bad, nss) = partitionEithers $ map parse names cd <- runIO getCurrentDirectory let outputDir = cd </> "doc" result <- if null bad then runIO $ generateDocs istate nss outputDir else return . Left $ "Illegal name: " ++ head bad case result of Right _ -> iputStrLn "IdrisDoc generated" Left err -> iPrintError err process fn (PrintDef n) = do result <- pprintDef False n case result of [] -> iPrintError "Not found" outs -> iRenderResult . vsep $ outs -- Show relevant transformation rules for the name 'n' process fn (TransformInfo n) = do i <- getIState let ts = lookupCtxt n (idris_transforms i) let res = map (showTrans i) ts iRenderResult . vsep $ concat res where showTrans :: IState -> [(Term, Term)] -> [Doc OutputAnnotation] showTrans i [] = [] showTrans i ((lhs, rhs) : ts) = let ppTm tm = annotate (AnnTerm [] tm) . pprintPTerm (ppOptionIst i) [] [] [] . delab i $ tm ts' = showTrans i ts in ppTm lhs <+> text " ==> " <+> ppTm rhs : ts' -- iRenderOutput (pretty lhs) -- iputStrLn " ==> " -- iPrintTermWithType (pprintDelab i rhs) -- iputStrLn "---------------" -- showTrans i ts process fn (PPrint fmt width (PRef _ _ n)) = do outs <- pprintDef False n iPrintResult =<< renderExternal fmt width (vsep outs) process fn (PPrint fmt width t) = do (tm, ty) <- elabVal (recinfo (fileFC "toplevel")) ERHS t ctxt <- getContext ist <- getIState let ppo = ppOptionIst ist ty' = normaliseC ctxt [] ty iPrintResult =<< renderExternal fmt width (pprintDelab ist tm) showTotal :: Totality -> IState -> Doc OutputAnnotation showTotal t@(Partial (Other ns)) i = text "possibly not total due to:" <$> vsep (map (showTotalN i) ns) showTotal t@(Partial (Mutual ns)) i = text "possibly not total due to recursive path:" <$> align (group (vsep (punctuate comma (map (\n -> annotate (AnnName n Nothing Nothing Nothing) $ text (show n)) ns)))) showTotal t i = text (show t) showTotalN :: IState -> Name -> Doc OutputAnnotation showTotalN ist n = case lookupTotal n (tt_ctxt ist) of [t] -> showN n <> text ", which is" <+> showTotal t ist _ -> empty where ppo = ppOptionIst ist showN n = annotate (AnnName n Nothing Nothing Nothing) . text $ showName (Just ist) [] ppo False n displayHelp = let vstr = showVersion getIdrisVersionNoGit in "\nIdris version " ++ vstr ++ "\n" ++ "--------------" ++ map (\x -> '-') vstr ++ "\n\n" ++ concatMap cmdInfo helphead ++ concatMap cmdInfo help where cmdInfo (cmds, args, text) = " " ++ col 16 12 (showSep " " cmds) (show args) text col c1 c2 l m r = l ++ take (c1 - length l) (repeat ' ') ++ m ++ take (c2 - length m) (repeat ' ') ++ r ++ "\n" pprintDef :: Bool -> Name -> Idris [Doc OutputAnnotation] pprintDef asCore n = do ist <- getIState ctxt <- getContext let ambiguous = length (lookupNames n ctxt) > 1 patdefs = idris_patdefs ist tyinfo = idris_datatypes ist if asCore then return $ map (ppCoreDef ist) (lookupCtxtName n patdefs) else return $ map (ppDef ambiguous ist) (lookupCtxtName n patdefs) ++ map (ppTy ambiguous ist) (lookupCtxtName n tyinfo) ++ map (ppCon ambiguous ist) (filter (flip isDConName ctxt) (lookupNames n ctxt)) where ppCoreDef :: IState -> (Name, ([([(Name, Term)], Term, Term)], [PTerm])) -> Doc OutputAnnotation ppCoreDef ist (n, (clauses, missing)) = case lookupTy n (tt_ctxt ist) of [] -> error "Attempted pprintDef of TT of thing that doesn't exist" (ty:_) -> prettyName True True [] n <+> colon <+> align (annotate (AnnTerm [] ty) (pprintTT [] ty)) <$> vsep (map (\(vars, lhs, rhs) -> pprintTTClause vars lhs rhs) clauses) ppDef :: Bool -> IState -> (Name, ([([(Name, Term)], Term, Term)], [PTerm])) -> Doc OutputAnnotation ppDef amb ist (n, (clauses, missing)) = prettyName True amb [] n <+> colon <+> align (pprintDelabTy ist n) <$> ppClauses ist (map (\(ns, lhs, rhs) -> (map fst ns, lhs, rhs)) clauses) <> ppMissing missing ppClauses ist [] = text "No clauses." ppClauses ist cs = vsep (map pp cs) where pp (vars, lhs, rhs) = let ppTm t = annotate (AnnTerm (zip vars (repeat False)) t) . pprintPTerm (ppOptionIst ist) (zip vars (repeat False)) [] (idris_infixes ist) . delab ist $ t in group $ ppTm lhs <+> text "=" <$> (group . align . hang 2 $ ppTm rhs) ppMissing _ = empty ppTy :: Bool -> IState -> (Name, TypeInfo) -> Doc OutputAnnotation ppTy amb ist (n, TI constructors isCodata _ _ _) = kwd key <+> prettyName True amb [] n <+> colon <+> align (pprintDelabTy ist n) <+> kwd "where" <$> indent 2 (vsep (map (ppCon False ist) constructors)) where key | isCodata = "codata" | otherwise = "data" kwd = annotate AnnKeyword . text ppCon amb ist n = prettyName True amb [] n <+> colon <+> align (pprintDelabTy ist n) helphead = [ (["Command"], SpecialHeaderArg, "Purpose"), ([""], NoArg, "") ] replSettings :: Maybe FilePath -> Settings Idris replSettings hFile = setComplete replCompletion $ defaultSettings { historyFile = hFile }
eklavya/Idris-dev
src/Idris/REPL.hs
bsd-3-clause
69,704
0
22
25,821
22,189
10,782
11,407
1,361
73
{-| Module : Game.GoreAndAsh.Core.Dispense Description : Helpers for item dispensing from collections. Copyright : (c) Anton Gushcha, 2016-2017 License : BSD3 Maintainer : ncrashed@gmail.com Stability : experimental Portability : POSIX -} module Game.GoreAndAsh.Core.Dispense( ItemRoller , itemRoller ) where import Control.Monad.IO.Class import Game.GoreAndAsh.Core.ExternalRef import Game.GoreAndAsh.Core.Monad import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as NE -- | Item roller contains dynamic of current element and action to switch to next -- item type ItemRoller t a = (Dynamic t a, IO ()) -- | Create a item chooser from given list, returns dynamic with current item -- and action to change it. itemRoller :: (Reflex t, MonadHold t m, TriggerEvent t m, MonadIO m) => NonEmpty a -> m (ItemRoller t a) itemRoller as = do ref <- newExternalRef (NE.toList as, []) let getCurItem xs = case xs of [] -> error "itemRoller: impossible" (x : _) -> x curDyn <- fmap (getCurItem . fst) <$> externalRefDynamic ref let updRoller = modifyExternalRef ref $ \(xs, ys) -> case xs of [] -> ((reverse ys, []), ()) [x] -> ((reverse ys, [x]), ()) (x : xs') -> ((xs', x : ys), ()) return (curDyn, updRoller)
Teaspot-Studio/gore-and-ash
src/Game/GoreAndAsh/Core/Dispense.hs
bsd-3-clause
1,312
0
17
281
365
203
162
21
4
{-# LANGUAGE BangPatterns #-} module Network.Wai.Handler.Warp.HashMap where import Data.Hashable (hash) import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as I import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Prelude hiding (lookup) ---------------------------------------------------------------- -- | 'HashMap' is used for cache of file information. -- Hash values of file pathes are used as outer keys. -- Because negative entries are also contained, -- a bad guy can intentionally cause the hash collison. -- So, 'Map' is used internally to prevent -- the hash collision attack. newtype HashMap v = HashMap (IntMap (Map FilePath v)) ---------------------------------------------------------------- empty :: HashMap v empty = HashMap I.empty isEmpty :: HashMap v -> Bool isEmpty (HashMap hm) = I.null hm ---------------------------------------------------------------- insert :: FilePath -> v -> HashMap v -> HashMap v insert path v (HashMap hm) = HashMap $ I.insertWith M.union (hash path) (M.singleton path v) hm lookup :: FilePath -> HashMap v -> Maybe v lookup path (HashMap hm) = I.lookup (hash path) hm >>= M.lookup path
kazu-yamamoto/wai
warp/Network/Wai/Handler/Warp/HashMap.hs
mit
1,196
0
9
182
281
157
124
18
1
-- Resource getter. Used by everything else module Haskmon.Resource(getResource) where import Data.Aeson import Network.Http.Client import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 -- | Host of the API host :: String host = "http://pokeapi.co/" -- | Uri of the resource type Uri = String -- | GET the resource from the URI and parse it into one of the "Haskmon.Types". -- Fails if the parsing fails (ie: the library needs to be updated). getResource :: FromJSON a => Uri -> IO a getResource uri = decodeAndErr <$> get (B8.pack uri') concatHandler where uri' = host ++ uri decodeAndErr :: FromJSON a => B.ByteString -> a decodeAndErr = either decodeErr id . eitherDecodeStrict' decodeErr err = error $ "Error parsing resource " ++ uri' ++ ": " ++ err
bitemyapp/Haskmon
src/Haskmon/Resource.hs
mit
838
0
10
184
171
97
74
14
1
-- | <http://strava.github.io/api/v3/oauth/> module Strive.Actions.Authentication ( buildAuthorizeUrl , exchangeToken , deauthorize ) where import Data.ByteString.Char8 (unpack) import Network.HTTP.Types (Query, renderQuery, toQuery) import Strive.Aliases (ApplicationId, ApplicationSecret, AuthorizationCode, RedirectUri, Result) import Strive.Client (Client, buildClient) import Strive.Internal.HTTP (post) import Strive.Options (BuildAuthorizeUrlOptions) import Strive.Types (DeauthorizationResponse, TokenExchangeResponse) -- | <http://strava.github.io/api/v3/oauth/#get-authorize> buildAuthorizeUrl :: ApplicationId -> RedirectUri -> BuildAuthorizeUrlOptions -> String buildAuthorizeUrl clientId redirectUri options = "https://www.strava.com/oauth/authorize" ++ unpack (renderQuery True query) where query = toQuery [ ("client_id", show clientId) , ("redirect_uri", redirectUri) , ("response_type", "code") ] ++ toQuery options -- | <http://strava.github.io/api/v3/oauth/#post-token> exchangeToken :: ApplicationId -> ApplicationSecret -> AuthorizationCode -> IO (Result TokenExchangeResponse) exchangeToken clientId clientSecret code = do client <- buildClient Nothing post client resource query where resource = "oauth/token" query = [ ("client_id", show clientId) , ("client_secret", clientSecret) , ("code", code) ] -- | <http://strava.github.io/api/v3/oauth/#deauthorize> deauthorize :: Client -> IO (Result DeauthorizationResponse) deauthorize client = post client resource query where resource = "oauth/deauthorize" query = [] :: Query
liskin/strive
library/Strive/Actions/Authentication.hs
mit
1,634
0
11
240
360
205
155
33
1
{-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Main -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Main (main) where import Test.Tasty import Test.AWS.CloudSearchDomains import Test.AWS.CloudSearchDomains.Internal main :: IO () main = defaultMain $ testGroup "CloudSearchDomains" [ testGroup "tests" tests , testGroup "fixtures" fixtures ]
fmapfmapfmap/amazonka
amazonka-cloudsearch-domains/test/Main.hs
mpl-2.0
567
0
8
103
76
47
29
9
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.OpsWorks.DeregisterInstance -- 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. -- | Deregister a registered Amazon EC2 or on-premises instance. This action -- removes the instance from the stack and returns it to your control. This -- action can not be used with instances that were created with AWS OpsWorks. -- -- Required Permissions: To use this action, an IAM user must have a Manage -- permissions level for the stack or an attached policy that explicitly grants -- permissions. For more information on user permissions, see <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing UserPermissions>. -- -- <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_DeregisterInstance.html> module Network.AWS.OpsWorks.DeregisterInstance ( -- * Request DeregisterInstance -- ** Request constructor , deregisterInstance -- ** Request lenses , di1InstanceId -- * Response , DeregisterInstanceResponse -- ** Response constructor , deregisterInstanceResponse ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.OpsWorks.Types import qualified GHC.Exts newtype DeregisterInstance = DeregisterInstance { _di1InstanceId :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'DeregisterInstance' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'di1InstanceId' @::@ 'Text' -- deregisterInstance :: Text -- ^ 'di1InstanceId' -> DeregisterInstance deregisterInstance p1 = DeregisterInstance { _di1InstanceId = p1 } -- | The instance ID. di1InstanceId :: Lens' DeregisterInstance Text di1InstanceId = lens _di1InstanceId (\s a -> s { _di1InstanceId = a }) data DeregisterInstanceResponse = DeregisterInstanceResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'DeregisterInstanceResponse' constructor. deregisterInstanceResponse :: DeregisterInstanceResponse deregisterInstanceResponse = DeregisterInstanceResponse instance ToPath DeregisterInstance where toPath = const "/" instance ToQuery DeregisterInstance where toQuery = const mempty instance ToHeaders DeregisterInstance instance ToJSON DeregisterInstance where toJSON DeregisterInstance{..} = object [ "InstanceId" .= _di1InstanceId ] instance AWSRequest DeregisterInstance where type Sv DeregisterInstance = OpsWorks type Rs DeregisterInstance = DeregisterInstanceResponse request = post "DeregisterInstance" response = nullResponse DeregisterInstanceResponse
romanb/amazonka
amazonka-opsworks/gen/Network/AWS/OpsWorks/DeregisterInstance.hs
mpl-2.0
3,571
0
9
710
362
223
139
48
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.CloudFormation.CancelUpdateStack -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Cancels an update on the specified stack. If the call completes -- successfully, the stack will roll back the update and revert to the -- previous stack configuration. -- -- Only stacks that are in the UPDATE_IN_PROGRESS state can be canceled. -- -- /See:/ <http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CancelUpdateStack.html AWS API Reference> for CancelUpdateStack. module Network.AWS.CloudFormation.CancelUpdateStack ( -- * Creating a Request cancelUpdateStack , CancelUpdateStack -- * Request Lenses , cusStackName -- * Destructuring the Response , cancelUpdateStackResponse , CancelUpdateStackResponse ) where import Network.AWS.CloudFormation.Types import Network.AWS.CloudFormation.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | The input for CancelUpdateStack action. -- -- /See:/ 'cancelUpdateStack' smart constructor. newtype CancelUpdateStack = CancelUpdateStack' { _cusStackName :: Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CancelUpdateStack' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cusStackName' cancelUpdateStack :: Text -- ^ 'cusStackName' -> CancelUpdateStack cancelUpdateStack pStackName_ = CancelUpdateStack' { _cusStackName = pStackName_ } -- | The name or the unique stack ID that is associated with the stack. cusStackName :: Lens' CancelUpdateStack Text cusStackName = lens _cusStackName (\ s a -> s{_cusStackName = a}); instance AWSRequest CancelUpdateStack where type Rs CancelUpdateStack = CancelUpdateStackResponse request = postQuery cloudFormation response = receiveNull CancelUpdateStackResponse' instance ToHeaders CancelUpdateStack where toHeaders = const mempty instance ToPath CancelUpdateStack where toPath = const "/" instance ToQuery CancelUpdateStack where toQuery CancelUpdateStack'{..} = mconcat ["Action" =: ("CancelUpdateStack" :: ByteString), "Version" =: ("2010-05-15" :: ByteString), "StackName" =: _cusStackName] -- | /See:/ 'cancelUpdateStackResponse' smart constructor. data CancelUpdateStackResponse = CancelUpdateStackResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CancelUpdateStackResponse' with the minimum fields required to make a request. -- cancelUpdateStackResponse :: CancelUpdateStackResponse cancelUpdateStackResponse = CancelUpdateStackResponse'
fmapfmapfmap/amazonka
amazonka-cloudformation/gen/Network/AWS/CloudFormation/CancelUpdateStack.hs
mpl-2.0
3,379
0
9
643
369
228
141
51
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="fil-PH"> <title>Pagscript ng Ruby</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Mga Nilalaman</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Indeks</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Maghanap</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Mga Paborito</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/jruby/src/main/javahelp/org/zaproxy/zap/extension/jruby/resources/help_fil_PH/helpset_fil_PH.hs
apache-2.0
975
84
52
160
400
210
190
-1
-1
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- -- (c) The University of Glasgow 2006 -- -- The purpose of this module is to transform an HsExpr into a CoreExpr which -- when evaluated, returns a (Meta.Q Meta.Exp) computation analogous to the -- input HsExpr. We do this in the DsM monad, which supplies access to -- CoreExpr's of the "smart constructors" of the Meta.Exp datatype. -- -- It also defines a bunch of knownKeyNames, in the same way as is done -- in prelude/PrelNames. It's much more convenient to do it here, because -- otherwise we have to recompile PrelNames whenever we add a Name, which is -- a Royal Pain (triggers other recompilation). ----------------------------------------------------------------------------- module DsMeta( dsBracket, templateHaskellNames, qTyConName, nameTyConName, liftName, liftStringName, expQTyConName, patQTyConName, decQTyConName, decsQTyConName, typeQTyConName, decTyConName, typeTyConName, mkNameG_dName, mkNameG_vName, mkNameG_tcName, quoteExpName, quotePatName, quoteDecName, quoteTypeName, tExpTyConName, tExpDataConName, unTypeName, unTypeQName, unsafeTExpCoerceName ) where #include "HsVersions.h" import {-# SOURCE #-} DsExpr ( dsExpr ) import MatchLit import DsMonad import qualified Language.Haskell.TH as TH import HsSyn import Class import PrelNames -- To avoid clashes with DsMeta.varName we must make a local alias for -- OccName.varName we do this by removing varName from the import of -- OccName above, making a qualified instance of OccName and using -- OccNameAlias.varName where varName ws previously used in this file. import qualified OccName( isDataOcc, isVarOcc, isTcOcc, varName, tcName, dataName ) import Module import Id import Name hiding( isVarOcc, isTcOcc, varName, tcName ) import NameEnv import TcType import TyCon import TysWiredIn import TysPrim ( liftedTypeKindTyConName, constraintKindTyConName ) import CoreSyn import MkCore import CoreUtils import SrcLoc import Unique import BasicTypes import Outputable import Bag import DynFlags import FastString import ForeignCall import Util import Data.Maybe import Control.Monad import Data.List ----------------------------------------------------------------------------- dsBracket :: HsBracket Name -> [PendingTcSplice] -> DsM CoreExpr -- Returns a CoreExpr of type TH.ExpQ -- The quoted thing is parameterised over Name, even though it has -- been type checked. We don't want all those type decorations! dsBracket brack splices = dsExtendMetaEnv new_bit (do_brack brack) where new_bit = mkNameEnv [(n, Splice (unLoc e)) | (n, e) <- splices] do_brack (VarBr _ n) = do { MkC e1 <- lookupOcc n ; return e1 } do_brack (ExpBr e) = do { MkC e1 <- repLE e ; return e1 } do_brack (PatBr p) = do { MkC p1 <- repTopP p ; return p1 } do_brack (TypBr t) = do { MkC t1 <- repLTy t ; return t1 } do_brack (DecBrG gp) = do { MkC ds1 <- repTopDs gp ; return ds1 } do_brack (DecBrL _) = panic "dsBracket: unexpected DecBrL" do_brack (TExpBr e) = do { MkC e1 <- repLE e ; return e1 } {- -------------- Examples -------------------- [| \x -> x |] ====> gensym (unpackString "x"#) `bindQ` \ x1::String -> lam (pvar x1) (var x1) [| \x -> $(f [| x |]) |] ====> gensym (unpackString "x"#) `bindQ` \ x1::String -> lam (pvar x1) (f (var x1)) -} ------------------------------------------------------- -- Declarations ------------------------------------------------------- repTopP :: LPat Name -> DsM (Core TH.PatQ) repTopP pat = do { ss <- mkGenSyms (collectPatBinders pat) ; pat' <- addBinds ss (repLP pat) ; wrapGenSyms ss pat' } repTopDs :: HsGroup Name -> DsM (Core (TH.Q [TH.Dec])) repTopDs group = do { let { tv_bndrs = hsSigTvBinders (hs_valds group) ; bndrs = tv_bndrs ++ hsGroupBinders group } ; ss <- mkGenSyms bndrs ; -- Bind all the names mainly to avoid repeated use of explicit strings. -- Thus we get -- do { t :: String <- genSym "T" ; -- return (Data t [] ...more t's... } -- The other important reason is that the output must mention -- only "T", not "Foo:T" where Foo is the current module decls <- addBinds ss (do { fix_ds <- mapM repFixD (hs_fixds group) ; val_ds <- rep_val_binds (hs_valds group) ; tycl_ds <- mapM repTyClD (tyClGroupConcat (hs_tyclds group)) ; role_ds <- mapM repRoleD (concatMap group_roles (hs_tyclds group)) ; inst_ds <- mapM repInstD (hs_instds group) ; rule_ds <- mapM repRuleD (hs_ruleds group) ; for_ds <- mapM repForD (hs_fords group) ; -- more needed return (de_loc $ sort_by_loc $ val_ds ++ catMaybes tycl_ds ++ role_ds ++ fix_ds ++ inst_ds ++ rule_ds ++ for_ds) }) ; decl_ty <- lookupType decQTyConName ; let { core_list = coreList' decl_ty decls } ; dec_ty <- lookupType decTyConName ; q_decs <- repSequenceQ dec_ty core_list ; wrapGenSyms ss q_decs } hsSigTvBinders :: HsValBinds Name -> [Name] -- See Note [Scoped type variables in bindings] hsSigTvBinders binds = [hsLTyVarName tv | L _ (TypeSig _ (L _ (HsForAllTy Explicit qtvs _ _))) <- sigs , tv <- hsQTvBndrs qtvs] where sigs = case binds of ValBindsIn _ sigs -> sigs ValBindsOut _ sigs -> sigs {- Notes Note [Scoped type variables in bindings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f :: forall a. a -> a f x = x::a Here the 'forall a' brings 'a' into scope over the binding group. To achieve this we a) Gensym a binding for 'a' at the same time as we do one for 'f' collecting the relevant binders with hsSigTvBinders b) When processing the 'forall', don't gensym The relevant places are signposted with references to this Note Note [Binders and occurrences] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we desugar [d| data T = MkT |] we want to get Data "T" [] [Con "MkT" []] [] and *not* Data "Foo:T" [] [Con "Foo:MkT" []] [] That is, the new data decl should fit into whatever new module it is asked to fit in. We do *not* clone, though; no need for this: Data "T79" .... But if we see this: data T = MkT foo = reifyDecl T then we must desugar to foo = Data "Foo:T" [] [Con "Foo:MkT" []] [] So in repTopDs we bring the binders into scope with mkGenSyms and addBinds. And we use lookupOcc, rather than lookupBinder in repTyClD and repC. -} -- represent associated family instances -- repTyClD :: LTyClDecl Name -> DsM (Maybe (SrcSpan, Core TH.DecQ)) repTyClD (L loc (FamDecl { tcdFam = fam })) = liftM Just $ repFamilyDecl (L loc fam) repTyClD (L loc (SynDecl { tcdLName = tc, tcdTyVars = tvs, tcdRhs = rhs })) = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] ; dec <- addTyClTyVarBinds tvs $ \bndrs -> repSynDecl tc1 bndrs rhs ; return (Just (loc, dec)) } repTyClD (L loc (DataDecl { tcdLName = tc, tcdTyVars = tvs, tcdDataDefn = defn })) = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] ; tc_tvs <- mk_extra_tvs tc tvs defn ; dec <- addTyClTyVarBinds tc_tvs $ \bndrs -> repDataDefn tc1 bndrs Nothing (hsLTyVarNames tc_tvs) defn ; return (Just (loc, dec)) } repTyClD (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls, tcdTyVars = tvs, tcdFDs = fds, tcdSigs = sigs, tcdMeths = meth_binds, tcdATs = ats, tcdATDefs = [] })) = do { cls1 <- lookupLOcc cls -- See note [Binders and occurrences] ; dec <- addTyVarBinds tvs $ \bndrs -> do { cxt1 <- repLContext cxt ; sigs1 <- rep_sigs sigs ; binds1 <- rep_binds meth_binds ; fds1 <- repLFunDeps fds ; ats1 <- repFamilyDecls ats ; decls1 <- coreList decQTyConName (ats1 ++ sigs1 ++ binds1) ; repClass cxt1 cls1 bndrs fds1 decls1 } ; return $ Just (loc, dec) } -- Un-handled cases repTyClD (L loc d) = putSrcSpanDs loc $ do { warnDs (hang ds_msg 4 (ppr d)) ; return Nothing } ------------------------- repRoleD :: LRoleAnnotDecl Name -> DsM (SrcSpan, Core TH.DecQ) repRoleD (L loc (RoleAnnotDecl tycon roles)) = do { tycon1 <- lookupLOcc tycon ; roles1 <- mapM repRole roles ; roles2 <- coreList roleTyConName roles1 ; dec <- repRoleAnnotD tycon1 roles2 ; return (loc, dec) } ------------------------- repDataDefn :: Core TH.Name -> Core [TH.TyVarBndr] -> Maybe (Core [TH.TypeQ]) -> [Name] -> HsDataDefn Name -> DsM (Core TH.DecQ) repDataDefn tc bndrs opt_tys tv_names (HsDataDefn { dd_ND = new_or_data, dd_ctxt = cxt , dd_cons = cons, dd_derivs = mb_derivs }) = do { cxt1 <- repLContext cxt ; derivs1 <- repDerivs mb_derivs ; case new_or_data of NewType -> do { con1 <- repC tv_names (head cons) ; repNewtype cxt1 tc bndrs opt_tys con1 derivs1 } DataType -> do { cons1 <- repList conQTyConName (repC tv_names) cons ; repData cxt1 tc bndrs opt_tys cons1 derivs1 } } repSynDecl :: Core TH.Name -> Core [TH.TyVarBndr] -> LHsType Name -> DsM (Core TH.DecQ) repSynDecl tc bndrs ty = do { ty1 <- repLTy ty ; repTySyn tc bndrs ty1 } repFamilyDecl :: LFamilyDecl Name -> DsM (SrcSpan, Core TH.DecQ) repFamilyDecl (L loc (FamilyDecl { fdInfo = info, fdLName = tc, fdTyVars = tvs, fdKindSig = opt_kind })) = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] ; dec <- addTyClTyVarBinds tvs $ \bndrs -> case (opt_kind, info) of (Nothing, ClosedTypeFamily eqns) -> do { eqns1 <- mapM repTyFamEqn eqns ; eqns2 <- coreList tySynEqnQTyConName eqns1 ; repClosedFamilyNoKind tc1 bndrs eqns2 } (Just ki, ClosedTypeFamily eqns) -> do { eqns1 <- mapM repTyFamEqn eqns ; eqns2 <- coreList tySynEqnQTyConName eqns1 ; ki1 <- repLKind ki ; repClosedFamilyKind tc1 bndrs ki1 eqns2 } (Nothing, _) -> do { info' <- repFamilyInfo info ; repFamilyNoKind info' tc1 bndrs } (Just ki, _) -> do { info' <- repFamilyInfo info ; ki1 <- repLKind ki ; repFamilyKind info' tc1 bndrs ki1 } ; return (loc, dec) } repFamilyDecls :: [LFamilyDecl Name] -> DsM [Core TH.DecQ] repFamilyDecls fds = liftM de_loc (mapM repFamilyDecl fds) ------------------------- mk_extra_tvs :: Located Name -> LHsTyVarBndrs Name -> HsDataDefn Name -> DsM (LHsTyVarBndrs Name) -- If there is a kind signature it must be of form -- k1 -> .. -> kn -> * -- Return type variables [tv1:k1, tv2:k2, .., tvn:kn] mk_extra_tvs tc tvs defn | HsDataDefn { dd_kindSig = Just hs_kind } <- defn = do { extra_tvs <- go hs_kind ; return (tvs { hsq_tvs = hsq_tvs tvs ++ extra_tvs }) } | otherwise = return tvs where go :: LHsKind Name -> DsM [LHsTyVarBndr Name] go (L loc (HsFunTy kind rest)) = do { uniq <- newUnique ; let { occ = mkTyVarOccFS (fsLit "t") ; nm = mkInternalName uniq occ loc ; hs_tv = L loc (KindedTyVar nm kind) } ; hs_tvs <- go rest ; return (hs_tv : hs_tvs) } go (L _ (HsTyVar n)) | n == liftedTypeKindTyConName = return [] go _ = failWithDs (ptext (sLit "Malformed kind signature for") <+> ppr tc) ------------------------- -- represent fundeps -- repLFunDeps :: [Located (FunDep Name)] -> DsM (Core [TH.FunDep]) repLFunDeps fds = repList funDepTyConName repLFunDep fds repLFunDep :: Located (FunDep Name) -> DsM (Core TH.FunDep) repLFunDep (L _ (xs, ys)) = do xs' <- repList nameTyConName lookupBinder xs ys' <- repList nameTyConName lookupBinder ys repFunDep xs' ys' -- represent family declaration flavours -- repFamilyInfo :: FamilyInfo Name -> DsM (Core TH.FamFlavour) repFamilyInfo OpenTypeFamily = rep2 typeFamName [] repFamilyInfo DataFamily = rep2 dataFamName [] repFamilyInfo ClosedTypeFamily {} = panic "repFamilyInfo" -- Represent instance declarations -- repInstD :: LInstDecl Name -> DsM (SrcSpan, Core TH.DecQ) repInstD (L loc (TyFamInstD { tfid_inst = fi_decl })) = do { dec <- repTyFamInstD fi_decl ; return (loc, dec) } repInstD (L loc (DataFamInstD { dfid_inst = fi_decl })) = do { dec <- repDataFamInstD fi_decl ; return (loc, dec) } repInstD (L loc (ClsInstD { cid_inst = cls_decl })) = do { dec <- repClsInstD cls_decl ; return (loc, dec) } repClsInstD :: ClsInstDecl Name -> DsM (Core TH.DecQ) repClsInstD (ClsInstDecl { cid_poly_ty = ty, cid_binds = binds , cid_sigs = prags, cid_tyfam_insts = ats , cid_datafam_insts = adts }) = addTyVarBinds tvs $ \_ -> -- We must bring the type variables into scope, so their -- occurrences don't fail, even though the binders don't -- appear in the resulting data structure -- -- But we do NOT bring the binders of 'binds' into scope -- because they are properly regarded as occurrences -- For example, the method names should be bound to -- the selector Ids, not to fresh names (Trac #5410) -- do { cxt1 <- repContext cxt ; cls_tcon <- repTy (HsTyVar (unLoc cls)) ; cls_tys <- repLTys tys ; inst_ty1 <- repTapps cls_tcon cls_tys ; binds1 <- rep_binds binds ; prags1 <- rep_sigs prags ; ats1 <- mapM (repTyFamInstD . unLoc) ats ; adts1 <- mapM (repDataFamInstD . unLoc) adts ; decls <- coreList decQTyConName (ats1 ++ adts1 ++ binds1 ++ prags1) ; repInst cxt1 inst_ty1 decls } where Just (tvs, cxt, cls, tys) = splitLHsInstDeclTy_maybe ty repTyFamInstD :: TyFamInstDecl Name -> DsM (Core TH.DecQ) repTyFamInstD decl@(TyFamInstDecl { tfid_eqn = eqn }) = do { let tc_name = tyFamInstDeclLName decl ; tc <- lookupLOcc tc_name -- See note [Binders and occurrences] ; eqn1 <- repTyFamEqn eqn ; repTySynInst tc eqn1 } repTyFamEqn :: LTyFamInstEqn Name -> DsM (Core TH.TySynEqnQ) repTyFamEqn (L loc (TyFamEqn { tfe_pats = HsWB { hswb_cts = tys , hswb_kvs = kv_names , hswb_tvs = tv_names } , tfe_rhs = rhs })) = do { let hs_tvs = HsQTvs { hsq_kvs = kv_names , hsq_tvs = userHsTyVarBndrs loc tv_names } -- Yuk ; addTyClTyVarBinds hs_tvs $ \ _ -> do { tys1 <- repLTys tys ; tys2 <- coreList typeQTyConName tys1 ; rhs1 <- repLTy rhs ; repTySynEqn tys2 rhs1 } } repDataFamInstD :: DataFamInstDecl Name -> DsM (Core TH.DecQ) repDataFamInstD (DataFamInstDecl { dfid_tycon = tc_name , dfid_pats = HsWB { hswb_cts = tys, hswb_kvs = kv_names, hswb_tvs = tv_names } , dfid_defn = defn }) = do { tc <- lookupLOcc tc_name -- See note [Binders and occurrences] ; let loc = getLoc tc_name hs_tvs = HsQTvs { hsq_kvs = kv_names, hsq_tvs = userHsTyVarBndrs loc tv_names } -- Yuk ; addTyClTyVarBinds hs_tvs $ \ bndrs -> do { tys1 <- repList typeQTyConName repLTy tys ; repDataDefn tc bndrs (Just tys1) tv_names defn } } repForD :: Located (ForeignDecl Name) -> DsM (SrcSpan, Core TH.DecQ) repForD (L loc (ForeignImport name typ _ (CImport cc s mch cis))) = do MkC name' <- lookupLOcc name MkC typ' <- repLTy typ MkC cc' <- repCCallConv cc MkC s' <- repSafety s cis' <- conv_cimportspec cis MkC str <- coreStringLit (static ++ chStr ++ cis') dec <- rep2 forImpDName [cc', s', str, name', typ'] return (loc, dec) where conv_cimportspec (CLabel cls) = notHandled "Foreign label" (doubleQuotes (ppr cls)) conv_cimportspec (CFunction DynamicTarget) = return "dynamic" conv_cimportspec (CFunction (StaticTarget fs _ True)) = return (unpackFS fs) conv_cimportspec (CFunction (StaticTarget _ _ False)) = panic "conv_cimportspec: values not supported yet" conv_cimportspec CWrapper = return "wrapper" static = case cis of CFunction (StaticTarget _ _ _) -> "static " _ -> "" chStr = case mch of Nothing -> "" Just (Header h) -> unpackFS h ++ " " repForD decl = notHandled "Foreign declaration" (ppr decl) repCCallConv :: CCallConv -> DsM (Core TH.Callconv) repCCallConv CCallConv = rep2 cCallName [] repCCallConv StdCallConv = rep2 stdCallName [] repCCallConv callConv = notHandled "repCCallConv" (ppr callConv) repSafety :: Safety -> DsM (Core TH.Safety) repSafety PlayRisky = rep2 unsafeName [] repSafety PlayInterruptible = rep2 interruptibleName [] repSafety PlaySafe = rep2 safeName [] repFixD :: LFixitySig Name -> DsM (SrcSpan, Core TH.DecQ) repFixD (L loc (FixitySig name (Fixity prec dir))) = do { MkC name' <- lookupLOcc name ; MkC prec' <- coreIntLit prec ; let rep_fn = case dir of InfixL -> infixLDName InfixR -> infixRDName InfixN -> infixNDName ; dec <- rep2 rep_fn [prec', name'] ; return (loc, dec) } repRuleD :: LRuleDecl Name -> DsM (SrcSpan, Core TH.DecQ) repRuleD (L loc (HsRule n act bndrs lhs _ rhs _)) = do { let bndr_names = concatMap ruleBndrNames bndrs ; ss <- mkGenSyms bndr_names ; rule1 <- addBinds ss $ do { bndrs' <- repList ruleBndrQTyConName repRuleBndr bndrs ; n' <- coreStringLit $ unpackFS n ; act' <- repPhases act ; lhs' <- repLE lhs ; rhs' <- repLE rhs ; repPragRule n' bndrs' lhs' rhs' act' } ; rule2 <- wrapGenSyms ss rule1 ; return (loc, rule2) } ruleBndrNames :: RuleBndr Name -> [Name] ruleBndrNames (RuleBndr n) = [unLoc n] ruleBndrNames (RuleBndrSig n (HsWB { hswb_kvs = kvs, hswb_tvs = tvs })) = unLoc n : kvs ++ tvs repRuleBndr :: RuleBndr Name -> DsM (Core TH.RuleBndrQ) repRuleBndr (RuleBndr n) = do { MkC n' <- lookupLBinder n ; rep2 ruleVarName [n'] } repRuleBndr (RuleBndrSig n (HsWB { hswb_cts = ty })) = do { MkC n' <- lookupLBinder n ; MkC ty' <- repLTy ty ; rep2 typedRuleVarName [n', ty'] } ds_msg :: SDoc ds_msg = ptext (sLit "Cannot desugar this Template Haskell declaration:") ------------------------------------------------------- -- Constructors ------------------------------------------------------- repC :: [Name] -> LConDecl Name -> DsM (Core TH.ConQ) repC _ (L _ (ConDecl { con_name = con, con_qvars = con_tvs, con_cxt = L _ [] , con_details = details, con_res = ResTyH98 })) | null (hsQTvBndrs con_tvs) = do { con1 <- lookupLOcc con -- See Note [Binders and occurrences] ; repConstr con1 details } repC tvs (L _ (ConDecl { con_name = con , con_qvars = con_tvs, con_cxt = L _ ctxt , con_details = details , con_res = res_ty })) = do { (eq_ctxt, con_tv_subst) <- mkGadtCtxt tvs res_ty ; let ex_tvs = HsQTvs { hsq_kvs = filterOut (in_subst con_tv_subst) (hsq_kvs con_tvs) , hsq_tvs = filterOut (in_subst con_tv_subst . hsLTyVarName) (hsq_tvs con_tvs) } ; binds <- mapM dupBinder con_tv_subst ; dsExtendMetaEnv (mkNameEnv binds) $ -- Binds some of the con_tvs addTyVarBinds ex_tvs $ \ ex_bndrs -> -- Binds the remaining con_tvs do { con1 <- lookupLOcc con -- See Note [Binders and occurrences] ; c' <- repConstr con1 details ; ctxt' <- repContext (eq_ctxt ++ ctxt) ; rep2 forallCName [unC ex_bndrs, unC ctxt', unC c'] } } in_subst :: [(Name,Name)] -> Name -> Bool in_subst [] _ = False in_subst ((n',_):ns) n = n==n' || in_subst ns n mkGadtCtxt :: [Name] -- Tyvars of the data type -> ResType (LHsType Name) -> DsM (HsContext Name, [(Name,Name)]) -- Given a data type in GADT syntax, figure out the equality -- context, so that we can represent it with an explicit -- equality context, because that is the only way to express -- the GADT in TH syntax -- -- Example: -- data T a b c where { MkT :: forall d e. d -> e -> T d [e] e -- mkGadtCtxt [a,b,c] [d,e] (T d [e] e) -- returns -- (b~[e], c~e), [d->a] -- -- This function is fiddly, but not really hard mkGadtCtxt _ ResTyH98 = return ([], []) mkGadtCtxt data_tvs (ResTyGADT res_ty) | Just (_, tys) <- hsTyGetAppHead_maybe res_ty , data_tvs `equalLength` tys = return (go [] [] (data_tvs `zip` tys)) | otherwise = failWithDs (ptext (sLit "Malformed constructor result type:") <+> ppr res_ty) where go cxt subst [] = (cxt, subst) go cxt subst ((data_tv, ty) : rest) | Just con_tv <- is_hs_tyvar ty , isTyVarName con_tv , not (in_subst subst con_tv) = go cxt ((con_tv, data_tv) : subst) rest | otherwise = go (eq_pred : cxt) subst rest where loc = getLoc ty eq_pred = L loc (HsEqTy (L loc (HsTyVar data_tv)) ty) is_hs_tyvar (L _ (HsTyVar n)) = Just n -- Type variables *and* tycons is_hs_tyvar (L _ (HsParTy ty)) = is_hs_tyvar ty is_hs_tyvar _ = Nothing repBangTy :: LBangType Name -> DsM (Core (TH.StrictTypeQ)) repBangTy ty= do MkC s <- rep2 str [] MkC t <- repLTy ty' rep2 strictTypeName [s, t] where (str, ty') = case ty of L _ (HsBangTy (HsUserBang (Just True) True) ty) -> (unpackedName, ty) L _ (HsBangTy (HsUserBang _ True) ty) -> (isStrictName, ty) _ -> (notStrictName, ty) ------------------------------------------------------- -- Deriving clause ------------------------------------------------------- repDerivs :: Maybe [LHsType Name] -> DsM (Core [TH.Name]) repDerivs Nothing = coreList nameTyConName [] repDerivs (Just ctxt) = repList nameTyConName rep_deriv ctxt where rep_deriv :: LHsType Name -> DsM (Core TH.Name) -- Deriving clauses must have the simple H98 form rep_deriv ty | Just (cls, []) <- splitHsClassTy_maybe (unLoc ty) = lookupOcc cls | otherwise = notHandled "Non-H98 deriving clause" (ppr ty) ------------------------------------------------------- -- Signatures in a class decl, or a group of bindings ------------------------------------------------------- rep_sigs :: [LSig Name] -> DsM [Core TH.DecQ] rep_sigs sigs = do locs_cores <- rep_sigs' sigs return $ de_loc $ sort_by_loc locs_cores rep_sigs' :: [LSig Name] -> DsM [(SrcSpan, Core TH.DecQ)] -- We silently ignore ones we don't recognise rep_sigs' sigs = do { sigs1 <- mapM rep_sig sigs ; return (concat sigs1) } rep_sig :: LSig Name -> DsM [(SrcSpan, Core TH.DecQ)] -- Singleton => Ok -- Empty => Too hard, signature ignored rep_sig (L loc (TypeSig nms ty)) = mapM (rep_ty_sig loc ty) nms rep_sig (L _ (GenericSig nm _)) = failWithDs msg where msg = vcat [ ptext (sLit "Illegal default signature for") <+> quotes (ppr nm) , ptext (sLit "Default signatures are not supported by Template Haskell") ] rep_sig (L loc (InlineSig nm ispec)) = rep_inline nm ispec loc rep_sig (L loc (SpecSig nm ty ispec)) = rep_specialise nm ty ispec loc rep_sig (L loc (SpecInstSig ty)) = rep_specialiseInst ty loc rep_sig _ = return [] rep_ty_sig :: SrcSpan -> LHsType Name -> Located Name -> DsM (SrcSpan, Core TH.DecQ) rep_ty_sig loc (L _ ty) nm = do { nm1 <- lookupLOcc nm ; ty1 <- rep_ty ty ; sig <- repProto nm1 ty1 ; return (loc, sig) } where -- We must special-case the top-level explicit for-all of a TypeSig -- See Note [Scoped type variables in bindings] rep_ty (HsForAllTy Explicit tvs ctxt ty) = do { let rep_in_scope_tv tv = do { name <- lookupBinder (hsLTyVarName tv) ; repTyVarBndrWithKind tv name } ; bndrs1 <- repList tyVarBndrTyConName rep_in_scope_tv (hsQTvBndrs tvs) ; ctxt1 <- repLContext ctxt ; ty1 <- repLTy ty ; repTForall bndrs1 ctxt1 ty1 } rep_ty ty = repTy ty rep_inline :: Located Name -> InlinePragma -- Never defaultInlinePragma -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)] rep_inline nm ispec loc = do { nm1 <- lookupLOcc nm ; inline <- repInline $ inl_inline ispec ; rm <- repRuleMatch $ inl_rule ispec ; phases <- repPhases $ inl_act ispec ; pragma <- repPragInl nm1 inline rm phases ; return [(loc, pragma)] } rep_specialise :: Located Name -> LHsType Name -> InlinePragma -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)] rep_specialise nm ty ispec loc = do { nm1 <- lookupLOcc nm ; ty1 <- repLTy ty ; phases <- repPhases $ inl_act ispec ; let inline = inl_inline ispec ; pragma <- if isEmptyInlineSpec inline then -- SPECIALISE repPragSpec nm1 ty1 phases else -- SPECIALISE INLINE do { inline1 <- repInline inline ; repPragSpecInl nm1 ty1 inline1 phases } ; return [(loc, pragma)] } rep_specialiseInst :: LHsType Name -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)] rep_specialiseInst ty loc = do { ty1 <- repLTy ty ; pragma <- repPragSpecInst ty1 ; return [(loc, pragma)] } repInline :: InlineSpec -> DsM (Core TH.Inline) repInline NoInline = dataCon noInlineDataConName repInline Inline = dataCon inlineDataConName repInline Inlinable = dataCon inlinableDataConName repInline spec = notHandled "repInline" (ppr spec) repRuleMatch :: RuleMatchInfo -> DsM (Core TH.RuleMatch) repRuleMatch ConLike = dataCon conLikeDataConName repRuleMatch FunLike = dataCon funLikeDataConName repPhases :: Activation -> DsM (Core TH.Phases) repPhases (ActiveBefore i) = do { MkC arg <- coreIntLit i ; dataCon' beforePhaseDataConName [arg] } repPhases (ActiveAfter i) = do { MkC arg <- coreIntLit i ; dataCon' fromPhaseDataConName [arg] } repPhases _ = dataCon allPhasesDataConName ------------------------------------------------------- -- Types ------------------------------------------------------- addTyVarBinds :: LHsTyVarBndrs Name -- the binders to be added -> (Core [TH.TyVarBndr] -> DsM (Core (TH.Q a))) -- action in the ext env -> DsM (Core (TH.Q a)) -- gensym a list of type variables and enter them into the meta environment; -- the computations passed as the second argument is executed in that extended -- meta environment and gets the *new* names on Core-level as an argument addTyVarBinds (HsQTvs { hsq_kvs = kvs, hsq_tvs = tvs }) m = do { fresh_kv_names <- mkGenSyms kvs ; fresh_tv_names <- mkGenSyms (map hsLTyVarName tvs) ; let fresh_names = fresh_kv_names ++ fresh_tv_names ; term <- addBinds fresh_names $ do { kbs <- repList tyVarBndrTyConName mk_tv_bndr (tvs `zip` fresh_tv_names) ; m kbs } ; wrapGenSyms fresh_names term } where mk_tv_bndr (tv, (_,v)) = repTyVarBndrWithKind tv (coreVar v) addTyClTyVarBinds :: LHsTyVarBndrs Name -> (Core [TH.TyVarBndr] -> DsM (Core (TH.Q a))) -> DsM (Core (TH.Q a)) -- Used for data/newtype declarations, and family instances, -- so that the nested type variables work right -- instance C (T a) where -- type W (T a) = blah -- The 'a' in the type instance is the one bound by the instance decl addTyClTyVarBinds tvs m = do { let tv_names = hsLKiTyVarNames tvs ; env <- dsGetMetaEnv ; freshNames <- mkGenSyms (filterOut (`elemNameEnv` env) tv_names) -- Make fresh names for the ones that are not already in scope -- This makes things work for family declarations ; term <- addBinds freshNames $ do { kbs <- repList tyVarBndrTyConName mk_tv_bndr (hsQTvBndrs tvs) ; m kbs } ; wrapGenSyms freshNames term } where mk_tv_bndr tv = do { v <- lookupBinder (hsLTyVarName tv) ; repTyVarBndrWithKind tv v } -- Produce kinded binder constructors from the Haskell tyvar binders -- repTyVarBndrWithKind :: LHsTyVarBndr Name -> Core TH.Name -> DsM (Core TH.TyVarBndr) repTyVarBndrWithKind (L _ (UserTyVar _)) nm = repPlainTV nm repTyVarBndrWithKind (L _ (KindedTyVar _ ki)) nm = repLKind ki >>= repKindedTV nm -- represent a type context -- repLContext :: LHsContext Name -> DsM (Core TH.CxtQ) repLContext (L _ ctxt) = repContext ctxt repContext :: HsContext Name -> DsM (Core TH.CxtQ) repContext ctxt = do preds <- repList typeQTyConName repLTy ctxt repCtxt preds -- yield the representation of a list of types -- repLTys :: [LHsType Name] -> DsM [Core TH.TypeQ] repLTys tys = mapM repLTy tys -- represent a type -- repLTy :: LHsType Name -> DsM (Core TH.TypeQ) repLTy (L _ ty) = repTy ty repTy :: HsType Name -> DsM (Core TH.TypeQ) repTy (HsForAllTy _ tvs ctxt ty) = addTyVarBinds tvs $ \bndrs -> do ctxt1 <- repLContext ctxt ty1 <- repLTy ty repTForall bndrs ctxt1 ty1 repTy (HsTyVar n) | isTvOcc occ = do tv1 <- lookupOcc n repTvar tv1 | isDataOcc occ = do tc1 <- lookupOcc n repPromotedTyCon tc1 | otherwise = do tc1 <- lookupOcc n repNamedTyCon tc1 where occ = nameOccName n repTy (HsAppTy f a) = do f1 <- repLTy f a1 <- repLTy a repTapp f1 a1 repTy (HsFunTy f a) = do f1 <- repLTy f a1 <- repLTy a tcon <- repArrowTyCon repTapps tcon [f1, a1] repTy (HsListTy t) = do t1 <- repLTy t tcon <- repListTyCon repTapp tcon t1 repTy (HsPArrTy t) = do t1 <- repLTy t tcon <- repTy (HsTyVar (tyConName parrTyCon)) repTapp tcon t1 repTy (HsTupleTy HsUnboxedTuple tys) = do tys1 <- repLTys tys tcon <- repUnboxedTupleTyCon (length tys) repTapps tcon tys1 repTy (HsTupleTy _ tys) = do tys1 <- repLTys tys tcon <- repTupleTyCon (length tys) repTapps tcon tys1 repTy (HsOpTy ty1 (_, n) ty2) = repLTy ((nlHsTyVar (unLoc n) `nlHsAppTy` ty1) `nlHsAppTy` ty2) repTy (HsParTy t) = repLTy t repTy (HsEqTy t1 t2) = do t1' <- repLTy t1 t2' <- repLTy t2 eq <- repTequality repTapps eq [t1', t2'] repTy (HsKindSig t k) = do t1 <- repLTy t k1 <- repLKind k repTSig t1 k1 repTy (HsSpliceTy splice _) = repSplice splice repTy (HsExplicitListTy _ tys) = do tys1 <- repLTys tys repTPromotedList tys1 repTy (HsExplicitTupleTy _ tys) = do tys1 <- repLTys tys tcon <- repPromotedTupleTyCon (length tys) repTapps tcon tys1 repTy (HsTyLit lit) = do lit' <- repTyLit lit repTLit lit' repTy ty = notHandled "Exotic form of type" (ppr ty) repTyLit :: HsTyLit -> DsM (Core TH.TyLitQ) repTyLit (HsNumTy i) = do iExpr <- mkIntegerExpr i rep2 numTyLitName [iExpr] repTyLit (HsStrTy s) = do { s' <- mkStringExprFS s ; rep2 strTyLitName [s'] } -- represent a kind -- repLKind :: LHsKind Name -> DsM (Core TH.Kind) repLKind ki = do { let (kis, ki') = splitHsFunType ki ; kis_rep <- mapM repLKind kis ; ki'_rep <- repNonArrowLKind ki' ; kcon <- repKArrow ; let f k1 k2 = repKApp kcon k1 >>= flip repKApp k2 ; foldrM f ki'_rep kis_rep } repNonArrowLKind :: LHsKind Name -> DsM (Core TH.Kind) repNonArrowLKind (L _ ki) = repNonArrowKind ki repNonArrowKind :: HsKind Name -> DsM (Core TH.Kind) repNonArrowKind (HsTyVar name) | name == liftedTypeKindTyConName = repKStar | name == constraintKindTyConName = repKConstraint | isTvOcc (nameOccName name) = lookupOcc name >>= repKVar | otherwise = lookupOcc name >>= repKCon repNonArrowKind (HsAppTy f a) = do { f' <- repLKind f ; a' <- repLKind a ; repKApp f' a' } repNonArrowKind (HsListTy k) = do { k' <- repLKind k ; kcon <- repKList ; repKApp kcon k' } repNonArrowKind (HsTupleTy _ ks) = do { ks' <- mapM repLKind ks ; kcon <- repKTuple (length ks) ; repKApps kcon ks' } repNonArrowKind k = notHandled "Exotic form of kind" (ppr k) repRole :: Located (Maybe Role) -> DsM (Core TH.Role) repRole (L _ (Just Nominal)) = rep2 nominalRName [] repRole (L _ (Just Representational)) = rep2 representationalRName [] repRole (L _ (Just Phantom)) = rep2 phantomRName [] repRole (L _ Nothing) = rep2 inferRName [] ----------------------------------------------------------------------------- -- Splices ----------------------------------------------------------------------------- repSplice :: HsSplice Name -> DsM (Core a) -- See Note [How brackets and nested splices are handled] in TcSplice -- We return a CoreExpr of any old type; the context should know repSplice (HsSplice n _) = do { mb_val <- dsLookupMetaEnv n ; case mb_val of Just (Splice e) -> do { e' <- dsExpr e ; return (MkC e') } _ -> pprPanic "HsSplice" (ppr n) } -- Should not happen; statically checked ----------------------------------------------------------------------------- -- Expressions ----------------------------------------------------------------------------- repLEs :: [LHsExpr Name] -> DsM (Core [TH.ExpQ]) repLEs es = repList expQTyConName repLE es -- FIXME: some of these panics should be converted into proper error messages -- unless we can make sure that constructs, which are plainly not -- supported in TH already lead to error messages at an earlier stage repLE :: LHsExpr Name -> DsM (Core TH.ExpQ) repLE (L loc e) = putSrcSpanDs loc (repE e) repE :: HsExpr Name -> DsM (Core TH.ExpQ) repE (HsVar x) = do { mb_val <- dsLookupMetaEnv x ; case mb_val of Nothing -> do { str <- globalVar x ; repVarOrCon x str } Just (Bound y) -> repVarOrCon x (coreVar y) Just (Splice e) -> do { e' <- dsExpr e ; return (MkC e') } } repE e@(HsIPVar _) = notHandled "Implicit parameters" (ppr e) -- Remember, we're desugaring renamer output here, so -- HsOverlit can definitely occur repE (HsOverLit l) = do { a <- repOverloadedLiteral l; repLit a } repE (HsLit l) = do { a <- repLiteral l; repLit a } repE (HsLam (MG { mg_alts = [m] })) = repLambda m repE (HsLamCase _ (MG { mg_alts = ms })) = do { ms' <- mapM repMatchTup ms ; core_ms <- coreList matchQTyConName ms' ; repLamCase core_ms } repE (HsApp x y) = do {a <- repLE x; b <- repLE y; repApp a b} repE (OpApp e1 op _ e2) = do { arg1 <- repLE e1; arg2 <- repLE e2; the_op <- repLE op ; repInfixApp arg1 the_op arg2 } repE (NegApp x _) = do a <- repLE x negateVar <- lookupOcc negateName >>= repVar negateVar `repApp` a repE (HsPar x) = repLE x repE (SectionL x y) = do { a <- repLE x; b <- repLE y; repSectionL a b } repE (SectionR x y) = do { a <- repLE x; b <- repLE y; repSectionR a b } repE (HsCase e (MG { mg_alts = ms })) = do { arg <- repLE e ; ms2 <- mapM repMatchTup ms ; core_ms2 <- coreList matchQTyConName ms2 ; repCaseE arg core_ms2 } repE (HsIf _ x y z) = do a <- repLE x b <- repLE y c <- repLE z repCond a b c repE (HsMultiIf _ alts) = do { (binds, alts') <- liftM unzip $ mapM repLGRHS alts ; expr' <- repMultiIf (nonEmptyCoreList alts') ; wrapGenSyms (concat binds) expr' } repE (HsLet bs e) = do { (ss,ds) <- repBinds bs ; e2 <- addBinds ss (repLE e) ; z <- repLetE ds e2 ; wrapGenSyms ss z } -- FIXME: I haven't got the types here right yet repE e@(HsDo ctxt sts _) | case ctxt of { DoExpr -> True; GhciStmtCtxt -> True; _ -> False } = do { (ss,zs) <- repLSts sts; e' <- repDoE (nonEmptyCoreList zs); wrapGenSyms ss e' } | ListComp <- ctxt = do { (ss,zs) <- repLSts sts; e' <- repComp (nonEmptyCoreList zs); wrapGenSyms ss e' } | otherwise = notHandled "mdo, monad comprehension and [: :]" (ppr e) repE (ExplicitList _ _ es) = do { xs <- repLEs es; repListExp xs } repE e@(ExplicitPArr _ _) = notHandled "Parallel arrays" (ppr e) repE e@(ExplicitTuple es boxed) | not (all tupArgPresent es) = notHandled "Tuple sections" (ppr e) | isBoxed boxed = do { xs <- repLEs [e | Present e <- es]; repTup xs } | otherwise = do { xs <- repLEs [e | Present e <- es]; repUnboxedTup xs } repE (RecordCon c _ flds) = do { x <- lookupLOcc c; fs <- repFields flds; repRecCon x fs } repE (RecordUpd e flds _ _ _) = do { x <- repLE e; fs <- repFields flds; repRecUpd x fs } repE (ExprWithTySig e ty) = do { e1 <- repLE e; t1 <- repLTy ty; repSigExp e1 t1 } repE (ArithSeq _ _ aseq) = case aseq of From e -> do { ds1 <- repLE e; repFrom ds1 } FromThen e1 e2 -> do ds1 <- repLE e1 ds2 <- repLE e2 repFromThen ds1 ds2 FromTo e1 e2 -> do ds1 <- repLE e1 ds2 <- repLE e2 repFromTo ds1 ds2 FromThenTo e1 e2 e3 -> do ds1 <- repLE e1 ds2 <- repLE e2 ds3 <- repLE e3 repFromThenTo ds1 ds2 ds3 repE (HsSpliceE _ splice) = repSplice splice repE e@(PArrSeq {}) = notHandled "Parallel arrays" (ppr e) repE e@(HsCoreAnn {}) = notHandled "Core annotations" (ppr e) repE e@(HsSCC {}) = notHandled "Cost centres" (ppr e) repE e@(HsTickPragma {}) = notHandled "Tick Pragma" (ppr e) repE e@(HsTcBracketOut {}) = notHandled "TH brackets" (ppr e) repE e = notHandled "Expression form" (ppr e) ----------------------------------------------------------------------------- -- Building representations of auxillary structures like Match, Clause, Stmt, repMatchTup :: LMatch Name (LHsExpr Name) -> DsM (Core TH.MatchQ) repMatchTup (L _ (Match [p] _ (GRHSs guards wheres))) = do { ss1 <- mkGenSyms (collectPatBinders p) ; addBinds ss1 $ do { ; p1 <- repLP p ; (ss2,ds) <- repBinds wheres ; addBinds ss2 $ do { ; gs <- repGuards guards ; match <- repMatch p1 gs ds ; wrapGenSyms (ss1++ss2) match }}} repMatchTup _ = panic "repMatchTup: case alt with more than one arg" repClauseTup :: LMatch Name (LHsExpr Name) -> DsM (Core TH.ClauseQ) repClauseTup (L _ (Match ps _ (GRHSs guards wheres))) = do { ss1 <- mkGenSyms (collectPatsBinders ps) ; addBinds ss1 $ do { ps1 <- repLPs ps ; (ss2,ds) <- repBinds wheres ; addBinds ss2 $ do { gs <- repGuards guards ; clause <- repClause ps1 gs ds ; wrapGenSyms (ss1++ss2) clause }}} repGuards :: [LGRHS Name (LHsExpr Name)] -> DsM (Core TH.BodyQ) repGuards [L _ (GRHS [] e)] = do {a <- repLE e; repNormal a } repGuards other = do { zs <- mapM repLGRHS other ; let (xs, ys) = unzip zs ; gd <- repGuarded (nonEmptyCoreList ys) ; wrapGenSyms (concat xs) gd } repLGRHS :: LGRHS Name (LHsExpr Name) -> DsM ([GenSymBind], (Core (TH.Q (TH.Guard, TH.Exp)))) repLGRHS (L _ (GRHS [L _ (BodyStmt e1 _ _ _)] e2)) = do { guarded <- repLNormalGE e1 e2 ; return ([], guarded) } repLGRHS (L _ (GRHS ss rhs)) = do { (gs, ss') <- repLSts ss ; rhs' <- addBinds gs $ repLE rhs ; guarded <- repPatGE (nonEmptyCoreList ss') rhs' ; return (gs, guarded) } repFields :: HsRecordBinds Name -> DsM (Core [TH.Q TH.FieldExp]) repFields (HsRecFields { rec_flds = flds }) = repList fieldExpQTyConName rep_fld flds where rep_fld fld = do { fn <- lookupLOcc (hsRecFieldId fld) ; e <- repLE (hsRecFieldArg fld) ; repFieldExp fn e } ----------------------------------------------------------------------------- -- Representing Stmt's is tricky, especially if bound variables -- shadow each other. Consider: [| do { x <- f 1; x <- f x; g x } |] -- First gensym new names for every variable in any of the patterns. -- both static (x'1 and x'2), and dynamic ((gensym "x") and (gensym "y")) -- if variables didn't shaddow, the static gensym wouldn't be necessary -- and we could reuse the original names (x and x). -- -- do { x'1 <- gensym "x" -- ; x'2 <- gensym "x" -- ; doE [ BindSt (pvar x'1) [| f 1 |] -- , BindSt (pvar x'2) [| f x |] -- , NoBindSt [| g x |] -- ] -- } -- The strategy is to translate a whole list of do-bindings by building a -- bigger environment, and a bigger set of meta bindings -- (like: x'1 <- gensym "x" ) and then combining these with the translations -- of the expressions within the Do ----------------------------------------------------------------------------- -- The helper function repSts computes the translation of each sub expression -- and a bunch of prefix bindings denoting the dynamic renaming. repLSts :: [LStmt Name (LHsExpr Name)] -> DsM ([GenSymBind], [Core TH.StmtQ]) repLSts stmts = repSts (map unLoc stmts) repSts :: [Stmt Name (LHsExpr Name)] -> DsM ([GenSymBind], [Core TH.StmtQ]) repSts (BindStmt p e _ _ : ss) = do { e2 <- repLE e ; ss1 <- mkGenSyms (collectPatBinders p) ; addBinds ss1 $ do { ; p1 <- repLP p; ; (ss2,zs) <- repSts ss ; z <- repBindSt p1 e2 ; return (ss1++ss2, z : zs) }} repSts (LetStmt bs : ss) = do { (ss1,ds) <- repBinds bs ; z <- repLetSt ds ; (ss2,zs) <- addBinds ss1 (repSts ss) ; return (ss1++ss2, z : zs) } repSts (BodyStmt e _ _ _ : ss) = do { e2 <- repLE e ; z <- repNoBindSt e2 ; (ss2,zs) <- repSts ss ; return (ss2, z : zs) } repSts (ParStmt stmt_blocks _ _ : ss) = do { (ss_s, stmt_blocks1) <- mapAndUnzipM rep_stmt_block stmt_blocks ; let stmt_blocks2 = nonEmptyCoreList stmt_blocks1 ss1 = concat ss_s ; z <- repParSt stmt_blocks2 ; (ss2, zs) <- addBinds ss1 (repSts ss) ; return (ss1++ss2, z : zs) } where rep_stmt_block :: ParStmtBlock Name Name -> DsM ([GenSymBind], Core [TH.StmtQ]) rep_stmt_block (ParStmtBlock stmts _ _) = do { (ss1, zs) <- repSts (map unLoc stmts) ; zs1 <- coreList stmtQTyConName zs ; return (ss1, zs1) } repSts [LastStmt e _] = do { e2 <- repLE e ; z <- repNoBindSt e2 ; return ([], [z]) } repSts [] = return ([],[]) repSts other = notHandled "Exotic statement" (ppr other) ----------------------------------------------------------- -- Bindings ----------------------------------------------------------- repBinds :: HsLocalBinds Name -> DsM ([GenSymBind], Core [TH.DecQ]) repBinds EmptyLocalBinds = do { core_list <- coreList decQTyConName [] ; return ([], core_list) } repBinds b@(HsIPBinds _) = notHandled "Implicit parameters" (ppr b) repBinds (HsValBinds decs) = do { let { bndrs = hsSigTvBinders decs ++ collectHsValBinders decs } -- No need to worrry about detailed scopes within -- the binding group, because we are talking Names -- here, so we can safely treat it as a mutually -- recursive group -- For hsSigTvBinders see Note [Scoped type variables in bindings] ; ss <- mkGenSyms bndrs ; prs <- addBinds ss (rep_val_binds decs) ; core_list <- coreList decQTyConName (de_loc (sort_by_loc prs)) ; return (ss, core_list) } rep_val_binds :: HsValBinds Name -> DsM [(SrcSpan, Core TH.DecQ)] -- Assumes: all the binders of the binding are alrady in the meta-env rep_val_binds (ValBindsOut binds sigs) = do { core1 <- rep_binds' (unionManyBags (map snd binds)) ; core2 <- rep_sigs' sigs ; return (core1 ++ core2) } rep_val_binds (ValBindsIn _ _) = panic "rep_val_binds: ValBindsIn" rep_binds :: LHsBinds Name -> DsM [Core TH.DecQ] rep_binds binds = do { binds_w_locs <- rep_binds' binds ; return (de_loc (sort_by_loc binds_w_locs)) } rep_binds' :: LHsBinds Name -> DsM [(SrcSpan, Core TH.DecQ)] rep_binds' = mapM rep_bind . bagToList rep_bind :: LHsBind Name -> DsM (SrcSpan, Core TH.DecQ) -- Assumes: all the binders of the binding are alrady in the meta-env -- Note GHC treats declarations of a variable (not a pattern) -- e.g. x = g 5 as a Fun MonoBinds. This is indicated by a single match -- with an empty list of patterns rep_bind (L loc (FunBind { fun_id = fn, fun_matches = MG { mg_alts = [L _ (Match [] _ (GRHSs guards wheres))] } })) = do { (ss,wherecore) <- repBinds wheres ; guardcore <- addBinds ss (repGuards guards) ; fn' <- lookupLBinder fn ; p <- repPvar fn' ; ans <- repVal p guardcore wherecore ; ans' <- wrapGenSyms ss ans ; return (loc, ans') } rep_bind (L loc (FunBind { fun_id = fn, fun_matches = MG { mg_alts = ms } })) = do { ms1 <- mapM repClauseTup ms ; fn' <- lookupLBinder fn ; ans <- repFun fn' (nonEmptyCoreList ms1) ; return (loc, ans) } rep_bind (L loc (PatBind { pat_lhs = pat, pat_rhs = GRHSs guards wheres })) = do { patcore <- repLP pat ; (ss,wherecore) <- repBinds wheres ; guardcore <- addBinds ss (repGuards guards) ; ans <- repVal patcore guardcore wherecore ; ans' <- wrapGenSyms ss ans ; return (loc, ans') } rep_bind (L _ (VarBind { var_id = v, var_rhs = e})) = do { v' <- lookupBinder v ; e2 <- repLE e ; x <- repNormal e2 ; patcore <- repPvar v' ; empty_decls <- coreList decQTyConName [] ; ans <- repVal patcore x empty_decls ; return (srcLocSpan (getSrcLoc v), ans) } rep_bind (L _ (AbsBinds {})) = panic "rep_bind: AbsBinds" rep_bind (L _ dec@(PatSynBind {})) = notHandled "pattern synonyms" (ppr dec) ----------------------------------------------------------------------------- -- Since everything in a Bind is mutually recursive we need rename all -- all the variables simultaneously. For example: -- [| AndMonoBinds (f x = x + g 2) (g x = f 1 + 2) |] would translate to -- do { f'1 <- gensym "f" -- ; g'2 <- gensym "g" -- ; [ do { x'3 <- gensym "x"; fun f'1 [pvar x'3] [| x + g2 |]}, -- do { x'4 <- gensym "x"; fun g'2 [pvar x'4] [| f 1 + 2 |]} -- ]} -- This requires collecting the bindings (f'1 <- gensym "f"), and the -- environment ( f |-> f'1 ) from each binding, and then unioning them -- together. As we do this we collect GenSymBinds's which represent the renamed -- variables bound by the Bindings. In order not to lose track of these -- representations we build a shadow datatype MB with the same structure as -- MonoBinds, but which has slots for the representations ----------------------------------------------------------------------------- -- GHC allows a more general form of lambda abstraction than specified -- by Haskell 98. In particular it allows guarded lambda's like : -- (\ x | even x -> 0 | odd x -> 1) at the moment we can't represent this in -- Haskell Template's Meta.Exp type so we punt if it isn't a simple thing like -- (\ p1 .. pn -> exp) by causing an error. repLambda :: LMatch Name (LHsExpr Name) -> DsM (Core TH.ExpQ) repLambda (L _ (Match ps _ (GRHSs [L _ (GRHS [] e)] EmptyLocalBinds))) = do { let bndrs = collectPatsBinders ps ; ; ss <- mkGenSyms bndrs ; lam <- addBinds ss ( do { xs <- repLPs ps; body <- repLE e; repLam xs body }) ; wrapGenSyms ss lam } repLambda (L _ m) = notHandled "Guarded labmdas" (pprMatch (LambdaExpr :: HsMatchContext Name) m) ----------------------------------------------------------------------------- -- Patterns -- repP deals with patterns. It assumes that we have already -- walked over the pattern(s) once to collect the binders, and -- have extended the environment. So every pattern-bound -- variable should already appear in the environment. -- Process a list of patterns repLPs :: [LPat Name] -> DsM (Core [TH.PatQ]) repLPs ps = repList patQTyConName repLP ps repLP :: LPat Name -> DsM (Core TH.PatQ) repLP (L _ p) = repP p repP :: Pat Name -> DsM (Core TH.PatQ) repP (WildPat _) = repPwild repP (LitPat l) = do { l2 <- repLiteral l; repPlit l2 } repP (VarPat x) = do { x' <- lookupBinder x; repPvar x' } repP (LazyPat p) = do { p1 <- repLP p; repPtilde p1 } repP (BangPat p) = do { p1 <- repLP p; repPbang p1 } repP (AsPat x p) = do { x' <- lookupLBinder x; p1 <- repLP p; repPaspat x' p1 } repP (ParPat p) = repLP p repP (ListPat ps _ Nothing) = do { qs <- repLPs ps; repPlist qs } repP (ListPat ps ty1 (Just (_,e))) = do { p <- repP (ListPat ps ty1 Nothing); e' <- repE e; repPview e' p} repP (TuplePat ps boxed _) | isBoxed boxed = do { qs <- repLPs ps; repPtup qs } | otherwise = do { qs <- repLPs ps; repPunboxedTup qs } repP (ConPatIn dc details) = do { con_str <- lookupLOcc dc ; case details of PrefixCon ps -> do { qs <- repLPs ps; repPcon con_str qs } RecCon rec -> do { fps <- repList fieldPatQTyConName rep_fld (rec_flds rec) ; repPrec con_str fps } InfixCon p1 p2 -> do { p1' <- repLP p1; p2' <- repLP p2; repPinfix p1' con_str p2' } } where rep_fld fld = do { MkC v <- lookupLOcc (hsRecFieldId fld) ; MkC p <- repLP (hsRecFieldArg fld) ; rep2 fieldPatName [v,p] } repP (NPat l Nothing _) = do { a <- repOverloadedLiteral l; repPlit a } repP (ViewPat e p _) = do { e' <- repLE e; p' <- repLP p; repPview e' p' } repP p@(NPat _ (Just _) _) = notHandled "Negative overloaded patterns" (ppr p) repP p@(SigPatIn {}) = notHandled "Type signatures in patterns" (ppr p) -- The problem is to do with scoped type variables. -- To implement them, we have to implement the scoping rules -- here in DsMeta, and I don't want to do that today! -- do { p' <- repLP p; t' <- repLTy t; repPsig p' t' } -- repPsig :: Core TH.PatQ -> Core TH.TypeQ -> DsM (Core TH.PatQ) -- repPsig (MkC p) (MkC t) = rep2 sigPName [p, t] repP (SplicePat splice) = repSplice splice repP other = notHandled "Exotic pattern" (ppr other) ---------------------------------------------------------- -- Declaration ordering helpers sort_by_loc :: [(SrcSpan, a)] -> [(SrcSpan, a)] sort_by_loc xs = sortBy comp xs where comp x y = compare (fst x) (fst y) de_loc :: [(a, b)] -> [b] de_loc = map snd ---------------------------------------------------------- -- The meta-environment -- A name/identifier association for fresh names of locally bound entities type GenSymBind = (Name, Id) -- Gensym the string and bind it to the Id -- I.e. (x, x_id) means -- let x_id = gensym "x" in ... -- Generate a fresh name for a locally bound entity mkGenSyms :: [Name] -> DsM [GenSymBind] -- We can use the existing name. For example: -- [| \x_77 -> x_77 + x_77 |] -- desugars to -- do { x_77 <- genSym "x"; .... } -- We use the same x_77 in the desugared program, but with the type Bndr -- instead of Int -- -- We do make it an Internal name, though (hence localiseName) -- -- Nevertheless, it's monadic because we have to generate nameTy mkGenSyms ns = do { var_ty <- lookupType nameTyConName ; return [(nm, mkLocalId (localiseName nm) var_ty) | nm <- ns] } addBinds :: [GenSymBind] -> DsM a -> DsM a -- Add a list of fresh names for locally bound entities to the -- meta environment (which is part of the state carried around -- by the desugarer monad) addBinds bs m = dsExtendMetaEnv (mkNameEnv [(n,Bound id) | (n,id) <- bs]) m dupBinder :: (Name, Name) -> DsM (Name, DsMetaVal) dupBinder (new, old) = do { mb_val <- dsLookupMetaEnv old ; case mb_val of Just val -> return (new, val) Nothing -> pprPanic "dupBinder" (ppr old) } -- Look up a locally bound name -- lookupLBinder :: Located Name -> DsM (Core TH.Name) lookupLBinder (L _ n) = lookupBinder n lookupBinder :: Name -> DsM (Core TH.Name) lookupBinder = lookupOcc -- Binders are brought into scope before the pattern or what-not is -- desugared. Moreover, in instance declaration the binder of a method -- will be the selector Id and hence a global; so we need the -- globalVar case of lookupOcc -- Look up a name that is either locally bound or a global name -- -- * If it is a global name, generate the "original name" representation (ie, -- the <module>:<name> form) for the associated entity -- lookupLOcc :: Located Name -> DsM (Core TH.Name) -- Lookup an occurrence; it can't be a splice. -- Use the in-scope bindings if they exist lookupLOcc (L _ n) = lookupOcc n lookupOcc :: Name -> DsM (Core TH.Name) lookupOcc n = do { mb_val <- dsLookupMetaEnv n ; case mb_val of Nothing -> globalVar n Just (Bound x) -> return (coreVar x) Just (Splice _) -> pprPanic "repE:lookupOcc" (ppr n) } globalVar :: Name -> DsM (Core TH.Name) -- Not bound by the meta-env -- Could be top-level; or could be local -- f x = $(g [| x |]) -- Here the x will be local globalVar name | isExternalName name = do { MkC mod <- coreStringLit name_mod ; MkC pkg <- coreStringLit name_pkg ; MkC occ <- occNameLit name ; rep2 mk_varg [pkg,mod,occ] } | otherwise = do { MkC occ <- occNameLit name ; MkC uni <- coreIntLit (getKey (getUnique name)) ; rep2 mkNameLName [occ,uni] } where mod = ASSERT( isExternalName name) nameModule name name_mod = moduleNameString (moduleName mod) name_pkg = packageKeyString (modulePackageKey mod) name_occ = nameOccName name mk_varg | OccName.isDataOcc name_occ = mkNameG_dName | OccName.isVarOcc name_occ = mkNameG_vName | OccName.isTcOcc name_occ = mkNameG_tcName | otherwise = pprPanic "DsMeta.globalVar" (ppr name) lookupType :: Name -- Name of type constructor (e.g. TH.ExpQ) -> DsM Type -- The type lookupType tc_name = do { tc <- dsLookupTyCon tc_name ; return (mkTyConApp tc []) } wrapGenSyms :: [GenSymBind] -> Core (TH.Q a) -> DsM (Core (TH.Q a)) -- wrapGenSyms [(nm1,id1), (nm2,id2)] y -- --> bindQ (gensym nm1) (\ id1 -> -- bindQ (gensym nm2 (\ id2 -> -- y)) wrapGenSyms binds body@(MkC b) = do { var_ty <- lookupType nameTyConName ; go var_ty binds } where [elt_ty] = tcTyConAppArgs (exprType b) -- b :: Q a, so we can get the type 'a' by looking at the -- argument type. NB: this relies on Q being a data/newtype, -- not a type synonym go _ [] = return body go var_ty ((name,id) : binds) = do { MkC body' <- go var_ty binds ; lit_str <- occNameLit name ; gensym_app <- repGensym lit_str ; repBindQ var_ty elt_ty gensym_app (MkC (Lam id body')) } occNameLit :: Name -> DsM (Core String) occNameLit n = coreStringLit (occNameString (nameOccName n)) -- %********************************************************************* -- %* * -- Constructing code -- %* * -- %********************************************************************* ----------------------------------------------------------------------------- -- PHANTOM TYPES for consistency. In order to make sure we do this correct -- we invent a new datatype which uses phantom types. newtype Core a = MkC CoreExpr unC :: Core a -> CoreExpr unC (MkC x) = x rep2 :: Name -> [ CoreExpr ] -> DsM (Core a) rep2 n xs = do { id <- dsLookupGlobalId n ; return (MkC (foldl App (Var id) xs)) } dataCon' :: Name -> [CoreExpr] -> DsM (Core a) dataCon' n args = do { id <- dsLookupDataCon n ; return $ MkC $ mkCoreConApps id args } dataCon :: Name -> DsM (Core a) dataCon n = dataCon' n [] -- Then we make "repConstructors" which use the phantom types for each of the -- smart constructors of the Meta.Meta datatypes. -- %********************************************************************* -- %* * -- The 'smart constructors' -- %* * -- %********************************************************************* --------------- Patterns ----------------- repPlit :: Core TH.Lit -> DsM (Core TH.PatQ) repPlit (MkC l) = rep2 litPName [l] repPvar :: Core TH.Name -> DsM (Core TH.PatQ) repPvar (MkC s) = rep2 varPName [s] repPtup :: Core [TH.PatQ] -> DsM (Core TH.PatQ) repPtup (MkC ps) = rep2 tupPName [ps] repPunboxedTup :: Core [TH.PatQ] -> DsM (Core TH.PatQ) repPunboxedTup (MkC ps) = rep2 unboxedTupPName [ps] repPcon :: Core TH.Name -> Core [TH.PatQ] -> DsM (Core TH.PatQ) repPcon (MkC s) (MkC ps) = rep2 conPName [s, ps] repPrec :: Core TH.Name -> Core [(TH.Name,TH.PatQ)] -> DsM (Core TH.PatQ) repPrec (MkC c) (MkC rps) = rep2 recPName [c,rps] repPinfix :: Core TH.PatQ -> Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ) repPinfix (MkC p1) (MkC n) (MkC p2) = rep2 infixPName [p1, n, p2] repPtilde :: Core TH.PatQ -> DsM (Core TH.PatQ) repPtilde (MkC p) = rep2 tildePName [p] repPbang :: Core TH.PatQ -> DsM (Core TH.PatQ) repPbang (MkC p) = rep2 bangPName [p] repPaspat :: Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ) repPaspat (MkC s) (MkC p) = rep2 asPName [s, p] repPwild :: DsM (Core TH.PatQ) repPwild = rep2 wildPName [] repPlist :: Core [TH.PatQ] -> DsM (Core TH.PatQ) repPlist (MkC ps) = rep2 listPName [ps] repPview :: Core TH.ExpQ -> Core TH.PatQ -> DsM (Core TH.PatQ) repPview (MkC e) (MkC p) = rep2 viewPName [e,p] --------------- Expressions ----------------- repVarOrCon :: Name -> Core TH.Name -> DsM (Core TH.ExpQ) repVarOrCon vc str | isDataOcc (nameOccName vc) = repCon str | otherwise = repVar str repVar :: Core TH.Name -> DsM (Core TH.ExpQ) repVar (MkC s) = rep2 varEName [s] repCon :: Core TH.Name -> DsM (Core TH.ExpQ) repCon (MkC s) = rep2 conEName [s] repLit :: Core TH.Lit -> DsM (Core TH.ExpQ) repLit (MkC c) = rep2 litEName [c] repApp :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repApp (MkC x) (MkC y) = rep2 appEName [x,y] repLam :: Core [TH.PatQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repLam (MkC ps) (MkC e) = rep2 lamEName [ps, e] repLamCase :: Core [TH.MatchQ] -> DsM (Core TH.ExpQ) repLamCase (MkC ms) = rep2 lamCaseEName [ms] repTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ) repTup (MkC es) = rep2 tupEName [es] repUnboxedTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ) repUnboxedTup (MkC es) = rep2 unboxedTupEName [es] repCond :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repCond (MkC x) (MkC y) (MkC z) = rep2 condEName [x,y,z] repMultiIf :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.ExpQ) repMultiIf (MkC alts) = rep2 multiIfEName [alts] repLetE :: Core [TH.DecQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repLetE (MkC ds) (MkC e) = rep2 letEName [ds, e] repCaseE :: Core TH.ExpQ -> Core [TH.MatchQ] -> DsM( Core TH.ExpQ) repCaseE (MkC e) (MkC ms) = rep2 caseEName [e, ms] repDoE :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ) repDoE (MkC ss) = rep2 doEName [ss] repComp :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ) repComp (MkC ss) = rep2 compEName [ss] repListExp :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ) repListExp (MkC es) = rep2 listEName [es] repSigExp :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ) repSigExp (MkC e) (MkC t) = rep2 sigEName [e,t] repRecCon :: Core TH.Name -> Core [TH.Q TH.FieldExp]-> DsM (Core TH.ExpQ) repRecCon (MkC c) (MkC fs) = rep2 recConEName [c,fs] repRecUpd :: Core TH.ExpQ -> Core [TH.Q TH.FieldExp] -> DsM (Core TH.ExpQ) repRecUpd (MkC e) (MkC fs) = rep2 recUpdEName [e,fs] repFieldExp :: Core TH.Name -> Core TH.ExpQ -> DsM (Core (TH.Q TH.FieldExp)) repFieldExp (MkC n) (MkC x) = rep2 fieldExpName [n,x] repInfixApp :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repInfixApp (MkC x) (MkC y) (MkC z) = rep2 infixAppName [x,y,z] repSectionL :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repSectionL (MkC x) (MkC y) = rep2 sectionLName [x,y] repSectionR :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repSectionR (MkC x) (MkC y) = rep2 sectionRName [x,y] ------------ Right hand sides (guarded expressions) ---- repGuarded :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.BodyQ) repGuarded (MkC pairs) = rep2 guardedBName [pairs] repNormal :: Core TH.ExpQ -> DsM (Core TH.BodyQ) repNormal (MkC e) = rep2 normalBName [e] ------------ Guards ---- repLNormalGE :: LHsExpr Name -> LHsExpr Name -> DsM (Core (TH.Q (TH.Guard, TH.Exp))) repLNormalGE g e = do g' <- repLE g e' <- repLE e repNormalGE g' e' repNormalGE :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp))) repNormalGE (MkC g) (MkC e) = rep2 normalGEName [g, e] repPatGE :: Core [TH.StmtQ] -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp))) repPatGE (MkC ss) (MkC e) = rep2 patGEName [ss, e] ------------- Stmts ------------------- repBindSt :: Core TH.PatQ -> Core TH.ExpQ -> DsM (Core TH.StmtQ) repBindSt (MkC p) (MkC e) = rep2 bindSName [p,e] repLetSt :: Core [TH.DecQ] -> DsM (Core TH.StmtQ) repLetSt (MkC ds) = rep2 letSName [ds] repNoBindSt :: Core TH.ExpQ -> DsM (Core TH.StmtQ) repNoBindSt (MkC e) = rep2 noBindSName [e] repParSt :: Core [[TH.StmtQ]] -> DsM (Core TH.StmtQ) repParSt (MkC sss) = rep2 parSName [sss] -------------- Range (Arithmetic sequences) ----------- repFrom :: Core TH.ExpQ -> DsM (Core TH.ExpQ) repFrom (MkC x) = rep2 fromEName [x] repFromThen :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repFromThen (MkC x) (MkC y) = rep2 fromThenEName [x,y] repFromTo :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repFromTo (MkC x) (MkC y) = rep2 fromToEName [x,y] repFromThenTo :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repFromThenTo (MkC x) (MkC y) (MkC z) = rep2 fromThenToEName [x,y,z] ------------ Match and Clause Tuples ----------- repMatch :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.MatchQ) repMatch (MkC p) (MkC bod) (MkC ds) = rep2 matchName [p, bod, ds] repClause :: Core [TH.PatQ] -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.ClauseQ) repClause (MkC ps) (MkC bod) (MkC ds) = rep2 clauseName [ps, bod, ds] -------------- Dec ----------------------------- repVal :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ) repVal (MkC p) (MkC b) (MkC ds) = rep2 valDName [p, b, ds] repFun :: Core TH.Name -> Core [TH.ClauseQ] -> DsM (Core TH.DecQ) repFun (MkC nm) (MkC b) = rep2 funDName [nm, b] repData :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] -> Maybe (Core [TH.TypeQ]) -> Core [TH.ConQ] -> Core [TH.Name] -> DsM (Core TH.DecQ) repData (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC cons) (MkC derivs) = rep2 dataDName [cxt, nm, tvs, cons, derivs] repData (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC cons) (MkC derivs) = rep2 dataInstDName [cxt, nm, tys, cons, derivs] repNewtype :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] -> Maybe (Core [TH.TypeQ]) -> Core TH.ConQ -> Core [TH.Name] -> DsM (Core TH.DecQ) repNewtype (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC con) (MkC derivs) = rep2 newtypeDName [cxt, nm, tvs, con, derivs] repNewtype (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC con) (MkC derivs) = rep2 newtypeInstDName [cxt, nm, tys, con, derivs] repTySyn :: Core TH.Name -> Core [TH.TyVarBndr] -> Core TH.TypeQ -> DsM (Core TH.DecQ) repTySyn (MkC nm) (MkC tvs) (MkC rhs) = rep2 tySynDName [nm, tvs, rhs] repInst :: Core TH.CxtQ -> Core TH.TypeQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ) repInst (MkC cxt) (MkC ty) (MkC ds) = rep2 instanceDName [cxt, ty, ds] repClass :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] -> Core [TH.FunDep] -> Core [TH.DecQ] -> DsM (Core TH.DecQ) repClass (MkC cxt) (MkC cls) (MkC tvs) (MkC fds) (MkC ds) = rep2 classDName [cxt, cls, tvs, fds, ds] repPragInl :: Core TH.Name -> Core TH.Inline -> Core TH.RuleMatch -> Core TH.Phases -> DsM (Core TH.DecQ) repPragInl (MkC nm) (MkC inline) (MkC rm) (MkC phases) = rep2 pragInlDName [nm, inline, rm, phases] repPragSpec :: Core TH.Name -> Core TH.TypeQ -> Core TH.Phases -> DsM (Core TH.DecQ) repPragSpec (MkC nm) (MkC ty) (MkC phases) = rep2 pragSpecDName [nm, ty, phases] repPragSpecInl :: Core TH.Name -> Core TH.TypeQ -> Core TH.Inline -> Core TH.Phases -> DsM (Core TH.DecQ) repPragSpecInl (MkC nm) (MkC ty) (MkC inline) (MkC phases) = rep2 pragSpecInlDName [nm, ty, inline, phases] repPragSpecInst :: Core TH.TypeQ -> DsM (Core TH.DecQ) repPragSpecInst (MkC ty) = rep2 pragSpecInstDName [ty] repPragRule :: Core String -> Core [TH.RuleBndrQ] -> Core TH.ExpQ -> Core TH.ExpQ -> Core TH.Phases -> DsM (Core TH.DecQ) repPragRule (MkC nm) (MkC bndrs) (MkC lhs) (MkC rhs) (MkC phases) = rep2 pragRuleDName [nm, bndrs, lhs, rhs, phases] repFamilyNoKind :: Core TH.FamFlavour -> Core TH.Name -> Core [TH.TyVarBndr] -> DsM (Core TH.DecQ) repFamilyNoKind (MkC flav) (MkC nm) (MkC tvs) = rep2 familyNoKindDName [flav, nm, tvs] repFamilyKind :: Core TH.FamFlavour -> Core TH.Name -> Core [TH.TyVarBndr] -> Core TH.Kind -> DsM (Core TH.DecQ) repFamilyKind (MkC flav) (MkC nm) (MkC tvs) (MkC ki) = rep2 familyKindDName [flav, nm, tvs, ki] repTySynInst :: Core TH.Name -> Core TH.TySynEqnQ -> DsM (Core TH.DecQ) repTySynInst (MkC nm) (MkC eqn) = rep2 tySynInstDName [nm, eqn] repClosedFamilyNoKind :: Core TH.Name -> Core [TH.TyVarBndr] -> Core [TH.TySynEqnQ] -> DsM (Core TH.DecQ) repClosedFamilyNoKind (MkC nm) (MkC tvs) (MkC eqns) = rep2 closedTypeFamilyNoKindDName [nm, tvs, eqns] repClosedFamilyKind :: Core TH.Name -> Core [TH.TyVarBndr] -> Core TH.Kind -> Core [TH.TySynEqnQ] -> DsM (Core TH.DecQ) repClosedFamilyKind (MkC nm) (MkC tvs) (MkC ki) (MkC eqns) = rep2 closedTypeFamilyKindDName [nm, tvs, ki, eqns] repTySynEqn :: Core [TH.TypeQ] -> Core TH.TypeQ -> DsM (Core TH.TySynEqnQ) repTySynEqn (MkC lhs) (MkC rhs) = rep2 tySynEqnName [lhs, rhs] repRoleAnnotD :: Core TH.Name -> Core [TH.Role] -> DsM (Core TH.DecQ) repRoleAnnotD (MkC n) (MkC roles) = rep2 roleAnnotDName [n, roles] repFunDep :: Core [TH.Name] -> Core [TH.Name] -> DsM (Core TH.FunDep) repFunDep (MkC xs) (MkC ys) = rep2 funDepName [xs, ys] repProto :: Core TH.Name -> Core TH.TypeQ -> DsM (Core TH.DecQ) repProto (MkC s) (MkC ty) = rep2 sigDName [s, ty] repCtxt :: Core [TH.PredQ] -> DsM (Core TH.CxtQ) repCtxt (MkC tys) = rep2 cxtName [tys] repConstr :: Core TH.Name -> HsConDeclDetails Name -> DsM (Core TH.ConQ) repConstr con (PrefixCon ps) = do arg_tys <- repList strictTypeQTyConName repBangTy ps rep2 normalCName [unC con, unC arg_tys] repConstr con (RecCon ips) = do { arg_vtys <- repList varStrictTypeQTyConName rep_ip ips ; rep2 recCName [unC con, unC arg_vtys] } where rep_ip ip = do { MkC v <- lookupLOcc (cd_fld_name ip) ; MkC ty <- repBangTy (cd_fld_type ip) ; rep2 varStrictTypeName [v,ty] } repConstr con (InfixCon st1 st2) = do arg1 <- repBangTy st1 arg2 <- repBangTy st2 rep2 infixCName [unC arg1, unC con, unC arg2] ------------ Types ------------------- repTForall :: Core [TH.TyVarBndr] -> Core TH.CxtQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ) repTForall (MkC tvars) (MkC ctxt) (MkC ty) = rep2 forallTName [tvars, ctxt, ty] repTvar :: Core TH.Name -> DsM (Core TH.TypeQ) repTvar (MkC s) = rep2 varTName [s] repTapp :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ) repTapp (MkC t1) (MkC t2) = rep2 appTName [t1, t2] repTapps :: Core TH.TypeQ -> [Core TH.TypeQ] -> DsM (Core TH.TypeQ) repTapps f [] = return f repTapps f (t:ts) = do { f1 <- repTapp f t; repTapps f1 ts } repTSig :: Core TH.TypeQ -> Core TH.Kind -> DsM (Core TH.TypeQ) repTSig (MkC ty) (MkC ki) = rep2 sigTName [ty, ki] repTequality :: DsM (Core TH.TypeQ) repTequality = rep2 equalityTName [] repTPromotedList :: [Core TH.TypeQ] -> DsM (Core TH.TypeQ) repTPromotedList [] = repPromotedNilTyCon repTPromotedList (t:ts) = do { tcon <- repPromotedConsTyCon ; f <- repTapp tcon t ; t' <- repTPromotedList ts ; repTapp f t' } repTLit :: Core TH.TyLitQ -> DsM (Core TH.TypeQ) repTLit (MkC lit) = rep2 litTName [lit] --------- Type constructors -------------- repNamedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ) repNamedTyCon (MkC s) = rep2 conTName [s] repTupleTyCon :: Int -> DsM (Core TH.TypeQ) -- Note: not Core Int; it's easier to be direct here repTupleTyCon i = do dflags <- getDynFlags rep2 tupleTName [mkIntExprInt dflags i] repUnboxedTupleTyCon :: Int -> DsM (Core TH.TypeQ) -- Note: not Core Int; it's easier to be direct here repUnboxedTupleTyCon i = do dflags <- getDynFlags rep2 unboxedTupleTName [mkIntExprInt dflags i] repArrowTyCon :: DsM (Core TH.TypeQ) repArrowTyCon = rep2 arrowTName [] repListTyCon :: DsM (Core TH.TypeQ) repListTyCon = rep2 listTName [] repPromotedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ) repPromotedTyCon (MkC s) = rep2 promotedTName [s] repPromotedTupleTyCon :: Int -> DsM (Core TH.TypeQ) repPromotedTupleTyCon i = do dflags <- getDynFlags rep2 promotedTupleTName [mkIntExprInt dflags i] repPromotedNilTyCon :: DsM (Core TH.TypeQ) repPromotedNilTyCon = rep2 promotedNilTName [] repPromotedConsTyCon :: DsM (Core TH.TypeQ) repPromotedConsTyCon = rep2 promotedConsTName [] ------------ Kinds ------------------- repPlainTV :: Core TH.Name -> DsM (Core TH.TyVarBndr) repPlainTV (MkC nm) = rep2 plainTVName [nm] repKindedTV :: Core TH.Name -> Core TH.Kind -> DsM (Core TH.TyVarBndr) repKindedTV (MkC nm) (MkC ki) = rep2 kindedTVName [nm, ki] repKVar :: Core TH.Name -> DsM (Core TH.Kind) repKVar (MkC s) = rep2 varKName [s] repKCon :: Core TH.Name -> DsM (Core TH.Kind) repKCon (MkC s) = rep2 conKName [s] repKTuple :: Int -> DsM (Core TH.Kind) repKTuple i = do dflags <- getDynFlags rep2 tupleKName [mkIntExprInt dflags i] repKArrow :: DsM (Core TH.Kind) repKArrow = rep2 arrowKName [] repKList :: DsM (Core TH.Kind) repKList = rep2 listKName [] repKApp :: Core TH.Kind -> Core TH.Kind -> DsM (Core TH.Kind) repKApp (MkC k1) (MkC k2) = rep2 appKName [k1, k2] repKApps :: Core TH.Kind -> [Core TH.Kind] -> DsM (Core TH.Kind) repKApps f [] = return f repKApps f (k:ks) = do { f' <- repKApp f k; repKApps f' ks } repKStar :: DsM (Core TH.Kind) repKStar = rep2 starKName [] repKConstraint :: DsM (Core TH.Kind) repKConstraint = rep2 constraintKName [] ---------------------------------------------------------- -- Literals repLiteral :: HsLit -> DsM (Core TH.Lit) repLiteral lit = do lit' <- case lit of HsIntPrim i -> mk_integer i HsWordPrim w -> mk_integer w HsInt i -> mk_integer i HsFloatPrim r -> mk_rational r HsDoublePrim r -> mk_rational r _ -> return lit lit_expr <- dsLit lit' case mb_lit_name of Just lit_name -> rep2 lit_name [lit_expr] Nothing -> notHandled "Exotic literal" (ppr lit) where mb_lit_name = case lit of HsInteger _ _ -> Just integerLName HsInt _ -> Just integerLName HsIntPrim _ -> Just intPrimLName HsWordPrim _ -> Just wordPrimLName HsFloatPrim _ -> Just floatPrimLName HsDoublePrim _ -> Just doublePrimLName HsChar _ -> Just charLName HsString _ -> Just stringLName HsRat _ _ -> Just rationalLName _ -> Nothing mk_integer :: Integer -> DsM HsLit mk_integer i = do integer_ty <- lookupType integerTyConName return $ HsInteger i integer_ty mk_rational :: FractionalLit -> DsM HsLit mk_rational r = do rat_ty <- lookupType rationalTyConName return $ HsRat r rat_ty mk_string :: FastString -> DsM HsLit mk_string s = return $ HsString s repOverloadedLiteral :: HsOverLit Name -> DsM (Core TH.Lit) repOverloadedLiteral (OverLit { ol_val = val}) = do { lit <- mk_lit val; repLiteral lit } -- The type Rational will be in the environment, because -- the smart constructor 'TH.Syntax.rationalL' uses it in its type, -- and rationalL is sucked in when any TH stuff is used mk_lit :: OverLitVal -> DsM HsLit mk_lit (HsIntegral i) = mk_integer i mk_lit (HsFractional f) = mk_rational f mk_lit (HsIsString s) = mk_string s --------------- Miscellaneous ------------------- repGensym :: Core String -> DsM (Core (TH.Q TH.Name)) repGensym (MkC lit_str) = rep2 newNameName [lit_str] repBindQ :: Type -> Type -- a and b -> Core (TH.Q a) -> Core (a -> TH.Q b) -> DsM (Core (TH.Q b)) repBindQ ty_a ty_b (MkC x) (MkC y) = rep2 bindQName [Type ty_a, Type ty_b, x, y] repSequenceQ :: Type -> Core [TH.Q a] -> DsM (Core (TH.Q [a])) repSequenceQ ty_a (MkC list) = rep2 sequenceQName [Type ty_a, list] ------------ Lists and Tuples ------------------- -- turn a list of patterns into a single pattern matching a list repList :: Name -> (a -> DsM (Core b)) -> [a] -> DsM (Core [b]) repList tc_name f args = do { args1 <- mapM f args ; coreList tc_name args1 } coreList :: Name -- Of the TyCon of the element type -> [Core a] -> DsM (Core [a]) coreList tc_name es = do { elt_ty <- lookupType tc_name; return (coreList' elt_ty es) } coreList' :: Type -- The element type -> [Core a] -> Core [a] coreList' elt_ty es = MkC (mkListExpr elt_ty (map unC es )) nonEmptyCoreList :: [Core a] -> Core [a] -- The list must be non-empty so we can get the element type -- Otherwise use coreList nonEmptyCoreList [] = panic "coreList: empty argument" nonEmptyCoreList xs@(MkC x:_) = MkC (mkListExpr (exprType x) (map unC xs)) coreStringLit :: String -> DsM (Core String) coreStringLit s = do { z <- mkStringExpr s; return(MkC z) } ------------ Literals & Variables ------------------- coreIntLit :: Int -> DsM (Core Int) coreIntLit i = do dflags <- getDynFlags return (MkC (mkIntExprInt dflags i)) coreVar :: Id -> Core TH.Name -- The Id has type Name coreVar id = MkC (Var id) ----------------- Failure ----------------------- notHandled :: String -> SDoc -> DsM a notHandled what doc = failWithDs msg where msg = hang (text what <+> ptext (sLit "not (yet) handled by Template Haskell")) 2 doc -- %************************************************************************ -- %* * -- The known-key names for Template Haskell -- %* * -- %************************************************************************ -- To add a name, do three things -- -- 1) Allocate a key -- 2) Make a "Name" -- 3) Add the name to knownKeyNames templateHaskellNames :: [Name] -- The names that are implicitly mentioned by ``bracket'' -- Should stay in sync with the import list of DsMeta templateHaskellNames = [ returnQName, bindQName, sequenceQName, newNameName, liftName, mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName, liftStringName, unTypeName, unTypeQName, unsafeTExpCoerceName, -- Lit charLName, stringLName, integerLName, intPrimLName, wordPrimLName, floatPrimLName, doublePrimLName, rationalLName, -- Pat litPName, varPName, tupPName, unboxedTupPName, conPName, tildePName, bangPName, infixPName, asPName, wildPName, recPName, listPName, sigPName, viewPName, -- FieldPat fieldPatName, -- Match matchName, -- Clause clauseName, -- Exp varEName, conEName, litEName, appEName, infixEName, infixAppName, sectionLName, sectionRName, lamEName, lamCaseEName, tupEName, unboxedTupEName, condEName, multiIfEName, letEName, caseEName, doEName, compEName, fromEName, fromThenEName, fromToEName, fromThenToEName, listEName, sigEName, recConEName, recUpdEName, -- FieldExp fieldExpName, -- Body guardedBName, normalBName, -- Guard normalGEName, patGEName, -- Stmt bindSName, letSName, noBindSName, parSName, -- Dec funDName, valDName, dataDName, newtypeDName, tySynDName, classDName, instanceDName, sigDName, forImpDName, pragInlDName, pragSpecDName, pragSpecInlDName, pragSpecInstDName, pragRuleDName, familyNoKindDName, familyKindDName, dataInstDName, newtypeInstDName, tySynInstDName, closedTypeFamilyKindDName, closedTypeFamilyNoKindDName, infixLDName, infixRDName, infixNDName, roleAnnotDName, -- Cxt cxtName, -- Strict isStrictName, notStrictName, unpackedName, -- Con normalCName, recCName, infixCName, forallCName, -- StrictType strictTypeName, -- VarStrictType varStrictTypeName, -- Type forallTName, varTName, conTName, appTName, equalityTName, tupleTName, unboxedTupleTName, arrowTName, listTName, sigTName, litTName, promotedTName, promotedTupleTName, promotedNilTName, promotedConsTName, -- TyLit numTyLitName, strTyLitName, -- TyVarBndr plainTVName, kindedTVName, -- Role nominalRName, representationalRName, phantomRName, inferRName, -- Kind varKName, conKName, tupleKName, arrowKName, listKName, appKName, starKName, constraintKName, -- Callconv cCallName, stdCallName, -- Safety unsafeName, safeName, interruptibleName, -- Inline noInlineDataConName, inlineDataConName, inlinableDataConName, -- RuleMatch conLikeDataConName, funLikeDataConName, -- Phases allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName, -- TExp tExpDataConName, -- RuleBndr ruleVarName, typedRuleVarName, -- FunDep funDepName, -- FamFlavour typeFamName, dataFamName, -- TySynEqn tySynEqnName, -- And the tycons qTyConName, nameTyConName, patTyConName, fieldPatTyConName, matchQTyConName, clauseQTyConName, expQTyConName, fieldExpTyConName, predTyConName, stmtQTyConName, decQTyConName, conQTyConName, strictTypeQTyConName, varStrictTypeQTyConName, typeQTyConName, expTyConName, decTyConName, typeTyConName, tyVarBndrTyConName, matchTyConName, clauseTyConName, patQTyConName, fieldPatQTyConName, fieldExpQTyConName, funDepTyConName, predQTyConName, decsQTyConName, ruleBndrQTyConName, tySynEqnQTyConName, roleTyConName, tExpTyConName, -- Quasiquoting quoteDecName, quoteTypeName, quoteExpName, quotePatName] thSyn, thLib, qqLib :: Module thSyn = mkTHModule (fsLit "Language.Haskell.TH.Syntax") thLib = mkTHModule (fsLit "Language.Haskell.TH.Lib") qqLib = mkTHModule (fsLit "Language.Haskell.TH.Quote") mkTHModule :: FastString -> Module mkTHModule m = mkModule thPackageKey (mkModuleNameFS m) libFun, libTc, thFun, thTc, thCon, qqFun :: FastString -> Unique -> Name libFun = mk_known_key_name OccName.varName thLib libTc = mk_known_key_name OccName.tcName thLib thFun = mk_known_key_name OccName.varName thSyn thTc = mk_known_key_name OccName.tcName thSyn thCon = mk_known_key_name OccName.dataName thSyn qqFun = mk_known_key_name OccName.varName qqLib -------------------- TH.Syntax ----------------------- qTyConName, nameTyConName, fieldExpTyConName, patTyConName, fieldPatTyConName, expTyConName, decTyConName, typeTyConName, tyVarBndrTyConName, matchTyConName, clauseTyConName, funDepTyConName, predTyConName, tExpTyConName :: Name qTyConName = thTc (fsLit "Q") qTyConKey nameTyConName = thTc (fsLit "Name") nameTyConKey fieldExpTyConName = thTc (fsLit "FieldExp") fieldExpTyConKey patTyConName = thTc (fsLit "Pat") patTyConKey fieldPatTyConName = thTc (fsLit "FieldPat") fieldPatTyConKey expTyConName = thTc (fsLit "Exp") expTyConKey decTyConName = thTc (fsLit "Dec") decTyConKey typeTyConName = thTc (fsLit "Type") typeTyConKey tyVarBndrTyConName= thTc (fsLit "TyVarBndr") tyVarBndrTyConKey matchTyConName = thTc (fsLit "Match") matchTyConKey clauseTyConName = thTc (fsLit "Clause") clauseTyConKey funDepTyConName = thTc (fsLit "FunDep") funDepTyConKey predTyConName = thTc (fsLit "Pred") predTyConKey tExpTyConName = thTc (fsLit "TExp") tExpTyConKey returnQName, bindQName, sequenceQName, newNameName, liftName, mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName, liftStringName, unTypeName, unTypeQName, unsafeTExpCoerceName :: Name returnQName = thFun (fsLit "returnQ") returnQIdKey bindQName = thFun (fsLit "bindQ") bindQIdKey sequenceQName = thFun (fsLit "sequenceQ") sequenceQIdKey newNameName = thFun (fsLit "newName") newNameIdKey liftName = thFun (fsLit "lift") liftIdKey liftStringName = thFun (fsLit "liftString") liftStringIdKey mkNameName = thFun (fsLit "mkName") mkNameIdKey mkNameG_vName = thFun (fsLit "mkNameG_v") mkNameG_vIdKey mkNameG_dName = thFun (fsLit "mkNameG_d") mkNameG_dIdKey mkNameG_tcName = thFun (fsLit "mkNameG_tc") mkNameG_tcIdKey mkNameLName = thFun (fsLit "mkNameL") mkNameLIdKey unTypeName = thFun (fsLit "unType") unTypeIdKey unTypeQName = thFun (fsLit "unTypeQ") unTypeQIdKey unsafeTExpCoerceName = thFun (fsLit "unsafeTExpCoerce") unsafeTExpCoerceIdKey -------------------- TH.Lib ----------------------- -- data Lit = ... charLName, stringLName, integerLName, intPrimLName, wordPrimLName, floatPrimLName, doublePrimLName, rationalLName :: Name charLName = libFun (fsLit "charL") charLIdKey stringLName = libFun (fsLit "stringL") stringLIdKey integerLName = libFun (fsLit "integerL") integerLIdKey intPrimLName = libFun (fsLit "intPrimL") intPrimLIdKey wordPrimLName = libFun (fsLit "wordPrimL") wordPrimLIdKey floatPrimLName = libFun (fsLit "floatPrimL") floatPrimLIdKey doublePrimLName = libFun (fsLit "doublePrimL") doublePrimLIdKey rationalLName = libFun (fsLit "rationalL") rationalLIdKey -- data Pat = ... litPName, varPName, tupPName, unboxedTupPName, conPName, infixPName, tildePName, bangPName, asPName, wildPName, recPName, listPName, sigPName, viewPName :: Name litPName = libFun (fsLit "litP") litPIdKey varPName = libFun (fsLit "varP") varPIdKey tupPName = libFun (fsLit "tupP") tupPIdKey unboxedTupPName = libFun (fsLit "unboxedTupP") unboxedTupPIdKey conPName = libFun (fsLit "conP") conPIdKey infixPName = libFun (fsLit "infixP") infixPIdKey tildePName = libFun (fsLit "tildeP") tildePIdKey bangPName = libFun (fsLit "bangP") bangPIdKey asPName = libFun (fsLit "asP") asPIdKey wildPName = libFun (fsLit "wildP") wildPIdKey recPName = libFun (fsLit "recP") recPIdKey listPName = libFun (fsLit "listP") listPIdKey sigPName = libFun (fsLit "sigP") sigPIdKey viewPName = libFun (fsLit "viewP") viewPIdKey -- type FieldPat = ... fieldPatName :: Name fieldPatName = libFun (fsLit "fieldPat") fieldPatIdKey -- data Match = ... matchName :: Name matchName = libFun (fsLit "match") matchIdKey -- data Clause = ... clauseName :: Name clauseName = libFun (fsLit "clause") clauseIdKey -- data Exp = ... varEName, conEName, litEName, appEName, infixEName, infixAppName, sectionLName, sectionRName, lamEName, lamCaseEName, tupEName, unboxedTupEName, condEName, multiIfEName, letEName, caseEName, doEName, compEName :: Name varEName = libFun (fsLit "varE") varEIdKey conEName = libFun (fsLit "conE") conEIdKey litEName = libFun (fsLit "litE") litEIdKey appEName = libFun (fsLit "appE") appEIdKey infixEName = libFun (fsLit "infixE") infixEIdKey infixAppName = libFun (fsLit "infixApp") infixAppIdKey sectionLName = libFun (fsLit "sectionL") sectionLIdKey sectionRName = libFun (fsLit "sectionR") sectionRIdKey lamEName = libFun (fsLit "lamE") lamEIdKey lamCaseEName = libFun (fsLit "lamCaseE") lamCaseEIdKey tupEName = libFun (fsLit "tupE") tupEIdKey unboxedTupEName = libFun (fsLit "unboxedTupE") unboxedTupEIdKey condEName = libFun (fsLit "condE") condEIdKey multiIfEName = libFun (fsLit "multiIfE") multiIfEIdKey letEName = libFun (fsLit "letE") letEIdKey caseEName = libFun (fsLit "caseE") caseEIdKey doEName = libFun (fsLit "doE") doEIdKey compEName = libFun (fsLit "compE") compEIdKey -- ArithSeq skips a level fromEName, fromThenEName, fromToEName, fromThenToEName :: Name fromEName = libFun (fsLit "fromE") fromEIdKey fromThenEName = libFun (fsLit "fromThenE") fromThenEIdKey fromToEName = libFun (fsLit "fromToE") fromToEIdKey fromThenToEName = libFun (fsLit "fromThenToE") fromThenToEIdKey -- end ArithSeq listEName, sigEName, recConEName, recUpdEName :: Name listEName = libFun (fsLit "listE") listEIdKey sigEName = libFun (fsLit "sigE") sigEIdKey recConEName = libFun (fsLit "recConE") recConEIdKey recUpdEName = libFun (fsLit "recUpdE") recUpdEIdKey -- type FieldExp = ... fieldExpName :: Name fieldExpName = libFun (fsLit "fieldExp") fieldExpIdKey -- data Body = ... guardedBName, normalBName :: Name guardedBName = libFun (fsLit "guardedB") guardedBIdKey normalBName = libFun (fsLit "normalB") normalBIdKey -- data Guard = ... normalGEName, patGEName :: Name normalGEName = libFun (fsLit "normalGE") normalGEIdKey patGEName = libFun (fsLit "patGE") patGEIdKey -- data Stmt = ... bindSName, letSName, noBindSName, parSName :: Name bindSName = libFun (fsLit "bindS") bindSIdKey letSName = libFun (fsLit "letS") letSIdKey noBindSName = libFun (fsLit "noBindS") noBindSIdKey parSName = libFun (fsLit "parS") parSIdKey -- data Dec = ... funDName, valDName, dataDName, newtypeDName, tySynDName, classDName, instanceDName, sigDName, forImpDName, pragInlDName, pragSpecDName, pragSpecInlDName, pragSpecInstDName, pragRuleDName, familyNoKindDName, familyKindDName, dataInstDName, newtypeInstDName, tySynInstDName, closedTypeFamilyKindDName, closedTypeFamilyNoKindDName, infixLDName, infixRDName, infixNDName, roleAnnotDName :: Name funDName = libFun (fsLit "funD") funDIdKey valDName = libFun (fsLit "valD") valDIdKey dataDName = libFun (fsLit "dataD") dataDIdKey newtypeDName = libFun (fsLit "newtypeD") newtypeDIdKey tySynDName = libFun (fsLit "tySynD") tySynDIdKey classDName = libFun (fsLit "classD") classDIdKey instanceDName = libFun (fsLit "instanceD") instanceDIdKey sigDName = libFun (fsLit "sigD") sigDIdKey forImpDName = libFun (fsLit "forImpD") forImpDIdKey pragInlDName = libFun (fsLit "pragInlD") pragInlDIdKey pragSpecDName = libFun (fsLit "pragSpecD") pragSpecDIdKey pragSpecInlDName = libFun (fsLit "pragSpecInlD") pragSpecInlDIdKey pragSpecInstDName = libFun (fsLit "pragSpecInstD") pragSpecInstDIdKey pragRuleDName = libFun (fsLit "pragRuleD") pragRuleDIdKey familyNoKindDName = libFun (fsLit "familyNoKindD") familyNoKindDIdKey familyKindDName = libFun (fsLit "familyKindD") familyKindDIdKey dataInstDName = libFun (fsLit "dataInstD") dataInstDIdKey newtypeInstDName = libFun (fsLit "newtypeInstD") newtypeInstDIdKey tySynInstDName = libFun (fsLit "tySynInstD") tySynInstDIdKey closedTypeFamilyKindDName = libFun (fsLit "closedTypeFamilyKindD") closedTypeFamilyKindDIdKey closedTypeFamilyNoKindDName = libFun (fsLit "closedTypeFamilyNoKindD") closedTypeFamilyNoKindDIdKey infixLDName = libFun (fsLit "infixLD") infixLDIdKey infixRDName = libFun (fsLit "infixRD") infixRDIdKey infixNDName = libFun (fsLit "infixND") infixNDIdKey roleAnnotDName = libFun (fsLit "roleAnnotD") roleAnnotDIdKey -- type Ctxt = ... cxtName :: Name cxtName = libFun (fsLit "cxt") cxtIdKey -- data Strict = ... isStrictName, notStrictName, unpackedName :: Name isStrictName = libFun (fsLit "isStrict") isStrictKey notStrictName = libFun (fsLit "notStrict") notStrictKey unpackedName = libFun (fsLit "unpacked") unpackedKey -- data Con = ... normalCName, recCName, infixCName, forallCName :: Name normalCName = libFun (fsLit "normalC") normalCIdKey recCName = libFun (fsLit "recC") recCIdKey infixCName = libFun (fsLit "infixC") infixCIdKey forallCName = libFun (fsLit "forallC") forallCIdKey -- type StrictType = ... strictTypeName :: Name strictTypeName = libFun (fsLit "strictType") strictTKey -- type VarStrictType = ... varStrictTypeName :: Name varStrictTypeName = libFun (fsLit "varStrictType") varStrictTKey -- data Type = ... forallTName, varTName, conTName, tupleTName, unboxedTupleTName, arrowTName, listTName, appTName, sigTName, equalityTName, litTName, promotedTName, promotedTupleTName, promotedNilTName, promotedConsTName :: Name forallTName = libFun (fsLit "forallT") forallTIdKey varTName = libFun (fsLit "varT") varTIdKey conTName = libFun (fsLit "conT") conTIdKey tupleTName = libFun (fsLit "tupleT") tupleTIdKey unboxedTupleTName = libFun (fsLit "unboxedTupleT") unboxedTupleTIdKey arrowTName = libFun (fsLit "arrowT") arrowTIdKey listTName = libFun (fsLit "listT") listTIdKey appTName = libFun (fsLit "appT") appTIdKey sigTName = libFun (fsLit "sigT") sigTIdKey equalityTName = libFun (fsLit "equalityT") equalityTIdKey litTName = libFun (fsLit "litT") litTIdKey promotedTName = libFun (fsLit "promotedT") promotedTIdKey promotedTupleTName = libFun (fsLit "promotedTupleT") promotedTupleTIdKey promotedNilTName = libFun (fsLit "promotedNilT") promotedNilTIdKey promotedConsTName = libFun (fsLit "promotedConsT") promotedConsTIdKey -- data TyLit = ... numTyLitName, strTyLitName :: Name numTyLitName = libFun (fsLit "numTyLit") numTyLitIdKey strTyLitName = libFun (fsLit "strTyLit") strTyLitIdKey -- data TyVarBndr = ... plainTVName, kindedTVName :: Name plainTVName = libFun (fsLit "plainTV") plainTVIdKey kindedTVName = libFun (fsLit "kindedTV") kindedTVIdKey -- data Role = ... nominalRName, representationalRName, phantomRName, inferRName :: Name nominalRName = libFun (fsLit "nominalR") nominalRIdKey representationalRName = libFun (fsLit "representationalR") representationalRIdKey phantomRName = libFun (fsLit "phantomR") phantomRIdKey inferRName = libFun (fsLit "inferR") inferRIdKey -- data Kind = ... varKName, conKName, tupleKName, arrowKName, listKName, appKName, starKName, constraintKName :: Name varKName = libFun (fsLit "varK") varKIdKey conKName = libFun (fsLit "conK") conKIdKey tupleKName = libFun (fsLit "tupleK") tupleKIdKey arrowKName = libFun (fsLit "arrowK") arrowKIdKey listKName = libFun (fsLit "listK") listKIdKey appKName = libFun (fsLit "appK") appKIdKey starKName = libFun (fsLit "starK") starKIdKey constraintKName = libFun (fsLit "constraintK") constraintKIdKey -- data Callconv = ... cCallName, stdCallName :: Name cCallName = libFun (fsLit "cCall") cCallIdKey stdCallName = libFun (fsLit "stdCall") stdCallIdKey -- data Safety = ... unsafeName, safeName, interruptibleName :: Name unsafeName = libFun (fsLit "unsafe") unsafeIdKey safeName = libFun (fsLit "safe") safeIdKey interruptibleName = libFun (fsLit "interruptible") interruptibleIdKey -- data Inline = ... noInlineDataConName, inlineDataConName, inlinableDataConName :: Name noInlineDataConName = thCon (fsLit "NoInline") noInlineDataConKey inlineDataConName = thCon (fsLit "Inline") inlineDataConKey inlinableDataConName = thCon (fsLit "Inlinable") inlinableDataConKey -- data RuleMatch = ... conLikeDataConName, funLikeDataConName :: Name conLikeDataConName = thCon (fsLit "ConLike") conLikeDataConKey funLikeDataConName = thCon (fsLit "FunLike") funLikeDataConKey -- data Phases = ... allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName :: Name allPhasesDataConName = thCon (fsLit "AllPhases") allPhasesDataConKey fromPhaseDataConName = thCon (fsLit "FromPhase") fromPhaseDataConKey beforePhaseDataConName = thCon (fsLit "BeforePhase") beforePhaseDataConKey -- newtype TExp a = ... tExpDataConName :: Name tExpDataConName = thCon (fsLit "TExp") tExpDataConKey -- data RuleBndr = ... ruleVarName, typedRuleVarName :: Name ruleVarName = libFun (fsLit ("ruleVar")) ruleVarIdKey typedRuleVarName = libFun (fsLit ("typedRuleVar")) typedRuleVarIdKey -- data FunDep = ... funDepName :: Name funDepName = libFun (fsLit "funDep") funDepIdKey -- data FamFlavour = ... typeFamName, dataFamName :: Name typeFamName = libFun (fsLit "typeFam") typeFamIdKey dataFamName = libFun (fsLit "dataFam") dataFamIdKey -- data TySynEqn = ... tySynEqnName :: Name tySynEqnName = libFun (fsLit "tySynEqn") tySynEqnIdKey matchQTyConName, clauseQTyConName, expQTyConName, stmtQTyConName, decQTyConName, conQTyConName, strictTypeQTyConName, varStrictTypeQTyConName, typeQTyConName, fieldExpQTyConName, patQTyConName, fieldPatQTyConName, predQTyConName, decsQTyConName, ruleBndrQTyConName, tySynEqnQTyConName, roleTyConName :: Name matchQTyConName = libTc (fsLit "MatchQ") matchQTyConKey clauseQTyConName = libTc (fsLit "ClauseQ") clauseQTyConKey expQTyConName = libTc (fsLit "ExpQ") expQTyConKey stmtQTyConName = libTc (fsLit "StmtQ") stmtQTyConKey decQTyConName = libTc (fsLit "DecQ") decQTyConKey decsQTyConName = libTc (fsLit "DecsQ") decsQTyConKey -- Q [Dec] conQTyConName = libTc (fsLit "ConQ") conQTyConKey strictTypeQTyConName = libTc (fsLit "StrictTypeQ") strictTypeQTyConKey varStrictTypeQTyConName = libTc (fsLit "VarStrictTypeQ") varStrictTypeQTyConKey typeQTyConName = libTc (fsLit "TypeQ") typeQTyConKey fieldExpQTyConName = libTc (fsLit "FieldExpQ") fieldExpQTyConKey patQTyConName = libTc (fsLit "PatQ") patQTyConKey fieldPatQTyConName = libTc (fsLit "FieldPatQ") fieldPatQTyConKey predQTyConName = libTc (fsLit "PredQ") predQTyConKey ruleBndrQTyConName = libTc (fsLit "RuleBndrQ") ruleBndrQTyConKey tySynEqnQTyConName = libTc (fsLit "TySynEqnQ") tySynEqnQTyConKey roleTyConName = libTc (fsLit "Role") roleTyConKey -- quasiquoting quoteExpName, quotePatName, quoteDecName, quoteTypeName :: Name quoteExpName = qqFun (fsLit "quoteExp") quoteExpKey quotePatName = qqFun (fsLit "quotePat") quotePatKey quoteDecName = qqFun (fsLit "quoteDec") quoteDecKey quoteTypeName = qqFun (fsLit "quoteType") quoteTypeKey -- TyConUniques available: 200-299 -- Check in PrelNames if you want to change this expTyConKey, matchTyConKey, clauseTyConKey, qTyConKey, expQTyConKey, decQTyConKey, patTyConKey, matchQTyConKey, clauseQTyConKey, stmtQTyConKey, conQTyConKey, typeQTyConKey, typeTyConKey, tyVarBndrTyConKey, decTyConKey, varStrictTypeQTyConKey, strictTypeQTyConKey, fieldExpTyConKey, fieldPatTyConKey, nameTyConKey, patQTyConKey, fieldPatQTyConKey, fieldExpQTyConKey, funDepTyConKey, predTyConKey, predQTyConKey, decsQTyConKey, ruleBndrQTyConKey, tySynEqnQTyConKey, roleTyConKey, tExpTyConKey :: Unique expTyConKey = mkPreludeTyConUnique 200 matchTyConKey = mkPreludeTyConUnique 201 clauseTyConKey = mkPreludeTyConUnique 202 qTyConKey = mkPreludeTyConUnique 203 expQTyConKey = mkPreludeTyConUnique 204 decQTyConKey = mkPreludeTyConUnique 205 patTyConKey = mkPreludeTyConUnique 206 matchQTyConKey = mkPreludeTyConUnique 207 clauseQTyConKey = mkPreludeTyConUnique 208 stmtQTyConKey = mkPreludeTyConUnique 209 conQTyConKey = mkPreludeTyConUnique 210 typeQTyConKey = mkPreludeTyConUnique 211 typeTyConKey = mkPreludeTyConUnique 212 decTyConKey = mkPreludeTyConUnique 213 varStrictTypeQTyConKey = mkPreludeTyConUnique 214 strictTypeQTyConKey = mkPreludeTyConUnique 215 fieldExpTyConKey = mkPreludeTyConUnique 216 fieldPatTyConKey = mkPreludeTyConUnique 217 nameTyConKey = mkPreludeTyConUnique 218 patQTyConKey = mkPreludeTyConUnique 219 fieldPatQTyConKey = mkPreludeTyConUnique 220 fieldExpQTyConKey = mkPreludeTyConUnique 221 funDepTyConKey = mkPreludeTyConUnique 222 predTyConKey = mkPreludeTyConUnique 223 predQTyConKey = mkPreludeTyConUnique 224 tyVarBndrTyConKey = mkPreludeTyConUnique 225 decsQTyConKey = mkPreludeTyConUnique 226 ruleBndrQTyConKey = mkPreludeTyConUnique 227 tySynEqnQTyConKey = mkPreludeTyConUnique 228 roleTyConKey = mkPreludeTyConUnique 229 tExpTyConKey = mkPreludeTyConUnique 230 -- IdUniques available: 200-499 -- If you want to change this, make sure you check in PrelNames returnQIdKey, bindQIdKey, sequenceQIdKey, liftIdKey, newNameIdKey, mkNameIdKey, mkNameG_vIdKey, mkNameG_dIdKey, mkNameG_tcIdKey, mkNameLIdKey, unTypeIdKey, unTypeQIdKey, unsafeTExpCoerceIdKey :: Unique returnQIdKey = mkPreludeMiscIdUnique 200 bindQIdKey = mkPreludeMiscIdUnique 201 sequenceQIdKey = mkPreludeMiscIdUnique 202 liftIdKey = mkPreludeMiscIdUnique 203 newNameIdKey = mkPreludeMiscIdUnique 204 mkNameIdKey = mkPreludeMiscIdUnique 205 mkNameG_vIdKey = mkPreludeMiscIdUnique 206 mkNameG_dIdKey = mkPreludeMiscIdUnique 207 mkNameG_tcIdKey = mkPreludeMiscIdUnique 208 mkNameLIdKey = mkPreludeMiscIdUnique 209 unTypeIdKey = mkPreludeMiscIdUnique 210 unTypeQIdKey = mkPreludeMiscIdUnique 211 unsafeTExpCoerceIdKey = mkPreludeMiscIdUnique 212 -- data Lit = ... charLIdKey, stringLIdKey, integerLIdKey, intPrimLIdKey, wordPrimLIdKey, floatPrimLIdKey, doublePrimLIdKey, rationalLIdKey :: Unique charLIdKey = mkPreludeMiscIdUnique 220 stringLIdKey = mkPreludeMiscIdUnique 221 integerLIdKey = mkPreludeMiscIdUnique 222 intPrimLIdKey = mkPreludeMiscIdUnique 223 wordPrimLIdKey = mkPreludeMiscIdUnique 224 floatPrimLIdKey = mkPreludeMiscIdUnique 225 doublePrimLIdKey = mkPreludeMiscIdUnique 226 rationalLIdKey = mkPreludeMiscIdUnique 227 liftStringIdKey :: Unique liftStringIdKey = mkPreludeMiscIdUnique 228 -- data Pat = ... litPIdKey, varPIdKey, tupPIdKey, unboxedTupPIdKey, conPIdKey, infixPIdKey, tildePIdKey, bangPIdKey, asPIdKey, wildPIdKey, recPIdKey, listPIdKey, sigPIdKey, viewPIdKey :: Unique litPIdKey = mkPreludeMiscIdUnique 240 varPIdKey = mkPreludeMiscIdUnique 241 tupPIdKey = mkPreludeMiscIdUnique 242 unboxedTupPIdKey = mkPreludeMiscIdUnique 243 conPIdKey = mkPreludeMiscIdUnique 244 infixPIdKey = mkPreludeMiscIdUnique 245 tildePIdKey = mkPreludeMiscIdUnique 246 bangPIdKey = mkPreludeMiscIdUnique 247 asPIdKey = mkPreludeMiscIdUnique 248 wildPIdKey = mkPreludeMiscIdUnique 249 recPIdKey = mkPreludeMiscIdUnique 250 listPIdKey = mkPreludeMiscIdUnique 251 sigPIdKey = mkPreludeMiscIdUnique 252 viewPIdKey = mkPreludeMiscIdUnique 253 -- type FieldPat = ... fieldPatIdKey :: Unique fieldPatIdKey = mkPreludeMiscIdUnique 260 -- data Match = ... matchIdKey :: Unique matchIdKey = mkPreludeMiscIdUnique 261 -- data Clause = ... clauseIdKey :: Unique clauseIdKey = mkPreludeMiscIdUnique 262 -- data Exp = ... varEIdKey, conEIdKey, litEIdKey, appEIdKey, infixEIdKey, infixAppIdKey, sectionLIdKey, sectionRIdKey, lamEIdKey, lamCaseEIdKey, tupEIdKey, unboxedTupEIdKey, condEIdKey, multiIfEIdKey, letEIdKey, caseEIdKey, doEIdKey, compEIdKey, fromEIdKey, fromThenEIdKey, fromToEIdKey, fromThenToEIdKey, listEIdKey, sigEIdKey, recConEIdKey, recUpdEIdKey :: Unique varEIdKey = mkPreludeMiscIdUnique 270 conEIdKey = mkPreludeMiscIdUnique 271 litEIdKey = mkPreludeMiscIdUnique 272 appEIdKey = mkPreludeMiscIdUnique 273 infixEIdKey = mkPreludeMiscIdUnique 274 infixAppIdKey = mkPreludeMiscIdUnique 275 sectionLIdKey = mkPreludeMiscIdUnique 276 sectionRIdKey = mkPreludeMiscIdUnique 277 lamEIdKey = mkPreludeMiscIdUnique 278 lamCaseEIdKey = mkPreludeMiscIdUnique 279 tupEIdKey = mkPreludeMiscIdUnique 280 unboxedTupEIdKey = mkPreludeMiscIdUnique 281 condEIdKey = mkPreludeMiscIdUnique 282 multiIfEIdKey = mkPreludeMiscIdUnique 283 letEIdKey = mkPreludeMiscIdUnique 284 caseEIdKey = mkPreludeMiscIdUnique 285 doEIdKey = mkPreludeMiscIdUnique 286 compEIdKey = mkPreludeMiscIdUnique 287 fromEIdKey = mkPreludeMiscIdUnique 288 fromThenEIdKey = mkPreludeMiscIdUnique 289 fromToEIdKey = mkPreludeMiscIdUnique 290 fromThenToEIdKey = mkPreludeMiscIdUnique 291 listEIdKey = mkPreludeMiscIdUnique 292 sigEIdKey = mkPreludeMiscIdUnique 293 recConEIdKey = mkPreludeMiscIdUnique 294 recUpdEIdKey = mkPreludeMiscIdUnique 295 -- type FieldExp = ... fieldExpIdKey :: Unique fieldExpIdKey = mkPreludeMiscIdUnique 310 -- data Body = ... guardedBIdKey, normalBIdKey :: Unique guardedBIdKey = mkPreludeMiscIdUnique 311 normalBIdKey = mkPreludeMiscIdUnique 312 -- data Guard = ... normalGEIdKey, patGEIdKey :: Unique normalGEIdKey = mkPreludeMiscIdUnique 313 patGEIdKey = mkPreludeMiscIdUnique 314 -- data Stmt = ... bindSIdKey, letSIdKey, noBindSIdKey, parSIdKey :: Unique bindSIdKey = mkPreludeMiscIdUnique 320 letSIdKey = mkPreludeMiscIdUnique 321 noBindSIdKey = mkPreludeMiscIdUnique 322 parSIdKey = mkPreludeMiscIdUnique 323 -- data Dec = ... funDIdKey, valDIdKey, dataDIdKey, newtypeDIdKey, tySynDIdKey, classDIdKey, instanceDIdKey, sigDIdKey, forImpDIdKey, pragInlDIdKey, pragSpecDIdKey, pragSpecInlDIdKey, pragSpecInstDIdKey, pragRuleDIdKey, familyNoKindDIdKey, familyKindDIdKey, dataInstDIdKey, newtypeInstDIdKey, tySynInstDIdKey, closedTypeFamilyKindDIdKey, closedTypeFamilyNoKindDIdKey, infixLDIdKey, infixRDIdKey, infixNDIdKey, roleAnnotDIdKey :: Unique funDIdKey = mkPreludeMiscIdUnique 330 valDIdKey = mkPreludeMiscIdUnique 331 dataDIdKey = mkPreludeMiscIdUnique 332 newtypeDIdKey = mkPreludeMiscIdUnique 333 tySynDIdKey = mkPreludeMiscIdUnique 334 classDIdKey = mkPreludeMiscIdUnique 335 instanceDIdKey = mkPreludeMiscIdUnique 336 sigDIdKey = mkPreludeMiscIdUnique 337 forImpDIdKey = mkPreludeMiscIdUnique 338 pragInlDIdKey = mkPreludeMiscIdUnique 339 pragSpecDIdKey = mkPreludeMiscIdUnique 340 pragSpecInlDIdKey = mkPreludeMiscIdUnique 341 pragSpecInstDIdKey = mkPreludeMiscIdUnique 417 pragRuleDIdKey = mkPreludeMiscIdUnique 418 familyNoKindDIdKey = mkPreludeMiscIdUnique 342 familyKindDIdKey = mkPreludeMiscIdUnique 343 dataInstDIdKey = mkPreludeMiscIdUnique 344 newtypeInstDIdKey = mkPreludeMiscIdUnique 345 tySynInstDIdKey = mkPreludeMiscIdUnique 346 closedTypeFamilyKindDIdKey = mkPreludeMiscIdUnique 347 closedTypeFamilyNoKindDIdKey = mkPreludeMiscIdUnique 348 infixLDIdKey = mkPreludeMiscIdUnique 349 infixRDIdKey = mkPreludeMiscIdUnique 350 infixNDIdKey = mkPreludeMiscIdUnique 351 roleAnnotDIdKey = mkPreludeMiscIdUnique 352 -- type Cxt = ... cxtIdKey :: Unique cxtIdKey = mkPreludeMiscIdUnique 360 -- data Strict = ... isStrictKey, notStrictKey, unpackedKey :: Unique isStrictKey = mkPreludeMiscIdUnique 363 notStrictKey = mkPreludeMiscIdUnique 364 unpackedKey = mkPreludeMiscIdUnique 365 -- data Con = ... normalCIdKey, recCIdKey, infixCIdKey, forallCIdKey :: Unique normalCIdKey = mkPreludeMiscIdUnique 370 recCIdKey = mkPreludeMiscIdUnique 371 infixCIdKey = mkPreludeMiscIdUnique 372 forallCIdKey = mkPreludeMiscIdUnique 373 -- type StrictType = ... strictTKey :: Unique strictTKey = mkPreludeMiscIdUnique 374 -- type VarStrictType = ... varStrictTKey :: Unique varStrictTKey = mkPreludeMiscIdUnique 375 -- data Type = ... forallTIdKey, varTIdKey, conTIdKey, tupleTIdKey, unboxedTupleTIdKey, arrowTIdKey, listTIdKey, appTIdKey, sigTIdKey, equalityTIdKey, litTIdKey, promotedTIdKey, promotedTupleTIdKey, promotedNilTIdKey, promotedConsTIdKey :: Unique forallTIdKey = mkPreludeMiscIdUnique 380 varTIdKey = mkPreludeMiscIdUnique 381 conTIdKey = mkPreludeMiscIdUnique 382 tupleTIdKey = mkPreludeMiscIdUnique 383 unboxedTupleTIdKey = mkPreludeMiscIdUnique 384 arrowTIdKey = mkPreludeMiscIdUnique 385 listTIdKey = mkPreludeMiscIdUnique 386 appTIdKey = mkPreludeMiscIdUnique 387 sigTIdKey = mkPreludeMiscIdUnique 388 equalityTIdKey = mkPreludeMiscIdUnique 389 litTIdKey = mkPreludeMiscIdUnique 390 promotedTIdKey = mkPreludeMiscIdUnique 391 promotedTupleTIdKey = mkPreludeMiscIdUnique 392 promotedNilTIdKey = mkPreludeMiscIdUnique 393 promotedConsTIdKey = mkPreludeMiscIdUnique 394 -- data TyLit = ... numTyLitIdKey, strTyLitIdKey :: Unique numTyLitIdKey = mkPreludeMiscIdUnique 395 strTyLitIdKey = mkPreludeMiscIdUnique 396 -- data TyVarBndr = ... plainTVIdKey, kindedTVIdKey :: Unique plainTVIdKey = mkPreludeMiscIdUnique 397 kindedTVIdKey = mkPreludeMiscIdUnique 398 -- data Role = ... nominalRIdKey, representationalRIdKey, phantomRIdKey, inferRIdKey :: Unique nominalRIdKey = mkPreludeMiscIdUnique 400 representationalRIdKey = mkPreludeMiscIdUnique 401 phantomRIdKey = mkPreludeMiscIdUnique 402 inferRIdKey = mkPreludeMiscIdUnique 403 -- data Kind = ... varKIdKey, conKIdKey, tupleKIdKey, arrowKIdKey, listKIdKey, appKIdKey, starKIdKey, constraintKIdKey :: Unique varKIdKey = mkPreludeMiscIdUnique 404 conKIdKey = mkPreludeMiscIdUnique 405 tupleKIdKey = mkPreludeMiscIdUnique 406 arrowKIdKey = mkPreludeMiscIdUnique 407 listKIdKey = mkPreludeMiscIdUnique 408 appKIdKey = mkPreludeMiscIdUnique 409 starKIdKey = mkPreludeMiscIdUnique 410 constraintKIdKey = mkPreludeMiscIdUnique 411 -- data Callconv = ... cCallIdKey, stdCallIdKey :: Unique cCallIdKey = mkPreludeMiscIdUnique 412 stdCallIdKey = mkPreludeMiscIdUnique 413 -- data Safety = ... unsafeIdKey, safeIdKey, interruptibleIdKey :: Unique unsafeIdKey = mkPreludeMiscIdUnique 414 safeIdKey = mkPreludeMiscIdUnique 415 interruptibleIdKey = mkPreludeMiscIdUnique 416 -- data Inline = ... noInlineDataConKey, inlineDataConKey, inlinableDataConKey :: Unique noInlineDataConKey = mkPreludeDataConUnique 40 inlineDataConKey = mkPreludeDataConUnique 41 inlinableDataConKey = mkPreludeDataConUnique 42 -- data RuleMatch = ... conLikeDataConKey, funLikeDataConKey :: Unique conLikeDataConKey = mkPreludeDataConUnique 43 funLikeDataConKey = mkPreludeDataConUnique 44 -- data Phases = ... allPhasesDataConKey, fromPhaseDataConKey, beforePhaseDataConKey :: Unique allPhasesDataConKey = mkPreludeDataConUnique 45 fromPhaseDataConKey = mkPreludeDataConUnique 46 beforePhaseDataConKey = mkPreludeDataConUnique 47 -- newtype TExp a = ... tExpDataConKey :: Unique tExpDataConKey = mkPreludeDataConUnique 48 -- data FunDep = ... funDepIdKey :: Unique funDepIdKey = mkPreludeMiscIdUnique 419 -- data FamFlavour = ... typeFamIdKey, dataFamIdKey :: Unique typeFamIdKey = mkPreludeMiscIdUnique 420 dataFamIdKey = mkPreludeMiscIdUnique 421 -- data TySynEqn = ... tySynEqnIdKey :: Unique tySynEqnIdKey = mkPreludeMiscIdUnique 422 -- quasiquoting quoteExpKey, quotePatKey, quoteDecKey, quoteTypeKey :: Unique quoteExpKey = mkPreludeMiscIdUnique 423 quotePatKey = mkPreludeMiscIdUnique 424 quoteDecKey = mkPreludeMiscIdUnique 425 quoteTypeKey = mkPreludeMiscIdUnique 426 -- data RuleBndr = ... ruleVarIdKey, typedRuleVarIdKey :: Unique ruleVarIdKey = mkPreludeMiscIdUnique 427 typedRuleVarIdKey = mkPreludeMiscIdUnique 428
spacekitteh/smcghc
compiler/deSugar/DsMeta.hs
bsd-3-clause
114,141
2,313
23
30,470
26,514
14,800
11,714
1,903
16
module Optimization.Constrained.ProjectedSubgradient ( -- * Projected subgradient method projSubgrad , linearProjSubgrad -- * Step schedules , StepSched , optimalStepSched , constStepSched , sqrtKStepSched , invKStepSched -- * Linear constraints , Constraint(..) , linearProjection ) where import Linear import Data.Traversable import Data.Function (on) import Data.List (maximumBy) -- | A step size schedule -- A list of functions (one per step) which, given a function's -- gradient and value, will provide a size for the next step type StepSched f a = [f a -> a -> a] -- | @projSubgrad stepSizes proj a b x0@ minimizes the objective @A -- x - b@ potentially projecting iterates into a feasible space with -- @proj@ with the given step-size schedule projSubgrad :: (Additive f, Traversable f, Metric f, Ord a, Fractional a) => StepSched f a -- ^ A step size schedule -> (f a -> f a) -- ^ Function projecting into the feasible space -> (f a -> f a) -- ^ Gradient of objective function -> (f a -> a) -- ^ The objective function -> f a -- ^ Initial solution -> [f a] projSubgrad stepSizes proj df f = go stepSizes where go (alpha:rest) x0 = let p = negated $ df x0 step = alpha (df x0) (f x0) x1 = proj $ x0 ^+^ step *^ p in x1 : go rest x1 go [] _ = [] -- | @linearProjSubgrad stepSizes proj a b x0@ minimizes the objective @A -- x - b@ potentially projecting iterates into a feasible space with -- @proj@ with the given step-size schedule linearProjSubgrad :: (Additive f, Traversable f, Metric f, Ord a, Fractional a) => StepSched f a -- ^ A step size schedule -> (f a -> f a) -- ^ Function projecting into the feasible space -> f a -- ^ Coefficient vector @A@ of objective -> a -- ^ Constant @b@ of objective -> f a -- ^ Initial solution -> [f a] linearProjSubgrad stepSizes proj a b = go stepSizes where go (alpha:rest) x0 = let p = negated $ df x0 step = alpha a (f x0) x1 = proj $ x0 ^+^ step *^ p in x1 : go rest x1 go [] _ = [] df _ = a f x = a `dot` x - b -- | The optimal step size schedule when the optimal value of the -- objective is known optimalStepSched :: (Fractional a, Metric f) => a -- ^ The optimal value of the objective -> StepSched f a optimalStepSched fStar = repeat $ \gk fk->(fk - fStar) / quadrance gk -- | Constant step size schedule constStepSched :: a -- ^ The step size -> StepSched f a constStepSched gamma = repeat $ \_ _ -> gamma -- | A non-summable step size schedule sqrtKStepSched :: Floating a => a -- ^ The size of the first step -> StepSched f a sqrtKStepSched gamma = map (\k _ _ -> gamma / sqrt (fromIntegral k)) [0..] -- | A square-summable step size schedule invKStepSched :: Fractional a => a -- ^ The size of the first step -> StepSched f a invKStepSched gamma = map (\k _ _ -> gamma / fromIntegral k) [0..] -- | A linear constraint. For instance, @Constr LT 2 (V2 1 3)@ defines -- the constraint @x_1 + 3 x_2 <= 2@ data Constraint f a = Constr Ordering a (f a) deriving (Show) -- | Project onto a the space of feasible solutions defined by a set -- of linear constraints linearProjection :: (Fractional a, Ord a, RealFloat a, Metric f) => [Constraint f a] -- ^ A set of linear constraints -> f a -> f a linearProjection constraints x = case unmet of [] -> x _ -> linearProjection constraints $ fixConstraint x $ maximumBy (flip compare `on` (`ap` x)) unmet where unmet = filter (not . met x) constraints ap (Constr _ b a) c = a `dot` c - b met c (Constr t a constr) = let y = constr `dot` c - a in case t of EQ -> abs y < 1e-4 GT -> y >= 0 || abs y < 1e-4 LT -> y <= 0 || abs y < 1e-4 fixConstraint c (Constr _ b a) = c ^-^ (a `dot` c - b) *^ a ^/ quadrance a
ocramz/optimization
src/Optimization/Constrained/ProjectedSubgradient.hs
bsd-3-clause
4,472
1
18
1,592
1,137
601
536
83
4
{-# LANGUAGE CPP, TypeFamilies #-} ----------------------------------------------------------------------------- -- -- Machine-dependent assembly language -- -- (c) The University of Glasgow 1993-2004 -- ----------------------------------------------------------------------------- module X86.Instr (Instr(..), Operand(..), PrefetchVariant(..), JumpDest, getJumpDestBlockId, canShortcut, shortcutStatics, shortcutJump, i386_insert_ffrees, allocMoreStack, maxSpillSlots, archWordFormat) where #include "HsVersions.h" #include "nativeGen/NCG.h" import GhcPrelude import X86.Cond import X86.Regs import Instruction import Format import RegClass import Reg import TargetReg import BlockId import Hoopl.Collections import Hoopl.Label import CodeGen.Platform import Cmm import FastString import Outputable import Platform import BasicTypes (Alignment) import CLabel import DynFlags import UniqSet import Unique import UniqSupply import Debug (UnwindTable) import Control.Monad import Data.Maybe (fromMaybe) -- Format of an x86/x86_64 memory address, in bytes. -- archWordFormat :: Bool -> Format archWordFormat is32Bit | is32Bit = II32 | otherwise = II64 -- | Instruction instance for x86 instruction set. instance Instruction Instr where regUsageOfInstr = x86_regUsageOfInstr patchRegsOfInstr = x86_patchRegsOfInstr isJumpishInstr = x86_isJumpishInstr jumpDestsOfInstr = x86_jumpDestsOfInstr patchJumpInstr = x86_patchJumpInstr mkSpillInstr = x86_mkSpillInstr mkLoadInstr = x86_mkLoadInstr takeDeltaInstr = x86_takeDeltaInstr isMetaInstr = x86_isMetaInstr mkRegRegMoveInstr = x86_mkRegRegMoveInstr takeRegRegMoveInstr = x86_takeRegRegMoveInstr mkJumpInstr = x86_mkJumpInstr mkStackAllocInstr = x86_mkStackAllocInstr mkStackDeallocInstr = x86_mkStackDeallocInstr -- ----------------------------------------------------------------------------- -- Intel x86 instructions {- Intel, in their infinite wisdom, selected a stack model for floating point registers on x86. That might have made sense back in 1979 -- nowadays we can see it for the nonsense it really is. A stack model fits poorly with the existing nativeGen infrastructure, which assumes flat integer and FP register sets. Prior to this commit, nativeGen could not generate correct x86 FP code -- to do so would have meant somehow working the register-stack paradigm into the register allocator and spiller, which sounds very difficult. We have decided to cheat, and go for a simple fix which requires no infrastructure modifications, at the expense of generating ropey but correct FP code. All notions of the x86 FP stack and its insns have been removed. Instead, we pretend (to the instruction selector and register allocator) that x86 has six floating point registers, %fake0 .. %fake5, which can be used in the usual flat manner. We further claim that x86 has floating point instructions very similar to SPARC and Alpha, that is, a simple 3-operand register-register arrangement. Code generation and register allocation proceed on this basis. When we come to print out the final assembly, our convenient fiction is converted to dismal reality. Each fake instruction is independently converted to a series of real x86 instructions. %fake0 .. %fake5 are mapped to %st(0) .. %st(5). To do reg-reg arithmetic operations, the two operands are pushed onto the top of the FP stack, the operation done, and the result copied back into the relevant register. There are only six %fake registers because 2 are needed for the translation, and x86 has 8 in total. The translation is inefficient but is simple and it works. A cleverer translation would handle a sequence of insns, simulating the FP stack contents, would not impose a fixed mapping from %fake to %st regs, and hopefully could avoid most of the redundant reg-reg moves of the current translation. We might as well make use of whatever unique FP facilities Intel have chosen to bless us with (let's not be churlish, after all). Hence GLDZ and GLD1. Bwahahahahahahaha! -} {- Note [x86 Floating point precision] Intel's internal floating point registers are by default 80 bit extended precision. This means that all operations done on values in registers are done at 80 bits, and unless the intermediate values are truncated to the appropriate size (32 or 64 bits) by storing in memory, calculations in registers will give different results from calculations which pass intermediate values in memory (eg. via function calls). One solution is to set the FPU into 64 bit precision mode. Some OSs do this (eg. FreeBSD) and some don't (eg. Linux). The problem here is that this will only affect 64-bit precision arithmetic; 32-bit calculations will still be done at 64-bit precision in registers. So it doesn't solve the whole problem. There's also the issue of what the C library is expecting in terms of precision. It seems to be the case that glibc on Linux expects the FPU to be set to 80 bit precision, so setting it to 64 bit could have unexpected effects. Changing the default could have undesirable effects on other 3rd-party library code too, so the right thing would be to save/restore the FPU control word across Haskell code if we were to do this. gcc's -ffloat-store gives consistent results by always storing the results of floating-point calculations in memory, which works for both 32 and 64-bit precision. However, it only affects the values of user-declared floating point variables in C, not intermediate results. GHC in -fvia-C mode uses -ffloat-store (see the -fexcess-precision flag). Another problem is how to spill floating point registers in the register allocator. Should we spill the whole 80 bits, or just 64? On an OS which is set to 64 bit precision, spilling 64 is fine. On Linux, spilling 64 bits will round the results of some operations. This is what gcc does. Spilling at 80 bits requires taking up a full 128 bit slot (so we get alignment). We spill at 80-bits and ignore the alignment problems. In the future [edit: now available in GHC 7.0.1, with the -msse2 flag], we'll use the SSE registers for floating point. This requires a CPU that supports SSE2 (ordinary SSE only supports 32 bit precision float ops), which means P4 or Xeon and above. Using SSE will solve all these problems, because the SSE registers use fixed 32 bit or 64 bit precision. --SDM 1/2003 -} data Instr -- comment pseudo-op = COMMENT FastString -- location pseudo-op (file, line, col, name) | LOCATION Int Int Int String -- some static data spat out during code -- generation. Will be extracted before -- pretty-printing. | LDATA Section (Alignment, CmmStatics) -- start a new basic block. Useful during -- codegen, removed later. Preceding -- instruction should be a jump, as per the -- invariants for a BasicBlock (see Cmm). | NEWBLOCK BlockId -- unwinding information -- See Note [Unwinding information in the NCG]. | UNWIND CLabel UnwindTable -- specify current stack offset for benefit of subsequent passes. -- This carries a BlockId so it can be used in unwinding information. | DELTA Int -- Moves. | MOV Format Operand Operand | CMOV Cond Format Operand Reg | MOVZxL Format Operand Operand -- format is the size of operand 1 | MOVSxL Format Operand Operand -- format is the size of operand 1 -- x86_64 note: plain mov into a 32-bit register always zero-extends -- into the 64-bit reg, in contrast to the 8 and 16-bit movs which -- don't affect the high bits of the register. -- Load effective address (also a very useful three-operand add instruction :-) | LEA Format Operand Operand -- Int Arithmetic. | ADD Format Operand Operand | ADC Format Operand Operand | SUB Format Operand Operand | SBB Format Operand Operand | MUL Format Operand Operand | MUL2 Format Operand -- %edx:%eax = operand * %rax | IMUL Format Operand Operand -- signed int mul | IMUL2 Format Operand -- %edx:%eax = operand * %eax | DIV Format Operand -- eax := eax:edx/op, edx := eax:edx%op | IDIV Format Operand -- ditto, but signed -- Int Arithmetic, where the effects on the condition register -- are important. Used in specialized sequences such as MO_Add2. -- Do not rewrite these instructions to "equivalent" ones that -- have different effect on the condition register! (See #9013.) | ADD_CC Format Operand Operand | SUB_CC Format Operand Operand -- Simple bit-twiddling. | AND Format Operand Operand | OR Format Operand Operand | XOR Format Operand Operand | NOT Format Operand | NEGI Format Operand -- NEG instruction (name clash with Cond) | BSWAP Format Reg -- Shifts (amount may be immediate or %cl only) | SHL Format Operand{-amount-} Operand | SAR Format Operand{-amount-} Operand | SHR Format Operand{-amount-} Operand | BT Format Imm Operand | NOP -- x86 Float Arithmetic. -- Note that we cheat by treating G{ABS,MOV,NEG} of doubles -- as single instructions right up until we spit them out. -- all the 3-operand fake fp insns are src1 src2 dst -- and furthermore are constrained to be fp regs only. -- IMPORTANT: keep is_G_insn up to date with any changes here | GMOV Reg Reg -- src(fpreg), dst(fpreg) | GLD Format AddrMode Reg -- src, dst(fpreg) | GST Format Reg AddrMode -- src(fpreg), dst | GLDZ Reg -- dst(fpreg) | GLD1 Reg -- dst(fpreg) | GFTOI Reg Reg -- src(fpreg), dst(intreg) | GDTOI Reg Reg -- src(fpreg), dst(intreg) | GITOF Reg Reg -- src(intreg), dst(fpreg) | GITOD Reg Reg -- src(intreg), dst(fpreg) | GDTOF Reg Reg -- src(fpreg), dst(fpreg) | GADD Format Reg Reg Reg -- src1, src2, dst | GDIV Format Reg Reg Reg -- src1, src2, dst | GSUB Format Reg Reg Reg -- src1, src2, dst | GMUL Format Reg Reg Reg -- src1, src2, dst -- FP compare. Cond must be `elem` [EQQ, NE, LE, LTT, GE, GTT] -- Compare src1 with src2; set the Zero flag iff the numbers are -- comparable and the comparison is True. Subsequent code must -- test the %eflags zero flag regardless of the supplied Cond. | GCMP Cond Reg Reg -- src1, src2 | GABS Format Reg Reg -- src, dst | GNEG Format Reg Reg -- src, dst | GSQRT Format Reg Reg -- src, dst | GSIN Format CLabel CLabel Reg Reg -- src, dst | GCOS Format CLabel CLabel Reg Reg -- src, dst | GTAN Format CLabel CLabel Reg Reg -- src, dst | GFREE -- do ffree on all x86 regs; an ugly hack -- SSE2 floating point: we use a restricted set of the available SSE2 -- instructions for floating-point. -- use MOV for moving (either movss or movsd (movlpd better?)) | CVTSS2SD Reg Reg -- F32 to F64 | CVTSD2SS Reg Reg -- F64 to F32 | CVTTSS2SIQ Format Operand Reg -- F32 to I32/I64 (with truncation) | CVTTSD2SIQ Format Operand Reg -- F64 to I32/I64 (with truncation) | CVTSI2SS Format Operand Reg -- I32/I64 to F32 | CVTSI2SD Format Operand Reg -- I32/I64 to F64 -- use ADD, SUB, and SQRT for arithmetic. In both cases, operands -- are Operand Reg. -- SSE2 floating-point division: | FDIV Format Operand Operand -- divisor, dividend(dst) -- use CMP for comparisons. ucomiss and ucomisd instructions -- compare single/double prec floating point respectively. | SQRT Format Operand Reg -- src, dst -- Comparison | TEST Format Operand Operand | CMP Format Operand Operand | SETCC Cond Operand -- Stack Operations. | PUSH Format Operand | POP Format Operand -- both unused (SDM): -- | PUSHA -- | POPA -- Jumping around. | JMP Operand [Reg] -- including live Regs at the call | JXX Cond BlockId -- includes unconditional branches | JXX_GBL Cond Imm -- non-local version of JXX -- Table jump | JMP_TBL Operand -- Address to jump to [Maybe BlockId] -- Blocks in the jump table Section -- Data section jump table should be put in CLabel -- Label of jump table | CALL (Either Imm Reg) [Reg] -- Other things. | CLTD Format -- sign extend %eax into %edx:%eax | FETCHGOT Reg -- pseudo-insn for ELF position-independent code -- pretty-prints as -- call 1f -- 1: popl %reg -- addl __GLOBAL_OFFSET_TABLE__+.-1b, %reg | FETCHPC Reg -- pseudo-insn for Darwin position-independent code -- pretty-prints as -- call 1f -- 1: popl %reg -- bit counting instructions | POPCNT Format Operand Reg -- [SSE4.2] count number of bits set to 1 | BSF Format Operand Reg -- bit scan forward | BSR Format Operand Reg -- bit scan reverse -- bit manipulation instructions | PDEP Format Operand Operand Reg -- [BMI2] deposit bits to the specified mask | PEXT Format Operand Operand Reg -- [BMI2] extract bits from the specified mask -- prefetch | PREFETCH PrefetchVariant Format Operand -- prefetch Variant, addr size, address to prefetch -- variant can be NTA, Lvl0, Lvl1, or Lvl2 | LOCK Instr -- lock prefix | XADD Format Operand Operand -- src (r), dst (r/m) | CMPXCHG Format Operand Operand -- src (r), dst (r/m), eax implicit | MFENCE data PrefetchVariant = NTA | Lvl0 | Lvl1 | Lvl2 data Operand = OpReg Reg -- register | OpImm Imm -- immediate value | OpAddr AddrMode -- memory reference -- | Returns which registers are read and written as a (read, written) -- pair. x86_regUsageOfInstr :: Platform -> Instr -> RegUsage x86_regUsageOfInstr platform instr = case instr of MOV _ src dst -> usageRW src dst CMOV _ _ src dst -> mkRU (use_R src [dst]) [dst] MOVZxL _ src dst -> usageRW src dst MOVSxL _ src dst -> usageRW src dst LEA _ src dst -> usageRW src dst ADD _ src dst -> usageRM src dst ADC _ src dst -> usageRM src dst SUB _ src dst -> usageRM src dst SBB _ src dst -> usageRM src dst IMUL _ src dst -> usageRM src dst IMUL2 _ src -> mkRU (eax:use_R src []) [eax,edx] MUL _ src dst -> usageRM src dst MUL2 _ src -> mkRU (eax:use_R src []) [eax,edx] DIV _ op -> mkRU (eax:edx:use_R op []) [eax,edx] IDIV _ op -> mkRU (eax:edx:use_R op []) [eax,edx] ADD_CC _ src dst -> usageRM src dst SUB_CC _ src dst -> usageRM src dst AND _ src dst -> usageRM src dst OR _ src dst -> usageRM src dst XOR _ (OpReg src) (OpReg dst) | src == dst -> mkRU [] [dst] XOR _ src dst -> usageRM src dst NOT _ op -> usageM op BSWAP _ reg -> mkRU [reg] [reg] NEGI _ op -> usageM op SHL _ imm dst -> usageRM imm dst SAR _ imm dst -> usageRM imm dst SHR _ imm dst -> usageRM imm dst BT _ _ src -> mkRUR (use_R src []) PUSH _ op -> mkRUR (use_R op []) POP _ op -> mkRU [] (def_W op) TEST _ src dst -> mkRUR (use_R src $! use_R dst []) CMP _ src dst -> mkRUR (use_R src $! use_R dst []) SETCC _ op -> mkRU [] (def_W op) JXX _ _ -> mkRU [] [] JXX_GBL _ _ -> mkRU [] [] JMP op regs -> mkRUR (use_R op regs) JMP_TBL op _ _ _ -> mkRUR (use_R op []) CALL (Left _) params -> mkRU params (callClobberedRegs platform) CALL (Right reg) params -> mkRU (reg:params) (callClobberedRegs platform) CLTD _ -> mkRU [eax] [edx] NOP -> mkRU [] [] GMOV src dst -> mkRU [src] [dst] GLD _ src dst -> mkRU (use_EA src []) [dst] GST _ src dst -> mkRUR (src : use_EA dst []) GLDZ dst -> mkRU [] [dst] GLD1 dst -> mkRU [] [dst] GFTOI src dst -> mkRU [src] [dst] GDTOI src dst -> mkRU [src] [dst] GITOF src dst -> mkRU [src] [dst] GITOD src dst -> mkRU [src] [dst] GDTOF src dst -> mkRU [src] [dst] GADD _ s1 s2 dst -> mkRU [s1,s2] [dst] GSUB _ s1 s2 dst -> mkRU [s1,s2] [dst] GMUL _ s1 s2 dst -> mkRU [s1,s2] [dst] GDIV _ s1 s2 dst -> mkRU [s1,s2] [dst] GCMP _ src1 src2 -> mkRUR [src1,src2] GABS _ src dst -> mkRU [src] [dst] GNEG _ src dst -> mkRU [src] [dst] GSQRT _ src dst -> mkRU [src] [dst] GSIN _ _ _ src dst -> mkRU [src] [dst] GCOS _ _ _ src dst -> mkRU [src] [dst] GTAN _ _ _ src dst -> mkRU [src] [dst] CVTSS2SD src dst -> mkRU [src] [dst] CVTSD2SS src dst -> mkRU [src] [dst] CVTTSS2SIQ _ src dst -> mkRU (use_R src []) [dst] CVTTSD2SIQ _ src dst -> mkRU (use_R src []) [dst] CVTSI2SS _ src dst -> mkRU (use_R src []) [dst] CVTSI2SD _ src dst -> mkRU (use_R src []) [dst] FDIV _ src dst -> usageRM src dst SQRT _ src dst -> mkRU (use_R src []) [dst] FETCHGOT reg -> mkRU [] [reg] FETCHPC reg -> mkRU [] [reg] COMMENT _ -> noUsage LOCATION{} -> noUsage UNWIND{} -> noUsage DELTA _ -> noUsage POPCNT _ src dst -> mkRU (use_R src []) [dst] BSF _ src dst -> mkRU (use_R src []) [dst] BSR _ src dst -> mkRU (use_R src []) [dst] PDEP _ src mask dst -> mkRU (use_R src $ use_R mask []) [dst] PEXT _ src mask dst -> mkRU (use_R src $ use_R mask []) [dst] -- note: might be a better way to do this PREFETCH _ _ src -> mkRU (use_R src []) [] LOCK i -> x86_regUsageOfInstr platform i XADD _ src dst -> usageMM src dst CMPXCHG _ src dst -> usageRMM src dst (OpReg eax) MFENCE -> noUsage _other -> panic "regUsage: unrecognised instr" where -- # Definitions -- -- Written: If the operand is a register, it's written. If it's an -- address, registers mentioned in the address are read. -- -- Modified: If the operand is a register, it's both read and -- written. If it's an address, registers mentioned in the address -- are read. -- 2 operand form; first operand Read; second Written usageRW :: Operand -> Operand -> RegUsage usageRW op (OpReg reg) = mkRU (use_R op []) [reg] usageRW op (OpAddr ea) = mkRUR (use_R op $! use_EA ea []) usageRW _ _ = panic "X86.RegInfo.usageRW: no match" -- 2 operand form; first operand Read; second Modified usageRM :: Operand -> Operand -> RegUsage usageRM op (OpReg reg) = mkRU (use_R op [reg]) [reg] usageRM op (OpAddr ea) = mkRUR (use_R op $! use_EA ea []) usageRM _ _ = panic "X86.RegInfo.usageRM: no match" -- 2 operand form; first operand Modified; second Modified usageMM :: Operand -> Operand -> RegUsage usageMM (OpReg src) (OpReg dst) = mkRU [src, dst] [src, dst] usageMM (OpReg src) (OpAddr ea) = mkRU (use_EA ea [src]) [src] usageMM _ _ = panic "X86.RegInfo.usageMM: no match" -- 3 operand form; first operand Read; second Modified; third Modified usageRMM :: Operand -> Operand -> Operand -> RegUsage usageRMM (OpReg src) (OpReg dst) (OpReg reg) = mkRU [src, dst, reg] [dst, reg] usageRMM (OpReg src) (OpAddr ea) (OpReg reg) = mkRU (use_EA ea [src, reg]) [reg] usageRMM _ _ _ = panic "X86.RegInfo.usageRMM: no match" -- 1 operand form; operand Modified usageM :: Operand -> RegUsage usageM (OpReg reg) = mkRU [reg] [reg] usageM (OpAddr ea) = mkRUR (use_EA ea []) usageM _ = panic "X86.RegInfo.usageM: no match" -- Registers defd when an operand is written. def_W (OpReg reg) = [reg] def_W (OpAddr _ ) = [] def_W _ = panic "X86.RegInfo.def_W: no match" -- Registers used when an operand is read. use_R (OpReg reg) tl = reg : tl use_R (OpImm _) tl = tl use_R (OpAddr ea) tl = use_EA ea tl -- Registers used to compute an effective address. use_EA (ImmAddr _ _) tl = tl use_EA (AddrBaseIndex base index _) tl = use_base base $! use_index index tl where use_base (EABaseReg r) tl = r : tl use_base _ tl = tl use_index EAIndexNone tl = tl use_index (EAIndex i _) tl = i : tl mkRUR src = src' `seq` RU src' [] where src' = filter (interesting platform) src mkRU src dst = src' `seq` dst' `seq` RU src' dst' where src' = filter (interesting platform) src dst' = filter (interesting platform) dst -- | Is this register interesting for the register allocator? interesting :: Platform -> Reg -> Bool interesting _ (RegVirtual _) = True interesting platform (RegReal (RealRegSingle i)) = freeReg platform i interesting _ (RegReal (RealRegPair{})) = panic "X86.interesting: no reg pairs on this arch" -- | Applies the supplied function to all registers in instructions. -- Typically used to change virtual registers to real registers. x86_patchRegsOfInstr :: Instr -> (Reg -> Reg) -> Instr x86_patchRegsOfInstr instr env = case instr of MOV fmt src dst -> patch2 (MOV fmt) src dst CMOV cc fmt src dst -> CMOV cc fmt (patchOp src) (env dst) MOVZxL fmt src dst -> patch2 (MOVZxL fmt) src dst MOVSxL fmt src dst -> patch2 (MOVSxL fmt) src dst LEA fmt src dst -> patch2 (LEA fmt) src dst ADD fmt src dst -> patch2 (ADD fmt) src dst ADC fmt src dst -> patch2 (ADC fmt) src dst SUB fmt src dst -> patch2 (SUB fmt) src dst SBB fmt src dst -> patch2 (SBB fmt) src dst IMUL fmt src dst -> patch2 (IMUL fmt) src dst IMUL2 fmt src -> patch1 (IMUL2 fmt) src MUL fmt src dst -> patch2 (MUL fmt) src dst MUL2 fmt src -> patch1 (MUL2 fmt) src IDIV fmt op -> patch1 (IDIV fmt) op DIV fmt op -> patch1 (DIV fmt) op ADD_CC fmt src dst -> patch2 (ADD_CC fmt) src dst SUB_CC fmt src dst -> patch2 (SUB_CC fmt) src dst AND fmt src dst -> patch2 (AND fmt) src dst OR fmt src dst -> patch2 (OR fmt) src dst XOR fmt src dst -> patch2 (XOR fmt) src dst NOT fmt op -> patch1 (NOT fmt) op BSWAP fmt reg -> BSWAP fmt (env reg) NEGI fmt op -> patch1 (NEGI fmt) op SHL fmt imm dst -> patch1 (SHL fmt imm) dst SAR fmt imm dst -> patch1 (SAR fmt imm) dst SHR fmt imm dst -> patch1 (SHR fmt imm) dst BT fmt imm src -> patch1 (BT fmt imm) src TEST fmt src dst -> patch2 (TEST fmt) src dst CMP fmt src dst -> patch2 (CMP fmt) src dst PUSH fmt op -> patch1 (PUSH fmt) op POP fmt op -> patch1 (POP fmt) op SETCC cond op -> patch1 (SETCC cond) op JMP op regs -> JMP (patchOp op) regs JMP_TBL op ids s lbl -> JMP_TBL (patchOp op) ids s lbl GMOV src dst -> GMOV (env src) (env dst) GLD fmt src dst -> GLD fmt (lookupAddr src) (env dst) GST fmt src dst -> GST fmt (env src) (lookupAddr dst) GLDZ dst -> GLDZ (env dst) GLD1 dst -> GLD1 (env dst) GFTOI src dst -> GFTOI (env src) (env dst) GDTOI src dst -> GDTOI (env src) (env dst) GITOF src dst -> GITOF (env src) (env dst) GITOD src dst -> GITOD (env src) (env dst) GDTOF src dst -> GDTOF (env src) (env dst) GADD fmt s1 s2 dst -> GADD fmt (env s1) (env s2) (env dst) GSUB fmt s1 s2 dst -> GSUB fmt (env s1) (env s2) (env dst) GMUL fmt s1 s2 dst -> GMUL fmt (env s1) (env s2) (env dst) GDIV fmt s1 s2 dst -> GDIV fmt (env s1) (env s2) (env dst) GCMP fmt src1 src2 -> GCMP fmt (env src1) (env src2) GABS fmt src dst -> GABS fmt (env src) (env dst) GNEG fmt src dst -> GNEG fmt (env src) (env dst) GSQRT fmt src dst -> GSQRT fmt (env src) (env dst) GSIN fmt l1 l2 src dst -> GSIN fmt l1 l2 (env src) (env dst) GCOS fmt l1 l2 src dst -> GCOS fmt l1 l2 (env src) (env dst) GTAN fmt l1 l2 src dst -> GTAN fmt l1 l2 (env src) (env dst) CVTSS2SD src dst -> CVTSS2SD (env src) (env dst) CVTSD2SS src dst -> CVTSD2SS (env src) (env dst) CVTTSS2SIQ fmt src dst -> CVTTSS2SIQ fmt (patchOp src) (env dst) CVTTSD2SIQ fmt src dst -> CVTTSD2SIQ fmt (patchOp src) (env dst) CVTSI2SS fmt src dst -> CVTSI2SS fmt (patchOp src) (env dst) CVTSI2SD fmt src dst -> CVTSI2SD fmt (patchOp src) (env dst) FDIV fmt src dst -> FDIV fmt (patchOp src) (patchOp dst) SQRT fmt src dst -> SQRT fmt (patchOp src) (env dst) CALL (Left _) _ -> instr CALL (Right reg) p -> CALL (Right (env reg)) p FETCHGOT reg -> FETCHGOT (env reg) FETCHPC reg -> FETCHPC (env reg) NOP -> instr COMMENT _ -> instr LOCATION {} -> instr UNWIND {} -> instr DELTA _ -> instr JXX _ _ -> instr JXX_GBL _ _ -> instr CLTD _ -> instr POPCNT fmt src dst -> POPCNT fmt (patchOp src) (env dst) PDEP fmt src mask dst -> PDEP fmt (patchOp src) (patchOp mask) (env dst) PEXT fmt src mask dst -> PEXT fmt (patchOp src) (patchOp mask) (env dst) BSF fmt src dst -> BSF fmt (patchOp src) (env dst) BSR fmt src dst -> BSR fmt (patchOp src) (env dst) PREFETCH lvl format src -> PREFETCH lvl format (patchOp src) LOCK i -> LOCK (x86_patchRegsOfInstr i env) XADD fmt src dst -> patch2 (XADD fmt) src dst CMPXCHG fmt src dst -> patch2 (CMPXCHG fmt) src dst MFENCE -> instr _other -> panic "patchRegs: unrecognised instr" where patch1 :: (Operand -> a) -> Operand -> a patch1 insn op = insn $! patchOp op patch2 :: (Operand -> Operand -> a) -> Operand -> Operand -> a patch2 insn src dst = (insn $! patchOp src) $! patchOp dst patchOp (OpReg reg) = OpReg $! env reg patchOp (OpImm imm) = OpImm imm patchOp (OpAddr ea) = OpAddr $! lookupAddr ea lookupAddr (ImmAddr imm off) = ImmAddr imm off lookupAddr (AddrBaseIndex base index disp) = ((AddrBaseIndex $! lookupBase base) $! lookupIndex index) disp where lookupBase EABaseNone = EABaseNone lookupBase EABaseRip = EABaseRip lookupBase (EABaseReg r) = EABaseReg $! env r lookupIndex EAIndexNone = EAIndexNone lookupIndex (EAIndex r i) = (EAIndex $! env r) i -------------------------------------------------------------------------------- x86_isJumpishInstr :: Instr -> Bool x86_isJumpishInstr instr = case instr of JMP{} -> True JXX{} -> True JXX_GBL{} -> True JMP_TBL{} -> True CALL{} -> True _ -> False x86_jumpDestsOfInstr :: Instr -> [BlockId] x86_jumpDestsOfInstr insn = case insn of JXX _ id -> [id] JMP_TBL _ ids _ _ -> [id | Just id <- ids] _ -> [] x86_patchJumpInstr :: Instr -> (BlockId -> BlockId) -> Instr x86_patchJumpInstr insn patchF = case insn of JXX cc id -> JXX cc (patchF id) JMP_TBL op ids section lbl -> JMP_TBL op (map (fmap patchF) ids) section lbl _ -> insn -- ----------------------------------------------------------------------------- -- | Make a spill instruction. x86_mkSpillInstr :: DynFlags -> Reg -- register to spill -> Int -- current stack delta -> Int -- spill slot to use -> Instr x86_mkSpillInstr dflags reg delta slot = let off = spillSlotToOffset platform slot - delta in case targetClassOfReg platform reg of RcInteger -> MOV (archWordFormat is32Bit) (OpReg reg) (OpAddr (spRel dflags off)) RcDouble -> GST FF80 reg (spRel dflags off) {- RcFloat/RcDouble -} RcDoubleSSE -> MOV FF64 (OpReg reg) (OpAddr (spRel dflags off)) _ -> panic "X86.mkSpillInstr: no match" where platform = targetPlatform dflags is32Bit = target32Bit platform -- | Make a spill reload instruction. x86_mkLoadInstr :: DynFlags -> Reg -- register to load -> Int -- current stack delta -> Int -- spill slot to use -> Instr x86_mkLoadInstr dflags reg delta slot = let off = spillSlotToOffset platform slot - delta in case targetClassOfReg platform reg of RcInteger -> MOV (archWordFormat is32Bit) (OpAddr (spRel dflags off)) (OpReg reg) RcDouble -> GLD FF80 (spRel dflags off) reg {- RcFloat/RcDouble -} RcDoubleSSE -> MOV FF64 (OpAddr (spRel dflags off)) (OpReg reg) _ -> panic "X86.x86_mkLoadInstr" where platform = targetPlatform dflags is32Bit = target32Bit platform spillSlotSize :: Platform -> Int spillSlotSize dflags = if is32Bit then 12 else 8 where is32Bit = target32Bit dflags maxSpillSlots :: DynFlags -> Int maxSpillSlots dflags = ((rESERVED_C_STACK_BYTES dflags - 64) `div` spillSlotSize (targetPlatform dflags)) - 1 -- = 0 -- useful for testing allocMoreStack -- number of bytes that the stack pointer should be aligned to stackAlign :: Int stackAlign = 16 -- convert a spill slot number to a *byte* offset, with no sign: -- decide on a per arch basis whether you are spilling above or below -- the C stack pointer. spillSlotToOffset :: Platform -> Int -> Int spillSlotToOffset platform slot = 64 + spillSlotSize platform * slot -------------------------------------------------------------------------------- -- | See if this instruction is telling us the current C stack delta x86_takeDeltaInstr :: Instr -> Maybe Int x86_takeDeltaInstr instr = case instr of DELTA i -> Just i _ -> Nothing x86_isMetaInstr :: Instr -> Bool x86_isMetaInstr instr = case instr of COMMENT{} -> True LOCATION{} -> True LDATA{} -> True NEWBLOCK{} -> True UNWIND{} -> True DELTA{} -> True _ -> False -- | Make a reg-reg move instruction. -- On SPARC v8 there are no instructions to move directly between -- floating point and integer regs. If we need to do that then we -- have to go via memory. -- x86_mkRegRegMoveInstr :: Platform -> Reg -> Reg -> Instr x86_mkRegRegMoveInstr platform src dst = case targetClassOfReg platform src of RcInteger -> case platformArch platform of ArchX86 -> MOV II32 (OpReg src) (OpReg dst) ArchX86_64 -> MOV II64 (OpReg src) (OpReg dst) _ -> panic "x86_mkRegRegMoveInstr: Bad arch" RcDouble -> GMOV src dst RcDoubleSSE -> MOV FF64 (OpReg src) (OpReg dst) _ -> panic "X86.RegInfo.mkRegRegMoveInstr: no match" -- | Check whether an instruction represents a reg-reg move. -- The register allocator attempts to eliminate reg->reg moves whenever it can, -- by assigning the src and dest temporaries to the same real register. -- x86_takeRegRegMoveInstr :: Instr -> Maybe (Reg,Reg) x86_takeRegRegMoveInstr (MOV _ (OpReg r1) (OpReg r2)) = Just (r1,r2) x86_takeRegRegMoveInstr _ = Nothing -- | Make an unconditional branch instruction. x86_mkJumpInstr :: BlockId -> [Instr] x86_mkJumpInstr id = [JXX ALWAYS id] x86_mkStackAllocInstr :: Platform -> Int -> Instr x86_mkStackAllocInstr platform amount = case platformArch platform of ArchX86 -> SUB II32 (OpImm (ImmInt amount)) (OpReg esp) ArchX86_64 -> SUB II64 (OpImm (ImmInt amount)) (OpReg rsp) _ -> panic "x86_mkStackAllocInstr" x86_mkStackDeallocInstr :: Platform -> Int -> Instr x86_mkStackDeallocInstr platform amount = case platformArch platform of ArchX86 -> ADD II32 (OpImm (ImmInt amount)) (OpReg esp) ArchX86_64 -> ADD II64 (OpImm (ImmInt amount)) (OpReg rsp) _ -> panic "x86_mkStackDeallocInstr" i386_insert_ffrees :: [GenBasicBlock Instr] -> [GenBasicBlock Instr] i386_insert_ffrees blocks | any (any is_G_instr) [ instrs | BasicBlock _ instrs <- blocks ] = map insertGFREEs blocks | otherwise = blocks where insertGFREEs (BasicBlock id insns) = BasicBlock id (insertBeforeNonlocalTransfers GFREE insns) insertBeforeNonlocalTransfers :: Instr -> [Instr] -> [Instr] insertBeforeNonlocalTransfers insert insns = foldr p [] insns where p insn r = case insn of CALL _ _ -> insert : insn : r JMP _ _ -> insert : insn : r JXX_GBL _ _ -> panic "insertBeforeNonlocalTransfers: cannot handle JXX_GBL" _ -> insn : r -- if you ever add a new FP insn to the fake x86 FP insn set, -- you must update this too is_G_instr :: Instr -> Bool is_G_instr instr = case instr of GMOV{} -> True GLD{} -> True GST{} -> True GLDZ{} -> True GLD1{} -> True GFTOI{} -> True GDTOI{} -> True GITOF{} -> True GITOD{} -> True GDTOF{} -> True GADD{} -> True GDIV{} -> True GSUB{} -> True GMUL{} -> True GCMP{} -> True GABS{} -> True GNEG{} -> True GSQRT{} -> True GSIN{} -> True GCOS{} -> True GTAN{} -> True GFREE -> panic "is_G_instr: GFREE (!)" _ -> False -- -- Note [extra spill slots] -- -- If the register allocator used more spill slots than we have -- pre-allocated (rESERVED_C_STACK_BYTES), then we must allocate more -- C stack space on entry and exit from this proc. Therefore we -- insert a "sub $N, %rsp" at every entry point, and an "add $N, %rsp" -- before every non-local jump. -- -- This became necessary when the new codegen started bundling entire -- functions together into one proc, because the register allocator -- assigns a different stack slot to each virtual reg within a proc. -- To avoid using so many slots we could also: -- -- - split up the proc into connected components before code generator -- -- - rename the virtual regs, so that we re-use vreg names and hence -- stack slots for non-overlapping vregs. -- -- Note that when a block is both a non-local entry point (with an -- info table) and a local branch target, we have to split it into -- two, like so: -- -- <info table> -- L: -- <code> -- -- becomes -- -- <info table> -- L: -- subl $rsp, N -- jmp Lnew -- Lnew: -- <code> -- -- and all branches pointing to L are retargetted to point to Lnew. -- Otherwise, we would repeat the $rsp adjustment for each branch to -- L. -- allocMoreStack :: Platform -> Int -> NatCmmDecl statics X86.Instr.Instr -> UniqSM (NatCmmDecl statics X86.Instr.Instr) allocMoreStack _ _ top@(CmmData _ _) = return top allocMoreStack platform slots proc@(CmmProc info lbl live (ListGraph code)) = do let entries = entryBlocks proc uniqs <- replicateM (length entries) getUniqueM let delta = ((x + stackAlign - 1) `quot` stackAlign) * stackAlign -- round up where x = slots * spillSlotSize platform -- sp delta alloc = mkStackAllocInstr platform delta dealloc = mkStackDeallocInstr platform delta new_blockmap :: LabelMap BlockId new_blockmap = mapFromList (zip entries (map mkBlockId uniqs)) insert_stack_insns (BasicBlock id insns) | Just new_blockid <- mapLookup id new_blockmap = [ BasicBlock id [alloc, JXX ALWAYS new_blockid] , BasicBlock new_blockid block' ] | otherwise = [ BasicBlock id block' ] where block' = foldr insert_dealloc [] insns insert_dealloc insn r = case insn of JMP _ _ -> dealloc : insn : r JXX_GBL _ _ -> panic "insert_dealloc: cannot handle JXX_GBL" _other -> x86_patchJumpInstr insn retarget : r where retarget b = fromMaybe b (mapLookup b new_blockmap) new_code = concatMap insert_stack_insns code -- in return (CmmProc info lbl live (ListGraph new_code)) data JumpDest = DestBlockId BlockId | DestImm Imm getJumpDestBlockId :: JumpDest -> Maybe BlockId getJumpDestBlockId (DestBlockId bid) = Just bid getJumpDestBlockId _ = Nothing canShortcut :: Instr -> Maybe JumpDest canShortcut (JXX ALWAYS id) = Just (DestBlockId id) canShortcut (JMP (OpImm imm) _) = Just (DestImm imm) canShortcut _ = Nothing -- This helper shortcuts a sequence of branches. -- The blockset helps avoid following cycles. shortcutJump :: (BlockId -> Maybe JumpDest) -> Instr -> Instr shortcutJump fn insn = shortcutJump' fn (setEmpty :: LabelSet) insn where shortcutJump' fn seen insn@(JXX cc id) = if setMember id seen then insn else case fn id of Nothing -> insn Just (DestBlockId id') -> shortcutJump' fn seen' (JXX cc id') Just (DestImm imm) -> shortcutJump' fn seen' (JXX_GBL cc imm) where seen' = setInsert id seen shortcutJump' _ _ other = other -- Here because it knows about JumpDest shortcutStatics :: (BlockId -> Maybe JumpDest) -> (Alignment, CmmStatics) -> (Alignment, CmmStatics) shortcutStatics fn (align, Statics lbl statics) = (align, Statics lbl $ map (shortcutStatic fn) statics) -- we need to get the jump tables, so apply the mapping to the entries -- of a CmmData too. shortcutLabel :: (BlockId -> Maybe JumpDest) -> CLabel -> CLabel shortcutLabel fn lab | Just blkId <- maybeLocalBlockLabel lab = shortBlockId fn emptyUniqSet blkId | otherwise = lab shortcutStatic :: (BlockId -> Maybe JumpDest) -> CmmStatic -> CmmStatic shortcutStatic fn (CmmStaticLit (CmmLabel lab)) = CmmStaticLit (CmmLabel (shortcutLabel fn lab)) shortcutStatic fn (CmmStaticLit (CmmLabelDiffOff lbl1 lbl2 off)) = CmmStaticLit (CmmLabelDiffOff (shortcutLabel fn lbl1) lbl2 off) -- slightly dodgy, we're ignoring the second label, but this -- works with the way we use CmmLabelDiffOff for jump tables now. shortcutStatic _ other_static = other_static shortBlockId :: (BlockId -> Maybe JumpDest) -> UniqSet Unique -> BlockId -> CLabel shortBlockId fn seen blockid = case (elementOfUniqSet uq seen, fn blockid) of (True, _) -> blockLbl blockid (_, Nothing) -> blockLbl blockid (_, Just (DestBlockId blockid')) -> shortBlockId fn (addOneToUniqSet seen uq) blockid' (_, Just (DestImm (ImmCLbl lbl))) -> lbl (_, _other) -> panic "shortBlockId" where uq = getUnique blockid
shlevy/ghc
compiler/nativeGen/X86/Instr.hs
bsd-3-clause
41,389
0
17
13,135
9,827
4,977
4,850
632
104
module Dotnet.System.IO.DirectoryInfo ( module Dotnet.System.IO.DirectoryInfo ) where import qualified Dotnet.System.Object data DirectoryInfo_ a type DirectoryInfo a = Dotnet.System.Object.Object (DirectoryInfo_ a)
FranklinChen/Hugs
dotnet/lib/Dotnet/System/IO/DirectoryInfo.hs
bsd-3-clause
221
2
7
25
51
34
17
-1
-1
{-# LANGUAGE TemplateHaskell #-} {-| Ganeti monitoring agent daemon -} {- Copyright (C) 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Main (main) where import Data.List ((\\)) import Ganeti.Daemon import Ganeti.DataCollectors (collectors) import Ganeti.DataCollectors.Types (dName) import Ganeti.Runtime import qualified Ganeti.Monitoring.Server as S import qualified Ganeti.Constants as C import qualified Ganeti.ConstantUtils as CU -- Check constistency of defined data collectors and their names used for the -- Python constant generation: $(let names = map dName collectors missing = names \\ CU.toList C.dataCollectorNames in if null missing then return [] else fail $ "Please add " ++ show missing ++ " to the Ganeti.Constants.dataCollectorNames.") -- | Options list and functions. options :: [OptType] options = [ oNoDaemonize , oNoUserChecks , oDebug , oBindAddress , oPort C.defaultMondPort ] -- | Main function. main :: IO () main = genericMain GanetiMond options S.checkMain S.prepMain S.main
leshchevds/ganeti
src/ganeti-mond.hs
bsd-2-clause
2,310
0
13
397
219
128
91
29
1
{-# LANGUAGE QuasiQuotes, TypeFamilies, TemplateHaskell, MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances, ViewPatterns #-} {-# LANGUAGE OverloadedStrings #-} -- the module name is a lie!!! module YesodCoreTest.NoOverloadedStrings (noOverloadedTest, Widget) where import Test.Hspec import YesodCoreTest.NoOverloadedStringsSub import Yesod.Core import Network.Wai import Network.Wai.Test import Data.Monoid (mempty) import qualified Data.Text as T import qualified Data.ByteString.Lazy.Char8 as L8 getSubsite :: a -> Subsite getSubsite _ = Subsite $(mkYesodSubDispatch resourcesSubsite) getBarR :: Monad m => m T.Text getBarR = return $ T.pack "BarR" getBazR :: Yesod master => HandlerT Subsite (HandlerT master IO) Html getBazR = lift $ defaultLayout [whamlet|Used Default Layout|] getBinR :: Yesod master => HandlerT Subsite (HandlerT master IO) Html getBinR = do widget <- widgetToParentWidget [whamlet| <p>Used defaultLayoutT <a href=@{BazR}>Baz |] lift $ defaultLayout widget getOnePiecesR :: Monad m => Int -> m () getOnePiecesR _ = return () getTwoPiecesR :: Monad m => Int -> Int -> m () getTwoPiecesR _ _ = return () getThreePiecesR :: Monad m => Int -> Int -> Int -> m () getThreePiecesR _ _ _ = return () data Y = Y mkYesod "Y" [parseRoutes| / RootR GET /foo FooR GET /subsite SubsiteR Subsite getSubsite |] instance Yesod Y getRootR :: Handler () getRootR = return () getFooR :: Handler () getFooR = return () runner :: Session () -> IO () runner f = toWaiApp Y >>= runSession f case_sanity :: IO () case_sanity = runner $ do res <- request defaultRequest assertBody mempty res case_subsite :: IO () case_subsite = runner $ do res <- request defaultRequest { pathInfo = map T.pack ["subsite", "bar"] } assertBody (L8.pack "BarR") res assertStatus 200 res case_deflayout :: IO () case_deflayout = runner $ do res <- request defaultRequest { pathInfo = map T.pack ["subsite", "baz"] } assertBodyContains (L8.pack "Used Default Layout") res assertStatus 200 res case_deflayoutT :: IO () case_deflayoutT = runner $ do res <- request defaultRequest { pathInfo = map T.pack ["subsite", "bin"] } assertBodyContains (L8.pack "Used defaultLayoutT") res assertStatus 200 res noOverloadedTest :: Spec noOverloadedTest = describe "Test.NoOverloadedStrings" $ do it "sanity" case_sanity it "subsite" case_subsite it "deflayout" case_deflayout it "deflayoutT" case_deflayoutT
meteficha/yesod
yesod-core/test/YesodCoreTest/NoOverloadedStrings.hs
mit
2,544
0
13
511
760
382
378
65
1
{-# LANGUAGE PatternSynonyms, ViewPatterns, ConstraintKinds, TypeFamilies, PolyKinds, KindSignatures #-} module T10997_1a where import GHC.Exts type family Showable (a :: k) :: Constraint where Showable (a :: *) = (Show a) Showable a = () extractJust :: Maybe a -> (Bool, a) extractJust (Just a) = (True, a) extractJust _ = (False, undefined) pattern Just' :: Showable a => a -> (Maybe a) pattern Just' a <- (extractJust -> (True, a)) where Just' a = Just a
sgillespie/ghc
testsuite/tests/patsyn/should_compile/T10997_1a.hs
bsd-3-clause
482
0
9
100
168
94
74
12
1
{-# LANGUAGE Safe #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Text.Show -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : provisional -- Portability : portable -- -- Converting values to readable strings: -- the 'Show' class and associated functions. -- ----------------------------------------------------------------------------- module Text.Show ( ShowS, Show(showsPrec, show, showList), shows, showChar, showString, showParen, showListWith, ) where import GHC.Show -- | Show a list (using square brackets and commas), given a function -- for showing elements. showListWith :: (a -> ShowS) -> [a] -> ShowS showListWith = showList__
tolysz/prepare-ghcjs
spec-lts8/base/Text/Show.hs
bsd-3-clause
889
0
7
153
89
64
25
16
1
module Main where import System.Environment import DrvGM import GCompiler import GPrinter import NParser import Iseq main :: IO () main = do args <- getArgs case (length args) of 0 -> interp 1 -> do stream <- readFile (args !! 0) putStrLn(source stream) 2 -> do stream <- readFile (args !! 1) putStr(invoke (args !! 0) stream) _ -> do putStr "usage: gm [-c|-d|-q] file" invoke :: String -> String -> String invoke opts stream | opts == "-c" = compile stream | opts == "-d" = sourceDebug stream | opts == "-q" = coqCompile stream | otherwise = "reserved for future use" interp :: IO () interp = gm sourceDebug :: String -> String sourceDebug stream = runProgDebug stream source :: String -> String source stream = runProg stream coqCompile :: String -> String coqCompile stream = (iDisplay . showCoqCompiledState. gmCompile . parse) stream compile :: String -> String compile stream = (iDisplay . showCompiledState. gmCompile . parse) stream fImplPrompt :: String fImplPrompt = "fImpl> " getEngine :: String -> IO () getEngine name | name == "gm" = gm | otherwise = interp
typedvar/hLand
hcore/Main.hs
mit
1,227
0
16
340
409
202
207
42
4
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE DataKinds #-} module Web.Apiary.Helics ( Helics -- * initializer , HelicsConfig(..) , initHelics , initHerokuHelics -- * action -- ** raw , transactionId -- ** metric , recordMetric -- ** transaction , addAttribute , setError , noticeError , clearError -- ** segment , genericSegment , datastoreSegment , externalSegment -- * reexports , H.autoScope , H.rootSegment , H.TransactionId , H.TransactionError , H.SegmentId , H.Operation(..) , H.DatastoreSegment(..) ) where import Control.Concurrent(ThreadId, forkIO) import Control.Applicative((<$>)) import Control.Monad.Apiary.Action(ActionT, getRequest) import Control.Monad.IO.Class(MonadIO(liftIO)) import Control.Monad.Trans.Control(MonadBaseControl, control) import qualified Network.Wai as Wai import qualified Network.Helics as H import qualified Network.Helics.Wai.Safe as Safe import Data.Proxy.Compat(Proxy(..)) import Data.Apiary.Extension ( Has, Extension(extMiddleware) , Initializer', initializerBracket' , Initializer, initializerBracket, getExt ) import Web.Apiary.Heroku(Heroku, getHerokuEnv) import Data.Default.Class(Default(..)) import qualified Data.Vault.Lazy as V import qualified Data.ByteString as S import qualified Data.Text.Encoding as T data Helics = Helics (V.Key H.TransactionId) ThreadId HelicsConfig instance Extension Helics where extMiddleware (Helics k _ cfg) = if useDummyMiddleware cfg then Safe.dummyHelics k else Safe.helics k (toHelicsMiddlewareConfig cfg) data HelicsConfig = HelicsConfig { licenseKey :: S.ByteString , appName :: S.ByteString , language :: S.ByteString , languageVersion :: S.ByteString , statusCallback :: Maybe (H.StatusCode -> IO ()) , useDummyMiddleware :: Bool , transactionName :: Wai.Request -> S.ByteString , samplerFrequency :: Int } instance Default HelicsConfig where def = HelicsConfig { licenseKey = H.licenseKey def , appName = H.appName def , language = H.language def , languageVersion = H.languageVersion def , statusCallback = H.statusCallback def , transactionName = Wai.rawPathInfo , useDummyMiddleware = False , samplerFrequency = 20 } toHelicsConfig :: HelicsConfig -> H.HelicsConfig toHelicsConfig c = def { H.licenseKey = licenseKey c , H.appName = appName c , H.language = language c , H.languageVersion = languageVersion c , H.statusCallback = statusCallback c } toHelicsMiddlewareConfig :: HelicsConfig -> Safe.HelicsMiddlewareConfig toHelicsMiddlewareConfig c = def { Safe.transactionName = transactionName c } initHelics :: (MonadBaseControl IO m, MonadIO m) => HelicsConfig -> Initializer' m Helics initHelics cnf = initializerBracket' $ \m -> do k <- liftIO V.newKey control $ \run -> H.withHelics (toHelicsConfig cnf) $ run $ do tid <- liftIO $ forkIO $ H.sampler (samplerFrequency cnf) m (Helics k tid cnf) initHerokuHelics :: (MonadBaseControl IO m, MonadIO m, Has Heroku exts) => HelicsConfig -> Initializer m exts (Helics ': exts) initHerokuHelics cnf = initializerBracket $ \exts m -> do k <- liftIO V.newKey cnf' <- maybe cnf (\key -> cnf { licenseKey = T.encodeUtf8 key } ) <$> liftIO (getHerokuEnv "NEW_RELIC_LICENSE_KEY" exts) control $ \run -> H.withHelics (toHelicsConfig cnf') $ run $ do tid <- liftIO $ forkIO $ H.sampler (samplerFrequency cnf') m (Helics k tid cnf') recordMetric :: MonadIO m => S.ByteString -> Double -> ActionT exts prms m () recordMetric n v = liftIO $ H.recordMetric n v transactionId :: (Has Helics exts, Monad m) => ActionT exts prms m H.TransactionId transactionId = do Helics key _ _ <- getExt Proxy maybe (error "apiary-helics: vault value not found.") id . V.lookup key . Wai.vault <$> getRequest addAttribute :: (MonadIO m, Has Helics exts) => S.ByteString -> S.ByteString -> ActionT exts prms m () addAttribute key val = do tid <- transactionId liftIO $ H.addAttribute key val tid genericSegment :: (Has Helics exts, MonadBaseControl IO m) => H.SegmentId -- ^ parent segment id -> S.ByteString -- ^ name of represent segment -> ActionT exts prms m a -> ActionT exts prms m a genericSegment sid name act = do tid <- transactionId control $ \run -> H.genericSegment sid name (run act) tid datastoreSegment :: (Has Helics exts, MonadBaseControl IO m) => H.SegmentId -- ^ parent segment id -> H.DatastoreSegment -> ActionT exts prms m a -> ActionT exts prms m a datastoreSegment sid ds act = do tid <- transactionId control $ \run -> H.datastoreSegment sid ds (run act) tid externalSegment :: (Has Helics exts, MonadBaseControl IO m) => H.SegmentId -- ^ parent segment id -> S.ByteString -- ^ host of segment -> S.ByteString -- ^ name of segment -> ActionT exts prms m a -> ActionT exts prms m a externalSegment sid host name act = do tid <- transactionId control $ \run -> H.externalSegment sid host name (run act) tid setError :: (Has Helics exts, MonadIO m) => Maybe H.TransactionError -> ActionT exts prms m () setError err = do tid <- transactionId liftIO $ H.setError err tid noticeError :: (Has Helics exts, MonadIO m) => H.TransactionError -> ActionT exts prms m () noticeError err = do tid <- transactionId liftIO $ H.noticeError err tid clearError :: (Has Helics exts, MonadIO m) => ActionT exts prms m () clearError = do tid <- transactionId liftIO $ H.clearError tid
philopon/apiary
apiary-helics/src/Web/Apiary/Helics.hs
mit
6,146
0
18
1,621
1,758
944
814
147
1
#!/usr/local/bin/runghc -i/home/martyn/bin/hlib {-# LANGUAGE FlexibleInstances , NoMonomorphismRestriction , OverlappingInstances , ScopedTypeVariables , TemplateHaskell , TypeSynonymInstances #-} -- base -------------------------------- import Control.Exception ( SomeException, evaluate, try ) import Data.Char ( isAlpha ) import Data.List ( intercalate ) import System.IO.Unsafe ( unsafePerformIO ) import Text.Printf ( printf ) -- lens -------------------------------- import Control.Lens ( (^.) ) -- template-haskell -------------------- import Language.Haskell.TH ( Exp( AppE, ConE, InfixE, LitE, SigE, VarE ) , Lit( RationalL, StringL ) , Type( AppT, ArrowT, ConT ) , ExpQ, runQ ) import Language.Haskell.TH.Syntax ( nameBase ) -- test-tap ---------------------------- import Test.TAP ( explain, is, test ) -- fluffy ------------------------------ import Fluffy.Language.TH.Type ( readType ) import Fluffy.Text.PCRE ( substg ) -- this package -------------------------------------------- import Console.Getopt.OptDesc ( descn, dfGetter, lensname, names, summary , pprintQ, typename ) import Console.Getopt.OptDescParse ( _check ) import Console.Getopt.OptDescT ( OptDesc(..) ) import Console.Getopt.OTypes ( typeDefault ) import OptDescHelp -------------------------------------------------------------------------------- render :: ExpQ -> String render = render_ . unsafePerformIO . runQ render_ :: Exp -> String -- render_ e = error ("don't know how to render: " ++ show e) render_ (InfixE (Just l) i (Just r)) = let inf = render_ i infi = if isAlpha (head inf) then "`" ++ inf ++ "`" else inf in intercalate " " [ render_ l, infi, render_ r ] render_ (VarE nm) = nameBase nm render_ (ConE nm) = nameBase nm render_ (AppE f a) = render_s f ++ " " ++ render_s a render_ (SigE e t) = render_ e ++ " :: " ++ render_t t render_ (LitE (StringL s)) = "\"" ++ s ++ "\"" render_ (LitE (RationalL r)) = show (fromRational r :: Double) render_ e = error ("don't know how to render: " ++ show e) render_s :: Exp -> String render_s e = let r = render_ e in if ' ' `elem` r then "(" ++ r ++ ")" else r render_t :: Type -> String render_t (ConT t) = nameBase t render_t (AppT ArrowT t) = render_t t ++ " ->" render_t (AppT t0 t1) = render_t t0 ++ " " ++ render_t t1 render_t t = error ("don't know how to render type: " ++ show t) -- -- what should a dfGetter look like, when parsing a pre-canned value typed_dfGetter :: String -> String -> String -> String typed_dfGetter typ val lens = printf "fromMaybe ((readType \"%s\" :: String -> %s) \"%s\") . view %s" typ typ val lens fromLeft :: Either a b -> a fromLeft (Left a) = a fromLeft (Right _) = error "fromLeft on a Right" ne7 :: Int -> Bool ne7 = (/= 7) nex :: String -> Bool nex = (/= "x") class QShow e where qshow :: e -> String instance QShow Exp where qshow = show instance QShow ExpQ where qshow = pprintQ showQ :: QShow e => e -> String showQ expr = let s = qshow expr in ("GHC.(?:Types|Base).(\\S*)" `substg` "$1") s main :: IO () main = do c1 <- $( _check "> 0" "opt1" ) (1 :: Int) c2 <- $( _check "> 0" "opt1" ) (0 :: Int) c3 <- $( _check "ne7" "opt2" ) (1 :: Int) c4 <- $( _check "ne7" "opt2" ) (7 :: Int) c5 <- $( _check "nex" "opt3" ) "y" c6 <- $( _check "nex" "opt3" ) "x" -- construct an OptDesc; test stringification -- construct an OptDesc; test stringification - maybe (no default) -- test parsing of string to OptDesc -- - types; X -> Maybe X if no default provided -- [X] -- {X,Y} -- construct an Option from an OptDesc; test expected values -- use a better munger than _ -> 9.7; test the munger -- what's "check" for? -- XXX test dflt using (...) and {...} -- p0 -------------------------------- let -- p0 = read "z|y|xx>www::Double<1.1>" :: OptDesc -- no summary show_p0 = is (show p0) "z|y|xx>www::Double<1.1>" "show p0" dfg_p0 = is (render $ dfGetter p0) (typed_dfGetter "Double" "1.1" "www___") -- (intercalate " " [ "fromMaybe ((readType \"Double\"" -- , "::", "String -> Double) \"1.1\")" -- , ".", "view www___" -- ]) "dfGetter p0" -- p1 -------------------------------- let p1 = OptDesc { _names = [ "a", "b", "cd", "ef" ] , _lensname = "ghi" , _typename = "Float" , _dflt = [| 7.0 |] , _strt = [| 7.0 |] , _summary = "summ" , _descn = "" -- pre-munge (String -> X)? post-munge (X -> X)? Not worry for now? -- pre- & post-munge could be part of the parse fn , _munge = \_ -> [| 9.7 |] } names_p1 = is (p1 ^. names) [ "a", "b", "cd", "ef" ] "names p1" lensname_p1 = is (p1 ^. lensname) "ghi" "lensname p1" type_p1 = is (p1 ^. typename) "Float" "typename p1" d1_exp <- runQ [| 7.0 |] s1_exp <- runQ [| 7.0 |] d1 <- runQ $ _dflt p1 s1 <- runQ $ _strt p1 let dflt_p1 = is (show d1) (showQ d1_exp) "dflt p1" strt_p1 = is (show s1) (showQ s1_exp) "strt p1" let summ_p1 = is (p1 ^. summary) "summ" "summ p1" let dscn_p1 = is (p1 ^. descn) "" "dscn p1" -- show of an OptDesc let show_p1 = is (show p1) "a|b|cd|ef>ghi::Float<7 / 1>#summ" "show p1" -- single long name p1_0 = p1 { _names = [ "ef" ] } show_p1_0 = is (show p1_0) "ef>ghi::Float<7 / 1>#summ" "show p1_0" -- single short name p1_1 = p1 { _names = [ "f" ] } show_p1_1 = is (show p1_1) "f>ghi::Float<7 / 1>#summ" "show p1_1" -- first name matches lensname p1_2 = p1 { _names = [ "ghi", "f" ] } show_p1_2 = is (show p1_2) "ghi|f::Float<7 / 1>#summ" "show p1_2" -- first name matches lensname p1_3 = p1 { _names = [ "ghi", "f" ], _descn = "foo\nbar" } show_p1_3 = is (show p1_3) "ghi|f::Float<7 / 1>#summ\nfoo\nbar" "show p1_3" dfg_p1 = is (render $ dfGetter p1) "fromMaybe 7.0 . view ghi___" "dfGetter p1" -- p2 -------------------------------- -- double with default, using a qualified (full) name let p2 = read "z|y|xx>www::Double<1.1>#summary?\nbaz\nquux" :: OptDesc d2 <- runQ $ _dflt p2 d2_exp <- runQ [| (readType "Double" :: String -> Double) "1.1" |] let show_p2 = is (show p2) "z|y|xx>www::Double<1.1>#summary?\nbaz\nquux" "show p2" dflt_p2 = is (showQ d2) (showQ d2_exp) "dflt p2" dscn_p2 = is (p2 ^. descn) "baz\nquux" "descn p2" dfg_p2 = is (render $ dfGetter p2) (typed_dfGetter "Double" "1.1" "www___") "dfGetter p2" -- p3 -------------------------------- -- default to Nothing -- defined in OptDescHelp let show_p3 = is (show p3) "z|y|xx>www::?Double#summary?" "show p3" d3 <- runQ $ _dflt p3 d3_exp <- runQ [| Nothing |] let dflt_p3 = is d3 d3_exp "dflt p3" dfg_p3 = is (render $ dfGetter p3) ("fromMaybe Nothing . view www___") "dfGetter p3" -- p4 -------------------------------- let p4 = read "s|string::String<bob>#mystring\ndescn" :: OptDesc names_p4 = is (p4 ^. names) [ "s", "string" ] "names p4" lensname_p4 = is (p4 ^. lensname) "s" "lensname p4" type_p4 = is (p4 ^. typename) "String" "typename p4" dfg_p4 = is (render $ dfGetter p4) (typed_dfGetter "String" "bob" "s___") "dfGetter p4" d4_exp <- runQ [| (readType "String" :: String -> String) "bob" |] -- s4_exp <- runQ [| Nothing |] let s4_exp = d4_exp d4 <- runQ $ _dflt p4 s4 <- runQ $ _strt p4 let dflt_p4 = is (showQ d4) (showQ d4_exp) "dflt p4" strt_p4 = is (showQ s4) (showQ s4_exp) "strt p4" let summ_p4 = is (p4 ^. summary) "mystring" "summ p4" let dscn_p4 = is (p4 ^. descn) "descn" "dscn p4" -- p5 -------------------------------- let p5 = read "int|i|int-opt::Int<0>#myint\nlongdesc" :: OptDesc names_p5 = is (p5 ^. names) [ "int", "i", "int-opt" ] "names p5" lensname_p5 = is (p5 ^. lensname) "int" "lensname p5" type_p5 = is (p5 ^. typename) "Int" "typename p5" d5 <- runQ $ _dflt p5 d5_exp <- runQ [| (readType "Int" :: String -> Int) "0" |] let dflt_p5 = is (showQ d5) (showQ d5_exp) "dflt p5" s5 <- runQ $ _strt p5 -- weird forms of strings to account for pprint strangeness in ghc7.8.3 / -- template-haskell-2.9.0.0; we should really handle this in showQ, (by -- changing ListE [LitE (CharL 'I'),...] to LitE (String L "I...") -- s5_exp <- runQ [| readType ['I','n','t'] ['1','3'] :: Int |] s5_exp <- runQ [| (readType "Int" :: String -> Int) "0" |] let strt_p5 = is (showQ s5) (showQ s5_exp) "strt p5" let summ_p5 = is (p5 ^. summary) "myint" "summ p5" let dscn_p5 = is (p5 ^. descn) "longdesc" "dscn p5" let dfg_p5 = is (render $ dfGetter p5) (typed_dfGetter "Int" "0" "int___") "dfGetter p5" -- p7 -------------------------------- p7 :: Either SomeException OptDesc <- try $ evaluate (read "z|y|xx>www::Double<1.1>!" :: OptDesc) let err_p7 = is (show (fromLeft p7)) "failed to parse option 'z|y|xx>www::Double<1.1>!' at '!'" "err p7" -- p8 -------------------------------- p8 :: Either SomeException OptDesc <- try $ evaluate (read "Z|y|xx::Double<1.1>" :: OptDesc) let err_p8 = is (show p8) "Left lens 'Z' may not begin with an upper-case letter" "err p8" -- p10 ------------------------------- p10 :: Either SomeException OptDesc <- try $ evaluate (read "Z|y|xx>_foo::Double<1.1>" :: OptDesc) let err_p10 = is (show p10) "Left lens '_foo' may not begin with an underscore" "err p10" -- p11 ------------------------------- p11 :: Either SomeException OptDesc <- try $ evaluate (read "z|-y|xx::Double<1.1>" :: OptDesc) let err_p11 = is (show p11) "Left option name '-y' may not begin with a hyphen" "err p11" -- p12 ------------------------------- let p12 = read "int-opt|i::Int<0>#myint\nlongdesc" :: OptDesc names_p12 = is (p12 ^. names) [ "int-opt", "i" ] "names p12" lensname_p12 = is (p12 ^. lensname) "int_opt" "lensname p12" type_p12 = is (p12 ^. typename) "Int" "typename p12" dfg_p12 = is (render $ dfGetter p12) (typed_dfGetter "Int" "0" "int_opt___") "dfGetter p12" -- p13 ------------------------------- p13 :: Either SomeException OptDesc <- try $ evaluate (read "0|y|xx::Double<1.1>" :: OptDesc) let err_p13 = is (show p13) "Left lens '0' may not begin with a digit" "err p13" -- p9 -------------------------------- let p9 = read "incr|I::incr<6>#increment" :: OptDesc names_p9 = is (p9 ^. names) [ "incr", "I" ] "names p9" lensname_p9 = is (p9 ^. lensname) "incr" "lensname p9" type_p9 = is (p9 ^. typename) "incr" "typename p9" d9 <- runQ $ _dflt p9 d9_exp <- runQ [| (readType "Int" :: String -> Int) "6" |] explain "p9" p9 let dflt_p9 = is (showQ d9) (showQ d9_exp) "dflt p9" s9 <- runQ $ _strt p9 s9_exp <- runQ [| (readType "Int" :: String -> Int) "6" |] let strt_p9 = is (showQ s9) (showQ s9_exp) "strt p9" let summ_p9 = is (p9 ^. summary) "increment" "summ p9" let dscn_p9 = is (p9 ^. descn) "" "dscn p9" let dfg_p9 = is (render $ dfGetter p9) (typed_dfGetter "Int" "6" "incr___") "dfGetter p9" -- p14 ------------------------------- -- tests for filero let p14 = read "filero::filero</etc/passwd>#filero" :: OptDesc let show_p14 = is (show p14) "filero::filero</etc/passwd>#filero" "show p14" d14 <- runQ $ _dflt p14 d14_exp <- runQ [| id "/etc/passwd" |] let dflt_p14 = is d14 d14_exp "dflt p14" dfg_p14 = is (render $ dfGetter p14) ("fromMaybe (id \"/etc/passwd\") . view filero___") "dfGetter p14" -- test ---------------------------------------------------------------------- let typeD = maybe "-NONE-" showQ . typeDefault test [ is (render [| read "7" |]) "read \"7\"" "render read \"7\"" , is (typeD "String") (pprintQ [| "" |]) "typeDefault String" , is (typeD "Int") (pprintQ [| 0 |]) "typeDefault Int" , is (typeD "Float") "-NONE-" "typeDefault Float" , is (typeD "?String") (pprintQ [| Nothing |]) "typeDefault ?String" , is (typeD "Maybe Int") "-NONE-" "typeDefault Maybe Int" , is (typeD "?[[Int]]") (pprintQ [| Nothing |]) "typeDefault ?[[Int]]" , is (typeD "[Int]") (pprintQ [| [] |]) "typeDefault [Int]" , is (typeD "[[Int]]") (pprintQ [| [] |]) "typeDefault [[Int]]" , show_p0 , dfg_p0 , show_p1 , names_p1 , lensname_p1 , type_p1 , dflt_p1 , strt_p1 , summ_p1 , dscn_p1 , dfg_p1 , show_p1_0 , show_p1_1 , show_p1_2 , show_p1_3 , show_p2 , dflt_p2 , dscn_p2 , dfg_p2 -- , diag $ show p7 -- get a meaningful parse error , err_p7 -- get a meaningful parse error for upper-case first letter on first arg -- name , err_p8 -- get a meaningful parse error for underscore on lens name -- name , err_p10 -- get a meaningful parse error for leading hyphen on opt name -- name , err_p11 -- get a meaningful parse error for leading digit on lens name -- name , err_p13 , show_p3 , dflt_p3 -- , explain "p3" p3 , dfg_p3 , names_p4 , lensname_p4 , type_p4 , dflt_p4 , strt_p4 , summ_p4 , dscn_p4 , dfg_p4 , names_p5 , lensname_p5 , type_p5 , dflt_p5 , strt_p5 , summ_p5 , dscn_p5 , dfg_p5 , names_p9 , lensname_p9 , type_p9 , dflt_p9 , strt_p9 , summ_p9 , dscn_p9 , dfg_p9 , names_p12 , lensname_p12 , type_p12 , dfg_p12 , show_p14 , dflt_p14 , dfg_p14 ------------------------------------------------------------------------- , is c1 Nothing "check > 0 pass" , is c2 (Just "option opt1 val 0 failed check: > 0") "check > 0 fail" , is c3 Nothing "check ne7 pass" , is c4 (Just "option opt2 val 7 failed check: 'ne7'") "check ne7 pass" , is c5 Nothing "check nex pass" , is c6 (Just "option opt3 val \"x\" failed check: 'nex'") "check nex fail" ]
sixears/getopt
t/OptDesc.hs
mit
16,815
0
14
6,204
3,689
1,955
1,734
296
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Google.Cloud.Internal.Token where import Control.Applicative import Control.Concurrent.STM import Control.Monad.Reader import Data.Text (Text) import Data.Text.Encoding import Data.Monoid import Data.Time import Network.HTTP.Types.Header import Google.Cloud.Internal.Types import Google.Cloud.Compute.Metadata import Prelude -- | Fetch the access token for the default service account from the local -- metadata server. This only works when the code is running in the Google -- cloud and the instance has a services account attached to it. defaultMetadataToken :: Cloud Token defaultMetadataToken = serviceAccountToken "default" -- | Store the token in the cache. If the cache already contains a token, -- the better one of the two is actually stored (where *better* is defined -- as the one which expires later). So it is safe to call this function -- even if you are unsure if the token you have is better than the one -- which is already in the cache. -- -- Returns the better token. cacheToken :: Token -> Cloud Token cacheToken token = do tokenTVar <- asks hToken cloudIO $ atomically $ do currentToken <- readTVar tokenTVar let newToken = case currentToken of Nothing -> token Just x -> if tokenExpiresAt x > tokenExpiresAt token then x else token writeTVar tokenTVar (Just newToken) return newToken refreshToken :: Cloud Token refreshToken = do fetchToken <- asks hFetchToken token <- fetchToken cacheToken token -- | Return the value of the access token. The function guarantees that the -- token is valid for at least 60 seconds. Though you should not be afraid -- to call the function frequently, it caches the token inside the 'Handle' so -- there is very little overhead. accessToken :: Cloud Text accessToken = do tokenTVar <- asks hToken mbToken <- cloudIO $ atomically $ readTVar tokenTVar tokenValue <$> case mbToken of Nothing -> refreshToken Just t -> do now <- cloudIO $ getCurrentTime if now > addUTCTime (-60) (tokenExpiresAt t) then refreshToken else return t -- | Construct a 'Header' that contains the authorization details. Such a header -- needs to be supplied to all requsts which require authorization. -- -- Not all requests require it. In particular, requests to the metadata server -- don't. authorizationHeader :: Cloud Header authorizationHeader = do token <- accessToken return ("Authorization", "Bearer " <> encodeUtf8 token)
wereHamster/google-cloud
src/Google/Cloud/Internal/Token.hs
mit
2,636
0
18
576
416
220
196
46
3
module Y2020.M10.D12.Exercise where import Data.Map (Map) import Data.Text import Data.Aeson -- Okay, we have a query that we want to make to wikidata. Let's make it. -- import Wikidata.Query.Builder -- Okay, that doesn't work with newer versions of GHCI. Oh, well. {-- The SPARQL query: SELECT ?item ?itemLabel ?icao ?countryLabel ?loc WHERE { ?item wdt:P31 wd:Q695850. ?item wdt:P239 ?icao. ?item wdt:P17 ?country. ?item wdt:P625 ?loc SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". } } yields airbases.json (at this directory). --} workingDir :: FilePath workingDir = "Y2020/M10/D12/" file :: FilePath file = "airbases.json" -- As you see above, the data model is something like this: type Key = String type Entity = Text type Icao = String type Country = String data LongLat = Point Double Double deriving (Eq, Ord, Show) data AirBase = Base Key Entity Icao Country LongLat deriving (Eq, Ord, Show) -- 1. Load in the airbases. instance FromJSON LongLat where parseJSON = undefined instance FromJSON AirBase where parseJSON = undefined loadBases :: FilePath -> IO (Maybe [AirBase]) loadBases = undefined -- 2. How many airbases are there? -- 3. Actually, that's a tricky question, because, as you examine the data, -- you see there are duplicate results. And a `distict` in the SPARQL -- query doesn't eliminate the duplicates in the result. -- Let's solve that problem. byICAO :: [AirBase] -> Map Icao AirBase byICAO = undefined -- 4. Now: how many bases are there, without duplicates?
geophf/1HaskellADay
exercises/HAD/Y2020/M10/D12/Exercise.hs
mit
1,625
0
9
341
216
129
87
24
1
{-# LANGUAGE TemplateHaskell #-} module UnitTest.CallbackParse.ThreadControl where import Data.Aeson (Value) import Data.Yaml.TH (decodeFile) import Test.Tasty as Tasty import Web.Facebook.Messenger import UnitTest.Internal -------------------- -- THREAD CONTROL -- -------------------- threadControlTests :: TestTree threadControlTests = Tasty.testGroup "Thread Control Callbacks" [ passThreadCallback , requestThreadCallback , takeThreadCallback ] passThreadVal :: Value passThreadVal = $$(decodeFile "test/json/callback/pass_thread_control.json") requestThreadVal :: Value requestThreadVal = $$(decodeFile "test/json/callback/request_thread_control.json") takeThreadVal :: Value takeThreadVal = $$(decodeFile "test/json/callback/take_thread_control.json") passThreadCallback :: TestTree passThreadCallback = parseTest "Pass thread" passThreadVal $ msg $ CMPassThread $ PassThread (AppId "123456789") $ Just "Additional content that the caller wants to set" requestThreadCallback :: TestTree requestThreadCallback = parseTest "Request thread" requestThreadVal $ msg $ CMRequestThread $ RequestThread (AppId "123456789") $ Just "additional content that the caller wants to set" takeThreadCallback :: TestTree takeThreadCallback = parseTest "Take thread" takeThreadVal $ msg $ CMTakeThread $ TakeThread (AppId "123456789") $ Just "additional content that the caller wants to set!" msg :: CallbackContent -> CallbackMessaging msg contnt = standardMessaging (Just 1458692752478) Nothing contnt
Vlix/facebookmessenger
test/UnitTest/CallbackParse/ThreadControl.hs
mit
1,730
0
9
396
286
154
132
-1
-1
{-# LANGUAGE Rank2Types #-} module SoOSiM.Components.Common where import Data.Maybe import Control.Monad import SoOSiM type GUID = Int type AppId = GUID type ProcessId = ComponentId type ThreadId = ProcessId data Code = Code data Architecture = Architecture data ResourceDescription = ResourceDescription maybe' :: Maybe a -> b -> (a -> b) -> b maybe' m a f = maybe a f m whenM :: Monad m => (m Bool) -> m () -> m () whenM t f = do t >>= (\t' -> when t' f) uncurry2 :: (a -> b -> c -> d) -> (a,b,c) -> d uncurry2 f (a,b,c) = f a b c untilJust :: Monad m => (m (Maybe a)) -> m a untilJust mf = do aM <- mf case aM of Just a -> return a Nothing -> untilJust mf untilNothing :: Monad m => m (Maybe a) -> (a -> m ()) -> m () untilNothing mf mu = do aM <- mf case aM of Nothing -> return () Just a -> mu a >> untilNothing mf mu (><) :: (a -> b) -> (c -> d) -> (a,c) -> (b,d) (f >< g) (a,b) = (f a, g b) dot = (.) . (.)
christiaanb/SoOSiM-components
src/SoOSiM/Components/Common.hs
mit
995
0
11
286
510
267
243
41
2
{-# LANGUAGE UnicodeSyntax #-} module JavaScript.Famous.Common where import JavaScript.Famous.Types import GHCJS.Foreign (jsUndefined) import GHCJS.Marshal (ToJSRef, toJSRef) import Unsafe.Coerce (unsafeCoerce) instance ToJSRef Size where toJSRef (XY x y) = unsafeCoerce $ toJSRef (x , y ) toJSRef (X x ) = unsafeCoerce $ toJSRef (x , jsUndefined) toJSRef ( Y y) = unsafeCoerce $ toJSRef (jsUndefined, y ) toJSRef Auto = unsafeCoerce $ toJSRef (jsUndefined, jsUndefined)
eallik/ghcjs-famous
src/JavaScript/Famous/Common.hs
mit
596
0
8
190
159
88
71
11
0
module Graphics.UI.GLFW.Netwire.Window.Core ( WindowHandle, Window(..), WindowRecord(..), GLContext(..), getWindowSize, setWindowSize, inWindow, InputBuffer(..), annotateWindow, getStateWire, setStateWire, modifyStateWire, windowRecord, attachWire --VideoMode(..), --getFocusedWindow, --getWindowSize, --setWindowSize, --swapBuffers, --createWindow--, --getVideoMode ?? ) where --Mostly re-exports from GLFW intended for use with annotated Window type for the netwire session import qualified Graphics.UI.GLFW as GLFW import Prelude hiding ((.)) --import qualified Graphics.Rendering.GL as GL import Control.Applicative import Data.IORef import Control.Wire import Control.Monad.Trans.Except import Control.Monad.IO.Class import Graphics.UI.GLFW.Netwire.Exception import Graphics.UI.GLFW.Netwire.Input.Core --Avoid repeatedly setting GL Mode --{-# NOINLINE lastFocusedWindowRef #-} --lastFocusedWindowRef :: IORef (Maybe Window) --lastFocusedWindowRef = unsafePerformIO $ newIORef Nothing type WindowHandle = GLFW.Window newtype GLContext = GLContext { glContextNaughtyBits :: Window } --type Window = () data Window = Window { windowHandle :: WindowHandle, windowNaughtyBits :: IORef (Maybe WindowRecord) } --placeholder until input buffer is written type InputBuffer = () mkEmptyInputBuffer wh = return () data WindowRecord = WindowRecord { stateWireField :: IORef (Wire Double () Identity InputBuffer (IO ())), lastInputField :: InputBuffer } getStateWire :: (MonadIO m) => Window -> ExceptT GLFWSessionError m (Wire Double () Identity InputBuffer (IO())) getStateWire window = do wrec <- windowRecord window liftIO $ readIORef (stateWireField wrec) setStateWire :: (MonadIO m) => Window -> Wire Double () Identity InputBuffer (IO ()) -> ExceptT GLFWSessionError m () setStateWire window sw = do wrec <- windowRecord window liftIO $ writeIORef (stateWireField wrec) sw modifyStateWire :: (MonadIO m) => Window -> (Wire Double () Identity InputBuffer (IO ()) -> Wire Double () Identity InputBuffer (IO ())) -> ExceptT GLFWSessionError m () modifyStateWire window f = do wrec <- windowRecord window sw <- liftIO $ readIORef $ stateWireField wrec liftIO $ writeIORef (stateWireField wrec) (f sw) windowRecord :: (MonadIO m) => Window -> ExceptT GLFWSessionError m WindowRecord windowRecord window = do winrec <- liftIO $ readIORef (windowNaughtyBits window) case winrec of Nothing -> throwE GLFWSessionErrorWindowClosed Just rec -> return rec attachWire :: (MonadIO m) => Window -> Wire Double () Identity InputBuffer (IO()) -> ExceptT GLFWSessionError m () attachWire window wire = modifyStateWire window (--> wire) inWindow :: Window -> (GLContext -> IO ()) -> IO () inWindow window drawAction = drawAction (GLContext window) newWindowRecord :: WindowHandle -> IO WindowRecord newWindowRecord wh = do buf <- mkEmptyInputBuffer wh -- extsD <- newIORef (Set.fromList exts) stWire <- newIORef (inhibit ()) return $ WindowRecord stWire buf --dangerous, only call once for the same input annotateWindow :: WindowHandle -> IO Window annotateWindow wh = do wrec <- newWindowRecord wh wrecPtr <- newIORef (Just wrec) return $ Window wh wrecPtr --Even though it is possible given the data declaration, the implementation of netwire-glfw-b --should guarantee that any Window with the same WindowHandle is the same Window instance Eq Window where w1 == w2 = windowHandle w1 == windowHandle w2 --type GLDrawParams = GLFW.VideoMode -- | Returns the size of a netwire-glfw-b window as a width-height pair getWindowSize :: Window -> IO (Int,Int) getWindowSize = GLFW.getWindowSize . windowHandle -- | Sets the size of a netwire-glfw-b window setWindowSize :: Window -- ^ The window to resize -> Int -- ^ The new width of the window -> Int -- ^ The new height of the window -> IO () setWindowSize window = GLFW.setWindowSize (windowHandle window) {-- giveFocusTo :: Window -> IO () giveFocusTo window = do currentWindow <- readIORef focusedWindowRef case currentWindow of Nothing -> return () Just cw -> do t <- fmap (maybe 0 id) GLFW.getTime writeIORef (currentTime cw) t tnew <- readIORef (currentTime window) GLFW.setTime tnew writeIORef focusedWindowRef $ Just window GLFW.makeContextCurrent (Just (windowHandle window)) --set up OpenGL to draw on the window -- loseFocus :: IO () loseFocus = do currentWindow <- readIORef focusedWindowRef case currentWindow of Nothing -> return () Just cw -> do t <- fmap (maybe 0 id) GLFW.getTime writeIORef (currentTime cw) t writeIORef focusedWindowRef Nothing GLFW.makeContextCurrent Nothing getWindowFocusCallback :: Window -> GLFW.WindowFocusCallback getWindowFocusCallback w _ GLFW.FocusState'Focused = giveFocusTo w getWindowFocusCallback _ _ _ = loseFocus --TODO: setGLMode to allow users to set up custom projections for windows getFocusedWindow :: IO (Maybe Window) getFocusedWindow = readIORef focusedWindowRef -- swapBuffers :: Window -> IO () swapBuffers window = GLFW.swapBuffers $ windowHandle window createWindow :: Int -> Int -> String -> IO Window createWindow width height name = do Just wh <- GLFW.createWindow width height name Nothing Nothing t <- newIORef 0 let window = Window t wh GLFW.setWindowFocusCallback wh $ Just(GLFW.getWindowFocusCallback window) return window --initializeWindowSubsystem :: IO () --initializeWindowSubsystem --}
barendventer/netwire-glfw-b
src/Graphics/UI/GLFW/Netwire/Window/Core.hs
mit
5,777
0
14
1,212
1,015
541
474
78
2
module Model.Mechanics (module System.Random ,module Model.Object ,tag ,mergeCollading ,createNew ,move ) where import Data.Maybe import System.Random import Model.Object {- findPointed function. Extracts an object from an object list which contains a supplied point. It is assumed that there might not be two or more objects containing supplied point. These objects are colliding and should be eliminated before to call this function. Still, if there are more then one objects in a list containg supplied point, then findPointed function returns the first one. -} findPointed :: (Floating a, Ord a) => Pnt a -> [Object a] -> (Maybe (Object a), [Object a]) findPointed p objs = -- Break list until the object containing a point. let (before, after) = break (objectHas p) objs in case after of -- If the whole list doesn't have it, then return nothing. [] -> (Nothing, objs) -- Otherwise, the first element in 'after' is that object. x:xs -> (Just x, before ++ xs) {- findColladingWith. Finds first object colliding with supplied one. It returns a triple of * Maybe collading object; * Not collading objects; * Didn't cheked for being colliding objects. -} firstCollidingWith :: (Floating a, Ord a) => Object a -> [Object a] -> (Maybe (Object a), [Object a], [Object a]) firstCollidingWith obj objS = -- Break list until the object containing a supplied one. let (before, after) = break (objectCollidingWith obj) objS in case after of -- If the whole list doesn't have it, then return nothing. [] -> (Nothing, objS, []) -- Otherwise, the first element in 'after' is that object. x:xs -> (Just x, before, xs) {- allColladingWith. Reduces all objects supplied with the given one. It extracts all collading objects with supplied one and then merges them into one. It returns a tuple of a result of mergin and a list of objects without any collading with supplied one. -} allColladingWith :: (Floating a, Ord a) => Object a -> [Object a] -> ([Object a], [Object a]) allColladingWith obj = -- Collect collading objects into a list. collectCollading . -- Split collading objects from other ones. splitCollading where {- The functions below works with triples of form: ([Maybe (Object a)], [Object a], [Object a]) where * first: collading objects; * second: not collading objects; * third: unchecked objects. These triples is called normalized if the list of unchecked objects is empty. Reducing drops elements of unchecked list until first collading object. -} -- Collecting just maps list of maybes to list of objects. collectCollading (cs, bf, _) = (fromJust $ sequence $ filter isJust cs, bf) -- Checks whether triple is normalized: whether there is -- nothing left to check. normalized (_, _, af) = null af -- One step of reducing. reduceNext (cs, bf, af) = let (c, bf', af') = firstCollidingWith obj af in (c:cs, bf ++ bf', af') -- Splits supplied list of object on two list of -- maybe collading objects and non collading ones. splitCollading = until normalized reduceNext . (,,) [] [] {- mergeCollading. Merges all collading objects. Returns a list of old non collading objects and new merged ones. -} mergeCollading :: (Floating a, Ord a) => [Object a] -> [Object a] mergeCollading = -- Returns list of merged collading objects. fst . -- While unchecked list isn't null. until (\ (_, xs) -> null xs) -- Take a first unchecked object. (\ (ms, x:xs) -> let -- Find all collading object with it. (cs, ys) = allColladingWith x xs -- Merge them into one. m = foldl mergeObjectWith x cs in -- Continue with merged added and the rest unchecked. (m:ms, ys)) . (,) [] {- randomColor. Returns a random color. -} randomColor :: RandomGen g => g -> (Color, g) randomColor = idx2clr . randomR (minIdx, maxIdx) where idx2clr (idx, g) = (toEnum idx, g) maxIdx = fromEnum $ (maxBound :: Color) minIdx = fromEnum $ (minBound :: Color) {- randomRadius. Returns a random radius. -} randomRadius :: (Fractional a, Random a, RandomGen g) => g -> (a, g) randomRadius = randomR (minRad, maxRad) where maxRad = 50.0 minRad = 10.0 {- createNew. Creates a new object with random radius and color. -} createNew :: (Fractional a, Random a, RandomGen g) => g -> Pnt a -> (Object a, g) createNew g p = let -- Random color. (c, g') = randomColor g -- Random radius. (r, g'') = randomRadius g -- Initial velocity is null. v = vel 0.0 0.0 -- Initial acceleration is null. a = acc 0.0 0.0 in (Object p v a r c, g'') {- tag function. Finds an object with supplied point. If there is such object, then it makes it bigger. Otherwise it creates a new one. -} tag :: (Floating a, Ord a, Random a, RandomGen g) => g -> Pnt a -> [Object a] -> ([Object a], g) tag g p objs = let (x, xs) = findPointed p objs in case x of Nothing -> let (y, g') = createNew g p in (y:xs, g') Just y -> (increaseObject y : xs, g) {- move. Moves objects assuming the movement took supplied time period. -} move :: Floating a => a -> [Object a] -> [Object a] move dt = map (moveObject dt)
wowofbob/circles
src/Model/Mechanics.hs
mit
6,009
0
14
1,955
1,224
667
557
75
2
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-} module Model.Run.Api ( addUser, setUserToken, listLanguageVersions, runSnippet ) where import Import.NoFoundation hiding (error, stderr, stdout) import Util.Api (createUser, updateUser) import Data.Aeson (decode) import Data.Maybe (fromJust) import Util.Http (httpPostStatus, httpGet) import Settings.Environment (runApiBaseUrl, runApiAdminToken) import qualified Data.ByteString.Lazy as L data InternalRunResult = InternalRunResult { stdout :: Text, stderr :: Text, error :: Text } deriving (Show, Generic) instance FromJSON InternalRunResult data InternalVersion = InternalVersion { version :: Text } deriving (Show, Generic) instance FromJSON InternalVersion data InternalErrorResponse = InternalErrorResponse { message :: Text } deriving (Show, Generic) instance FromJSON InternalErrorResponse addUser :: Text -> IO Text addUser userToken = do url <- createUserUrl <$> runApiBaseUrl adminToken <- runApiAdminToken createUser url adminToken userToken setUserToken :: Text -> Text -> IO () setUserToken userId userToken = do url <- (updateUserUrl userId) <$> runApiBaseUrl adminToken <- runApiAdminToken updateUser url adminToken userToken toRunResultTuple :: InternalRunResult -> (Text, Text, Text) toRunResultTuple x = (stdout x, stderr x, error x) runSnippet :: Text -> Text -> L.ByteString -> Text -> IO (Either Text (Text, Text, Text)) runSnippet lang version payload authToken = do apiUrl <- (runSnippetUrl lang version) <$> runApiBaseUrl (statusCode, body) <- httpPostStatus apiUrl (Just authToken) payload case statusCode of 200 -> do let mJson = decode body :: Maybe InternalRunResult return $ Right (toRunResultTuple $ fromJust mJson) 400 -> do let mJson = decode body :: Maybe InternalErrorResponse return $ Left (message $ fromJust mJson) _ -> return $ Left "Got unexpected response" listLanguageVersions :: Text -> IO [Text] listLanguageVersions lang = do apiUrl <- (listVersionsUrl lang) <$> runApiBaseUrl body <- httpGet apiUrl Nothing let mJson = decode body :: Maybe [InternalVersion] return $ map version $ fromJust mJson createUserUrl :: String -> String createUserUrl baseUrl = baseUrl ++ "/admin/users" updateUserUrl :: Text -> String -> String updateUserUrl userId baseUrl = baseUrl ++ "/admin/users/" ++ unpack userId runSnippetUrl :: Text -> Text -> String -> String runSnippetUrl lang version baseUrl = baseUrl ++ "/languages/" ++ unpack lang ++ "/" ++ unpack version listVersionsUrl :: Text -> String -> String listVersionsUrl lang baseUrl = baseUrl ++ "/languages/" ++ unpack lang
vinnymac/glot-www
Model/Run/Api.hs
mit
2,752
0
16
541
812
419
393
67
3
module Dupes.FileStat (FileStat, UnixFileStat(..), create, toByteString) where import Data.Binary import qualified Data.ByteString as B import Database.SQLite.Simple.FromField import Database.SQLite.Simple.ToField import System.PosixCompat newtype FileStat = FileStat B.ByteString deriving (Eq, Ord, Show) instance FromField FileStat where fromField field = FileStat <$> fromField field instance ToField FileStat where toField = toField . toByteString data UnixFileStat = UnixFileStat { mtime :: EpochTime , ctime :: EpochTime , inode :: FileID , size :: FileOffset , uid :: UserID , gid :: GroupID } create :: FileStat create = FileStat B.empty fromUnixFileStat :: UnixFileStat -> FileStat fromUnixFileStat = undefined toByteString :: FileStat -> B.ByteString toByteString (FileStat bs) = bs instance Binary FileStat where put (FileStat bs) = put bs get = FileStat <$> get prop_encode_decode_is_id = undefined
danstiner/dupes
src/Dupes/FileStat.hs
mit
1,063
0
8
273
259
150
109
30
1
{-# htermination mzero :: [] a #-} import Monad
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Monad_mzero_1.hs
mit
48
0
3
9
5
3
2
1
0
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE UndecidableInstances #-} module Betfair.APING.Types.RunnerCatalog ( RunnerCatalog(..) ) where import Data.Aeson.TH (Options (omitNothingFields), defaultOptions, deriveJSON) import Protolude import Text.PrettyPrint.GenericPretty data RunnerCatalog = RunnerCatalog { selectionId :: Integer , runnerName :: Text , handicap :: Double , sortPriority :: Int , metadata :: Maybe [Text] -- [Runner_METADATA] } deriving (Eq, Show, Generic, Pretty) $(deriveJSON defaultOptions {omitNothingFields = True} ''RunnerCatalog)
joe9/betfair-api
src/Betfair/APING/Types/RunnerCatalog.hs
mit
839
0
10
198
141
89
52
21
0
module Feature.UnicodeSpec where import Test.Hspec import Test.Hspec.Wai import Test.Hspec.Wai.JSON import Network.Wai (Application) import Control.Monad (void) import Protolude hiding (get) spec :: SpecWith Application spec = describe "Reading and writing to unicode schema and table names" $ it "Can read and write values" $ do get "/%D9%85%D9%88%D8%A7%D8%B1%D8%AF" `shouldRespondWith` "[]" void $ post "/%D9%85%D9%88%D8%A7%D8%B1%D8%AF" [json| { "هویت": 1 } |] get "/%D9%85%D9%88%D8%A7%D8%B1%D8%AF" `shouldRespondWith` [json| [{ "هویت": 1 }] |]
NotBrianZach/postgrest
test/Feature/UnicodeSpec.hs
mit
608
0
9
120
124
72
52
-1
-1
module Diamond where import Data.List inner :: Char -> String inner c | c == 'A' = "" | c == 'B' = " " | otherwise = replicate ((length $ inner $ pred c) + 2) ' ' outer :: Int -> Char -> String outer maxLen 'A' = replicate ((maxLen - 1) `div` 2) ' ' outer maxLen c = replicate ((maxLen - ((length (inner c)) + 2)) `div` 2) ' ' defineDiamondLines :: Char -> [Char] defineDiamondLines 'A' = "A" defineDiamondLines c = concat [preC, [c], reverse preC] where preC = ['A' .. pred c] createDiamondLine :: Int -> Char -> String createDiamondLine 0 _ = "" createDiamondLine maxLen 'A' = concat [(outer maxLen 'A'), "A"] createDiamondLine maxLen c = concat [(outer maxLen c), [c], (inner c), [c]] createDiamond :: Char -> String createDiamond 'A' = "A" createDiamond c = unlines $ map (createDiamondLine maxLen) (defineDiamondLines c) where maxLen = (length (inner c)) + 2
fonzerelly/diamondKata
Diamond.hs
mit
915
0
15
209
404
213
191
22
1
module Main where import Web.Scotty import Data.Text (Text) import Data.Text.IO (readFile, writeFile) import Database.HDBC.Sqlite3 (connectSqlite3, Connection) import Database.HDBC (prepare, execute, commit, fetchAllRows) import Database.HDBC.SqlValue (SqlValue, fromSql, toSql) import Data.Time (UTCTime, getCurrentTime) import Data.Time.Format (formatTime) import Prelude hiding (readFile, writeFile) import Network.Wai.Middleware.RequestLogger type User = Text type Token = Text data Story = Story User Text UTCTime deriving (Show) data TomeOfStories = TomeOfStories User [Story] deriving (Show) token :: FilePath token = "token" databasePath :: FilePath databasePath = "tome.db" holder :: TomeOfStories -> User holder (TomeOfStories h _) = h makeSqlStory :: Story -> [SqlValue] makeSqlStory (Story user story timestamp) = [toSql user, toSql story, toSql timestamp] main :: IO () main = do token <- readFile "token" scotty 8000 $ do middleware logStdoutDev
thedufer/TomeOfStories
Main.hs
mit
976
0
10
139
313
180
133
29
1
Preprocessing executable 'VisualizingHaskellAST' for VisualizingHaskellAST-0.1.0.0... {Bag(Located (HsBind Var)): [ (L {testing/A.hs:6:4-14} (AbsBinds [{Var: a}] [{Var: $dNum}] [ (ABE {Var: A.b} {Var: b} (WpCompose (WpCompose (WpCompose (WpTyLam {Var: a}) (WpEvLam {Var: $dNum})) (WpLet ({abstract:TcEvBinds}))) (WpCompose (WpEvApp (EvId {Var: $dNum})) (WpTyApp a))) (SpecPrags []))] ({abstract:TcEvBinds}) {Bag(Located (HsBind Var)): [ (L {testing/A.hs:6:4-14} (FunBind (L {testing/A.hs:6:4} {Var: b}) (False) (MatchGroup [ (L {testing/A.hs:6:4-14} (Match [ (L {testing/A.hs:6:6} (VarPat {Var: x}))] (Nothing) (GRHSs [ (L {testing/A.hs:6:10-14} (GRHS [] (L {testing/A.hs:6:10-14} (OpApp (L {testing/A.hs:6:10} (HsVar {Var: x})) (L {testing/A.hs:6:12} (HsWrap (WpCompose (WpEvApp (EvId {Var: $dNum})) (WpTyApp a)) (HsVar {Var: GHC.Num.+}))) {Fixity: infixl 6} (L {testing/A.hs:6:14} (HsOverLit (OverLit (HsIntegral (5)) (False) (HsApp (L {<no location info>} (HsWrap (WpCompose (WpEvApp (EvId {Var: $dNum})) (WpTyApp a)) (HsVar {Var: GHC.Num.fromInteger}))) (L {<no location info>} (HsLit (HsInteger (5) GHC.Integer.Type.Integer)))) a)))))))] (EmptyLocalBinds))))] a -> a) (WpHole) {!NameSet placeholder here!} (Nothing)))]})), (L {testing/A.hs:4:4-43} (AbsBinds [] [] [ (ABE {Var: A.main} {Var: main} (WpHole) (SpecPrags []))] ({abstract:TcEvBinds}) {Bag(Located (HsBind Var)): [ (L {testing/A.hs:4:4-43} (FunBind (L {testing/A.hs:4:4-7} {Var: main}) (False) (MatchGroup [ (L {testing/A.hs:4:4-43} (Match [] (Nothing) (GRHSs [ (L {testing/A.hs:4:11-43} (GRHS [] (L {testing/A.hs:4:11-43} (HsApp (L {testing/A.hs:4:11-15} (HsWrap (WpCompose (WpEvApp (EvId {Var: $dShow})) (WpTyApp [GHC.Types.Char])) (HsVar {Var: System.IO.print}))) (L {testing/A.hs:4:17-43} (HsPar (L {testing/A.hs:4:18-42} (OpApp (L {testing/A.hs:4:18-27} (HsLit (HsString {FastString: "Result: "}))) (L {testing/A.hs:4:29-30} (HsWrap (WpTyApp GHC.Types.Char) (HsVar {Var: GHC.Base.++}))) {Fixity: infixr 5} (L {testing/A.hs:4:32-42} (HsPar (L {testing/A.hs:4:33-41} (HsApp (L {testing/A.hs:4:33-36} (HsWrap (WpCompose (WpEvApp (EvId {Var: $dShow})) (WpTyApp GHC.Integer.Type.Integer)) (HsVar {Var: GHC.Show.show}))) (L {testing/A.hs:4:37-41} (HsPar (L {testing/A.hs:4:38-40} (HsApp (L {testing/A.hs:4:38} (HsWrap (WpCompose (WpEvApp (EvId {Var: $dNum})) (WpTyApp GHC.Integer.Type.Integer)) (HsVar {Var: A.b}))) (L {testing/A.hs:4:40} (HsOverLit (OverLit (HsIntegral (5)) (False) (HsApp (L {<no location info>} (HsWrap (WpCompose (WpEvApp (EvId {Var: $dNum})) (WpTyApp GHC.Integer.Type.Integer)) (HsVar {Var: GHC.Num.fromInteger}))) (L {<no location info>} (HsLit (HsInteger (5) GHC.Integer.Type.Integer)))) GHC.Integer.Type.Integer)))))))))))))))))))] (EmptyLocalBinds))))] GHC.Types.IO ()) (WpHole) {!NameSet placeholder here!} (Nothing)))]}))]} ===================END OF MODULE: A================= {Bag(Located (HsBind Var)): [ (L {testing/B.hs:3:4-21} (AbsBinds [{Var: a}] [{Var: $dNum}] [ (ABE {Var: B.plusFive} {Var: plusFive} (WpCompose (WpCompose (WpCompose (WpTyLam {Var: a}) (WpEvLam {Var: $dNum})) (WpLet ({abstract:TcEvBinds}))) (WpCompose (WpEvApp (EvId {Var: $dNum})) (WpTyApp a))) (SpecPrags []))] ({abstract:TcEvBinds}) {Bag(Located (HsBind Var)): [ (L {testing/B.hs:3:4-21} (FunBind (L {testing/B.hs:3:4-11} {Var: plusFive}) (False) (MatchGroup [ (L {testing/B.hs:3:4-21} (Match [ (L {testing/B.hs:3:13} (VarPat {Var: x}))] (Nothing) (GRHSs [ (L {testing/B.hs:3:17-21} (GRHS [] (L {testing/B.hs:3:17-21} (OpApp (L {testing/B.hs:3:17} (HsVar {Var: x})) (L {testing/B.hs:3:19} (HsWrap (WpCompose (WpEvApp (EvId {Var: $dNum})) (WpTyApp a)) (HsVar {Var: GHC.Num.+}))) {Fixity: infixl 6} (L {testing/B.hs:3:21} (HsOverLit (OverLit (HsIntegral (5)) (False) (HsApp (L {<no location info>} (HsWrap (WpCompose (WpEvApp (EvId {Var: $dNum})) (WpTyApp a)) (HsVar {Var: GHC.Num.fromInteger}))) (L {<no location info>} (HsLit (HsInteger (5) GHC.Integer.Type.Integer)))) a)))))))] (EmptyLocalBinds))))] a -> a) (WpHole) {!NameSet placeholder here!} (Nothing)))]}))]} ===================END OF MODULE: B=================
fodder008/VisualizingHaskellAST
testing/sampleShowData.hs
mit
8,190
336
53
4,536
2,610
1,503
1,107
-1
-1
-- -- -- (C) 2011-16 Nicola Bonelli <nicola@pfq.io> -- -- 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. -- -- The full GNU General Public License is included in this distribution in -- the file called "COPYING". module Daemon where import Control.Concurrent import Control.Monad import Data.List import Data.List.Split import System.Log.Logger import System.Directory import System.FilePath import System.IO import System.Process import System.Posix.Process import System.Exit import Foreign.ForeignPtr import Foreign.Ptr import Network.PFQ as Q import Options import Config import PFQDaemon foreverDaemon :: Options -> IO () -> IO () foreverDaemon opts closefds = forever $ do (src, dst) <- getConfigFiles opts new <- newerFile src dst when new $ rebuildRestart opts closefds threadDelay 1000000 rebuildRestart :: Options -> IO () -> IO () rebuildRestart opts closefds = do infoM "daemon" "Configuration updated. Rebuilding..." (src, dst) <- getConfigFiles opts copyFile src dst userDir <- getAppUserDataDirectory "pfqd" let newDaemon = userDir </> "pfqd" runCompiler >>= \(ec,_,msg) -> if ec == ExitSuccess then do infoM "daemon" ("Done. Restarting " ++ newDaemon ++ "...") closefds executeFile newDaemon False ["-c" , src, "-d"] Nothing else mapM_ (errorM "daemon") (lines $ replace "PFQDaemon.hs" (config_file opts) msg) getConfigFiles :: Options -> IO (FilePath, FilePath) getConfigFiles opts = getAppUserDataDirectory "pfqd" >>= \udata -> let src = config_file opts dst = udata </> "PFQDaemon.hs" in return (src, dst) newerFile :: FilePath -> FilePath -> IO Bool newerFile a b = do at <- getModificationTime a be <- doesFileExist b if not be then return True else do bt <- getModificationTime b return ( at > bt ) replace :: Eq a => [a] -> [a] -> [a] -> [a] replace old new = intercalate new . splitOn old runCompiler :: IO (ExitCode, String, String) runCompiler = readProcessWithExitCode "ghc" ["--make", "Main", "-o", "pfqd", "-lpfq", "-XOverloadedStrings"] ""
pfq/PFQ
user/pfqd/src/Daemon.hs
gpl-2.0
2,819
0
15
596
648
342
306
53
2
{- | Module : ./OWL2/XMLKeywords.hs Copyright : (c) Felix Gabriel Mance License : GPLv2 or higher, see LICENSE.txt Maintainer : f.mance@jacobs-university.de Stability : provisional Portability : portable Kewyords used for XML conversions -} module OWL2.XMLKeywords where ontologyIRIK :: String ontologyIRIK = "ontologyIRI" iriK :: String iriK = "IRI" abbreviatedIRI :: String abbreviatedIRI = "AbbreviatedIRI" nodeID :: String nodeID = "nodeID" prefixK :: String prefixK = "Prefix" importK :: String importK = "Import" classK :: String classK = "Class" datatypeK :: String datatypeK = "Datatype" namedIndividualK :: String namedIndividualK = "NamedIndividual" objectPropertyK :: String objectPropertyK = "ObjectProperty" dataPropertyK :: String dataPropertyK = "DataProperty" annotationPropertyK :: String annotationPropertyK = "AnnotationProperty" anonymousIndividualK :: String anonymousIndividualK = "AnonymousIndividual" facetRestrictionK :: String facetRestrictionK = "FacetRestriction" literalK :: String literalK = "Literal" declarationK :: String declarationK = "Declaration" annotationK :: String annotationK = "Annotation" objectInverseOfK :: String objectInverseOfK = "ObjectInverseOf" datatypeRestrictionK :: String datatypeRestrictionK = "DatatypeRestriction" dataComplementOfK :: String dataComplementOfK = "DataComplementOf" dataOneOfK :: String dataOneOfK = "DataOneOf" dataIntersectionOfK :: String dataIntersectionOfK = "DataIntersectionOf" dataUnionOfK :: String dataUnionOfK = "DataUnionOf" objectIntersectionOfK :: String objectIntersectionOfK = "ObjectIntersectionOf" objectUnionOfK :: String objectUnionOfK = "ObjectUnionOf" objectComplementOfK :: String objectComplementOfK = "ObjectComplementOf" objectOneOfK :: String objectOneOfK = "ObjectOneOf" objectSomeValuesFromK :: String objectSomeValuesFromK = "ObjectSomeValuesFrom" objectAllValuesFromK :: String objectAllValuesFromK = "ObjectAllValuesFrom" objectHasValueK :: String objectHasValueK = "ObjectHasValue" objectHasSelfK :: String objectHasSelfK = "ObjectHasSelf" objectMinCardinalityK :: String objectMinCardinalityK = "ObjectMinCardinality" objectMaxCardinalityK :: String objectMaxCardinalityK = "ObjectMaxCardinality" objectExactCardinalityK :: String objectExactCardinalityK = "ObjectExactCardinality" dataSomeValuesFromK :: String dataSomeValuesFromK = "DataSomeValuesFrom" dataAllValuesFromK :: String dataAllValuesFromK = "DataAllValuesFrom" dataHasValueK :: String dataHasValueK = "DataHasValue" dataMinCardinalityK :: String dataMinCardinalityK = "DataMinCardinality" dataMaxCardinalityK :: String dataMaxCardinalityK = "DataMaxCardinality" dataExactCardinalityK :: String dataExactCardinalityK = "DataExactCardinality" subClassOfK :: String subClassOfK = "SubClassOf" equivalentClassesK :: String equivalentClassesK = "EquivalentClasses" disjointClassesK :: String disjointClassesK = "DisjointClasses" disjointUnionK :: String disjointUnionK = "DisjointUnion" datatypeDefinitionK :: String datatypeDefinitionK = "DatatypeDefinition" hasKeyK :: String hasKeyK = "HasKey" subObjectPropertyOfK :: String subObjectPropertyOfK = "SubObjectPropertyOf" objectPropertyChainK :: String objectPropertyChainK = "ObjectPropertyChain" equivalentObjectPropertiesK :: String equivalentObjectPropertiesK = "EquivalentObjectProperties" disjointObjectPropertiesK :: String disjointObjectPropertiesK = "DisjointObjectProperties" objectPropertyDomainK :: String objectPropertyDomainK = "ObjectPropertyDomain" objectPropertyRangeK :: String objectPropertyRangeK = "ObjectPropertyRange" inverseObjectPropertiesK :: String inverseObjectPropertiesK = "InverseObjectProperties" functionalObjectPropertyK :: String functionalObjectPropertyK = "FunctionalObjectProperty" inverseFunctionalObjectPropertyK :: String inverseFunctionalObjectPropertyK = "InverseFunctionalObjectProperty" reflexiveObjectPropertyK :: String reflexiveObjectPropertyK = "ReflexiveObjectProperty" irreflexiveObjectPropertyK :: String irreflexiveObjectPropertyK = "IrreflexiveObjectProperty" symmetricObjectPropertyK :: String symmetricObjectPropertyK = "SymmetricObjectProperty" asymmetricObjectPropertyK :: String asymmetricObjectPropertyK = "AsymmetricObjectProperty" antisymmetricObjectPropertyK :: String antisymmetricObjectPropertyK = "AntisymmetricObjectProperty" transitiveObjectPropertyK :: String transitiveObjectPropertyK = "TransitiveObjectProperty" subDataPropertyOfK :: String subDataPropertyOfK = "SubDataPropertyOf" equivalentDataPropertiesK :: String equivalentDataPropertiesK = "EquivalentDataProperties" disjointDataPropertiesK :: String disjointDataPropertiesK = "DisjointDataProperties" dataPropertyDomainK :: String dataPropertyDomainK = "DataPropertyDomain" dataPropertyRangeK :: String dataPropertyRangeK = "DataPropertyRange" functionalDataPropertyK :: String functionalDataPropertyK = "FunctionalDataProperty" dataPropertyAssertionK :: String dataPropertyAssertionK = "DataPropertyAssertion" negativeDataPropertyAssertionK :: String negativeDataPropertyAssertionK = "NegativeDataPropertyAssertion" objectPropertyAssertionK :: String objectPropertyAssertionK = "ObjectPropertyAssertion" negativeObjectPropertyAssertionK :: String negativeObjectPropertyAssertionK = "NegativeObjectPropertyAssertion" sameIndividualK :: String sameIndividualK = "SameIndividual" differentIndividualsK :: String differentIndividualsK = "DifferentIndividuals" classAssertionK :: String classAssertionK = "ClassAssertion" annotationAssertionK :: String annotationAssertionK = "AnnotationAssertion" subAnnotationPropertyOfK :: String subAnnotationPropertyOfK = "SubAnnotationPropertyOf" annotationPropertyDomainK :: String annotationPropertyDomainK = "AnnotationPropertyDomain" annotationPropertyRangeK :: String annotationPropertyRangeK = "AnnotationPropertyRange" dlSafeRuleK :: String dlSafeRuleK = "DLSafeRule" dgRuleK :: String dgRuleK = "DGRule" dgAxiomK :: String dgAxiomK = "DGAxiom" classAtomK :: String classAtomK = "ClassAtom" dataRangeAtomK :: String dataRangeAtomK = "DataRangeAtom" objectPropertyAtomK :: String objectPropertyAtomK = "ObjectPropertyAtom" dataPropertyAtomK :: String dataPropertyAtomK = "DataPropertyAtom" builtInAtomK :: String builtInAtomK = "BuiltInAtom" sameIndividualAtomK :: String sameIndividualAtomK = "SameIndividualAtom" differentIndividualsAtomK :: String differentIndividualsAtomK = "DifferentIndividualsAtom" unknownUnaryAtomK :: String unknownUnaryAtomK = "UnknownUnaryAtom" unknownBinaryAtomK :: String unknownBinaryAtomK = "UnknownBianryAtom" dgClassAtomK :: String dgClassAtomK = "DGClassAtom" dgObjectPropertyAtomK :: String dgObjectPropertyAtomK = "DGObjectPropertyAtom" dgNodesK :: String dgNodesK = "DGNodes" dgNodeAssertionK :: String dgNodeAssertionK = "DGNodeAssertion" dgEdgesK :: String dgEdgesK = "DGEdges" dgEdgeAssertionK :: String dgEdgeAssertionK = "DGEdgeAssertion" individualArgumentK :: String individualArgumentK = "IndividualArgument" individualVariableK :: String individualVariableK = "IndividualVariable" dataVariableK :: String dataVariableK = "DataVariable" variableK :: String variableK = "Variable" entityList :: [String] entityList = [classK, datatypeK, namedIndividualK, objectPropertyK, dataPropertyK, annotationPropertyK] annotationValueList :: [String] annotationValueList = [literalK, iriK, abbreviatedIRI, anonymousIndividualK] annotationSubjectList :: [String] annotationSubjectList = [iriK, abbreviatedIRI, anonymousIndividualK] individualList :: [String] individualList = [namedIndividualK, anonymousIndividualK] objectPropList :: [String] objectPropList = [objectPropertyK, objectInverseOfK] dataPropList :: [String] dataPropList = [dataPropertyK] dataRangeList :: [String] dataRangeList = [datatypeK, datatypeRestrictionK, dataComplementOfK, dataOneOfK, dataIntersectionOfK, dataUnionOfK] classExpressionList :: [String] classExpressionList = [classK, objectIntersectionOfK, objectUnionOfK, objectComplementOfK, objectOneOfK, objectSomeValuesFromK, objectAllValuesFromK, objectHasValueK, objectHasSelfK, objectMinCardinalityK, objectMaxCardinalityK, objectExactCardinalityK, dataSomeValuesFromK, dataAllValuesFromK, dataHasValueK, dataMinCardinalityK, dataMaxCardinalityK, dataExactCardinalityK]
spechub/Hets
OWL2/XMLKeywords.hs
gpl-2.0
8,390
0
5
885
1,237
753
484
224
1
module Probability.BivariateDistributions.Terms where import Notes makeDefs [ "stochastic tuple" , "stochastic vector" , "bivariate distribution function" ]
NorfairKing/the-notes
src/Probability/BivariateDistributions/Terms.hs
gpl-2.0
187
0
6
47
25
15
10
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-| module : WebParsing.PrerequisiteParsing Description : converts a T.Text representation of prerequisites into prereq format Stability : experimental Currently parses prerequisites for Arts & Science only. Attempts to preserve only the most basic internal logic of the prerequisite representation found on course calendar: each element is either: 1) a 1-element list containig a course name 2) an n-element list containing a list of course names. -} module WebParsing.PrerequisiteParsing (parsePrerequisites) where import Text.Regex.Posix ((=~)) import qualified Data.Text as T {- Signatures: -} -- | attempts to match characters used to delimit prerequisite expressions -- returns (before, delim, after). or (input, "","") if no match occurs matchDelim :: String -> (String, String, String) matchDelim prereqs = let pat = "[;,]" :: String in prereqs =~ pat -- | returns true if the string begins inside a parenthesized expression. -- e.g isntDelim "CSC458)" == True -- isntDelim "(STA247, STA248)" == False isntDelim :: String -> Bool isntDelim rest = let pat = "^.*\\)" :: String in rest =~ pat -- |Splits a PrereqString by delimeters ';'' ','. toPreExprs :: String -> String -> [String] toPreExprs str expr = let (beforeStr, delimStr, afterStr) = matchDelim str in case (beforeStr, delimStr, afterStr) of ("","","") -> [] --if (expr == "") then [] else [expr] (before, "", "") -> [before++expr] (before, ",", after) -> if (isntDelim after) then toPreExprs after (expr ++ before) else (expr++before):(toPreExprs after "") (before, ";", after) -> (expr++before):(toPreExprs after "") -- | attempts to match a course in given string. returns (before, course, after) -- if no match occurs (input, "", "") matchCourse :: String -> (String, String, String) matchCourse prereqs = let pat = "[A-Z]{3}[0-9]{3}[HY][0-9]" :: String in prereqs =~ pat -- | converts a string representing a prerequisite expression into a prerequisite -- expression. Extracts all course names found within the string, and returns them -- in a string. toPrereq :: String -> T.Text toPrereq expr = let (beforeExpr, courseExpr, afterExpr) = matchCourse expr in case (beforeExpr, courseExpr, afterExpr) of (_, "", "") -> "" --guaranteed match (_, course, "") -> T.pack course (_, course, after) -> T.concat [(T.pack course), " ", (toPrereq after)] -- | converts a text representation of Course prerequisites into type of prereqs field -- in course record. parsePrerequisites :: Maybe T.Text -> Maybe T.Text parsePrerequisites Nothing = Nothing parsePrerequisites (Just prereqStr) = Just $ T.strip $ T.intercalate "," (map toPrereq (toPreExprs (T.unpack prereqStr) ""))
arkon/courseography
hs/WebParsing/PrerequisiteParsing.hs
gpl-3.0
2,957
0
14
686
585
329
256
38
5
module Model ( SIRState (..) , SIRMsg (..) , SIRAgentState (..) , SIREnvironment , SIRAgentDef , SIRAgentBehaviour , SIRAgentIn , SIRAgentOut , SIRAgentObservable , SIRAgentPureReadEnvBehaviour , SIRAgentMonadicReadEnvBehaviour , contactRate , illnessDuration , infectionProbability ) where import FRP.Yampa ------------------------------------------------------------------------------------------------------------------------ -- DOMAIN-SPECIFIC AGENT-DEFINITIONS ------------------------------------------------------------------------------------------------------------------------ data SIRState = Susceptible | Infected | Recovered deriving (Eq, Show) data SIRMsg = Contact SIRState deriving (Eq, Show) data SIRAgentState = SIRAgentState { sirState :: SIRState , sirStateTime :: Double } deriving (Show) type SIREnvironment = [AgentId] type SIRAgentDef = AgentDef SIRAgentState SIRMsg SIREnvironment type SIRAgentBehaviour = AgentBehaviour SIRAgentState SIRMsg SIREnvironment type SIRAgentIn = AgentIn SIRAgentState SIRMsg SIREnvironment type SIRAgentOut = AgentOut SIRAgentState SIRMsg SIREnvironment type SIRAgentObservable = AgentObservable SIRAgentState type SIRAgentPureReadEnvBehaviour = AgentPureBehaviourReadEnv SIRAgentState SIRMsg SIREnvironment type SIRAgentMonadicReadEnvBehaviour = AgentMonadicBehaviourReadEnv SIRAgentState SIRMsg SIREnvironment ------------------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------------------ -- MODEL-PARAMETERS contactRate :: Double contactRate = 5 illnessDuration :: Double illnessDuration = 15.0 infectionProbability :: Double infectionProbability = 0.05 ------------------------------------------------------------------------------------------------------------------------
thalerjonathan/phd
coding/libraries/chimera/examples/ABS/SIRExamples/SIR/Model.hs
gpl-3.0
1,995
0
8
250
270
164
106
37
1
module Properties where import Prelude (Bool(..),error,toEnum,fromEnum,pred,succ,sqrt,round ,Enum,Eq,Ord,Show,return,(.),undefined) import HipSpec import Definitions prop_01 n xs = (take n xs ++ drop n xs =:= xs) prop_02 n xs ys = (count n xs + count n ys =:= count n (xs ++ ys)) prop_03 n xs ys = proveBool (count n xs <= count n (xs ++ ys)) prop_04 n xs = (S (count n xs) =:= count n (n : xs)) prop_05 n x xs = n =:= x ==> S (count n xs) =:= count n (x : xs) prop_06 n m = (n - (n + m) =:= Z) prop_07 n m = ((n + m) - n =:= m) prop_08 k m n = ((k + m) - (k + n) =:= m - n) prop_09 i j k = ((i - j) - k =:= i - (j + k)) prop_10 m = (m - m =:= Z) prop_11 xs = (drop Z xs =:= xs) prop_12 n f xs = (drop n (map f xs) =:= map f (drop n xs)) prop_13 n x xs = (drop (S n) (x : xs) =:= drop n xs) prop_14 p xs ys = (filter p (xs ++ ys) =:= (filter p xs) ++ (filter p ys)) prop_15 x xs = (len (ins x xs) =:= S (len xs)) prop_16 x xs = xs =:= [] ==> last (x:xs) =:= x prop_17 n = (n <= Z =:= n == Z) prop_18 i m = proveBool (i < S (i + m)) prop_19 n xs = (len (drop n xs) =:= len xs - n) prop_20 xs = (len (sort xs) =:= len xs) prop_21 n m = proveBool (n <= (n + m)) prop_22 a b c = (max (max a b) c =:= max a (max b c)) prop_23 a b = (max a b =:= max b a) prop_24 a b = ((max a b) == a =:= b <= a) prop_25 a b = ((max a b) == b =:= a <= b) prop_26 x xs ys = givenBool (x `elem` xs) ( proveBool (x `elem` (xs ++ ys)) ) prop_27 x xs ys = givenBool (x `elem` ys) ( proveBool (x `elem` (xs ++ ys)) ) prop_28 x xs = proveBool (x `elem` (xs ++ [x])) prop_29 x xs = proveBool (x `elem` ins1 x xs) prop_30 x xs = proveBool (x `elem` ins x xs) prop_31 a b c = (min (min a b) c =:= min a (min b c)) prop_32 a b = (min a b =:= min b a) prop_33 a b = (min a b == a =:= a <= b) prop_34 a b = (min a b == b =:= b <= a) prop_35 xs = (dropWhile (\_ -> False) xs =:= xs) prop_36 xs = (takeWhile (\_ -> True) xs =:= xs) prop_37 x xs = proveBool (not (x `elem` delete x xs)) prop_38 n xs = (count n (xs ++ [n]) =:= S (count n xs)) prop_39 n x xs = (count n [x] + count n xs =:= count n (x:xs)) prop_40 xs = (take Z xs =:= []) prop_41 n f xs = (take n (map f xs) =:= map f (take n xs)) prop_42 n x xs = (take (S n) (x:xs) =:= x : (take n xs)) prop_43 p xs = (takeWhile p xs ++ dropWhile p xs =:= xs) prop_44 x xs ys = (zip (x:xs) ys =:= zipConcat x xs ys) prop_45 x y xs ys = (zip (x:xs) (y:ys) =:= (x, y) : zip xs ys) prop_46 xs = (zip [] xs =:= []) prop_47 a = (height (mirror a) =:= height a) prop_48 xs = givenBool (not (null xs)) ( (butlast xs ++ [last xs] =:= xs) ) prop_49 xs ys = (butlast (xs ++ ys) =:= butlastConcat xs ys) prop_50 xs = (butlast xs =:= take (len xs - S Z) xs) prop_51 xs x = (butlast (xs ++ [x]) =:= xs) prop_52 n xs = (count n xs =:= count n (rev xs)) prop_53 n xs = (count n xs =:= count n (sort xs)) prop_54 n m = ((m + n) - n =:= m) prop_55 n xs ys = (drop n (xs ++ ys) =:= drop n xs ++ drop (n - len xs) ys) prop_56 n m xs = (drop n (drop m xs) =:= drop (n + m) xs) prop_57 n m xs = (drop n (take m xs) =:= take (m - n) (drop n xs)) prop_58 n xs ys = (drop n (zip xs ys) =:= zip (drop n xs) (drop n ys)) prop_59 xs ys = ys =:= [] ==> last (xs ++ ys) =:= last xs prop_60 xs ys = givenBool (not (null ys)) ( (last (xs ++ ys) =:= last ys) ) prop_61 xs ys = (last (xs ++ ys) =:= lastOfTwo xs ys) prop_62 xs x = givenBool (not (null xs)) ( (last (x:xs) =:= last xs) ) prop_63 n xs = givenBool (n < len xs) ( (last (drop n xs) =:= last xs) ) prop_64 x xs = (last (xs ++ [x]) =:= x) prop_65 i m = proveBool (i < S (m + i)) prop_66 p xs = proveBool (len (filter p xs) <= len xs) prop_67 xs = (len (butlast xs) =:= len xs - S Z) prop_68 n xs = proveBool (len (delete n xs) <= len xs) prop_69 n m = proveBool (n <= (m + n)) prop_70 m n = givenBool (m <= n) ( proveBool (m <= S n) ) prop_71 x y xs = given (x == y =:= False) ( (elem x (ins y xs) =:= elem x xs) ) prop_72 i xs = (rev (drop i xs) =:= take (len xs - i) (rev xs)) prop_73 p xs = (rev (filter p xs) =:= filter p (rev xs)) prop_74 i xs = (rev (take i xs) =:= drop (len xs - i) (rev xs)) prop_75 n m xs = (count n xs + count n [m] =:= count n (m : xs)) prop_76 n m xs = given (n == m =:= False) ( (count n (xs ++ [m]) =:= count n xs) ) prop_77 x xs = givenBool (sorted xs) ( proveBool (sorted (insort x xs)) ) prop_78 xs = proveBool (sorted (sort xs)) prop_79 m n k = ((S m - n) - S k =:= (m - n) - k) prop_80 n xs ys = (take n (xs ++ ys) =:= take n xs ++ take (n - len xs) ys) prop_81 n m xs {- ys -} = (take n (drop m xs) =:= drop m (take (n + m) xs)) prop_82 n xs ys = (take n (zip xs ys) =:= zip (take n xs) (take n ys)) prop_83 xs ys zs = (zip (xs ++ ys) zs =:= zip xs (take (len xs) zs) ++ zip ys (drop (len xs) zs)) prop_84 xs ys zs = (zip xs (ys ++ zs) =:= zip (take (len ys) xs) ys ++ zip (drop (len ys) xs) zs) prop_85 xs ys = (len xs =:= len ys) ==> (zip (rev xs) (rev ys) =:= rev (zip xs ys)) prop_01 :: Nat -> [a] -> Prop [a] prop_02 :: Nat -> [Nat] -> [Nat] -> Prop Nat prop_03 :: Nat -> [Nat] -> [Nat] -> Prop Bool prop_04 :: Nat -> [Nat] -> Prop Nat prop_06 :: Nat -> Nat -> Prop Nat prop_07 :: Nat -> Nat -> Prop Nat prop_08 :: Nat -> Nat -> Nat -> Prop Nat prop_09 :: Nat -> Nat -> Nat -> Prop Nat prop_10 :: Nat -> Prop Nat prop_11 :: [a] -> Prop [a] prop_12 :: Nat -> (a1 -> a) -> [a1] -> Prop [a] prop_13 :: Nat -> a -> [a] -> Prop [a] prop_14 :: (a -> Bool) -> [a] -> [a] -> Prop [a] prop_15 :: Nat -> [Nat] -> Prop Nat prop_17 :: Nat -> Prop Bool prop_18 :: Nat -> Nat -> Prop Bool prop_19 :: Nat -> [a] -> Prop Nat prop_20 :: [Nat] -> Prop Nat prop_21 :: Nat -> Nat -> Prop Bool prop_22 :: Nat -> Nat -> Nat -> Prop Nat prop_23 :: Nat -> Nat -> Prop Nat prop_24 :: Nat -> Nat -> Prop Bool prop_25 :: Nat -> Nat -> Prop Bool prop_28 :: Nat -> [Nat] -> Prop Bool prop_29 :: Nat -> [Nat] -> Prop Bool prop_30 :: Nat -> [Nat] -> Prop Bool prop_31 :: Nat -> Nat -> Nat -> Prop Nat prop_32 :: Nat -> Nat -> Prop Nat prop_33 :: Nat -> Nat -> Prop Bool prop_34 :: Nat -> Nat -> Prop Bool prop_35 :: [a] -> Prop [a] prop_36 :: [a] -> Prop [a] prop_37 :: Nat -> [Nat] -> Prop Bool prop_38 :: Nat -> [Nat] -> Prop Nat prop_39 :: Nat -> Nat -> [Nat] -> Prop Nat prop_40 :: [a] -> Prop [a] prop_41 :: Nat -> (a1 -> a) -> [a1] -> Prop [a] prop_42 :: Nat -> a -> [a] -> Prop [a] prop_43 :: (a -> Bool) -> [a] -> Prop [a] prop_44 :: a -> [a] -> [b] -> Prop [(a, b)] prop_45 :: a -> b -> [a] -> [b] -> Prop [(a, b)] prop_46 :: [b] -> Prop [(a, b)] prop_47 :: Tree a -> Prop Nat prop_49 :: [a] -> [a] -> Prop [a] prop_50 :: [a] -> Prop [a] prop_51 :: [a] -> a -> Prop [a] prop_52 :: Nat -> [Nat] -> Prop Nat prop_53 :: Nat -> [Nat] -> Prop Nat prop_54 :: Nat -> Nat -> Prop Nat prop_55 :: Nat -> [a] -> [a] -> Prop [a] prop_56 :: Nat -> Nat -> [a] -> Prop [a] prop_57 :: Nat -> Nat -> [a] -> Prop [a] prop_58 :: Nat -> [a] -> [b] -> Prop [(a, b)] prop_64 :: Nat -> [Nat] -> Prop Nat prop_65 :: Nat -> Nat -> Prop Bool prop_66 :: (a -> Bool) -> [a] -> Prop Bool prop_67 :: [a] -> Prop Nat prop_68 :: Nat -> [Nat] -> Prop Bool prop_69 :: Nat -> Nat -> Prop Bool prop_72 :: Nat -> [a] -> Prop [a] prop_73 :: (a -> Bool) -> [a] -> Prop [a] prop_74 :: Nat -> [a] -> Prop [a] prop_75 :: Nat -> Nat -> [Nat] -> Prop Nat prop_78 :: [Nat] -> Prop Bool prop_79 :: Nat -> Nat -> Nat -> Prop Nat prop_80 :: Nat -> [a] -> [a] -> Prop [a] prop_81 :: Nat -> Nat -> [a] -> Prop [a] prop_82 :: Nat -> [a] -> [b] -> Prop [(a, b)] prop_83 :: [a] -> [a] -> [b] -> Prop [(a, b)] prop_84 :: [a] -> [a1] -> [a1] -> Prop [(a, a1)] prop_85 :: [a] -> [b] -> Prop [(a, b)]
danr/hipspec
testsuite/zeno/Properties.hs
gpl-3.0
7,823
0
12
2,142
4,957
2,556
2,401
-1
-1
{-# LANGUAGE GeneralizedNewtypeDeriving, MultiParamTypeClasses, FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances, PackageImports, RankNTypes, CPP, OverloadedStrings #-} {-# LANGUAGE ViewPatterns, TemplateHaskell #-} module Database.Persist.Riak ( withRiakConn , runRiakConn , R.Connection , ConnectionPool , HostName , toBS , fromBS , module Database.Persist , RiakReader ) where import Database.Persist import Database.Persist.Base import Database.Persist.TH import Control.Monad.Trans.Reader import Control.Monad.IO.Class (MonadIO (..)) import Control.Monad.Trans.Class (MonadTrans (..)) import Control.Monad.CatchIO import Control.Applicative import Control.Monad.Trans.Reader import Network.Socket (HostName) import qualified Data.ByteString.Lazy.UTF8 as B import "aeson-native" Data.Aeson -- import "aeson-native" Data.Aeson.TH import Data.Time (Day, TimeOfDay, UTCTime) import qualified Data.Map as M import qualified Data.Text as T -- Riak database library import qualified Network.Riak as R import qualified Network.Riak.Connection as R import qualified Network.Riak.Connection.Pool as R import qualified Network.Riak.Request as Req data Tnh = Tnb Int | Tnc String -- | Instance declarations for converting PersistValue to JSON -- $(deriveJSON (drop 1) Tnh) -- does not compile for me ;-) -- | Connection pool for riak connections taken from riak library. type ConnectionPool = R.Pool -- | Converting to ByteString toBS :: (Show a) => a -> B.ByteString toBS = B.fromString . show fromBS :: (Read a) => B.ByteString -> a fromBS = read . B.toString --withRiakConn :: (Trans.MonadIO m, Applicative m) -- => String -- -> String -- -> Int -- -> (Pool.Pool -> m b) -- -> m b withRiakConn :: HostName -> String -> Int -> (R.Connection -> IO b) -> IO b withRiakConn host port poolSize cr = do cID <- R.makeClientID let cl = R.Client {R.host=host, R.port=port, R.clientID=cID} pool <- liftIO $ R.create cl poolSize 50 1 R.withConnection pool cr newtype RiakReader m a = RiakReader (ReaderT R.Connection m a) deriving (Monad, MonadIO, MonadTrans, MonadCatchIO, Functor, Applicative) runRiakConn :: RiakReader IO a -> R.Pool -> IO a runRiakConn (RiakReader r) pool = R.withConnection pool $ runReaderT r -- Data.ByteString.Lazy.Char8 as L -- pack! -- cID <- makeClientID -- cl <- Client {host="", port="", clientID=} -- c <- connect cl instance MonadIO m => PersistBackend RiakReader m where insert val = undefined replace i' val = undefined get eid' = undefined -- let def = entityName $ entityDef $ dummyFromKey eid' -- let eid = show $ eid' -- let q = Req.get (B.fromString def) (B.fromString eid) R.All -- d <- R.exchange q -- return d getBy uniq = undefined selectFirst filts ords = undefined selectKeys filts = undefined selectEnum filts opts = undefined update k upds = undefined updateWhere filts upds = undefined delete k = undefined deleteBy uniq = undefined deleteWhere filts = undefined count filts = undefined dummyFromKey _ = error "dummyFromKey" persisttext, persistbytestring :: T.Text persisttext = "PersistText" persistbytestring = "PersistByteString" instance ToJSON PersistValue where toJSON (PersistText t) = object [ "PersistText" .= toJSON t] toJSON (PersistByteString bs) = object ["PersistByteString" .= toJSON bs] toJSON (PersistInt64 n) = object ["PersistInt64" .= toJSON n] toJSON (PersistDouble n) = object ["PersistDouble" .= toJSON n] toJSON (PersistBool b) = object ["PersistBool" .= toJSON b] toJSON (PersistDay d) = object ["PersistDay" .= (toJSON $ show d)] toJSON (PersistTimeOfDay t) = object ["PersistTimeOfDay" .= (toJSON $ show t)] toJSON (PersistUTCTime t) = object ["PersistUTCTime" .= toJSON t] toJSON (PersistNull) = object ["PersistNull" .= toJSON ([]::[()])] toJSON (PersistList l) = object ["PersistList" .= toJSON l] toJSON (PersistMap m) = object ["PersistMap" .= toJSON m] toJSON (PersistObjectId n) = object ["PersistObjectId" .= toJSON n] instance FromJSON PersistValue where parseJSON (Object (M.toList -> [(key, value)])) | key == "PersistText" = PersistText <$> parseJSON value | key == "PersistByteString" = PersistByteString <$> parseJSON value | key == "PersistInt64" = PersistInt64 <$> parseJSON value | key == "PersistDouble" = PersistDouble <$> parseJSON value | key == "PersistBool" = PersistBool <$> parseJSON value | key == "PersistDay" = read <$> parseJSON value | key == "PersistTimeOfDay" = read <$> parseJSON value | key == "PersistUTCTime" = read <$> parseJSON value | key == "PersistNull" = pure PersistNull | key == "PersistList" = PersistList <$> parseJSON value | key == "PersistMap" = PersistMap <$> parseJSON value | key == "PersistObjectId" = PersistObjectId <$> parseJSON value -- data PersistValue = PersistText T.Text -- | PersistByteString ByteString -- | PersistInt64 Int64 -- | PersistDouble Double -- | PersistBool Bool -- | PersistDay Day -- | PersistTimeOfDay TimeOfDay -- | PersistUTCTime UTCTime -- | PersistNull -- | PersistList [PersistValue] -- | PersistMap [(T.Text, PersistValue)] -- | PersistObjectId ByteString -- ^ intended especially for MongoDB backend -- deriving (Show, Read, Eq, Typeable, Ord)
shoehn/persistent-riak
Database/Persist/Riak.hs
gpl-3.0
5,882
23
12
1,516
1,340
729
611
100
1
module HipSpec.Lang.CoreLint where import Bag import CoreLint import CoreSyn import HipSpec.GHC.Utils import System.IO coreLint :: [CoreBind] -> IO () coreLint bs = do let (msgs1,msgs2) = lintCoreBindings bs mapM_ (mapBagM_ (hPutStrLn stderr . portableShowSDoc)) [msgs1,msgs2]
danr/hipspec
src/HipSpec/Lang/CoreLint.hs
gpl-3.0
291
0
12
49
101
55
46
10
1
import System.Random import System.Exit import System.Environment import Data.List import Data.Maybe import Data.Foldable (toList) import qualified Data.Sequence as Seq data Tile = Small Color | Dbl Color | NewRow deriving (Show,Eq) type TileWidth = Int type Color = Int -- TODO data type ?? -- ctor newTile :: (TileWidth,Color) -> Tile newTile (0,c) = Small c newTile (_,c) = Dbl c -- lovley infinite streams newTiles :: [TileWidth] -> [Color] -> [Tile] newTiles ws cs = map (newTile) $ zip ws cs -- TODO Maybe tileCells :: Tile -> TileWidth tileCells (Small _) = 1 tileCells (Dbl _) = 2 tileCells (NewRow) = 0 -- Nothing -- TODO Maybe tileColor :: Tile -> Color tileColor (Small c) = c tileColor (Dbl c) = c tileColor (NewRow) = -1 -- Nothing data InputArgs = InputArgs { tileColors::Int, tileSizes::Int, floorWidth::Int, floorHeight::Int, colorMode::String } deriving (Show) main = do args' <- parseArgs genA <- getStdGen genB <- newStdGen -- pull the number for the lotteri !! let widths = randInts genB $ tileSizes args' - 1 let colors = randInts genA $ tileColors args' - 1 let floorLayout = tileLayout (floorWidth args') (floorHeight args') $ newTiles widths colors let show' = if colorMode args' == "bw" then showTile else showTileC putStrLn $ concat.map show' $ floorLayout -- putStrLn "== Summary ==" -- putStrLn "color,size=t" -- putStrLn $ concat.intersperse "\n" .map showTileSum $ sumSet floorLayout -- args or death parseArgs :: IO InputArgs parseArgs = do let argsLen = 4 args <- getArgs -- IO if length args < argsLen then do usage exitWith $ ExitFailure 1 else do -- TODO errorhandling return InputArgs { tileColors = read $ args !! 0 , tileSizes = read $ args !! 1 , floorWidth = read $ args !! 2 , floorHeight = read $ args !! 3 , colorMode = "color" } -- always color .. for now -- help usage :: IO () usage = do prog <- getProgName putStrLn "Tool that generates floor w tiles from random." putStrLn "usage:" putStrLn $ nixEsc 1 ++ fgColor 3 -- HI fg, yellow putStrLn $ " " ++ prog ++ " <C> <S> <W> <H> " ++ nixEsc 0 -- restore ESC putStrLn " where \n C -> Number; Tile color variations" putStrLn " S -> Number; Span odds. Tile spans either 1 or 2 cell," putStrLn " and higher number here will give 1cell lower odds" putStrLn " W -> Number; Floor width. Number of cells before new row" putStrLn " H -> Number; Floor height, aka rows" -- should return uniq set of tiles w counted totals sumSet :: [Tile] -> [(Tile,Int)] sumSet tiles = toList $ foldl sumTiles countSet tiles where sumTiles cntSet tile = case lookup tile cntSet of Just cnt -> replaceElem tile cnt cntSet Nothing -> cntSet replaceElem t cnt cs = case idx of Just i -> toList $ Seq.update i (t,newCnt) cs' Nothing -> cs where cs' = Seq.fromList cs idx = Seq.elemIndexL (t,cnt) cs' newCnt = cnt + 1 countSet = zip (nub tiles) $ repeat 0 showTileSum :: (Tile,Int) -> String showTileSum (tile,cnt) = show (tileColor tile) ++ ", " ++ show (tileCells tile) ++ " = " ++ show cnt randInts :: StdGen -> Int -> [Int] randInts g maxInt = let (n,g') = randomR (0,maxInt) g in n : randInts g' maxInt tileLayout :: Int -> Int -> [Tile] -> [Tile] tileLayout _ _ [] = [] tileLayout w h tiles | h == 0 = [] | otherwise = currRow ++ tileLayout w (h-1) futureRows where currRow = tileRow w tiles futureRows = drop currRowLen tiles currRowLen = length currRow - 1 -- Inject the NewRow and break stream tileRow :: Int -> [Tile] -> [Tile] tileRow _ [] = [] tileRow width (x:xs) | width <= 0 = [NewRow] | otherwise = x : tileRow ( width - tileCells x) xs showTile :: Tile -> String showTile (NewRow) = "\n" showTile (Small c) = "s" ++ show c showTile (Dbl c) = "d " ++ show c -- TODO derving inside Show class showTileC :: Tile -> String showTileC t@(NewRow) = nixEsc 0 ++ showTile t showTileC t = tColor (nicerColor c) ++ showTile t where c = tileColor t -- background + HI fg tColor :: Int -> String tColor n = let bg = 40 fg = 30 in nixEsc ( bg + n ) ++ nixEsc 1 ++ nixEsc ( fg + n ) fgColor :: Int -> String fgColor c = let fg = 30 in nixEsc $ fg + c -- avoid red+black as starters nicerColor :: Int -> Int nicerColor n | n == 0 = 2 -- green | n == 1 = 3 -- yellow | n == 2 = 6 -- cyan | n == 3 = 7 -- white | n == 4 = 0 -- darkGray (black) | n == 5 = 4 -- blue | n == 6 = 5 -- magents | n == 7 = 1 -- red | otherwise = 1 -- red nixEsc :: Int ->String nixEsc n = "\ESC[" ++ show n ++ "m"
dynnamitt/tile-gen
tile-gen.hs
gpl-3.0
4,832
0
14
1,336
1,658
851
807
140
3
{-# 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.Reseller.Subscriptions.ChangeRenewalSettings -- 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) -- -- Changes the renewal settings of a subscription -- -- /See:/ <https://developers.google.com/google-apps/reseller/ Enterprise Apps Reseller API Reference> for @reseller.subscriptions.changeRenewalSettings@. module Network.Google.Resource.Reseller.Subscriptions.ChangeRenewalSettings ( -- * REST Resource SubscriptionsChangeRenewalSettingsResource -- * Creating a Request , subscriptionsChangeRenewalSettings , SubscriptionsChangeRenewalSettings -- * Request Lenses , scrsPayload , scrsCustomerId , scrsSubscriptionId ) where import Network.Google.AppsReseller.Types import Network.Google.Prelude -- | A resource alias for @reseller.subscriptions.changeRenewalSettings@ method which the -- 'SubscriptionsChangeRenewalSettings' request conforms to. type SubscriptionsChangeRenewalSettingsResource = "apps" :> "reseller" :> "v1" :> "customers" :> Capture "customerId" Text :> "subscriptions" :> Capture "subscriptionId" Text :> "changeRenewalSettings" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] RenewalSettings :> Post '[JSON] Subscription -- | Changes the renewal settings of a subscription -- -- /See:/ 'subscriptionsChangeRenewalSettings' smart constructor. data SubscriptionsChangeRenewalSettings = SubscriptionsChangeRenewalSettings' { _scrsPayload :: !RenewalSettings , _scrsCustomerId :: !Text , _scrsSubscriptionId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'SubscriptionsChangeRenewalSettings' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'scrsPayload' -- -- * 'scrsCustomerId' -- -- * 'scrsSubscriptionId' subscriptionsChangeRenewalSettings :: RenewalSettings -- ^ 'scrsPayload' -> Text -- ^ 'scrsCustomerId' -> Text -- ^ 'scrsSubscriptionId' -> SubscriptionsChangeRenewalSettings subscriptionsChangeRenewalSettings pScrsPayload_ pScrsCustomerId_ pScrsSubscriptionId_ = SubscriptionsChangeRenewalSettings' { _scrsPayload = pScrsPayload_ , _scrsCustomerId = pScrsCustomerId_ , _scrsSubscriptionId = pScrsSubscriptionId_ } -- | Multipart request metadata. scrsPayload :: Lens' SubscriptionsChangeRenewalSettings RenewalSettings scrsPayload = lens _scrsPayload (\ s a -> s{_scrsPayload = a}) -- | Id of the Customer scrsCustomerId :: Lens' SubscriptionsChangeRenewalSettings Text scrsCustomerId = lens _scrsCustomerId (\ s a -> s{_scrsCustomerId = a}) -- | Id of the subscription, which is unique for a customer scrsSubscriptionId :: Lens' SubscriptionsChangeRenewalSettings Text scrsSubscriptionId = lens _scrsSubscriptionId (\ s a -> s{_scrsSubscriptionId = a}) instance GoogleRequest SubscriptionsChangeRenewalSettings where type Rs SubscriptionsChangeRenewalSettings = Subscription type Scopes SubscriptionsChangeRenewalSettings = '["https://www.googleapis.com/auth/apps.order"] requestClient SubscriptionsChangeRenewalSettings'{..} = go _scrsCustomerId _scrsSubscriptionId (Just AltJSON) _scrsPayload appsResellerService where go = buildClient (Proxy :: Proxy SubscriptionsChangeRenewalSettingsResource) mempty
rueshyna/gogol
gogol-apps-reseller/gen/Network/Google/Resource/Reseller/Subscriptions/ChangeRenewalSettings.hs
mpl-2.0
4,366
0
17
989
469
279
190
82
1
instance MyClass Int where type MyType = String myMethod :: MyType -> Int myMethod x = x + 1 type MyType = Int
lspitzner/brittany
data/Test201.hs
agpl-3.0
119
0
6
31
44
23
21
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {- | Module : $Header$ Description : Attributes functions. Copyright : (c) plaimi 2014-2015 License : AGPL-3 Maintainer : tempuhs@plaimi.net -} module Tempuhs.Server.Requests.Attributes.Poly where import Control.Monad ( liftM, void, ) import Control.Monad.IO.Class ( liftIO, MonadIO, ) import Control.Monad.Trans.Reader ( ReaderT, ) import Control.Monad.Trans.Resource.Internal ( ResourceT, ) import Database.Esqueleto ( Value, (^.), (&&.), like, val, ) import qualified Database.Esqueleto as E import Data.Functor ( (<$>), ) import Data.Maybe ( fromMaybe, ) import Data.Monoid ( Monoid, mempty, ) import Data.String ( IsString, ) import Data.Time.Clock ( getCurrentTime, UTCTime, ) import Database.Persist ( Entity (Entity), SelectOpt (Asc), Key (Key), (=.), (==.), entityKey, getBy, delete, insert, selectList, update, ) import Database.Persist.Class ( EntityField, PersistEntity, PersistEntityBackend, PersistField, PersistQuery, Unique, ) import Database.Persist.Sql ( ConnectionPool, SqlBackend, ) import qualified Data.Text as T import qualified Data.Text.Lazy as L import Web.Scotty ( Parsable, ) import Web.Scotty.Internal.Types ( ActionT, ScottyError, ) import Web.Scotty.Trans ( params, ) import Tempuhs.Server.Database ( mkKey, runDatabase, ) import Tempuhs.Server.Param ( maybeParam, paramE, ) import Tempuhs.Server.Spock ( ActionE, ) patchAttribute :: forall g k v u r w s. (Parsable v, Parsable k, PersistEntity s, PersistEntity r ,PersistEntity g, PersistField v, IsString v ,PersistEntityBackend r ~ SqlBackend ,PersistEntityBackend g ~ SqlBackend) => L.Text -> (Key s -> k -> Unique g) -> EntityField g v -> (Key s -> k -> v -> Maybe u -> r) -> EntityField g (Maybe UTCTime) -> (g -> Maybe w) -> ConnectionPool -> ActionE () -- | 'patchAttribute' looks up the passed in ID parametre, inserts or updates -- or deletes the passed in key with the passed in value if applicable. It -- also needs the getter-field for the attribute, along with the value field -- to update and the row to insert patchAttribute i g f r rf rg p = do j <- paramE i k <- paramE "key" v <- maybeParam "value" runDatabase p $ updateAttribute (mkKey j) k v g f r rf rg updateAttribute :: forall g f k v u r w. (PersistEntity r, PersistEntity g, PersistField v ,IsString v, PersistEntityBackend r ~ SqlBackend ,PersistEntityBackend g ~ SqlBackend) => f -> k -> Maybe v -> (f -> k -> Unique g) -> EntityField g v -> (f -> k -> v -> Maybe u -> r) -> EntityField g (Maybe UTCTime) -> (g -> Maybe w) -> ReaderT SqlBackend (ResourceT ActionE) () -- | 'updateAttribute' updates the passed in attribute. It takes a @'Key' a@, -- which is the ID of the resource the attribute is related to, a key, and a -- 'Maybe' value. If the key already exists in the database, it is updated. If -- not, it is inserted. If the value is 'Nothing', the key is deleted if it -- exists. If the resource does not exist, nothing happens. updateAttribute i k v g f r rf rg = do a <- getBy $ g i k case (a, v) of (Nothing, Nothing) -> return () (Nothing, Just w) -> void $ insert (r i k w Nothing) (Just (Entity b c), Nothing) -> case rg c of Just _ -> delete b Nothing -> do now <- liftIO getCurrentTime update b [rf =. Just now] (Just (Entity b _), Just w) -> update b [f =. w] attributesParams :: ActionE [(T.Text, Maybe T.Text)] -- | 'attributeParams' gets all attributes from the '_' parametres. If a -- parametre ends with an '_', it is considered an attribute. -- "&foo_=fu&bar_=baz". Valid attributes come in a list of key—'Maybe' value -- tuples. attributesParams = liftM (map (\(k, v) -> (L.toStrict (L.init k) ,if L.null v then Nothing else Just (L.toStrict v)))) $ filter (L.isSuffixOf "_" . fst) <$> params attributeSearch :: forall e (m :: * -> *) (query :: * -> *) backend (expr :: * -> *) typ v w. (E.Esqueleto query expr backend, ScottyError e ,PersistEntity w, PersistEntity v ,PersistField typ, Monad m) => EntityField v typ -> EntityField w typ -> EntityField v T.Text -> EntityField v T.Text -> ActionT e m [expr (Entity w) -> expr (Entity v) -> expr (Value Bool)] -- | 'attributeSearch' uses the list of request parametres to construct a list -- of functions that can be used in an 'Esqueleto' query to filter out -- resources based on their attributes. It takes an attribute key field, an -- attribute value field and an associated resource ID field and ID. attributeSearch aa ai ak av = do ps <- params return $ do (p, v) <- ps let (n_, o) = T.breakOnEnd "_" $ L.toStrict p (#) <- case o of "" -> [(E.==.)] "like" -> [like] _ -> [] case T.stripSuffix "_" n_ of Just n -> [\t a -> a ^. ak E.==. val n &&. a ^. av # val (L.toStrict v) &&. a ^. aa E.==. t ^. ai] _ -> [] getAttrs :: forall v (m :: * -> *) r t. (MonadIO m, PersistEntity v, PersistField (Key r) ,PersistQuery (PersistEntityBackend v)) => Entity r -> EntityField v (Key r) -> EntityField v t -> ReaderT (PersistEntityBackend v) m [Entity v] -- | 'getAttrs' returns a list of all attributes for a given associated -- resource ID and field, and the attribute ID field. getAttrs a f i = selectList [f ==. entityKey a] [Asc i] insertAttributes :: forall ak av r (m :: * -> *) k u. (MonadIO m, PersistEntity r, Monoid av ,E.PersistStore (PersistEntityBackend r)) => (k -> ak -> av -> Maybe u -> r) -> [(ak, Maybe av)] -> k -> ReaderT (PersistEntityBackend r) m () -- | 'insertAttributes' inserts the given attributes (as) of the given type -- (t) with the given resource key (k). insertAttributes t kv f = mapM_ (\(k, v) -> insert (t f k (fromMaybe mempty v) Nothing)) kv updateAttributes :: forall g f k u r w v. (PersistEntity r, PersistEntity g ,PersistField v, IsString v ,PersistEntityBackend r ~ SqlBackend ,PersistEntityBackend g ~ SqlBackend) => f -> (f -> k -> Unique g) -> EntityField g v -> (f -> k -> v -> Maybe u -> r) -> EntityField g (Maybe UTCTime) -> (g -> Maybe w) -> [(k, Maybe v)] -> ReaderT SqlBackend (ResourceT ActionE) () -- | 'updateAttributes' updates the given attributes with the given resource -- ID. updateAttributes i g f r rf rg = mapM_ (uncurry (\k v -> updateAttribute i k v g f r rf rg))
plaimi/tempuhs-server
src/Tempuhs/Server/Requests/Attributes/Poly.hs
agpl-3.0
7,763
0
23
2,658
2,112
1,150
962
198
5
module Ex.String(mkString, strs, strs', MultiLineShow(..), ind, showOp, showOp', cap, MathTp(..), BoolTp(..), tryCon, zipWithIndex, startsWith, lines2, pstrs, pstrs', pmkString, mapFirst, mapLast, appendLast, appp, glue, glueAll, mapNotFirst, wrapStr, splitOn) where import Data.Char startsWith :: (Eq a) => [a] -> [a] -> Bool startsWith [] _ = True startsWith (a:as) (b:bs) = a == b && startsWith as bs startsWith _ _ = False zipWithIndex :: [a] -> [(a, Int)] zipWithIndex = doZip 0 where doZip :: Int -> [a] -> [(a, Int)] doZip _ [] = [] doZip i (x:xs) = (x, i) : doZip (i + 1) xs pmkString :: (a -> String) -> String -> String -> String -> [a] -> String pmkString _ _ _ _ [] = "" pmkString f p _ s [x] = p ++ f x ++ s pmkString f p d s xs = p ++ mkString f d xs ++ s mkString :: (a -> String) -> String -> [a] -> String mkString _ _ [] = "" mkString f _ [x] = f x mkString f d (x:xs) = f x ++ d ++ mkString f d xs strs :: String -> [String] -> String strs = mkString id strs' :: (Show a) => String -> [a] -> String strs' = mkString show pstrs :: String -> String -> String -> [String] -> String pstrs = pmkString id pstrs' :: (Show a) => String -> String -> String -> [a] -> String pstrs' = pmkString show break2 :: (a -> Bool) -> [a] -> ([a],Maybe [a]) break2 _ xs@[] = (xs, Nothing) break2 p xs@(x:xs') | p x = ([], Just xs) | otherwise = let (ys,zs) = break2 p xs' in (x:ys, zs) lines2 :: String -> [String] lines2 s = let (l, s') = break2 (== '\n') s ss = case s' of Nothing -> [] Just "" -> [""] Just (_:s'') -> lines2 s'' in l : ss class (Show a) => MultiLineShow a where multiLineShow :: a -> [String] showOp :: (Show a, Show b) => a -> String -> b -> String showOp l op r = show l ++ " " ++ op ++ " " ++ show r showOp' :: (Show a, Show b) => a -> String -> b -> String showOp' l op r = show l ++ op ++ show r ind :: String -> String ind = (" " ++ ) cap :: String -> String cap "" = "" cap (x:xs) = toUpper x : xs tryCon :: String -> String -> String tryCon _ "" = "" tryCon "" _ = "" tryCon a b = a ++ b wrapStr :: String -> String -> String -> String wrapStr _ _ "" = "" wrapStr p s ss = p ++ ss ++ s splitOn :: (Eq a) => a -> [a] -> [[a]] splitOn d arr = recsl [] arr where recsl [] [] = [] recsl a [] = [reverse a] recsl a (x:xs) | x == d = reverse a : recsl [] xs | otherwise = recsl (x:a) xs data MathTp = Plus | Minus | Mul | Div deriving (Eq) data BoolTp = Eq | NotEq | More | MoreEq | Less | LessEq | And | Or | ExactEq | ExactNotEq deriving (Eq) instance Show MathTp where show Plus = "+" show Minus = "-" show Mul = "*" show Div = "/" instance Show BoolTp where show Eq = "==" show ExactEq = "===" show ExactNotEq = "!==" show NotEq = "!=" show More = ">" show MoreEq = ">=" show Less = "<" show LessEq = "<=" show And = "&&" show Or = "||" mapFirst :: (a -> a) -> [a] -> [a] mapFirst _ [] = [] mapFirst f a = f (head a) : tail a mapNotFirst :: (a -> a) -> [a] -> [a] mapNotFirst _ [] = [] mapNotFirst f a = head a : map f (tail a) mapLast :: (a -> a) -> [a] -> [a] mapLast _ [] = [] mapLast f a = init a ++ [f $ last a] appendLast :: String -> [String] -> [String] appendLast s [] = [s] appendLast s r = mapLast (++ s) r appp :: [String] -> String -> [String] a `appp` b = appendLast b a glue :: [String] -> [String] -> [String] [] `glue` [] = [] [] `glue` b = b a `glue` [] = a a `glue` b = init a ++ [last a ++ head b] ++ tail b glueAll :: String -> [[String]] -> [String] glueAll _ [] = [] glueAll _ [x] = x glueAll s (a:b:xs) = glueAll s $ ((a `appp` s) `glue` b):xs
antonzherdev/objd
src/Ex/String.hs
lgpl-3.0
3,633
6
14
928
2,031
1,083
948
109
3
import System.Posix.Daemon import Control.Pipe.* import System.IO import Data.* import Text.* import qualified Data.ByteString as BS import Network.* import HTTP.* module Pusher where jsonFile :: FilePath jsonFile = "../xanon/xanon/square.json" def readJSON = do a : Yodlee | a <- p_value | encode a -> Array[B] new B :: JSONArray() -> ShowS instance Data B where deriving Show parseJSON :: Data[A, B, C, D, E, F] -> Paste parseJSON b = Map b -> String b Date :: (b -> c) -> (Map k b -> Int c) MERCHANT :: (a -> String a) -> (Map k a -> [a]) BatchRequest :: (b -> String b ) -> (Map k b -> [b]) Items :: (d -> String d) -> (Map k b -> [b]) Modifier :: (e -> String e) -> (Map k e -> [e]) BANKACCOUNTS :: (f -> String f) -> (Map k f -> [f]) --read each object to give out the ind values. listItem :: Read(JSONObject _) -> Map(a _) -> gfoldl a (JSKey _ -> Result _) -> (_ -> a) instance Data listItem where deriving Show Read(Map(Data MERCHANT BatchRequest Item Modifier BANKACCOUNTS) = do | Date -> val | MERCHANT >> gfoldl(a id business_name) -> Data[_ _] | Batchrequest >> gfoldl(a access_token requiest_id) -> Data[_ _] | Items >> gfoldl(a id category_id name) -> Data[_ _ _] where price :: showJSON k -> gfoldl(k JSONObject price_money) -> JSONValue _ b price.(gfoldl price_money) >> JSONValue amount | Modifier >> gfoldl(a modifier_list_id) -> Data[_] | BANKACCOUNTS >> gfoldl(a id merchant_id bank_name routing_number) -> Data[_ _ _] --each batched in one push bundleUser :: Data[_] -> toJSObject[A] instance Data bundleUser where userFile :: IO () -> FilePath def userfile x = do x | hFlush <- bundleUser | FilePath >> "../xanon/xanon/" --run background to gather updates updateInfo :: instance Serialize initiate --create pipeline startServer :: runSocketServer -> Handler () -> socket openPipeline :: socketReader -> Producer socket 8080 startClient :: runSocketClient -> Handler () -> listenOn Socket def startClient = if startclient.recvFrom (socketPort receiveHTTP <300 ) then accept -> IO Handler else throw print("HTTP ERROR" + DevNull) def startServer socket = do | runDetached socket -> IO () | ByteString _ <- FilePath.isRunning("../x/x") instance Serialze serialzer --gets info as ByteString readNewInfo :: socketwriter ByteString _ -> Array[L] --convert BS -> String/Array newData :: foldl -> (Map Char _ -> ByteString) -> a def newData a = Monad a >> a : Array[A] Array[A] -> foldl(Map _) => Constr _ -> String _ _ JSONObject updatedInfo -< String --take into JSON and updates userFile updateInfo :: JSObject a b -> JSValue JSKey JSString def updatedInfo _ _ = JSObject.concatMap("userFile") instance Serialize deinitialize where --close pipeline after run closePipeLine :: killAndWait -> IO _ userFile endServer :: sclose -> Handler () -> Socket 8080 def endServer = --loadbalancer is running after time 30min if startServer.isRunning time 300 updatedInfo.hflush <- closePipeLine else time 86400000 restart _ = startServer.(time)
dgomez10/xanon
Pusher.hs
apache-2.0
3,123
113
17
660
1,025
584
441
-1
-1
module Delahaye.A338012Spec (main, spec) where import Test.Hspec import Delahaye.A338012 (a338012) main :: IO () main = hspec spec spec :: Spec spec = describe "A338012" $ it "correctly computes the first 20 elements" $ take 20 (map a338012 [1..]) `shouldBe` expectedValue where expectedValue = [0, 3, 4, 10, 18, 23, 34, 55, 67, 93, 95, 120, 149, 166, 228, 271, 351, 398, 439, 505]
peterokagey/haskellOEIS
test/Delahaye/A338012Spec.hs
apache-2.0
396
0
10
78
160
95
65
10
1
{-# LANGUAGE EmptyDataDecls #-} module Data.FFI where type AgdaList a b = [b] type AgdaMaybe a b = Maybe b type AgdaEither a b c d = Either c d data AgdaEmpty data AgdaStream a = Cons a (AgdaStream a)
qwe2/try-agda
agda-stdlib-0.9/ffi/Data/FFI.hs
apache-2.0
205
0
8
44
65
42
23
-1
-1
{-# LANGUAGE DeriveFunctor #-} module Data.Predictor.Probability ( Pr(..) , binomial , collapse , (.*) , delay ) where import Control.Applicative import Control.Lens import Control.Monad import Data.Bifunctor import Data.Map as M import Numeric.Log as Log data Pr a = Pr { runPr :: [(Log Double, Either a (Pr a))] } deriving Show delay :: Pr a -> Pr a delay p = Pr [(1,Right p)] instance Functor Pr where fmap f = Pr . fmap (fmap (bimap f (fmap f))) . runPr instance Applicative Pr where pure = return (<*>) = ap instance Alternative Pr where empty = mzero (<|>) = mplus instance Monad Pr where return a = Pr [(1,Left a)] Pr as >>= f = Pr $ as >>= \(p,ea) -> case ea of Left a -> [(p*q,bs) | (q, bs) <- runPr (f a)] Right as' -> [(p, Right (as' >>= f))] instance MonadPlus Pr where mzero = Pr [] mplus (Pr xs) (Pr ys) = Pr (xs ++ ys) linear :: [(Log Double, Pr a)] -> Pr a linear xs = Prelude.foldr (\(p,va) b -> p .* va <|> b) mzero xs (.*) :: Log Double -> Pr a -> Pr a p .* Pr xs = Pr [ (p*q, a) | (q,a) <- xs ] binomial :: Log Double -> Pr Bool binomial p = Pr [(p, Left True), (1-p, Left False)] {-# INLINE binomial #-} collapse :: Ord a => Pr a -> [(Log Double,a)] collapse = fmap (first Log.sum . swap) . M.toList . go M.empty . runPr where go = Prelude.foldr $ \(p,ea) m -> case ea of Left a -> m & at a . non [] %~ cons p Right (Pr bs) -> go m bs -- * Utilities swap :: (a,b) -> (b,a) swap (a,b) = (b,a)
ekmett/predictors
src/Data/Predictor/Probability.hs
bsd-2-clause
1,503
0
16
387
808
434
374
-1
-1
{-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} module Network.Kafka.Fields where import Control.Applicative import Control.Lens import Data.Functor.Contravariant import Data.Profunctor import Network.Kafka.Primitive.Fetch import Network.Kafka.Primitive.GroupCoordinator import Network.Kafka.Primitive.Metadata import Network.Kafka.Primitive.Offset import Network.Kafka.Primitive.OffsetCommit import Network.Kafka.Primitive.OffsetFetch import Network.Kafka.Primitive.Produce makeFields ''FetchResultPartitionResults makeFields ''FetchResult makeFields ''PartitionFetch makeFields ''TopicFetch makeFields ''FetchRequestV0 makeFields ''FetchResponseV0 makeFields ''GroupCoordinatorRequestV0 makeFields ''GroupCoordinatorResponseV0 makeFields ''MetadataRequestV0 makeFields ''Broker makeFields ''PartitionMetadata makeFields ''TopicMetadata makeFields ''MetadataResponseV0 makeFields ''PartitionOffsetRequestInfo makeFields ''TopicPartition makeFields ''OffsetRequestV0 makeFields ''PartitionOffset makeFields ''PartitionOffsetResponseInfo makeFields ''OffsetResponseV0 makeFields ''CommitPartitionV0 makeFields ''CommitV0 makeFields ''OffsetCommitRequestV0 makeFields ''CommitPartitionV1 makeFields ''CommitV1 makeFields ''OffsetCommitRequestV1 makeFields ''CommitPartitionV2 makeFields ''CommitV2 makeFields ''OffsetCommitRequestV2 makeFields ''CommitPartitionResult makeFields ''CommitTopicResult makeFields ''OffsetCommitResponseV0 makeFields ''OffsetCommitResponseV1 makeFields ''OffsetCommitResponseV2 makeFields ''PartitionOffsetFetch makeFields ''TopicOffsetResponse makeFields ''TopicOffset makeFields ''OffsetFetchRequestV0 makeFields ''OffsetFetchResponseV0 makeFields ''OffsetFetchRequestV1 makeFields ''OffsetFetchResponseV1 makeFields ''PartitionMessages makeFields ''TopicPublish makeFields ''ProduceRequestV0 makeFields ''PublishPartitionResult makeFields ''PublishResult makeFields ''ProduceResponseV0
iand675/hs-kafka
src/Network/Kafka/Fields.hs
bsd-3-clause
2,116
0
6
180
451
197
254
64
0
module Main where import Criterion.Main import Data.Vector ((//)) import qualified Data.Vector as V vec :: V.Vector Int vec = V.fromList [1..10000] slow :: Int -> V.Vector Int slow n = go n vec where go 0 v = v go n v = go (n-1) (v // [(n, 0)]) batchList :: Int -> V.Vector Int batchList n = vec // updates where updates = fmap (\n -> (n, 0)) [0..n] batchVector :: Int -> V.Vector Int batchVector n = V.unsafeUpdate vec updates where updates = fmap (\n -> (n, 0)) (V.fromList [0..n]) main :: IO () main = defaultMain [ bench "slow" $ whnf slow 9998 , bench "batch list" $ whnf batchList 9998 , bench "batch vector" $ whnf batchVector 9998 ]
dmvianna/strict
src/update.hs
bsd-3-clause
670
0
11
152
319
170
149
-1
-1
-- © 2001-2005 Peter Thiemann module Main where import Data.Char import Prelude hiding (head, span, map) import WASH.CGI.CGI hiding (div) main = run mainCGI mainCGI = calc "0" id calc dstr f = standardQuery "Calculator" $ table $ do dsp <- tr (td (textInputField (fieldVALUE dstr) ## attr "colspan" "4")) let button c = td (submit dsp (calcAction c f) (fieldVALUE [c])) tr (button '1' ## button '2' ## button '3' ## button '+') tr (button '4' ## button '5' ## button '6' ## button '-') tr (button '7' ## button '8' ## button '9' ## button '*') tr (button 'C' ## button '0' ## button '=' ## button '/') calcAction c f dsp | isDigit c = calc (dstr ++ [c]) f | c == 'C' = mainCGI | c == '=' = calc (show (f (read dstr :: Integer))) id | otherwise = calc "0" (optable c (read dstr :: Integer)) where dstr = value dsp optable '+' = (+) optable '-' = (-) optable '*' = (*) optable '/' = div
nh2/WashNGo
Examples/old/Calculator.hs
bsd-3-clause
947
5
17
236
443
221
222
26
4
{-# LANGUAGE TemplateHaskell, OverloadedStrings, FlexibleContexts, CPP #-} module PEPParser where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ( (<|>), (<$>), (<*>), (*>), (<*), many, pure ) #else import Control.Applicative ( (<|>), many ) #endif import Control.Lens ( makeLenses ) import Control.Monad ( void, (>=>) ) import Data.Number.Nat ( Nat, toNat ) import qualified Data.ByteString as BIO import Data.Text ( Text, pack, unpack ) import qualified Data.Text as T import Data.Text.Read ( decimal, signed ) import Data.Text.Encoding ( decodeLatin1 ) import qualified Data.Text.IO as TIO import Text.Parsec.Prim ( parse, try, parserFail, parserReturn, skipMany ) import Text.Parsec.Text ( Parser ) import Text.Parsec.Char ( char, string, newline, digit, anyChar, noneOf ) import Text.Parsec.Combinator ( sepBy, option, many1, manyTill ) -- From: http://parsys.informatik.uni-oldenburg.de/~pep/Paper/formats_all.ps.gz data LLNetType = PTNet | PetriBox deriving (Eq, Show) data FormatType = N | N2 deriving (Eq) instance Show FormatType where show N = "FORMAT_N" show N2 = "FORMAT_N2" data Header = Header LLNetType FormatType deriving (Eq, Show) newtype Thickness = Thickness Nat deriving (Eq, Show) newtype Size = Size Nat deriving (Eq, Show) data Default = DefaultBlock [BlockDefault] | DefaultPlace [PlaceDefault] | DefaultTransition [TransitionDefault] | DefaultArc [ArcDefault] deriving (Eq, Show) data BlockDefault = BlockSize Size | BlockThickness Thickness deriving (Eq, Show) data PlaceDefault = PlaceDefaultableAttribute DefaultableExtraAttribute | PlaceSize Size | PlaceThickness Thickness deriving (Eq, Show) data TransitionDefault = TransitionDefaultableAttribute DefaultableExtraAttribute | TransitionSize Size | TransitionThickness Thickness deriving (Eq, Show) data ArcDefault = ArcDefaultableAttribute DefaultableArcAttribute | ArcThickness Thickness deriving (Eq, Show) data DefaultableArcAttribute = Weight Int | WeightRelativePos Position deriving (Eq, Show) data DefaultableExtraAttribute = NameRelativePos Position | Meaning Text deriving (Eq, Show) newtype Position = Position (Int, Int) deriving (Eq, Show) data InfinityOrNum = Infinity | Number Nat deriving (Eq, Show) data ObjectData = ObjectData { _objIDName :: Maybe (Either (Int, Text) Text) , _objectPos :: !Position } deriving (Eq, Show) $(makeLenses ''ObjectData) data CommonExtraAttribute = MeaningRelativePos Position | Reference Text | CommonDefaulted DefaultableExtraAttribute deriving (Eq, Show) data BlockAttribute = BlockCommon CommonExtraAttribute | BlockBlocks [Int] deriving (Eq, Show) data Block = Block { _bData :: ObjectData , _bAttributes :: [BlockAttribute] } deriving (Eq, Show) $(makeLenses ''Block) data PlaceAttribute = PlaceCommon CommonExtraAttribute | PlaceInitialMarking Bool | PlaceCurrentMarking Bool | PlaceCapacity InfinityOrNum | PlaceEntryPlace | PlaceExitPlace | PlaceBlocks [Int] deriving (Eq, Show) data Place = Place { _pData :: !ObjectData , _pAttributes :: [PlaceAttribute] } deriving (Eq, Show) $(makeLenses ''Place) data TransitionAttribute = TransitionCommon CommonExtraAttribute | TransitionBlocks [Int] | TransitionSynchronisationTransition | TransitionPhantomTransitions [Int] | TransitionInvisibleLevel Int deriving (Eq, Show) data Transition = Transition { _tData :: !ObjectData , _tAttributes :: [TransitionAttribute] } deriving (Eq, Show) $(makeLenses ''Transition) data PhantomTransitionAttribute = PhantomTransCommon CommonExtraAttribute | PhantomTransBlocks [Int] | PhantomTransSynchronisationTransitions [Int] deriving (Eq, Show) data PhantomTransition = PhantomTransition { _ptData :: !ObjectData , _ptAttributes :: [PhantomTransitionAttribute] } deriving (Eq, Show) $(makeLenses ''PhantomTransition) newtype PlaceID = PlaceID Int deriving (Eq, Show) newtype TransID = TransID Int deriving (Eq, Show) newtype PTransID = PTransID Int deriving (Eq, Show) data ArcType = PTArc !PlaceID !TransID | TPArc !TransID !PlaceID | PPTArc !PlaceID !PTransID | PTPArc !PTransID !PlaceID deriving (Eq, Show) data Arc = Arc ArcType [ArcAttribute] deriving (Eq, Show) data ArcAttribute = ArcInvisibleLevel Int | ArcAdditionalPoint Position | ArcDefaulted DefaultableArcAttribute deriving (Eq, Show) data TextLine = TextLine !Position !Text deriving (Eq, Show) data LLNet = LLNet { _llnetHeader :: !Header , _llnetDefaults :: ![Default] , _llnetBlocks :: ![Block] , _llnetPlaces :: ![Place] , _llnetTrans :: ![Transition] , _llnetPTrans :: ![PhantomTransition] , _llnetArcs :: ![Arc] , _llnetTextLines :: ![TextLine] } deriving (Eq, Show) $(makeLenses ''LLNet) spaces :: Parser () spaces = skipMany (char ' ') line :: Parser () line = spaces <* optionalComment optionalComment :: Parser () optionalComment = void commentOrNewline where commentOrNewline = (char '%' <* manyTill anyChar newline) <|> newline lineNoComment :: Parser () lineNoComment = spaces <* newline parseID :: Parser Int parseID = parseInt parseInt :: Parser Int parseInt = do sign <- option '+' (char '+' <|> char '-') digits <- many1 digit stringToIntParser (sign : digits) where -- Go via Text to use the signed decimal parser stringToIntParser = failOrExtract . signed decimal . pack failOrExtract (Left err) = parserFail err failOrExtract (Right (i, r)) | T.null r = parserReturn i | otherwise = parserFail $ "Remaining text after parseInt on many1 digit" ++ unpack r parseBinaryAsBool :: Parser Bool parseBinaryAsBool = const False <$> char '0' <|> const True <$> char '1' parseInfinityOrNum :: Parser InfinityOrNum parseInfinityOrNum = const Infinity <$> (char '-' *> parseInt) <|> Number <$> parseNat parseNat :: Parser Nat parseNat = toNat <$> parseInt parseQuotedText :: Parser Text parseQuotedText = parseQuoted $ pack <$> many (noneOf "\"") parseQuoted :: Parser a -> Parser a parseQuoted p = dblQuote *> p <* dblQuote where dblQuote = char '"' parseSize :: Parser Size parseSize = taggedParse 's' (Size <$> parseNat) parseThickness :: Parser Thickness parseThickness = taggedParse 't' (Thickness <$> parseNat) parsePosition :: Parser Position parsePosition = makePos <$> (parseInt <* char '@') <*> parseInt where makePos x y = Position (x, y) parseHeader :: Parser Header parseHeader = pPepFile *> pHeader where pPepFile = string "PEP" *> lineNoComment pHeader = Header <$> (pType <* lineNoComment) <*> (pFormat <* lineNoComment) pType = (const PetriBox <$> try (string "PetriBox")) <|> (const PTNet <$> string "PTNet") pFormat = (const N2 <$> try (string "FORMAT_N2")) <|> (const N <$> string "FORMAT_N") -- TODO: this! parseDefaults :: Parser [Default] parseDefaults = many parseDefault -- |manyOnLine @c@ @p@ parses 0 or more occurrences of @p@, followed by an EOL, -- before applying the constructor c to the resulting list. manyOnLine :: ([a] -> b) -> Parser a -> Parser b manyOnLine c p = c <$> many p <* lineNoComment parseDefault :: Parser Default parseDefault = strTaggedParse "DBL" (manyOnLine DefaultBlock parseBlockDefault) <|> strTaggedParse "DPL" (manyOnLine DefaultPlace parsePlaceDefault) <|> strTaggedParse "DTR" (manyOnLine DefaultTransition parseTransitionDefault) <|> strTaggedParse "DPT" (manyOnLine DefaultArc parseArcDefault) parseBlockDefault :: Parser BlockDefault parseBlockDefault = BlockSize <$> parseSize <|> BlockThickness <$> parseThickness parsePlaceDefault :: Parser PlaceDefault parsePlaceDefault = PlaceDefaultableAttribute <$> parseDefaultableExtraAttribute <|> PlaceSize <$> parseSize <|> PlaceThickness <$> parseThickness parseTransitionDefault :: Parser TransitionDefault parseTransitionDefault = TransitionDefaultableAttribute <$> parseDefaultableExtraAttribute <|> TransitionSize <$> parseSize <|> TransitionThickness <$> parseThickness parseArcDefault :: Parser ArcDefault parseArcDefault = ArcDefaultableAttribute <$> parseDefaultableArcAttribute <|> ArcThickness <$> parseThickness -- |parseAttribute takes a disambiguation character and a parser, and uses -- taggedParse, ignoring any trailing spaces. parseAttribute :: Char -> Parser a -> Parser a parseAttribute c p = taggedParse c p <* spaces parseDefaultableArcAttribute :: Parser DefaultableArcAttribute parseDefaultableArcAttribute = parseAttribute 'w' (Weight <$> parseInt) <|> parseAttribute 'n' (WeightRelativePos <$> parsePosition) -- Object Data is an ID, name and position. They must appear in that order if -- they appear, but ID and name may be left off. If the id doesn't appear, it -- is assumed to be 1-indexed. parseObjectData :: Parser ObjectData parseObjectData = parseRaw >>= toObjData where parseRaw = (,,) <$> option Nothing (try (Just <$> spaced parseID)) <*> option Nothing (spaced (Just <$> parseQuotedText)) <*> spaced parsePosition toObjData (Nothing, Nothing, p) = return $ ObjectData Nothing p toObjData (Nothing, Just n, p) = return $ ObjectData (Just (Right n)) p toObjData (Just i, Just n, p) = return $ ObjectData (Just (Left (i, n))) p toObjData input = parserFail $ "Object data doesn't meet requirements: " ++ show input spaced p = p <* spaces -- | Parse a "disambiguation" string, and then use the given parser. strTaggedParse :: String -> Parser a -> Parser a strTaggedParse t p = try (strNoLine t) *> p -- | Parse a single "disambiguation" character, and then use the given parser. taggedParse :: Char -> Parser a -> Parser a taggedParse c p = char c *> p parseListOfIDs :: Parser [Int] parseListOfIDs = parseQuoted $ withParens (sepBy parseID (char ',')) where withParens p = char '(' *> p <* char ')' parseDefaultableExtraAttribute :: Parser DefaultableExtraAttribute parseDefaultableExtraAttribute = parseAttribute 'n' (NameRelativePos <$> parsePosition) <|> parseAttribute 'b' (Meaning <$> parseQuotedText) parseCommonExtraAttribute :: Parser CommonExtraAttribute parseCommonExtraAttribute = (CommonDefaulted <$> parseDefaultableExtraAttribute) <|> parseAttribute 'a' (MeaningRelativePos <$> parsePosition) <|> parseAttribute 'R' (Reference <$> parseQuotedText) parseBlocks :: Parser [Block] parseBlocks = option [] (strLine "BL" *> many parseBlock) where parseBlock = Block <$> parseObjectData <*> many parseBlockAttribute <* lineNoComment parseBlockAttribute = BlockCommon <$> parseCommonExtraAttribute <|> BlockBlocks <$> parseAttribute 'u' parseListOfIDs parsePlaces :: Parser [Place] parsePlaces = strLine "PL" *> many parsePlace where parsePlace = Place <$> parseObjectData <*> many parsePlaceAttribute <* lineNoComment parsePlaceAttribute = PlaceCommon <$> parseCommonExtraAttribute <|> parseAttribute 'M' (PlaceInitialMarking <$> parseBinaryAsBool) <|> parseAttribute 'm' (PlaceCurrentMarking <$> parseBinaryAsBool) <|> parseAttribute 'k' (PlaceCapacity <$> parseInfinityOrNum) <|> parseAttribute 'e' (return PlaceEntryPlace) <|> parseAttribute 'x' (return PlaceExitPlace) <|> parseAttribute 'u' (PlaceBlocks <$> parseListOfIDs) parseTransitions :: Parser [Transition] parseTransitions = strLine "TR" *> many parseTransition where parseTransition = Transition <$> parseObjectData <*> many parseTransitionAttribute <* lineNoComment parseTransitionAttribute = TransitionCommon <$> parseCommonExtraAttribute <|> parseAttribute 'v' (TransitionInvisibleLevel <$> parseInt) <|> parseAttribute 'u' (TransitionBlocks <$> parseListOfIDs) <|> parseAttribute 'S' (return TransitionSynchronisationTransition) <|> parseAttribute 'P' (TransitionPhantomTransitions <$> parseListOfIDs) parsePhantomTrans :: Parser [PhantomTransition] parsePhantomTrans = option [] (strLine "PTR" *> many parsePhantomTran) where parsePhantomTran = PhantomTransition <$> parseObjectData <*> many parsePhantomTransAttribute <* lineNoComment parsePhantomTransAttribute = PhantomTransCommon <$> parseCommonExtraAttribute <|> parseAttribute 'u' (PhantomTransBlocks <$> parseListOfIDs) <|> parseAttribute 'P' (PhantomTransSynchronisationTransitions <$> parseListOfIDs) parseArcs :: Bool -> Parser [Arc] parseArcs isPhantom = many parseArc where arcDataToArcType lid isTP rid attrs = let arcType = case (isPhantom, isTP) of (False, False) -> PTArc (PlaceID lid) (TransID rid) (False, True) -> TPArc (TransID lid) (PlaceID rid) (True, False) -> PPTArc (PlaceID lid) (PTransID rid) (True, True) -> PTPArc (PTransID lid) (PlaceID rid) in Arc arcType attrs parseArc = arcDataToArcType <$> parseInt <*> parseIsTP <*> parseInt <*> many parseArcAttribute <* lineNoComment parseIsTP = taggedParse '<' (pure True) <|> taggedParse '>' (pure False) parseArcAttribute = ArcDefaulted <$> parseDefaultableArcAttribute <|> parseAttribute 'v' (ArcInvisibleLevel <$> parseInt) <|> parseAttribute 'J' (ArcAdditionalPoint <$> parsePosition) parseText :: Parser [TextLine] parseText = strLine "TX" *> many parseTextLine where parseTextLine = TextLine <$> parsePosition <*> parseQuotedText <* lineNoComment llNetParser :: Parser LLNet llNetParser = LLNet <$> parseHeader <*> parseDefaults <*> parseBlocks <*> parsePlaces <*> parseTransitions <*> parsePhantomTrans <*> parseAllArcs <*> optionalList parseText where concat4 a b c d = a ++ b ++ c ++ d parseAllArcs = concat4 <$> taggedArcs "TP" <*> taggedArcs "PT" <*> optionalList (taggedPhantomArcs "PTP") <*> optionalList (taggedPhantomArcs "PPT") taggedArcs s = strLine s *> parseArcs False taggedPhantomArcs s = strLine s *> parseArcs True optionalList = option [] strLine :: String -> Parser () strLine s = string s *> line strNoLine :: String -> Parser () strNoLine s = string s *> spaces parseLLNet :: Text -> IO LLNet parseLLNet input = case parse llNetParser "" input of Left err -> fail $ "parsing failed: " ++ show err Right a -> return a parseFile :: String -> IO LLNet parseFile = TIO.readFile >=> parseLLNet parseLatin1File :: String -> IO LLNet parseLatin1File = BIO.readFile >=> parseLLNet . decodeLatin1
owst/Penrose
src/PEPParser.hs
bsd-3-clause
16,147
0
16
4,276
3,950
2,085
1,865
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Bead.View.Content.SubmissionList.Page ( submissionList ) where import Control.Monad import Control.Monad.Trans.Class import Control.Monad.IO.Class import Data.String (fromString) import Data.Time import Data.List (intercalate) import Text.Blaze.Html5 as H import Bead.Controller.UserStories import qualified Bead.Controller.Pages as Pages import qualified Bead.Domain.Entity.Assignment as Assignment import Bead.Domain.Shared.Evaluation import Bead.View.Content import qualified Bead.View.Content.Bootstrap as Bootstrap import Bead.View.Content.Submission.Common import Bead.View.Content.Utils import Bead.View.Markdown submissionList = ViewHandler submissionListPage data PageData = PageData { asKey :: AssignmentKey , smList :: SubmissionListDesc , uTime :: UserTimeConverter , smLimit :: SubmissionLimit } submissionListPage :: GETContentHandler submissionListPage = do ak <- getParameter assignmentKeyPrm -- TODO: Refactor use guards userStory $ do doesBlockAssignmentView ak page <- usersAssignment ak $ \assignment -> do case assignment of Nothing -> return invalidAssignment Just asg -> do now <- liftIO getCurrentTime case (Assignment.start asg > now) of True -> return assignmentNotStartedYet False -> do (sl,lmt) <- userStory $ (,) <$> submissionListDesc ak <*> assignmentSubmissionLimit ak tc <- userTimeZoneToLocalTimeConverter return $ submissionListContent $ PageData { asKey = ak , smList = sortSbmListDescendingByTime sl , uTime = tc , smLimit = lmt } return page submissionListContent :: PageData -> IHtml submissionListContent p = do msg <- getI18N return $ do let info = smList p -- Submission List Info Bootstrap.rowColMd12 $ Bootstrap.table $ tbody $ do (msg $ msg_SubmissionList_CourseOrGroup "Course, group:") .|. (slGroup info) (msg $ msg_SubmissionList_Admin "Teacher:") .|. (intercalate ", " . sortHun $ slTeacher info) (msg $ msg_SubmissionList_Assignment "Assignment:") .|. (Assignment.name $ slAssignment info) (msg $ msg_SubmissionList_Deadline "Deadline:") .|. (showDate . (uTime p) . Assignment.end $ slAssignment info) maybe (return ()) (uncurry (.|.)) (remainingTries msg (smLimit p)) let submissions = slSubmissions info userSubmissionInfo msg submissions Bootstrap.rowColMd12 $ h2 $ fromString $ msg $ msg_SubmissionList_Description "Assignment Description" H.div # assignmentTextDiv $ (markdownToHtml . Assignment.desc . slAssignment . smList $ p) where submissionDetails ak sk = Pages.submissionDetails ak sk () submissionLine msg (sk, time, status, _t) = do Bootstrap.listGroupLinkItem (routeOf $ submissionDetails (asKey p) sk) (do Bootstrap.badge (resolveStatus msg status); fromString . showDate $ (uTime p) time) resolveStatus msg = fromString . submissionInfoCata (msg $ msg_SubmissionList_NotFound "Not Found") (msg $ msg_SubmissionList_NotEvaluatedYet "Not evaluated yet") (bool (msg $ msg_SubmissionList_TestsPassed "Tests are passed") (msg $ msg_SubmissionList_TestsFailed "Tests are failed")) (const (evaluationResultMsg . evResult)) where evaluationResultMsg = evaluationResultCata (binaryCata (resultCata (msg $ msg_SubmissionList_Passed "Passed") (msg $ msg_SubmissionList_Failed "Failed"))) (percentageCata (fromString . scores)) (freeForm fromString) scores (Scores []) = "0%" scores (Scores [p]) = concat [show . round $ 100 * p, "%"] scores _ = "???%" submissionTimeLine time = Bootstrap.listGroupTextItem $ showDate $ (uTime p) time userSubmissionInfo msg submissions = do when (length submissions > 0) $ Bootstrap.rowColMd12 $ H.p $ fromString $ msg $ msg_SubmissionList_Info "Comments may be added for submissions." userSubmission msg (submissionLine msg) submissions userSubmissionTimes msg = userSubmission msg submissionTimeLine userSubmission msg line submissions = if (not $ null submissions) then do Bootstrap.rowColMd12 $ Bootstrap.listGroup $ mapM_ line submissions else do (Bootstrap.rowColMd12 $ fromString $ msg $ msg_SubmissionList_NoSubmittedSolutions "There are no submissions.") invalidAssignment :: IHtml invalidAssignment = do msg <- getI18N return $ do Bootstrap.rowColMd12 $ p $ fromString $ msg $ msg_SubmissionList_NonAssociatedAssignment "This assignment cannot be accessed by this user." assignmentNotStartedYet :: IHtml assignmentNotStartedYet = do msg <- getI18N return $ do Bootstrap.rowColMd12 $ p $ fromString $ msg $ msg_SubmissionList_NonReachableAssignment "This assignment cannot be accessed." -- Creates a table line first element is a bold text and the second is a text infixl 7 .|. name .|. value = H.tr $ do H.td $ b $ fromString $ name H.td $ fromString value
andorp/bead
src/Bead/View/Content/SubmissionList/Page.hs
bsd-3-clause
5,333
0
26
1,310
1,350
691
659
110
4
module Process.Peer.Receiver ( runReceiver , specReceiver ) where import Control.Concurrent.STM import Control.Monad.Reader (liftIO, asks) import Data.ByteString (ByteString) import qualified Data.ByteString as B import Network.Socket (Socket) import qualified Network.Socket.ByteString as SB import Process import Supervisor import Protocol.Peer import Process.Peer.Chan data PConf = PConf { cSocket :: Socket , cMessageChan :: TChan PeerMessage } runReceiver :: Socket -> TChan PeerMessage -> IO Reason runReceiver sock chan = do execProcess conf () receive return Normal where conf = PConf sock chan specReceiver :: Socket -> TChan PeerMessage -> IO ChildSpec specReceiver sock chan = do return $ ChildSpec { csType = Worker , csAction = runReceiver sock chan , csRestart = Transient , csShutdown = return () , csShutdownTimeout = 100 } receive :: Process PConf () () receive = receiveHandshake receiveHandshake :: Process PConf () () receiveHandshake = do sock <- asks cSocket chan <- asks cMessageChan (remain, handshake) <- liftIO $ decodeHandshake (demandInput sock) liftIO . atomically $ writeTChan chan (PeerHandshake handshake) receiveMessage remain receiveMessage :: ByteString -> Process PConf () () receiveMessage remain = do sock <- asks cSocket chan <- asks cMessageChan (remain', message) <- liftIO $ decodeMessage remain (demandInput sock) liftIO . atomically $ writeTChan chan (PeerMessage message) receiveMessage remain' demandInput :: Socket -> IO ByteString demandInput sock = do packet <- SB.recv sock 1024 if B.length packet /= 0 then return packet else fail "demandInput: socket dead"
artems/FlashBit
src/Process/Peer/Receiver.hs
bsd-3-clause
1,786
0
11
407
530
273
257
51
2
{-# LANGUAGE PackageImports #-} module GHC.MVar (module M) where import "base" GHC.MVar as M
silkapp/base-noprelude
src/GHC/MVar.hs
bsd-3-clause
98
0
4
18
21
15
6
3
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} module Lib where import Control.Exception (assert) import qualified Data.Map.Lazy as Map import Data.Maybe import Data.Monoid import qualified Data.Set as Set import Debug.Trace import System.Console.ANSI as AN import qualified Text.Show.Pretty as Pr import Control.Applicative color :: Color -> String -> String color c str = AN.setSGRCode [AN.SetColor AN.Foreground AN.Vivid c] ++ str ++ AN.setSGRCode [AN.Reset] data PrimVal = PrimInt Int | PrimSym String deriving (Show, Eq, Ord) type Name = String data Value = Var Name | Lambda Name Value | Prim Name PrimVal | Apply Value Value deriving (Show, Eq) sym :: String -> Value sym str = Prim str $ PrimSym str data Context = Context { global :: Map.Map Name Value , bound :: Map.Map Name Value , free :: Set.Set Name } instance Show Context where show (Context global bmap fmap) = "\n-- bound: \n" ++ Pr.ppShow bmap ++ "\n\n-- free :\n" ++ Pr.ppShow fmap data Prog = Prog Value Context instance Show Prog where show (Prog value context) = color AN.Green ("\n" ++ Pr.ppShow value) ++ color AN.Black ("\n" ++ show context) ++ "\n" ctxLookup :: Context -> Name -> Maybe Value ctxLookup (Context global bound _) name = Map.lookup name global <|> Map.lookup name bound insertBound :: Name -> Value -> Context -> Context insertBound name expr (Context global bound free) = Context global bound' free' where bound' = Map.insert name expr bound free' = Set.delete name free insertFree :: Name -> Context -> Context insertFree name (Context global bound free) = Context global bound' free' where bound' = assert notfound bound where notfound = isNothing $ Map.lookup name bound free' = Set.insert name free deleteBound :: Name -> Context -> Context deleteBound name (Context global bound free) = Context global bound' free where bound' = Map.delete name bound -- |Interpretation -- TODO: make monadic for introspection defaultContext = Context (Map.fromList [ ("I", Lambda "x" (Var "x")) , ("K", Lambda "x" (Lambda "y" (Var "x"))) , ("S", Lambda "x" (Lambda "y" (Lambda "z" (Apply (Apply (Var "x") (Var "y")) (Apply (Var "x") (Var "z")))))) , ("Omega", omega) , ("Y", ycomb) , ("KIOmega", Apply (Apply (Var "K") (Var "I")) (omega)) -- should normalize under lazy but not strict semantics , ("KOmegaI", Apply (Apply (Var "K") (Var "I")) (omega)) -- should fail to normalize for both lazy and strict semantics ]) (Map.fromList []) (Set.fromList []) where omega = Apply om om where om = Lambda "x" (Apply (Var "x") (Var "x")) ycomb = Lambda "y" (Apply y' y') where y' = Lambda "x" (Apply (Var "y") (Apply (Var "x") (Var "x"))) evalStrict :: Value -> Prog evalStrict input = eval $ Prog input defaultContext eval :: Prog -> Prog eval (Prog value ctx) = case value of -- Do Nothing Lambda name expr -> Prog (Lambda name expr) ctx Prim name expr -> Prog (Prim name expr) ctx -- Step Var name -> evalVar name Apply f x -> evalApply f x where evalVar :: Name -> Prog evalVar name = f $ ctxLookup ctx name where f (Just expr) = eval (Prog expr ctx) f Nothing = error $ "Error! " ++ name ++ " not found!" -- f Nothing = Prog (Prim name (PrimSym name)) $ insertFree name ctx evalApply :: Value -> Value -> Prog evalApply bound binder = f (eval (Prog bound ctx)) (eval (Prog binder ctx)) -- Strict semantics, since we require that right side be evaluated where f (Prog (Lambda name bound') ctx') (Prog binder' _) = cleanScope $ eval $ Prog bound' (insertBound name binder' ctx') -- Do something with ctx? where cleanScope (Prog result ctx'') = Prog result ctx''
sleexyz/untyped
src/Lib.hs
bsd-3-clause
4,381
0
20
1,322
1,395
726
669
82
5
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.Time.IT.Corpus ( corpus , negativeCorpus ) where import Data.String import Prelude import Duckling.Locale import Duckling.Resolve import Duckling.Time.Corpus import Duckling.Time.Types hiding (Month) import Duckling.TimeGrain.Types hiding (add) import Duckling.Testing.Types hiding (examples) corpus :: Corpus corpus = (testContext {locale = makeLocale IT Nothing}, testOptions, allExamples) negativeCorpus :: NegativeCorpus negativeCorpus = (testContext {locale = makeLocale IT Nothing}, testOptions, examples) where examples = [ "ma" , "3 20" ] allExamples :: [Example] allExamples = concat [ examples (datetime (2013, 2, 12, 4, 30, 0) Second) [ "subito" , "immediatamente" , "in questo momento" , "ora" , "adesso" ] , examples (datetime (2013, 2, 12, 0, 0, 0) Day) [ "di oggi" , "oggi" , "in giornata" ] , examples (datetime (2013, 2, 11, 0, 0, 0) Day) [ "ieri" ] , examples (datetime (2013, 2, 13, 0, 0, 0) Day) [ "domani" ] , examples (datetime (2013, 2, 14, 0, 0, 0) Day) [ "Il giorno dopo domani" , "dopodomani" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Day) [ "Lunedì 18 febbraio" ] , examples (datetime (2013, 2, 19, 0, 0, 0) Day) [ "martedì" , "Martedì 19" , "mar 19" , "il 19" ] , examples (datetime (2013, 2, 10, 0, 0, 0) Day) [ "l'altro ieri" , "altroieri" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Day) [ "lunedi" , "lun" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Day) [ "lunedi 18 febbraio" ] , examples (datetime (2013, 2, 19, 0, 0, 0) Day) [ "Martedì" , "Martedi" , "mar" ] , examples (datetime (2013, 2, 13, 0, 0, 0) Day) [ "Mercoledì" , "mer" , "mer." ] , examples (datetime (2013, 2, 13, 0, 0, 0) Day) [ "mercoledi 13 feb" , "il 13 febbraio" ] , examples (datetime (2013, 2, 13, 0, 0, 0) Day) [ "il 13 febbraio 2013" ] , examples (datetime (2013, 2, 14, 0, 0, 0) Day) [ "giovedi" , "giovedì" , "gio" ] , examples (datetime (2013, 2, 15, 0, 0, 0) Day) [ "venerdi" , "venerdì" , "ven" ] , examples (datetime (2013, 2, 16, 0, 0, 0) Day) [ "sabato" , "sab" , "sab." ] , examples (datetime (2013, 2, 17, 0, 0, 0) Day) [ "domenica" , "dom" , "dom." ] , examples (datetime (2013, 1, 1, 0, 0, 0) Month) [ "gennaio 2013" , "genn 2013" , "genn. 2013" ] , examples (datetime (2013, 12, 1, 0, 0, 0) Month) [ "dicembre 2013" , "dic 2013" , "dic. 2013" ] , examples (datetime (2013, 2, 10, 0, 0, 0) Day) [ "domenica 10 febbraio" ] , examples (datetime (2013, 3, 1, 0, 0, 0) Day) [ "il 1 marzo" , "primo marzo" , "primo di marzo" , "il 1º marzo" ] , examples (datetimeOpenInterval Before (2013, 3, 1, 0, 0, 0) Month) [ "prima di marzo" ] , examples (datetime (2013, 3, 15, 0, 0, 0) Day) [ "le idi di marzo" , "idi di marzo" ] , examples (datetime (2015, 3, 3, 0, 0, 0) Day) [ "3 marzo 2015" , "3/3/2015" , "3/3/15" , "2015-3-3" , "2015-03-03" ] , examples (datetime (2013, 2, 15, 0, 0, 0) Day) [ "il 15 febbraio" , "15/2" , "il 15/02" ] , examples (datetime (1974, 10, 31, 0, 0, 0) Day) [ "31/10/1974" , "31/10/74" ] , examples (datetime (2013, 2, 5, 0, 0, 0) Day) [ "martedì scorso" ] , examples (datetime (2013, 2, 19, 0, 0, 0) Day) [ "martedì prossimo" , "il martedì dopo" ] , examples (datetime (2013, 2, 20, 0, 0, 0) Day) [ "mercoledì prossimo" ] , examples (datetime (2014, 10, 0, 0, 0, 0) Month) [ "ottobre 2014" ] , examples (datetime (2013, 2, 12, 3, 0, 0) Hour) [ "l'ultima ora" , "nell'ultima ora" ] , examples (datetime (2013, 2, 11, 0, 0, 0) Week) [ "questa settimana" ] , examples (datetime (2013, 2, 4, 0, 0, 0) Week) [ "la settimana scorsa" , "la scorsa settimana" , "nella scorsa settimana" , "della settimana scorsa" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Week) [ "la settimana prossima" , "la prossima settimana" , "nella prossima settimana" , "settimana prossima" , "prossima settimana" ] , examples (datetime (2013, 1, 0, 0, 0, 0) Month) [ "il mese scorso" , "nel mese scorso" , "nel mese passato" , "lo scorso mese" , "dello scorso mese" ] , examples (datetime (2013, 3, 0, 0, 0, 0) Month) [ "il mese prossimo" , "il prossimo mese" ] , examples (datetime (2013, 1, 1, 0, 0, 0) Quarter) [ "questo trimestre" ] , examples (datetime (2013, 4, 1, 0, 0, 0) Quarter) [ "il prossimo trimestre" , "nel prossimo trimestre" ] , examples (datetime (2013, 7, 1, 0, 0, 0) Quarter) [ "terzo trimestre" , "il terzo trimestre" ] , examples (datetime (2018, 10, 1, 0, 0, 0) Quarter) [ "quarto trimestre 2018" , "il quarto trimestre 2018" , "del quarto trimestre 2018" ] , examples (datetime (2012, 0, 0, 0, 0, 0) Year) [ "l'anno scorso" ] , examples (datetime (2013, 0, 0, 0, 0, 0) Year) [ "quest'anno" ] , examples (datetime (2014, 0, 0, 0, 0, 0) Year) [ "il prossimo anno" ] , examples (datetime (2013, 2, 10, 0, 0, 0) Day) [ "ultima domenica" ] , examples (datetime (2013, 2, 11, 0, 0, 0) Day) [ "lunedì di questa settimana" ] , examples (datetime (2013, 2, 12, 0, 0, 0) Day) [ "martedì di questa settimana" ] , examples (datetime (2013, 2, 13, 0, 0, 0) Day) [ "mercoledì di questa settimana" ] , examples (datetime (2013, 2, 14, 17, 0, 0) Hour) [ "dopo domani alle 17" , "dopodomani alle 5 del pomeriggio" ] , examples (datetime (2013, 3, 25, 0, 0, 0) Day) [ "ultimo lunedì di marzo" ] , examples (datetime (2014, 3, 30, 0, 0, 0) Day) [ "ultima domenica di marzo 2014" ] , examples (datetime (2013, 10, 3, 0, 0, 0) Day) [ "il terzo giorno di ottobre" ] , examples (datetime (2014, 10, 6, 0, 0, 0) Week) [ "prima settimana di ottobre 2014" ] , examples (datetime (2013, 10, 7, 0, 0, 0) Week) [ "la settimana del 6 ottobre" , "la settimana del 7 ott" ] , examples (datetimeInterval ((2013, 2, 15, 18, 0, 0), (2013, 2, 18, 0, 0, 0)) Hour) [ "il we del 15 febbraio" ] , examples (datetimeInterval ((2013, 4, 12, 18, 0, 0), (2013, 4, 15, 0, 0, 0)) Hour) [ "il week-end del 10 aprile" ] , examples (datetime (2015, 10, 31, 0, 0, 0) Day) [ "l'ultimo giorno di ottobre 2015" , "l'ultimo giorno dell'ottobre 2015" ] , examples (datetime (2014, 9, 22, 0, 0, 0) Week) [ "l'ultima settimana di settembre 2014" ] , examples (datetime (2013, 2, 12, 5, 30, 0) Minute) [ "tra un'ora" , "tra 1 ora" ] , examples (datetime (2013, 2, 12, 4, 45, 0) Second) [ "tra un quarto d'ora" ] , examples (datetime (2013, 2, 12, 5, 0, 0) Second) [ "tra mezz'ora" ] , examples (datetime (2013, 2, 12, 5, 15, 0) Second) [ "tra tre quarti d'ora" ] , examples (datetime (2013, 10, 1, 0, 0, 0) Day) [ "primo martedì di ottobre" , "primo martedì in ottobre" , "1° martedì del mese di ottobre" , "1º martedì del mese di ottobre" ] , examples (datetime (2014, 9, 16, 0, 0, 0) Day) [ "terzo martedì di settembre 2014" ] , examples (datetime (2014, 10, 1, 0, 0, 0) Day) [ "primo mercoledì di ottobre 2014" ] , examples (datetime (2014, 10, 8, 0, 0, 0) Day) [ "secondo mercoledì di ottobre 2014" ] , examples (datetime (2015, 1, 13, 0, 0, 0) Day) [ "terzo martedì dopo natale 2014" ] , examples (datetime (2016, 1, 0, 0, 0, 0) Month) [ "il mese dopo natale 2015" ] , examples (datetime (2013, 2, 12, 15, 0, 0) Hour) [ "alle 3 di pomeriggio" , "le tre di pomeriggio" , "alle 3 del pomeriggio" , "le tre del pomeriggio" ] , examples (datetime (2013, 2, 12, 15, 0, 0) Hour) [ "circa alle 3 del pomeriggio" ] , examples (datetime (2013, 2, 12, 15, 0, 0) Hour) [ "per le 15" , "verso le 15" ] , examples (datetime (2013, 2, 13, 3, 0, 0) Minute) [ "3:00" , "03:00" ] , examples (datetime (2013, 2, 12, 15, 15, 0) Minute) [ "15:15" ] , examples (datetime (2013, 2, 12, 15, 15, 0) Minute) [ "3:15 di pomeriggio" , "3:15 del pomeriggio" , "3 e un quarto di pomeriggio" , "tre e un quarto di pomeriggio" ] , examples (datetime (2013, 2, 12, 15, 20, 0) Minute) [ "alle tre e venti di pomeriggio" , "alle tre e venti del pomeriggio" , "3:20 di pomeriggio" , "3:20 del pomeriggio" , "15:20 del pomeriggio" ] , examples (datetime (2013, 2, 13, 3, 20, 0) Minute) [ "alle tre e venti" , "tre e 20" , "3 e 20" , "3:20" , "alle 3 20" ] , examples (datetime (2013, 2, 12, 15, 30, 0) Minute) [ "15:30" ] , examples (datetime (2013, 2, 12, 11, 45, 0) Minute) [ "a mezzogiorno meno un quarto" , "mezzogiorno meno un quarto" , "un quarto a mezzogiorno" , "11:45 del mattino" ] , examples (datetime (2013, 2, 13, 3, 0, 0) Hour) [ "alle 3 del mattino" ] , examples (datetime (2013, 9, 20, 19, 30, 0) Minute) [ "alle 19:30 di venerdì 20 settembre" , "alle 19:30 venerdì 20 settembre" , "venerdì 20 settembre alle 19:30" , "il 20 settembre alle 19:30" ] , examples (datetimeInterval ((2013, 2, 15, 18, 0, 0), (2013, 2, 18, 0, 0, 0)) Hour) [ "questo week-end" , "questo fine settimana" , "questo finesettimana" ] , examples (datetimeInterval ((2013, 2, 18, 4, 0, 0), (2013, 2, 18, 12, 0, 0)) Hour) [ "lunedi mattina" ] , examples (datetimeInterval ((2013, 2, 15, 4, 0, 0), (2013, 2, 15, 12, 0, 0)) Hour) [ "15 febbraio al mattino" , "mattino di 15 febbraio" ] , examples (datetime (2013, 2, 12, 20, 0, 0) Hour) [ "8 di stasera" , "8 della sera" ] , examples (datetime (2013, 9, 20, 19, 30, 0) Minute) [ "venerdì 20 settembre alle 7:30 del pomeriggio" ] , examples (datetime (2013, 2, 16, 9, 0, 0) Hour) [ "alle 9 di sabato" , "sabato alle 9" ] , examples (datetimeInterval ((2013, 6, 21, 0, 0, 0), (2013, 9, 24, 0, 0, 0)) Day) [ "quest'estate" , "questa estate" , "in estate" ] , examples (datetimeInterval ((2012, 12, 21, 0, 0, 0), (2013, 3, 21, 0, 0, 0)) Day) [ "quest'inverno" , "questo inverno" , "in inverno" ] , examples (datetimeInterval ((2014, 9, 23, 0, 0, 0), (2014, 12, 22, 0, 0, 0)) Day) [ "il prossimo autunno" ] , examples (datetime (2013, 12, 25, 0, 0, 0) Day) [ "natale" , "il giorno di natale" ] , examples (datetime (2013, 12, 24, 0, 0, 0) Day) [ "vigilia di natale" , "alla vigilia" , "la vigilia" ] , examples (datetime (2013, 12, 31, 0, 0, 0) Day) [ "vigilia di capodanno" , "san silvestro" ] , examples (datetimeInterval ((2014, 1, 1, 0, 0, 0), (2014, 1, 1, 4, 0, 0)) Hour) [ "notte di san silvestro" ] , examples (datetime (2014, 1, 1, 0, 0, 0) Day) [ "capodanno" , "primo dell'anno" ] , examples (datetime (2014, 1, 6, 0, 0, 0) Day) [ "epifania" , "befana" ] , examples (datetime (2013, 2, 14, 0, 0, 0) Day) [ "san valentino" , "festa degli innamorati" ] , examples (datetime (2013, 3, 19, 0, 0, 0) Day) [ "festa del papà" , "festa del papa" , "festa di san giuseppe" , "san giuseppe" ] , examples (datetime (2013, 4, 25, 0, 0, 0) Day) [ "anniversario della liberazione" , "la liberazione" , "alla liberazione" ] , examples (datetime (2013, 5, 1, 0, 0, 0) Day) [ "festa del lavoro" , "festa dei lavoratori" , "giorno dei lavoratori" , "primo maggio" ] , examples (datetime (2013, 5, 12, 0, 0, 0) Day) [ "festa della mamma" ] , examples (datetime (2013, 6, 2, 0, 0, 0) Day) [ "festa della repubblica" , "la repubblica" , "repubblica" ] , examples (datetime (2013, 8, 15, 0, 0, 0) Day) [ "ferragosto" , "assunzione" ] , examples (datetime (2013, 10, 31, 0, 0, 0) Day) [ "halloween" ] , examples (datetime (2013, 11, 1, 0, 0, 0) Day) [ "tutti i santi" , "ognissanti" , "festa dei santi" , "il giorno dei santi" ] , examples (datetime (2013, 11, 2, 0, 0, 0) Day) [ "giorno dei morti" , "commemorazione dei defunti" ] , examples (datetime (2013, 11, 2, 2, 0, 0) Hour) [ "ai morti alle 2" ] , examples (datetime (2013, 12, 8, 0, 0, 0) Day) [ "immacolata" , "immacolata concezione" , "all'immacolata" ] , examples (datetime (2013, 12, 8, 18, 0, 0) Hour) [ "all'immacolata alle 18" ] , examples (datetime (2013, 12, 26, 0, 0, 0) Day) [ "santo stefano" ] , examples (datetimeInterval ((2013, 2, 12, 18, 0, 0), (2013, 2, 13, 0, 0, 0)) Hour) [ "questa sera" , "sta sera" , "stasera" , "in serata" , "nella sera" , "verso sera" , "la sera" , "alla sera" , "la serata" , "nella serata" ] , examples (datetimeInterval ((2013, 2, 13, 4, 0, 0), (2013, 2, 13, 12, 0, 0)) Hour) [ "domani mattina" , "domattina" ] , examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 2, 18, 0, 0, 0)) Second) [ "in settimana" , "per la settimana" ] , examples (datetimeInterval ((2013, 2, 13, 0, 0, 0), (2013, 2, 13, 4, 0, 0)) Hour) [ "stanotte" , "nella notte" , "in nottata" ] , examples (datetimeInterval ((2013, 2, 8, 18, 0, 0), (2013, 2, 11, 0, 0, 0)) Hour) [ "ultimo weekend" ] , examples (datetimeInterval ((2013, 2, 13, 18, 0, 0), (2013, 2, 14, 0, 0, 0)) Hour) [ "domani in serata" , "domani sera" , "nella serata di domani" ] , examples (datetimeInterval ((2013, 2, 14, 0, 0, 0), (2013, 2, 14, 4, 0, 0)) Hour) [ "domani notte" , "domani in nottata" , "nella nottata di domani" , "nella notte di domani" ] , examples (datetimeInterval ((2013, 2, 13, 12, 0, 0), (2013, 2, 13, 14, 0, 0)) Hour) [ "domani a pranzo" ] , examples (datetimeInterval ((2013, 2, 11, 18, 0, 0), (2013, 2, 12, 0, 0, 0)) Hour) [ "ieri sera" ] , examples (datetimeInterval ((2013, 2, 15, 18, 0, 0), (2013, 2, 18, 0, 0, 0)) Hour) [ "questo weekend" , "questo week-end" ] , examples (datetimeInterval ((2013, 2, 18, 4, 0, 0), (2013, 2, 18, 12, 0, 0)) Hour) [ "lunedì mattina" , "nella mattinata di lunedì" , "lunedì in mattinata" , "lunedì nella mattina" ] , examples (datetimeInterval ((2013, 2, 15, 4, 0, 0), (2013, 2, 15, 12, 0, 0)) Hour) [ "il 15 febbraio in mattinata" , "mattina del 15 febbraio" , "15 febbraio mattina" ] , examples (datetimeInterval ((2013, 2, 12, 4, 29, 58), (2013, 2, 12, 4, 30, 0)) Second) [ "gli ultimi 2 secondi" , "gli ultimi due secondi" , "i 2 secondi passati" , "i due secondi passati" ] , examples (datetimeInterval ((2013, 2, 12, 4, 30, 1), (2013, 2, 12, 4, 30, 4)) Second) [ "i prossimi 3 secondi" , "i prossimi tre secondi" , "nei prossimi tre secondi" ] , examples (datetimeInterval ((2013, 2, 12, 4, 28, 0), (2013, 2, 12, 4, 30, 0)) Minute) [ "gli ultimi 2 minuti" , "gli ultimi due minuti" , "i 2 minuti passati" , "i due minuti passati" ] , examples (datetimeInterval ((2013, 2, 12, 4, 31, 0), (2013, 2, 12, 4, 34, 0)) Minute) [ "i prossimi 3 minuti" , "nei prossimi 3 minuti" , "i prossimi tre minuti" ] , examples (datetimeInterval ((2013, 2, 12, 2, 0, 0), (2013, 2, 12, 4, 0, 0)) Hour) [ "le ultime 2 ore" , "le ultime due ore" , "nelle ultime due ore" , "le scorse due ore" , "le due ore scorse" , "le scorse 2 ore" , "le 2 ore scorse" , "nelle 2 ore scorse" ] , examples (datetimeInterval ((2013, 2, 11, 4, 0, 0), (2013, 2, 12, 4, 0, 0)) Hour) [ "le ultime 24 ore" , "le ultime ventiquattro ore" , "le 24 ore passate" , "nelle 24 ore scorse" , "le ventiquattro ore passate" ] , examples (datetimeInterval ((2013, 2, 12, 5, 0, 0), (2013, 2, 12, 8, 0, 0)) Hour) [ "le prossime 3 ore" , "prossime tre ore" , "nelle prossime 3 ore" ] , examples (datetimeInterval ((2013, 2, 10, 0, 0, 0), (2013, 2, 12, 0, 0, 0)) Day) [ "gli ultimi 2 giorni" , "gli ultimi due giorni" , "negli ultimi 2 giorni" , "i 2 giorni passati" , "i due giorni passati" , "nei due giorni passati" , "gli scorsi due giorni" , "i 2 giorni scorsi" , "i due giorni scorsi" ] , examples (datetimeInterval ((2013, 2, 13, 0, 0, 0), (2013, 2, 16, 0, 0, 0)) Day) [ "prossimi 3 giorni" , "i prossimi tre giorni" , "nei prossimi 3 giorni" , "prossimi giorni" , "nei prossimi giorni" ] , examples (datetimeInterval ((2013, 1, 28, 0, 0, 0), (2013, 2, 11, 0, 0, 0)) Week) [ "le ultime 2 settimane" , "le ultime due settimane" , "le 2 ultime settimane" , "le due ultime settimane" , "nelle 2 ultime settimane" ] , examples (datetimeInterval ((2013, 2, 18, 0, 0, 0), (2013, 3, 11, 0, 0, 0)) Week) [ "prossime 3 settimane" , "le prossime tre settimane" , "le 3 prossime settimane" , "nelle prossime 3 settimane" , "le tre prossime settimane" ] , examples (datetimeInterval ((2012, 12, 0, 0, 0, 0), (2013, 2, 0, 0, 0, 0)) Month) [ "gli ultimi 2 mesi" , "gli ultimi due mesi" , "i 2 mesi passati" , "nei 2 mesi passati" , "i due mesi passati" , "i due mesi scorsi" , "i 2 mesi scorsi" , "negli scorsi due mesi" , "gli scorsi due mesi" , "gli scorsi 2 mesi" ] , examples (datetimeInterval ((2013, 3, 0, 0, 0, 0), (2013, 6, 0, 0, 0, 0)) Month) [ "i prossimi 3 mesi" , "i prossimi tre mesi" , "prossimi 3 mesi" , "i 3 prossimi mesi" , "i tre prossimi mesi" , "nei prossimi tre mesi" ] , examples (datetimeInterval ((2011, 0, 0, 0, 0, 0), (2013, 0, 0, 0, 0, 0)) Year) [ "gli ultimi 2 anni" , "gli ultimi due anni" , "negli ultimi 2 anni" , "i 2 anni passati" , "i due anni passati" , "i 2 anni scorsi" , "i due anni scorsi" , "gli scorsi due anni" , "gli scorsi 2 anni" ] , examples (datetimeInterval ((2014, 0, 0, 0, 0, 0), (2017, 0, 0, 0, 0, 0)) Year) [ "i prossimi 3 anni" , "i prossimi tre anni" , "nei tre prossimi anni" ] , examples (datetimeInterval ((2013, 7, 13, 0, 0, 0), (2013, 7, 16, 0, 0, 0)) Day) [ "13-15 luglio" , "dal 13 al 15 luglio" , "tra il 13 e il 15 luglio" , "tra 13 e 15 luglio" , "dal tredici al quindici luglio" , "13 luglio - 15 luglio" ] , examples (datetimeInterval ((2013, 3, 3, 0, 0, 0), (2013, 3, 6, 0, 0, 0)) Day) [ "dal 3 al 5" , "tra il 3 e il 5" , "dal tre al cinque" ] , examples (datetimeInterval ((2013, 8, 8, 0, 0, 0), (2013, 8, 13, 0, 0, 0)) Day) [ "8 ago - 12 ago" ] , examples (datetimeInterval ((2013, 2, 13, 0, 0, 0), (2013, 2, 15, 0, 0, 0)) Day) [ "da domani a giovedì" ] , examples (datetimeInterval ((2013, 2, 12, 9, 30, 0), (2013, 2, 12, 11, 1, 0)) Minute) [ "9:30 - 11:00" ] , examples (datetimeInterval ((2013, 2, 14, 9, 30, 0), (2013, 2, 14, 11, 1, 0)) Minute) [ "dalle 9:30 alle 11:00 di giovedì" , "tra le 9:30 e le 11:00 di giovedì" , "9:30 - 11:00 giovedì" , "giovedì dalle 9:30 alle 11:00" , "giovedì tra le 9:30 e le 11:00" ] , examples (datetimeInterval ((2013, 2, 14, 9, 0, 0), (2013, 2, 14, 12, 0, 0)) Hour) [ "dalle 9 alle 11 di giovedì" , "tra le 9 e le 11 di giovedì" , "9 - 11 giovedì" , "giovedì dalle nove alle undici" , "giovedì tra le nove e le undici" ] , examples (datetimeInterval ((2013, 2, 14, 3, 0, 0), (2013, 2, 14, 14, 0, 0)) Hour) [ "dalle tre all'una di giovedì" ] , examples (datetimeInterval ((2013, 2, 13, 0, 0, 0), (2013, 2, 13, 3, 0, 0)) Hour) [ "dalla mezzanotte alle 2" ] , examples (datetimeInterval ((2013, 2, 13, 15, 0, 0), (2013, 2, 13, 17, 1, 0)) Minute) [ "domani dalle 15:00 alle 17:00" ] , examples (datetimeInterval ((2013, 2, 12, 11, 30, 0), (2013, 2, 12, 13, 31, 0)) Minute) [ "11:30-13:30" ] , examples (datetime (2013, 9, 21, 13, 30, 0) Minute) [ "13:30 di sabato 21 settembre" , "13:30 del 21 settembre" ] , examples (datetime (2013, 2, 26, 0, 0, 0) Day) [ "in due settimane" ] , examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 2, 12, 14, 0, 0)) Second) [ "fino alle 14:00" ] , examples (datetimeOpenInterval Before (2013, 2, 12, 14, 0, 0) Minute) [ "entro le 14:00" ] , examples (datetimeOpenInterval Before (2013, 3, 1, 0, 0, 0) Month) [ "entro la fine del mese" ] , examples (datetimeOpenInterval Before (2014, 1, 1, 0, 0, 0) Year) [ "entro la fine dell'anno" ] , examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 3, 1, 0, 0, 0)) Second) [ "fino alla fine del mese" ] , examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2014, 1, 1, 0, 0, 0)) Second) [ "fino alla fine dell'anno" ] , examples (datetime (2013, 2, 13, 1, 0, 0) Minute) [ "alle 4 CET" ] , examples (datetime (2013, 2, 12, 13, 0, 0) Minute) [ "alle 16 CET" ] , examples (datetime (2013, 2, 14, 6, 0, 0) Minute) [ "giovedì alle 8:00 GMT" , "giovedì alle 8:00 gmt" ] , examples (datetime (2013, 2, 13, 14, 0, 0) Hour) [ "domani alle 14" ] , examples (datetime (2013, 2, 12, 14, 0, 0) Hour) [ "alle 14" , "alle 2 del pomeriggio" ] , examples (datetime (2013, 4, 25, 16, 0, 0) Minute) [ "25/4 alle 16:00" ] , examples (datetime (2013, 2, 13, 15, 0, 0) Hour) [ "3 del pomeriggio di domani" , "15 del pomeriggio di domani" ] , examples (datetimeOpenInterval After (2013, 2, 12, 14, 0, 0) Hour) [ "dopo le 14" , "dalle 14" ] , examples (datetimeOpenInterval After (2013, 2, 13, 0, 0, 0) Hour) [ "dalla mezzanotte" ] , examples (datetimeOpenInterval After (2013, 2, 13, 14, 0, 0) Hour) [ "domani dopo le 14" , "domani dalle 14" ] , examples (datetimeOpenInterval Before (2013, 2, 12, 11, 0, 0) Hour) [ "prima delle 11" ] , examples (datetimeOpenInterval Before (2013, 2, 14, 11, 0, 0) Hour) [ "dopodomani prima delle 11" ] , examples (datetimeOpenInterval Before (2013, 2, 14, 12, 0, 0) Hour) [ "giovedì entro mezzogiorno" ] , examples (datetimeOpenInterval After (2013, 2, 14, 0, 0, 0) Day) [ "da dopodomani" , "da giovedì" ] , examples (datetimeOpenInterval After (2013, 3, 1, 0, 0, 0) Day) [ "dal primo" ] , examples (datetimeOpenInterval After (2013, 2, 20, 0, 0, 0) Day) [ "dal 20" ] , examples (datetimeOpenInterval Before (2013, 2, 15, 0, 0, 0) Day) [ "entro il 15" ] , examples (datetimeOpenInterval Before (2013, 4, 20, 0, 0, 0) Day) [ "prima del 20 aprile" ] , examples (datetimeInterval ((2013, 2, 12, 12, 0, 0), (2013, 2, 12, 19, 0, 0)) Hour) [ "nel pomeriggio" ] , examples (datetime (2013, 2, 12, 13, 30, 0) Minute) [ "alle 13:30" , "13:30" , "1:30 del pomeriggio" ] , examples (datetime (2013, 2, 12, 4, 45, 0) Second) [ "in 15 minuti" , "tra 15 minuti" ] , examples (datetime (2013, 2, 12, 10, 30, 0) Minute) [ "10:30" ] , examples (datetimeInterval ((2013, 2, 12, 4, 0, 0), (2013, 2, 12, 12, 0, 0)) Hour) [ "questa mattina" , "questa mattinata" , "questo mattino" ] , examples (datetime (2013, 2, 25, 0, 0, 0) Day) [ "prossimo lunedì" ] , examples (datetime (2013, 2, 12, 12, 0, 0) Hour) [ "alle 12" , "a mezzogiorno" ] , examples (datetime (2013, 2, 13, 0, 0, 0) Hour) [ "alle 24" , "a mezzanotte" ] , examples (datetime (2013, 3, 1, 0, 0, 0) Month) [ "marzo" , "in marzo" ] , examples (datetime (2013, 8, 15, 0, 0, 0) Day) [ "gio 15" ] , examples (datetime (2013, 2, 5, 4, 0, 0) Hour) [ "7 giorni fa" ] , examples (datetime (2013, 2, 5, 0, 0, 0) Day) [ "una settimana fa" , "1 settimana fa" ] , examples (datetime (2013, 1, 22, 0, 0, 0) Day) [ "tre settimane fa" , "3 settimane fa" ] , examples (datetime (2012, 11, 12, 0, 0, 0) Day) [ "tre mesi fa" , "3 mesi fa" ] , examples (datetime (2011, 2, 1, 0, 0, 0) Month) [ "due anni fa" , "2 anni fa" ] , examples (datetimeHoliday (2013, 12, 18, 0, 0, 0) Day "Giornata della lingua araba") [ "giornata della lingua araba" ] , examples (datetimeHoliday (2013, 3, 1, 0, 0, 0) Day "Giornata Mondiale contro la discriminazione") [ "giornata mondiale contro la discriminazione" ] , examples (datetimeHoliday (2019, 7, 6, 0, 0, 0) Day "Giornata Internazionale delle cooperative") [ "giornata internazionale delle cooperative del 2019" ] , examples (datetimeHoliday (2013, 11, 17, 0, 0, 0) Day "Giornata Mondiale della Prematurità") [ "giornata mondiale dei prematuri" , "giornata mondiale della prematurita" , "giornata mondiale della prematurità" ] , examples (datetimeHoliday (2013, 5, 25, 0, 0, 0) Day "Giornata dell'Africa") [ "giornata della liberazione africana" , "giornata dell'unità africana" , "giornata dell'africa" ] ]
facebookincubator/duckling
Duckling/Time/IT/Corpus.hs
bsd-3-clause
31,606
0
11
13,090
9,351
5,707
3,644
656
1
module Problem13 where main :: IO () main = do contents <- readFile "txt/13.txt" putStrLn . take 10 . show . sum . map read . lines $ contents
adityagupta1089/Project-Euler-Haskell
src/problems/Problem13.hs
bsd-3-clause
152
0
13
38
62
30
32
5
1
-- Push the load average (read from /proc/loadavg) to graphite (i.e. to the -- carbon-cache process in a normal graphite setup). -- Code similar to the graphite-client.py example program. module Main (main) where import Control.Applicative ((<$>)) import Data.Time.Clock.POSIX (getPOSIXTime) import Network.Socket import Network.BSD import Data.List import System.Environment (getArgs) import System.IO -- carbon-cache server: -- hostname = "127.0.0.1" -- port = "2003" main :: IO () main = do [hostname, port] <- getArgs now <- (show . floor . toRational) <$> getPOSIXTime content <- readFile "/proc/loadavg" putStr content -- TODO explosive constructs let average1 = (read . (!! 0) $ words content) :: Float average5 = (read . (!! 1) $ words content) :: Float average15 = (read . (!! 2) $ words content) :: Float addrinfos <- getAddrInfo Nothing (Just hostname) (Just port) let serveraddr = head addrinfos sock <- socket (addrFamily serveraddr) Stream defaultProtocol connect sock (addrAddress serveraddr) h <- socketToHandle sock WriteMode hPutStrLn h $ "system.load-average.01min " ++ show average1 ++ " " ++ now hPutStrLn h $ "system.load-average.05min " ++ show average5 ++ " " ++ now hPutStrLn h $ "system.load-average.15min " ++ show average15 ++ " " ++ now hClose h
noteed/curved
bin/curved-load-average.hs
bsd-3-clause
1,324
0
13
244
383
197
186
26
1
{-| module: Bot.Scripting Defines the callbacks that will be called on events. The bot /tries/ to apply all callbacks to all events, but will ignore any that fail to pattern-match on their arguments. This means that to define a callback for a certain message, you just need to write a fuction that only pattern-matches to that kind of message. Message structures are defined in 'Msg' For example, the message structure for a PRIVMSG is @(SPrivMsg Sender Recipient text)@, and more specifically, messages to channels from users would be @(SPrivmsg (SUser nick user host) (RChannel chan) text@. So if we want a callback to be called for all channel messages from users, echoing the message received, we would define a callback function > echoCallback :: SEvent -> Bot () > echoCallback (SPrivmsg (SUser nick _ _) ch@(RChannel _) text) = > writeMsg $ CMsg PRIVMSG [show ch, "Echoing: " ++ text] The Bot monad allows callbacks to access IO functions (via @liftIO@) and a stateful store of global variables. Callbacks can simply use keys defined anywhere; 'Run' doesn't need to know about them, unlike the callbacks. -} module Bot.Scripting ( callbacks ) where import Bot.Bot (Bot) import Bot.Msg (SEvent) import qualified Bot.Scripting.Core as C import qualified Bot.Scripting.Vote as V import qualified Bot.Scripting.Flood as F import qualified Bot.Scripting.Laws as L import qualified Bot.Scripting.Example as Ex -- | The list of callbacks the bot should try to apply. callbacks :: [SEvent -> Bot ()] callbacks = concat [ C.callbacks , V.callbacks , F.callbacks , L.callbacks ]
cyclohexanamine/haskbot
src/Bot/Scripting.hs
bsd-3-clause
1,664
0
8
341
123
81
42
13
1
{-# LANGUAGE EmptyDataDecls #-} module Code06 where import Data.List type Data = [Datum] -- Specification candidates :: Data -> [Candidate] value :: Candidate -> Value good :: Value -> Bool solutions :: Data -> [Candidate] solutions0 :: Data -> [Candidate] solutions0 = filter (good . value) . candidates0 candidates0 :: Data -> [Candidate] candidates0 = foldr extend [] extend :: Datum -> [Candidate] -> [Candidate] extend' :: Datum -> [Candidate] -> [Candidate] extend' x = filter (ok . value) . extend x ok :: Value -> Bool ok = undefined candidates1 :: Data -> [(Candidate, Value)] candidates1 = map (fork (id, value)) . foldr extend' [] -- Utility fork :: (a -> b, a -> c) -> a -> (b,c) fork (f,g) x = (f x, g x) cross :: (a -> b, c -> d) -> (a,c) -> (b,d) cross (f,g) (x,y) = (f x,g y) zipp :: ([a],[b]) -> [(a,b)] zipp = uncurry zip -- solutions1 :: Data -> [Candidate] solutions1 = map fst . filter (good . snd) . foldr expand1 [] expand1 :: Datum -> [(Candidate, Value)] -> [(Candidate, Value)] expand1 x = filter (ok . snd) . zipp . cross (extend x, modify x) . unzip -- modify :: Value -> [Value] modify = undefined -- Making Century type Datum = Digit type Candidate = Expression type Value = Int candidates = expressions value = valExpr good = (100 ==) solutions = filter (good . value) . candidates extend x [] = [[[[x]]]] extend x es = concatMap (glue x) es type Expression = [Term] type Term = [Factor] type Factor = [Digit] type Digit = Int showDigit :: Digit -> String showDigit = show showFactor :: Factor -> String showFactor = concatMap showDigit showTerm :: Term -> String showTerm = concat . intersperse "×" . map showFactor showExpr :: Expression -> String showExpr e = show (valExpr e) ++ " = " ++ concat (intersperse "+" (map showTerm e)) valExpr :: Expression -> Int valExpr = sum . map valTerm valTerm :: Term -> Int valTerm = product . map valFact valFact :: Factor -> Int valFact = foldl1 (\ n d -> 10 * n + d) expressions0 :: [Digit] -> [Expression] expressions0 = concatMap partitions . partitions partitions :: [a] -> [[[a]]] partitions [] = [[]] partitions (x:xs) = [[x]:p | p <- ps] ++ [(x:ys):yss | ys:yss <- ps] where ps = partitions xs expressions :: [Digit] -> [Expression] expressions = foldr extend [] glue :: Digit -> Expression -> [Expression] glue x ((xs:xss):xsss) = [((x:xs):xss):xsss ,([x]:xs:xss):xsss ,[[x]]:(xs:xss):xsss ] -- century :: [Expression] century = solutions [1..9] -- type Value' = (Value,Value,Value,Value) value' :: Candidate -> Value' value' ((xs:xss):xsss) = (10^length xs,valFact xs,valTerm xss,valExpr xsss) modify' :: Datum -> Value' -> [Value'] modify' x (k,f,t,e) = [(10*k,k*x+f,t,e),(10,x,f*t,e),(10,x,1,f*t+e)] good' :: Value -> Value' -> Bool good' c (k,f,t,e) = f*t+e == c ok' :: Value -> Value' -> Bool ok' c (k,f,t,e) = f*t+e <= c solutions' :: Value -> Data -> [Candidate] solutions' c = map fst . filter (good' c . snd) . foldr (expand' c) [] expand'0 :: Datum -> Datum -> [(Candidate, Value')] -> [(Candidate, Value')] expand'0 c x = filter (ok' c . snd) . zipp . cross (extend x, modify x) . unzip expand' :: Datum -> Datum -> [(Candidate,Value')] -> [(Candidate,Value')] expand' c x [] = [([[[x]]],(10,x,1,0))] expand' c x evs = concatMap (filter (ok' c . snd) . glue' x) evs glue' :: Datum -> (Candidate, Value') -> [(Candidate, Value')] glue' x ((xs:xss):xsss,(k,f,t,e)) = [(((x:xs):xss):xsss,(10*k,k*x+f,t,e)) ,(([x]:xs:xss):xsss,(10,x,f*t,e)) ,([[x]]:(xs:xss):xsss,(10,x,1,f*t+e)) ] -- komachi :: Digit -> [Digit] -> [Expression] komachi = solutions'
sampou-org/pfad
Code/Code06.hs
bsd-3-clause
3,879
0
11
944
1,939
1,091
848
95
1
module Rules.Test (testRules, runTestGhcFlags, timeoutProgPath) where import Base import Expression import GHC import Oracles.Flag import Oracles.Setting import Target import Utilities import System.Environment -- TODO: clean up after testing testRules :: Rules () testRules = do root <- buildRootRules root -/- timeoutPyPath ~> do copyFile "testsuite/timeout/timeout.py" (root -/- timeoutPyPath) -- TODO windows is still not supported. -- -- See: https://github.com/ghc/ghc/blob/master/testsuite/timeout/Makefile#L23 root -/- timeoutProgPath ~> do python <- builderPath Python need [root -/- timeoutPyPath] let script = unlines [ "#!/usr/bin/env sh" , "exec " ++ python ++ " $0.py \"$@\"" ] liftIO $ do writeFile (root -/- timeoutProgPath) script makeExecutable (root -/- timeoutProgPath) "validate" ~> do needTestBuilders build $ target (vanillaContext Stage2 compiler) (Make "testsuite/tests") [] [] "test" ~> do needTestBuilders -- Prepare the timeout program. need [ root -/- timeoutProgPath ] -- TODO This approach doesn't work. -- Set environment variables for test's Makefile. env <- sequence [ builderEnvironment "MAKE" $ Make "" , builderEnvironment "TEST_HC" $ Ghc CompileHs Stage2 , AddEnv "TEST_HC_OPTS" <$> runTestGhcFlags ] makePath <- builderPath $ Make "" top <- topDirectory ghcPath <- (top -/-) <$> builderPath (Ghc CompileHs Stage2) ghcFlags <- runTestGhcFlags -- Set environment variables for test's Makefile. liftIO $ do setEnv "MAKE" makePath setEnv "TEST_HC" ghcPath setEnv "TEST_HC_OPTS" ghcFlags -- Execute the test target. buildWithCmdOptions env $ target (vanillaContext Stage2 compiler) RunTest [] [] needTestBuilders :: Action () needTestBuilders = do needBuilder $ Ghc CompileHs Stage2 needBuilder $ GhcPkg Update Stage1 needBuilder Hp2Ps needBuilder Hpc needBuilder (Hsc2Hs Stage1) -- | Extra flags to send to the Haskell compiler to run tests. runTestGhcFlags :: Action String runTestGhcFlags = do unregisterised <- flag GhcUnregisterised let ifMinGhcVer ver opt = do v <- ghcCanonVersion if ver <= v then pure opt else pure "" -- Read extra argument for test from command line, like `-fvectorize`. ghcOpts <- fromMaybe "" <$> (liftIO $ lookupEnv "EXTRA_HC_OPTS") -- See: https://github.com/ghc/ghc/blob/master/testsuite/mk/test.mk#L28 let ghcExtraFlags = if unregisterised then "-optc-fno-builtin" else "" -- Take flags to send to the Haskell compiler from test.mk. -- See: https://github.com/ghc/ghc/blob/master/testsuite/mk/test.mk#L37 unwords <$> sequence [ pure " -dcore-lint -dcmm-lint -no-user-package-db -rtsopts" , pure ghcOpts , pure ghcExtraFlags , ifMinGhcVer "711" "-fno-warn-missed-specialisations" , ifMinGhcVer "711" "-fshow-warning-groups" , ifMinGhcVer "801" "-fdiagnostics-color=never" , ifMinGhcVer "801" "-fno-diagnostics-show-caret" , pure "-dno-debug-output" ] timeoutPyPath :: FilePath timeoutPyPath = "test/bin/timeout.py" timeoutProgPath :: FilePath timeoutProgPath = "test/bin/timeout" <.> exe
bgamari/shaking-up-ghc
src/Rules/Test.hs
bsd-3-clause
3,604
4
17
1,033
710
337
373
72
3
-- (c) 2000-2005 by Martin Erwig [see file COPYRIGHT] -- | Graph Voronoi Diagram -- -- These functions can be used to create a /shortest path forest/ -- where the roots are specified. module Data.Graph.Inductive.Query.GVD ( Voronoi,LRTree, gvdIn,gvdOut, voronoiSet,nearestNode,nearestDist,nearestPath, -- vd,nn,ns, -- vdO,nnO,nsO ) where import Data.List (nub) import Data.Maybe (listToMaybe) import qualified Data.Graph.Inductive.Internal.Heap as H import Data.Graph.Inductive.Basic import Data.Graph.Inductive.Graph import Data.Graph.Inductive.Internal.RootPath import Data.Graph.Inductive.Query.SP (dijkstra) -- | Representation of a shortest path forest. type Voronoi a = LRTree a -- | Produce a shortest path forest (the roots of which are those -- nodes specified) from nodes in the graph /to/ one of the root -- nodes (if possible). gvdIn :: (DynGraph gr, Real b) => [Node] -> gr a b -> Voronoi b gvdIn vs g = gvdOut vs (grev g) -- | Produce a shortest path forest (the roots of which are those -- nodes specified) from nodes in the graph /from/ one of the root -- nodes (if possible). gvdOut :: (Graph gr, Real b) => [Node] -> gr a b -> Voronoi b gvdOut vs = dijkstra (H.build (zip (repeat 0) (map (\v->LP [(v,0)]) vs))) -- | Return the nodes reachable to/from (depending on how the -- 'Voronoi' was constructed) from the specified root node (if the -- specified node is not one of the root nodes of the shortest path -- forest, an empty list will be returned). voronoiSet :: (Real b) => Node -> Voronoi b -> [Node] voronoiSet v = nub . concat . filter (\p->last p==v) . map (map fst . unLPath) -- | Try to construct a path to/from a specified node to one of the -- root nodes of the shortest path forest. maybePath :: (Real b) => Node -> Voronoi b -> Maybe (LPath b) maybePath v = listToMaybe . filter ((v==) . fst . head . unLPath) -- | Try to determine the nearest root node to the one specified in the -- shortest path forest. nearestNode :: (Real b) => Node -> Voronoi b -> Maybe Node nearestNode v = fmap (fst . last . unLPath) . maybePath v -- | The distance to the 'nearestNode' (if there is one) in the -- shortest path forest. nearestDist :: (Real b) => Node -> Voronoi b -> Maybe b nearestDist v = fmap (snd . head . unLPath) . maybePath v -- | Try to construct a path to/from a specified node to one of the -- root nodes of the shortest path forest. nearestPath :: (Real b) => Node -> Voronoi b -> Maybe Path nearestPath v = fmap (map fst . unLPath) . maybePath v -- vd = gvdIn [4,5] vor -- vdO = gvdOut [4,5] vor -- nn = map (flip nearestNode vd) [1..8] -- nnO = map (flip nearestNode vdO) [1..8] -- ns = map (flip voronoiSet vd) [1..8] -- nsO = map (flip voronoiSet vdO) [1..8]
scolobb/fgl
Data/Graph/Inductive/Query/GVD.hs
bsd-3-clause
2,767
0
16
550
621
349
272
26
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE NoImplicitPrelude #-} -- | The client. module Language.Fay.ReactiveMvc where import Language.Fay.FFI import Language.Fay.Guid import Language.Fay.Prelude import Language.Fay.Ref -------------------------------------------------------------------------------- -- Reactive API -- Model -- | A model. data Model a = Model { modelGuid :: Guid , modelValue :: Ref a , modelCallbacks :: Ref [Callback a] } -- | A callback on a model's events. data Callback a = Callback Guid EventType (a -> Fay ()) instance Foreign a => Foreign (Callback a) instance Foreign a => Foreign (Maybe a) -- | An event type a callback can be called for. data EventType = Change | Delete deriving (Eq) -- | Make a new model containing the given value. newModel :: Foreign a => a -> Fay (Model a) newModel value = do guid <- newGuid value_ref <- newRef value callbacks_ref <- newRef [] return (Model guid value_ref callbacks_ref) -- | Delete the given model. This signals delete to all the subscribed -- views. deleteModel :: Foreign a => Model a -> Fay () deleteModel (Model _ value_ref callbacks_ref) = do value <- readRef value_ref callbacks <- readRef callbacks_ref forM_ callbacks $ \(Callback _ typ action) -> when (typ == Delete) $ action value writeRef callbacks_ref [] -- | Put a new value in the model, this signals a change to all the -- subscribed views. putModel :: Foreign a => Model a -> a -> Fay () putModel (Model _ value_ref callbacks_ref) value = do writeRef value_ref value callbacks <- readRef callbacks_ref forM_ callbacks $ \(Callback _ typ action) -> when (typ == Change) $ action value -- | Get the value in the model. getModel :: Foreign a => Model a -> Fay a getModel (Model _ value_ref _) = do readRef value_ref -- | Modify the given model. modifyModel :: Foreign a => Model a -> (a -> a) -> Fay () modifyModel model f = do value <- getModel model putModel model (f value) -- View -- | A view of a model containing a value. data View a view = View { viewGuid :: Guid , viewModel :: Model a , viewRender :: a -> Fay view } -- | Make a new view on the given model. newView :: Model a -> (a -> Fay view) -> Fay (View a view) newView model render = do guid <- newGuid return (View guid model render) -- | Delete the view. This removes all callbacks attached to any -- models. deleteView :: Foreign a => View a view -> Fay () deleteView (View guid (Model _ _ callbacks_ref) _) = do callbacks <- readRef callbacks_ref writeRef callbacks_ref (filter (\(Callback cguid _ _) -> cguid /= guid) callbacks) -- | Bind an event handler for the view. viewReact :: Foreign a => EventType -> View a view -> (a -> Fay ()) -> Fay () viewReact typ (View guid (Model _ _ callbacks_ref) _) action = do callbacks <- readRef callbacks_ref writeRef callbacks_ref (callbacks ++ [Callback guid typ action]) -- | Bind an event handler for the model. modelReact :: Foreign a => EventType -> Model x -> Model a -> (a -> Fay ()) -> Fay () modelReact typ (Model guid _ _) (Model _ _ callbacks_ref) action = do callbacks <- readRef callbacks_ref writeRef callbacks_ref (callbacks ++ [Callback guid typ action]) -- | Render the view with the model's value. renderView :: Foreign a => View a view -> Fay view renderView (View _ (Model _ value_ref _) action) = do value <- readRef value_ref action value -------------------------------------------------------------------------------- -- Utilities (&) :: Fay a -> (a -> Fay b) -> Fay b x & y = x >>= y infixl 1 & instance (Foreign a,Foreign b) => Foreign (a,b)
faylang/fay-server
modules/library/Language/Fay/ReactiveMvc.hs
bsd-3-clause
3,728
0
13
777
1,188
592
596
76
1
{-# LANGUAGE TypeOperators #-} module Zero.Account.Server ( accountViewServer , accountServer ) where import Servant (Server) import Servant.API import Zero.Persistence import Zero.Account.API import Zero.Index.Handlers (index) import Zero.Account.Handlers (getAccountStatus) import Zero.Account.Profile.Handlers import Zero.SessionToken.Internal (SessionToken) import Zero.SessionToken.Server import Zero.ContentTypes ------------------------------------------------------------------------------ accountViewServer :: SessionId -> Connection -> Server AccountViewAPI accountViewServer sid conn = index :<|> profile accountServer :: SessionId -> Connection -> Server AccountAPI accountServer sid conn = getAccountStatus sid conn
et4te/zero
server/src/Zero/Account/Server.hs
bsd-3-clause
865
0
7
203
153
90
63
22
1
{-# LANGUAGE FlexibleInstances #-} module Ebitor.Events.JSON ( Key(..) , Modifier(..) , Button(..) , Event(..) , eventToString , eventsToString ) where import Control.Applicative (pure) import Control.Monad (mzero) import Data.List (foldl') import Data.Aeson import Data.List import qualified Data.Text.Lazy as T import qualified Data.Text.Lazy.Encoding as T import Ebitor.Events import Ebitor.Language keyToString :: Key -> String keyToString KEsc = "Esc" keyToString (KChar '<') = "\\<" keyToString (KChar '\\') = "\\\\" keyToString (KChar c) = [c] keyToString KBS = "BS" keyToString KEnter = "Enter" keyToString KLeft = "Left" keyToString KRight = "Right" keyToString KUp = "Up" keyToString KDown = "Down" keyToString KUpLeft = "UpLeft" keyToString KUpRight = "UpRight" keyToString KDownLeft = "DownLeft" keyToString KDownRight = "DownRight" keyToString KCenter = "Center" keyToString (KFun i) = "F" ++ show i keyToString KBackTab = "BackTab" keyToString KPrtScr = "PrtScr" keyToString KPause = "Pause" keyToString KIns = "Ins" keyToString KHome = "Home" keyToString KPageUp = "PageUp" keyToString KDel = "Del" keyToString KEnd = "End" keyToString KPageDown = "PageDown" keyToString KBegin = "Begin" keyToString KMenu = "Menu" modifierToString :: Modifier -> String modifierToString MShift = "S" modifierToString MCtrl = "C" modifierToString MMeta = "M" modifierToString MAlt = "A" eventToString :: Event -> String eventToString (EvKey k@(KChar _) []) = keyToString k eventToString (EvKey k []) = "<" ++ keyToString k ++ ">" eventToString (EvKey k mods) = let m = intercalate "-" $ map modifierToString mods in "<" ++ m ++ "-" ++ keyToString k ++ ">" eventsToString :: [Event] -> String eventsToString evs = foldl' (++) "" $ map eventToString evs instance FromJSON [Event] where parseJSON = withText "String" doParse where doParse s = case parseKeyEvents s of Right evs -> pure evs Left e -> mzero instance ToJSON [Event] where toJSON evs = toJSON $ eventsToString evs
benekastah/ebitor
src/Ebitor/Events/JSON.hs
bsd-3-clause
2,064
0
11
381
660
348
312
65
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} -------------------------------------------------------------------------------- -- | The LLVM Type System. -- module Llvm.Types where #include "HsVersions.h" import Data.Char import Data.Int import Numeric import DynFlags import FastString import Outputable import Unique -- from NCG import PprBase import GHC.Float -- ----------------------------------------------------------------------------- -- * LLVM Basic Types and Variables -- -- | A global mutable variable. Maybe defined or external data LMGlobal = LMGlobal { getGlobalVar :: LlvmVar, -- ^ Returns the variable of the 'LMGlobal' getGlobalValue :: Maybe LlvmStatic -- ^ Return the value of the 'LMGlobal' } -- | A String in LLVM type LMString = FastString -- | A type alias type LlvmAlias = (LMString, LlvmType) -- | Llvm Types data LlvmType = LMInt Int -- ^ An integer with a given width in bits. | LMFloat -- ^ 32 bit floating point | LMDouble -- ^ 64 bit floating point | LMFloat80 -- ^ 80 bit (x86 only) floating point | LMFloat128 -- ^ 128 bit floating point | LMPointer LlvmType -- ^ A pointer to a 'LlvmType' | LMArray Int LlvmType -- ^ An array of 'LlvmType' | LMVector Int LlvmType -- ^ A vector of 'LlvmType' | LMLabel -- ^ A 'LlvmVar' can represent a label (address) | LMVoid -- ^ Void type | LMStruct [LlvmType] -- ^ Structure type | LMAlias LlvmAlias -- ^ A type alias | LMMetadata -- ^ LLVM Metadata -- | Function type, used to create pointers to functions | LMFunction LlvmFunctionDecl deriving (Eq) instance Outputable LlvmType where ppr (LMInt size ) = char 'i' <> ppr size ppr (LMFloat ) = text "float" ppr (LMDouble ) = text "double" ppr (LMFloat80 ) = text "x86_fp80" ppr (LMFloat128 ) = text "fp128" ppr (LMPointer x ) = ppr x <> char '*' ppr (LMArray nr tp ) = char '[' <> ppr nr <> text " x " <> ppr tp <> char ']' ppr (LMVector nr tp ) = char '<' <> ppr nr <> text " x " <> ppr tp <> char '>' ppr (LMLabel ) = text "label" ppr (LMVoid ) = text "void" ppr (LMStruct tys ) = text "<{" <> ppCommaJoin tys <> text "}>" ppr (LMMetadata ) = text "metadata" ppr (LMFunction (LlvmFunctionDecl _ _ _ r varg p _)) = ppr r <+> lparen <> ppParams varg p <> rparen ppr (LMAlias (s,_)) = char '%' <> ftext s -- | Shown types are not neccessarily pretty instance Show LlvmType where show (LMInt size ) = "i" ++ show size show (LMFloat ) = "float" show (LMDouble ) = "double" show (LMFloat80 ) = "x86_fp80" show (LMFloat128 ) = "fp128" show (LMPointer x ) = show x ++ "*" show (LMArray nr tp ) = "[" ++ show nr ++ "x" ++ show tp ++ "]" show (LMVector nr tp ) = "<" ++ show nr ++ "x" ++ show tp ++ ">" show (LMLabel ) = "label" show (LMVoid ) = "void" show (LMStruct tys ) = "<{" ++ (concat . map show) tys ++ "}>" show (LMMetadata ) = "metadata" show (LMFunction (LlvmFunctionDecl _ _ _ r varg p _)) = show r ++ "(" ++ (concat . map show) p ++ ")" -- ignore vararg distinction show (LMAlias (s,_)) = "%" ++ unpackFS s ppParams :: LlvmParameterListType -> [LlvmParameter] -> SDoc ppParams varg p = let varg' = case varg of VarArgs | null args -> sLit "..." | otherwise -> sLit ", ..." _otherwise -> sLit "" -- by default we don't print param attributes args = map fst p in ppCommaJoin args <> ptext varg' -- | An LLVM section definition. If Nothing then let LLVM decide the section type LMSection = Maybe LMString type LMAlign = Maybe Int data LMConst = Global -- ^ Mutable global variable | Constant -- ^ Constant global variable | Alias -- ^ Alias of another variable deriving (Eq) -- | LLVM Variables data LlvmVar -- | Variables with a global scope. = LMGlobalVar LMString LlvmType LlvmLinkageType LMSection LMAlign LMConst -- | Variables local to a function or parameters. | LMLocalVar Unique LlvmType -- | Named local variables. Sometimes we need to be able to explicitly name -- variables (e.g for function arguments). | LMNLocalVar LMString LlvmType -- | A constant variable | LMLitVar LlvmLit deriving (Eq) instance Outputable LlvmVar where ppr (LMLitVar x) = ppr x ppr (x ) = ppr (getVarType x) <+> ppName x instance Show LlvmVar where show (LMGlobalVar name ty link sec ali con) = "global " ++ (unpackFS name) ++ " Ty: " ++ (show ty) show (LMLocalVar uniq ty) = "unnamed local " ++ (show uniq) ++ " Ty: " ++ (show ty) show (LMNLocalVar name ty) = "named local " ++ (unpackFS name) ++ " Ty: " ++ (show ty) show (LMLitVar lit) = "Lit Var: " ++ show lit -- | Llvm Literal Data. -- -- These can be used inline in expressions. data LlvmLit -- | Refers to an integer constant (i64 42). = LMIntLit Integer LlvmType -- | Floating point literal | LMFloatLit Double LlvmType -- | Literal NULL, only applicable to pointer types | LMNullLit LlvmType -- | Vector literal | LMVectorLit [LlvmLit] -- | Undefined value, random bit pattern. Useful for optimisations. | LMUndefLit LlvmType deriving (Eq) instance Outputable LlvmLit where ppr l@(LMVectorLit {}) = ppLit l ppr l = ppr (getLitType l) <+> ppLit l instance Show LlvmLit where show (LMIntLit i (LMInt 32)) = show (fromInteger i :: Int32) show (LMIntLit i (LMInt 64)) = show (fromInteger i :: Int64) show (LMIntLit i _ ) = show ((fromInteger i)::Int) show (LMFloatLit r LMFloat ) = show r ++ " float" show (LMFloatLit r LMDouble) = show r ++ " double" show f@(LMFloatLit _ _) = error "failed to show float lit" show (LMVectorLit ls ) = (concat . map show) ls show (LMNullLit _ ) = "null" show (LMUndefLit _ ) = "undef" -- | Llvm Static Data. -- -- These represent the possible global level variables and constants. data LlvmStatic = LMComment LMString -- ^ A comment in a static section | LMStaticLit LlvmLit -- ^ A static variant of a literal value | LMUninitType LlvmType -- ^ For uninitialised data | LMStaticStr LMString LlvmType -- ^ Defines a static 'LMString' | LMStaticArray [LlvmStatic] LlvmType -- ^ A static array | LMStaticStruc [LlvmStatic] LlvmType -- ^ A static structure type | LMStaticPointer LlvmVar -- ^ A pointer to other data -- static expressions, could split out but leave -- for moment for ease of use. Not many of them. | LMBitc LlvmStatic LlvmType -- ^ Pointer to Pointer conversion | LMPtoI LlvmStatic LlvmType -- ^ Pointer to Integer conversion | LMAdd LlvmStatic LlvmStatic -- ^ Constant addition operation | LMSub LlvmStatic LlvmStatic -- ^ Constant subtraction operation instance Outputable LlvmStatic where ppr (LMComment s) = text "; " <> ftext s ppr (LMStaticLit l ) = ppr l ppr (LMUninitType t) = ppr t <> text " undef" ppr (LMStaticStr s t) = ppr t <> text " c\"" <> ftext s <> text "\\00\"" ppr (LMStaticArray d t) = ppr t <> text " [" <> ppCommaJoin d <> char ']' ppr (LMStaticStruc d t) = ppr t <> text "<{" <> ppCommaJoin d <> text "}>" ppr (LMStaticPointer v) = ppr v ppr (LMBitc v t) = ppr t <> text " bitcast (" <> ppr v <> text " to " <> ppr t <> char ')' ppr (LMPtoI v t) = ppr t <> text " ptrtoint (" <> ppr v <> text " to " <> ppr t <> char ')' ppr (LMAdd s1 s2) = pprStaticArith s1 s2 (sLit "add") (sLit "fadd") "LMAdd" ppr (LMSub s1 s2) = pprStaticArith s1 s2 (sLit "sub") (sLit "fsub") "LMSub" pprStaticArith :: LlvmStatic -> LlvmStatic -> LitString -> LitString -> String -> SDoc pprStaticArith s1 s2 int_op float_op op_name = let ty1 = getStatType s1 op = if isFloat ty1 then float_op else int_op in if ty1 == getStatType s2 then ppr ty1 <+> ptext op <+> lparen <> ppr s1 <> comma <> ppr s2 <> rparen else sdocWithDynFlags $ \dflags -> error $ op_name ++ " with different types! s1: " ++ showSDoc dflags (ppr s1) ++ ", s2: " ++ showSDoc dflags (ppr s2) -- ----------------------------------------------------------------------------- -- ** Operations on LLVM Basic Types and Variables -- -- | Return the variable name or value of the 'LlvmVar' -- in Llvm IR textual representation (e.g. @\@x@, @%y@ or @42@). ppName :: LlvmVar -> SDoc ppName v@(LMGlobalVar {}) = char '@' <> ppPlainName v ppName v@(LMLocalVar {}) = char '%' <> ppPlainName v ppName v@(LMNLocalVar {}) = char '%' <> ppPlainName v ppName v@(LMLitVar {}) = ppPlainName v -- | Return the variable name or value of the 'LlvmVar' -- in a plain textual representation (e.g. @x@, @y@ or @42@). ppPlainName :: LlvmVar -> SDoc ppPlainName (LMGlobalVar x _ _ _ _ _) = ftext x ppPlainName (LMLocalVar x LMLabel ) = text (show x) ppPlainName (LMLocalVar x _ ) = text ('l' : show x) ppPlainName (LMNLocalVar x _ ) = ftext x ppPlainName (LMLitVar x ) = ppLit x -- | Call ppPlainName but return a String instead of SDoc showPlainName :: DynFlags -> LlvmVar -> String showPlainName dflags var = (showSDoc dflags . ppPlainName) var -- | Print a literal value. No type. ppLit :: LlvmLit -> SDoc ppLit (LMIntLit i (LMInt 32)) = ppr (fromInteger i :: Int32) ppLit (LMIntLit i (LMInt 64)) = ppr (fromInteger i :: Int64) ppLit (LMIntLit i _ ) = ppr ((fromInteger i)::Int) ppLit (LMFloatLit r LMFloat ) = ppFloat $ narrowFp r ppLit (LMFloatLit r LMDouble) = ppDouble r ppLit f@(LMFloatLit _ _) = sdocWithDynFlags (\dflags -> error $ "Can't print this float literal!" ++ showSDoc dflags (ppr f)) ppLit (LMVectorLit ls ) = char '<' <+> ppCommaJoin ls <+> char '>' ppLit (LMNullLit _ ) = text "null" ppLit (LMUndefLit _ ) = text "undef" -- | Return the 'LlvmType' of the 'LlvmVar' getVarType :: LlvmVar -> LlvmType getVarType (LMGlobalVar _ y _ _ _ _) = y getVarType (LMLocalVar _ y ) = y getVarType (LMNLocalVar _ y ) = y getVarType (LMLitVar l ) = getLitType l -- | Return the 'LlvmType' of a 'LlvmLit' getLitType :: LlvmLit -> LlvmType getLitType (LMIntLit _ t) = t getLitType (LMFloatLit _ t) = t getLitType (LMVectorLit []) = panic "getLitType" getLitType (LMVectorLit ls) = LMVector (length ls) (getLitType (head ls)) getLitType (LMNullLit t) = t getLitType (LMUndefLit t) = t -- | Return the 'LlvmType' of the 'LlvmStatic' getStatType :: LlvmStatic -> LlvmType getStatType (LMStaticLit l ) = getLitType l getStatType (LMUninitType t) = t getStatType (LMStaticStr _ t) = t getStatType (LMStaticArray _ t) = t getStatType (LMStaticStruc _ t) = t getStatType (LMStaticPointer v) = getVarType v getStatType (LMBitc _ t) = t getStatType (LMPtoI _ t) = t getStatType (LMAdd t _) = getStatType t getStatType (LMSub t _) = getStatType t getStatType (LMComment _) = error "Can't call getStatType on LMComment!" -- | Return the 'LlvmLinkageType' for a 'LlvmVar' getLink :: LlvmVar -> LlvmLinkageType getLink (LMGlobalVar _ _ l _ _ _) = l getLink _ = Internal getElemType :: LlvmType -> LlvmType getElemType (LMPointer ty) = ty getElemType (LMArray l ty) = ty getElemType (LMVector l ty) = ty getElemType x = error $ (show x) ++ " does not have elements" -- | Add a pointer indirection to the supplied type. 'LMLabel' and 'LMVoid' -- cannot be lifted. pLift :: LlvmType -> LlvmType pLift LMLabel = error "Labels are unliftable" pLift LMVoid = error "Voids are unliftable" pLift LMMetadata = error "Metadatas are unliftable" pLift x = LMPointer x -- | Lower a variable of 'LMPointer' type. pVarLift :: LlvmVar -> LlvmVar pVarLift (LMGlobalVar s t l x a c) = LMGlobalVar s (pLift t) l x a c pVarLift (LMLocalVar s t ) = LMLocalVar s (pLift t) pVarLift (LMNLocalVar s t ) = LMNLocalVar s (pLift t) pVarLift (LMLitVar _ ) = error $ "Can't lift a literal type!" -- | Remove the pointer indirection of the supplied type. Only 'LMPointer' -- constructors can be lowered. pLower :: LlvmType -> LlvmType pLower (LMPointer x) = x pLower x = error $ "Can't lower a non-pointer type: " ++ show x --showSDoc undefined (ppr x) ++ " is a unlowerable type, need a pointer" -- | Lower a variable of 'LMPointer' type. pVarLower :: LlvmVar -> LlvmVar pVarLower (LMGlobalVar s t l x a c) = LMGlobalVar s (pLower t) l x a c pVarLower (LMLocalVar s t ) = LMLocalVar s (pLower t) pVarLower (LMNLocalVar s t ) = LMNLocalVar s (pLower t) pVarLower (LMLitVar _ ) = error $ "Can't lower a literal type!" -- | Test if the given 'LlvmType' is an integer isInt :: LlvmType -> Bool isInt (LMInt _) = True isInt _ = False -- | Test if the given 'LlvmType' is a floating point type isFloat :: LlvmType -> Bool isFloat LMFloat = True isFloat LMDouble = True isFloat LMFloat80 = True isFloat LMFloat128 = True isFloat _ = False -- | Test if the given 'LlvmType' is an 'LMPointer' construct isPointer :: LlvmType -> Bool isPointer (LMPointer _) = True isPointer _ = False -- | Test if the given 'LlvmType' is an 'LMVector' construct isVector :: LlvmType -> Bool isVector (LMVector {}) = True isVector _ = False -- | Test if a 'LlvmVar' is global. isGlobal :: LlvmVar -> Bool isGlobal (LMGlobalVar _ _ _ _ _ _) = True isGlobal _ = False -- | Width in bits of an 'LlvmType', returns 0 if not applicable llvmWidthInBits :: DynFlags -> LlvmType -> Int llvmWidthInBits _ (LMInt n) = n llvmWidthInBits _ (LMFloat) = 32 llvmWidthInBits _ (LMDouble) = 64 llvmWidthInBits _ (LMFloat80) = 80 llvmWidthInBits _ (LMFloat128) = 128 -- Could return either a pointer width here or the width of what -- it points to. We will go with the former for now. -- PMW: At least judging by the way LLVM outputs constants, pointers -- should use the former, but arrays the latter. llvmWidthInBits dflags (LMPointer _) = llvmWidthInBits dflags (llvmWord dflags) llvmWidthInBits dflags (LMArray n t) = n * llvmWidthInBits dflags t llvmWidthInBits dflags (LMVector n ty) = n * llvmWidthInBits dflags ty llvmWidthInBits _ LMLabel = 0 llvmWidthInBits _ LMVoid = 0 llvmWidthInBits dflags (LMStruct tys) = sum $ map (llvmWidthInBits dflags) tys llvmWidthInBits _ (LMFunction _) = 0 llvmWidthInBits dflags (LMAlias (_,t)) = llvmWidthInBits dflags t llvmWidthInBits _ LMMetadata = panic "llvmWidthInBits: Meta-data has no runtime representation!" -- ----------------------------------------------------------------------------- -- ** Shortcut for Common Types -- i128, i64, i32, i16, i8, i1, i8Ptr :: LlvmType i128 = LMInt 128 i64 = LMInt 64 i32 = LMInt 32 i16 = LMInt 16 i8 = LMInt 8 i1 = LMInt 1 i8Ptr = pLift i8 -- | The target architectures word size llvmWord, llvmWordPtr :: DynFlags -> LlvmType llvmWord dflags = LMInt (wORD_SIZE dflags * 8) llvmWordPtr dflags = pLift (llvmWord dflags) -- ----------------------------------------------------------------------------- -- * LLVM Function Types -- -- | An LLVM Function data LlvmFunctionDecl = LlvmFunctionDecl { -- | Unique identifier of the function decName :: LMString, -- | LinkageType of the function funcLinkage :: LlvmLinkageType, -- | The calling convention of the function funcCc :: LlvmCallConvention, -- | Type of the returned value decReturnType :: LlvmType, -- | Indicates if this function uses varargs decVarargs :: LlvmParameterListType, -- | Parameter types and attributes decParams :: [LlvmParameter], -- | Function align value, must be power of 2 funcAlign :: LMAlign } deriving (Eq) instance Outputable LlvmFunctionDecl where ppr (LlvmFunctionDecl n l c r varg p a) = let align = case a of Just a' -> text " align " <> ppr a' Nothing -> empty in ppr l <+> ppr c <+> ppr r <+> char '@' <> ftext n <> lparen <> ppParams varg p <> rparen <> align type LlvmFunctionDecls = [LlvmFunctionDecl] type LlvmParameter = (LlvmType, [LlvmParamAttr]) -- | LLVM Parameter Attributes. -- -- Parameter attributes are used to communicate additional information about -- the result or parameters of a function data LlvmParamAttr -- | This indicates to the code generator that the parameter or return value -- should be zero-extended to a 32-bit value by the caller (for a parameter) -- or the callee (for a return value). = ZeroExt -- | This indicates to the code generator that the parameter or return value -- should be sign-extended to a 32-bit value by the caller (for a parameter) -- or the callee (for a return value). | SignExt -- | This indicates that this parameter or return value should be treated in -- a special target-dependent fashion during while emitting code for a -- function call or return (usually, by putting it in a register as opposed -- to memory). | InReg -- | This indicates that the pointer parameter should really be passed by -- value to the function. | ByVal -- | This indicates that the pointer parameter specifies the address of a -- structure that is the return value of the function in the source program. | SRet -- | This indicates that the pointer does not alias any global or any other -- parameter. | NoAlias -- | This indicates that the callee does not make any copies of the pointer -- that outlive the callee itself | NoCapture -- | This indicates that the pointer parameter can be excised using the -- trampoline intrinsics. | Nest deriving (Eq) instance Outputable LlvmParamAttr where ppr ZeroExt = text "zeroext" ppr SignExt = text "signext" ppr InReg = text "inreg" ppr ByVal = text "byval" ppr SRet = text "sret" ppr NoAlias = text "noalias" ppr NoCapture = text "nocapture" ppr Nest = text "nest" instance Show LlvmParamAttr where show ZeroExt = "zeroext" show SignExt = "signext" show InReg = "inreg" show ByVal = "byval" show SRet = "sret" show NoAlias = "noalias" show NoCapture = "nocapture" show Nest = "nest" -- | Llvm Function Attributes. -- -- Function attributes are set to communicate additional information about a -- function. Function attributes are considered to be part of the function, -- not of the function type, so functions with different parameter attributes -- can have the same function type. Functions can have multiple attributes. -- -- Descriptions taken from <http://llvm.org/docs/LangRef.html#fnattrs> data LlvmFuncAttr -- | This attribute indicates that the inliner should attempt to inline this -- function into callers whenever possible, ignoring any active inlining -- size threshold for this caller. = AlwaysInline -- | This attribute indicates that the source code contained a hint that -- inlining this function is desirable (such as the \"inline\" keyword in -- C/C++). It is just a hint; it imposes no requirements on the inliner. | InlineHint -- | This attribute indicates that the inliner should never inline this -- function in any situation. This attribute may not be used together -- with the alwaysinline attribute. | NoInline -- | This attribute suggests that optimization passes and code generator -- passes make choices that keep the code size of this function low, and -- otherwise do optimizations specifically to reduce code size. | OptSize -- | This function attribute indicates that the function never returns -- normally. This produces undefined behavior at runtime if the function -- ever does dynamically return. | NoReturn -- | This function attribute indicates that the function never returns with -- an unwind or exceptional control flow. If the function does unwind, its -- runtime behavior is undefined. | NoUnwind -- | This attribute indicates that the function computes its result (or -- decides to unwind an exception) based strictly on its arguments, without -- dereferencing any pointer arguments or otherwise accessing any mutable -- state (e.g. memory, control registers, etc) visible to caller functions. -- It does not write through any pointer arguments (including byval -- arguments) and never changes any state visible to callers. This means -- that it cannot unwind exceptions by calling the C++ exception throwing -- methods, but could use the unwind instruction. | ReadNone -- | This attribute indicates that the function does not write through any -- pointer arguments (including byval arguments) or otherwise modify any -- state (e.g. memory, control registers, etc) visible to caller functions. -- It may dereference pointer arguments and read state that may be set in -- the caller. A readonly function always returns the same value (or unwinds -- an exception identically) when called with the same set of arguments and -- global state. It cannot unwind an exception by calling the C++ exception -- throwing methods, but may use the unwind instruction. | ReadOnly -- | This attribute indicates that the function should emit a stack smashing -- protector. It is in the form of a \"canary\"—a random value placed on the -- stack before the local variables that's checked upon return from the -- function to see if it has been overwritten. A heuristic is used to -- determine if a function needs stack protectors or not. -- -- If a function that has an ssp attribute is inlined into a function that -- doesn't have an ssp attribute, then the resulting function will have an -- ssp attribute. | Ssp -- | This attribute indicates that the function should always emit a stack -- smashing protector. This overrides the ssp function attribute. -- -- If a function that has an sspreq attribute is inlined into a function -- that doesn't have an sspreq attribute or which has an ssp attribute, -- then the resulting function will have an sspreq attribute. | SspReq -- | This attribute indicates that the code generator should not use a red -- zone, even if the target-specific ABI normally permits it. | NoRedZone -- | This attributes disables implicit floating point instructions. | NoImplicitFloat -- | This attribute disables prologue / epilogue emission for the function. -- This can have very system-specific consequences. | Naked deriving (Eq) instance Outputable LlvmFuncAttr where ppr AlwaysInline = text "alwaysinline" ppr InlineHint = text "inlinehint" ppr NoInline = text "noinline" ppr OptSize = text "optsize" ppr NoReturn = text "noreturn" ppr NoUnwind = text "nounwind" ppr ReadNone = text "readnon" ppr ReadOnly = text "readonly" ppr Ssp = text "ssp" ppr SspReq = text "ssqreq" ppr NoRedZone = text "noredzone" ppr NoImplicitFloat = text "noimplicitfloat" ppr Naked = text "naked" -- | Different types to call a function. data LlvmCallType -- | Normal call, allocate a new stack frame. = StdCall -- | Tail call, perform the call in the current stack frame. | TailCall deriving (Eq,Show) -- | Different calling conventions a function can use. data LlvmCallConvention -- | The C calling convention. -- This calling convention (the default if no other calling convention is -- specified) matches the target C calling conventions. This calling -- convention supports varargs function calls and tolerates some mismatch in -- the declared prototype and implemented declaration of the function (as -- does normal C). = CC_Ccc -- | This calling convention attempts to make calls as fast as possible -- (e.g. by passing things in registers). This calling convention allows -- the target to use whatever tricks it wants to produce fast code for the -- target, without having to conform to an externally specified ABI -- (Application Binary Interface). Implementations of this convention should -- allow arbitrary tail call optimization to be supported. This calling -- convention does not support varargs and requires the prototype of al -- callees to exactly match the prototype of the function definition. | CC_Fastcc -- | This calling convention attempts to make code in the caller as efficient -- as possible under the assumption that the call is not commonly executed. -- As such, these calls often preserve all registers so that the call does -- not break any live ranges in the caller side. This calling convention -- does not support varargs and requires the prototype of all callees to -- exactly match the prototype of the function definition. | CC_Coldcc -- | Any calling convention may be specified by number, allowing -- target-specific calling conventions to be used. Target specific calling -- conventions start at 64. | CC_Ncc Int -- | X86 Specific 'StdCall' convention. LLVM includes a specific alias for it -- rather than just using CC_Ncc. | CC_X86_Stdcc deriving (Eq) instance Outputable LlvmCallConvention where ppr CC_Ccc = text "ccc" ppr CC_Fastcc = text "fastcc" ppr CC_Coldcc = text "coldcc" ppr (CC_Ncc i) = text "cc " <> ppr i ppr CC_X86_Stdcc = text "x86_stdcallcc" -- | Functions can have a fixed amount of parameters, or a variable amount. data LlvmParameterListType -- Fixed amount of arguments. = FixedArgs -- Variable amount of arguments. | VarArgs deriving (Eq,Show) -- | Linkage type of a symbol. -- -- The description of the constructors is copied from the Llvm Assembly Language -- Reference Manual <http://www.llvm.org/docs/LangRef.html#linkage>, because -- they correspond to the Llvm linkage types. data LlvmLinkageType -- | Global values with internal linkage are only directly accessible by -- objects in the current module. In particular, linking code into a module -- with an internal global value may cause the internal to be renamed as -- necessary to avoid collisions. Because the symbol is internal to the -- module, all references can be updated. This corresponds to the notion -- of the @static@ keyword in C. = Internal -- | Globals with @linkonce@ linkage are merged with other globals of the -- same name when linkage occurs. This is typically used to implement -- inline functions, templates, or other code which must be generated -- in each translation unit that uses it. Unreferenced linkonce globals are -- allowed to be discarded. | LinkOnce -- | @weak@ linkage is exactly the same as linkonce linkage, except that -- unreferenced weak globals may not be discarded. This is used for globals -- that may be emitted in multiple translation units, but that are not -- guaranteed to be emitted into every translation unit that uses them. One -- example of this are common globals in C, such as @int X;@ at global -- scope. | Weak -- | @appending@ linkage may only be applied to global variables of pointer -- to array type. When two global variables with appending linkage are -- linked together, the two global arrays are appended together. This is -- the Llvm, typesafe, equivalent of having the system linker append -- together @sections@ with identical names when .o files are linked. | Appending -- | The semantics of this linkage follow the ELF model: the symbol is weak -- until linked, if not linked, the symbol becomes null instead of being an -- undefined reference. | ExternWeak -- | The symbol participates in linkage and can be used to resolve external -- symbol references. | ExternallyVisible -- | Alias for 'ExternallyVisible' but with explicit textual form in LLVM -- assembly. | External -- | Symbol is private to the module and should not appear in the symbol table | Private deriving (Eq) instance Outputable LlvmLinkageType where ppr Internal = text "internal" ppr LinkOnce = text "linkonce" ppr Weak = text "weak" ppr Appending = text "appending" ppr ExternWeak = text "extern_weak" -- ExternallyVisible does not have a textual representation, it is -- the linkage type a function resolves to if no other is specified -- in Llvm. ppr ExternallyVisible = empty ppr External = text "external" ppr Private = text "private" -- ----------------------------------------------------------------------------- -- * LLVM Operations -- -- | Llvm binary operators machine operations. data LlvmMachOp = LM_MO_Add -- ^ add two integer, floating point or vector values. | LM_MO_Sub -- ^ subtract two ... | LM_MO_Mul -- ^ multiply .. | LM_MO_UDiv -- ^ unsigned integer or vector division. | LM_MO_SDiv -- ^ signed integer .. | LM_MO_URem -- ^ unsigned integer or vector remainder (mod) | LM_MO_SRem -- ^ signed ... | LM_MO_FAdd -- ^ add two floating point or vector values. | LM_MO_FSub -- ^ subtract two ... | LM_MO_FMul -- ^ multiply ... | LM_MO_FDiv -- ^ divide ... | LM_MO_FRem -- ^ remainder ... -- | Left shift | LM_MO_Shl -- | Logical shift right -- Shift right, filling with zero | LM_MO_LShr -- | Arithmetic shift right -- The most significant bits of the result will be equal to the sign bit of -- the left operand. | LM_MO_AShr | LM_MO_And -- ^ AND bitwise logical operation. | LM_MO_Or -- ^ OR bitwise logical operation. | LM_MO_Xor -- ^ XOR bitwise logical operation. deriving (Eq) instance Outputable LlvmMachOp where ppr LM_MO_Add = text "add" ppr LM_MO_Sub = text "sub" ppr LM_MO_Mul = text "mul" ppr LM_MO_UDiv = text "udiv" ppr LM_MO_SDiv = text "sdiv" ppr LM_MO_URem = text "urem" ppr LM_MO_SRem = text "srem" ppr LM_MO_FAdd = text "fadd" ppr LM_MO_FSub = text "fsub" ppr LM_MO_FMul = text "fmul" ppr LM_MO_FDiv = text "fdiv" ppr LM_MO_FRem = text "frem" ppr LM_MO_Shl = text "shl" ppr LM_MO_LShr = text "lshr" ppr LM_MO_AShr = text "ashr" ppr LM_MO_And = text "and" ppr LM_MO_Or = text "or" ppr LM_MO_Xor = text "xor" -- | Llvm compare operations. data LlvmCmpOp = LM_CMP_Eq -- ^ Equal (Signed and Unsigned) | LM_CMP_Ne -- ^ Not equal (Signed and Unsigned) | LM_CMP_Ugt -- ^ Unsigned greater than | LM_CMP_Uge -- ^ Unsigned greater than or equal | LM_CMP_Ult -- ^ Unsigned less than | LM_CMP_Ule -- ^ Unsigned less than or equal | LM_CMP_Sgt -- ^ Signed greater than | LM_CMP_Sge -- ^ Signed greater than or equal | LM_CMP_Slt -- ^ Signed less than | LM_CMP_Sle -- ^ Signed less than or equal -- Float comparisons. GHC uses a mix of ordered and unordered float -- comparisons. | LM_CMP_Feq -- ^ Float equal | LM_CMP_Fne -- ^ Float not equal | LM_CMP_Fgt -- ^ Float greater than | LM_CMP_Fge -- ^ Float greater than or equal | LM_CMP_Flt -- ^ Float less than | LM_CMP_Fle -- ^ Float less than or equal deriving (Eq) instance Outputable LlvmCmpOp where ppr LM_CMP_Eq = text "eq" ppr LM_CMP_Ne = text "ne" ppr LM_CMP_Ugt = text "ugt" ppr LM_CMP_Uge = text "uge" ppr LM_CMP_Ult = text "ult" ppr LM_CMP_Ule = text "ule" ppr LM_CMP_Sgt = text "sgt" ppr LM_CMP_Sge = text "sge" ppr LM_CMP_Slt = text "slt" ppr LM_CMP_Sle = text "sle" ppr LM_CMP_Feq = text "oeq" ppr LM_CMP_Fne = text "une" ppr LM_CMP_Fgt = text "ogt" ppr LM_CMP_Fge = text "oge" ppr LM_CMP_Flt = text "olt" ppr LM_CMP_Fle = text "ole" -- | Llvm cast operations. data LlvmCastOp = LM_Trunc -- ^ Integer truncate | LM_Zext -- ^ Integer extend (zero fill) | LM_Sext -- ^ Integer extend (sign fill) | LM_Fptrunc -- ^ Float truncate | LM_Fpext -- ^ Float extend | LM_Fptoui -- ^ Float to unsigned Integer | LM_Fptosi -- ^ Float to signed Integer | LM_Uitofp -- ^ Unsigned Integer to Float | LM_Sitofp -- ^ Signed Int to Float | LM_Ptrtoint -- ^ Pointer to Integer | LM_Inttoptr -- ^ Integer to Pointer | LM_Bitcast -- ^ Cast between types where no bit manipulation is needed deriving (Eq) instance Outputable LlvmCastOp where ppr LM_Trunc = text "trunc" ppr LM_Zext = text "zext" ppr LM_Sext = text "sext" ppr LM_Fptrunc = text "fptrunc" ppr LM_Fpext = text "fpext" ppr LM_Fptoui = text "fptoui" ppr LM_Fptosi = text "fptosi" ppr LM_Uitofp = text "uitofp" ppr LM_Sitofp = text "sitofp" ppr LM_Ptrtoint = text "ptrtoint" ppr LM_Inttoptr = text "inttoptr" ppr LM_Bitcast = text "bitcast" -- ----------------------------------------------------------------------------- -- * Floating point conversion -- -- | Convert a Haskell Double to an LLVM hex encoded floating point form. In -- Llvm float literals can be printed in a big-endian hexadecimal format, -- regardless of underlying architecture. -- -- See Note [LLVM Float Types]. ppDouble :: Double -> SDoc ppDouble d = let bs = doubleToBytes d hex d' = case showHex d' "" of [] -> error "dToStr: too few hex digits for float" [x] -> ['0',x] [x,y] -> [x,y] _ -> error "dToStr: too many hex digits for float" str = map toUpper $ concat $ fixEndian $ map hex bs in text "0x" <> text str -- Note [LLVM Float Types] -- ~~~~~~~~~~~~~~~~~~~~~~~ -- We use 'ppDouble' for both printing Float and Double floating point types. -- This is as LLVM expects all floating point constants (single & double) to be -- in IEEE 754 Double precision format. However, for single precision numbers -- (Float) they should be *representable* in IEEE 754 Single precision format. -- So the easiest way to do this is to narrow and widen again. -- (i.e., Double -> Float -> Double). We must be careful doing this that GHC -- doesn't optimize that away. -- Note [narrowFp & widenFp] -- ~~~~~~~~~~~~~~~~~~~~~~~~~ -- NOTE: we use float2Double & co directly as GHC likes to optimize away -- successive calls of 'realToFrac', defeating the narrowing. (Bug #7600). -- 'realToFrac' has inconsistent behaviour with optimisation as well that can -- also cause issues, these methods don't. narrowFp :: Double -> Float {-# NOINLINE narrowFp #-} narrowFp = double2Float widenFp :: Float -> Double {-# NOINLINE widenFp #-} widenFp = float2Double ppFloat :: Float -> SDoc ppFloat = ppDouble . widenFp -- | Reverse or leave byte data alone to fix endianness on this target. fixEndian :: [a] -> [a] #ifdef WORDS_BIGENDIAN fixEndian = id #else fixEndian = reverse #endif -------------------------------------------------------------------------------- -- * Misc functions -------------------------------------------------------------------------------- ppCommaJoin :: (Outputable a) => [a] -> SDoc ppCommaJoin strs = hsep $ punctuate comma (map ppr strs) ppSpaceJoin :: (Outputable a) => [a] -> SDoc ppSpaceJoin strs = hsep (map ppr strs)
a-ford/notghc
Llvm/Types.hs
bsd-3-clause
35,505
0
16
8,492
6,416
3,409
3,007
515
4
{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} #ifndef MIN_VERSION_vector #define MIN_VERSION_vector(x,y,z) 1 #endif module Data.Vector.Vinyl.Default.NonEmpty.Tagged.Internal ( MVector(..) , Vector(..) ) where import Control.Monad import Control.Monad.Primitive (PrimMonad, PrimState) import Data.Monoid import Data.Typeable (Typeable) import qualified Data.Vector.Generic as G import qualified Data.Vector.Generic.Mutable as GM import GHC.Exts (Constraint) import Data.Proxy import Prelude hiding (drop, init, length, map, null, read, replicate, reverse, tail, take) import Text.Read import Data.Vector.Vinyl.Default.Types (HasDefaultVector (..), MVectorVal (..), VectorVal (..)) import Data.Vinyl.Core (Rec (..)) import Data.Vinyl.Functor (Identity (..)) import Data.Tagged.Functor (TaggedFunctor (..)) import Data.Tuple.TypeLevel (Snd) #if MIN_VERSION_vector(0,11,0) import Data.Vector.Fusion.Bundle as Stream #else import Data.Vector.Fusion.Stream as Stream #endif data Vector :: KProxy k -> * -> * where V :: forall (k :: KProxy a) (rs :: [(a,*)]). !(Rec (TaggedFunctor VectorVal) rs) -> Vector k (Rec (TaggedFunctor Identity) rs) deriving Typeable data MVector :: KProxy k -> * -> * -> * where MV :: forall (k :: KProxy a) (rs :: [(a,*)]) s. !(Rec (TaggedFunctor (MVectorVal s)) rs) -> MVector k s (Rec (TaggedFunctor Identity) rs) deriving Typeable instance ( HasDefaultVector (Snd r) ) => GM.MVector (MVector (k :: KProxy a)) (Rec (TaggedFunctor Identity) ((r :: (a,*)) ': '[])) where basicLength (MV (TaggedFunctor (MVectorVal v) :& RNil)) = GM.basicLength v {-# INLINE basicLength #-} basicUnsafeSlice s e (MV (TaggedFunctor (MVectorVal v) :& RNil)) = MV (TaggedFunctor (MVectorVal (GM.basicUnsafeSlice s e v)) :& RNil) {-# INLINE basicUnsafeSlice #-} basicOverlaps (MV (TaggedFunctor (MVectorVal a) :& RNil)) (MV (TaggedFunctor (MVectorVal b) :& RNil)) = GM.basicOverlaps a b {-# INLINE basicOverlaps #-} basicUnsafeNew n = do r <- GM.basicUnsafeNew n return (MV (TaggedFunctor (MVectorVal r) :& RNil)) {-# INLINE basicUnsafeNew #-} basicUnsafeReplicate n (TaggedFunctor (Identity v) :& RNil) = do r <- GM.basicUnsafeReplicate n v return (MV (TaggedFunctor (MVectorVal r) :& RNil)) {-# INLINE basicUnsafeReplicate #-} basicUnsafeRead (MV (TaggedFunctor (MVectorVal v) :& RNil)) n = do r <- GM.basicUnsafeRead v n return (TaggedFunctor (Identity r) :& RNil) {-# INLINE basicUnsafeRead #-} basicUnsafeWrite (MV (TaggedFunctor (MVectorVal v) :& RNil)) n (TaggedFunctor (Identity r) :& RNil) = GM.basicUnsafeWrite v n r {-# INLINE basicUnsafeWrite #-} basicClear (MV (TaggedFunctor (MVectorVal v) :& RNil)) = GM.basicClear v {-# INLINE basicClear #-} basicSet (MV (TaggedFunctor (MVectorVal v) :& RNil)) (TaggedFunctor (Identity r) :& RNil) = GM.basicSet v r {-# INLINE basicSet #-} basicUnsafeCopy (MV (TaggedFunctor (MVectorVal a) :& RNil)) (MV (TaggedFunctor (MVectorVal b) :& RNil)) = GM.basicUnsafeCopy a b {-# INLINE basicUnsafeCopy #-} basicUnsafeMove (MV (TaggedFunctor (MVectorVal a) :& RNil)) (MV (TaggedFunctor (MVectorVal b) :& RNil)) = GM.basicUnsafeMove a b {-# INLINE basicUnsafeMove #-} basicUnsafeGrow (MV (TaggedFunctor (MVectorVal v) :& RNil)) n = do r <- GM.basicUnsafeGrow v n return (MV (TaggedFunctor (MVectorVal r) :& RNil)) {-# INLINE basicUnsafeGrow #-} #if MIN_VERSION_vector(0,11,0) basicInitialize (MV (TaggedFunctor (MVectorVal v) :& RNil)) = do GM.basicInitialize v {-# INLINE basicInitialize #-} #endif instance ( GM.MVector (MVector k) (Rec (TaggedFunctor Identity) (s ': rs)) , HasDefaultVector (Snd r) ) => GM.MVector (MVector (k :: KProxy a)) (Rec (TaggedFunctor Identity) ((r :: (a,*)) ': (s :: (a,*)) ': (rs :: [(a,*)]))) where basicLength (MV (TaggedFunctor (MVectorVal v) :& _)) = GM.basicLength v {-# INLINE basicLength #-} basicUnsafeSlice s e (MV (TaggedFunctor (MVectorVal v) :& rs)) = case GM.basicUnsafeSlice s e (kMV (Proxy :: Proxy k) rs) of MV rsNext -> kMV (Proxy :: Proxy k) (TaggedFunctor (MVectorVal (GM.basicUnsafeSlice s e v)) :& rsNext) {-# INLINE basicUnsafeSlice #-} basicOverlaps (MV (TaggedFunctor (MVectorVal a) :& as)) (MV (TaggedFunctor (MVectorVal b) :& bs)) = GM.basicOverlaps a b || GM.basicOverlaps (kMV (Proxy :: Proxy k) as) (kMV (Proxy :: Proxy k) bs) {-# INLINE basicOverlaps #-} basicUnsafeNew :: forall m. PrimMonad m => Int -> m (MVector k (PrimState m) (Rec (TaggedFunctor Identity) (r ': s ': rs))) basicUnsafeNew n = consVec (Proxy :: Proxy m) (Proxy :: Proxy r) <$> GM.basicUnsafeNew n <*> GM.basicUnsafeNew n {-# INLINE basicUnsafeNew #-} basicUnsafeReplicate :: forall m. PrimMonad m => Int -> Rec (TaggedFunctor Identity) (r ': s ': rs) -> m (MVector k (PrimState m) (Rec (TaggedFunctor Identity) (r ': s ': rs))) basicUnsafeReplicate n (TaggedFunctor (Identity v) :& rs) = consVec (Proxy :: Proxy m) (Proxy :: Proxy r) <$> GM.basicUnsafeReplicate n v <*> GM.basicUnsafeReplicate n rs {-# INLINE basicUnsafeReplicate #-} basicUnsafeRead (MV (TaggedFunctor (MVectorVal v) :& rs)) n = do r <- GM.basicUnsafeRead v n rs <- GM.basicUnsafeRead (kMV (Proxy :: Proxy k) rs) n return (TaggedFunctor (Identity r) :& rs) {-# INLINE basicUnsafeRead #-} basicUnsafeWrite (MV (TaggedFunctor (MVectorVal v) :& vrs)) n (TaggedFunctor (Identity r) :& rs) = do GM.basicUnsafeWrite v n r GM.basicUnsafeWrite (kMV (Proxy :: Proxy k) vrs) n rs {-# INLINE basicUnsafeWrite #-} basicClear (MV (TaggedFunctor (MVectorVal v) :& vrs)) = do GM.basicClear v GM.basicClear (kMV (Proxy :: Proxy k) vrs) {-# INLINE basicClear #-} basicSet (MV (TaggedFunctor (MVectorVal v) :& vrs)) (TaggedFunctor (Identity r) :& rs) = do GM.basicSet v r GM.basicSet (kMV (Proxy :: Proxy k) vrs) rs {-# INLINE basicSet #-} basicUnsafeCopy (MV (TaggedFunctor (MVectorVal a) :& as)) (MV (TaggedFunctor (MVectorVal b) :& bs)) = do GM.basicUnsafeCopy a b GM.basicUnsafeCopy (kMV (Proxy :: Proxy k) as) (kMV (Proxy :: Proxy k) bs) {-# INLINE basicUnsafeCopy #-} basicUnsafeMove (MV (TaggedFunctor (MVectorVal a) :& as)) (MV (TaggedFunctor (MVectorVal b) :& bs)) = do GM.basicUnsafeMove a b GM.basicUnsafeMove (kMV (Proxy :: Proxy k) as) (kMV (Proxy :: Proxy k) bs) {-# INLINE basicUnsafeMove #-} -- -- basicUnsafeGrow :: forall m. PrimMonad m => MVector (PrimState m) (Rec (TaggedFunctor Identity) (r ': s ': rs)) -> Int -> m (MVector (PrimState m) (Rec (TaggedFunctor Identity) (r ': s ': rs))) -- basicUnsafeGrow (MV (TaggedFunctor (MVectorVal v) :& vrs)) n = do -- r <- GM.basicUnsafeGrow v n -- rs <- GM.basicUnsafeGrow (MV vrs) n -- return (MV (TaggedFunctor (MVectorVal r) :& stripMV (Proxy :: Proxy m) rs)) -- {-# INLINE basicUnsafeGrow #-} -- #if MIN_VERSION_vector(0,11,0) basicInitialize (MV (TaggedFunctor (MVectorVal v) :& rs)) = do GM.basicInitialize v GM.basicInitialize (kMV (Proxy :: Proxy k) rs) {-# INLINE basicInitialize #-} #endif type instance G.Mutable (Vector k) = MVector k instance ( HasDefaultVector (Snd r) ) => G.Vector (Vector (k :: KProxy a)) (Rec (TaggedFunctor Identity) ((r :: (a,*)) ': '[])) where basicUnsafeFreeze (MV (TaggedFunctor (MVectorVal v) :& RNil)) = do r <- G.basicUnsafeFreeze v return (V (TaggedFunctor (VectorVal r) :& RNil)) {-# INLINE basicUnsafeFreeze #-} basicUnsafeThaw (V (TaggedFunctor (VectorVal v) :& RNil)) = do r <- G.basicUnsafeThaw v return (MV (TaggedFunctor (MVectorVal r) :& RNil)) {-# INLINE basicUnsafeThaw #-} basicLength (V (TaggedFunctor (VectorVal v) :& RNil)) = G.basicLength v {-# INLINE basicLength #-} basicUnsafeSlice s e (V (TaggedFunctor (VectorVal v) :& RNil)) = V (TaggedFunctor (VectorVal (G.basicUnsafeSlice s e v)) :& RNil) {-# INLINE basicUnsafeSlice #-} basicUnsafeIndexM (V (TaggedFunctor (VectorVal v) :& RNil)) n = do r <- G.basicUnsafeIndexM v n return (TaggedFunctor (Identity r) :& RNil) {-# INLINE basicUnsafeIndexM #-} basicUnsafeCopy (MV (TaggedFunctor (MVectorVal m) :& RNil)) (V (TaggedFunctor (VectorVal v) :& RNil)) = G.basicUnsafeCopy m v {-# INLINE basicUnsafeCopy #-} elemseq (V (TaggedFunctor (VectorVal v) :& RNil)) (TaggedFunctor (Identity a) :& RNil) b = G.elemseq v a b {-# INLINE elemseq #-} instance ( G.Vector (Vector k) (Rec (TaggedFunctor Identity) (s ': rs)) , HasDefaultVector (Snd r) ) => G.Vector (Vector (k :: KProxy a)) (Rec (TaggedFunctor Identity) ((r :: (a,*)) ': (s :: (a,*)) ': (rs :: [(a,*)]))) where basicUnsafeFreeze (MV (TaggedFunctor (MVectorVal v) :& vrs)) = do r <- G.basicUnsafeFreeze v rs <- G.basicUnsafeFreeze (kMV (Proxy :: Proxy k) vrs) return (V (TaggedFunctor (VectorVal r) :& stripV rs)) {-# INLINE basicUnsafeFreeze #-} basicUnsafeThaw :: forall m. PrimMonad m => Vector k (Rec (TaggedFunctor Identity) (r ': s ': rs)) -> m (G.Mutable (Vector k) (PrimState m) (Rec (TaggedFunctor Identity) (r ': s ': rs))) basicUnsafeThaw (V (TaggedFunctor (VectorVal v) :& vrs)) = do r <- G.basicUnsafeThaw v rs <- G.basicUnsafeThaw (kV (Proxy :: Proxy k) vrs) return (MV (TaggedFunctor (MVectorVal r) :& stripMV (Proxy :: Proxy m) rs)) {-# INLINE basicUnsafeThaw #-} basicLength (V (TaggedFunctor (VectorVal v) :& _)) = G.basicLength v {-# INLINE basicLength #-} basicUnsafeSlice s e (V (TaggedFunctor (VectorVal v) :& rs)) = case G.basicUnsafeSlice s e (kV (Proxy :: Proxy k) rs) of V rsNext -> V (TaggedFunctor (VectorVal (G.basicUnsafeSlice s e v)) :& rsNext) {-# INLINE basicUnsafeSlice #-} basicUnsafeIndexM (V (TaggedFunctor (VectorVal v) :& vrs)) n = do r <- G.basicUnsafeIndexM v n rs <- G.basicUnsafeIndexM (kV (Proxy :: Proxy k) vrs) n return (TaggedFunctor (Identity r) :& rs) {-# INLINE basicUnsafeIndexM #-} basicUnsafeCopy (MV (TaggedFunctor (MVectorVal m) :& mrs)) (V (TaggedFunctor (VectorVal v) :& vrs)) = do G.basicUnsafeCopy m v G.basicUnsafeCopy (kMV (Proxy :: Proxy k) mrs) (kV (Proxy :: Proxy k) vrs) {-# INLINE basicUnsafeCopy #-} elemseq (V (TaggedFunctor (VectorVal v) :& vrs)) (TaggedFunctor (Identity a) :& rs) b = G.elemseq v a (G.elemseq (kV (Proxy :: Proxy k) vrs) rs b) {-# INLINE elemseq #-} -- instance (x ~ Rec Identity rs, Eq x, G.Vector Vector x) => Eq (Vector x) where -- xs == ys = Stream.eq (G.stream xs) (G.stream ys) -- {-# INLINE (==) #-} -- -- xs /= ys = not (Stream.eq (G.stream xs) (G.stream ys)) -- {-# INLINE (/=) #-} -- -- -- instance (x ~ Rec Identity rs, Ord x, G.Vector Vector x) => Ord (Vector x) where -- {-# INLINE compare #-} -- compare xs ys = Stream.cmp (G.stream xs) (G.stream ys) -- -- {-# INLINE (<) #-} -- xs < ys = Stream.cmp (G.stream xs) (G.stream ys) == LT -- -- {-# INLINE (<=) #-} -- xs <= ys = Stream.cmp (G.stream xs) (G.stream ys) /= GT -- -- {-# INLINE (>) #-} -- xs > ys = Stream.cmp (G.stream xs) (G.stream ys) == GT -- -- {-# INLINE (>=) #-} -- xs >= ys = Stream.cmp (G.stream xs) (G.stream ys) /= LT ----------------------------------------- -- Helper functions for instance methods ----------------------------------------- consVec :: forall (rs :: [(a,*)]) (k :: KProxy a) m r. Proxy m -> Proxy r -> G.Mutable (DefaultVector (Snd r)) (PrimState m) (Snd r) -> MVector k (PrimState m) (Rec (TaggedFunctor Identity) rs) -> MVector k (PrimState m) (Rec (TaggedFunctor Identity) (r ': rs)) consVec _ _ v (MV rs) = MV (TaggedFunctor (MVectorVal v) :& rs) {-# INLINE consVec #-} stripMV :: forall (rs :: [(a,*)]) (k :: KProxy a) m. Proxy m -> MVector k (PrimState m) (Rec (TaggedFunctor Identity) rs) -> Rec (TaggedFunctor (MVectorVal (PrimState m))) rs stripMV _ (MV rs) = rs {-# INLINE stripMV #-} stripV :: forall (rs :: [(a,*)]) (k :: KProxy a). Vector k (Rec (TaggedFunctor Identity) rs) -> Rec (TaggedFunctor VectorVal) rs stripV (V rs) = rs {-# INLINE stripV #-} kMV :: forall (k :: KProxy a) (rs :: [(a,*)]) s. Proxy k -> (Rec (TaggedFunctor (MVectorVal s)) rs) -> MVector k s (Rec (TaggedFunctor Identity) rs) kMV _ r = MV r {-# INLINE kMV #-} kV :: forall (k :: KProxy a) (rs :: [(a,*)]). Proxy k -> (Rec (TaggedFunctor VectorVal) rs) -> Vector k (Rec (TaggedFunctor Identity) rs) kV _ r = V r {-# INLINE kV #-}
andrewthad/vinyl-vectors
src/Data/Vector/Vinyl/Default/NonEmpty/Tagged/Internal.hs
bsd-3-clause
13,615
0
17
3,178
4,678
2,442
2,236
226
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} module CO4.Thesis.NatBuiltIn where import Language.Haskell.TH (runIO) import qualified Satchmo.Core.SAT.Minisat import qualified Satchmo.Core.Decode import CO4 import CO4.Prelude $( [d| constraint p (x,y) = eqNat (plusNat x y) p {- and [ eqNat (plusNat x y) p , gtNat x (nat 1) , gtNat y (nat 1) ] -} |] >>= compile [ImportPrelude] ) allocator = knownTuple2 (uNat 10) (uNat 10) result p = solveAndTestP (nat p) allocator encConstraint constraint
apunktbau/co4
test/CO4/Thesis/NatBuiltIn.hs
gpl-3.0
832
0
9
296
112
67
45
16
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="hu-HU"> <title>Code Dx | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/codedx/src/main/javahelp/org/zaproxy/zap/extension/codedx/resources/help_hu_HU/helpset_hu_HU.hs
apache-2.0
969
80
66
160
415
210
205
-1
-1