code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{- |
Module : ./Maude/Parse.hs
Description : extract Maude text in structured specs
Copyright : (c) C. Maeder, DFKI GmbH 2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : portable
extract Maude text from structured specs and stops at an unbalanced curly brace
-}
module Maude.Parse where
import Text.ParserCombinators.Parsec
import Common.Parsec
mStuff :: CharParser st String
mStuff = flat . many $ lineComment <|> blockComment <|> stringLit
<|> balanced "{}"
<|> balanced "()"
<|> balanced "[]"
<|> (char '`' <:> single anyChar)
<|> fmap (: []) (noneOf "\"`])}")
balanced :: String -> CharParser st String
balanced [o, c] = char o <:> mStuff <++> string [c]
balanced _ = error "balanced"
blockComment :: CharParser st String
blockComment = tryString "***(" <++> parbalanced <++> string ")"
parbalanced :: CharParser st String
parbalanced = flat . many $ char '(' <:> parbalanced <++> string ")"
<|> many1 (noneOf "()")
lineComment :: CharParser st String
lineComment = (tryString "---" <|> tryString "***")
<++> many (noneOf "\n")
| spechub/Hets | Maude/Parse.hs | gpl-2.0 | 1,193 | 0 | 13 | 256 | 284 | 142 | 142 | 21 | 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="ko-KR">
<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_ko_KR/helpset_ko_KR.hs | apache-2.0 | 969 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
--------------------------------------------------------------------------
-- |
-- Module : Data.Parition
-- Copyright : (c) Luke Palmer, 2013
-- License : BSD3
--
-- Maintainer : Luke Palmer <lrpalmer@gmail.com>
-- Stability : experimental
-- Portability : portable
--
-- Disjoint set data structure -- @IntPartition@ maintains a collection of
-- disjoint sets of type @a@, with the ability to find which set a particular
-- item belongs to and the ability to merge any two such sets into one.
---------------------------------------------------------------------------
module MyPart
( IntPartition, discrete, empty, fromSets, nontrivialSets, join, find, rep )
where
import qualified Data.IntMap as Map
import qualified Data.IntSet as Set
import Data.Maybe (fromMaybe)
-- | A Partition of @a@: represents a collection of disjoint sets of @a@ whose
-- union includes every element of @a@. Semantics: @[[IntPartition]] = P(P(a))@
-- where @P@ is the power set operation.
data IntPartition
= IntPartition { forwardMap :: Map.IntMap Int, backwardMap :: Map.IntMap (Set.IntSet) }
deriving (Eq, Ord) -- Since the representative is always the least element,
-- we have a canonical representation and Eq is meaningful.
-- Ord may not mean anything, but at least there some
-- computable total ordering on Partitions, and that is helpful
-- sometimes.
instance Show (IntPartition) where
show p = "fromSets " ++ show (nontrivialSets p)
-- | A partition in which every element of @a@ is in its own set. Semantics:
-- @[[discrete]] = { { x } | x in a }@
discrete :: IntPartition
discrete = IntPartition Map.empty Map.empty
-- | Synonym for @discrete@.
empty :: IntPartition
empty = discrete
-- | Takes a list of disjoint sets and constructs a partition containing those sets,
-- with every remaining element being given its own set.
fromSets :: [Set.IntSet] -> IntPartition
fromSets sets = IntPartition {
forwardMap = Map.fromList [ (x, Set.findMin s) | s <- sets, x <- Set.toList s ],
backwardMap = Map.fromList [ (Set.findMin s, s) | s <- sets ]
}
-- | Returns a list of all nontrivial sets (sets with more than one element) in the
-- partition.
nontrivialSets :: IntPartition -> [Set.IntSet]
nontrivialSets = Map.elems . backwardMap
-- | @join x y@ merges the two sets containing @x@ and @y@ into a single set. Semantics:
-- @[[join x y p]] = (p \`minus\` find x \`minus\` find y) \`union\` { find x \`union\` find y }@
join :: Int -> Int -> IntPartition -> IntPartition
join x y p = case compare x' y' of
LT -> go x' y'
EQ -> p
GT -> go y' x'
where
x' = rep p x
y' = rep p y
go into other = IntPartition {
forwardMap = compose [ Map.insert o into | o <- Set.toList otherSrc ] (forwardMap p),
backwardMap = Map.insert into (Set.union (repFind p into) otherSrc)
. Map.delete other
$ backwardMap p
}
where
otherSrc = repFind p other
-- | @find p x@ finds the set that the element @x@ is associated with. Semantics:
-- @[[find p x]] = the unique s in p such that x in s@.
find :: IntPartition -> Int -> Set.IntSet
find p = repFind p . rep p
-- | @rep p x@ finds the minimum element in the set containing @x@.
rep :: IntPartition -> Int -> Int
rep p x = fromMaybe x (Map.lookup x (forwardMap p))
-- Find the set that x is in given that x is already a representative element.
repFind :: IntPartition -> Int -> Set.IntSet
repFind p x = fromMaybe (Set.singleton x) (Map.lookup x (backwardMap p))
compose :: [a -> a] -> a -> a
compose = foldr (.) id
| cglazner/ibd_particle | src/MyPart.hs | bsd-3-clause | 3,884 | 0 | 15 | 1,048 | 689 | 381 | 308 | 41 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : Eta.LanguageExtensions.Type
-- Copyright : (c) TypeLead 2017
--
-- Maintainer : typeleadhq@gmail.com
-- Portability : portable
--
-- A data type defining the language extensions supported by Eta.
--
{-# LANGUAGE DeriveGeneric #-}
module Eta.LanguageExtensions.Type ( Extension(..) ) where
import GHC.Generics
-- | The language extensions known to Eta.
--
-- Note that there is an orphan 'Binary' instance for this type supplied by
-- the "Eta.LanguageExtensions" module provided by @eta-boot@. We can't provide
-- here as this would require adding transitive dependencies to the
-- @template-haskell@ package, which must have a minimal dependency set.
data Extension
-- See Note [Updating flag description in the User's Guide] in DynFlags
= Cpp
| OverlappingInstances
| UndecidableInstances
| IncoherentInstances
| UndecidableSuperClasses
| MonomorphismRestriction
| MonoPatBinds
| MonoLocalBinds
| RelaxedPolyRec -- Deprecated
| ExtendedDefaultRules -- Use Eta's extended rules for defaulting
| ForeignFunctionInterface
| UnliftedFFITypes
| InterruptibleFFI
| CApiFFI
| GHCForeignImportPrim
| JavaScriptFFI
| ParallelArrays -- Syntactic support for parallel arrays
| Arrows -- Arrow-notation syntax
| TemplateHaskell
| TemplateHaskellQuotes -- subset of TH supported by stage1, no splice
| QuasiQuotes
| ImplicitParams
| ImplicitPrelude
| ScopedTypeVariables
| AllowAmbiguousTypes
| UnboxedTuples
| UnboxedSums
| BangPatterns
| TypeFamilies
| TypeFamilyDependencies
| TypeInType
| OverloadedStrings
| OverloadedLists
| NumDecimals
| DisambiguateRecordFields
| RecordWildCards
| RecordPuns
| ViewPatterns
| GADTs
| GADTSyntax
| NPlusKPatterns
| DoAndIfThenElse
| RebindableSyntax
| ConstraintKinds
| PolyKinds -- Kind polymorphism
| DataKinds -- Datatype promotion
| InstanceSigs
| ApplicativeDo
| StandaloneDeriving
| DeriveDataTypeable
| AutoDeriveTypeable -- Automatic derivation of Typeable
| DeriveFunctor
| DeriveTraversable
| DeriveFoldable
| DeriveGeneric -- Allow deriving Generic/1
| DefaultSignatures -- Allow extra signatures for defmeths
| DeriveAnyClass -- Allow deriving any class
| DeriveLift -- Allow deriving Lift
| DerivingStrategies
| TypeSynonymInstances
| FlexibleContexts
| FlexibleInstances
| ConstrainedClassMethods
| MultiParamTypeClasses
| NullaryTypeClasses
| FunctionalDependencies
| UnicodeSyntax
| ExistentialQuantification
| MagicHash
| EmptyDataDecls
| KindSignatures
| RoleAnnotations
| ParallelListComp
| TransformListComp
| MonadComprehensions
| GeneralizedNewtypeDeriving
| RecursiveDo
| PostfixOperators
| TupleSections
| PatternGuards
| LiberalTypeSynonyms
| RankNTypes
| ImpredicativeTypes
| TypeOperators
| ExplicitNamespaces
| PackageImports
| ExplicitForAll
| AlternativeLayoutRule
| AlternativeLayoutRuleTransitional
| DatatypeContexts
| NondecreasingIndentation
| RelaxedLayout
| TraditionalRecordSyntax
| LambdaCase
| MultiWayIf
| BinaryLiterals
| NegativeLiterals
| DuplicateRecordFields
| OverloadedLabels
| EmptyCase
| PatternSynonyms
| PartialTypeSignatures
| NamedWildCards
| StaticPointers
| TypeApplications
| Strict
| StrictData
| MonadFailDesugaring
deriving (Eq, Enum, Show, Generic)
| pparkkin/eta | libraries/eta-boot-th/Eta/LanguageExtensions/Type.hs | bsd-3-clause | 3,701 | 0 | 6 | 859 | 398 | 272 | 126 | 113 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module SecondTransfer.Utils.DevNull(
dropIncomingData
, dropWouldGoData
) where
import Data.Conduit
import Control.Monad.IO.Class (liftIO, MonadIO)
import qualified Control.Monad.Trans.Resource as ReT
import SecondTransfer.MainLoop.CoherentWorker
import SecondTransfer.Exception
-- TODO: Handling unnecessary data should be done in some other, less
-- harmfull way... need to think about that.
-- | If you are not processing the potential POST input in a request,
-- use this consumer to drop the data to oblivion. Otherwise it will
-- remain in an internal queue until the client closes the
-- stream, and if the client doesn't want to do so....
dropIncomingData :: MonadIO m => Maybe InputDataStream -> m ()
dropIncomingData Nothing = return ()
dropIncomingData (Just data_source) = do
_ <- liftIO . forkIOExc "dropIncomingData" .
ignoreException blockedIndefinitelyOnMVar () .
ReT.runResourceT $
data_source $$ awaitForever (\ _ -> do
return () )
return ()
dropWouldGoData :: DataAndConclusion -> IO ()
dropWouldGoData data_source = do
let
do_empty = do
x <- await
case x of
Nothing -> return ()
Just _ -> do_empty
_ <- forkIOExc "dropWouldGoData" $ do
_ <- ReT.runResourceT . runConduit $ fuseBoth data_source do_empty
return ()
return ()
| shimmercat/second-transfer | hs-src/SecondTransfer/Utils/DevNull.hs | bsd-3-clause | 1,523 | 0 | 16 | 432 | 297 | 151 | 146 | 30 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE Rank2Types #-}
module Language.Embedded.Hardware.Interface.AXI (axi_light, AXIPred, FreePrim(..)) where
import Language.Embedded.VHDL (Mode(..))
import Language.Embedded.Hardware.Command.CMD
import Language.Embedded.Hardware.Command.Frontend
import Language.Embedded.Hardware.Interface
import Language.Embedded.Hardware.Expression.Frontend
import Language.Embedded.Hardware.Expression.Represent
import Language.Embedded.Hardware.Expression.Represent.Bit (Bits, Bit, bitFromInteger, ni)
-- hmm...
import Language.Embedded.Hardware.Expression.Syntax (HExp, HType)
import Language.Embedded.Hardware.Expression.Backend.VHDL ()
import Control.Monad.Identity (Identity)
import Control.Monad.Operational.Higher hiding (when)
import Data.Constraint (Constraint)
import Data.Typeable
import Data.Int
import Data.Word
import Data.Bits ()
import Data.Ix (Ix)
import Data.Constraint
import GHC.TypeLits
import qualified GHC.Exts as GHC (Constraint)
import Prelude hiding (not, and, or, div, null)
import qualified Prelude as P
--------------------------------------------------------------------------------
-- * AXI-light Controller.
--------------------------------------------------------------------------------
-- | Make sure that `pred a` implies `PredicateExp exp a`.
class FreeExp exp => FreePrim exp pred
where
witPred :: PrimType a => Proxy exp -> Dict (pred a) -> Dict (PredicateExp exp a)
instance FreePrim HExp HType
where
witPred _ _ = Dict
litP :: forall exp pred a . (FreePrim exp pred, PrimType a, pred a)
=> Proxy pred -> a -> exp a
litP _ a = case witPred (Proxy :: Proxy exp) (Dict :: Dict (pred a)) of
Dict -> litE a
--------------------------------------------------------------------------------
-- | Short-hand for programs.
type Prog instr exp pred = Program instr (Param2 exp pred)
-- | Short-hand for constraints.
type AXIPred instr exp pred = (
-- Instructions.
SignalCMD :<: instr
, ArrayCMD :<: instr
, VariableCMD :<: instr
, ConditionalCMD :<: instr
, ProcessCMD :<: instr
, LoopCMD :<: instr
, ComponentCMD :<: instr
, VHDLCMD :<: instr
-- Expressions.
, Expr exp
, Rel exp
, Factor exp
, Primary exp
--
, FreeExp exp
, FreePrim exp pred
--
, PredicateExp exp (Bit)
, PredicateExp exp (Bits 2)
, PredicateExp exp (Bits 3)
, PredicateExp exp (Bits 4)
, PredicateExp exp (Bits 32)
, PredicateExp exp (Integer)
--
, pred (Bit)
, pred (Bits 2)
, pred (Bits 3)
, pred (Bits 4)
, pred (Bits 32)
, pred (Integer)
--
, Num (exp Integer)
)
--------------------------------------------------------------------------------
-- ** Signature.
--------------------------------------------------------------------------------
axi_light
:: forall instr exp pred sig . AXIPred instr exp pred
=> Comp instr exp pred Identity sig
-> Sig instr exp pred Identity (
Signal (Bits 32) -- ^ Write address.
-> Signal (Bits 3) -- ^ Write channel protection type.
-> Signal Bit -- ^ Write address valid.
-> Signal Bit -- ^ Write address ready.
-> Signal (Bits 32) -- ^ Write data.
-> Signal (Bits 4) -- ^ Write strobes.
-> Signal Bit -- ^ Write valid.
-> Signal Bit -- ^ Write ready.
-> Signal (Bits 2) -- ^ Write response.
-> Signal Bit -- ^ Write response valid.
-> Signal Bit -- ^ Response ready.
-> Signal (Bits 32) -- ^ Read address.
-> Signal (Bits 3) -- ^ Protection type.
-> Signal Bit -- ^ Read address valid.
-> Signal Bit -- ^ Read address ready.
-> Signal (Bits 32) -- ^ Read data.
-> Signal (Bits 2) -- ^ Read response.
-> Signal Bit -- ^ Read valid.
-> Signal Bit -- ^ Read ready.
-> ()
)
axi_light comp =
exactInput "S_AXI_AWADDR" $ \s_axi_awaddr ->
exactInput "S_AXI_AWPROT" $ \s_axi_awprot ->
exactInput "S_AXI_AWVALID" $ \s_axi_awvalid ->
exactOutput "S_AXI_AWREADY" $ \s_axi_awready ->
exactInput "S_AXI_WDATA" $ \s_axi_wdata ->
exactInput "S_AXI_WSTRB" $ \s_axi_wstrb ->
exactInput "S_AXI_WVALID" $ \s_axi_wvalid ->
exactOutput "S_AXI_WREADY" $ \s_axi_wready ->
exactOutput "S_AXI_BRESP" $ \s_axi_bresp ->
exactOutput "S_AXI_BVALID" $ \s_axi_bvalid ->
exactInput "S_AXI_BREADY" $ \s_axi_bready ->
exactInput "S_AXI_ARADDR" $ \s_axi_araddr ->
exactInput "S_AXI_ARPROT" $ \s_axi_arprot ->
exactInput "S_AXI_ARVALID" $ \s_axi_arvalid ->
exactOutput "S_AXI_ARREADY" $ \s_axi_arready ->
exactOutput "S_AXI_RDATA" $ \s_axi_rdata ->
exactOutput "S_AXI_RRESP" $ \s_axi_rresp ->
exactOutput "S_AXI_RVALID" $ \s_axi_rvalid ->
exactInput "S_AXI_RREADY" $ \s_axi_rready ->
ret $ axi_light_impl comp
s_axi_awaddr s_axi_awprot s_axi_awvalid s_axi_awready
s_axi_wdata s_axi_wstrb s_axi_wvalid s_axi_wready
s_axi_bresp s_axi_bvalid s_axi_bready
s_axi_araddr s_axi_arprot s_axi_arvalid s_axi_arready s_axi_rdata
s_axi_rresp s_axi_rvalid s_axi_rready
--------------------------------------------------------------------------------
-- ** Implementation.
--------------------------------------------------------------------------------
axi_light_impl
:: forall instr exp pred sig . AXIPred instr exp pred
-- Component to connect:
=> Comp instr exp pred Identity sig
-- AXI signals:
-> Signal (Bits 32) -- ^ Write address.
-> Signal (Bits 3) -- ^ Write channel protection type.
-> Signal Bit -- ^ Write address valid.
-> Signal Bit -- ^ Write address ready.
-> Signal (Bits 32) -- ^ Write data.
-> Signal (Bits 4) -- ^ Write strobes.
-> Signal Bit -- ^ Write valid.
-> Signal Bit -- ^ Write ready.
-> Signal (Bits 2) -- ^ Write response.
-> Signal Bit -- ^ Write response valid.
-> Signal Bit -- ^ Response ready.
-> Signal (Bits 32) -- ^ Read address.
-> Signal (Bits 3) -- ^ Protection type.
-> Signal Bit -- ^ Read address valid.
-> Signal Bit -- ^ Read address ready.
-> Signal (Bits 32) -- ^ Read data.
-> Signal (Bits 2) -- ^ Read response.
-> Signal Bit -- ^ Read valid.
-> Signal Bit -- ^ Read ready.
-> Prog instr exp pred ()
axi_light_impl comp
s_axi_awaddr s_axi_awprot s_axi_awvalid s_axi_awready
s_axi_wdata s_axi_wstrb s_axi_wvalid s_axi_wready
s_axi_bresp s_axi_bvalid s_axi_bready
s_axi_araddr s_axi_arprot s_axi_arvalid s_axi_arready s_axi_rdata
s_axi_rresp s_axi_rvalid s_axi_rready
= do
----------------------------------------
-- AXI Light signals.
--
awaddr :: Signal (Bits 32) <- newNamedSignal "axi_awaddr"
awready :: Signal (Bit) <- newNamedSignal "axi_awready"
wready :: Signal (Bit) <- newNamedSignal "axi_wready"
bresp :: Signal (Bits 2) <- newNamedSignal "axi_bresp"
bvalid :: Signal (Bit) <- newNamedSignal "axi_bvalid"
araddr :: Signal (Bits 32) <- newNamedSignal "axi_araddr"
arready :: Signal (Bit) <- newNamedSignal "axi_arready"
rdata :: Signal (Bits 32) <- newNamedSignal "axi_rdata"
rresp :: Signal (Bits 2) <- newNamedSignal "axi_rresp"
rvalid :: Signal (Bit) <- newNamedSignal "axi_rvalid"
----------------------------------------
-- Signals for user logic registers.
--
reg_rden :: Signal (Bit) <- newNamedSignal "slv_reg_rden"
reg_wren :: Signal (Bit) <- newNamedSignal "slv_reg_wren"
reg_out :: Signal (Bits 32) <- newNamedSignal "reg_data_out"
reg_index :: Signal (Integer) <- newNamedSignal "byte_index"
registers <- declareRegisters (signatureOf comp)
----------------------------------------
-- Short-hands for ...
--
-- > reset all input registers.
let mReset = resetInputs (signatureOf comp) registers
-- > reload all input registers.
let mReload = reloadInputs (signatureOf comp) registers
-- > fetch the names of all input registers.
let mInputs = identInputs (signatureOf comp) registers
-- > fetch the names of all output registers.
let mOutputs = identOutputs (signatureOf comp) registers
-- > write to output.
let mWrite :: Prog instr exp pred ()
mWrite = loadOutputs araddr reg_out
(addr_lsb) (addr_bits) -- sizes.
(signatureOf comp) (registers) -- sig and args.
-- > read from input.
let mRead :: Prog instr exp pred ()
mRead = loadInputs awaddr reg_wren s_axi_wdata s_axi_wstrb
(addr_lsb) (addr_bits) -- sizes.
(signatureOf comp) (registers) -- sig and args.
----------------------------------------
-- I/O Connections.
--
s_axi_awready <=- awready
s_axi_wready <=- wready
s_axi_bresp <=- bresp
s_axi_bvalid <=- bvalid
s_axi_arready <=- arready
s_axi_rdata <=- rdata
s_axi_rresp <=- rresp
s_axi_rvalid <=- rvalid
----------------------------------------
-- Mem. mapped register select and write
-- logic generation.
--
u_wr <- unsafeFreezeSignal wready
u_wv <- unsafeFreezeSignal s_axi_wvalid
u_awr <- unsafeFreezeSignal awready
u_awv <- unsafeFreezeSignal s_axi_awvalid
setSignal reg_wren
(u_wr `and` u_wv `and` u_awr `and` u_awv)
----------------------------------------
-- Mem. mapped register select and read
-- logic generation.
--
u_arr <- unsafeFreezeSignal arready
u_arv <- unsafeFreezeSignal s_axi_arvalid
u_rv <- unsafeFreezeSignal rvalid
setSignal reg_rden
(u_arr `and` u_arv `and` not u_rv)
----------------------------------------
-- AXI_AWREADY generation.
--
-- processR s_axi_aclk s_axi_aresetn []
processR []
(do awready <== low)
(do rdy <- unsafeFreezeSignal awready
awv <- unsafeFreezeSignal s_axi_awvalid
wv <- unsafeFreezeSignal s_axi_wvalid
iff (isLow rdy `and` isHigh awv `and` isHigh wv)
(do awready <== high)
(do awready <== low))
----------------------------------------
-- AXI_AWADDR latching.
--
processR []
(do awaddr <== zeroes)
(do rdy <- unsafeFreezeSignal awready
awv <- unsafeFreezeSignal s_axi_awvalid
wv <- unsafeFreezeSignal s_axi_wvalid
when (isLow rdy `and` isHigh awv `and` isHigh wv)
(do awaddr <=- s_axi_awaddr))
----------------------------------------
-- AXI_WREADY generation.
--
processR []
(do wready <== low)
(do rdy <- unsafeFreezeSignal awready
awv <- unsafeFreezeSignal s_axi_awvalid
wv <- unsafeFreezeSignal s_axi_wvalid
iff (isLow rdy `and` isHigh wv `and` isHigh awv)
(do wready <== high)
(do wready <== low))
----------------------------------------
-- Slave register logic.
--
processR [] (mReset) (mRead)
----------------------------------------
-- Write response logic.
--
processR []
(do bvalid <== low
bresp <== zeroes)
(do awr <- unsafeFreezeSignal awready
awv <- unsafeFreezeSignal s_axi_awvalid
wr <- unsafeFreezeSignal wready
wv <- unsafeFreezeSignal s_axi_wvalid
bv <- unsafeFreezeSignal bvalid
br <- unsafeFreezeSignal s_axi_bready
ifE ( isHigh awr `and`
isHigh awv `and`
isHigh wr `and`
isHigh wv `and`
isLow bv
, do bvalid <== high
bresp <== zeroes)
( isHigh br `and`
isHigh bv
, do bvalid <== low))
----------------------------------------
-- AXI_AWREADY generation.
--
processR []
(do arready <== low
araddr <== ones)
(do arr <- unsafeFreezeSignal arready
arv <- unsafeFreezeSignal s_axi_arvalid
iff (isLow arr `and` isHigh arv)
(do arready <== high
araddr <=- s_axi_araddr)
(do arready <== low))
----------------------------------------
-- AXI_ARVALID generation.
--
processR []
(do rvalid <== low
rresp <== zeroes)
(do arr <- unsafeFreezeSignal arready
arv <- unsafeFreezeSignal s_axi_arvalid
rv <- unsafeFreezeSignal rvalid
rr <- unsafeFreezeSignal s_axi_rready
ifE ( isHigh arr `and` isHigh arv `and` isLow rv
, do rvalid <== high
rresp <== zeroes)
( isHigh rv `and` isHigh rr
, do rvalid <== low))
----------------------------------------
-- Memory mapped rigister select and
-- read logic generaiton.
--
process (araddr .: mOutputs) (mWrite)
----------------------------------------
-- Output register of memory read data.
--
processR []
(do rdata <== zeroes)
(do rden <- unsafeFreezeSignal reg_rden
when (isHigh rden)
(do rdata <=- reg_out))
----------------------------------------
-- User logic.
--
portmap comp registers
--
-- The end.
----------------------------------------
where
-- Application-specific design signals. The first depends on the bus width,
-- the second on the number of bits needed to store an address. There's no
-- '+ 1' on 'addr_bits' since the ranges add that by default (i.e. '0 to 0'
-- contains one element).
addr_lsb, addr_bits :: Integer
addr_lsb = 2 -- always '2' for a 32-bit bus.
addr_bits = bits (widthOf comp) - 1
where
bits :: Integer -> Integer
bits 0 = 1
bits 1 = 1
bits x = floor $ (1+) $ logBase 2.0 $ fromIntegral x
-- AXI-lite constants.
axi_data_width, axi_addr_width :: Integer
axi_data_width = 32 -- always use 32-bit wide busses for AXI-lite.
axi_addr_width = addr_lsb + addr_bits + 1 -- added one for consistency.
--------------------------------------------------------------------------------
-- ** Helpers.
--------------------------------------------------------------------------------
-- | Declare the registers which will be used by our AXI-lite slave to store
-- values received from the master and, once filled, as input for the comp.
declareRegisters :: forall instr (exp :: * -> *) pred m a . AXIPred instr exp pred
=> Sig instr exp pred Identity a
-> Prog instr exp pred (Argument pred a)
declareRegisters (Ret _) = return Nil
declareRegisters (SSig _ _ sf) =
do s <- newSignal
a <- declareRegisters (sf s)
return (ASig s a)
declareRegisters (SArr _ _ l af) =
do s <- newArray (litP (Proxy :: Proxy pred) l)
a <- declareRegisters (af s)
return (AArr s a)
--------------------------------------------------------------------------------
-- | Reset the input registers.
resetInputs :: forall instr (exp :: * -> *) pred m a . AXIPred instr exp pred
=> Sig instr exp pred Identity a
-> Argument pred a
-> Prog instr exp pred ()
resetInputs (Ret _) (Nil) = return ()
resetInputs (SSig _ Out sf) (ASig s arg) = resetInputs (sf s) arg
resetInputs (SArr _ Out _ af) (AArr a arg) = resetInputs (af a) arg
resetInputs (SSig _ In sf) (ASig s arg) =
do setSignal s (litP (Proxy :: Proxy pred) reset)
resetInputs (sf s) arg
resetInputs (SArr _ In _ af) (AArr a arg) =
do resetArray a (litP (Proxy :: Proxy pred) reset)
resetInputs (af a) arg
--------------------------------------------------------------------------------
-- | Reset the input registers to their previous values.
reloadInputs :: forall instr (exp :: * -> *) pred m a . AXIPred instr exp pred
=> Sig instr exp pred Identity a
-> Argument pred a
-> Prog instr exp pred ()
reloadInputs (Ret _) (Nil) = return ()
reloadInputs (SSig _ Out sf) (ASig s arg) = reloadInputs (sf s) arg
reloadInputs (SArr _ Out _ af) (AArr a arg) = reloadInputs (af a) arg
reloadInputs (SSig _ In sf) (ASig (s :: Signal b) arg) =
case witPred (Proxy :: Proxy exp) (Dict :: Dict (pred b)) of
Dict -> do
sv <- unsafeFreezeSignal s
setSignal s sv
reloadInputs (sf s) arg
reloadInputs (SArr _ In l af) (AArr a arg) =
do copyArray (a, lit 0) (a, lit 0) (lit $ l - 1)
reloadInputs (af a) arg
where
lit :: (FreePrim exp pred, PrimType b, pred b) => b -> exp b
lit = litP (Proxy :: Proxy pred)
--------------------------------------------------------------------------------
-- | ...
loadInputs :: forall instr (exp :: * -> *) pred a . AXIPred instr exp pred
=> Signal (Bits 32) -- ^ Address.
-> Signal (Bit) -- ^ Ready.
-> Signal (Bits 32) -- ^ Input.
-> Signal (Bits 4) -- ^ Protected bits.
-> Integer -- ^ Address lsb.
-> Integer -- ^ Address width.
-> Sig instr exp pred Identity a
-> Argument pred a
-> Prog instr exp pred ()
loadInputs waddr rwren wdata wren addr_lsb addr_bits sig arg =
do loc <- getBits waddr (lit addr_lsb) (lit $ addr_bits - 1)
ready <- unsafeFreezeSignal rwren
when (isHigh ready) $
switched loc
(cases 0 sig arg)
(reloadInputs sig arg)
where
cases :: Integer
-> Sig instr exp pred Identity b
-> Argument pred b
-> [When Integer (Prog instr exp pred)]
cases ix (Ret _) (Nil) = []
cases ix (SSig _ Out sf) (ASig s arg) = cases (ix + 1) (sf s) arg
cases ix (SArr _ Out l af) (AArr a arg) = cases (ix + P.toInteger l) (af a) arg
cases ix (SSig _ In sf) (ASig s arg) =
let new = is (ix) (loadInputSignal wdata wren s)
in new : cases (ix + 1) (sf s) arg
cases ix (SArr _ In l af) (AArr a arg) =
let len = P.toInteger l
new = map (\(i, j) -> is i (loadInputArray wdata wren a j)) $ zip [ix..ix+len-1] [0..]
in new ++ cases (ix + len) (af a) arg
lit :: (FreePrim exp pred, PrimType b, pred b) => b -> exp b
lit = litP (Proxy :: Proxy pred)
loadInputSignal :: forall instr (exp :: * -> *) pred a .
(AXIPred instr exp pred, pred a, Sized a)
=> Signal (Bits 32)
-> Signal (Bits 4)
-> Signal a
-> Prog instr exp pred ()
loadInputSignal wdata wren reg = for 0 size $ \byte_index ->
do bit <- getBit wren byte_index
when (isHigh bit) $
copyBits (reg, byte_index*8) (wdata, byte_index*8) (lit 7)
where
size :: exp Integer
size = lit $ (P.div (bits reg) 8) - 1
-- todo: I assume that `a` has a type \width\ that is some multiple of eight.
lit :: (FreePrim exp pred, PrimType b, pred b) => b -> exp b
lit = litP (Proxy :: Proxy pred)
loadInputArray :: forall instr (exp :: * -> * ) pred i a .
(AXIPred instr exp pred, pred a, Sized a)
=> Signal (Bits 32)
-> Signal (Bits 4)
-> Array a
-> Integer
-> Prog instr exp pred ()
loadInputArray wdata wren arr ix = for 0 size $ \byte_index ->
do bit <- getBit wren byte_index
when (isHigh bit) $
copyABits (arr, byte_index*8, lit ix) (wdata, byte_index*8) (lit 7)
where
size :: exp Integer
size = lit $ (P.div (bits arr) 8) - 1
-- todo: I assume that `a` has a type \width\ that is some multiple of eight.
lit :: (FreePrim exp pred, PrimType b, pred b) => b -> exp b
lit = litP (Proxy :: Proxy pred)
--------------------------------------------------------------------------------
-- | ...
loadOutputs :: forall instr (exp :: * -> *) pred a . AXIPred instr exp pred
=> Signal (Bits 32) -- ^ Address.
-> Signal (Bits 32) -- ^ Output.
-> Integer -- ^ Address lsb.
-> Integer -- ^ Address width.
-> Sig instr exp pred Identity a
-> Argument pred a
-> Prog instr exp pred ()
loadOutputs araddr rout addr_lsb addr_bits sig arg =
do loc <- getBits araddr (lit addr_lsb) (lit $ addr_bits - 1)
switched loc
(cases 0 sig arg)
(resetOut)
where
cases :: Integer
-> Sig instr exp pred Identity b
-> Argument pred b
-> [When Integer (Prog instr exp pred)]
-- todo: due to a bug in the Xilinx tools I use (Vivado 2015.4), we cannot skip
-- any cases. So even if a signal is tagged as an input singal, it must be
-- part of the generated case statement to avoid holes. That is, we can't have:
-- cases ix (Ret _) (Nil) = []
-- cases ix (SSig _ In sf) (ASig s arg) = cases (ix + 1) (sf s) arg
-- cases ix (SArr _ In l af) (AArr a arg) = cases (ix + P.toInteger l) (af a) arg
cases ix (Ret _) (Nil)
| ix < addr_max = to ix addr_max (resetOut) : []
| otherwise = []
cases ix (SSig _ In sf) (ASig s arg) =
is ix (resetOut) : cases (ix + 1) (sf s) arg
cases ix (SArr _ In l af) (AArr a arg) = let len = P.toInteger l in
to ix (ix + len - 1) (resetOut) : cases (ix + len) (af a) arg
cases ix (SSig _ Out sf) (ASig s arg) =
let new = is ix (loadOutputSignal rout s)
in new : cases (ix + 1) (sf s) arg
cases ix (SArr _ Out l af) (AArr a arg) =
let len = P.toInteger l
new = map (\(i, j) -> is i (loadOutputArray rout a j)) $ zip [ix..ix+len-1] [0..]
in new ++ cases (ix + len) (af a) arg
lit :: (FreePrim exp pred, PrimType b, pred b) => b -> exp b
lit = litP (Proxy :: Proxy pred)
addr_max :: Integer
addr_max = addr_bits ^ 2 - 1
resetOut :: Prog instr exp pred ()
resetOut = setSignal rout (lit reset)
loadOutputSignal :: forall instr (exp :: * -> *) pred a .
(AXIPred instr exp pred, pred a, PrimType a, Integral a)
=> Signal (Bits 32)
-> Signal a
-> Prog instr exp pred ()
loadOutputSignal rout reg =
case witPred (Proxy :: Proxy exp) (Dict :: Dict (pred a)) of
Dict -> do
r <- unsafeFreezeSignal reg
setSignal rout (toBits r :: exp (Bits 32))
loadOutputArray :: forall instr (exp :: * -> *) pred a .
( AXIPred instr exp pred, pred a, PrimType a, Integral a)
=> Signal (Bits 32)
-> Array a
-> Integer
-> Prog instr exp pred ()
loadOutputArray rout arr ix =
case witPred (Proxy :: Proxy exp) (Dict :: Dict (pred a)) of
Dict -> do
r <- getArray arr (lit $ P.fromInteger ix)
setSignal rout (toBits r :: exp (Bits 32))
where
lit :: (FreePrim exp pred, PrimType b, pred b) => b -> exp b
lit = litP (Proxy :: Proxy pred)
--------------------------------------------------------------------------------
identInputs :: forall instr (exp :: * -> *) pred m a .
Sig instr exp pred m a
-> Argument pred a
-> [Ident]
identInputs (Ret _) (Nil) = []
identInputs (SSig _ In sf) (ASig s arg) = toIdent s : identInputs (sf s) arg
identInputs (SSig _ _ sf) (ASig s arg) = identInputs (sf s) arg
identInputs (SArr _ In _ af) (AArr a arg) = toIdent a : identInputs (af a) arg
identInputs (SArr _ _ _ af) (AArr a arg) = identInputs (af a) arg
identOutputs :: forall instr (exp :: * -> *) pred m a .
Sig instr exp pred m a
-> Argument pred a
-> [Ident]
identOutputs (Ret _) (Nil) = []
identOutputs (SSig _ Out sf) (ASig s arg) = toIdent s : identOutputs (sf s) arg
identOutputs (SSig _ _ sf) (ASig s arg) = identOutputs (sf s) arg
identOutputs (SArr _ Out _ af) (AArr a arg) = toIdent a : identOutputs (af a) arg
identOutputs (SArr _ _ _ af) (AArr a arg) = identOutputs (af a) arg
--------------------------------------------------------------------------------
signatureOf
:: Comp instr exp pred m sig
-> Sig instr exp pred m sig
signatureOf (Component _ _ sig) = sig
widthOf
:: Comp instr exp pred m sig
-> Integer
widthOf comp = go (signatureOf comp)
where
go :: Sig instr exp pred m b -> Integer
go (Ret _) = 0
go (SSig _ _ f) = 1 + go (f dummy)
go (SArr _ _ l g) = P.toInteger l + go (g dummy)
dummy :: a
dummy = error "todo: evaluated dummy"
high, low :: Expr exp => exp Bit
high = true
low = false
isHigh, isLow :: (Expr exp, Rel exp) => exp Bit -> exp Bit
isHigh e = e `eq` high
isLow e = e `eq` low
zeroes :: (Primary exp, Typeable n, KnownNat n) => exp (Bits n)
zeroes = value 0
ones :: forall exp n. (Primary exp, Typeable n, KnownNat n) => exp (Bits n)
ones = value $ bitFromInteger (2 ^ size - 1)
where size = fromIntegral (ni (Proxy::Proxy n))
--------------------------------------------------------------------------------
| markus-git/imperative-edsl-vhdl | src/Language/Embedded/Hardware/Interface/AXI.hs | bsd-3-clause | 25,510 | 0 | 44 | 7,163 | 7,611 | 3,888 | 3,723 | 486 | 5 |
{-# Language OverloadedStrings #-}
import Shelly
main :: IO ()
main =
shelly $ do
echo "sleeping"
run "sleep" ["5"]
echo "all done"
| adinapoli/Shelly.hs | test/src/sleep.hs | bsd-3-clause | 147 | 0 | 9 | 38 | 47 | 22 | 25 | 8 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Control.Concurrent.SampleVar
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable (concurrency)
--
-- Sample variables
--
-----------------------------------------------------------------------------
module Control.Concurrent.SampleVar
(
-- * Sample Variables
SampleVar, -- :: type _ =
newEmptySampleVar, -- :: IO (SampleVar a)
newSampleVar, -- :: a -> IO (SampleVar a)
emptySampleVar, -- :: SampleVar a -> IO ()
readSampleVar, -- :: SampleVar a -> IO a
writeSampleVar, -- :: SampleVar a -> a -> IO ()
isEmptySampleVar, -- :: SampleVar a -> IO Bool
) where
import Prelude
import Control.Concurrent.MVar
-- |
-- Sample variables are slightly different from a normal 'MVar':
--
-- * Reading an empty 'SampleVar' causes the reader to block.
-- (same as 'takeMVar' on empty 'MVar')
--
-- * Reading a filled 'SampleVar' empties it and returns value.
-- (same as 'takeMVar')
--
-- * Writing to an empty 'SampleVar' fills it with a value, and
-- potentially, wakes up a blocked reader (same as for 'putMVar' on
-- empty 'MVar').
--
-- * Writing to a filled 'SampleVar' overwrites the current value.
-- (different from 'putMVar' on full 'MVar'.)
type SampleVar a
= MVar (Int, -- 1 == full
-- 0 == empty
-- <0 no of readers blocked
MVar a)
-- |Build a new, empty, 'SampleVar'
newEmptySampleVar :: IO (SampleVar a)
newEmptySampleVar = do
v <- newEmptyMVar
newMVar (0,v)
-- |Build a 'SampleVar' with an initial value.
newSampleVar :: a -> IO (SampleVar a)
newSampleVar a = do
v <- newEmptyMVar
putMVar v a
newMVar (1,v)
-- |If the SampleVar is full, leave it empty. Otherwise, do nothing.
emptySampleVar :: SampleVar a -> IO ()
emptySampleVar v = do
(readers, var) <- takeMVar v
if readers > 0 then do
takeMVar var
putMVar v (0,var)
else
putMVar v (readers,var)
-- |Wait for a value to become available, then take it and return.
readSampleVar :: SampleVar a -> IO a
readSampleVar svar = do
--
-- filled => make empty and grab sample
-- not filled => try to grab value, empty when read val.
--
(readers,val) <- takeMVar svar
putMVar svar (readers-1,val)
takeMVar val
-- |Write a value into the 'SampleVar', overwriting any previous value that
-- was there.
writeSampleVar :: SampleVar a -> a -> IO ()
writeSampleVar svar v = do
--
-- filled => overwrite
-- not filled => fill, write val
--
(readers,val) <- takeMVar svar
case readers of
1 ->
swapMVar val v >>
putMVar svar (1,val)
_ ->
putMVar val v >>
putMVar svar (min 1 (readers+1), val)
-- | Returns 'True' if the 'SampleVar' is currently empty.
--
-- Note that this function is only useful if you know that no other
-- threads can be modifying the state of the 'SampleVar', because
-- otherwise the state of the 'SampleVar' may have changed by the time
-- you see the result of 'isEmptySampleVar'.
--
isEmptySampleVar :: SampleVar a -> IO Bool
isEmptySampleVar svar = do
(readers,val) <- readMVar svar
return (readers == 0)
| kaoskorobase/mescaline | resources/hugs/packages/base/Control/Concurrent/SampleVar.hs | gpl-3.0 | 3,369 | 10 | 15 | 768 | 540 | 303 | 237 | 49 | 2 |
-- Example of concurrent Haskell and Gtk.
--
-- As long as GHC does not support OS level threads by default, a trick has
-- to be used to let Haskell programs continue while the GUI is running.
-- We attach a call to the Haskell function "yield" to the timeout handler of
-- Gtk's main loop. Thus GHC regularly gets a chance to execute Haskell
-- threads.
import Graphics.UI.Gtk
import Control.Applicative
import Prelude
import Control.Concurrent
main :: IO ()
main = do
initGUI
dia <- dialogNew
dialogAddButton dia stockClose ResponseClose
contain <- castToBox <$> dialogGetContentArea dia
pb <- progressBarNew
boxPackStart contain pb PackNatural 0
widgetShowAll dia
forkIO (doTask pb)
-- 50ms timeout, so GHC will get a chance to scheule about 20 times a second
-- which gives reasonable latency without the polling generating too much
-- cpu load.
timeoutAddFull (yield >> return True) priorityDefaultIdle 50
dialogRun dia
return ()
doTask :: ProgressBar -> IO ()
doTask pb = do
progressBarPulse pb
threadDelay 100000
doTask pb
| mimi1vx/gtk2hs | gtk/demo/concurrent/Progress.hs | gpl-3.0 | 1,070 | 0 | 10 | 206 | 190 | 90 | 100 | 22 | 1 |
-- #2931
module Foo where
a = 1
-- NB: no newline after the 'a'!
b = 'a
| sdiehl/ghc | testsuite/tests/quotes/T2931.hs | bsd-3-clause | 74 | 0 | 4 | 20 | 17 | 12 | 5 | -1 | -1 |
-- $Id: ScopeRec.hs,v 1.1 2001/07/24 17:39:10 moran Exp $
module ScopeRec where
import Syntax
import List(find, nub, nubBy, (\\), sortBy, groupBy, union)
--import Observe
import PrettyPrint
import Maybe
import IOExts
import SyntaxUtil(isTyVar, getTyName)
import Scope2
import HsConstants
import ScopeStruct
names :: HsDecl -> Senv
names (Dec d) = namesD d
dataName (HsConDecl s nm slots) = (nm, s, length slots)
dataName (HsRecDecl s nm slots) = (nm, s, length slots)
recordName :: HsConDecl t -> [(HsName, SrcLoc)]
recordName (HsConDecl s nm slots) = []
recordName (HsRecDecl s nm slots) = foldr f [] slots
where f (names,domain) xs = map (\nm -> (nm,s)) names ++ xs
allNames :: [HsDecl] -> Senv -> Senv
allNames ds initial = foldr acc initial ds
where acc d env = concatEnv (names d) env
----------------------------------------------------------------------
-- Generic Static checking functions
duplicates :: Eq a => [a] -> [a]
duplicates [] = []
duplicates (x:xs) =
if elem x xs then x : (duplicates (filter (/=x) xs)) else (duplicates xs)
collect_duplicate_info :: ([a] -> [b]) -> (a -> a -> Ordering) -> [a] -> [b]
collect_duplicate_info infof compare =
concat . (map infof) . (groupBy (lift compare)) . (sortBy compare)
where lift g x y = case g x y of { EQ -> True; _ -> False }
dupErrs :: (Show a, Show b) => b -> [(a,SrcLoc)] -> [Error]
dupErrs sort [] = []
dupErrs sort [x] =[]
dupErrs sort xs@((nm,loc):_) = chk loc True (duplicate_things sort nm (map snd xs))
dupTvErr srcloc [x] = []
dupTvErr srcloc (x:xs) = [(srcloc, duplicate_type_vars x)]
chk:: SrcLoc -> Bool -> String -> [Error]
chk loc test message = if test then [(loc,message)] else []
unique :: Eq a => [(a,b)] -> [(a,b)]
unique = nubBy (\(a,_) (b,_) -> a==b)
------------------------------------------------------------------------------
-- Scope checking
------------------------------------------------------------------------------
nmConflict :: Senv -> [Error]
nmConflict env =
let ts = tconstrNames env
cs = classNames env
sameName (tn,tloc,_,_) errs =
case find (\(a,_,_,_) -> a==tn) cs of
Nothing -> errs
Just (_,cloc,_,_) -> (tloc, type_class_conflict tn [tloc,cloc]) : errs
in foldr sameName [] ts
classMethodErr :: Senv -> [Error]
classMethodErr env =
let ss = sigNames env
vs = varNames env
sigExists (vn,vloc) errs =
case find (\(a,_) -> a==vn) ss of
Nothing -> (vloc, method_without_signature vn) : errs
Just _ -> errs
in foldr sigExists [] vs
type_class_conflict tn cloc =
"Type name " ++ pp tn ++ " is used as class name "++ pp cloc
method_without_signature vn =
"Definition of " ++ pp vn ++ " without declaration"
getClass (Typ (HsTyApp x _)) = getClass x
getClass (Typ (HsTyCon c)) = Just c
getClass _ = Nothing
allTypNames (Typ (HsTyVar v)) (vs, cs) = (v : vs, cs)
allTypNames (Typ (HsTyCon c)) (vs, cs) = (vs, c : cs)
allTypNames (Typ t) ans = accT allTypNames t ans
isTyConApp (Typ (HsTyCon _)) = True
isTyConApp (Typ (HsTyApp f _)) = isTyConApp f
isTyConApp _ = False
getTyAppArgs (Typ (HsTyCon _)) args = args
getTyAppArgs (Typ (HsTyApp f x)) args = getTyAppArgs f (x:args)
-- Well formed type expression: C x*
wfTp :: SrcLoc -> TPContext -> HsType -> [Error] -> [Error]
wfTp srcloc c t errs =
if isTyConApp t && all isTyVar (getTyAppArgs t []) then
errs
else
(srcloc, type_former_is_not_constructor t c) : errs
-- well formed simple class specification: C x+
wfSclass :: SrcLoc -> HsType -> [Error] -> [Error]
wfSclass loc t errs =
if isTyConApp t && not (null args) && all isTyVar args then
errs
else
(loc, illformed_sclass t) : errs
where args = getTyAppArgs t []
-------------------------------------------------------------------------
srcloc (HsTypeDecl loc _ _ ) = loc
srcloc (HsNewTypeDecl loc _ _ _ _ ) = loc
srcloc (HsDataDecl loc _ _ _ _ ) = loc
srcloc (HsClassDecl loc _ _ _ ) = loc
srcloc (HsInstDecl loc _ _ _ ) = loc
srcloc (HsDefaultDecl loc _ ) = loc
srcloc (HsTypeSig loc _ _ _ ) = loc
srcloc (HsFunBind loc _ ) = loc
srcloc (HsPatBind loc _ _ _ ) = loc
srcloc (HsPrimitiveTypeDecl loc _ _ ) = loc
srcloc (HsPrimitiveBind loc _ _ ) = loc
whatIs (HsTypeDecl _ _ _ ) = "type declaration"
whatIs (HsNewTypeDecl _ _ _ _ _ ) = "newtype declaration"
whatIs (HsDataDecl _ _ _ _ _ ) = "data declaration"
whatIs (HsClassDecl _ _ _ _ ) = "class declaration"
whatIs (HsInstDecl _ _ _ _ ) = "instance declaration"
whatIs (HsDefaultDecl _ _ ) = "declaration"
whatIs (HsTypeSig _ _ _ _ ) = "type signature"
whatIs (HsFunBind _ _ ) = "function binding"
whatIs (HsPatBind _ _ _ _ ) = "pattern binding"
whatIs (HsPrimitiveTypeDecl _ _ _ ) = "declaration"
whatIs (HsPrimitiveBind _ _ _ ) = "declaration"
--------------------------------------------------------------
-- The first kind of scoping and its combinators
--------------------------------------------------------------
scopE :: v -> E (v -> e) (v->v,v -> p) (v->v,v -> ds) (v -> t) (v -> c) -> E e p ds t c
scopE env x =
case x of
HsLet (envtrans,f) e -> let env2 = envtrans env
in HsLet (f env2) (e env2)
HsLambda ps e -> let (env2,ps') = scopPatList env ps
in HsLambda ps' (e env2)
HsCase e alts -> HsCase (e env) (map (scopAlt env) alts)
HsDo stmt -> HsDo (scopStmt env stmt)
HsListComp stmt -> HsListComp (scopStmt env stmt)
z -> mapE (\ f -> f env) (error "missing HsExp case")
(error "missing HsDecl case") (\ f -> f env) (\ f -> f env) z
scopAlt :: v -> HsAlt (v -> e) (v->v,v -> p) (v->v,v -> ds) -> HsAlt e p ds
scopAlt env (HsAlt s (f,pf) rhs (g,dsf)) =
let env2 = g (f env)
in (HsAlt s (pf env) (scopRhs env2 rhs) (dsf env2))
scopRhs :: v -> HsRhs (v -> e) -> HsRhs e
scopRhs env x = mapRhs (\ f -> f env) x
scopStmt :: v -> HsStmt (v -> e) (v->v,v -> p) (v->v,v -> ds) -> HsStmt e p ds
scopStmt env (HsGenerator (tr,pf) e s) =
let env2 = tr env in HsGenerator (pf env) (e env2) (scopStmt env2 s)
scopStmt env (HsQualifier e s) = HsQualifier (e env) (scopStmt env s)
scopStmt env (HsLetStmt (tf,dsf) s) =
let env2 = tf env in HsLetStmt (dsf env2) (scopStmt env2 s)
scopStmt env (HsLast e) = HsLast (e env)
scopPatList :: v -> [(v -> v,v -> p)] -> (v,[p])
scopPatList env ps = (foldr (\ (tf,_ ) e -> tf e) env ps,
map (\ (_ ,pf) -> pf env) ps)
--------------------------------------------------------------------------
-- Then for the declaration sub-language
scopD :: Env v => v ->
D (v -> e)
(v -> v, v -> p)
(v -> v, v -> ds)
(v -> t)
(v -> c)
(v -> v, v -> tp) ->
D e p ds t c tp
scopD env x =
let scopConDecl env = mapConDecl (\f -> f env)
extendWithTvs env tvs = foldr extTvar env tvs
scopMatch env (HsMatch loc nm ps rhs (dectrans,ds)) =
let (env2,ps') = scopPatList env ps
env3 = dectrans (extVar nm loc env2)
in HsMatch loc nm ps' (scopRhs env3 rhs) (ds env3)
in
case x of
HsPatBind loc (pattrans,pf) rhs (dectrans,dsf) ->
let env2 = dectrans (pattrans env)
in
HsPatBind loc (pf env) (scopRhs env2 rhs) (dsf env2)
HsFunBind loc matches -> HsFunBind loc (map (scopMatch env) matches)
HsTypeDecl loc (transtpfs @ ((ctrans,cmaker):fs)) tf ->
let env2 = ctrans env
constr = cmaker env
(env3,args) = scopPatList env fs
in HsTypeDecl loc (constr:args) (tf env3)
HsNewTypeDecl loc contxtf transtpfs condecl derivs ->
let (env2,args) = scopPatList env transtpfs
(env3,_) = scopPatList (restrictTvar env) (tail transtpfs)
in HsNewTypeDecl loc (contxtf env3) args (scopConDecl env2 condecl) derivs
HsDataDecl loc contxtf transtpfs condecls derivs ->
let (env2,args) = scopPatList env transtpfs
(env3,_) = scopPatList (restrictTvar env) (tail transtpfs)
in HsDataDecl loc (contxtf env3) args (map (scopConDecl env2) condecls) derivs
HsClassDecl loc contxtf (trans,tpf) (dectrans,dsf) ->
let env1 = trans (restrictTvar env)
in HsClassDecl loc (contxtf env1) (tpf env) (dsf $ dectrans env1)
HsInstDecl loc contxtf (trans,tpf) (dectrans,dsf) ->
let env1 = trans (restrictTvar env)
in HsInstDecl loc (contxtf env1) (tpf env) (dsf $ dectrans env1)
HsTypeSig loc nms contxtf (transf, tpf) ->
HsTypeSig loc nms (contxtf (transf env)) (tpf env)
z -> mapD (\ f -> f env) h h (\ f -> f env) (\ f -> f env) (error "type pattern") z
where h (trans,f) = f (trans env)
--------------------------------------------------------------------------
-- Then for the type sub-language
scopT :: v -> T (v -> t) -> T t
scopT env t = mapT (\f -> f env) t
--------------------------------------------------------------------------
-- Computing Things about patterns
--------------------------------------------------------------------------
boundInP :: HsPat -> [HsName] -> [HsName]
boundInP (Pat(HsPId(HsVar s))) ans = s:ans
boundInP (Pat(HsPAsPat n p)) ans = boundInP p (n:ans)
boundInP (Pat x) ans = accP boundInP ans x
------------------------------------------------------------------------
-- patBound: Compute three things while visiting each pattern sub-node.
-- 1) A list of unique names bound by the pattern
-- 2) A list of names that appear more than once.
-- These are errors because we allow only linear patterns
-- 3) A list of every construtor and the arity at which it was used.
-- These are potential errors if the arites do not match
patBound :: HsPat -> ([HsName], [HsName], [(HsName, Int)]) ->
([HsName], [HsName], [(HsName, Int)])
patBound (Pat p) ans =
case p of
HsPId(HsVar n) -> add n ans
HsPAsPat n p -> patBound p (add n ans)
HsPApp c ps -> cadd c (length ps) ans'
HsPInfixApp p1 c p2 -> cadd (getHSName c) 2 ans'
_ -> ans'
where add x (a, b, c) =
if elem x a
then if elem x b
then (a, b, c)
else (a, x:b, c)
else (x:a, b, c)
cadd c n (x, y, z) = (x, y, (c, n):z)
ans' = accP patBound ans p
------------------------------------------------------------------------------
-- Static Check for Expressions
chE :: SrcLoc -> HsExp -> Senv -> [Error]
chE loc (exp @ (Exp x)) env =
case scopE env (mapE (chE loc) (chP loc)
(chDs WhereLikeDecl) (chT loc ) (error "ctxt") x) of
HsId (HsVar n) -> chk loc (not (varDefined n env)) (undefined_variable n)
HsInfixApp x (HsVar n) y -> chk loc (not (varDefined n env)) (undefined_variable n)
HsLeftSection x (HsVar n) -> chk loc (not (varDefined n env)) (undefined_variable n)
HsRightSection (HsVar n) x -> chk loc (not (varDefined n env)) (undefined_variable n)
HsLambda ps e -> e ++ (chPatList loc env ps)
z -> accE (++) (\ (ns,errs) a -> errs++a) (++) (++) (++) z []
--------------------------------------------
-- Static checks for individual patterns
chP :: SrcLoc -> HsPat -> (Senv -> Senv,Senv -> ([HsName],[Error]))
chP loc (pat @ (Pat x)) = (envTrans, f)
where (uniqueNames,dups,constrArities) = patBound pat ([],[],[])
envTrans env = foldr extName env uniqueNames
extName nm = extVar nm loc
duperr = chk loc (not (null dups)) (duplicate_vars_in_pattern dups)
f env = (uniqueNames,allErrors env)
allErrors env = foldr arityCheck duperr constrArities
where arityCheck (c,n) ans = check c n (cArity c env) ++ ans
check c n Nothing = [(loc,undefined_constr c)]
check c n (Just m) = chk loc (m /=n) (constr_wrong_arity n c)
-----------------------------------------------------------------------------
-- When language constructs have a list of patterns like : (\ p1 ... pn -> e)
-- or (case x of { C p1 ... pn -> e }), Haskell has the rule that no variable
-- should appear more than once in the list. We can't check this, pattern by
-- pattern, but have to observe the complete list. If we map (chP env) over a
-- list of patterns we get [([unique_names],[error_messages])], from this we
-- can compute additional error_messages dealing with duplicates.
chPatList :: SrcLoc -> Senv -> [([HsName],[Error])] -> [Error]
chPatList loc env ps =
let accumulate (ns,errs) (names,errors) = (ns++names,errs++errors)
(allbound,internalerr) = foldr accumulate ([],[]) ps
dups = duplicates allbound
duperr = chk loc (not (null dups)) (repeated_pattern_variables dups)
in internalerr ++ duperr
--------------------------------------------------------------------------
-- static checks for a list of Decls
chDs :: DeclContext -> [HsDecl] -> (Senv->Senv,Senv -> [Error] )
chDs contxt ds = (envtrans,errorfun)
where env = allNames ds env0
envtrans = concatEnv env
errorfun env = foldr (\ d ans -> (check env d) ++ ans) allErrors ds
sameName (x,y) (a,b) = compare x a
contextErrors = catMaybes $ map (legal contxt) ds
dupErr k message = collect_duplicate_info (dupErrs message) sameName (locations k env)
dupValErrors = dupErr Var "value definitions"
dupSigErrors = dupErr Sig "type signatures"
dupClsErrors = dupErr Class "class definitions"
dupTypErrors = dupErr TyCons "type definitions"
dupConsErrors = dupErr Cons "constructor functions"
allErrors = contextErrors++dupValErrors++dupSigErrors++dupClsErrors
++ dupTypErrors ++ dupConsErrors ++ nmConflict env ++ clsMethodErr
sigerr loc name = chk loc ((not $ elem name (map fst (varNames env))) && contxt/=ClassDecl)
(signature_without_definition name)
methodErr c (nm,loc) = chk loc (not $ isMethod nm c env) (not_a_method nm c)
clsMethodErr = case contxt of
ClassDecl -> classMethodErr env
other -> []
check env (Dec x) =
let loc = srcloc x
methodErrs (HsInstDecl loc c tp ds) =
let nms = varNames $ allNames ds env0
in case getClass tp of
Nothing -> []
Just c -> concat $ map (methodErr c) nms
in
case scopD env (mapD' (chE loc) (chP loc) (chDs) (chT loc) (chCntxt loc) (chTp loc) x) of
HsTypeSig loc nms c t -> (concat $ map (sigerr loc) nms)++c++t
HsInstDecl loc c tp ds -> methodErrs x ++ c ++ tp ++ ds
z -> accD (++) (\ (ns,errs) a -> (errs)++a) (++) (++) (++) (++) z []
---------------------------------------------------------------------------
chT :: SrcLoc -> HsType -> Senv -> [Error]
chT loc (typ @ (Typ t)) env =
case t of
HsTyVar nm -> chk loc (not (tvarDefined nm env)) (undefined_tvar nm)
HsTyCon nm -> chk loc (not (tconDefined nm env)) (undefined_tcon nm)
HsTyApp (Typ f) x -> synCheck (chT loc) env f x 1
z -> accT (++) (scopT env (mapT (chT loc) z)) []
synCheck chf env (HsTyCon c) arg n =
case synArity c env of
Nothing -> chk loc (not (tconDefined c env)) (undefined_tcon c) ++ chf arg env
Just m -> chk loc (m/=n) (tysynonym_not_fully_applied c) ++ chf arg env
synCheck chf env (HsTyApp (Typ f) x) arg n =
synCheck chf env f x (n+1) ++ chf arg env
synCheck chf env t arg n = chf (Typ t) env ++ chf arg env
-----------------------------------------------------------------------------
-- Static checks for contexts
chCntxt :: SrcLoc -> DeclContext -> [HsType] -> (Senv -> [Error])
chCntxt loc c ts env = foldr (check c) [] ts
where inscope (Typ (HsTyVar x)) ans =
chk loc (not $ tvarDefined x env) (undefined_tvar_in_context x) ++ ans
inscope (Typ (HsTyCon c)) ans =
chk loc (not $ classDefined c env) (undefined_class_in_context c) ++ ans
inscope (Typ x) ans = accT inscope x ans
-- class: C (x t*)+
wfClass t (Typ (HsTyApp (Typ (HsTyCon c)) x )) xs =
wfClassArg x x xs
wfClass t (Typ (HsTyApp x y )) xs =
wfClass t x $ wfClassArg x x xs
wfClass t (Typ x) xs =
(loc, illformed_class t) : xs
-- class arg: x t*
wfClassArg t (Typ (HsTyVar y)) xs = xs
wfClassArg t (Typ (HsTyApp x _)) xs = wfClassArg t x xs
wfClassArg t (Typ x) xs = (loc, illformed_class_arg t) : xs
check ClassDecl x ans = wfSclass loc x (inscope x ans)
check InstDecl x ans = wfSclass loc x (inscope x ans)
check _ x ans = wfClass x x (inscope x ans)
-----------------------------------------------------------------------------
-- Static checks for type patterns
chTp :: SrcLoc -> TPContext -> HsType -> (Senv -> Senv, Senv -> [Error])
chTp srcloc InstTP x =
let errors = wf x []
-- well formed instance: C (C x*)+
wf (Typ(HsTyApp (Typ(HsTyCon c)) arg)) xs =
wfTp srcloc InstTP arg xs
wf (Typ(HsTyCon c)) xs =
(srcloc, instance_required c) : xs
wf (Typ(HsTyApp y arg)) xs =
wf y (wfTp srcloc InstTP arg xs)
wf tp xs =
(srcloc, instance_not_class_app tp) : xs
(classname, ts) = instPatToParts x
(tvs, cs) = foldr allTypNames ([], []) ts
trans env = if null errors then foldr extTvar env tvs else env
clsError env = chk srcloc (not $ classDefined classname env)
(undefined_class_in_instance classname)
cdef env c ans =
if tconDefined c env
then case synArity c env of
Nothing -> ans
Just _ -> (srcloc, synonym_illegal_in_instance c):ans
else (srcloc,undefined_tcon_in_instance c):ans
dupErrs = collect_duplicate_info (dupTvErr srcloc) compare tvs
tpf env = if null errors
then foldr (cdef env) (dupErrs ++ clsError env) cs
else errors
in (trans, tpf)
chTp srcloc SigTP x =
let (tvs, cs) = allTypNames x ([], [])
trans env = foldr extTvar env tvs
cdef env c ans =
if tconDefined c env
then ans
else (srcloc, undefined_tcon_in_signature c):ans
tpf env = foldr (cdef env) [] cs
in (trans, tpf)
chTp srcloc cntxt x =
let (constr, tvs) = typePatToParts x
errors = case cntxt of DataLikeTP -> wfTp srcloc cntxt x []
ClassTP -> wfSclass srcloc x []
trans env = if null errors then foldr extTvar env tvs else env
tpf env = if null errors
then collect_duplicate_info (dupTvErr srcloc) compare tvs
else errors
in (trans, tpf)
-------------------------------------------------------------------------
-- Error Message Strings are computed here
-------------------------------------------------------------------------
undefined_variable nm = "Undefined variable: "++ pp nm
duplicate_vars_in_pattern dups =
"Variables appear more than once in single pattern: " ++ pp dups
undefined_constr c =
"Undefined Constructor in pattern: " ++ pp c
constr_wrong_arity n c =
"Constructor "++ pp c++ " must have exactly "++ pp n ++ " arguments."
repeated_pattern_variables dups =
"Repeated variables in pattern list: " ++ pp dups
duplicate_things sort name locs =
"Duplicate " ++ show sort ++ " of " ++ show name ++
" at locations: " ++ pp locs
signature_without_definition name =
"Signature for "++pp name++" without matching definition."
undefined_class_in_instance classname =
"Class name in instance: " ++ pp classname ++ " is not defined"
undefined_tcon_in_instance c =
"Type constructor " ++ pp c ++ " in instance is not defined"
synonym_illegal_in_instance c =
"Type synonym " ++ pp c ++ " in instance"
undefined_tcon_in_signature c =
"Type constructor " ++ pp c ++ " in signature is not defined"
undefined_class_in_context clsname =
"Class name " ++ pp clsname ++ " in context is not defined"
undefined_tvar_in_context tvarname =
"Type variable " ++ pp tvarname ++ " in context is not defined"
undefined_tvar tvarname =
"Type variable " ++ pp tvarname ++ " is not defined"
undefined_tcon tconname =
"Type constructor " ++ pp tconname ++ " is not defined"
tysynonym_not_fully_applied tyconname =
"Type synonym " ++ pp tyconname ++ " is not fully applied"
duplicate_type_vars x =
"Duplicate type variables in definition: " ++ pp x
non_tyvar_arg_in_pattern a c =
"Argument in Type Pattern in " ++ show c ++ " is not a variable: "++ pp a
type_former_is_not_constructor x c =
"Type pattern in " ++ show c ++ " is not an application of a type constructor: "++ pp x
instance_required tp =
"Instance of class " ++ pp tp ++ " required"
instance_not_class_app tp =
"Instance is not an application of a class constructor: "++pp tp
illformed_sclass t=
"ill formed class "++pp t
illformed_class t=
"ill formed class in context "++pp t
illformed_class_arg t=
"ill formed argument " ++ pp t ++ " to class in context "
not_a_method nm c =
pp nm ++ " is not a method of class " ++ pp c
{-
showAst === pp
showAst :: Printable a => a -> String
showAst = render . ppi
-}
----------------------------------------------------------------------------------
-- some tests
sh :: Printable b => b -> IO ()
sh = putStr . render . ppi
loc = SrcLoc "Scope tests" 0 0
names2 @ [fn,gn,hn,kn,xn,yn,zn] = map UnQual ["f","g","h","k","x","y","z"]
names3 @ [an,bn,cn,dn,en,tn,sn] = map UnQual ["A","B","C","D","E","T","S"]
exps @ [fe,ge,he,ke,xe,ye,ze] = map hsEVar names2
pats @ [fp,gp,hp,kp,xp,yp,zp] = map hsPVar names2
typs @ [ft,gt,ht,kt,xt,yt,zt] = map hsTyVar names2
cons @ [ac,bc,cc,dc,ec,tc,sc] = map hsECon names3
tcons @ [at,bt,ct,dt,et,tt,st] = map hsTyCon names3
ap2 [x] = x
ap2 (x:y:xs) = ap2((hsApp x y):xs)
apt [x] = x
apt (x:y:xs) = apt((hsTyApp x y):xs)
arr = hsTyFun
class1 = hsClassDecl loc [] (apt [ct,xt])
[ hsTypeSig loc [fn] [] (xt `arr` xt) ]
class2 = hsClassDecl loc [apt[ct,yt]] (apt [dt,yt])
[ hsTypeSig loc [gn] [] (yt `arr` yt) ]
class3 = hsClassDecl loc [apt[at,yt,xt]] (apt [et,yt,yt])
[ hsTypeSig loc [zn] [] (yt `arr` yt) ]
inst0 = hsInstDecl loc [] (ct) []
inst0'= hsInstDecl loc [] (xt) []
inst1 = hsInstDecl loc [] (apt [ct,xt]) []
inst2 = hsInstDecl loc [] (apt [ct,apt [dt,xt,xt]]) []
inst3 = hsInstDecl loc [] (apt [ct,apt [dt,at]]) []
inst4 = hsInstDecl loc [apt [dt,xt]] (apt [ct,tt]) []
inst5 = hsInstDecl loc [] (apt [ct,at]) []
inst6 = hsInstDecl loc [] (yt `arr` yt) []
data1 = hsDataDecl loc [] [tt] [HsConDecl loc cn []] []
data2 = hsDataDecl loc [] [tt,xt] [] []
data3 = hsDataDecl loc [] [tt] [HsConDecl loc cn [HsBangedType yt]
,HsConDecl loc dn [HsUnBangedType at]
,HsConDecl loc dn []
] []
data4 = hsDataDecl loc [] [tt,xt] [HsConDecl loc dn [HsUnBangedType st]] []
data5 = hsDataDecl loc [] [tt,xt] [HsConDecl loc dn [HsUnBangedType (apt [st,xt])]] []
data6 = hsDataDecl loc [] [tt,xt] [HsConDecl loc dn [HsUnBangedType (apt [st,xt,yt])]] []
data7 = hsDataDecl loc [] [tt,xt] [HsConDecl loc dn [HsUnBangedType (apt [st,xt,yt,yt])]] []
type1 = hsTypeDecl loc [st,xt,yt] (hsTyTuple [xt,yt])
sig1 = hsTypeSig loc [zn] [] (apt [st,xt])
p0 = [class1,class2,class3,inst1,inst2,inst3]
p1 = [inst2]
p2 = [class1,class1,data1,data2,inst4,inst5]
run env prog = let (f,x) = chDs TopDecl prog in x(f env)
ss = run env0
showErr (SrcLoc f n m, s) = "(" ++ show n ++ ", " ++ show m ++ ") " ++ s
sck ds = (putStr . unlines . map showErr . ss) ds
test prog = do {sh prog; putStr "\n------------\n"; sck prog}
testDs :: (String,[HsDecl]) -> IO ()
testDs (s, ds) =
do { putStr "\n==============================================\n"
; putStr s
; putStr "\n--- test code----------\n"
; sh ds
; putStr "\n--- errors ------------\n"
; (putStr . unlines . map showErr . run env0) ds
}
tests ts = sequence_ $ map testDs ts
insts :: [(String, [HsDecl])]
insts = [ ("Ill formed instance type", [ hsInstDecl loc [] (ct) [] ] )
, ("Ill formed instance type", [ hsInstDecl loc [] (xt) [] ])
, ("Ill formed instance type", [hsInstDecl loc [] (apt [ct,xt]) []])
, ("Undefined class & type" , [hsInstDecl loc [] (apt [ct,dt]) []])
, ("Duplicate type vars",
[ hsDataDecl loc [] [dt] [] []
, hsClassDecl loc [] (apt [ct,xt]) []
, hsInstDecl loc [] (apt [ct,apt [dt,xt,xt]]) []])
, ("Argument to TyCon must be tyvar", [hsInstDecl loc [] (apt [ct,apt [dt,at]]) []])
, ("Many undefined", [hsInstDecl loc [apt [dt,xt]] (apt [ct,tt]) []])
, ("Type synonym illegal",
[ hsTypeDecl loc [at] bt
, hsDataDecl loc [] [bt] [] []
, hsClassDecl loc [] (apt [ct,xt]) []
, hsInstDecl loc [] (apt [ct,at]) []
])
, ("Context errors",
[ hsDataDecl loc [] [at] [] []
, hsDataDecl loc [] [bt,xt] [] []
, hsClassDecl loc [] (apt [ct,xt]) []
, hsClassDecl loc [] (apt [dt,xt]) []
, hsInstDecl loc [xt] (apt [ct,at]) []
, hsInstDecl loc [dt] (apt [ct,at]) []
, hsInstDecl loc [apt[dt,apt[xt,yt]]] (apt [ct,apt [bt,xt]]) []
])
, ("",
[ hsDataDecl loc [] [at] [] []
, hsClassDecl loc [] (apt [ct,xt]) [ hsTypeSig loc [fn] [] (xt `arr` xt) ]
, hsInstDecl loc [] (apt [ct,at])
[ hsTypeSig loc [fn] [] (xt `arr` xt)
, hsFunBind loc [HsMatch loc fn [xp] (HsBody(hsEVar xn)) []]
, hsFunBind loc [HsMatch loc gn [xp] (HsBody(hsEVar yn)) []]
]
])
, ("OK", [ hsDataDecl loc [] [at] [] []
, hsDataDecl loc [] [bt,xt] [] []
, hsClassDecl loc [] (apt [ct,xt]) []
, hsClassDecl loc [] (apt [dt,xt]) []
, hsInstDecl loc [] (apt [ct,at]) []
, hsInstDecl loc [apt [dt,xt]] (apt [ct,apt [bt,xt]]) []
])
, ("class/type name conflict",
[ hsDataDecl loc [] [at] [] []
, hsDataDecl loc [] [bt] [] []
, hsInstDecl loc [] (apt [at,bt]) []
, hsInstDecl loc [] (apt [ct,bt]) []
] )
]
dts = [ ("", [ hsDataDecl loc [] [at,bt] [] [] ] )
, ("", [ hsDataDecl loc [] [xt,yt] [] [] ] )
]
clss = [ ("OK", [hsClassDecl loc [] (apt [ct,xt]) []])
, ("ill formed class specification", [hsClassDecl loc [] (ct) []])
, ("ill formed class specification", [hsClassDecl loc [] (xt) []])
, ("class/type name conflict",
[ hsDataDecl loc [] [at] [] []
, hsDataDecl loc [] [bt] [] []
, hsClassDecl loc [] (apt [at,xt]) []
, hsClassDecl loc [] (apt [bt,xt]) []
] )
, ("ill formed class specification",
[ hsClassDecl loc [] (apt [ct,at]) []
] )
, ("ill formed class specification",
[ hsClassDecl loc [] (apt [ct,at]) []
, hsClassDecl loc [] (apt [dt,at]) []
] )
, ("ill formed class specification",
[ hsDataDecl loc [] [at] [] []
, hsClassDecl loc [] (apt [ct,at]) []
] )
, ("",
[ hsClassDecl loc [] (apt [ct,xt])
[ hsTypeSig loc [fn] [] (arr xt xt)
, hsPatBind loc fp (HsBody (hsLambda [xp] xe)) []
, hsPatBind loc gp (HsBody (hsLambda [xp] xe)) []
]
] )
]
patBind p e = hsPatBind loc p (HsBody e) []
d1 = [patBind fp (hsLambda [xp] xe), patBind fp (hsLambda [xp] (xe))]
{-
p2 = [hsTypeSig loc [zn] (TypeUnQual$ hsTyCon (UnQual "Int"))]
p3 = [hsTypeSig loc [yn,yn] (TypeUnQual $ Typ $ HsTyCon (UnQual "Int"))]
p4 = [patBind fp (hsLet [patBind xp ye] xe)]
p5 = [patBind fp (hsLambda [xp] (ye))]
p6 = [patBind fp (hsLambda [hsPTuple [xp, xp], xp] ye)]
p7 = [patBind fp (hsLambda [hsPTuple [xp, xp, xp], xp] ye)]
runP p = let (envt,f) = chP loc p in f (envt env0)
-}
-----------------------------------------------------------------------------
-- computing free variables
-- Computing free variables is a tricky computation, because the same variable
-- may be free in one spot and bound in another. We need an environment to
-- determine what variables are bound at any particular point. We use a list
-- of HsName as the environment
-- Given an expression and an environment telling what vars are bound
-- determine the free variables in the expression.
freeE :: HsExp -> [HsName] -> [HsName]
freeE (Exp x) env =
case scopE env (mapE freeE freeP freeD freeT freeC x) of
HsId(HsVar s) -> if elem s env then [] else [s]
HsInfixApp x (HsVar s) y -> if elem s env then [] else [s]
HsLeftSection x (HsVar s) -> if elem s env then [] else [s]
HsRightSection (HsVar s) x -> if elem s env then [] else [s]
x -> accE (++) (++) (++) (++) (++) x []
-- Return a pair of functions. The first is an env transformer, adding
-- the vars in the pattern, the second is a function given an env, which
-- determines the free vars in the pattern. The second is the constant []
-- function since patterns only introduce variables, they only have binding
-- occurences.
freeP :: HsPat -> ([HsName]->[HsName],[HsName]->[HsName])
freeP p = ((vs++),const [])
where vs = boundInP p []
-- Return a pair of functions. The first is an env transformer, adding
-- the vars declared by the list of Decls, the second is a function which
-- when given an env, determines the free vars in the Decls
freeD :: [HsDecl] -> ([HsName]->[HsName],[HsName]->[HsName])
freeD ds = (ext,free)
where bound = foldr add [] ds
ext env = bound ++ env
add (Dec (HsPatBind s p rhs ds)) env = boundInP p env
add (Dec (HsFunBind s ((HsMatch s2 nm ps rhs ds):_))) env = nm : env
add (Dec (HsDataDecl s ctx typats condecls derivings)) env =
getTyName (head typats) : env
add (Dec (HsTypeDecl s typats t)) env = getTyName (head typats) : env
add d env = env
getNameOfTypat (Typ x) =
case x of
HsTyApp l _ -> getNameOfTypat l
HsTyCon n -> n
HsTyVar n -> n
_ -> error "getNameOfTypat "
free env = (foldr (f env) [] ds) \\ bound
f env (Dec d) ans =
accD (++)(++)(++)(++)(++)(++)
(scopD env (mapD (\ x -> ( (freeE x))) freeP freeD freeT freeC freeTP d)) ans
ff env (Dec d) ans =
accD (++)(++)(++)(++)(++)(++)
(scopD env (mapD (\ x -> ( (freeE x))) freeP freeD freeT freeC freeTP d)) ans
instance Env [HsName] where
extClass n l a args env = env
extTconstr n l a b env = n:env
extTvar n env = n:env
extConstr n l a env = n:env
extVar n l env = n:env
extSig n l env = env
extMod n env = env
env0 = []
restrictTvar env = env
-- Given an environment holding bound variables, return the
-- free variables in the HsType
freeT :: HsType -> [HsName] -> [HsName]
freeT (Typ x) env =
case scopT env (mapT freeT x) of
HsTyCon n -> if elem n env then [] else [n]
HsTyVar n -> if elem n env then [] else [n]
x -> accT (union) x []
allFree :: HsType -> [HsName] -> [HsName]
allFree (Typ x) ans =
case x of
HsTyCon n -> union [n] ans
HsTyVar n -> union [n] ans
x -> accT allFree x ans
-- compute the free variables in a context.
freeC :: [HsType] -> [HsName] -> [HsName]
freeC x env = concat (map (\z -> freeT z env) x)
-- Type patterns are HsTYpes which act as binding occurences. Hence
-- they return a pair. First an env transformer, and Second a function
-- that given an env, computes the TypePatterns free variables. Like patterns
-- this always returns []
freeTP :: HsType -> ([HsName] -> [HsName],[HsName] -> [HsName])
freeTP x = (allFree x,const [])
makeSCC ds env =
let (envtrans,_) = freeD ds
bound = envtrans []
oneD d = let (_,free) = freeD [d] in free env
oneBind d = let (envt,_) = freeD [d] in envt []
allFree = map oneD ds
allBound = map oneBind ds
in (allFree,allBound)
--------------------------------------------------------------------------
-- Contexts
--------------------------------------------------------------------------
-- type patterns appear in 4 different contexts
data TPContext = DataLikeTP | ClassTP | InstTP | SigTP
instance Show TPContext where
show DataLikeTP = "type, data, or newtype declaration"
show ClassTP = "class declaration"
show InstTP = "instance declaration"
show SigTP = "type signature"
-----------------------------------------------------------------
-- Lists of declarations can appear in four different contexts
-- Only certain kinds of declarations are legal in some of these.
data DeclContext = TopDecl | ClassDecl | InstDecl | WhereLikeDecl deriving (Eq)
instance Show DeclContext where
show TopDecl = "top level"
show ClassDecl = "class declaration"
show InstDecl = "class declaration"
show WhereLikeDecl = "local declaration"
legal :: DeclContext -> HsDecl -> Maybe Error
legal context (d @ (Dec x)) =
let err context x = Just (srcloc x,
"Illegal "++ whatIs x ++" in " ++ show context)
in case (context,x) of
(TopDecl, any) -> Nothing
(ClassDecl, HsTypeSig _ _ _ _) -> Nothing
(ClassDecl, HsFunBind _ _) -> Nothing
(ClassDecl, HsPatBind _ (Pat(HsPId(HsVar _))) _ _) -> Nothing
(ClassDecl, any) -> err context x
(InstDecl, HsFunBind _ _) -> Nothing
(InstDecl, HsPatBind _ (Pat(HsPId(HsVar _))) _ _) -> Nothing
(InstDecl, any) -> err context x
(WhereLikeDecl, HsTypeSig _ _ _ _) -> Nothing
(WhereLikeDecl, HsFunBind _ _) -> Nothing
(WhereLikeDecl, HsPatBind _ _ _ _) -> Nothing
(WhereLikeDecl, any) -> err context x
-----------------------------------------------------------------------
-- MapD' is like mapD, except it know what kind of contexts are
-- appropriate and passes this information downwards
mapD' :: (a -> b) -> (c -> d) -> (DeclContext -> e -> f) -> (g -> h) -> (DeclContext -> i -> j)
-> (TPContext -> k -> l) -> D a c e g i k -> D b d f h j l
mapD' ef pf df tf cf tpf decl =
case decl of
HsTypeDecl s tps t ->
HsTypeDecl s (map (tpf DataLikeTP) tps) (tf t)
HsNewTypeDecl s cntxt tps cd names ->
HsNewTypeDecl s (cf TopDecl cntxt)
(map (tpf DataLikeTP) tps) (mapConDecl tf cd) names
HsDataDecl s cntxt tps cds names ->
HsDataDecl s (cf TopDecl cntxt)
(map (tpf DataLikeTP) tps)
(map (mapConDecl tf) cds) names
HsClassDecl s c tp ds ->
HsClassDecl s (cf ClassDecl c) (tpf ClassTP tp) (df ClassDecl ds)
HsInstDecl s c tp ds ->
HsInstDecl s (cf InstDecl c) (tpf InstTP tp) (df InstDecl ds)
HsDefaultDecl s t ->
HsDefaultDecl s (tf t)
HsTypeSig s nms c t ->
HsTypeSig s nms (cf TopDecl c) (tpf SigTP t)
HsFunBind s matches ->
HsFunBind s (map (mapMatch ef pf (df WhereLikeDecl)) matches)
HsPatBind s p rhs ds ->
HsPatBind s (pf p) (mapRhs ef rhs) (df WhereLikeDecl ds)
HsPrimitiveTypeDecl s cntxt nm ->
HsPrimitiveTypeDecl s (cf TopDecl cntxt) nm
HsPrimitiveBind s nm t ->
HsPrimitiveBind s nm (tf t) -- Hugs compatibility
-------------------------------------------------------------------
-------------------------------------------------------------------
-- Static Checking using Bind based scoping
-------------------------------------------------------------------------
-- Example extend function for the static env Senv of the static checker
-- extTvar nm env = env {tvarNames = (nm) : tvarNames env}
extend :: Bind -> Senv -> Senv
extend (Bpat loc pat) env = foldr extName env uniqueNames
where (uniqueNames,dups,constrArities) = patBound pat ([],[],[])
extName nm env = env {varNames = (nm,loc) : varNames env}
extend (Bpats loc ps) env = foldr extend env (map (Bpat loc) ps)
extend (Bdecls ds) env = allNames ds env
extend (Bname loc nm) env = env {varNames = (nm,loc) : varNames env}
extend (Btypat tag tp) env =
case tag of
ClassTag -> -- (Env e x) -- expects (C v1 ... vn)
let (constr, tvs) = typePatToParts tp
in foldr extTvar env tvs
InstTag -> -- (Env [Int] Bool) -- expects (C t1 ... tn)
let (classname, ts) = instPatToParts tp
(tvs, cs) = foldr allTypNames ([], []) ts
in foldr extTvar env tvs
SigTag -> -- (e : typ)
let (tvs, cs) = allTypNames tp ([], [])
in foldr extTvar env tvs
extend (Btypats tag (tps @ (constr : args))) env =
case tag of
DataTPS -> foldr (\ t e -> extTvar (getTyName t) e) env tps
TypeTPS -> foldr (\ t e -> extTvar (getTyName t) e) env args
staticlib = Sc extend restrictTvar
------------------------------------------------------------------
-- Static checks for expressions
checkE :: SrcLoc -> HsExp -> Senv -> [Error]
checkE loc (exp @ (Exp x)) env =
case scopeE staticlib env
(mapE (checkE loc) (checkP loc)
(checkDs WhereLikeDecl) (checkT loc) (checkCnxt loc WhereLikeDecl) x) of
HsId (HsVar n) -> chk loc (not (varDefined n env)) (undefined_variable n)
HsInfixApp x (HsVar n) y -> chk loc (not (varDefined n env)) (undefined_variable n)
HsLeftSection x (HsVar n) -> chk loc (not (varDefined n env)) (undefined_variable n)
HsRightSection (HsVar n) x -> chk loc (not (varDefined n env)) (undefined_variable n)
HsLambda ps e -> e ++ (checkPList loc env ps)
z -> accE (++) (\ (nm,err) a -> err ++ a) (++) (++) (++) z []
-----------------------------------------------------------------------------
-- When language constructs have a list of patterns like : (\ p1 ... pn -> e)
-- or (case x of { C p1 ... pn -> e }), Haskell has the rule that no variable
-- should appear more than once in the list. We can't check this, pattern by
-- pattern, but have to observe the complete list. If we map (chP env) over a
-- list of patterns we get [([unique_names],[error_messages])], from this we
-- can compute additional error_messages dealing with duplicates.
checkPList :: SrcLoc -> Senv -> [([HsName],[Error])] -> [Error]
checkPList loc env ps =
let accumulate (ns,errs) (names,errors) = (ns++names,errs++errors)
(allbound,internalerr) = foldr accumulate ([],[]) ps
dups = duplicates allbound
duperr = chk loc (not (null dups)) (repeated_pattern_variables dups)
in internalerr ++ duperr
--------------------------------------------
-- Static checks for individual patterns
checkP :: SrcLoc -> HsPat -> (HsPat, Senv -> ([HsName],[Error]))
checkP loc (pat @ (Pat x)) = (pat, f)
where (uniqueNames,dups,constrArities) = patBound pat ([],[],[])
duperr = chk loc (not (null dups)) (duplicate_vars_in_pattern dups)
f env = (uniqueNames,allErrors env)
allErrors env = foldr arityCheck duperr constrArities
where arityCheck (c,n) ans = check c n (cArity c env) ++ ans
check c n Nothing = [(loc,undefined_constr c)]
check c n (Just m) = chk loc (m /=n) (constr_wrong_arity n c)
------------------------------------------------------------------------------
-- Static Check for Expressions
-- checkDs assumes that all the names in the [Decl] have already been added
-- to the environment which is passed to checkDs result function.
-- e.g. in scopeE for HsLet we say:
-- HsLet (ds,f) e ->
-- let env2 = ext (Bdecls ds) env
-- in HsLet (f env2) (e env2)
-- note how we compute the new env, and pass it to both the ds and the f
checkDs :: DeclContext -> [HsDecl] -> ([HsDecl],Senv -> [Error])
checkDs contxt ds = (ds,errorfun)
where env = allNames ds env0
errorfun env = foldr (\ d ans -> (check env d) ++ ans) allErrors ds
sameName (x,y) (a,b) = compare x a
contextErrors = catMaybes $ map (legal contxt) ds
dupErr k message = collect_duplicate_info (dupErrs message) sameName (locations k env)
dupValErrors = dupErr Var "value definitions"
dupSigErrors = dupErr Sig "type signatures"
dupClsErrors = dupErr Class "class definitions"
dupTypErrors = dupErr TyCons "type definitions"
dupConsErrors = dupErr Cons "constructor functions"
allErrors = contextErrors++dupValErrors++dupSigErrors++dupClsErrors
++ dupTypErrors ++ dupConsErrors ++ nmConflict env ++ clsMethodErr
sigerr loc name = chk loc ((not $ elem name (map fst (varNames env))) && contxt/=ClassDecl)
(signature_without_definition name)
methodErr c (nm,loc) = chk loc (not $ isMethod nm c env) (not_a_method nm c)
clsMethodErr = case contxt of
ClassDecl -> classMethodErr env
other -> []
check env (Dec x) =
let loc = srcloc x
methodErrs (HsInstDecl loc c tp ds) =
let nms = varNames $ allNames ds env0
in case getClass tp of
Nothing -> []
Just c -> concat $ map (methodErr c) nms
in
case scopeD staticlib env
(mapD' (checkE loc) (checkP loc) (checkDs)
(checkT loc) (checkCnxt loc) (checkTp loc) x) of
HsTypeSig loc nms c t -> (concat $ map (sigerr loc) nms)++c++t
HsInstDecl loc c tp ds -> methodErrs x ++ c ++ tp ++ ds
z -> accD (++) (\ (ns,errs) a -> (errs)++a) (++) (++) (++) (++) z []
---------------------------------------------------------------------------
-- static checks for types
checkT :: SrcLoc -> HsType -> Senv -> [Error]
checkT loc (typ @ (Typ t)) env =
case t of
HsTyVar nm -> chk loc (not (tvarDefined nm env)) (undefined_tvar nm)
HsTyCon nm -> chk loc (not (tconDefined nm env)) (undefined_tcon nm)
HsTyApp (y @ (Typ f)) x -> synArityCheck (checkT loc) env f x 1
z -> accT (++) (scopeT env (mapT (checkT loc) z)) []
synArityCheck chf env typ arg n =
case typ of
(HsTyCon c) ->
case synArity c env of
Nothing -> chk loc (not (tconDefined c env)) (undefined_tcon c) ++ chf arg env
Just m -> chk loc (m/=n) (tysynonym_not_fully_applied c) ++ chf arg env
(HsTyApp (Typ f) x) -> synArityCheck chf env f x (n+1) ++ chf arg env
t -> chf (Typ t) env ++ chf arg env
----------------------------------------------------------------------
-- Static Checking for contexts
checkCnxt :: SrcLoc -> DeclContext -> [HsType] -> Senv -> [Error]
checkCnxt loc c ts env = foldr (check c) [] ts
where inscope (Typ (HsTyVar x)) ans =
chk loc (not $ tvarDefined x env) (undefined_tvar_in_context x) ++ ans
inscope (Typ (HsTyCon c)) ans =
chk loc (not $ classDefined c env) (undefined_class_in_context c) ++ ans
inscope (Typ x) ans = accT inscope x ans
-- class: C (x t*)+
wfClass t (Typ (HsTyApp (Typ (HsTyCon c)) x )) xs =
wfClassArg x x xs
wfClass t (Typ (HsTyApp x y )) xs =
wfClass t x $ wfClassArg x x xs
wfClass t (Typ x) xs =
(loc, illformed_class t) : xs
-- class arg: x t*
wfClassArg t (Typ (HsTyVar y)) xs = xs
wfClassArg t (Typ (HsTyApp x _)) xs = wfClassArg t x xs
wfClassArg t (Typ x) xs = (loc, illformed_class_arg t) : xs
check ClassDecl x ans = wfSclass loc x (inscope x ans)
check InstDecl x ans = wfSclass loc x (inscope x ans)
check _ x ans = wfClass x x (inscope x ans)
---------------------------------------------------------------------
-- Static checks for type-patterns
--checkTp :: SrcLoc -> TPContext -> HsType -> (HsType,Senv -> [Error])
checkTp :: SrcLoc -> TPContext -> HsType -> (HsType, Senv -> [Error])
checkTp srcloc InstTP x =
let errors = wf x []
-- well formed instance: C (C x*)+
wf (Typ(HsTyApp (Typ(HsTyCon c)) arg)) xs =
wfTp srcloc InstTP arg xs
wf (Typ(HsTyCon c)) xs =
(srcloc, instance_required c) : xs
wf (Typ(HsTyApp y arg)) xs =
wf y (wfTp srcloc InstTP arg xs)
wf tp xs =
(srcloc, instance_not_class_app tp) : xs
(classname, ts) = instPatToParts x
(tvs, cs) = foldr allTypNames ([], []) ts
clsError env = chk srcloc (not $ classDefined classname env)
(undefined_class_in_instance classname)
cdef env c ans =
if tconDefined c env
then case synArity c env of
Nothing -> ans
Just _ -> (srcloc, synonym_illegal_in_instance c):ans
else (srcloc,undefined_tcon_in_instance c):ans
dupErrs = collect_duplicate_info (dupTvErr srcloc) compare tvs
tpf env = if null errors
then foldr (cdef env) (dupErrs ++ clsError env) cs
else errors
in (x, tpf)
checkTp srcloc SigTP x =
let (_, cs) = allTypNames x ([], [])
cdef env c ans =
if tconDefined c env
then ans
else (srcloc, undefined_tcon_in_signature c):ans
tpf env = foldr (cdef env) [] cs
in (x, tpf)
checkTp srcloc cntxt x =
let (_, tvs) = typePatToParts x
errors = case cntxt of DataLikeTP -> wfTp srcloc cntxt x []
ClassTP -> wfSclass srcloc x []
tpf env = if null errors
then collect_duplicate_info (dupTvErr srcloc) compare tvs
else errors
in (x, tpf)
-----------------------------------------------------------------
-- Running the basic tests
run2 env prog = let (ds,f) = checkDs TopDecl prog in (f (allNames ds env))
new (_,x) = run2 env0 x
old (_,x) = run env0 x
test2 :: (String,[HsDecl]) -> IO ()
test2 (s, ds) =
do { putStr "\n==============================================\n"
; putStr s
; putStr "\n--- test code----------\n"
; sh ds
; putStr "\n--- errors ------------\n"
; (putStr . unlines . map showErr . run2 env0) ds
}
tests2 ts = sequence_ (map test2 ts)
errors1 ts = map (run2 env0) (map snd ts)
errors2 ts = map (run env0) (map snd ts)
new1 = errors1 insts
old1 = errors2 insts
oks = zipWith (==) old1 new1
[x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11] = insts
gg x = concat(map (\ (y,_,_,_) -> show y) (classNames x))
------------------------------------------------------------------
-- extra stuff
-- supply a unique integer string
count :: IORef Int
count = unsafePerformIO $ newIORef 0
initCount = writeIORef count 10
incCount a = unsafePerformIO $ do { c <- readIORef count
; writeIORef count $! (c+1)
; return c
}
uniqueStr a = show $ incCount ()
| forste/haReFork | tools/base/SA/ScopeRec.hs | bsd-3-clause | 48,944 | 523 | 40 | 14,338 | 17,219 | 9,283 | 7,936 | 824 | 12 |
module Main where
class C a where
op :: (Show a, Show b) => a -> b -> String
-- This class op adds a constraint on 'a'
-- In GHC 7.0 this is fine, and it's a royal
-- pain to reject it when in H98 mode, so
-- I'm just allowing it
instance C Int where
op x y = show x ++ " " ++ show y
main = print (op (1::Int) 2)
| green-haskell/ghc | testsuite/tests/typecheck/should_fail/tcfail149.hs | bsd-3-clause | 326 | 0 | 9 | 89 | 99 | 53 | 46 | 6 | 1 |
{-# LANGUAGE TypeFamilies, StandaloneDeriving #-}
-- Crashed 6.12
module T1769 where
data family T a
deriving instance Functor T
| urbanslug/ghc | testsuite/tests/indexed-types/should_fail/DerivUnsatFam.hs | bsd-3-clause | 140 | 0 | 5 | 30 | 19 | 13 | 6 | 4 | 0 |
{-# LANGUAGE TypeFamilies #-}
module ShouldFail where
class C3 a where
data S3 a :: *
data S3n a :: *
foo3 :: a -> S3 a
foo3n :: a -> S3n a
bar3 :: S3 a -> a
bar3n :: S3n a -> a
instance C3 Int where
data S3 Int = D3Int
newtype S3n Int = D3Intn ()
foo3 _ = D3Int
foo3n _ = D3Intn ()
bar3 D3Int = 1
bar3n (D3Intn _) = 1
instance C3 Char where
data S3 Char = D3Char
foo3 _ = D3Char
bar3 D3Char = 'c'
bar3' :: S3 Char -> Char
bar3' D3Char = 'a'
-- must fail: signature too general
bar3wrong :: S3 a -> a
bar3wrong D3Int = 1
| urbanslug/ghc | testsuite/tests/indexed-types/should_fail/SimpleFail5a.hs | bsd-3-clause | 605 | 0 | 8 | 205 | 228 | 117 | 111 | 24 | 1 |
-- !!! ds019 -- mixed var and uni-constructor pats
module ShouldCompile where
f (a,b,c) i o = []
f d (j,k) p = []
f (e,f,g) l q = []
f h (m,n) r = []
| forked-upstream-packages-for-ghcjs/ghc | testsuite/tests/deSugar/should_compile/ds019.hs | bsd-3-clause | 172 | 0 | 6 | 58 | 91 | 52 | 39 | 5 | 1 |
module Frontend.Monomorphise (monomorphise) where
import Control.Applicative
import Control.Monad.Reader
import Control.Monad.State
import Data.Maybe
import Data.Map (Map)
import qualified Data.Map as M
import qualified Data.Set as S
import Data.Bifunctor
import Data.Bitraversable
import Frontend.AST
import Frontend.Types
import Frontend.Alpha
import Internal
-- Monomorphise
monomorphise :: AnnProgram -> Fresh AnnProgram
monomorphise = bimapM return $ runMono . monoExpr
type Instantiate = Map [Type] Name
type VariableUse = Map Name Instantiate
type Mono a = ReaderT TypeSubst (StateT VariableUse Fresh) a
runMono :: Mono a -> Fresh a
runMono = flip evalStateT M.empty . flip runReaderT M.empty
withSubst :: [(TypeVar, Type)] -> Mono a -> Mono a
withSubst s = local $ flip (foldr $ uncurry bind) s
replaceType :: Type -> Mono Type
replaceType t = f <$> asks (flip subst t)
where
-- replace free type variables with unit type
f (DataType targs tcon) = DataType (map f targs) tcon
f (TypeVar v) = UnitType
f (FunType t1 t2) = FunType (f t1) (f t2)
f (TupleType ts) = TupleType (map f ts)
f t = t
useOf :: Name -> Mono Instantiate
useOf name = gets $ fromMaybe M.empty . M.lookup name
monoExpr :: AnnExpr -> Mono AnnExpr
monoExpr (AVar name []) = return $ AVar name []
monoExpr (AVar name targs) = do
targs' <- mapM replaceType targs
use <- useOf name
case M.lookup targs' use of
Just name' -> return $ AVar name' []
Nothing -> do
name' <- flip rename name <$> fresh
modify $ M.insert name $ M.insert targs' name' use
return $ AVar name' []
monoExpr (AValue val) = return $ AValue val
monoExpr (AIf e1 e2 e3) =
AIf <$> monoExpr e1 <*> monoExpr e2 <*> monoExpr e3
monoExpr (ALet d e) =
foldr ALet <$> monoExpr e <*> monoDecl d
monoExpr (AMatch e alts) =
AMatch <$> monoExpr e <*> mapM monoAlt alts
monoExpr (AFun b e) =
AFun <$> bimapM return replaceType b <*> monoExpr e
monoExpr (AApply e1 e2) =
AApply <$> monoExpr e1 <*> monoExpr e2
monoExpr (AOp op es) =
AOp op <$> mapM monoExpr es
monoExpr (ACon con tcon targs es) = do
targs' <- mapM replaceType targs
ACon con tcon targs' <$> mapM monoExpr es
monoExpr (ATuple es) =
ATuple <$> mapM monoExpr es
monoExpr (AExt s t ns) = return $ AExt s t ns
monoDecl :: AnnDecl -> Mono [AnnDecl]
monoDecl (ARecDecl (name, TypeScheme [] t) e) = do
t' <- replaceType t
(:[]) . ARecDecl (name, TypeScheme [] t') <$> monoExpr e
monoDecl (ARecDecl (name, TypeScheme vs t) e) = do
use <- useOf name
forM (M.toList use) $ \(targs, name') -> do
withSubst (zip vs targs) $ do
t' <- replaceType t
let alphaEnv = M.singleton name name'
e' <- lift . lift $ alpha alphaEnv e
ARecDecl (name', TypeScheme [] t') <$> monoExpr e'
monoDecl (ADecl (name, TypeScheme [] t) e) = do
t' <- replaceType t
(:[]) . ADecl (name, TypeScheme [] t') <$> monoExpr e
monoDecl (ADecl (name, TypeScheme vs t) e) = do
use <- useOf name
forM (M.toList use) $ \(targs, name') ->
withSubst (zip vs targs) $ do
t' <- replaceType t
e' <- lift . lift $ alpha M.empty e
ADecl (name', TypeScheme [] t') <$> monoExpr e'
monoDecl (ATupleDecl bs@((_, TypeScheme [] _):_) e) = do
let ts = map (\(_, TypeScheme _ t) -> t) bs
bs' <- zip (map fst bs) <$> mapM (replaceType >=> return . TypeScheme []) ts
(:[]) . ATupleDecl bs' <$> monoExpr e
monoDecl (ATupleDecl bs@((_, TypeScheme vs _):_) e) = do
uses <- mapM (useOf . fst) bs
let ts = map (\(_, TypeScheme _ t) -> t) bs
use = map (\targs -> (targs, map (fromMaybe Erased . M.lookup targs) uses)) $
S.toList $ S.unions $ map M.keysSet uses
forM use $ \(targs, names) ->
withSubst (zip vs targs) $ do
bs' <- zip names <$> mapM (replaceType >=> return . TypeScheme []) ts
e' <- lift . lift $ alpha M.empty e
ATupleDecl bs' <$> monoExpr e'
monoAlt :: AnnAlt -> Mono AnnAlt
monoAlt (AConCase con tcon targs bs e) = do
targs' <- mapM replaceType targs
bs' <- mapM (bimapM return replaceType) bs
AConCase con tcon targs' bs' <$> monoExpr e
monoAlt (ADefaultCase e) =
ADefaultCase <$> monoExpr e
| alpicola/mel | src/Frontend/Monomorphise.hs | mit | 4,137 | 0 | 21 | 915 | 1,899 | 928 | 971 | -1 | -1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.Location
(js_assign, assign, js_replace, replace, js_reload, reload,
js_toString, toString, js_setHref, setHref, js_getHref, getHref,
js_setProtocol, setProtocol, js_getProtocol, getProtocol,
js_setHost, setHost, js_getHost, getHost, js_setHostname,
setHostname, js_getHostname, getHostname, js_setPort, setPort,
js_getPort, getPort, js_setPathname, setPathname, js_getPathname,
getPathname, js_setSearch, setSearch, js_getSearch, getSearch,
js_setHash, setHash, js_getHash, getHash, js_getOrigin, getOrigin,
js_getAncestorOrigins, getAncestorOrigins, Location,
castToLocation, gTypeLocation)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"assign\"]($2)" js_assign ::
Location -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.assign Mozilla Location.assign documentation>
assign :: (MonadIO m, ToJSString url) => Location -> url -> m ()
assign self url = liftIO (js_assign (self) (toJSString url))
foreign import javascript unsafe "$1[\"replace\"]($2)" js_replace
:: Location -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.replace Mozilla Location.replace documentation>
replace :: (MonadIO m, ToJSString url) => Location -> url -> m ()
replace self url = liftIO (js_replace (self) (toJSString url))
foreign import javascript unsafe "$1[\"reload\"]()" js_reload ::
Location -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.reload Mozilla Location.reload documentation>
reload :: (MonadIO m) => Location -> m ()
reload self = liftIO (js_reload (self))
foreign import javascript unsafe "$1[\"toString\"]()" js_toString
:: Location -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.toString Mozilla Location.toString documentation>
toString ::
(MonadIO m, FromJSString result) => Location -> m result
toString self = liftIO (fromJSString <$> (js_toString (self)))
foreign import javascript unsafe "$1[\"href\"] = $2;" js_setHref ::
Location -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.href Mozilla Location.href documentation>
setHref :: (MonadIO m, ToJSString val) => Location -> val -> m ()
setHref self val = liftIO (js_setHref (self) (toJSString val))
foreign import javascript unsafe "$1[\"href\"]" js_getHref ::
Location -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.href Mozilla Location.href documentation>
getHref :: (MonadIO m, FromJSString result) => Location -> m result
getHref self = liftIO (fromJSString <$> (js_getHref (self)))
foreign import javascript unsafe "$1[\"protocol\"] = $2;"
js_setProtocol :: Location -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.protocol Mozilla Location.protocol documentation>
setProtocol ::
(MonadIO m, ToJSString val) => Location -> val -> m ()
setProtocol self val
= liftIO (js_setProtocol (self) (toJSString val))
foreign import javascript unsafe "$1[\"protocol\"]" js_getProtocol
:: Location -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.protocol Mozilla Location.protocol documentation>
getProtocol ::
(MonadIO m, FromJSString result) => Location -> m result
getProtocol self
= liftIO (fromJSString <$> (js_getProtocol (self)))
foreign import javascript unsafe "$1[\"host\"] = $2;" js_setHost ::
Location -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.host Mozilla Location.host documentation>
setHost :: (MonadIO m, ToJSString val) => Location -> val -> m ()
setHost self val = liftIO (js_setHost (self) (toJSString val))
foreign import javascript unsafe "$1[\"host\"]" js_getHost ::
Location -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.host Mozilla Location.host documentation>
getHost :: (MonadIO m, FromJSString result) => Location -> m result
getHost self = liftIO (fromJSString <$> (js_getHost (self)))
foreign import javascript unsafe "$1[\"hostname\"] = $2;"
js_setHostname :: Location -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.hostname Mozilla Location.hostname documentation>
setHostname ::
(MonadIO m, ToJSString val) => Location -> val -> m ()
setHostname self val
= liftIO (js_setHostname (self) (toJSString val))
foreign import javascript unsafe "$1[\"hostname\"]" js_getHostname
:: Location -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.hostname Mozilla Location.hostname documentation>
getHostname ::
(MonadIO m, FromJSString result) => Location -> m result
getHostname self
= liftIO (fromJSString <$> (js_getHostname (self)))
foreign import javascript unsafe "$1[\"port\"] = $2;" js_setPort ::
Location -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.port Mozilla Location.port documentation>
setPort :: (MonadIO m, ToJSString val) => Location -> val -> m ()
setPort self val = liftIO (js_setPort (self) (toJSString val))
foreign import javascript unsafe "$1[\"port\"]" js_getPort ::
Location -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.port Mozilla Location.port documentation>
getPort :: (MonadIO m, FromJSString result) => Location -> m result
getPort self = liftIO (fromJSString <$> (js_getPort (self)))
foreign import javascript unsafe "$1[\"pathname\"] = $2;"
js_setPathname :: Location -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.pathname Mozilla Location.pathname documentation>
setPathname ::
(MonadIO m, ToJSString val) => Location -> val -> m ()
setPathname self val
= liftIO (js_setPathname (self) (toJSString val))
foreign import javascript unsafe "$1[\"pathname\"]" js_getPathname
:: Location -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.pathname Mozilla Location.pathname documentation>
getPathname ::
(MonadIO m, FromJSString result) => Location -> m result
getPathname self
= liftIO (fromJSString <$> (js_getPathname (self)))
foreign import javascript unsafe "$1[\"search\"] = $2;"
js_setSearch :: Location -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.search Mozilla Location.search documentation>
setSearch :: (MonadIO m, ToJSString val) => Location -> val -> m ()
setSearch self val = liftIO (js_setSearch (self) (toJSString val))
foreign import javascript unsafe "$1[\"search\"]" js_getSearch ::
Location -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.search Mozilla Location.search documentation>
getSearch ::
(MonadIO m, FromJSString result) => Location -> m result
getSearch self = liftIO (fromJSString <$> (js_getSearch (self)))
foreign import javascript unsafe "$1[\"hash\"] = $2;" js_setHash ::
Location -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.hash Mozilla Location.hash documentation>
setHash :: (MonadIO m, ToJSString val) => Location -> val -> m ()
setHash self val = liftIO (js_setHash (self) (toJSString val))
foreign import javascript unsafe "$1[\"hash\"]" js_getHash ::
Location -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.hash Mozilla Location.hash documentation>
getHash :: (MonadIO m, FromJSString result) => Location -> m result
getHash self = liftIO (fromJSString <$> (js_getHash (self)))
foreign import javascript unsafe "$1[\"origin\"]" js_getOrigin ::
Location -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.origin Mozilla Location.origin documentation>
getOrigin ::
(MonadIO m, FromJSString result) => Location -> m result
getOrigin self = liftIO (fromJSString <$> (js_getOrigin (self)))
foreign import javascript unsafe "$1[\"ancestorOrigins\"]"
js_getAncestorOrigins :: Location -> IO (Nullable DOMStringList)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Location.ancestorOrigins Mozilla Location.ancestorOrigins documentation>
getAncestorOrigins ::
(MonadIO m) => Location -> m (Maybe DOMStringList)
getAncestorOrigins self
= liftIO (nullableToMaybe <$> (js_getAncestorOrigins (self))) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/Location.hs | mit | 9,398 | 152 | 10 | 1,461 | 2,255 | 1,225 | 1,030 | 131 | 1 |
import XMonad
import XMonad.Util.Run
import qualified XMonad.StackSet as W
import XMonad.Hooks.DynamicLog
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.UrgencyHook
import XMonad.Layout.ResizableTile
import XMonad.Layout.NoBorders
import XMonad.Layout.PerWorkspace
import XMonad.Layout.Fullscreen
import XMonad.Layout.NoFrillsDecoration
import XMonad.Layout.Renamed
import System.Exit
import qualified Data.Map as M
myModMasks :: [KeyMask]
myModMasks = [altMask, winMask]
where altMask = mod1Mask
winMask = mod4Mask
myKeys :: XConfig Layout -> M.Map (KeyMask, KeySym) (X ())
myKeys conf = M.fromList $ concat $ flip map myModMasks (\modm ->
[ ((modm, xK_b ), sendMessage ToggleStruts) -- %! Toggle struts `aka panel`
, ((modm, xK_F10 ), spawn "amixer -D pulse set Master toggle")
, ((modm, xK_F11 ), spawn "amixer -D pulse set Master on && amixer -D pulse set Master 3%-")
, ((modm, xK_F12 ), spawn "amixer -D pulse set Master on && amixer -D pulse set Master 3%+")
, ((noModMask, xK_Print ), spawn "gnome-screenshot") -- %! Screenshot
, ((modm, xK_Print ), spawn "gnome-screenshot -i")
-- launching and killing programs
, ((modm .|. shiftMask, xK_Return), spawn $ XMonad.terminal conf) -- %! Launch terminal
, ((modm .|. shiftMask, xK_f ), spawn "nemo") -- %! Launch file manager
, ((modm .|. shiftMask, xK_g ), spawn "google-chrome") -- %! Launch web browser
, ((modm, xK_p ), spawn "xfce4-appfinder") -- %! Launch appfinder
, ((modm .|. shiftMask, xK_p ), spawn "synapse") -- %! Launch launcher
, ((modm .|. shiftMask, xK_c ), kill) -- %! Close the focused window
, ((modm, xK_space ), sendMessage NextLayout) -- %! Rotate through the available layout algorithms
, ((modm .|. shiftMask, xK_space ), setLayout $ XMonad.layoutHook conf) -- %! Reset the layouts on the current workspace to default
, ((modm, xK_n ), refresh) -- %! Resize viewed windows to the correct size
-- move focus up or down the window stack
, ((modm, xK_Tab ), windows W.focusDown) -- %! Move focus to the next window
, ((modm .|. shiftMask, xK_Tab ), windows W.focusUp ) -- %! Move focus to the previous window
, ((modm, xK_k ), windows W.focusDown) -- %! Move focus to the next window
, ((modm, xK_j ), windows W.focusUp ) -- %! Move focus to the previous window
, ((modm, xK_m ), windows W.focusMaster ) -- %! Move focus to the master window
-- modifying the window order
, ((modm, xK_Return), windows W.swapMaster) -- %! Swap the focused window and the master window
, ((modm .|. shiftMask, xK_j ), windows W.swapDown ) -- %! Swap the focused window with the next window
, ((modm .|. shiftMask, xK_k ), windows W.swapUp ) -- %! Swap the focused window with the previous window
-- resizing the master/slave ratio
, ((modm, xK_h ), sendMessage Shrink) -- %! Shrink the master area
, ((modm, xK_l ), sendMessage Expand) -- %! Expand the master area
, ((modm, xK_i ), sendMessage MirrorShrink)
, ((modm, xK_u ), sendMessage MirrorExpand)
-- floating layer support
, ((modm, xK_t ), withFocused $ windows . W.sink) -- %! Push window back into tiling
-- increase or decrease number of windows in the master area
, ((modm , xK_comma ), sendMessage (IncMasterN 1)) -- %! Increment the number of windows in the master area
, ((modm , xK_period), sendMessage (IncMasterN (-1))) -- %! Deincrement the number of windows in the master area
-- quit, or restart
, ((modm .|. shiftMask, xK_q ), io exitSuccess) -- %! Quit xmonad
, ((modm , xK_q ), spawn "if type xmonad; then xmonad --recompile && xmonad --restart; else xmessage xmonad not in \\$PATH: \"$PATH\"; fi") -- %! Restart xmonad
]
++
-- mod-[1..9] %! Switch to workspace N
-- mod-shift-[1..9] %! Move client to workspace N
do
let workspaceKeys = [xK_1 .. xK_9] ++ [xK_0, xK_minus, xK_equal]
(i, k) <- zip (XMonad.workspaces conf) workspaceKeys
(f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]
pure ((modm .|. m, k), windows $ f i)
++
-- mod-{w,e,r} %! Switch to physical/Xinerama screens 1, 2, or 3
-- mod-shift-{w,e,r} %! Move client to screen 1, 2, or 3
[((modm .|. m, key), screenWorkspace sc >>= flip whenJust (windows . f))
| (key, sc) <- zip [xK_w, xK_e, xK_r] [0..]
, (f, m) <- [(W.view, 0), (W.shift, shiftMask)]]
)
myWorkspaces :: [String]
myWorkspaces =
["1:Browser", "2:Dev", "3:Alpha", "4:Beta", "5:Gamma", "6:Delta", "7:Epsilon", "8:Zeta", "9:Eta", "0", "-", "="]
myLayoutHook = renamed [CutWordsLeft 1] $
fullscreenFocus . smartBorders . avoidStruts $
onWorkspaces (take 1 myWorkspaces) full $
deco tile ||| full -- ||| deco (Mirror tile) ||| deco Accordion
where
tile = renamed [Replace "Tall"] $ ResizableTall 1 (3/100) (1/2) []
full = renamed [PrependWords "Full"] $ noBorders Full
deco = noFrillsDeco shrinkText Theme
{ activeColor = "#000000"
, inactiveColor = "#000000"
, urgentColor = "#FF0000"
, activeBorderColor = "#ffffff"
, inactiveBorderColor = "#ffffff"
, urgentBorderColor = "#FF0000"
, activeTextColor = "#00FF00"
, inactiveTextColor = "#BFBFBF"
, urgentTextColor = "#FFFF00"
, fontName = "xft:Noto Sans CJK:size=12:antialias=true"
, decoWidth = 200
, decoHeight = 27
, windowTitleAddons = []
, windowTitleIcons = []
}
myManageHook = composeAll
[ className =? "Gimp" --> doFloat
, className =? "Xmessage" --> doFloat
, appName =? "vlc" --> doFloat
, appName =? "xfrun4" --> doFloat
, appName =? "xfce4-appfinder" --> doFloat
, appName =? "synapse" --> doIgnore
, appName =? "stalonetray" --> doIgnore
]
-- | Mouse bindings: default actions bound to mouse events
myMouseBindings :: XConfig Layout -> M.Map (KeyMask, Button) (Window -> X ())
myMouseBindings conf = M.fromList $ concat $ flip map myModMasks (\modm ->
-- mod-button1 %! Set the window to floating mode and move by dragging
[ ((modm, button1), \w -> focus w >> mouseMoveWindow w >> windows W.shiftMaster)
-- mod-button2 %! Raise the window to the top of the stack
, ((modm, button2), windows . (W.shiftMaster .) . W.focusWindow)
-- mod-button3 %! Set the window to floating mode and resize by dragging
, ((modm, button3), \w -> focus w >> mouseResizeWindow w >> windows W.shiftMaster)
-- you may also bind events to the mouse scroll wheel (button4 and button5)
]
)
main :: IO ()
main = do
xmobar <- spawnPipe "xmobar"
xmonad $ withUrgencyHook NoUrgencyHook $ def
{ modMask = mod1Mask
, terminal = myTerminal
, keys = myKeys
, workspaces = myWorkspaces
, mouseBindings = myMouseBindings
, focusFollowsMouse = True
, manageHook = manageDocks <+> fullscreenManageHook <+> myManageHook
, layoutHook = myLayoutHook
, borderWidth = 1
, normalBorderColor = "#FFFFFF"
, focusedBorderColor = "#FFFFFF"
, logHook = dynamicLogWithPP def
{ ppOutput = hPutStrLn xmobar
, ppCurrent = xmobarColor "yellow" "" . wrap "[ " " ]"
, ppTitle = xmobarColor "green" "" . shorten 80
, ppVisible = wrap "(" ")"
, ppUrgent = xmobarColor "red" "" . wrap "[ " " ]"
, ppSep = " "
}
, handleEventHook = fullscreenEventHook
}
where
myTerminal = "xfce4-terminal"
| silverneko/dotfiles | xmonad.hs | mit | 8,046 | 0 | 17 | 2,292 | 1,874 | 1,103 | 771 | 123 | 1 |
module Unison.Runtime.Debug
( traceComb
, traceCombs
, tracePretty
, tracePrettyGroup
) where
import Data.Word
import qualified Unison.Term as Tm
import Unison.Var (Var)
import Unison.PrettyPrintEnv (PrettyPrintEnv)
import Unison.TermPrinter (pretty)
import Unison.Util.Pretty (toANSI)
import Unison.Util.EnumContainers
import Unison.Runtime.ANF
import Unison.Runtime.MCode
import Debug.Trace
type Term v = Tm.Term v ()
traceComb :: Bool -> Word64 -> Comb -> Bool
traceComb False _ _ = True
traceComb True w c = trace (prettyComb w 0 c "\n") True
traceCombs
:: Word64
-> Bool
-> EnumMap Word64 Comb
-> EnumMap Word64 Comb
traceCombs _ False c = c
traceCombs w True c = trace (prettyCombs w c "") c
tracePretty
:: Var v
=> PrettyPrintEnv
-> Bool
-> Term v
-> Term v
tracePretty _ False tm = tm
tracePretty ppe True tm = trace (toANSI 50 $ pretty ppe tm) tm
tracePrettyGroup
:: Var v
=> Word64
-> Bool
-> SuperGroup v
-> SuperGroup v
tracePrettyGroup _ False g = g
tracePrettyGroup w True g = trace (prettyGroup (show w) g "") g
| unisonweb/platform | parser-typechecker/src/Unison/Runtime/Debug.hs | mit | 1,078 | 0 | 9 | 219 | 387 | 204 | 183 | 42 | 1 |
-- | A program to sanitize an HTML tag to a Haskell function.
--
module Util.Sanitize
( sanitize
, keywords
, prelude
) where
import Data.Char (toLower, toUpper)
import Data.Set (Set)
import qualified Data.Set as S
-- | Sanitize a tag. This function returns a name that can be used as
-- combinator in haskell source code.
--
-- Examples:
--
-- > sanitize "class" == "class_"
-- > sanitize "http-equiv" == "httpEquiv"
--
sanitize :: String -> String
sanitize str
| lower == "doctypehtml" = "docTypeHtml"
| otherwise = appendUnderscore $ removeDash lower
where
lower = map toLower str
-- Remove a dash, replacing it by camelcase notation
--
-- Example:
--
-- > removeDash "foo-bar" == "fooBar"
--
removeDash ('-' : x : xs) = toUpper x : removeDash xs
removeDash (x : xs) = x : removeDash xs
removeDash [] = []
appendUnderscore t | t `S.member` keywords = t ++ "_"
| otherwise = t
-- | A set of standard Haskell keywords, which cannot be used as combinators.
--
keywords :: Set String
keywords = S.fromList
[ "case", "class", "data", "default", "deriving", "do", "else", "if"
, "import", "in", "infix", "infixl", "infixr", "instance" , "let", "module"
, "newtype", "of", "then", "type", "where"
]
-- | Set of functions from the Prelude, which we do not use as combinators.
--
prelude :: Set String
prelude = S.fromList
[ "abs", "acos", "acosh", "all", "and", "any", "appendFile", "asTypeOf"
, "asin", "asinh", "atan", "atan2", "atanh", "break", "catch", "ceiling"
, "compare", "concat", "concatMap", "const", "cos", "cosh", "curry", "cycle"
, "decodeFloat", "div", "divMod", "drop", "dropWhile", "either", "elem"
, "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo", "enumFromTo"
, "error", "even", "exp", "exponent", "fail", "filter", "flip"
, "floatDigits", "floatRadix", "floatRange", "floor", "fmap", "foldl"
, "foldl1", "foldr", "foldr1", "fromEnum", "fromInteger", "fromIntegral"
, "fromRational", "fst", "gcd", "getChar", "getContents", "getLine", "head"
, "id", "init", "interact", "ioError", "isDenormalized", "isIEEE"
, "isInfinite", "isNaN", "isNegativeZero", "iterate", "last", "lcm"
, "length", "lex", "lines", "log", "logBase", "lookup", "map", "mapM"
, "mapM_", "max", "maxBound", "maximum", "maybe", "min", "minBound"
, "minimum", "mod", "negate", "not", "notElem", "null", "odd", "or"
, "otherwise", "pi", "pred", "print", "product", "properFraction", "putChar"
, "putStr", "putStrLn", "quot", "quotRem", "read", "readFile", "readIO"
, "readList", "readLn", "readParen", "reads", "readsPrec", "realToFrac"
, "recip", "rem", "repeat", "replicate", "return", "reverse", "round"
, "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq", "sequence"
, "sequence_", "show", "showChar", "showList", "showParen", "showString"
, "shows", "showsPrec", "significand", "signum", "sin", "sinh", "snd"
, "span", "splitAt", "sqrt", "subtract", "succ", "sum", "tail", "take"
, "takeWhile", "tan", "tanh", "toEnum", "toInteger", "toRational"
, "truncate", "uncurry", "undefined", "unlines", "until", "unwords", "unzip"
, "unzip3", "userError", "words", "writeFile", "zip", "zip3", "zipWith"
, "zipWith3"
]
| ajnsit/haste-markup | src/Util/Sanitize.hs | mit | 3,367 | 0 | 10 | 681 | 839 | 531 | 308 | 50 | 3 |
module Day5 where
import Data.List
(.&&.) :: (a -> Bool) -> (a -> Bool) -> (a -> Bool)
(.&&.) f g a = (f a) && (g a)
hasVowels :: String -> Bool
hasVowels = (>= 3) . length . (filter isVowel)
where isVowel = (`elem` "aeiou")
hasDoubles :: String -> Bool
hasDoubles (x:y:xs) = x==y || (hasDoubles (y:xs))
hasDoubles (x:[]) = False
hasDoubles [] = False
containsForbidden :: String -> Bool
containsForbidden word = foldl (\acc digraph -> acc || digraph `isInfixOf` word) False forbiddenDigraphs
where forbiddenDigraphs = ["ab", "cd", "pq", "xy"]
countNice :: [String] -> Int
countNice = length . filterConditions
where filterConditions = filter (hasDoubles .&&. hasVowels .&&. (not . containsForbidden))
containsABA :: String -> Bool
containsABA [] = False
containsABA (x:[]) = False
containsABA (x:y:[]) = False
containsABA (x:y:z:xs) = x==z || (containsABA (y:z:xs))
containsTwoPair :: String -> Bool
containsTwoPair [] = False
containsTwoPair (x:[]) = False
containsTwoPair (x:y:xs) = (x:y:[]) `isInfixOf` xs || (containsTwoPair (y:xs))
countNiceBetter :: [String] -> Int
countNiceBetter = length . filterConditions
where filterConditions = filter (containsABA .&&. containsTwoPair)
| AndrewSinclair/aoc-haskell | src/Day5.hs | mit | 1,204 | 0 | 11 | 197 | 542 | 298 | 244 | 29 | 1 |
module Platforms.GLFW.FRP where
import Hickory.FRP (CoreEventGenerators, coreEventGenerators)
import Hickory.Platform (makeTimePoller)
import Platforms.GLFW (getGLFWWindowSizeRef, makeGLFWInputPoller)
import qualified Graphics.UI.GLFW as GLFW
glfwCoreEventGenerators :: GLFW.Window -> IO (IO (), CoreEventGenerators)
glfwCoreEventGenerators win = do
wSizeRef <- getGLFWWindowSizeRef win
inputPoller <- makeGLFWInputPoller win wSizeRef
timePoller <- makeTimePoller
coreEventGenerators inputPoller timePoller wSizeRef
| asivitz/Hickory | GLFW/Platforms/GLFW/FRP.hs | mit | 528 | 0 | 9 | 59 | 124 | 67 | 57 | 11 | 1 |
module Parser
( parser
) where
import Data.Set (empty)
import DataStructures
import Wires
parser :: IO(Frame)
parser = do
content <- readFile "configMinimumViableProduct"
let usefullContent = ((filter (\x -> take 2 x /= "--")) . lines) content
let parsedEnnemies = parsingEnnemies usefullContent
return $ Frame (start_x,start_y) [] parsedEnnemies empty game
parsingEnnemies :: [String] -> [Ennemy]
parsingEnnemies [] = []
parsingEnnemies configLines@(x:xs) =
(Ennemy
pos
dim
(case (list_of_words !! 2) of
"bouncing" -> bouncing
"angle_bouncing" ->
let angle = read (list_of_words !! 3) in
angle_bouncing angle
"boss_bouncing" ->
let angle = read (list_of_words !! 3) in
let sens = read (list_of_words !! 4) in
boss_bouncing angle sens
)
)
:parsingEnnemies xs
where list_of_words = ((drop 1) . words) x
pos = read (list_of_words !! 0)
dim = read (list_of_words !! 1)
| hardkey/Netwire5-shmup-prototype | src/Parser.hs | mit | 1,076 | 0 | 20 | 340 | 349 | 179 | 170 | 30 | 3 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.TheBook.Monad
-- Copyright : (c) 2014, Jakub Kozlowski
-- License : MIT
--
-- Maintainer : mail@jakub-kozlowski.com
--
-- Unrolled concrete monad that can be used by the rules.
-----------------------------------------------------------------------------
module Data.TheBook.Monad (
Result(..)
, Rule, runRule
) where
import Control.Applicative (Alternative, Applicative, empty,
pure, (<*>), (<|>))
import Control.Monad (MonadPlus, ap, mplus, mzero)
import Control.Monad.Error (Error, MonadError, catchError,
throwError)
import Control.Monad.Reader.Class (MonadReader, ask, local)
import Control.Monad.State.Class (MonadState, get, put, state)
import Control.Monad.Writer.Class (MonadWriter, listen, pass)
import Data.Monoid (Monoid, mempty, (<>))
-- | The result of trying to match a rule.
-- This is parameterised over:
-- * @s@ type of the read/write state
-- * @w@ type of the log
-- * @e@ type of exceptions
-- * @a@ type of the result
data Result s w e a
= Match s w a
-- ^ The rule fired successfully.
| NoMatch
-- ^ The rule did not fire.
| Exception e
-- ^ The rule threw an exception.
-- | Specific monad that can be used to run rules.
--
-- This type is an instance of the following classes:
--
-- * 'Monad', where 'fail' throws an exception,
-- 'return' constitues a 'Match' and '(>>=)'
-- does not evaluate the right hand side if
-- the left hand side terminates with 'NoMatch'
-- or 'Exception'.
--
-- *
newtype Rule s w e a = Rule { runRule :: s -> Result s w e a }
instance (Monoid w, Error e) => Monad (Rule s w e) where
return = returnR
(>>=) = bindR
fail = failR
instance Functor (Rule s w e) where
fmap = fmapR
instance (Monoid w, Error e) => Applicative (Rule s w e) where
pure = returnR
(<*>) = ap
instance (Monoid w, Error e) => Alternative (Rule s w e) where
empty = mzeroR
(<|>) = orR
instance (Monoid w, Error e) => MonadPlus (Rule s w e) where
mzero = mzeroR
mplus = mplusR
instance (Monoid w, Error e) => MonadError e (Rule s w e) where
throwError = throwErrorR
catchError = catchErrorR
instance (Monoid w, Error e) => MonadState s (Rule s w e) where
get = getR
put = putR
state = stateR
instance (Monoid w, Error e) => MonadReader s (Rule s w e) where
ask = askR
local = localR
instance (Monoid w, Error e) => MonadWriter w (Rule s w e) where
listen = listenR
pass = passR
{-# INLINE returnR #-}
returnR :: Monoid w => a -> Rule s w e a
returnR x = Rule $ \s -> Match s mempty x
{-# INLINE bindR #-}
bindR :: Monoid w
=> Rule s w e a
-> (a -> Rule s w e b)
-> Rule s w e b
bindR m f = Rule $ \s -> case runRule m s of
Match s' w a -> case runRule (f a) s' of
Match s'' w' b -> Match s'' (w <> w') b
NoMatch -> NoMatch
Exception e -> Exception e
NoMatch -> NoMatch
Exception e -> Exception e
{-# INLINE failR #-}
failR :: String -> Rule s w e a
failR = error
{-# INLINE fmapR #-}
fmapR :: (a -> b) -> Rule s w e a -> Rule s w e b
fmapR f m = Rule $ \s -> case runRule m s of
Match s' w a -> Match s' w (f a)
NoMatch -> NoMatch
Exception e -> Exception e
{-# INLINE mzeroR #-}
mzeroR :: Rule s w e a
mzeroR = Rule $ const NoMatch
{-# INLINE mplusR #-}
mplusR :: (Monoid w, Error e)
=> Rule s w e a
-> Rule s w e a
-> Rule s w e a
mplusR l r = bindR l (const r)
{-# INLINE throwErrorR #-}
throwErrorR :: (Monoid w, Error e)
=> e
-> Rule s w e a
throwErrorR e = Rule $ const (Exception e)
{-# INLINE catchErrorR #-}
catchErrorR :: (Monoid w, Error e)
=> Rule s w e a
-> (e -> Rule s w e a)
-> Rule s w e a
catchErrorR m f = Rule $ \s -> case runRule m s of
match@(Match _ _ _) -> match
NoMatch -> NoMatch
Exception e -> runRule (f e) s
{-# INLINE getR #-}
getR :: (Monoid w) => Rule s w e s
getR = Rule $ \s -> Match s mempty s
{-# INLINE putR #-}
putR :: (Monoid w) => s -> Rule s w e ()
putR s = Rule $ \_ -> Match s mempty ()
{-# INLINE stateR #-}
stateR :: (Monoid w) => (s -> (a, s)) -> Rule s w e a
stateR f = Rule $ \s -> case f s of (a, s') -> Match s' mempty a
{-# INLINE askR #-}
askR :: (Monoid w) => Rule s w e s
askR = Rule $ \s -> Match s mempty s
{-# INLINE localR #-}
localR :: (Monoid w, Error e) => (s -> s) -> Rule s w e a -> Rule s w e a
localR f m = Rule $ \s -> runRule m (f s)
{-# INLINE listenR #-}
listenR :: (Monoid w, Error e) => Rule s w e a -> Rule s w e (a, w)
listenR = undefined
{-# INLINE passR #-}
passR :: (Monoid w, Error e) => Rule s w e (a, w -> w) -> Rule s w e a
passR m = Rule $ \s -> case runRule m s of
Match s' w (a, fw) -> Match s' (fw w) a
NoMatch -> NoMatch
Exception e -> Exception e
{-# INLINE orR #-}
orR :: (Monoid w, Error e) => Rule s w e a -> Rule s w e a -> Rule s w e a
orR left right = Rule $ \s -> case runRule left s of
m@(Match _ _ _) -> m
NoMatch -> runRule right s
ex@(Exception _ ) -> ex
| ggreif/thebook-haskell | src/Data/TheBook/Monad.hs | mit | 5,470 | 0 | 15 | 1,638 | 1,923 | 1,036 | 887 | 124 | 5 |
module Fusc where
fusc :: Int -> Int
fusc 0 = 0
fusc 1 = 1
fusc n
| even n = fusc (n `div` 2)
| odd n = fusc ((n-1) `div` 2) + fusc (((n-1) `div` 2) + 1) | pasaunders/code-katas | fusc.hs | mit | 158 | 0 | 13 | 45 | 119 | 63 | 56 | 7 | 1 |
{-# LANGUAGE
ExistentialQuantification,
RecordWildCards
#-}
{-|
Module : HSat.Parser
Description : Main Parsing module
Copyright : (c) Andrew Burnett 2014-2015
Maintainer : andyburnett88@gmail.com
Stability : experimental
Portability : Unknown
Module exports some generic Parsing functions
-}
module HSat.Parser (
-- * Data Type
ProblemParseError(..) ,
-- * Functions
fromFile , -- :: (MonadThorw m, MonadIO m) => [Parser] -> FilePath -> m Problem
fromFolder , -- :: (MonadThrow m, MonadIo m) => (Filepath -> m Problem) -> FilePath -> m [Problem]
module HSat.Parser.Class,
parserInstances ,
) where
import Control.Monad.Catch
import Control.Monad.Trans
import Data.List (delete)
import HSat.Parser.Class
import HSat.Problem
import HSat.Problem.ProblemExpr.Class
import HSat.Problem.Source
import System.Directory
import HSat.Problem.Instances.CNF.Parser
{-|
The default set of 'Parser's that are tried when extracting a file
-}
parserInstances :: [Parser]
parserInstances = [
Parser "cnf" (runParser cnfParser)
]
{-|
Given a list of Parsers, a file, will return a problem in a monad io context
-}
fromFile :: (MonadThrow m, MonadIO m) => [Parser] -> FilePath -> m Problem
fromFile [] fp = throwM $ UnrecognisedFileSuffix (getSuffix fp)
fromFile (Parser{..}:xs) fp =
if correctSuffix fileExtension fp then
(MkProblem (mkFileSource fp) . ProblemExpr) <$> parser fp else
fromFile xs fp
{-|
Given a function that takes a 'FilePath' and returns a 'Problem', a folder,
applies the function to each file in the folder
-}
fromFolder :: (MonadThrow m, MonadIO m) => (FilePath -> m Problem) -> FilePath ->
m [Problem]
fromFolder f folder = do
original <- liftIO getCurrentDirectory
contents <- delete "." . delete ".." <$> liftIO (getDirectoryContents folder)
liftIO (setCurrentDirectory folder) *> mapM f contents <* liftIO (setCurrentDirectory original)
getSuffix :: FilePath -> FilePath
getSuffix [] = []
getSuffix ('.':xs) = xs
getSuffix (_:xs) = getSuffix xs
correctSuffix :: FilePath -> FilePath -> Bool
correctSuffix extension fp =
let fp' = tail $ dropWhile (/='.') fp
in fp' == extension
{-|
A sum-type describing errors
-}
data ProblemParseError =
-- | If the file suffix is not recognised
UnrecognisedFileSuffix String |
ParseException String
deriving (Eq,Show)
instance Exception ProblemParseError
| aburnett88/HSat | src/HSat/Parser.hs | mit | 2,557 | 0 | 11 | 589 | 517 | 280 | 237 | 46 | 2 |
f n = concat . map (take n . repeat)
-- This part handles the Input and Output and can be used as it is. Do not modify this part.
main = do
n <- readLn :: IO Int
inputdata <- getContents
mapM_ putStrLn $ map show $ f n $ map (read :: String -> Int) $ lines inputdata
| tsurai/hackerrank | functional-programming/introduction/list-replication.hs | mit | 277 | 0 | 11 | 70 | 96 | 45 | 51 | 5 | 1 |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-
So here's the thing: I think LanguageDefs aren't used for manipulating
source files directly, they're only good for parsing out the actual expressions.
A source file consists of *several* "programs" -- function definitions that I can parse using
a LanguageDef, and same goes for the type declarations. However, I don't want to lex everything together...that's bad.
NOTE: We can parse individual lines + the lines that are preceded by spaces or tabs as single expressions
(type level or normal), and parse into these *first*
-}
module Parser where
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Language
import Text.ParserCombinators.Parsec.Expr
import qualified Text.Parsec.Token as T
import Control.Applicative hiding (optional, many, (<|>))
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Trans.State
import qualified Data.Map as M
import Data.Maybe
import Data.Traversable
import Types
import Util
fievelDef = LanguageDef {
commentStart = "{-"
, commentEnd = "-}"
, commentLine = "--"
, nestedComments = False
, identStart = letter <|> oneOf "_'"
, identLetter = alphaNum <|> oneOf "_'"
, opStart = oneOf "~!@#$%^&*|:<>?=+-\\"
, opLetter = oneOf "~!@#$%^&*|:<>?=+-"
, reservedNames = [ "if", "then", "else", "let", "be", "in", "Int", "Bool", "String"
, "True", "False", "run" ]
, reservedOpNames = [ "+", "-", "*", "^", "/", "<>", "!", ":=", "=", "!="
, ">", "<", ">=", "<=", "'", "\"", "->", "." ]
, caseSensitive = True
}
-- Lexer
lexer = T.makeTokenParser fievelDef
reserved = T.reserved lexer
-- Expression parsers
bool = (reserved "True" *> pure (EVal . VBool $ True))
<|> (reserved "False" *> pure (EVal . VBool $ False))
int = liftA (EVal . VInt . fromIntegral) $ T.integer lexer
str = liftA (EVal . VStr) $ T.stringLiteral lexer
ifte = do
reserved "if"
t1 <- fievelExpr
reserved "then"
t2 <- fievelExpr
reserved "else"
t3 <- fievelExpr
return $ EIf t1 t2 t3
letExpr = do
reserved "let"
name <- T.identifier lexer
reserved "be"
t1 <- fievelExpr
reserved "in"
t2 <- fievelExpr
return $ ELet name t1 t2
lambda = do
T.reservedOp lexer "\\"
name <- T.identifier lexer
T.reservedOp lexer "->"
exprs <- many1 fievelExpr
return $ ELam name (foldr1 EAp exprs)
defn = do
name <- T.identifier lexer <|> (reserved "run" >> return "run")
T.reservedOp lexer ":="
expr <- fievelExpr
return $ EDef name expr
fundefn = do
(f:args) <- many1 (T.identifier lexer)
T.reservedOp lexer ":="
exprs <- many1 fievelExpr
return $ EDef f (foldr ELam (foldr1 EAp exprs) args)
variable = liftA EVar $ T.identifier lexer
fievelExpr =
let paren = T.parens lexer
trys = ((<|>) <$> try <*> (try . paren)) <$> [ifte, lambda, letExpr, operator]
in choice trys
term = choice $ ((<|>) <$> id <*> T.parens lexer)
<$> [variable, bool, int, str]
-- Operator-y expression Parser
operator = expr
where expr = buildExpressionParser operators term
operators = [ [Prefix (string "!" >> spaces >> return (EOp . BNot)) ]
, [ typedBinOp "*" (:*:)
, typedBinOp "/" (:/:)
, typedBinOp "<>" (:<>:)
, typedBinOp "|" (:|:)
, typedBinOp "&" (:&:)
]
, [ typedBinOp "+" (:+:)
, typedBinOp "-" (:-:)
, typedBinOp "=" (:=:)
, typedBinOp "!=" (:!=:)
, typedBinOp ">=" (:>=:)
, typedBinOp "<=" (:<=:)
, typedBinOp ">" (:>:)
, typedBinOp "<" (:<:) ]
]
-- ** NB. I don't know if `try` is safe here!!
where binary n c = Infix (try $ string n *> spaces *> pure c) AssocLeft
lifted ctor = \x y -> EOp $ x `ctor` y
typedBinOp symb ctor = binary symb (lifted ctor)
-- Type parsers
constType =
reserved "Int" *> pure TInt
<|> reserved "Bool" *> pure TBool
<|> reserved "String" *> pure TStr
fievelType =
liftA (foldr1 TLam)
( (constType <|> T.parens lexer fievelType)
`sepBy`
(T.reservedOp lexer "->") )
typeSig = do
name <- T.identifier lexer
T.colon lexer
typ <- fievelType
return $ EType name typ
typeToTuple :: Expr -> Maybe (String, Type)
typeToTuple (EType nm tp) = Just $ (nm, tp)
typeToTuple _ = Nothing
defToTuple :: Expr -> Maybe (String, Expr)
defToTuple (EDef a val) = Just $ (a, val)
defToTuple _ = Nothing
isWhitespace :: Char -> Bool
isWhitespace c = c == ' ' || c == '\t'
chunk :: String -> [String] -> [String]
chunk acc [] = [acc]
chunk acc (x:xs)
| null x = chunk acc xs
| isWhitespace (head x) = chunk (acc ++ (' ': dropWhile isWhitespace x)) xs
| otherwise = acc : chunk x xs
-- Separate a file into "chunks": Sections of code that
-- start with a line with no leading whitespace,
-- with possible trailing lines with leading whitespace.
chunkify :: FilePath -> IO [String]
chunkify file = do
contents <- lines <$> readFile file
return $ filter (not . null) $ chunk [] contents
typeBinding = do
name <- T.identifier lexer
T.colon lexer
typ <- fievelType
return $ (name, typ)
expressionBinding = do
def <- choice $ (<|>) <$> try <*> (try . paren) <$> [fundefn, defn]
case defToTuple def of
Just tpl -> return tpl
_ -> error "Parsing failed; internal error."
where paren = T.parens lexer
parseFievelExpr =
try (PExpr <$> expressionBinding)
<|> PType <$> typeBinding
data ParseResult =
PType (String, Type)
| PExpr (String, Expr)
deriving (Show, Eq)
partition :: [ParseResult] -> ([(String, Type)], [(String, Expr)])
partition [] = ([], [])
partition (PType st : xs) = let (ts, es) = partition xs in (st:ts, es)
partition (PExpr se : xs) = let (ts, es) = partition xs in (ts, se:es)
-- call a parsing function with the empty state
initially :: (FievelState -> a) -> a
initially f = f emptyState
parseSingleExpr :: String -> Either FievelError Expr
parseSingleExpr str =
let exprs = parse fievelExpr "(fievel)" str
in case exprs of
Left err -> Left $ Parser (show err)
Right expr -> Right expr
parseFievel :: FievelState -> String -> Either FievelError (ParseResult, FievelState)
parseFievel fs str =
let exprs = parse parseFievelExpr "(fievel)" str
in case exprs of
Left err -> Left $ Parser (show err)
Right e@(PExpr expr) -> Right $ (e, (FievelState (M.fromList [expr]) (M.empty)) `mergeBindings` fs)
Right t@(PType typ) -> Right $ (t, (FievelState (M.empty) (M.fromList [typ])) `mergeBindings` fs)
parseFievelFile :: FievelState -> FilePath -> IO (Either FievelError FievelState)
parseFievelFile fs file = do
exprs <- traverse (parse parseFievelExpr "(fievel file)") <$> chunkify file
case exprs of
Left err -> return . Left $ Parser (show err)
Right xs -> let (ts, es) = partition xs
in return . Right $ (FievelState (M.fromList es) (M.fromList ts)) `mergeBindings` fs
| 5outh/fievel | Parser.hs | gpl-2.0 | 7,270 | 0 | 18 | 1,915 | 2,411 | 1,261 | 1,150 | 169 | 3 |
module InterfazSE where
import FuncionesInterfaz
import GraficosFunciones
import GramaticaConcreta
import SistemasEcuaciones
import UU.Parsing
import FuncionesAuxiliaresSE
import Graphics.UI.Gtk
import Foreign
sistemasEcuaciones :: IO Table
sistemasEcuaciones= do
table <- tableNew 4 1 False
content <- vBoxNew False 4
sistem <- vBoxNew False 4
grafMatriz <- textViewNew
tableAttachDefaults table content 0 1 0 1
values <- entryNew
valuesb <- entryNew
labelv <- labelNew (Just "Ingrese matriz aumentada para Eliminaciones Gaussianas o matriz de coeficientes para Métodos Iterativos (Por filas y elementos separados por espacios)")
labelb <- labelNew (Just "Ingrese el vector de términos independientes (Elementos separados por espacios)")
labels <- labelNew (Just "Valores de las incognitas")
eval <- buttonNewWithLabel "Evaluar"
boxPackStart content sistem PackNatural 0
boxPackStart sistem labelv PackNatural 0
boxPackStart sistem values PackNatural 0
boxPackStart sistem labelb PackNatural 0
boxPackStart sistem valuesb PackNatural 0
{-MATRIZ RESULTANTE-}
tableAttachDefaults table grafMatriz 0 1 1 2
textViewSetEditable grafMatriz False
buffer <- textViewGetBuffer grafMatriz
labelbuffer <- labelNew (Just "")
containerAdd sistem labelbuffer
labelmm <- labelNew (Just "Matriz resultante")
labelm <- labelNew (Just "Resultados")
containerAdd sistem labelm
containerAdd sistem labelmm
{-RESULTADOS-}
resu <- vBoxNew False 0
salida <- entryNew
ayuda <- buttonNewWithLabel "¿Necesitas ayuda?"
tableAttachDefaults table resu 0 1 2 3
boxPackStart resu labels PackNatural 0
boxPackStart resu salida PackNatural 0
boxPackStart resu eval PackNatural 0
boxPackStart resu ayuda PackNatural 0
{-METODOS DIRECTOS-}
directosp <- vBoxNew False 5
directosaux <- hBoxNew False 5
directos <- vBoxNew False 5
directosh <- vBoxNew False 5
directoshh <- vBoxNew False 5
directoshhh <- vBoxNew False 5
directoshhhh <- vBoxNew False 5
directoshhhhh <- vBoxNew False 5
tama <- vBoxNew False 0
tableAttachDefaults table directosp 0 1 3 4
tamaño <- entryNew
labeld <- labelNew (Just "Métodos directos")
labeltama <- labelNew (Just "Tamaño del sistema")
containerAdd tama labeltama
containerAdd tama tamaño
containerAdd directosp labeld
containerAdd directosaux directos
containerAdd directosaux tama
containerAdd directosaux directosh
containerAdd directosaux directoshh
containerAdd directosaux directoshhh
containerAdd directosaux directoshhhh
containerAdd directosaux directoshhhhh
containerAdd directosp directosaux
{-ELIMINACION GAUSSIANA SIMPLE-}
gsim <- vBoxNew False 5
option <- hBoxNew False 0
containerAdd directos gsim
radio1 <- radioButtonNewWithLabel "Eliminación Gaussiana Simple"
boxPackStart option radio1 PackNatural 5
boxPackStart gsim option PackNatural 0
{-ELIMINACION CON PIVOTEO PARCIAL-}
gparcial <- hBoxNew False 5
optionp <- vBoxNew False 0
containerAdd directos gparcial
radio2 <- radioButtonNewWithLabelFromWidget radio1 "Eliminación con Pivoteo Parcial"
boxPackStart optionp radio2 PackNatural 5
boxPackStart gparcial optionp PackNatural 0
{-ELIMINACION CON PIVOTEO TOTAL-}
gtotal <- hBoxNew False 5
optiont <- vBoxNew False 0
containerAdd directos gtotal
radio3 <- radioButtonNewWithLabelFromWidget radio2 "Eliminación con Pivoteo Total"
boxPackStart optiont radio3 PackNatural 5
boxPackStart gtotal optiont PackNatural 0
{-METODOS ITERATIVOS-}
viterativo <- hBoxNew False 5
iterativo <- vBoxNew False 5
labeliter <- labelNew (Just "Métodos iterativos")
labelen <- labelNew (Just "Ingrese los respectivos valores y luego seleccion el método a usar")
containerAdd iterativo labeliter
tableAttachDefaults table iterativo 0 1 4 5
bxoj <- vBoxNew False 5
bnj <- vBoxNew False 5
blaj <- vBoxNew False 5
btolj <- vBoxNew False 5
bij <- vBoxNew False 5
labela <- labelNew (Just "Valores iniciales")
miscSetAlignment labela 0 0
boxPackStart bxoj labela PackNatural 0
xoj <- entryNew
boxPackStart bxoj xoj PackNatural 0
labelnj <- labelNew (Just "Tamaño del sistema")
miscSetAlignment labelnj 0 0
boxPackStart bnj labelnj PackNatural 0
nj <- entryNew
boxPackStart bnj nj PackNatural 0
labellaj <- labelNew (Just "Relajación")
miscSetAlignment labellaj 0 0
boxPackStart blaj labellaj PackNatural 0
laj <- entryNew
boxPackStart blaj laj PackNatural 0
labeltolj <- labelNew (Just "Tolerancia")
miscSetAlignment labeltolj 0 0
boxPackStart btolj labeltolj PackNatural 0
tolj <- entryNew
boxPackStart btolj tolj PackNatural 0
labelij <- labelNew (Just "Numero maximo iteraciones")
miscSetAlignment labelij 0 0
boxPackStart bij labelij PackNatural 0
ij <- entryNew
boxPackStart bij ij PackNatural 0
{-OPCIONES ITERATIVOS-}
optioniter <- vBoxNew False 5
jaco <- hBoxNew False 5
optionj <- vBoxNew False 5
radio4 <- radioButtonNewWithLabelFromWidget radio3 "Jacobi"
boxPackStart optionj radio4 PackNatural 5
boxPackStart jaco optionj PackNatural 0
seidel <- hBoxNew False 5
options <- vBoxNew False 5
radio5 <- radioButtonNewWithLabelFromWidget radio4 "Gauss Seidel"
boxPackStart options radio5 PackNatural 5
boxPackStart seidel options PackNatural 0
containerAdd optioniter jaco
containerAdd optioniter seidel
containerAdd viterativo optioniter
containerAdd iterativo viterativo
boxPackStart viterativo bxoj PackNatural 0
boxPackStart viterativo bnj PackNatural 0
boxPackStart viterativo blaj PackNatural 0
boxPackStart viterativo btolj PackNatural 0
boxPackStart viterativo bij PackNatural 0
onClicked ayuda $ do
ayudaSE
onClicked eval $ do
s <- get values entryText
n <- get tamaño entryText
au <- parseIO pListDouble (funScanTxt(s))
if (unsafePerformIO(toggleButtonGetActive radio1))
then do
let result = eGaussSim (leerMatrizAu (read n) au) (read n)
set salida [entryText := show(result)]
let mat = mtos'(matrizEGaussSim (leerMatrizAu (read n) au) (read n)) (read n)
textBufferSetText buffer mat
else
if (unsafePerformIO(toggleButtonGetActive radio2))
then do
let result = eGaussPParcial (leerMatrizAu (read n) au) (read n)
set salida [entryText := show(result)]
let mat = mtos'(matrizEGaussParcial (leerMatrizAu (read n) au) (read n)) (read n)
textBufferSetText buffer mat
else
if (unsafePerformIO(toggleButtonGetActive radio3))
then do
let result = eGaussPTotal (leerMatrizAu (read n) au) (read n)
set salida [entryText := show(result)]
let mat = mtos'(matrizEGaussTotal(leerMatrizAu (read n) au) (read n)) (read n)
textBufferSetText buffer mat
else do
sxo <- get xoj entryText
sb <- get valuesb entryText
sla <- get laj entryText
stol <- get tolj entryText
i <- get ij entryText
ni <- get nj entryText
xo <- parseIO pListDouble (funScanTxt sxo)
b <- parseIO pListDouble (funScanTxt sb)
la <- parseIO pDouble (funScanTxt sla)
tol <- parseIO pDouble (funScanTxt stol)
if (unsafePerformIO(toggleButtonGetActive radio4))
then do
let result = jacobi (leerMatriz (read ni) au) (leerXo (read ni) xo) (leerB (read ni) b) (read ni) la tol (read i)
set salida [entryText := (show result)]
else do
let result = gaussSeidel (leerMatriz (read ni) au) (leerXo (read ni) xo) (leerB (read ni) b) (read ni) la tol (read i)
set salida [entryText := (show result)]
return table
| dmuneras/LambdaMethods | src/InterfazSE.hs | gpl-2.0 | 12,237 | 1 | 25 | 6,114 | 2,390 | 1,052 | 1,338 | 185 | 5 |
module Masque.AST where
import Control.Applicative
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Trans.State
import Data.Binary.Get
import Data.Binary.IEEE754
import Data.Bits
import qualified Data.ByteString.Char8 as BSC
import Data.Foldable
import Data.List (genericIndex)
data Expr = NullExpr
| CharExpr Char
| DoubleExpr Double
| IntExpr Integer
| StrExpr String
| AssignExpr String Expr
| BindingExpr String
| CallExpr Expr String [Expr] [NamedExpr]
| DefExpr Patt Expr Expr
| EscapeOnlyExpr Patt Expr
| EscapeExpr Patt Expr Patt Expr
| FinallyExpr Expr Expr
| HideExpr Expr
| IfExpr Expr Expr Expr
| MatcherExpr Patt Expr
| MethodExpr String String [Patt] [NamedPatt] Expr Expr
| NounExpr String
| ObjectExpr String Patt Expr [Expr] [Expr] [Expr]
| SequenceExpr [Expr]
| TryExpr Expr Patt Expr
deriving (Eq, Show, Read)
data NamedExpr = NamedExpr Expr Expr
deriving (Eq, Show, Read)
data Patt = IgnorePatt Expr
| BindPatt String
| FinalPatt String Expr
| ListPatt [Patt]
| VarPatt String Expr
| ViaPatt Expr Patt
deriving (Eq, Show, Read)
data NamedPatt = NamedPatt Expr Patt Expr
deriving (Eq, Show, Read)
-- | Deserialization
type MASTContext = ([Expr], [Patt])
getVarInt :: StateT MASTContext Get Integer
getVarInt = do
b <- lift getWord8
let rv = toInteger $ b .&. 0x7f
if b .&. 0x80 == 0x00
then return rv
else do
vi <- getVarInt
return $ rv .|. vi `shiftL` 7
getDouble :: StateT MASTContext Get Double
getDouble = do
bs <- replicateM 8 (lift getWord8)
let w64 = foldl' (\w x -> w `shiftL` 8 .|. fromIntegral x) 0 bs
return $ wordToDouble w64
zzd :: Integer -> Integer
zzd i = if i .&. 1 == 1 then (i `div` 2) `xor` (-1) else i `div` 2
-- XXX UTF-8 decode
getStr :: StateT MASTContext Get String
getStr = do
len <- getVarInt
bs <- lift $ getByteString (fromIntegral len)
return $ BSC.unpack bs
getExpr :: StateT MASTContext Get Expr
getExpr = do
i <- getVarInt
gets (\(exprs, _) -> exprs `genericIndex` i)
getExprs :: StateT MASTContext Get [Expr]
getExprs = do
i <- getVarInt
replicateM (fromInteger i) getExpr
getNamedExprs :: StateT MASTContext Get [NamedExpr]
getNamedExprs = do
i <- getVarInt
replicateM (fromInteger i) $ do
k <- getExpr
v <- getExpr
return $ NamedExpr k v
getPatt :: StateT MASTContext Get Patt
getPatt = do
i <- getVarInt
gets (\(_, patts) -> patts `genericIndex` i)
getPatts :: StateT MASTContext Get [Patt]
getPatts = do
i <- getVarInt
replicateM (fromInteger i) getPatt
getNamedPatts :: StateT MASTContext Get [NamedPatt]
getNamedPatts = do
i <- getVarInt
replicateM (fromInteger i) $ do
k <- getExpr
p <- getPatt
v <- getExpr
return $ NamedPatt k p v
nextTag :: StateT MASTContext Get ()
nextTag = do
tag <- lift getWord8
case (toEnum . fromEnum) tag of
-- Literals
'L' -> do
literalTag <- lift getWord8
expr <- case (toEnum . fromEnum) literalTag of
-- 'C' -> do ...
'D' -> DoubleExpr <$> getDouble
'I' -> do
i <- getVarInt
return $ IntExpr $ zzd i
'N' -> return NullExpr
'S' -> StrExpr <$> getStr
modify (\(exprs, patts) -> (exprs ++ [expr], patts))
-- Patts
'P' -> do
pattTag <- lift getWord8
patt <- case (toEnum . fromEnum) pattTag of
'A' -> ViaPatt <$> getExpr <*> getPatt
'B' -> BindPatt <$> getStr
'F' -> FinalPatt <$> getStr <*> getExpr
'I' -> IgnorePatt <$> getExpr
'L' -> ListPatt <$> getPatts
'V' -> VarPatt <$> getStr <*> getExpr
modify (\(exprs, patts) -> (exprs, patts ++ [patt]))
-- Exprs
tag -> do
expr <- case tag of
'A' -> AssignExpr <$> getStr <*> getExpr
'B' -> BindingExpr <$> getStr
'C' -> CallExpr <$> getExpr <*> getStr <*> getExprs <*> getNamedExprs
'D' -> DefExpr <$> getPatt <*> getExpr <*> getExpr
'E' -> EscapeExpr <$> getPatt <*> getExpr <*> getPatt <*> getExpr
'F' -> FinallyExpr <$> getExpr <*> getExpr
'H' -> HideExpr <$> getExpr
'I' -> IfExpr <$> getExpr <*> getExpr <*> getExpr
'M' -> MethodExpr <$> getStr <*> getStr <*> getPatts <*> getNamedPatts <*> getExpr <*> getExpr
'N' -> NounExpr <$> getStr
'O' -> ObjectExpr <$> getStr <*> getPatt <*> getExpr <*> getExprs <*> getExprs <*> getExprs
'R' -> MatcherExpr <$> getPatt <*> getExpr
'S' -> SequenceExpr <$> getExprs
'Y' -> TryExpr <$> getExpr <*> getPatt <*> getExpr
'e' -> EscapeOnlyExpr <$> getPatt <*> getExpr
modify (\(exprs, patts) -> (exprs ++ [expr], patts))
getFullFile :: Get Expr
getFullFile = do
-- Skip the magic for now.
skip 10
(exprs, _) <- execStateT loop ([], [])
return $ last exprs
where
loop = do
nextTag
finished <- lift isEmpty
unless finished loop
| monte-language/masque | Masque/AST.hs | gpl-3.0 | 5,532 | 0 | 21 | 1,861 | 1,721 | 896 | 825 | 147 | 25 |
{---------------------------------------------------------------------}
{- Copyright 2015 Nathan Bloomfield -}
{- -}
{- This file is part of Feivel. -}
{- -}
{- Feivel is free software: you can redistribute it and/or modify -}
{- it under the terms of the GNU General Public License version 3, -}
{- as published by the Free Software Foundation. -}
{- -}
{- Feivel 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 Feivel. If not, see <http://www.gnu.org/licenses/>. -}
{---------------------------------------------------------------------}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Feivel.Eval.Eval where
import Feivel.Eval.EvalM
import Feivel.Grammar
import Feivel.Store
import Feivel.Error
import Carl.String
import Carl.Data.Rat
class Eval t where
eval :: t -> EvalM t
instance Eval Integer where eval = return
instance Eval String where eval = return
instance Eval Text where eval = return
instance Eval Rat where eval = return
instance Eval Bool where eval = return
class Glyph t where
toGlyph :: t -> EvalM String
lift1
:: ( Eval x, ToExpr x, Get a, HasLocus x
, Put b, Get y
, PromoteError err
) => Locus -> x -> (a -> Either err b) -> EvalM y
lift1 loc x f = do
a <- eval x >>= getVal
b <- tryEvalM loc $ f a
getVal (put loc b)
lift2
:: ( Eval x, ToExpr x, Get a, HasLocus x
, Eval y, ToExpr y, Get b, HasLocus y
, Put c, Get z
, PromoteError err
) => Locus -> x -> y -> (a -> b -> Either err c) -> EvalM z
lift2 loc x y f = do
a <- eval x >>= getVal
b <- eval y >>= getVal
c <- tryEvalM loc $ f a b
getVal (put loc c)
lift3
:: ( Eval x, ToExpr x, Get a, HasLocus x
, Eval y, ToExpr y, Get b, HasLocus y
, Eval z, ToExpr z, Get c, HasLocus z
, Put d, Get w
, PromoteError err
) => Locus -> x -> y -> z -> (a -> b -> c -> Either err d) -> EvalM w
lift3 loc x y z f = do
a <- eval x >>= getVal
b <- eval y >>= getVal
c <- eval z >>= getVal
d <- tryEvalM loc $ f a b c
getVal (put loc d)
lift4
:: ( Eval x, ToExpr x, Get a, HasLocus x
, Eval y, ToExpr y, Get b, HasLocus y
, Eval z, ToExpr z, Get c, HasLocus z
, Eval w, ToExpr w, Get d, HasLocus w
, Put e, Get u
, PromoteError err
) => Locus -> x -> y -> z -> w -> (a -> b -> c -> d -> Either err e) -> EvalM u
lift4 loc x y z w f = do
a <- eval x >>= getVal
b <- eval y >>= getVal
c <- eval z >>= getVal
d <- eval w >>= getVal
e <- tryEvalM loc $ f a b c d
getVal (put loc e)
| nbloomf/feivel | src/Feivel/Eval/Eval.hs | gpl-3.0 | 3,211 | 0 | 17 | 1,109 | 1,001 | 499 | 502 | 66 | 1 |
{-# LANGUAGE LambdaCase #-}
module Utils.Conduit (foldGroup) where
import Data.Function (fix)
import Data.Conduit as C
import qualified Data.Conduit.Combinators as C
foldGroup
:: Monad m
=> (a -> a -> Bool)
-> ConduitT a b m b
-> ConduitT a b m ()
foldGroup p sink = fix $ \loop -> await >>= \case
Nothing -> return ()
Just e -> do
leftover e
(C.takeWhile (p e) .| sink) >>= yield
loop
{-# INLINE foldGroup #-}
| merijn/GPU-benchmarks | benchmark-analysis/src/Utils/Conduit.hs | gpl-3.0 | 461 | 0 | 18 | 125 | 169 | 89 | 80 | 17 | 2 |
{--
The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s.
We shall consider fractions like, 30/50 = 3/5, to be trivial examples.
There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator.
If the product of these four fractions is given in its lowest common terms, find the value of the denominator.
--}
-- for fraction type
import Data.Ratio
-- my own operator to make a number from 2 digits :)
(*|) a b = a * 10 + b
main = print $ denominator $ product [ a%c | c<-[2..9], a<-[1..c-1], b<-[1..9], (a *| b) * c == a * ( b *| c) ]
| goalieca/haskelling | 033.hs | gpl-3.0 | 793 | 0 | 13 | 168 | 125 | 68 | 57 | 3 | 1 |
module MLLabs.Distance
( Metric
, minkowskiMetric
, manhattanMetric
, euclidianMetric
, chebyshevMetric
) where
import Linear.Vector (Additive (..))
type Metric obj = obj -> obj -> Double
minkowskiMetric :: (Foldable f, Additive f) => Double -> Metric (f Double)
minkowskiMetric p l1 l2 =
(** (1/p)) $ sum $ fmap ((** p) . abs) $ l1 ^-^ l2
manhattanMetric :: (Foldable f, Additive f) => Metric (f Double)
manhattanMetric = minkowskiMetric 1
euclidianMetric :: (Foldable f, Additive f) => Metric (f Double)
euclidianMetric = minkowskiMetric 2
chebyshevMetric :: (Foldable f, Additive f) => Metric (f Double)
chebyshevMetric l1 l2 = maximum $ fmap abs $ l1 ^-^ l2
| zhenyavinogradov/ml-labs | src/MLLabs/Distance.hs | gpl-3.0 | 724 | 0 | 11 | 170 | 266 | 144 | 122 | 17 | 1 |
module Data.Fit.Example (
fitSpeeds,
fitFields,
readEntries,
degrees,
semicircles,
cmToM,
msToMPH
) where
import Control.Lens
import Data.List
import Data.Time
import Data.Time
import Data.Time.Clock.POSIX
import Fit
data Entry = Entry {
lat :: Int, -- latitude in semicircles
latDeg :: Double, -- latitude in degrees
lon :: Int, -- longitude in semicircles
lonDeg :: Double, -- longitude in degrees
ts :: Int, -- scaled unix timestamp
tsUTC :: UTCTime, -- proper unix timestamp
distance :: Int, -- scaled distance
distanceCM :: Double, -- distance in cm
speed :: Int, -- scaled speed
speedMS :: Double, -- speed in m/s
speedMPH :: Double -- speed in mph
} deriving (Show, Read, Eq)
degrees semicircles = semicircles * (180 / 2^31)
semicircles degrees = degrees * (2^31 / 180)
cmToM = (*) 0.01
msToMPH = (*) 2.23693629
fitSpeeds path = do
Right fit <- readFileMessages path
let speeds = fit ^.. message 20 . field 6 . int
return speeds
fitFields path f = do
Right fit <- readFileMessages path
let fs = fit ^.. message 20 . field f . int
return fs
readEntries path = do
Right fit <- readFileMessages path
let
timestamps = fit ^.. message 20 . field 253 . int
latitudes = fit ^.. message 20 . field 0 . int
longitudes = fit ^.. message 20 . field 1 . int
distances = fit ^.. message 20 . field 5 . int
speeds = fit ^.. message 20 . field 6 . int
everything = zip5 timestamps latitudes longitudes distances speeds
return $ map (\(ts,lat,lon,dist,speed) -> Entry {
ts = ts,
tsUTC = posixSecondsToUTCTime (fromIntegral ts),
lat = lat,
latDeg = degrees $ fromIntegral lat,
lon = lon,
lonDeg = degrees $ fromIntegral lon,
distance = dist,
distanceCM = (fromIntegral dist) / 100,
speed = speed,
speedMS = (fromIntegral speed) / 1000,
speedMPH = msToMPH ((fromIntegral speed) / 1000)
}) everything
-- stuff
-- liftM (sum . map distanceCM) $ readEntries "/code/GARMIN/GARMIN/ACTIVITY/61G90344.FIT"
| adarqui/ToyBox | haskell/mgiles/fit/src/Data/Fit/Example.hs | gpl-3.0 | 2,277 | 0 | 17 | 713 | 657 | 358 | 299 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Test.FileTypeDetection (fileTypeDetectionTests) where
import Network.Gopher (GopherFileType (..))
import Network.Spacecookie.FileType
import System.FilePath.Posix.ByteString (takeExtension)
import Test.Tasty
import Test.Tasty.HUnit
fileTypeDetectionTests :: TestTree
fileTypeDetectionTests = testGroup "spacecookie server file type detection"
[ ioTests
, suffixTests
]
ioTests :: TestTree
ioTests = testCase "gopherFileType tests" $ do
assertEqual "Fallback to File without extension" (Right File)
=<< gopherFileType "LICENSE"
assertEqual "non-existent dot files are forbidden" (Left PathIsNotAllowed)
=<< gopherFileType ".dot-file-missing"
assertEqual "dot file along the path" (Left PathIsNotAllowed)
=<< gopherFileType ".git/HEAD"
assertEqual "dot file along the path" (Left PathIsNotAllowed)
=<< gopherFileType "./foo/.git/HEAD"
assertEqual ".. is disallowed" (Left PathIsNotAllowed)
=<< gopherFileType "/lol/../../doing/directory/traversal.txt"
assertEqual "\".\" is allowed" (Right Directory)
=<< gopherFileType "."
assertEqual "txt files" (Right File)
=<< gopherFileType "./docs/rfc1436.txt"
assertEqual "missing file" (Left PathDoesNotExist)
=<< gopherFileType "missing/this.txt"
suffixTests :: TestTree
suffixTests = testCase "correct mapping of suffixes" $ do
assertEqual "BinHexMacintoshFile" BinHexMacintoshFile $
lookupSuffix $ takeExtension "test.hqx"
assertEqual "tar.gz is BinaryFile" BinaryFile $
lookupSuffix $ takeExtension "/releases/spacecookie-0.3.0.0.tar.gz"
assertEqual "gif file" GifFile $
lookupSuffix $ takeExtension "funny.gif"
mapM_ (assertEqual "image file" ImageFile . lookupSuffix . takeExtension)
[ "hello.png", "/my/beautiful.jpg", "./../lol.jpeg"
, "../bar.tif", "my.tiff", ".hidden.svg", "my.bmp" ]
assertEqual "fallback to File" File $
lookupSuffix $ takeExtension "my/unknown.strange-extension"
| sternenseemann/spacecookie | test/Test/FileTypeDetection.hs | gpl-3.0 | 1,979 | 0 | 12 | 297 | 399 | 195 | 204 | 42 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.RegionOperations.Wait
-- 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)
--
-- Waits for the specified Operation resource to return as \`DONE\` or for
-- the request to approach the 2 minute deadline, and retrieves the
-- specified Operation resource. This method differs from the \`GET\`
-- method in that it waits for no more than the default deadline (2
-- minutes) and then returns the current state of the operation, which
-- might be \`DONE\` or still in progress. This method is called on a
-- best-effort basis. Specifically: - In uncommon cases, when the server is
-- overloaded, the request might return before the default deadline is
-- reached, or might return after zero seconds. - If the default deadline
-- is reached, there is no guarantee that the operation is actually done
-- when the method returns. Be prepared to retry if the operation is not
-- \`DONE\`.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionOperations.wait@.
module Network.Google.Resource.Compute.RegionOperations.Wait
(
-- * REST Resource
RegionOperationsWaitResource
-- * Creating a Request
, regionOperationsWait
, RegionOperationsWait
-- * Request Lenses
, rowProject
, rowOperation
, rowRegion
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.regionOperations.wait@ method which the
-- 'RegionOperationsWait' request conforms to.
type RegionOperationsWaitResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"regions" :>
Capture "region" Text :>
"operations" :>
Capture "operation" Text :>
"wait" :>
QueryParam "alt" AltJSON :> Post '[JSON] Operation
-- | Waits for the specified Operation resource to return as \`DONE\` or for
-- the request to approach the 2 minute deadline, and retrieves the
-- specified Operation resource. This method differs from the \`GET\`
-- method in that it waits for no more than the default deadline (2
-- minutes) and then returns the current state of the operation, which
-- might be \`DONE\` or still in progress. This method is called on a
-- best-effort basis. Specifically: - In uncommon cases, when the server is
-- overloaded, the request might return before the default deadline is
-- reached, or might return after zero seconds. - If the default deadline
-- is reached, there is no guarantee that the operation is actually done
-- when the method returns. Be prepared to retry if the operation is not
-- \`DONE\`.
--
-- /See:/ 'regionOperationsWait' smart constructor.
data RegionOperationsWait =
RegionOperationsWait'
{ _rowProject :: !Text
, _rowOperation :: !Text
, _rowRegion :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RegionOperationsWait' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rowProject'
--
-- * 'rowOperation'
--
-- * 'rowRegion'
regionOperationsWait
:: Text -- ^ 'rowProject'
-> Text -- ^ 'rowOperation'
-> Text -- ^ 'rowRegion'
-> RegionOperationsWait
regionOperationsWait pRowProject_ pRowOperation_ pRowRegion_ =
RegionOperationsWait'
{ _rowProject = pRowProject_
, _rowOperation = pRowOperation_
, _rowRegion = pRowRegion_
}
-- | Project ID for this request.
rowProject :: Lens' RegionOperationsWait Text
rowProject
= lens _rowProject (\ s a -> s{_rowProject = a})
-- | Name of the Operations resource to return.
rowOperation :: Lens' RegionOperationsWait Text
rowOperation
= lens _rowOperation (\ s a -> s{_rowOperation = a})
-- | Name of the region for this request.
rowRegion :: Lens' RegionOperationsWait Text
rowRegion
= lens _rowRegion (\ s a -> s{_rowRegion = a})
instance GoogleRequest RegionOperationsWait where
type Rs RegionOperationsWait = Operation
type Scopes RegionOperationsWait =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient RegionOperationsWait'{..}
= go _rowProject _rowRegion _rowOperation
(Just AltJSON)
computeService
where go
= buildClient
(Proxy :: Proxy RegionOperationsWaitResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/RegionOperations/Wait.hs | mpl-2.0 | 5,300 | 0 | 17 | 1,165 | 492 | 302 | 190 | 78 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.StorageTransfer.TransferJobs.Patch
-- 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)
--
-- Updates a transfer job. Updating a job\'s transfer spec does not affect
-- transfer operations that are running already. **Note:** The job\'s
-- status field can be modified using this RPC (for example, to set a
-- job\'s status to DELETED, DISABLED, or ENABLED).
--
-- /See:/ <https://cloud.google.com/storage-transfer/docs Storage Transfer API Reference> for @storagetransfer.transferJobs.patch@.
module Network.Google.Resource.StorageTransfer.TransferJobs.Patch
(
-- * REST Resource
TransferJobsPatchResource
-- * Creating a Request
, transferJobsPatch
, TransferJobsPatch
-- * Request Lenses
, tjpXgafv
, tjpUploadProtocol
, tjpAccessToken
, tjpJobName
, tjpUploadType
, tjpPayload
, tjpCallback
) where
import Network.Google.Prelude
import Network.Google.StorageTransfer.Types
-- | A resource alias for @storagetransfer.transferJobs.patch@ method which the
-- 'TransferJobsPatch' request conforms to.
type TransferJobsPatchResource =
"v1" :>
Capture "jobName" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] UpdateTransferJobRequest :>
Patch '[JSON] TransferJob
-- | Updates a transfer job. Updating a job\'s transfer spec does not affect
-- transfer operations that are running already. **Note:** The job\'s
-- status field can be modified using this RPC (for example, to set a
-- job\'s status to DELETED, DISABLED, or ENABLED).
--
-- /See:/ 'transferJobsPatch' smart constructor.
data TransferJobsPatch =
TransferJobsPatch'
{ _tjpXgafv :: !(Maybe Xgafv)
, _tjpUploadProtocol :: !(Maybe Text)
, _tjpAccessToken :: !(Maybe Text)
, _tjpJobName :: !Text
, _tjpUploadType :: !(Maybe Text)
, _tjpPayload :: !UpdateTransferJobRequest
, _tjpCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TransferJobsPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tjpXgafv'
--
-- * 'tjpUploadProtocol'
--
-- * 'tjpAccessToken'
--
-- * 'tjpJobName'
--
-- * 'tjpUploadType'
--
-- * 'tjpPayload'
--
-- * 'tjpCallback'
transferJobsPatch
:: Text -- ^ 'tjpJobName'
-> UpdateTransferJobRequest -- ^ 'tjpPayload'
-> TransferJobsPatch
transferJobsPatch pTjpJobName_ pTjpPayload_ =
TransferJobsPatch'
{ _tjpXgafv = Nothing
, _tjpUploadProtocol = Nothing
, _tjpAccessToken = Nothing
, _tjpJobName = pTjpJobName_
, _tjpUploadType = Nothing
, _tjpPayload = pTjpPayload_
, _tjpCallback = Nothing
}
-- | V1 error format.
tjpXgafv :: Lens' TransferJobsPatch (Maybe Xgafv)
tjpXgafv = lens _tjpXgafv (\ s a -> s{_tjpXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
tjpUploadProtocol :: Lens' TransferJobsPatch (Maybe Text)
tjpUploadProtocol
= lens _tjpUploadProtocol
(\ s a -> s{_tjpUploadProtocol = a})
-- | OAuth access token.
tjpAccessToken :: Lens' TransferJobsPatch (Maybe Text)
tjpAccessToken
= lens _tjpAccessToken
(\ s a -> s{_tjpAccessToken = a})
-- | Required. The name of job to update.
tjpJobName :: Lens' TransferJobsPatch Text
tjpJobName
= lens _tjpJobName (\ s a -> s{_tjpJobName = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
tjpUploadType :: Lens' TransferJobsPatch (Maybe Text)
tjpUploadType
= lens _tjpUploadType
(\ s a -> s{_tjpUploadType = a})
-- | Multipart request metadata.
tjpPayload :: Lens' TransferJobsPatch UpdateTransferJobRequest
tjpPayload
= lens _tjpPayload (\ s a -> s{_tjpPayload = a})
-- | JSONP
tjpCallback :: Lens' TransferJobsPatch (Maybe Text)
tjpCallback
= lens _tjpCallback (\ s a -> s{_tjpCallback = a})
instance GoogleRequest TransferJobsPatch where
type Rs TransferJobsPatch = TransferJob
type Scopes TransferJobsPatch =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient TransferJobsPatch'{..}
= go _tjpJobName _tjpXgafv _tjpUploadProtocol
_tjpAccessToken
_tjpUploadType
_tjpCallback
(Just AltJSON)
_tjpPayload
storageTransferService
where go
= buildClient
(Proxy :: Proxy TransferJobsPatchResource)
mempty
| brendanhay/gogol | gogol-storage-transfer/gen/Network/Google/Resource/StorageTransfer/TransferJobs/Patch.hs | mpl-2.0 | 5,416 | 0 | 16 | 1,226 | 780 | 457 | 323 | 113 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AndroidEnterprise.Users.GenerateAuthenticationToken
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Generates an authentication token which the device policy client can use
-- to provision the given EMM-managed user account on a device. The
-- generated token is single-use and expires after a few minutes. You can
-- provision a maximum of 10 devices per user. This call only works with
-- EMM-managed accounts.
--
-- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.users.generateAuthenticationToken@.
module Network.Google.Resource.AndroidEnterprise.Users.GenerateAuthenticationToken
(
-- * REST Resource
UsersGenerateAuthenticationTokenResource
-- * Creating a Request
, usersGenerateAuthenticationToken
, UsersGenerateAuthenticationToken
-- * Request Lenses
, ugatXgafv
, ugatUploadProtocol
, ugatEnterpriseId
, ugatAccessToken
, ugatUploadType
, ugatUserId
, ugatCallback
) where
import Network.Google.AndroidEnterprise.Types
import Network.Google.Prelude
-- | A resource alias for @androidenterprise.users.generateAuthenticationToken@ method which the
-- 'UsersGenerateAuthenticationToken' request conforms to.
type UsersGenerateAuthenticationTokenResource =
"androidenterprise" :>
"v1" :>
"enterprises" :>
Capture "enterpriseId" Text :>
"users" :>
Capture "userId" Text :>
"authenticationToken" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Post '[JSON] AuthenticationToken
-- | Generates an authentication token which the device policy client can use
-- to provision the given EMM-managed user account on a device. The
-- generated token is single-use and expires after a few minutes. You can
-- provision a maximum of 10 devices per user. This call only works with
-- EMM-managed accounts.
--
-- /See:/ 'usersGenerateAuthenticationToken' smart constructor.
data UsersGenerateAuthenticationToken =
UsersGenerateAuthenticationToken'
{ _ugatXgafv :: !(Maybe Xgafv)
, _ugatUploadProtocol :: !(Maybe Text)
, _ugatEnterpriseId :: !Text
, _ugatAccessToken :: !(Maybe Text)
, _ugatUploadType :: !(Maybe Text)
, _ugatUserId :: !Text
, _ugatCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UsersGenerateAuthenticationToken' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ugatXgafv'
--
-- * 'ugatUploadProtocol'
--
-- * 'ugatEnterpriseId'
--
-- * 'ugatAccessToken'
--
-- * 'ugatUploadType'
--
-- * 'ugatUserId'
--
-- * 'ugatCallback'
usersGenerateAuthenticationToken
:: Text -- ^ 'ugatEnterpriseId'
-> Text -- ^ 'ugatUserId'
-> UsersGenerateAuthenticationToken
usersGenerateAuthenticationToken pUgatEnterpriseId_ pUgatUserId_ =
UsersGenerateAuthenticationToken'
{ _ugatXgafv = Nothing
, _ugatUploadProtocol = Nothing
, _ugatEnterpriseId = pUgatEnterpriseId_
, _ugatAccessToken = Nothing
, _ugatUploadType = Nothing
, _ugatUserId = pUgatUserId_
, _ugatCallback = Nothing
}
-- | V1 error format.
ugatXgafv :: Lens' UsersGenerateAuthenticationToken (Maybe Xgafv)
ugatXgafv
= lens _ugatXgafv (\ s a -> s{_ugatXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ugatUploadProtocol :: Lens' UsersGenerateAuthenticationToken (Maybe Text)
ugatUploadProtocol
= lens _ugatUploadProtocol
(\ s a -> s{_ugatUploadProtocol = a})
-- | The ID of the enterprise.
ugatEnterpriseId :: Lens' UsersGenerateAuthenticationToken Text
ugatEnterpriseId
= lens _ugatEnterpriseId
(\ s a -> s{_ugatEnterpriseId = a})
-- | OAuth access token.
ugatAccessToken :: Lens' UsersGenerateAuthenticationToken (Maybe Text)
ugatAccessToken
= lens _ugatAccessToken
(\ s a -> s{_ugatAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ugatUploadType :: Lens' UsersGenerateAuthenticationToken (Maybe Text)
ugatUploadType
= lens _ugatUploadType
(\ s a -> s{_ugatUploadType = a})
-- | The ID of the user.
ugatUserId :: Lens' UsersGenerateAuthenticationToken Text
ugatUserId
= lens _ugatUserId (\ s a -> s{_ugatUserId = a})
-- | JSONP
ugatCallback :: Lens' UsersGenerateAuthenticationToken (Maybe Text)
ugatCallback
= lens _ugatCallback (\ s a -> s{_ugatCallback = a})
instance GoogleRequest
UsersGenerateAuthenticationToken
where
type Rs UsersGenerateAuthenticationToken =
AuthenticationToken
type Scopes UsersGenerateAuthenticationToken =
'["https://www.googleapis.com/auth/androidenterprise"]
requestClient UsersGenerateAuthenticationToken'{..}
= go _ugatEnterpriseId _ugatUserId _ugatXgafv
_ugatUploadProtocol
_ugatAccessToken
_ugatUploadType
_ugatCallback
(Just AltJSON)
androidEnterpriseService
where go
= buildClient
(Proxy ::
Proxy UsersGenerateAuthenticationTokenResource)
mempty
| brendanhay/gogol | gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/Users/GenerateAuthenticationToken.hs | mpl-2.0 | 6,265 | 0 | 20 | 1,431 | 793 | 464 | 329 | 122 | 1 |
import Data.Word
import Data.List (unfoldr)
likedOverTime :: Word8 -> Integer
likedOverTime = sum . unfoldr go . (,) 5 . toInteger
where
likedToday = flip div 2
shared = (* 3)
go (_, 0) = Nothing
go (x, n) =
let x' = likedToday x
in Just (x', (shared x', n - 1))
main = print =<< fmap (likedOverTime . read) getLine
| itsbruce/hackerrank | alg/implementation/viralAd.hs | unlicense | 379 | 0 | 12 | 125 | 157 | 84 | 73 | 11 | 2 |
module Handler.Post where
import Import
import Yesod.Form.Bootstrap3
import Text.Blaze.Internal (Markup)
data RawPost = RawPost
{ rPname :: Text
, rPgender :: Text
, rPlookingFor :: Text
, rPlat :: Text
, rPlng :: Text
, rpdesc :: Text
, user :: UserId
}
getPostR :: Handler Html
getPostR = do
uid <- requireAuthId
(widget,enctype) <- generateFormPost $ renderBootstrap3 BootstrapBasicForm (postForm uid)
defaultLayout $ [whamlet|
<form method="post" enctype=#{enctype}>
^{widget}
<p>
<button type="submit" class="btn btn-default" role="button">Post! »
|]
postPostR :: Handler Html
postPostR = do
uid <- requireAuthId
((res,widget),enctype) <- runFormPost (validPostForm uid)
case res of
FormSuccess p -> do
runDB $ insert_ p
redirect ShowR
_ ->
defaultLayout $ [whamlet|
<form method="post" enctype=#{enctype}>
^{widget}
<p>
<button type="submit" class="btn btn-default" role="button">Post! »
|]
validPostForm :: UserId -> Markup -> MForm Handler (FormResult Post, Widget)
validPostForm uid html = do
(res, widget) <- renderBootstrap3 BootstrapBasicForm (postForm uid) html
return $ case res of
FormSuccess r -> convert r
where
msg = "Invalid coordinates" :: Text
convert (RawPost n g l lat lng d u) = case (,) <$> convlat lat <*> convlng lng of
Just (lat', lng') -> (FormSuccess (Post n g l lat' lng' d u), widget)
Nothing -> (FormFailure [msg], [whamlet|
<p .errors>#{msg}
^{widget}
|])
_ -> (convWrong <$> res, widget)
convlat :: Text -> Maybe Double
convlat c = readMay c
--TODO: add parser for 51ˇ21'22''N-Format
convlng :: Text -> Maybe Double
convlng c = readMay c
--TODO: add parser for 51ˇ21'22''N-Format
convWrong :: RawPost -> Post
convWrong (RawPost n g l _ _ d u) = Post n g l 0 0 d u
postForm :: UserId -> AForm Handler RawPost
postForm uid = RawPost
<$> areq textField (withAutofocus $ withPlaceholder "Bernd" $ bfs ("Nickname" :: Text)) Nothing
<*> areq textField (withPlaceholder "unicorn" $ bfs ("Gender" :: Text)) Nothing
<*> areq textField (withPlaceholder "anyone" $ bfs ("Looking for..." :: Text)) Nothing
<*> areq textField (withPlaceholder "Latitude" $ bfs ("Latitude" :: Text)) Nothing
<*> areq textField (withPlaceholder "Longitude" $ bfs ("Longitude" :: Text)) Nothing
<*> (unTextarea <$> areq textareaField (withPlaceholder "I want some choclate... and candy.." $ bfs ("Description" :: Text)) Nothing)
<*> pure uid
| Drezil/FFF | Handler/Post.hs | apache-2.0 | 3,077 | 0 | 19 | 1,084 | 771 | 403 | 368 | -1 | -1 |
module HelperSequences.A070939Spec (main, spec) where
import Test.Hspec
import HelperSequences.A070939 (a070939)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A070939" $
it "correctly computes the first 20 elements" $
take 20 (map a070939 [0..]) `shouldBe` expectedValue where
expectedValue = [1,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5]
| peterokagey/haskellOEIS | test/HelperSequences/A070939Spec.hs | apache-2.0 | 365 | 0 | 10 | 59 | 160 | 95 | 65 | 10 | 1 |
{-# LANGUAGE PackageImports, Rank2Types, ExistentialQuantification,
ScopedTypeVariables, FlexibleContexts, GADTs #-}
module Event where
import Type
import Graphics.UI.Gtk
import Coroutine
import Control.Monad.Trans
import Data.IORef
data AllCont = forall o a. (Show o) =>
AllCont { runcont :: (EventResult -> CoroutineT EventResult o IO a) }
data EventGADT a where
GADTButtonPress :: EventGADT EButton
GADTButtonRelease :: EventGADT EButton
GADTMouseMove :: EventGADT EMotion
coroutineHandler :: EventGADT a -> IORef AllCont -> EventM a ()
coroutineHandler GADTButtonPress contref = do
(x,y) <- eventCoordinates
let eventdata = (ButtonPress,(x,y))
action contref eventdata
coroutineHandler GADTButtonRelease contref = do
(x,y) <- eventCoordinates
let eventdata = (ButtonRelease,(x,y))
action contref eventdata
coroutineHandler GADTMouseMove contref = do
(x,y) <- eventCoordinates
let eventdata = (MouseMove,(x,y))
action contref eventdata
run exp = runCoroutineT exp
action contref eventdata = do
cont <- liftIO $ readIORef contref
case cont of
AllCont fun -> do
r <- liftIO $ run $ fun eventdata
case r of
Result a -> do
let newone = \_ -> CoroutineT $ (return r)
liftIO $ writeIORef contref (AllCont newone)
return ()
Yield o ncont -> do
liftIO $ putStrLn $ show o
liftIO $ writeIORef contref (AllCont ncont)
return ()
| wavewave/hournal | xinput/Event.hs | bsd-2-clause | 1,526 | 0 | 23 | 394 | 471 | 237 | 234 | 42 | 2 |
{-# LANGUAGE TypeFamilies, FlexibleInstances, FlexibleContexts,
DeriveDataTypeable, StandaloneDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module : HEP.Automation.MadGraph.Model.ADMXQLD111degen
-- Copyright : (c) 2012,2013 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <ianwookim@gmail.com>
-- Stability : experimental
-- Portability : GHC
--
-- ADM (asymmetric dark matter) XQLD model, 111 generation
--
-----------------------------------------------------------------------------
module HEP.Automation.MadGraph.Model.ADMXQLD111degen where
import Control.Monad.Identity
import Data.Typeable
import Data.Data
import Text.Parsec
import Text.Printf
import Text.StringTemplate
import Text.StringTemplate.Helpers
-- from hep-platform
import HEP.Automation.MadGraph.Model
-- |
data ADMXQLD111degen = ADMXQLD111degen
deriving (Show, Typeable, Data)
instance Model ADMXQLD111degen where
data ModelParam ADMXQLD111degen = ADMXQLD111degenParam { mgluino :: Double
, msquark :: Double
, mslepton :: Double
, mneut :: Double }
deriving Show
briefShow ADMXQLD111degen = "ADMXQLD111degen"
madgraphVersion _ = MadGraph5
modelName _ = "ADMXQLD111degen"
modelFromString str = case str of
"ADMXQLD111degen" -> Just ADMXQLD111degen
_ -> Nothing
paramCard4Model ADMXQLD111degen = "param_card_ADMXQLD111degen.dat"
paramCardSetup tpath ADMXQLD111degen (ADMXQLD111degenParam mg msq msl mn) = do
templates <- directoryGroup tpath
return $ ( renderTemplateGroup
templates
[ ("mgluino", (printf "%.4e" mg :: String))
, ("msquark", (printf "%.4e" msq :: String))
, ("msquarkheavy" , (printf "%.4e" (msq + 5) :: String))
, ("mslepton", (printf "%.4e" msl :: String))
, ("mneut", (printf "%.4e" mn :: String)) ]
(paramCard4Model ADMXQLD111degen) ) ++ "\n\n\n"
briefParamShow (ADMXQLD111degenParam mg msq msl mn) = "MG"++show mg++"MQ"++show msq ++ "ML" ++ show msl ++ "MN"++show mn
interpreteParam str = let r = parse xqldparse "" str
in case r of
Right param -> param
Left err -> error (show err)
-- |
xqldparse :: ParsecT String () Identity (ModelParam ADMXQLD111degen)
xqldparse = do
string "MG"
mgstr <- many1 (oneOf "+-0123456789.")
string "MQ"
mqstr <- many1 (oneOf "+-0123456789.")
string "ML"
mlstr <- many1 (oneOf "+-0123456789.")
string "MN"
mnstr <- many1 (oneOf "+-0123456789.")
return (ADMXQLD111degenParam (read mgstr) (read mqstr) (read mlstr) (read mnstr))
-----------------------------
-- for type representation
-----------------------------
-- |
admxqldTr :: TypeRep
admxqldTr = mkTyConApp (mkTyCon "HEP.Automation.MadGraph.Model.ADMXQLD111degen.ADMXQLD111degen") []
-- |
instance Typeable (ModelParam ADMXQLD111degen) where
typeOf _ = mkTyConApp modelParamTc [admxqldTr]
-- |
deriving instance Data (ModelParam ADMXQLD111degen) | wavewave/madgraph-auto-model | src/HEP/Automation/MadGraph/Model/ADMXQLD111degen.hs | bsd-2-clause | 3,309 | 0 | 17 | 855 | 714 | 378 | 336 | 57 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : JSON
-- Copyright : (c) Masahiro Sakai & Jun Mukai 2006
-- License : BSD-style
--
-- Maintainer : sakai@tom.sfc.keio.ac.jp
-- Stability : experimental
-- Portability : portable
--
-----------------------------------------------------------------------------
module MonadServ.JSON
( Value (..)
, parse
, json
, stringify
, stringify'
, toDoc
, toDoc'
) where
import Control.Monad hiding (join)
import Text.ParserCombinators.Parsec hiding (parse)
import qualified Text.ParserCombinators.Parsec as P
import Text.PrettyPrint.HughesPJ hiding (char)
import Text.Printf (printf)
import Data.Char (ord, chr, isControl)
import Data.List (unfoldr)
import Data.Bits
import qualified Data.Map as M
-- ---------------------------------------------------------------------------
-- The Value data type
data Value
= String String
| Number !Double
| Object !(M.Map String Value)
| Array [Value]
| Bool !Bool
| Null
deriving (Eq,Show)
{-
instance Show Value where
showsPrec p = showsPrec p . toDoc
-}
-- ---------------------------------------------------------------------------
-- The JSON Parser
parse :: String -> Maybe Value
parse s = case P.parse json "JSON.parse" s of
Left err -> Nothing
Right v -> Just v
json :: Parser Value
json = spaces >> tok value
tok :: Parser a -> Parser a
tok p = do{ x <- p; spaces; return x }
value :: Parser Value
value = msum
[ liftM String str
, liftM Number number
, liftM Object object
, liftM Array array
, string "true" >> return (Bool True)
, string "false" >> return (Bool False)
, string "null" >> return Null
]
str :: Parser String
str = liftM decodeSurrogatePairs $
between (char '"') (char '"') $ many c1
where c1 = satisfy (\c -> not (c=='"' || c=='\\' || isControl c))
<|> (char '\\' >> c2)
c2 = msum
[ char '"'
, char '\\'
, char '/'
, char 'b' >> return '\b'
, char 'f' >> return '\f'
, char 'n' >> return '\n'
, char 'r' >> return '\r'
, char 't' >> return '\t'
, char 'u' >> do xs <- count 4 hexDigit
return $ read $ "'\\x"++xs++"'"
]
number :: Parser Double
number = liftM read $ int >>+ option "" frac >>+ option "" exp
where digits = many1 digit
int = option "" (string "-") >>+ digits
frac = char '.' >>: digits
exp = e >>+ digits
e = oneOf "eE" >>: option "" (string "+" <|> string "-")
(>>+) = liftM2 (++)
(>>:) = liftM2 (:)
object :: Parser (M.Map String Value)
object = liftM M.fromList $
between (tok (char '{')) (char '}') $
tok member `sepBy` tok (char ',')
where member = do k <- tok str
tok (char ':')
v <- value
return (k,v)
array :: Parser [Value]
array = between (tok (char '[')) (char ']') $
tok value `sepBy` tok (char ',')
decodeSurrogatePairs :: String -> String
decodeSurrogatePairs = unfoldr phi
where
phi :: String -> Maybe (Char, String)
phi (h:l:xs)
| '\xD800' <= h && h <= '\xDBFF' && '\xDC00' <= l && l <= '\xDFFF'
= seq c $ Just (c, xs)
where c = chr $ ((ord h .&. 1023) `shiftL` 10 .|. ord l .&. 1023) + 0x10000
phi (x:xs) = Just (x, xs)
phi [] = Nothing
-- ---------------------------------------------------------------------------
-- The JSON Printer
stringify :: Value -> String
stringify = stringify' (const False)
stringify' :: (Char -> Bool) -> Value -> String
stringify' needEscape = show . toDoc' needEscape
toDoc :: Value -> Doc
toDoc = toDoc' (const False)
toDoc' :: (Char -> Bool) -> Value -> Doc
toDoc' needEscape = go
where
go :: Value -> Doc
go (String s) = strToDoc s
go (Number x)
| isInfinite x = error "can't stringify infinity"
| isNaN x = error "can't stringify NaN"
| otherwise = double x
go (Object m) = lbrace <+> join comma members $+$ rbrace
where members = [fsep [strToDoc k <> colon, nest 2 (go v)]
| (k,v) <- M.toList m]
go (Array xs) = lbrack <+> join comma (map go xs) <+> rbrack
go (Bool b) = text $ if b then "true" else "false"
go Null = text "null"
strToDoc :: String -> Doc
strToDoc = doubleQuotes . text . concatMap f
where f '"' = "\\\""
f '\\' = "\\\\"
f '\b' = "\\b"
f '\f' = "\\f"
f '\n' = "\\n"
f '\r' = "\\r"
f '\t' = "\\t"
f c | isControl c || needEscape c =
if c < '\x10000'
then printf "\\u%04x" c
else case makeSurrogatePair c of
(h,l) -> printf "\\u%04x\\u%04x" h l
| otherwise = [c]
join :: Doc -> [Doc] -> Doc
join s = fcat . punctuate s
makeSurrogatePair :: Char -> (Char,Char)
makeSurrogatePair c = (chr h, chr l)
where c' = ord c
h = (c' - 0x10000) `shiftR` 10 .|. 0xd800
l = c' .&. 1023 .|. 0xdc00
| jcaldwell/monadserv | src/MonadServ/JSON.hs | bsd-2-clause | 5,485 | 0 | 17 | 1,860 | 1,784 | 921 | 863 | 135 | 15 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Data.Swagger.Schema.Generator where
import Prelude ()
import Prelude.Compat
import Control.Lens.Operators
import Control.Monad (filterM)
import Data.Aeson
import qualified Data.Aeson.KeyMap as KM
import Data.Aeson.Types
import qualified Data.HashMap.Strict.InsOrd as M
import Data.Maybe
import Data.Proxy
import Data.Scientific
import qualified Data.Set as S
import Data.Swagger
import Data.Swagger.Declare
import Data.Swagger.Internal.Schema.Validation (inferSchemaTypes)
import qualified Data.Text as T
import qualified Data.Vector as V
import Test.QuickCheck (arbitrary)
import Test.QuickCheck.Gen
import Test.QuickCheck.Property
-- | Note: 'schemaGen' may 'error', if schema type is not specified,
-- and cannot be inferred.
schemaGen :: Definitions Schema -> Schema -> Gen Value
schemaGen _ schema
| Just cases <- schema ^. paramSchema . enum_ = elements cases
schemaGen defns schema =
case schema ^. type_ of
Nothing ->
case inferSchemaTypes schema of
[ inferredType ] -> schemaGen defns (schema & type_ ?~ inferredType)
-- Gen is not MonadFail
_ -> error "unable to infer schema type"
Just SwaggerBoolean -> Bool <$> elements [True, False]
Just SwaggerNull -> pure Null
Just SwaggerNumber
| Just min <- schema ^. minimum_
, Just max <- schema ^. maximum_ ->
Number . fromFloatDigits <$>
choose (toRealFloat min, toRealFloat max :: Double)
| otherwise -> Number .fromFloatDigits <$> (arbitrary :: Gen Double)
Just SwaggerInteger
| Just min <- schema ^. minimum_
, Just max <- schema ^. maximum_ ->
Number . fromInteger <$>
choose (truncate min, truncate max)
| otherwise -> Number . fromInteger <$> arbitrary
Just SwaggerArray
| Just 0 <- schema ^. maxLength -> pure $ Array V.empty
| Just items <- schema ^. items ->
case items of
SwaggerItemsObject ref -> do
size <- getSize
let itemSchema = dereference defns ref
minLength' = fromMaybe 0 $ fromInteger <$> schema ^. minItems
maxLength' = fromMaybe size $ fromInteger <$> schema ^. maxItems
arrayLength <- choose (minLength', max minLength' maxLength')
generatedArray <- vectorOf arrayLength $ schemaGen defns itemSchema
return . Array $ V.fromList generatedArray
SwaggerItemsArray refs ->
let itemGens = schemaGen defns . dereference defns <$> refs
in fmap (Array . V.fromList) $ sequence itemGens
Just SwaggerString -> do
size <- getSize
let minLength' = fromMaybe 0 $ fromInteger <$> schema ^. minLength
let maxLength' = fromMaybe size $ fromInteger <$> schema ^. maxLength
length <- choose (minLength', max minLength' maxLength')
str <- vectorOf length arbitrary
return . String $ T.pack str
Just SwaggerObject -> do
size <- getSize
let props = dereference defns <$> schema ^. properties
reqKeys = S.fromList $ schema ^. required
allKeys = S.fromList . M.keys $ schema ^. properties
optionalKeys = allKeys S.\\ reqKeys
minProps' = fromMaybe (length reqKeys) $
fromInteger <$> schema ^. minProperties
maxProps' = fromMaybe size $ fromInteger <$> schema ^. maxProperties
shuffledOptional <- shuffle $ S.toList optionalKeys
numProps <- choose (minProps', max minProps' maxProps')
let presentKeys = take numProps $ S.toList reqKeys ++ shuffledOptional
let presentProps = M.filterWithKey (\k _ -> k `elem` presentKeys) props
let gens = schemaGen defns <$> presentProps
additionalGens <- case schema ^. additionalProperties of
Just (AdditionalPropertiesSchema addlSchema) -> do
additionalKeys <- sequence . take (numProps - length presentProps) . repeat $ T.pack <$> arbitrary
return . M.fromList $ zip additionalKeys (repeat . schemaGen defns $ dereference defns addlSchema)
_ -> return []
x <- sequence $ gens <> additionalGens
return . Object . KM.fromHashMapText $ M.toHashMap x
where
dereference :: Definitions a -> Referenced a -> a
dereference _ (Inline a) = a
dereference defs (Ref (Reference ref)) = fromJust $ M.lookup ref defs
genValue :: (ToSchema a) => Proxy a -> Gen Value
genValue p =
let (defs, NamedSchema _ schema) = runDeclare (declareNamedSchema p) M.empty
in schemaGen defs schema
validateFromJSON :: forall a . (ToSchema a, FromJSON a) => Proxy a -> Property
validateFromJSON p = forAll (genValue p) $
\val -> case parseEither parseJSON val of
Right (_ :: a) -> succeeded
Left err -> failed
{ reason = err
}
| GetShopTV/swagger2 | src/Data/Swagger/Schema/Generator.hs | bsd-3-clause | 5,649 | 1 | 24 | 2,005 | 1,469 | 727 | 742 | -1 | -1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module SAWServer.Data.LLVMType (JSONLLVMType, llvmType) where
import Control.Applicative
import qualified Data.Aeson as JSON
import Data.Aeson (withObject, withText, (.:))
import qualified Data.Text as T
import Text.LLVM.AST (FloatType(..), Type'(..), Type, Ident(..), PrimType(..))
newtype JSONLLVMIdent = JSONLLVMIdent { getIdent :: Ident }
instance JSON.FromJSON JSONLLVMIdent where
parseJSON =
withText "LLVM identifier" $ pure . JSONLLVMIdent . Ident . T.unpack
newtype JSONLLVMType = JSONLLVMType { getLLVMType :: Type' JSONLLVMIdent }
data LLVMTypeTag
= TagPrimType
| TagAlias
| TagArray
| TagFunTy
| TagPtrTo
| TagStruct
| TagPackedStruct
| TagVector
| TagOpaque
instance JSON.FromJSON LLVMTypeTag where
parseJSON =
withText "LLVM type tag" $
\case
"primitive type" -> pure TagPrimType
"type alias" -> pure TagAlias
"array"-> pure TagArray
"function" -> pure TagFunTy
"pointer" -> pure TagPtrTo
"struct" -> pure TagStruct
"packed struct" -> pure TagPackedStruct
"vector" -> pure TagVector
"opaque" -> pure TagOpaque
_ -> empty
data PrimTypeTag
= TagLabel
| TagVoid
| TagInteger
| TagFloatType
| TagX86mmx
| TagMetadata
instance JSON.FromJSON PrimTypeTag where
parseJSON =
withText "LLVM primitive type tag" $
\case
"label" -> pure TagLabel
"void" -> pure TagVoid
"integer" -> pure TagInteger
"float" -> pure TagFloatType
"X86mmx" -> pure TagX86mmx
"metadata" -> pure TagMetadata
_ -> empty
newtype JSONFloatType = JSONFloatType { getFloatType :: FloatType }
instance JSON.FromJSON JSONFloatType where
parseJSON =
withText "LLVM float type" $ \t -> fmap JSONFloatType $
case t of
"half" -> pure Half
"float" -> pure Float
"double" -> pure Double
"fp128" -> pure Fp128
"x86_fp80" -> pure X86_fp80
"PPC_fp128" -> pure PPC_fp128
_ -> empty
instance JSON.FromJSON JSONLLVMType where
parseJSON =
primType
where
primType =
withObject "LLVM type" $ \o -> fmap JSONLLVMType $
o .: "type" >>=
\case
TagPrimType ->
fmap PrimType $
o .: "primitive" >>=
\case
TagLabel -> pure Label
TagVoid -> pure Void
TagInteger -> Integer <$> o .: "size"
TagFloatType ->
FloatType . getFloatType <$> o .: "float type"
TagX86mmx -> pure X86mmx
TagMetadata -> pure Metadata
TagAlias -> Alias <$> o .: "alias of"
TagArray -> Array <$> o .: "size" <*> (getLLVMType <$> o .: "element type")
TagFunTy -> FunTy <$> (getLLVMType <$> o .: "return type") <*> (fmap getLLVMType <$> o .: "argument types") <*> o .: "varargs"
TagPtrTo -> PtrTo <$> (getLLVMType <$> o .: "to type")
TagStruct -> Struct <$> (fmap getLLVMType <$> o .: "fields")
TagPackedStruct -> PackedStruct <$> (fmap getLLVMType <$> o .: "fields")
TagVector -> Vector <$> o .: "size" <*> (getLLVMType <$> o .: "element type")
TagOpaque -> pure Opaque
llvmType :: JSONLLVMType -> Type
llvmType = fmap getIdent . getLLVMType
| GaloisInc/saw-script | saw-remote-api/src/SAWServer/Data/LLVMType.hs | bsd-3-clause | 3,354 | 0 | 20 | 924 | 880 | 463 | 417 | 96 | 1 |
module CouchGames.Manager
( Manager
, ManagerS
, emptyManager
, newUser
, getUserFromSession
, newLobby
, joinLobby
, getLobbies
, newPlayer
, getSockets
, removeSocket
) where
import qualified Data.Map as Map
import qualified Data.IntMap as IMap
import qualified Data.Text as T
import qualified Data.List as L
import Data.Int
import Control.Monad.State
import CouchGames.Player
import CouchGames.Lobby
import CouchGames.Game
import qualified CouchGames.Resistance as R
import Web.Users.Types
import Network.WebSockets
data Game
= GameResistance R.GameState
-- A user may have one player
-- A player may have many sockets
data Manager = Manager
{ sessions :: Map.Map T.Text (Int64, User) -- Session Ids to Users
, sockets :: IMap.IntMap [Connection] -- Player Ids to Sockets
, nextPlayerId :: Int
, players :: IMap.IntMap Player -- User Ids to Players
, nextLobbyId :: Int
, lobbies :: IMap.IntMap Lobby -- Lobby Id to Lobby
, nextGameId :: Int
, games :: IMap.IntMap Game -- Game Id to Game
}
type ManagerS = State Manager
emptyManager :: Manager
emptyManager = Manager
{ sessions = Map.empty
, sockets = IMap.empty
, nextPlayerId = 1
, players = IMap.empty
, nextLobbyId = 1
, lobbies = IMap.empty
, nextGameId = 1
, games = IMap.empty
}
newUser :: Int64 -> User -> T.Text -> ManagerS ()
newUser uid user sessId = do
m <- get
put m { sessions = Map.insert sessId (uid, user) (sessions m) }
getUserFromSession :: T.Text -> ManagerS (Maybe (Int64, User))
getUserFromSession sessId = do
m <- get
return $ Map.lookup sessId (sessions m)
newLobby :: GameType -> ManagerS Int
newLobby gameType = do
m <- get
put m { lobbies = IMap.insert (nextLobbyId m) (lobby (nextLobbyId m)) (lobbies m), nextLobbyId = nextLobbyId m + 1 }
return $ nextLobbyId m
where
lobby id = Lobby { lobbyId = id
, lobbyPlayers = []
, lobbyGame = gameType
, lobbyState = LSOpen
}
joinLobby :: Int -> Int -> ManagerS ()
joinLobby playerId lobbyId = do
m <- get
case (IMap.lookup playerId (players m)) of
(Just p) ->
put m { lobbies = IMap.adjust (addPlayer p) lobbyId (lobbies m) }
Nothing ->
return ()
getLobbies :: ManagerS [Lobby]
getLobbies = do
m <- get
return $ IMap.elems (lobbies m)
newPlayer :: Int64 -> T.Text -> Connection -> ManagerS Int
newPlayer userId userName socket = do
m <- get
put m { players = players' m, sockets = sockets' m, nextPlayerId = nextPlayerId m + 1 }
return $ nextPlayerId m
where
players' m = IMap.insert (fromIntegral userId) (p m) (players m)
p m = Player { playerId = nextPlayerId m
, displayName = userName
}
sockets' m = IMap.insert (nextPlayerId m) [socket] (sockets m)
-- For now just removes all sockets from a player
removeSocket :: Int -> ManagerS ()
removeSocket playerId = do
m <- get
case (IMap.lookup playerId (sockets m)) of
Just pid -> put m { sockets = IMap.adjust (const []) playerId (sockets m) }
Nothing -> return ()
getSockets :: ManagerS [Connection]
getSockets = do
m <- get
return $ concat $ IMap.elems (sockets m)
| alexlegg/couchgames | src/CouchGames/Manager.hs | bsd-3-clause | 3,597 | 0 | 16 | 1,159 | 1,074 | 577 | 497 | 94 | 2 |
-- | Loads the icons into the component info icon view
module View.InitIconsInfoArea where
-- External libraries
import Graphics.UI.Gtk
-- Internal libraries
import View.Objects
import Paths
type IconsInfoViewStore = ListStore (Pixbuf, String)
-- | Loads the icons into the component info icon view
initIconsInfoArea :: Builder -> IO IconsInfoViewStore
initIconsInfoArea bldr = do
m <- listStoreNew =<< getIconList
iv <- infoIconView bldr
iconViewSetModel iv (Just m)
col1 <- treeViewColumnNew
renderer1 <- cellRendererTextNew
cellLayoutPackStart col1 renderer1 True
cellLayoutSetAttributes col1 renderer1 m $ \row -> [ cellText := snd row ]
icon <- treeViewColumnNew
renderIcon <- cellRendererPixbufNew
cellLayoutPackStart icon renderIcon True
cellLayoutSetAttributes icon renderIcon m $ \row -> [ cellPixbuf := fst row ]
treeModelSetColumn m _PIXBUF_COLUMN fst
treeModelSetColumn m _STRING_COLUMN snd
iconViewSetPixbufColumn iv _PIXBUF_COLUMN
iconViewSetTextColumn iv _STRING_COLUMN
return m
-- | The pixbuf column
_PIXBUF_COLUMN :: ColumnId (Pixbuf, String) Pixbuf
_PIXBUF_COLUMN = makeColumnIdPixbuf 0
-- | The string column
_STRING_COLUMN :: ColumnId (Pixbuf, String) String
_STRING_COLUMN = makeColumnIdString 1
-- | The icon list with proper sizes
getIconList :: IO [(Pixbuf, String)]
getIconList = mapM f icons
where f (x,y) = do w <- getDataFileName x
pb <- pixbufNewFromFileAtSize w stdIconSize stdIconSize
return (pb, y)
-- | The list of icons and their labels
icons :: [(String, String)]
icons = [ ("images/icons/info.png", "Basic info")
, ("images/icons/trace.png", "Trace")
]
-- | The icon size for these icons
stdIconSize :: Int
stdIconSize = 48
| ivanperez-keera/SoOSiM-ui | src/View/InitIconsInfoArea.hs | bsd-3-clause | 1,769 | 0 | 11 | 339 | 421 | 216 | 205 | 37 | 1 |
module Lib where
import Examples
someFunc :: IO ()
someFunc = putStrLn "someFunc"
| lambdatoast/gadt-spec | src/Lib.hs | bsd-3-clause | 84 | 0 | 6 | 15 | 25 | 14 | 11 | 4 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
module Servant.API.JSONUtf8 where
import ClassyPrelude
import Servant.API.ContentTypes
import Data.Aeson ( FromJSON, ToJSON, encode )
import qualified Network.HTTP.Media as M
data JSONUtf8 deriving Typeable
-- | @application/json@
instance Accept JSONUtf8 where
contentType _ = "application" M.// "json" M./: ("charset", "utf-8")
-- | `encode`
instance {-# OVERLAPPABLE #-} ToJSON a => MimeRender JSONUtf8 a where
mimeRender _ = encode
-- | `eitherDecode`
instance FromJSON a => MimeUnrender JSONUtf8 a where
mimeUnrender _ = eitherDecodeLenient
| CthulhuDen/api-ai | src/Servant/API/JSONUtf8.hs | bsd-3-clause | 603 | 0 | 7 | 94 | 136 | 79 | 57 | -1 | -1 |
--------------------------------------------------------------------------------
-- |
-- Module : Network.OpenID.Assocation.Map
-- Copyright : (c) Trevor Elliott, 2008
-- License : BSD3
--
-- Maintainer : Trevor Elliott <trevor@geekgateway.com>
-- Stability :
-- Portability :
--
module Network.OpenID.Association.Map (
-- Association Map
AssociationMap(..)
, emptyAssociationMap
) where
-- friends
import Network.OpenID.Association.Manager
import Network.OpenID.Types
-- libraries
import Data.Time
import qualified Data.Map as Map
-- | A simple association manager based on Data.Map
newtype AssociationMap = AM (Map.Map String (UTCTime,Association))
deriving (Show,Read)
instance AssociationManager AssociationMap where
findAssociation (AM m) p = snd `fmap` Map.lookup (showProvider p) m
addAssociation (AM m) now p a = AM (Map.insert (showProvider p) (ex,a) m)
where ex = addUTCTime (toEnum (assocExpiresIn a)) now
expire (AM m) now = AM (Map.filter ((now >) . fst) m)
exportAssociations (AM m) = map f (Map.toList m)
where f (p,(t,a)) = (p,t,a)
-- | An empty association map.
emptyAssociationMap :: AssociationMap
emptyAssociationMap = AM Map.empty
| elliottt/hsopenid | src/Network/OpenID/Association/Map.hs | bsd-3-clause | 1,211 | 0 | 12 | 208 | 323 | 186 | 137 | 18 | 1 |
module Main where
import Data.Numbers.Primes (isPrime, primes)
import Control.Monad (guard)
mersenneNumber :: Integer -> Integer
mersenneNumber n = 2 ^ n - 1
mersennePrimes :: [Integer]
mersennePrimes = do
let selectedPrimes = [ x | x <- primes, x <= 57885161 ]
x <- selectedPrimes
let n = mersenneNumber x
guard $ isPrime n
return n
main :: IO ()
main = do
putStrLn "Printing Mersenne primes!"
mapM_ print mersennePrimes
| Michaelt293/mersenne | src/Main.hs | bsd-3-clause | 454 | 0 | 12 | 102 | 158 | 80 | 78 | 16 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
module FPNLA.Matrix.Instances.VectorMatrix (
VVector,
VMatrix(VMatrix),
) where
import Control.DeepSeq (NFData, rnf)
import Control.Parallel.Strategies (rdeepseq, withStrategy)
import qualified Data.Foldable (foldr)
import qualified Data.Vector as DV (Vector, concat, drop,
fromList, generate, head,
length, map, take, toList,
zipWith, (!), (++))
import FPNLA.Matrix (Matrix (..), MatrixVector (..),
Vector (..), cantCols_m)
import FPNLA.Utils (iif)
{-
instance (NFData a) => NFData (DV.Vector a) where
rnf v = evalVect (DV.length v)
where evalVect i
| i > 0 = withStrategy rdeepseq (v DV.! (i-1)) `seq` evalVect (i-1)
| otherwise = ()
-}
instance (NFData a) => NFData (VMatrix a) where
rnf (VMatrix v) = withStrategy rdeepseq v `seq` ()
--
type VVector = DV.Vector
instance Vector (DV.Vector) e where
generate_v = DV.generate
fromList_v = DV.fromList
concat_v = DV.concat
elem_v = flip (DV.!)
length_v = DV.length
foldr_v = Data.Foldable.foldr
map_v = DV.map
zipWith_v = DV.zipWith
--
newtype VMatrix e = VMatrix (DV.Vector (DV.Vector e)) deriving (Show)
wrapIn :: DV.Vector (DV.Vector e) -> VMatrix e
wrapIn = VMatrix
wrapOut :: VMatrix e -> DV.Vector (DV.Vector e)
wrapOut (VMatrix vv) = vv
instance Matrix VMatrix e where
generate_m cr cc gen = wrapIn $ DV.generate cc (\j -> DV.generate cr (`gen` j))
--fromList_m =
--transpose_m =
-- Se guarda por columnas!
dim_m m = (iif (cc > 0) cr 0, cc)
where cc = DV.length (wrapOut m)
cr = DV.length $ DV.head (wrapOut m)
elem_m i j m = wrapOut m DV.! j DV.! i
map_m f m = wrapIn $ DV.map (DV.map f) (wrapOut m)
zipWith_m f m1 m2 = wrapIn $ DV.zipWith (DV.zipWith f) (wrapOut m1) (wrapOut m2)
subMatrix_m posI posJ cantRows cantCols =
wrapIn . DV.map (DV.take cantRows . DV.drop posI) . DV.take cantCols . DV.drop posJ . wrapOut
fromBlocks_m = expandVert . map expandHoriz
where
expandVert lm = wrapIn . DV.generate (cantCols_m (head lm)) $ (\c -> foldr1 (DV.++) $ map (col_vm c) lm)
expandHoriz = wrapIn . foldr1 (DV.++) . map wrapOut
--toBlocks_m
instance MatrixVector VMatrix DV.Vector e where
row_vm i m = DV.map (DV.! i) (wrapOut m)
col_vm j m = wrapOut m DV.! j
fromCols_vm = wrapIn . DV.fromList
toCols_vm = DV.toList . wrapOut
| mauroblanco/fpnla-examples | src/FPNLA/Matrix/Instances/VectorMatrix.hs | bsd-3-clause | 2,815 | 0 | 14 | 889 | 874 | 479 | 395 | 54 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Control.DeepSeq (deepseq)
import Criterion.Main
import Symantics (fact15)
import Simple
import Staged
import ErrorHandling
import ErrorHandlingStaged
import CPS
import CPSStaged
import Inlining
import InliningNoDup
import All
main :: IO ()
main = defaultMain
[ bgroup "factorial-15"
[ bench "simple" $ nf (evalSimple fact15 `deepseq`) ()
, bench "staged" $ nf ($(evalStaged fact15) `deepseq`) ()
, bench "error-handling" $ nf (evalEH fact15 `deepseq`) ()
, bench "error-handling-staged" $ nf ($(evalEHS fact15) `deepseq`) ()
, bench "cps" $ nf (evalCPS fact15 `deepseq`) ()
, bench "cps-staged" $ nf ($(evalCPSS fact15) `deepseq`) ()
, bench "inlining" $ nf ($(evalInlining fact15) `deepseq`) ()
, bench "inlining-nodup" $ nf ($(evalIND fact15) `deepseq`) ()
, bench "all" $ nf ($(evalAll fact15) `deepseq`) ()
]
]
| maoe/MSP | bench.hs | bsd-3-clause | 939 | 0 | 14 | 192 | 339 | 187 | 152 | 26 | 1 |
-- 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.
module Duckling.Dimensions.AR
( allDimensions
) where
import Duckling.Dimensions.Types
allDimensions :: [Seal Dimension]
allDimensions =
[ Seal Duration
, Seal Numeral
, Seal Ordinal
, Seal Quantity
, Seal Temperature
, Seal Time
, Seal Volume
]
| facebookincubator/duckling | Duckling/Dimensions/AR.hs | bsd-3-clause | 475 | 0 | 6 | 95 | 81 | 47 | 34 | 12 | 1 |
module Stars where
import Rumpus
-- Golden Section Spiral (via http://www.softimageblog.com/archives/115)
pointsOnSphere :: Int -> [V3 GLfloat]
pointsOnSphere (fromIntegral -> n) =
let inc = pi * (3 - sqrt 5)
off = 2 / n
halfOff = off / 2
in for [0..n] $ \k ->
let y = k * off - 1 + halfOff
r = sqrt (1 - y*y)
phi = k * inc
in V3 (cos phi * r) y (sin phi * r)
start :: Start
start = do
-- We only take half the request points to get the upper hemisphere
let numPoints = 200 :: Int
--points = reverse $ drop (numPoints `div` 2) $ pointsOnSphere numPoints
points = reverse $ pointsOnSphere numPoints
hues = map ((/ fromIntegral numPoints) . fromIntegral) [0..numPoints]
forM_ (zip3 [0..] points hues) $ \(i, pos, hue) -> spawnChild $ do
myTransformType ==> AbsolutePose
myShape ==> Sphere
mySize ==> 0.001
myColor ==> colorHSL hue 0.8 0.8
myPose ==> position (pos * 500)
myStart ==> do
setDelayedAction (fromIntegral i * 0.05) $
setSize 5
| lukexi/rumpus | pristine/Lobby/Stars.hs | bsd-3-clause | 1,228 | 0 | 19 | 466 | 364 | 186 | 178 | -1 | -1 |
{-# language CPP #-}
-- No documentation found for Chapter "DescriptorPoolCreateFlagBits"
module Vulkan.Core10.Enums.DescriptorPoolCreateFlagBits ( DescriptorPoolCreateFlags
, DescriptorPoolCreateFlagBits( DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT
, DESCRIPTOR_POOL_CREATE_HOST_ONLY_BIT_VALVE
, DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT
, ..
)
) where
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import GHC.Show (showString)
import Numeric (showHex)
import Vulkan.Zero (Zero)
import Data.Bits (Bits)
import Data.Bits (FiniteBits)
import Foreign.Storable (Storable)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Vulkan.Core10.FundamentalTypes (Flags)
type DescriptorPoolCreateFlags = DescriptorPoolCreateFlagBits
-- | VkDescriptorPoolCreateFlagBits - Bitmask specifying certain supported
-- operations on a descriptor pool
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>,
-- 'DescriptorPoolCreateFlags'
newtype DescriptorPoolCreateFlagBits = DescriptorPoolCreateFlagBits Flags
deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits)
-- | 'DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT' specifies that
-- descriptor sets /can/ return their individual allocations to the pool,
-- i.e. all of 'Vulkan.Core10.DescriptorSet.allocateDescriptorSets',
-- 'Vulkan.Core10.DescriptorSet.freeDescriptorSets', and
-- 'Vulkan.Core10.DescriptorSet.resetDescriptorPool' are allowed.
-- Otherwise, descriptor sets allocated from the pool /must/ not be
-- individually freed back to the pool, i.e. only
-- 'Vulkan.Core10.DescriptorSet.allocateDescriptorSets' and
-- 'Vulkan.Core10.DescriptorSet.resetDescriptorPool' are allowed.
pattern DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT = DescriptorPoolCreateFlagBits 0x00000001
-- | 'DESCRIPTOR_POOL_CREATE_HOST_ONLY_BIT_VALVE' specifies that this
-- descriptor pool and the descriptor sets allocated from it reside
-- entirely in host memory and cannot be bound. Descriptor sets allocated
-- from this pool are partially exempt from the external synchronization
-- requirement in
-- 'Vulkan.Extensions.VK_KHR_descriptor_update_template.updateDescriptorSetWithTemplateKHR'
-- and 'Vulkan.Core10.DescriptorSet.updateDescriptorSets'. Descriptor sets
-- and their descriptors can be updated concurrently in different threads,
-- though the same descriptor /must/ not be updated concurrently by two
-- threads.
pattern DESCRIPTOR_POOL_CREATE_HOST_ONLY_BIT_VALVE = DescriptorPoolCreateFlagBits 0x00000004
-- | 'DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT' specifies that descriptor
-- sets allocated from this pool /can/ include bindings with the
-- 'Vulkan.Core12.Enums.DescriptorBindingFlagBits.DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT'
-- bit set. It is valid to allocate descriptor sets that have bindings that
-- do not set the
-- 'Vulkan.Core12.Enums.DescriptorBindingFlagBits.DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT'
-- bit from a pool that has 'DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT'
-- set.
pattern DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT = DescriptorPoolCreateFlagBits 0x00000002
conNameDescriptorPoolCreateFlagBits :: String
conNameDescriptorPoolCreateFlagBits = "DescriptorPoolCreateFlagBits"
enumPrefixDescriptorPoolCreateFlagBits :: String
enumPrefixDescriptorPoolCreateFlagBits = "DESCRIPTOR_POOL_CREATE_"
showTableDescriptorPoolCreateFlagBits :: [(DescriptorPoolCreateFlagBits, String)]
showTableDescriptorPoolCreateFlagBits =
[ (DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, "FREE_DESCRIPTOR_SET_BIT")
, (DESCRIPTOR_POOL_CREATE_HOST_ONLY_BIT_VALVE , "HOST_ONLY_BIT_VALVE")
, (DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT , "UPDATE_AFTER_BIND_BIT")
]
instance Show DescriptorPoolCreateFlagBits where
showsPrec = enumShowsPrec enumPrefixDescriptorPoolCreateFlagBits
showTableDescriptorPoolCreateFlagBits
conNameDescriptorPoolCreateFlagBits
(\(DescriptorPoolCreateFlagBits x) -> x)
(\x -> showString "0x" . showHex x)
instance Read DescriptorPoolCreateFlagBits where
readPrec = enumReadPrec enumPrefixDescriptorPoolCreateFlagBits
showTableDescriptorPoolCreateFlagBits
conNameDescriptorPoolCreateFlagBits
DescriptorPoolCreateFlagBits
| expipiplus1/vulkan | src/Vulkan/Core10/Enums/DescriptorPoolCreateFlagBits.hs | bsd-3-clause | 4,945 | 1 | 10 | 1,045 | 402 | 251 | 151 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, TupleSections #-}
module GLBackend where
import Control.Applicative
import Control.Monad
import Data.Bitmap
import Data.ByteString.Char8 (ByteString)
import Data.List
import Data.Maybe
import Data.Trie (Trie)
import Foreign
import qualified Data.ByteString.Char8 as SB
import qualified Data.Set as Set
import qualified Data.Trie as T
import qualified Data.Vector.Storable as V
import Graphics.Rendering.OpenGL.Raw.Core32
import GraphicsPipeline
-- compiled pipeline
data GLProgram
= GLProgram
{ glpObject :: GLuint
, glpShaders :: [GLuint]
, glpAttributes :: Trie (GLuint,AttributeType)
, glpUniforms :: Trie (GLint,UniformType)
, glpSamplers :: Trie (GLint,SamplerType,GLenum)
, glpAttributeCount :: GLuint
}
data GLAttribute
= GLAttribute
{ glaType :: AttributeType
, glaSize :: GLsizei -- ^ attribute vector length
, glaObject :: GLuint
}
data GLPrimitive
= GLPoints
| GLTriangleStrip
| GLTriangles
| GLTriangleStripI GLsizei GLuint -- ^ index buffer size, index buffer ID
| GLTrianglesI GLsizei GLuint
data GLMesh = GLMesh [(GLAttribute,ByteString)] GLPrimitive
class GLTexture2D t where
glTexture2DObject :: t -> GLuint
data GLDepthTexture2D = GLDepthTexture2D GLuint
data GLStencilTexture = GLStencilTexture
data GLColorTexture2D = GLColorTexture2D GLuint
data GLFramebuffer = GLFramebuffer GLuint GLint
instance GLTexture2D GLColorTexture2D where
glTexture2DObject (GLColorTexture2D to) = to
instance GLTexture2D GLDepthTexture2D where
glTexture2DObject (GLDepthTexture2D to) = to
{-
-- shader
uint CreateShader( enum type );
void ShaderSource( uint shader, sizei count, const char**string,const int*length);
void CompileShader( uint shader );
void DeleteShader( uint shader );
void GetShaderiv( uint shader, enum pname, int *params );
- pname:
SHADER_TYPE
VERTEX_SHADER
GEOMETRY_SHADER
FRAGMENT_SHADER
DELETE_STATUS
TRUE
FALSE
COMPILE_STATUS
TRUE
FALSE
INFO_LOG_LENGTH
SHADER_SOURCE_LENGTH
void GetShaderInfoLog( uint shader, sizei bufSize, sizei *length, char *infoLog );
-- program
uint CreateProgram( void );
void AttachShader( uint program, uint shader );
void DetachShader( uint program, uint shader );
void LinkProgram( uint program );
void GetProgramiv( uint program, enum pname, int *params );
- pname:
DELETE_STATUS
TRUE
FALSE
LINK_STATUS
TRUE
FALSE
VALIDATE_STATUS
TRUE
FALSE
INFO_LOG_LENGTH
ATTACHED_SHADERS
ACTIVE_ATTRIBUTES
ACTIVE_ATTRIBUTE_MAX_LENGTH
ACTIVE_UNIFORMS
ACTIVE_UNIFORM_MAX_LENGTH
TRANSFORM_FEEDBACK_BUFFER_MODE
SEPARATE_ATTRIBS
INTERLEAVED_ATTRIBS
TRANSFORM_FEEDBACK_VARYINGS
TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH
ACTIVE_UNIFORM_BLOCKS
ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH
GEOMETRY_VERTICES_OUT
GEOMETRY_INPUT_TYPE
POINTS
LINES
LINES_ADJACENCY
TRIANGLES
TRIANGLES_ADJACENCY
GEOMETRY_OUTPUT_TYPE
POINTS
LINE_STRIP
TRIANGLE_STRIP
void ValidateProgram( uint program );
void GetProgramInfoLog( uint program, sizei bufSize, sizei *length, char *infoLog );
void UseProgram( uint program );
void DeleteProgram( uint program );
-- vertex attributes
-- queries:
void GetActiveAttrib( uint program, uint index, sizei bufSize, sizei *length, int *size, enum *type, char *name );
int GetAttribLocation( uint program, const char *name );
-- setup:
void BindAttribLocation( uint program, uint index, const char *name );
-- uniform variables
int GetUniformLocation( uint program, const char *name );
uint GetUniformBlockIndex( uint program, const char *uniformBlockName );
void GetActiveUniformBlockName( uint program, uint uniformBlockIndex, sizei bufSize, sizei *length, char *uniformBlockName );
void GetActiveUniformBlockiv( uint program, uint uniformBlockIndex, enum pname, int *params );
- pname
UNIFORM_BLOCK_BINDING
UNIFORM_BLOCK_DATA_SIZE
UNIFORM_BLOCK_NAME_LENGTH
UNIFORM_BLOCK_ACTIVE_UNIFORMS
UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES
UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER
UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER
UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER
void GetUniformIndices( uint program, sizeiuniformCount,const char**uniformNames, uint *uniformIndices );
void GetActiveUniformName( uint program, uint uniformIndex, sizei bufSize, sizei *length, char *uniformName );
void GetActiveUniform( uint program, uint index, sizei bufSize, sizei *length, int *size, enum *type, char *name );
void GetActiveUniformsiv( uint program, sizeiuniformCount,const uint*uniformIndices, enum pname, int *params );
- pname
UNIFORM_TYPE
UNIFORM_SIZE
UNIFORM_NAME_LENGTH
UNIFORM_BLOCK_INDEX
UNIFORM_OFFSET
UNIFORM_ARRAY_STRIDE
UNIFORM_MATRIX_STRIDE
UNIFORM_IS_ROW_MAJOR
void Uniform{1234}{if}( int location, T value );
void Uniform{1234}{if}v( int location, sizei count, const T value );
void Uniform{1234}ui( int location, T value );
void Uniform{1234}uiv( int location, sizei count, const T value );
void UniformMatrix{234}fv( int location, sizei count, booleantranspose,const float*value);
void UniformMatrix{2x3,3x2,2x4,4x2,3x4,4x3}fv( int location, sizei count, boolean transpose, const float *value );
-- uniform blocks
void UniformBlockBinding( uint program, uint uniformBlockIndex, uint uniformBlockBinding );
-- transform feedback
void TransformFeedbackVaryings( uint program, sizeicount,const char**varyings,enumbufferMode);
void GetTransformFeedbackVarying( uint program, uint index, sizei bufSize, sizei *length, sizei *size, enum *type, char *name );
-}
printShaderLog :: GLuint -> IO ()
printShaderLog o = do
i <- glGetShaderiv1 gl_INFO_LOG_LENGTH o
allocaArray (fromIntegral i) $ \ps -> glGetShaderInfoLog o (fromIntegral i) nullPtr ps >> SB.packCString (castPtr ps) >>= SB.putStr
compileShader' :: GLuint -> [ByteString] -> IO ()
compileShader' o srcl = withMany SB.useAsCString srcl $ \l -> withArray l $ \p -> do
glShaderSource o (fromIntegral $ length srcl) (castPtr p) nullPtr
glCompileShader o
printShaderLog o
glGetShaderiv1 :: GLenum -> GLuint -> IO GLint
glGetShaderiv1 pname o = alloca $ \pi -> glGetShaderiv o pname pi >> peek pi
glGetProgramiv1 :: GLenum -> GLuint -> IO GLint
glGetProgramiv1 pname o = alloca $ \pi -> glGetProgramiv o pname pi >> peek pi
printProgramLog :: GLuint -> IO ()
printProgramLog o = do
i <- glGetProgramiv1 gl_INFO_LOG_LENGTH o
allocaArray (fromIntegral i) $ \ps -> glGetProgramInfoLog o (fromIntegral i) nullPtr ps >> SB.packCString (castPtr ps) >>= SB.putStr
finalizeProgram :: GLProgram -> IO ()
finalizeProgram (GLProgram po l _ _ _ _) = glDeleteProgram po >> mapM_ glDeleteShader l
compileProgram' :: Program -> IO (Maybe GLProgram)
compileProgram' p = do
po <- glCreateProgram
let createAndAttach f t
| null $ f p = return Nothing
| otherwise = do
o <- glCreateShader t
compileShader o $ f p
glAttachShader po o
return $ Just o
vs <- createAndAttach vertexShader gl_VERTEX_SHADER
gs <- createAndAttach geometryShader gl_GEOMETRY_SHADER
fs <- createAndAttach fragmentShader gl_FRAGMENT_SHADER
glLinkProgram po
printProgramLog po
validateAndCreateGLProgram p po $ catMaybes [vs,gs,fs]
validateAndCreateGLProgram :: Program -> GLuint -> [GLuint] -> IO (Maybe GLProgram)
validateAndCreateGLProgram p po ol = do
shstatus <- mapM (glGetShaderiv1 gl_COMPILE_STATUS) ol
pstatus <- glGetProgramiv1 gl_LINK_STATUS po
let failed = glDeleteProgram po >> mapM_ glDeleteShader ol >> return Nothing
if any (/= fromIntegral gl_TRUE) (pstatus:shstatus) then failed else do
(sl,ul) <- filterSamplers <$> getNameTypeSize po glGetActiveUniform glGetUniformLocation gl_ACTIVE_UNIFORMS gl_ACTIVE_UNIFORM_MAX_LENGTH
al <- getNameTypeSize po glGetActiveAttrib glGetAttribLocation gl_ACTIVE_ATTRIBUTES gl_ACTIVE_ATTRIBUTE_MAX_LENGTH
let ul' = [(n,(i,t)) | (n,i,e,s) <- ul, Just t <- [fromGLUniformType (e,s)]]
al' = [(n,(fromIntegral i,t)) | (n,i,e,s) <- al, Just t <- [fromGLAttributeType (e,s)]]
sl' = [(n,(i,t,tex)) | ((n,i,e,s),tex) <- zip sl [0..], Just t <- [fromGLSamplerType (e,s)]]
lal = length al
lul = length ul
lsl = length sl
okL = Set.size sA' == lal && Set.size sU' == lul && Set.size sS' == lsl
sA = Set.fromList $ attributes p
sA' = Set.fromList [(n,t) | (n,(_,t)) <- al']
sU = Set.fromList $ uniforms p
sU' = Set.fromList [(n,t) | (n,(_,t)) <- ul']
sS = Set.fromList $ samplers p
sS' = Set.fromList [(n,t) | (n,(_,t,_)) <- sl']
if sA == sA' && sU == sU' && sS == sS' && okL then return $ Just $ GLProgram po ol (T.fromList al') (T.fromList ul') (T.fromList sl') (fromIntegral lal) else do
SB.putStrLn "[E] program validation failed:"
SB.putStr " * missing attributes: " >> print (sA' Set.\\ sA)
SB.putStr " * unbinded attributes: " >> print (sA Set.\\ sA')
SB.putStr " * missing uniforms: " >> print (sU' Set.\\ sU)
SB.putStr " * unbinded uniforms: " >> print (sU Set.\\ sU')
SB.putStr " * missing samplers: " >> print (sS' Set.\\ sS)
SB.putStr " * unbinded samplers: " >> print (sS Set.\\ sS')
failed
getNameTypeSize' :: GLuint -> (GLuint -> GLuint -> GLsizei -> Ptr GLsizei -> Ptr GLint -> Ptr GLenum -> Ptr GLchar -> IO ())
-> (GLuint -> Ptr GLchar -> IO GLint) -> GLenum -> GLenum -> IO [(ByteString,GLint,GLenum,GLint)]
getNameTypeSize' o f g enum enumLen = do
nameLen <- glGetProgramiv1 enumLen o
allocaArray (fromIntegral nameLen) $ \namep -> alloca $ \sizep -> alloca $ \typep -> do
n <- glGetProgramiv1 enum o
forM [0..n-1] $ \i -> f o (fromIntegral i) (fromIntegral nameLen) nullPtr sizep typep namep >>
(,,,) <$> SB.packCString (castPtr namep) <*> g o namep <*> peek typep <*> peek sizep
filterSamplers :: [(ByteString,GLint,GLenum,GLint)] -> ([(ByteString,GLint,GLenum,GLint)],[(ByteString,GLint,GLenum,GLint)])
filterSamplers l = partition (\(_,_,e,_) -> elem e samplerTypes) l
where
samplerTypes = [gl_SAMPLER_2D]
fromGLSamplerType :: (GLenum,GLint) -> Maybe SamplerType
fromGLSamplerType (t,1)
| t == gl_SAMPLER_2D = Just ST_Sampler2D
| otherwise = Nothing
fromGLSamplerType _ = Nothing
fromGLUniformType :: (GLenum,GLint) -> Maybe UniformType
fromGLUniformType (t,1)
| t == gl_FLOAT = Just UT_Float
| t == gl_FLOAT_VEC2 = Just UT_Vec2
| t == gl_FLOAT_VEC3 = Just UT_Vec3
| t == gl_FLOAT_VEC4 = Just UT_Vec4
| t == gl_FLOAT_MAT2 = Just UT_Mat2
| t == gl_FLOAT_MAT3 = Just UT_Mat3
| t == gl_FLOAT_MAT4 = Just UT_Mat4
| t == gl_INT = Just UT_Int
| t == gl_UNSIGNED_INT = Just UT_Word
| t == gl_BOOL = Just UT_Bool
| otherwise = Nothing
fromGLUniformType _ = Nothing
fromGLAttributeType :: (GLenum,GLint) -> Maybe AttributeType
fromGLAttributeType (t,1)
| t == gl_FLOAT = Just AT_Float
| t == gl_FLOAT_VEC2 = Just AT_Vec2
| t == gl_FLOAT_VEC3 = Just AT_Vec3
| t == gl_FLOAT_VEC4 = Just AT_Vec4
| t == gl_FLOAT_MAT2 = Just AT_Mat2
| t == gl_FLOAT_MAT3 = Just AT_Mat3
| t == gl_FLOAT_MAT4 = Just AT_Mat4
| t == gl_INT = Just AT_Int
| t == gl_UNSIGNED_INT = Just AT_Word
| otherwise = Nothing
fromGLAttributeType _ = Nothing
uploadVector' :: Storable a => GLenum -> V.Vector a -> IO GLuint
uploadVector' t v = withForeignPtr fp $ \p -> do
bo <- alloca $ \pbo -> glGenBuffers 1 pbo >> peek pbo
glBindBuffer t bo
glBufferData t (fromIntegral len) (plusPtr p offset) gl_STATIC_DRAW
glBindBuffer t 0
return bo
where
s = sizeOf $ v `V.unsafeIndex` 0
(fp,o,l) = V.unsafeToForeignPtr v
offset = o * s
len = l * s
uploadVectorArray' :: Storable a => V.Vector a -> IO GLuint
uploadVectorArray' v = uploadVector gl_ARRAY_BUFFER v
attrSize :: Storable a => V.Vector a -> GLsizei
attrSize = fromIntegral . V.length
compileAttribute' :: Attribute -> IO GLAttribute
compileAttribute' (A_Float v) = GLAttribute AT_Float (attrSize v) <$> uploadVectorArray v
compileAttribute' (A_Vec2 v) = GLAttribute AT_Vec2 (attrSize v) <$> uploadVectorArray v
compileAttribute' (A_Vec3 v) = GLAttribute AT_Vec3 (attrSize v) <$> uploadVectorArray v
compileAttribute' (A_Vec4 v) = GLAttribute AT_Vec4 (attrSize v) <$> uploadVectorArray v
compileAttribute' (A_Mat2 v) = GLAttribute AT_Mat2 (attrSize v) <$> uploadVectorArray v
compileAttribute' (A_Mat3 v) = GLAttribute AT_Mat3 (attrSize v) <$> uploadVectorArray v
compileAttribute' (A_Mat4 v) = GLAttribute AT_Mat4 (attrSize v) <$> uploadVectorArray v
compileAttribute' (A_Int v) = GLAttribute AT_Int (attrSize v) <$> uploadVectorArray v
compileAttribute' (A_Word v) = GLAttribute AT_Word (attrSize v) <$> uploadVectorArray v
finalizeAttribute :: GLAttribute -> IO ()
finalizeAttribute a = with (glaObject a) (glDeleteBuffers 1)
uploadVectorElement' :: V.Vector Int -> IO GLuint
uploadVectorElement' v = uploadVector gl_ELEMENT_ARRAY_BUFFER $ V.map (fromIntegral :: Int -> Int32) v
compilePrimitive' :: Primitive -> IO GLPrimitive
compilePrimitive' Points = return GLPoints
compilePrimitive' TriangleStrip = return GLTriangleStrip
compilePrimitive' Triangles = return GLTriangles
compilePrimitive' (TriangleStripI v) = GLTriangleStripI (fromIntegral $ V.length v) <$> uploadVectorElement v
compilePrimitive' (TrianglesI v) = GLTrianglesI (fromIntegral $ V.length v) <$> uploadVectorElement v
{-
void Uniform{1234}{if}( int location, T value );
void Uniform{1234}{if}v( int location, sizei count, const T value );
void Uniform{1234}ui( int location, T value );
void Uniform{1234}uiv( int location, sizei count, const T value );
void UniformMatrix{234}fv( int location, sizei count, boolean transpose, const float *value);
void UniformMatrix{2x3,3x2,2x4,4x2,3x4,4x3}fv( int location, sizei count, boolean transpose, const float *value );
-}
setUniform' :: GLProgram -> ByteString -> Uniform -> IO Bool
setUniform' p name (U_Float d) = checkUniform name p UT_Float $ \i -> with d $ \p -> glUniform1fv i 1 $ castPtr p
setUniform' p name (U_Vec2 d) = checkUniform name p UT_Vec2 $ \i -> with d $ \p -> glUniform2fv i 1 $ castPtr p
setUniform' p name (U_Vec3 d) = checkUniform name p UT_Vec3 $ \i -> with d $ \p -> glUniform3fv i 1 $ castPtr p
setUniform' p name (U_Vec4 d) = checkUniform name p UT_Vec4 $ \i -> with d $ \p -> glUniform4fv i 1 $ castPtr p
setUniform' p name (U_Int d) = checkUniform name p UT_Int $ \i -> with d $ \p -> glUniform1iv i 1 $ castPtr p
setUniform' p name (U_Word d) = checkUniform name p UT_Word $ \i -> with d $ \p -> glUniform1uiv i 1 $ castPtr p
setUniform' p name (U_Bool d) = checkUniform name p UT_Bool $ \i -> glUniform1ui i (if d then 1 else 0)
setUniform' p name (U_Mat2 d) = checkUniform name p UT_Mat2 $ \i -> with d $ \p -> glUniformMatrix2fv i 1 (fromIntegral gl_TRUE) $ castPtr p
setUniform' p name (U_Mat3 d) = checkUniform name p UT_Mat3 $ \i -> with d $ \p -> glUniformMatrix3fv i 1 (fromIntegral gl_TRUE) $ castPtr p
setUniform' p name (U_Mat4 d) = checkUniform name p UT_Mat4 $ \i -> with d $ \p -> glUniformMatrix4fv i 1 (fromIntegral gl_TRUE) $ castPtr p
--setUniform _ _ _ = return False
checkUniform' :: ByteString -> GLProgram -> UniformType -> (GLint -> IO ()) -> IO Bool
checkUniform' name p t f = case T.lookup name $ glpUniforms p of
Nothing -> return False
Just (i,t') -> if t /= t' then return False else f (fromIntegral i) >> return True
setSampler' :: GLTexture2D t => GLProgram -> ByteString -> t -> IO Bool
setSampler' p name t = checkSampler name p ST_Sampler2D $ \i tc -> do
glUniform1i i (fromIntegral tc)
glActiveTexture $ gl_TEXTURE0 + tc
glBindTexture gl_TEXTURE_2D $ glTexture2DObject t
checkSampler' :: ByteString -> GLProgram -> SamplerType -> (GLint -> GLenum -> IO ()) -> IO Bool
checkSampler' name p t f = case T.lookup name $ glpSamplers p of
Nothing -> return False
Just (i,t',tc) -> if t /= t' then return False else f (fromIntegral i) tc >> return True
{-
-- buffer objects
void GenBuffers( sizei n, uint *buffers );
void DeleteBuffers( sizei n, const uint *buffers );
void BindBuffer( enum target, uint buffer );
- target
ARRAY_BUFFER
COPY_READ_BUFFER
COPY_WRITE_BUFFER
ELEMENT_ARRAY_BUFFER
PIXEL_PACK_BUFFER
PIXEL_UNPACK_BUFFER
TEXTURE_BUFFER
TRANSFORM_FEEDBACK_BUFFER
UNIFORM_BUFFER
void BindBufferRange( enum target, uint index, uint buffer, intptr offset, sizeiptr size );
void BindBufferBase( enum target, uint index, uint buffer );
- target
TRANSFORM_FEEDBACK_BUFFER
UNIFORM_BUFFER
void BufferData( enum target, sizeiptr size, const void *data, enum usage );
- usage
STREAM_DRAW
STREAM_READ
STREAM_COPY
STATIC_DRAW
STATIC_READ
STATIC_COPY
DYNAMIC_DRAW
DYNAMIC_READ
DYNAMIC_COPY
void BufferSubData( enum target, intptr offset, sizeiptrsize,const void*data);
void *MapBufferRange( enum target, intptr offset, sizeiptr length, bitfield access );
- access
MAP_READ_BIT
MAP_WRITE_BIT
MAP_INVALIDATE_RANGE_BIT
void *MapBuffer( enum target, enum access );
void FlushMappedBufferRange( enum target, intptr offset, sizeiptr length );
boolean UnmapBuffer( enum target );
void *CopyBufferSubData( enum readtarget, enum writetarget, intptr readoffset, intptr writeoffset, sizeiptr size );
-- vertex array objects
void GenVertexArrays( sizei n, uint *arrays );
void DeleteVertexArrays( sizei n, const uint *arrays );
void BindVertexArray( uint array );
-}
{-
-- generic attributes
void VertexAttrib{1234}{sfd}( uint index, T values );
void VertexAttrib{123}{sfd}v( uint index, const T values );
void VertexAttrib4{bsifd ub us ui}v( uint index, const T values );
void VertexAttrib4Nub( uint index, T values );
void VertexAttrib4N{bsi ub us ui}v( uint index, const T values );
void VertexAttribI{1234}{i ui}( uint index, T values );
void VertexAttribI{1234}{i ui}v( uint index, const T values );
void VertexAttribI4{bs ubus}v( uint index, const T values );
void VertexAttribP{1234}ui(uint index,enum type,boolean normalized,uint value);
void VertexAttribP{1234}uiv(uint index,enum type,boolean normalized,const uint *value);
-- vertex arrays
void VertexAttribPointer( uint index, int size, enum type, boolean normalized, sizei stride, const void *pointer );
void VertexAttribIPointer( uint index, int size, enum type, sizei stride, const void *pointer);
void EnableVertexAttribArray( uint index );
void DisableVertexAttribArray( uint index );
void VertexAttribDivisor( uint index, uint divisor );
-}
setAttribute' :: GLProgram -> GLAttribute -> ByteString -> IO Bool
setAttribute' p (GLAttribute a _ bo) name
| a == AT_Float = setFloat 1
| a == AT_Vec2 = setFloat 2
| a == AT_Vec3 = setFloat 3
| a == AT_Vec4 = setFloat 4
| a == AT_Mat2 = setFloat 4
| a == AT_Mat3 = setFloat 9
| a == AT_Mat4 = setFloat 16
| a == AT_Int = setInt 1 gl_INT
| a == AT_Word = setInt 1 gl_UNSIGNED_INT
| otherwise = return False
where
setFloat n = check $ \i -> glVertexAttribPointer i n gl_FLOAT (fromIntegral gl_FALSE) 0 nullPtr
setInt n t = check $ \i -> glVertexAttribIPointer i n t 0 nullPtr
check f = case T.lookup name $ glpAttributes p of
Nothing -> return False
Just (i,t) -> if a /= t then return False else do
glBindBuffer gl_ARRAY_BUFFER bo
glEnableVertexAttribArray i
f i
glBindBuffer gl_ARRAY_BUFFER 0
return True
withGLProgram' :: GLProgram -> IO a -> IO a
withGLProgram' p f = do
glUseProgram (glpObject p)
a <- f
--glValidateProgram (glpObject p)
--printProgramLog (glpObject p)
glUseProgram 0
return a
withGLAttributes' :: GLProgram -> [(GLAttribute,ByteString)] -> IO () -> IO Bool
withGLAttributes' p al f = do
ok <- and <$> mapM (uncurry $ setAttribute p) al
when ok f
forM_ [0..glpAttributeCount p-1] glDisableVertexAttribArray
return ok
{-
helper: void DrawArraysOneInstance( enum mode, int first, sizei count, int instance );
void DrawArrays( enum mode, int first, sizei count );
void DrawArraysInstanced( enum mode, int first, sizei count, sizei primcount );
void MultiDrawArrays( enum mode, const int *first, const sizei *count, sizei primcount);
helper: void DrawElementsOneInstance( enum mode, sizei count, enum type, const void *indices);
void DrawElements( enum mode, sizei count, enum type, const void*indices);
void DrawElementsInstanced( enum mode, sizei count, enum type, const void *indices, sizei primcount);
void MultiDrawElements( enum mode, const sizei *count, enum type, const void **indices, sizei primcount );
void DrawRangeElements( enum mode, uint start, uint end, sizei count, enum type, const void *indices );
void DrawElementsBaseVertex( enum mode, sizei count, enum type, const void *indices, int basevertex);
void DrawRangeElementsBaseVertex( enum mode, uint start, uint end, sizei count, enum type, const void *indices, int basevertex );
void DrawElementsInstancedBaseVertex( enum mode, sizei count, enum type, const void *indices, sizei primcount, int basevertex );
void MultiDrawElementsBaseVertex( enum mode, const sizei *count, enum type, const void **indices, sizei primcount, const int *basevertex);
-}
renderGLPrimitive' :: GLPrimitive -> GLsizei -> IO ()
renderGLPrimitive' GLPoints s = glDrawArrays gl_POINTS 0 s
renderGLPrimitive' GLTriangleStrip s = glDrawArrays gl_TRIANGLE_STRIP 0 s
renderGLPrimitive' GLTriangles s = glDrawArrays gl_TRIANGLES 0 s
renderGLPrimitive' (GLTriangleStripI s bo) _ = glBindBuffer gl_ELEMENT_ARRAY_BUFFER bo >> glDrawElements gl_TRIANGLE_STRIP s gl_UNSIGNED_INT nullPtr
renderGLPrimitive' (GLTrianglesI s bo) _ = glBindBuffer gl_ELEMENT_ARRAY_BUFFER bo >> glDrawElements gl_TRIANGLES s gl_UNSIGNED_INT nullPtr
-- mesh utility functions
compileMesh' :: Mesh -> IO GLMesh
compileMesh' (Mesh al p) = GLMesh <$> mapM (\(n,a) -> (,n) <$> compileAttribute a) al <*> compilePrimitive p
renderGLMeshD :: GLProgram -> GLMesh -> IO Bool
renderGLMeshD p m = renderGLMesh' p m $ return True
-- this is for setting up uniforms in action
renderGLMesh'D :: GLProgram -> GLMesh -> IO Bool -> IO Bool
renderGLMesh'D p (GLMesh al pr) setup = withGLProgram p $ do
ok <- setup
if not ok then return False else
withGLAttributes p [a | a@(_,name) <- al, hasAttr name] $ renderGLPrimitive pr s
where
s = glaSize $ fst $ head al
hasAttr n = T.member n (glpAttributes p)
clearGLFramebuffer :: IO ()
clearGLFramebuffer = do
glClearColor 0 0 0 1
glClear $ fromIntegral (gl_COLOR_BUFFER_BIT .|. gl_DEPTH_BUFFER_BIT)
-- texturing
{-
TEXTURE_1D
TEXTURE_2D
TEXTURE_3D
TEXTURE_1D_ARRAY
TEXTURE_2D_ARRAY
TEXTURE_RECTANGLE
TEXTURE_BUFFER
TEXTURE_CUBE_MAP
TEXTURE_2D_MULTISAMPLE
TEXTURE_2D_MULTISAMPLE_ARRAY
-}
{-
void SamplerParameter{if}v( uint sampler, enum pname, T param );
void SamplerParameterI{u ui}v( uint sampler, enum pname, T *params );
- pname:
TEXTURE_WRAP_S
TEXTURE_WRAP_T
TEXTURE_WRAP_R
TEXTURE_MIN_FILTER
TEXTURE_MAG_FILTER
TEXTURE_BORDER_COLOR
TEXTURE_MIN_LOD
TEXTURE_MAX_LOD
TEXTURE_LOD_BIAS
TEXTURE_COMPARE_MODE
TEXTURE_COMPARE_FUNC
-}
uploadTexture2D' :: Size -> GLenum -> GLenum -> Ptr a -> IO GLuint
uploadTexture2D' (w,h) intf f ptr = do
glBindBuffer gl_ARRAY_BUFFER 0
glBindBuffer gl_ELEMENT_ARRAY_BUFFER 0
to <- alloca $ \pto -> glGenTextures 1 pto >> peek pto
glBindTexture gl_TEXTURE_2D to
--glPixelStorei gl_UNPACK_ALIGNMENT padding
-- UNPACK_ROW_LENGTH and UNPACK_ALIGNMENT
glTexParameteri gl_TEXTURE_2D gl_TEXTURE_BASE_LEVEL 0
glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MAX_LEVEL 0
glTexImage2D gl_TEXTURE_2D 0 (fromIntegral intf) (fromIntegral w) (fromIntegral h) 0 f gl_UNSIGNED_BYTE ptr
glBindTexture gl_TEXTURE_2D 0
return to
compileColorTexture2D' :: Bitmap Word8 -> IO GLColorTexture2D
compileColorTexture2D' b = withBitmap b $ \size 3 _padding ptr -> GLColorTexture2D <$> uploadTexture2D size gl_RGBA32F gl_RGB ptr
newGLDepthTexture2D' :: Size -> IO GLDepthTexture2D
newGLDepthTexture2D' size = GLDepthTexture2D <$> uploadTexture2D size gl_DEPTH_COMPONENT32F gl_DEPTH_COMPONENT nullPtr
{-
COLOR_ATTACHMENT0
DEPTH_ATTACHMENT.
STENCIL_ATTACHMENT.
MAX_COLOR_ATTACHMENTS
-}
glGetIntegerv1 :: GLenum -> IO GLint
glGetIntegerv1 e = alloca $ \pi -> glGetIntegerv e pi >> peek pi
newGLFramebuffer :: IO GLFramebuffer
newGLFramebuffer = GLFramebuffer <$> (alloca $ \pto -> glGenFramebuffers 1 pto >> peek pto) <*> glGetIntegerv1 gl_MAX_COLOR_ATTACHMENTS
withFramebuffer' :: GLFramebuffer -> Maybe GLDepthTexture2D -> Maybe GLStencilTexture -> [GLColorTexture2D] -> IO Bool -> IO Bool
withFramebuffer' (GLFramebuffer fbo maxcolor) mdt Nothing cl a = if length cl > fromIntegral maxcolor then return False else do
glBindFramebuffer gl_DRAW_FRAMEBUFFER fbo
forM_ (zip [0 :: Int ..] cl) $ \(i,(GLColorTexture2D to)) ->
glFramebufferTexture2D gl_DRAW_FRAMEBUFFER (gl_COLOR_ATTACHMENT0 + fromIntegral i) gl_TEXTURE_2D to 0
-- disable unused
forM_ [(fromIntegral $ length cl)..maxcolor-1] $ \i ->
glFramebufferTexture2D gl_DRAW_FRAMEBUFFER (gl_COLOR_ATTACHMENT0 + fromIntegral i) gl_TEXTURE_2D 0 0
let dto = case mdt of
Nothing -> 0
Just (GLDepthTexture2D to) -> to
glFramebufferTexture2D gl_DRAW_FRAMEBUFFER gl_DEPTH_STENCIL_ATTACHMENT gl_TEXTURE_2D 0 0
glFramebufferTexture2D gl_DRAW_FRAMEBUFFER gl_DEPTH_ATTACHMENT gl_TEXTURE_2D dto 0
glFramebufferTexture2D gl_DRAW_FRAMEBUFFER gl_STENCIL_ATTACHMENT gl_TEXTURE_2D 0 0
e <- glCheckFramebufferStatus gl_DRAW_FRAMEBUFFER
b <- if e == gl_FRAMEBUFFER_COMPLETE then a else case e of
0 -> checkGL >>= SB.putStrLn >> return False
_ -> SB.putStrLn "Framebuffer is not complete" >> return False
glBindFramebuffer gl_DRAW_FRAMEBUFFER 0
return b
withDepth' :: IO a -> IO a
withDepth' a = do glEnable gl_DEPTH_TEST ; r <- a ; glDisable gl_DEPTH_TEST ; return r
{-
-- constraints
MAX_3D_TEXTURE_SIZE
MAX_ARRAY_TEXTURE_LAYERS
MAX_COLOR_ATTACHMENTS
MAX_COLOR_TEXTURE_SAMPLES
MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS
MAX_COMBINED_TEXTURE_IMAGE_UNITS
MAX_COMBINED_UNIFORM_BLOCKS
MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS
MAX_CUBE_MAP_TEXTURE_SIZE
MAX_DEPTH_TEXTURE_SAMPLES
MAX_DRAW_BUFFERS
MAX_DUAL_SOURCE_DRAW_BUFFERS
MAX_ELEMENTS_INDICES
MAX_ELEMENTS_VERTICES
MAX_FRAGMENT_INPUT_COMPONENTS
MAX_FRAGMENT_UNIFORM_BLOCKS
MAX_FRAGMENT_UNIFORM_COMPONENTS
MAX_GEOMETRY_INPUT_COMPONENTS
MAX_GEOMETRY_OUTPUT_COMPONENTS
MAX_GEOMETRY_OUTPUT_VERTICES
MAX_GEOMETRY_TEXTURE_IMAGE_UNITS
MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS
MAX_GEOMETRY_UNIFORM_BLOCKS
MAX_GEOMETRY_UNIFORM_COMPONENTS
MAX_INTEGER_SAMPLES
MAX_PROGRAM_TEXEL_OFFSET
MAX_RECTANGLE_TEXTURE_SIZE
MAX_RENDERBUFFER_SIZE
MAX_SAMPLES
MAX_SAMPLE_MASK_WORDS
MAX_SERVER_WAIT_TIMEOUT
MAX_TEXTURE_BUFFER_SIZE
MAX_TEXTURE_IMAGE_UNITS
MAX_TEXTURE_LOD_BIAS
MAX_TEXTURE_SIZE
MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS
MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS
MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS
MAX_UNIFORM_BLOCK_SIZE
MAX_UNIFORM_BUFFER_BINDINGS
MAX_VARYING_COMPONENTS
MAX_VERTEX_ATTRIBS
MAX_VERTEX_OUTPUT_COMPONENTS
MAX_VERTEX_TEXTURE_IMAGE_UNITS
MAX_VERTEX_UNIFORM_BLOCKS
MAX_VERTEX_UNIFORM_COMPONENTS
MAX_VIEWPORT_DIMS
-}
glDebug :: IO ()
glDebug = do
putStr "gl_MAX_DRAW_BUFFERS: "
print =<< glGetIntegerv1 gl_MAX_DRAW_BUFFERS
-- putStr "gl_MAX_DUAL_SOURCE_DRAW_BUFFERS"
-- print =<< glGetIntegerv1 gl_MAX_DUAL_SOURCE_DRAW_BUFFERS
printGLVersion :: IO ()
printGLVersion = glDebug >> getString gl_VERSION >>= SB.putStrLn
getString :: GLenum -> IO ByteString
getString n = glGetString n >>= maybeNullPtr (return "") (SB.packCString . castPtr)
where
maybeNullPtr :: b -> (Ptr a -> b) -> Ptr a -> b
maybeNullPtr n f ptr | ptr == nullPtr = n
| otherwise = f ptr
-----------------
-- debug code
-----------------
checkGL :: IO ByteString
checkGL = do
let f e | e == gl_INVALID_ENUM = "INVALID_ENUM"
| e == gl_INVALID_VALUE = "INVALID_VALUE"
| e == gl_INVALID_OPERATION = "INVALID_OPERATION"
| e == gl_INVALID_FRAMEBUFFER_OPERATION = "INVALID_FRAMEBUFFER_OPERATION"
| e == gl_OUT_OF_MEMORY = "OUT_OF_MEMORY"
| e == gl_NO_ERROR = "OK"
| otherwise = "Unknown error"
e <- glGetError
return $ f e
st :: ByteString -> IO ()
st n = do
s <- checkGL
unless (s == "OK") $ do
SB.putStr n
SB.putStr " "
SB.putStrLn s
renderGLMesh' :: GLProgram -> GLMesh -> IO Bool -> IO Bool
renderGLMesh' p m a = do
st "BEGIN[renderGLMesh']"
r <- renderGLMesh'D p m a
st "END[renderGLMesh']"
return r
renderGLMesh :: GLProgram -> GLMesh -> IO Bool
renderGLMesh p m = do
st "BEGIN[renderGLMesh]"
r <- renderGLMeshD p m
st "END[renderGLMesh]"
return r
compileMesh :: Mesh -> IO GLMesh
compileMesh m = do
st "BEGIN[compileMesh]"
r <- compileMesh' m
st "END[compileMesh]"
return r
renderGLPrimitive :: GLPrimitive -> GLsizei -> IO ()
renderGLPrimitive p s = do
st "BEGIN[renderGLPrimitive]"
r <- renderGLPrimitive' p s
st "END[renderGLPrimitive]"
return r
withGLAttributes :: GLProgram -> [(GLAttribute,ByteString)] -> IO () -> IO Bool
withGLAttributes p l a = do
st "BEGIN[withGLAttributes]"
r <- withGLAttributes' p l a
st "END[withGLAttributes]"
return r
withGLProgram :: GLProgram -> IO a -> IO a
withGLProgram p a = do
st "BEGIN[withGLProgram]"
r <- withGLProgram' p a
st "END[withGLProgram]"
return r
setAttribute :: GLProgram -> GLAttribute -> ByteString -> IO Bool
setAttribute p l a = do
st "BEGIN[setAttribute]"
r <- setAttribute' p l a
st "END[setAttribute]"
return r
checkUniform :: ByteString -> GLProgram -> UniformType -> (GLint -> IO ()) -> IO Bool
checkUniform n p t a = do
st "BEGIN[checkUniform]"
r <- checkUniform' n p t a
st "END[checkUniform]"
return r
setUniform :: GLProgram -> ByteString -> Uniform -> IO Bool
setUniform p n u = do
st "BEGIN[setUniform]"
r <- setUniform' p n u
st "END[setUniform]"
return r
checkSampler :: ByteString -> GLProgram -> SamplerType -> (GLint -> GLenum -> IO ()) -> IO Bool
checkSampler n p t a = do
st "BEGIN[checkSampler]"
r <- checkSampler' n p t a
st "END[checkSampler]"
return r
setSampler :: GLTexture2D t => GLProgram -> ByteString -> t -> IO Bool
setSampler p n u = do
st "BEGIN[setSampler]"
r <- setSampler' p n u
st "END[setSampler]"
return r
compileColorTexture2D :: Bitmap Word8 -> IO GLColorTexture2D
compileColorTexture2D b = do
st "BEGIN[compileColorTexture2D]"
r <- compileColorTexture2D' b
st "END[compileColorTexture2D]"
return r
compilePrimitive :: Primitive -> IO GLPrimitive
compilePrimitive p = do
st "BEGIN[compilePrimitive]"
r <- compilePrimitive' p
st "END[compilePrimitive]"
return r
uploadVectorElement :: V.Vector Int -> IO GLuint
uploadVectorElement v = do
st "BEGIN[uploadVectorElement]"
r <- uploadVectorElement' v
st "END[uploadVectorElement]"
return r
compileAttribute :: Attribute -> IO GLAttribute
compileAttribute a = do
st "BEGIN[compileAttribute]"
r <- compileAttribute' a
st "END[compileAttribute]"
return r
uploadVectorArray :: Storable a => V.Vector a -> IO GLuint
uploadVectorArray v = do
st "BEGIN[uploadVectorArray]"
r <- uploadVectorArray' v
st "END[uploadVectorArray]"
return r
uploadVector :: Storable a => GLenum -> V.Vector a -> IO GLuint
uploadVector e v = do
st "BEGIN[uploadVector]"
r <- uploadVector' e v
st "END[uploadVector]"
return r
getNameTypeSize :: GLuint -> (GLuint -> GLuint -> GLsizei -> Ptr GLsizei -> Ptr GLint -> Ptr GLenum -> Ptr GLchar -> IO ())
-> (GLuint -> Ptr GLchar -> IO GLint) -> GLenum -> GLenum -> IO [(ByteString,GLint,GLenum,GLint)]
getNameTypeSize a b c d e = do
st "BEGIN[getNameTypeSize]"
r <- getNameTypeSize' a b c d e
st "END[getNameTypeSize]"
return r
compileProgram :: Program -> IO (Maybe GLProgram)
compileProgram p = do
st "BEGIN[compileProgram]"
r <- compileProgram' p
st "END[compileProgram]"
return r
compileShader :: GLuint -> [ByteString] -> IO ()
compileShader a b = do
st "BEGIN[compileShader]"
r <- compileShader' a b
st "END[compileShader]"
return r
withFramebuffer :: GLFramebuffer -> Maybe GLDepthTexture2D -> Maybe GLStencilTexture -> [GLColorTexture2D] -> IO Bool -> IO Bool
withFramebuffer a b c d e = do
st "BEGIN[withFramebuffer]"
r <- withFramebuffer' a b c d e
st "END[withFramebuffer]"
return r
uploadTexture2D :: Size -> GLenum -> GLenum -> Ptr a -> IO GLuint
uploadTexture2D a b c d = do
st "BEGIN[uploadTexture2D]"
r <- uploadTexture2D' a b c d
st "END[uploadTexture2D]"
return r
newGLDepthTexture2D :: Size -> IO GLDepthTexture2D
newGLDepthTexture2D a = do
st "BEGIN[newGLDepthTexture2D]"
r <- newGLDepthTexture2D' a
st "END[newGLDepthTexture2D]"
return r
withDepth :: IO a -> IO a
withDepth a = do
st "BEGIN[withDepth]"
r <- withDepth' a
st "END[withDepth]"
return r
| csabahruska/GFXDemo | GLBackend.hs | bsd-3-clause | 34,530 | 0 | 24 | 7,433 | 8,135 | 3,905 | 4,230 | 482 | 5 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE NamedFieldPuns #-}
module PackageSets.Types where
import Data.Data
import Data.List
import Data.Maybe
import System.Process
import Path
data PackageSet
= PackageSet {
cabalConfig :: [(String, String)]
}
| StackageConfigFile {
cabalConfigUrl :: String,
packages :: [String]
}
| CustomPackageSet {
cabalConfigFile :: String
}
deriving (Show, Eq, Typeable, Data)
packageNames :: PackageSet -> [String]
packageNames PackageSet{cabalConfig} = map fst cabalConfig
packageNames (StackageConfigFile _ names) = names
packageNames (CustomPackageSet cabalConfig)
| Just comment <- listToMaybe (lines cabalConfig)
, "--" `isPrefixOf` comment
= words (drop 2 comment)
packageNames (CustomPackageSet _) = []
writeCabalConfig :: Path Sandbox -> PackageSet -> IO ()
writeCabalConfig sandboxDir (PackageSet cabalConfig) = do
writeFile (toPath $ getCabalConfig sandboxDir) $ unlines $
"constraints:" :
map (\ (package, version) -> " " ++ package ++ " == " ++ version)
cabalConfig
writeCabalConfig sandboxDir (StackageConfigFile url _) = do
callCommand ("wget '" ++ url ++ "' -O " ++ toPath (getCabalConfig sandboxDir))
writeCabalConfig sandboxDir (CustomPackageSet content) = do
writeFile (toPath $ getCabalConfig sandboxDir) content
| soenkehahn/runstaskell | src/PackageSets/Types.hs | bsd-3-clause | 1,384 | 0 | 13 | 286 | 403 | 211 | 192 | 35 | 1 |
module Utils (showEnum, lookupEnum, normalize, parseNum) where
import Debug.Trace
import Data.Default
import qualified Data.List as L
import qualified Data.Char as C
import qualified Data.Text as T
showEnum :: (Show a, Enum a) => a -> String
showEnum = (map C.toLower) . show
isParen :: Char -> Bool
isParen c = c == '(' || c == ')'
dropParens :: String -> String
dropParens = filter (not . isParen)
lookupEnum :: (Default a, Enum a) => [String] -> String -> a
lookupEnum haystack needle =
case L.elemIndex (dropParens needle) haystack of
Just r -> toEnum r
Nothing -> trace ("Not in enum:" ++ needle) def
normalize :: T.Text -> String
normalize = T.unpack . T.toLower . T.strip
-- TODO: -> throw on unreadable
parseNum :: (Read a, Num a) => String -> a
parseNum x =
let x' = dropParens x in
(read x') * (if length x - length x' == 2 then -1 else 1)
| ostronom/pokerstars-audit | src/Utils.hs | bsd-3-clause | 873 | 0 | 12 | 179 | 348 | 189 | 159 | 23 | 2 |
{-# LANGUAGE FlexibleContexts #-}
module Network.Orchid.Core.Handler
( FileStoreType (..)
, hRepository
, hViewer
, hWiki
, hWikiCustomViewer
)
where
import Control.Applicative
import Control.Monad.Trans
import Data.FileStore hiding (NotFound)
import Network.Orchid.Core.Format
import Network.Orchid.Core.Liaison
import Network.Orchid.FormatRegister
import Network.Protocol.Http
import Network.Protocol.Uri
import Network.Salvia.Handler.ExtendedFileSystem
import Network.Salvia.Handlers
import Network.Salvia.Httpd
import Paths_orchid
data FileStoreType = Git | Darcs
mkFileStore :: FileStoreType -> FilePath -> FileStore
mkFileStore Git = gitFileStore
mkFileStore Darcs = darcsFileStore
-- todo: clean up this mess:
hRepository
:: (BodyM Request m, HttpM' m, MonadIO m, SendM m, LoginM m p)
=> FileStoreType -> FilePath -> FilePath -> m ()
hRepository kind repo dir =
let fs = mkFileStore kind repo in
hPath "/search" (post (hWikiSearch fs))
$ hPrefix "/_images" (hFileSystem (repo /+ "_images"))
$ hPrefix "/_cache" (hFileSystem (repo /+ "_cache"))
$ hFileTypeDispatcher
hDirectoryResource
(\_ -> hWithoutDir repo (hWikiREST dir fs))
repo
hViewer
:: (MonadIO m, HttpM' m, SendM m, QueueM m, BodyM Request m, Alternative m)
=> FilePath -> m ()
hViewer dir =
hPath "/"
(hFileResource (dir /+ "show.html"))
(hExtendedFileSystem dir)
hWiki
:: (MonadIO m, BodyM Request m, LoginM m p, Alternative m, QueueM m, SendM m, HttpM' m)
=> FileStoreType -> FilePath -> FilePath -> m ()
hWiki kind repo dir = do
viewerDir <- liftIO (getDataFileName "viewer")
hWikiCustomViewer viewerDir kind repo dir
hWikiCustomViewer
:: (LoginM m p, Alternative m, QueueM m, SendM m, MonadIO m, HttpM' m, BodyM Request m)
=> FilePath -> FileStoreType -> FilePath -> FilePath -> m ()
hWikiCustomViewer viewerDir kind repo dir =
hPrefix "/data"
(hRepository kind repo dir)
(authHandlers (hViewer viewerDir))
authHandlers :: (LoginM m p, HttpM' m, SendM m) => m () -> m ()
authHandlers =
hPathRouter
[ ("/loginfo", authorized (Just "loginfo") forbidden (const loginfo))
, ("/login", post (login forbidden (const ok)))
, ("/logout", post logout)
, ("/signup", post (signup ["loginfo", "show", "edit", "create"] forbidden (const ok)))
]
ok :: (HttpM Response m, SendM m) => m ()
ok = hCustomError OK "ok"
post :: (HttpM Response m, SendM m, HttpM Request m) => m () -> m ()
post h = hMethod POST h (hError NotFound)
forbidden :: (HttpM Response m, SendM m) => m ()
forbidden = hCustomError Forbidden "No authorized to perform this action"
hWikiREST
:: (HttpM' m, BodyM Request m, SendM m, MonadIO m, LoginM m p)
=> FilePath -> FileStore -> m ()
hWikiREST dir fs =
hUri $ \u ->
previewHandlers u
. actionHandlers u
$ hError BadRequest
where
previewHandlers u = hPathRouter
$ map (\ext -> ("/preview." ++ ext, hWikiRetrieve fs dir True u))
(map postfix wikiFormats)
actionHandlers u =
hMethodRouter [
(GET, hWikiRetrieve fs dir False u )
, (PUT, authorized (Just "edit") forbidden (\user -> hWikiStore fs user u))
, (DELETE, authorized (Just "delete") forbidden (\user -> hWikiDeleteOrRename fs user u))
]
| sebastiaanvisser/orchid | src/Network/Orchid/Core/Handler.hs | bsd-3-clause | 3,325 | 0 | 14 | 710 | 1,187 | 623 | 564 | 84 | 1 |
module Assets
(
module Assets.Internal,
addAnimation,
getAnimation
) where
import Environment
import Assets.Internal
import Animation
import Data.Map as Map
import Control.Lens
import Control.Monad.IO.Class
import Control.Monad.Trans
import Control.Monad.Reader.Class
addAnimation :: String -> Animation -> MainMonad ()
addAnimation animationName animation =
assets.animations %= insert animationName animation
getAnimation :: (MonadReader a m, AssetsReader a) => String -> m (Maybe Animation)
getAnimation animationName = do
assets' <- query getAssets
return $ Map.lookup animationName (assets'^.animations)
| alexisVallet/haskell-shmup | Assets.hs | bsd-3-clause | 661 | 0 | 10 | 122 | 174 | 96 | 78 | -1 | -1 |
module ZMQHS (module X) where
import ZMQHS.Connection as X
import ZMQHS.Message as X
import ZMQHS.ConnSpec as X
import ZMQHS.Async as X
import ZMQHS.Application as X
import ZMQHS.Frame as X | xrl/zmqhs | ZMQHS.hs | bsd-3-clause | 189 | 0 | 4 | 28 | 52 | 37 | 15 | 7 | 0 |
module Render.Element.Write where
import Data.Char ( isLower )
import Data.List ( lookup )
import Data.List.Extra ( groupOn
, nubOrd
, nubOrdOn
)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Set ( unions )
import Data.Text as T
import Data.Text.IO as T
import Prettyprinter
import Prettyprinter.Render.Text
import qualified Data.Vector.Extra as V
import Data.Vector.Extra ( Vector )
import Foreign.Ptr
import Language.Haskell.Brittany
import Language.Haskell.Brittany.Internal.Config.Types
import Language.Haskell.TH ( mkName
, nameBase
, nameModule
)
import Polysemy
import Polysemy.Input
import Relude hiding ( Handle
, State
, modify'
, runState
)
import System.Directory
import System.FilePath
import qualified Data.Vector.Generic as VG
import Type.Reflection
import Control.Exception ( IOException )
import Control.Exception.Base ( catch )
import Documentation
import Documentation.Haddock
import Error
import Haskell.Name
import qualified Prelude
import Render.Element
import Render.Names
import Render.SpecInfo
import Render.Utils
import Spec.Types
import Write.Segment
----------------------------------------------------------------
-- Rendering
----------------------------------------------------------------
renderSegments
:: forall r
. ( HasErr r
, MemberWithError (Embed IO) r
, HasSpecInfo r
, HasTypeInfo r
, HasRenderedNames r
, HasRenderParams r
)
=> (Documentee -> Maybe Documentation)
-> FilePath
-> [Segment ModName RenderElement]
-> Sem r ()
renderSegments getDoc out segments = do
let exportMap :: Map.Map HName (Export, ModName)
exportMap = Map.fromList
[ (n, (e, m))
| Segment m rs <- segments
, r <- toList rs
, e <- toList (reExports r)
, n <- exportName e : (exportName <$> V.toList (exportWith e))
]
findLocalModule :: HName -> Maybe ModName
findLocalModule n = snd <$> Map.lookup n exportMap
findModule :: Name -> Maybe ModName
findModule n = ModName . T.pack <$> nameModule n
--
-- Boot module handling
-- TODO, move this checking elsewhere
--
allBootSegments :: [Segment ModName RenderElement]
allBootSegments =
Relude.filter (\(Segment _ es) -> not (V.null es))
$ segments
<&> \(Segment m es) -> Segment m (V.mapMaybe reBoot es)
findBootElems :: HName -> Sem r (ModName, RenderElement)
findBootElems =
let bootElemMap :: Map HName (ModName, RenderElement)
bootElemMap = Map.fromList
[ (n, (m, re))
| Segment m res <- allBootSegments
, re <- toList res
, e <- toList (reExports re)
, n <- exportName e : (exportName <$> V.toList (exportWith e))
]
in \n ->
note @r ("Unable to find boot element for " <> show n)
$ Map.lookup n bootElemMap
sourceImportNames = nubOrd
[ n
| Segment _ res <- segments
, re <- toList res
, Import { importName = n, importSource = True } <- toList
(reLocalImports re <> maybe mempty reLocalImports (reBoot re))
]
-- TODO: do this segmentation properly, nubbing here is nasty
requiredBootElements <-
nubOrdOn (reExports . snd) <$> forV sourceImportNames findBootElems
let requiredBootSegments =
fmap (\((m, re) : res) -> Segment m (fromList (re : (snd <$> res))))
. groupOn fst
. sortOn fst
$ requiredBootElements
--
-- Write the files
--
traverseV_ (renderModule out False getDoc findModule findLocalModule) segments
traverseV_ (renderModule out True getDoc findModule findLocalModule)
requiredBootSegments
renderModule
:: ( MemberWithError (Embed IO) r
, HasErr r
, HasSpecInfo r
, HasTypeInfo r
, HasRenderedNames r
, HasRenderParams r
)
=> FilePath
-- ^ out directory
-> Bool
-- ^ Is a boot file
-> (Documentee -> Maybe Documentation)
-> (Name -> Maybe ModName)
-> (HName -> Maybe ModName)
-> Segment ModName RenderElement
-> Sem r ()
renderModule out boot getDoc findModule findLocalModule (Segment modName unsortedElements)
= do
let exportsType = V.any (isTyConName . exportName) . reExports
es = fromList . sortOn exportsType . toList $ unsortedElements
RenderParams {..} <- input
let
ext = bool ".hs" ".hs-boot" boot
f =
toString
(out <> "/" <> T.unpack (T.replace "." "/" (unModName modName) <> ext)
)
openImports = vsep
( fmap (\(ModName n) -> "import" <+> pretty n)
. Set.toList
. Set.unions
$ (reReexportedModules <$> V.toList es)
)
declaredNames = V.concatMap
(\RenderElement {..} -> allExports (reExports <> reInternal))
es
importFilter =
Relude.filter (\(Import n _ _ _ _) -> n `V.notElem` declaredNames)
findModule' n =
note ("Unable to find module for " <> show n) (findModule n)
findLocalModule' n =
note ("Unable to find local module for " <> show n) (findLocalModule n)
imports <- vsep <$> traverseV
(renderImport findModule' (T.pack . nameBase) thNameNamespace id)
( mapMaybe
(\i -> do
n <- if V.null (importChildren i)
then fixOddImport (importName i)
else Just (importName i)
pure i { importName = n }
)
. Relude.toList
. unions
$ (reImports <$> V.toList es)
)
let
exportToImport (Export name withAll with _) =
Import name False mempty (withAll || not (V.null with)) False
allReexportImports =
fmap exportToImport
. Relude.toList
. unions
. fmap reReexportedNames
. V.toList
$ es
allLocalImports =
Relude.toList . unions . fmap reLocalImports . V.toList $ es
resolveAlias <- getResolveAlias
parentedImports <- traverse adoptConstructors
(allLocalImports <> allReexportImports)
localImports <- vsep <$> traverseV
(renderImport findLocalModule' unName nameNameSpace resolveAlias)
(importFilter parentedImports)
let
locate :: CName -> DocumenteeLocation
locate n =
let names = case n of
CName "" -> []
CName n' | isLower (T.head n') -> [mkFunName n]
_ -> [mkTyName n, mkFunName n, mkPatternName n]
in case asum ((\n -> (n, ) <$> findLocalModule n) <$> names) of
Just (n, m) | m == modName -> ThisModule n
Just (n, m) -> OtherModule m n
Nothing -> Unknown
getDocumentation :: Documentee -> Doc ()
getDocumentation target = case getDoc target of
Nothing -> "-- No documentation found for" <+> viaShow target
Just d -> case documentationToHaddock externalDocHTML locate d of
Left e ->
"-- Error getting documentation for"
<+> viaShow target
<> ":"
<+> viaShow e
Right (Haddock t) -> commentNoWrap t
allReexportedModules =
V.fromList
. Set.toList
. Set.unions
. fmap reReexportedModules
. toList
$ es
exports = V.concatMap reExports es
reexports = V.concatMap
(\re -> V.fromList
( (\(Export name withAll with reexportable) ->
Export name (withAll || not (V.null with)) mempty reexportable
)
<$> toList (reReexportedNames re)
)
)
es
languageExtensions =
let allExts =
Set.toList
. Set.insert (LanguageExtension "CPP")
. Set.unions
. toList
. fmap reExtensions
$ es
in [ "{-# language" <+> pretty e <+> "#-}" | e <- allExts ]
moduleChapter (ModName m) =
let lastComponent = Prelude.last (T.splitOn "." m)
in Chapter lastComponent
moduleDocumentation = getDocumentation (moduleChapter modName)
layoutDoc = renderStrict
. layoutPretty defaultLayoutOptions { layoutPageWidth = Unbounded }
headerContents = vsep
[ vsep languageExtensions
, moduleDocumentation
, "module"
<+> pretty modName
<> indent
2
( parenList
$ (fmap exportDoc . nubOrdOnV exportName $ (exports <> reexports)
)
<> ( (\(ModName m) -> renderExport Module m mempty)
<$> allReexportedModules
)
)
<+> "where"
, openImports
, imports
, localImports
]
layoutContent e = runMaybeT $ do
d <- maybe mzero pure $ reDoc e getDocumentation
let t = layoutDoc (d <> line <> line)
if getAll (reCanFormat e)
then liftIO (parsePrintModule brittanyConfig t) >>= \case
Left err ->
error
$ "Fail: Brittany failed to handle module:\n"
<> T.intercalate "\n" (fmap (T.pack . showBError) err)
<> "\n\n\n"
<> t
where
showBError = \case
ErrorInput x -> "ErrorInput " <> x
ErrorUnusedComment x -> "ErrorUnusedComent " <> x
ErrorMacroConfig x y -> "ErrorMacroConfig " <> x <> " " <> y
LayoutWarning x -> "LayoutWarning " <> x
ErrorUnknownNode x _ -> "ErrorUnknownNode " <> x <> " <<>>"
ErrorOutputCheck -> "ErrorOutputCheck"
Right f -> pure f
else pure t
contentsTexts <- mapMaybeM layoutContent (V.toList es)
let moduleText =
T.intercalate "\n" (layoutDoc headerContents : contentsTexts)
liftIO $ createDirectoryIfMissing True (takeDirectory f)
writeIfChanged f moduleText
allExports :: Vector Export -> Vector HName
allExports =
V.concatMap (\Export {..} -> exportName `V.cons` allExports exportWith)
-- | If we are importing constructors of a type alias, resolve the alias and
-- import the constructors with the resolved name.
renderImport
:: (HasErr r, HasSpecInfo r, Eq a)
=> (a -> Sem r ModName)
-> (a -> Text)
-> (a -> NameSpace)
-> (a -> a)
-> Import a
-> Sem r (Doc ())
renderImport findModule getName getNameSpace resolveAlias i =
let resolved = resolveAlias (importName i)
importsNoChildren = V.null (importChildren i) && not (importWithAll i)
in if importsNoChildren || resolved == importName i
then renderImport' findModule getName getNameSpace i
else do
a <- renderImport'
findModule
getName
getNameSpace
i { importWithAll = False, importChildren = mempty }
c <- renderImport' findModule
getName
getNameSpace
i { importName = resolved }
pure $ vsep [a, c]
renderImport'
:: (HasErr r, HasSpecInfo r, Eq a)
=> (a -> Sem r ModName)
-> (a -> Text)
-> (a -> NameSpace)
-> Import a
-> Sem r (Doc ())
renderImport' findModule getName getNameSpace (Import n qual children withAll source)
= do
ModName mod' <- findModule n
let sourceDoc = bool "" " {-# SOURCE #-}" source
qualDoc = bool "" " qualified" qual
base = getName n
ns = getNameSpace n
baseP = wrapSymbol ns base
spec = nameSpacePrefix ns
childrenDoc = if V.null children && not withAll
then ""
else parenList
( (wrapSymbol (getNameSpace n) . getName <$> children)
<> (if withAll then V.singleton ".." else V.empty)
)
when (T.null mod') $ throw "Trying to render an import with no module!"
pure $ "import" <> sourceDoc <> qualDoc <+> pretty mod' <+> parenList
(V.singleton (spec <> baseP <> childrenDoc))
fixOddImport :: Name -> Maybe Name
fixOddImport n = fromMaybe (Just n) (lookup n fixes)
where
fixes =
[ -- Prelude types
(''Maybe , Nothing)
, (''Word , Nothing)
, (''() , Nothing)
, (''IO , Nothing)
, (''Integral , Nothing)
, (''Eq , Nothing)
, (''Float , Nothing)
, (''Double , Nothing)
, (''Int , Nothing)
, (''Bool , Nothing)
,
-- Base
(''Int8 , Just (mkName "Data.Int.Int8"))
, (''Int16 , Just (mkName "Data.Int.Int16"))
, (''Int32 , Just (mkName "Data.Int.Int32"))
, (''Int64 , Just (mkName "Data.Int.Int64"))
, (''Word8 , Just (mkName "Data.Word.Word8"))
, (''Word16 , Just (mkName "Data.Word.Word16"))
, (''Word32 , Just (mkName "Data.Word.Word32"))
, (''Word64 , Just (mkName "Data.Word.Word64"))
, (''Ptr , Just (mkName "Foreign.Ptr.Ptr"))
, (''FunPtr , Just (mkName "Foreign.Ptr.FunPtr"))
, ('nullPtr , Just (mkName "Foreign.Ptr.nullPtr"))
, ('castFunPtr, Just (mkName "Foreign.Ptr.castFunPtr"))
, ('plusPtr , Just (mkName "Foreign.Ptr.plusPtr"))
, (''Type , Just (mkName "Data.Kind.Type"))
, (''Nat , Just (mkName "GHC.TypeNats.Nat"))
, (''Constraint, Just (mkName "Data.Kind.Constraint"))
, (''Typeable, Just (mkName "Data.Typeable.Typeable"))
, ('typeRep, Just (mkName "Type.Reflection.typeRep"))
, (''TypeRep, Just (mkName "Type.Reflection.TypeRep"))
, ('coerce , Just (mkName "Data.Coerce.coerce"))
,
-- Other
(''ByteString, Just (mkName "Data.ByteString.ByteString"))
, (''VG.Vector, Just (mkName "Data.Vector.Generic.Vector"))
]
----------------------------------------------------------------
--
----------------------------------------------------------------
newtype TypeInfo = TypeInfo
{ tiConMap :: HName -> Maybe HName
}
type HasTypeInfo r = MemberWithError (Input TypeInfo) r
withTypeInfo
:: HasRenderParams r => Spec t -> Sem (Input TypeInfo ': r) a -> Sem r a
withTypeInfo spec a = do
ti <- specTypeInfo spec
runInputConst ti a
specTypeInfo :: HasRenderParams r => Spec t -> Sem r TypeInfo
specTypeInfo Spec {..} = do
RenderParams {..} <- input
let tyMap :: Map HName HName
tyMap = Map.fromList
[ (mkConName eExportedName evName, mkTyName eExportedName)
| Enum {..} <- V.toList specEnums
, let eExportedName = case eType of
AnEnum -> eName
ABitmask flags _ -> flags
, EnumValue {..} <- V.toList eValues
]
pure $ TypeInfo (`Map.lookup` tyMap)
adoptConstructors :: HasTypeInfo r => Import HName -> Sem r (Import HName)
adoptConstructors = \case
i@(Import n q cs _ source) -> getConParent n <&> \case
Just p -> Import p q (V.singleton n <> cs) False source
Nothing -> i
where getConParent n = inputs (`tiConMap` n)
----------------------------------------------------------------
--
----------------------------------------------------------------
nubOrdOnV :: Ord b => (a -> b) -> Vector a -> Vector a
nubOrdOnV p = fromList . nubOrdOn p . toList
writeIfChanged :: MonadIO m => FilePath -> Text -> m ()
writeIfChanged f t' = liftIO $ do
t <- readFileMaybe f
when (t /= Just t') $ T.writeFile f t'
readFileMaybe :: FilePath -> IO (Maybe Text)
readFileMaybe f =
(Just <$> T.readFile f) `catch` (\(_ :: IOException) -> pure Nothing)
brittanyConfig :: CConfig Identity
brittanyConfig = staticDefaultConfig
{ _conf_preprocessor = PreProcessorConfig (pure (pure CPPModeNowarn))
(pure (pure True))
, _conf_layout = (_conf_layout staticDefaultConfig)
{ _lconfig_cols = pure (pure 120)
}
, _conf_forward = ForwardOptions (pure [])
-- ^ TODO: put language exts here
}
| expipiplus1/vulkan | generate-new/src/Render/Element/Write.hs | bsd-3-clause | 17,216 | 0 | 26 | 6,096 | 4,810 | 2,479 | 2,331 | -1 | -1 |
module Wham.AnalyzeRunner(
run,
ControlPointMap,
ConfigurationSet) where
import Wham.SignExc
import Wham.SignBoolExc
import Wham.InterpreterTypes
import Wham.Interpreter
import Wham.AMDefinitions hiding ((==), (+))
import qualified Data.Set as Set
import qualified Data.Map as Map
type AbstractConfiguration = (Configuration SignExc SignBoolExc)
type ConfigurationSet = Set.Set AbstractConfiguration
type ControlPointMap =
Map.Map Integer ConfigurationSet
type ConfigurationQueue = Map.Map Integer [AbstractConfiguration]
run :: ConfigurationQueue -> ControlPointMap ->
Either String ControlPointMap
run queue cpm
| empty queue = Right cpm
| otherwise = case astep queue cpm of
Right (confs, queue') -> run queue' (cpm' confs)
Left err -> Left err
where
cp = cpToExec queue
Just cs = Map.lookup cp queue
c = head cs
cpm' confs = foldl (insert c) cpm confs
insert :: AbstractConfiguration -> ControlPointMap ->
AbstractConfiguration -> ControlPointMap
insert _ m c@((STORE _ cp):_, _, _) = insertImpl cp c m
insert _ m c@((BRANCH _ _ cp):_,_,_) = insertImpl cp c m
insert _ m c@((TRY _ _ cp):_, _, _) = insertImpl cp c m
insert ((ANALYZE cp):_, _, _) m c = insertImpl cp c m
insert _ m c@((NOOP cp):_, _, _) = insertImpl cp c m
insert _ m _ = m
insertImpl :: Integer -> AbstractConfiguration -> ControlPointMap ->
ControlPointMap
insertImpl cp c m = case Map.lookup cp m of
Nothing -> Map.insert cp (Set.singleton c) m
Just set -> Map.insert cp (Set.insert c set) m
empty :: ConfigurationQueue -> Bool
empty q = Map.null q
astep :: ConfigurationQueue -> ControlPointMap ->
Either String ([AbstractConfiguration], ConfigurationQueue)
astep queue cps = case istep queue of
Right (queue', set) -> Right (Set.toList set, increase queue' set)
Left err -> Left err
where
increase q set = foldl (\acc c -> update acc c cps) q $ Set.toList set
update :: ConfigurationQueue -> AbstractConfiguration ->
ControlPointMap -> ConfigurationQueue
update q c cps =
case mcp of
Nothing -> q
Just cp -> case Map.lookup cp cps of
Just set -> case Set.member c set of
True -> q
False -> q' cp
Nothing -> q' cp
where
mcp = getCP c
q' cp = case Map.lookup cp q of
Just confs -> Map.insert cp (c:confs) q
Nothing -> Map.insert cp [c] q
getCP :: AbstractConfiguration -> Maybe Integer
getCP ([], _, _) = Nothing
getCP ((PUSH _ cp):_, _, _) = Just cp
getCP ((FETCH _ cp):_, _, _) = Just cp
getCP ((STORE _ cp):_, _, _) = Just cp
getCP ((BRANCH _ _ cp):_, _, _) = Just cp
getCP ((LOOP _ _ cp):_, _, _) = Just cp
getCP ((TRY _ _ cp):_, _, _) = Just cp
getCP ((CATCH _ cp):_, _, _) = Just cp
getCP ((NOOP cp):_, _, _) = Just cp
getCP ((TRUE cp):_, _, _) = Just cp
getCP ((FALSE cp):_, _, _) = Just cp
getCP ((ADD cp):_, _, _) = Just cp
getCP ((SUB cp):_, _, _) = Just cp
getCP ((MULT cp):_, _, _) = Just cp
getCP ((DIV cp):_, _, _) = Just cp
getCP ((NEG cp):_, _, _) = Just cp
getCP ((EQUAL cp):_, _, _) = Just cp
getCP ((LE cp):_, _, _) = Just cp
getCP ((AND cp):_, _, _) = Just cp
getCP ((ANALYZE cp):_, _, _) = Just cp
cpToExec :: ConfigurationQueue -> Integer
cpToExec q = cp
where
keys = Map.keys q
cp = foldl min (head keys) keys
istep :: ConfigurationQueue ->
Either String (ConfigurationQueue, ConfigurationSet)
istep queue = case Map.lookup cp queue of
Just conf -> case step $ head conf of
Right confs -> Right (adjust cp queue, confs)
Left err -> Left err
Nothing -> Left $ "Could not find any configuratuion for control point " ++
(show cp)
where
cp = cpToExec queue
adjust :: Integer -> ConfigurationQueue -> ConfigurationQueue
adjust cp q = case Map.lookup cp q of
Just confs -> if length confs == 1
then Map.delete cp q
else Map.insert cp (tail confs) q
Nothing -> q
| helino/wham | src/Wham/AnalyzeRunner.hs | bsd-3-clause | 4,233 | 0 | 14 | 1,232 | 1,816 | 938 | 878 | 102 | 5 |
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Config.Kde
-- Description : Config for integrating xmonad with KDE.
-- Copyright : (c) Spencer Janssen <spencerjanssen@gmail.com>
-- License : BSD
--
-- Maintainer : Spencer Janssen <spencerjanssen@gmail.com>
-- Stability : unstable
-- Portability : unportable
--
-- This module provides a config suitable for use with the KDE desktop
-- environment.
module XMonad.Config.Kde (
-- * Usage
-- $usage
kdeConfig,
kde4Config,
desktopLayoutModifiers
) where
import XMonad
import XMonad.Config.Desktop
import qualified Data.Map as M
-- $usage
-- To use this module, start with the following @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad
-- > import XMonad.Config.Kde
-- >
-- > main = xmonad kdeConfig
--
-- For KDE 4, replace 'kdeConfig' with 'kde4Config'
--
-- For examples of how to further customize @kdeConfig@ see "XMonad.Config.Desktop".
kdeConfig = desktopConfig
{ terminal = "konsole"
, keys = kdeKeys <+> keys desktopConfig }
kde4Config = desktopConfig
{ terminal = "konsole"
, keys = kde4Keys <+> keys desktopConfig }
kdeKeys XConfig{modMask = modm} = M.fromList
[ ((modm, xK_p), spawn "dcop kdesktop default popupExecuteCommand")
, ((modm .|. shiftMask, xK_q), spawn "dcop kdesktop default logout")
]
kde4Keys XConfig{modMask = modm} = M.fromList
[ ((modm, xK_p), spawn "krunner")
, ((modm .|. shiftMask, xK_q), spawn "dbus-send --print-reply --dest=org.kde.ksmserver /KSMServer org.kde.KSMServerInterface.logout int32:1 int32:0 int32:1")
]
| xmonad/xmonad-contrib | XMonad/Config/Kde.hs | bsd-3-clause | 1,731 | 0 | 9 | 348 | 238 | 151 | 87 | 20 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Lazy as B hiding (putStrLn)
import qualified Data.ByteString.Lazy.Char8 as B (putStrLn)
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.Encoding as E
import Data.Monoid ((<>))
import Control.Monad (when, forM_)
import System.FilePath ((</>))
import Control.Lens
import Notebook as N
import Utils
import Formats
import Options.Applicative as Opt hiding (command)
langTag :: T.Text -> T.Text
langTag command = if T.toStrict command `safeIndex` 0 == Just '%'
then T.drop 1 (head (T.lines command))
else "scala"
prependCode :: B.ByteString -> N.Notebook -> N.Notebook
prependCode c = over nCommands (codeBlock :)
where codeBlock = C (T.toStrict $ langTag (E.decodeUtf8 c)) (T.toStrict $ dropFirstLine $ E.decodeUtf8 c) Nothing False False
dropFirstLine = T.unlines . tail . T.lines
prependCodes :: B.ByteString -> Either String [(String, N.Notebook)] -> Either String [(String, N.Notebook)]
prependCodes c nList = over (each . _2) (prependCode c) <$> nList
format :: Parser NotebookFormat
format = parseFormat <$> format'
where parseFormat "databricks-json" = databricksJSONFormat
parseFormat "zeppelin" = zeppelinFormat
parseFormat _ = error "Unknown target format"
format' = strOption ( long "format"
<> short 'f'
<> metavar "FORMAT"
<> help "Format of the notebook" )
inputPaths :: Parser [FilePath]
inputPaths = some (Opt.argument str (metavar "INPUT NOTEBOOKS"))
outputPath :: Parser FilePath
outputPath = strOption (long "out" <> short 'o' <> metavar "OUTPUT")
inputCode :: Parser FilePath
inputCode = strOption (long "code" <> short 'c' <> metavar "CODE FILE" <> help "File containing code to prepend")
data Run = Run { inputFormat :: NotebookFormat, codeFile :: FilePath, inputs :: [FilePath], output :: Maybe FilePath }
run :: Parser Run
run = Run <$> format <*> inputCode <*> inputPaths <*> optional outputPath
opts :: ParserInfo Run
opts = info (run <**> helper)
( fullDesc
<> progDesc "Adds the contents of the provided text file as the first cell of the provided notebook." )
main :: IO ()
main = do
(Run (from, to) codefile inputs output) <- execParser opts
inputStreams <- if null inputs
then do stream <- B.getContents
return [("stdin", stream)]
else do streams <- mapM B.readFile inputs
return (zip inputs streams)
code <- B.readFile codefile
let attempt = to <$> concatMapM (prependCodes code . uncurry from) inputStreams
results = either (error . show) id attempt
when (null results) (error "Nothing to output.")
case output of
Nothing -> case results of
[(_, x)] -> B.putStrLn x
_ -> error "Cannot output multiple files to stdout"
Just o -> forM_ results $ \(f, x) -> do
ensureCanBeCreated (o </> f)
B.writeFile (o </> f) x
| TiloWiklund/pinot | src/Adder.hs | bsd-3-clause | 3,077 | 0 | 16 | 746 | 975 | 514 | 461 | 65 | 4 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
module API.Btce (
-- * Feed
feed
-- * Trading Proxies
, session
, BtceSession
, send
, cancelOrders
)
where
---------------------------------------------------------------------------------------------------
import Pipes
---------------------------------------------------------------------------------------------------
import Control.Monad ( (>=>), forM_, mzero, liftM, unless)
---------------------------------------------------------------------------------------------------
import Debug.Trace
import Data.Char ( isDigit )
import Data.List ( isPrefixOf )
import Data.IORef
import Data.Aeson ( (.:) )
import Codec.Digest.SHA ( hmac, Length( SHA512 ) )
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy.Char8 as LC
import qualified Blaze.ByteString.Builder as Builder
import qualified Data.Aeson as A
import Data.BtcExchanges
---------------------------------------------------------------------------------------------------
import Network.Http.Client hiding (put, get)
import Network.HTTP.Base ( urlEncodeVars )
---------------------------------------------------------------------------------------------------
import OpenSSL (withOpenSSL)
---------------------------------------------------------------------------------------------------
import qualified System.IO.Streams as Streams
{-import qualified System.IO.Streams.Debug as D-}
---------------------------------------------------------------------------------------------------
import qualified Data.Btce as B
---------------------------------------------------------------------------------------------------
import API.BtcExchanges.Internal
import qualified Numeric
feed :: CurrencyPair -> Producer BC.ByteString IO ()
feed c = httpFeed "btc-e.com" 443 (BC.pack $ "/api/2/" ++ show c ++ "/depth") 1
newtype BtceSession = BtceSession (B.BtceKey, B.BtceSecret, IORef Int)
newtype JSONResponse = W { unwrap :: Either B.BtceError B.BtceResponse }
instance A.FromJSON JSONResponse where
parseJSON (A.Object v) = do
s <- v .: "success"
if s == (0 :: Int)
then liftM (W . Left) $ v .: "error"
else liftM (W . Right) $ v .: "return"
parseJSON _ = mzero
session :: B.BtceKey -> B.BtceSecret -> IO BtceSession
session k s = do
n <- newIORef 0
let sess = BtceSession (k, s, n)
-- get next nonce parameter and store it in btce session:
-- send dummy request with nonce == 0 then server will reply with an
-- error message and next expected nonce value.
err <- send sess B.GetInfo
unless (isRight' err) $
let nextN = fromLeft' extract err
in maybe (fail $ "can not extract nonce from " ++ fromLeft' Prelude.id err) (writeIORef n) nextN
return sess
where
-- try to extract the next expected nonce parameter from servers error
-- message.
extract :: String -> Maybe Int
extract = go
where
go [] = Nothing
go e' = let expect = "on key:" in
if expect `isPrefixOf` e'
then Just $ read $ takeWhile isDigit $ drop (length expect) e'
else go $ tail e'
isRight' (Left _) = False
isRight' (Right _) = True
fromLeft' f (Left a) = f a
fromLeft' _ (Right _) = fail "fromLeft' on a right value"
send :: BtceSession -> B.BtceRequest -> IO (Either B.BtceError B.BtceResponse)
send s req = let
BtceSession (key, secret, nonce) = s
encodeAndSign' :: Int -> B.BtceRequest -> (BC.ByteString, BC.ByteString)
encodeAndSign' n r =
let b = urlEncodeVars $ ("nonce", show n) : encode' r
s' = BC.pack secret
in (BC.pack b, hmac SHA512 s' $ BC.pack b)
where
encode' B.GetInfo = newReq "getInfo" []
encode' (B.CancelOrder o) = newReq "CancelOrder" [("order_id", show o)]
encode' (B.Trade pa t p v) = newReq "Trade" [pair pa, ttype t, rate p, amount v]
encode' (B.GetActiveOrders pa) = newReq "ActiveOrders" $ maybe [] (aSingle.pair) pa
newReq t ps = ("method", t) : ps
aSingle x = [x]
pair pa = ("pair", show pa)
ttype t = ("type", show t)
rate p = ("rate", showFloat' p)
amount v = ("amount", showFloat' v)
showFloat' f = Numeric.showFFloat Nothing (normalize f) ""
normalize f = (fromInteger . round $ f * (10^8)) / (10.0^8)
#if MIN_VERSION_base(4,6,0)
#else
-- |Strict version of 'modifyIORef'
modifyIORef' :: IORef a -> (a -> a) -> IO ()
modifyIORef' ref f = do
x <- readIORef ref
let x' = f x
x' `seq` writeIORef ref x'
-- |/O(1)/ Convert a strict 'ByteString' into a lazy 'ByteString'.
fromStrict :: BC.ByteString -> LC.ByteString
fromStrict bs | S.null bs = Empty
| otherwise = Chunk bs Empty
#endif
in
withOpenSSL $ do
let btceDomain = "btc-e.com"
btcePort = 443
ctx <- baselineContextSSL
c <- openConnectionSSL ctx btceDomain btcePort
-- get the next nonce parameter
n <- modifyIORef' nonce (+ 1) >> readIORef nonce
let (b, sign) = encodeAndSign' n req
req' <- buildRequest $ do
http POST "/tapi"
setContentType "application/x-www-form-urlencoded"
setHeader "Key" $ BC.pack key
setHeader "Sign" sign
trace (show b) $ sendRequest c req' (Streams.write (Just $ Builder.fromByteString b))
m <- receiveResponse c (\_ i -> Streams.read i)
let extractResponse m' = unwrap =<< A.eitherDecode (LC.fromStrict m')
return $ maybe (Left "no response") extractResponse m
cancelOrders :: BtceSession -> IO ()
cancelOrders s = do
let send' r = fmap (either ignoreNoOrders id) $ send s r
orderID (B.BtceBookEntry o _ _ _ _ _ _) = o
(B.ActiveOrders os) <- send' $ B.GetActiveOrders Nothing
forM_ (map orderID os) $ send s . B.CancelOrder >=> ignoreErrs
where
ignoreErrs _ = return ()
anError e = error $ "Request to Btce failed. Reason: " ++ show e
ignoreNoOrders e = if e == "no orders" then B.ActiveOrders [] else anError e
| RobinKrom/BtcExchanges | src/API/Btce.hs | bsd-3-clause | 6,665 | 0 | 17 | 1,931 | 1,665 | 867 | 798 | -1 | -1 |
module Linear.Constraints.WeightSpec
( weightSpec
) where
import Linear.Constraints.Weights
import Data.Maybe (isNothing)
import qualified Data.Map as Map
import Data.Foldable (toList)
import Test.Tasty
import Test.Tasty.QuickCheck as QC
import Test.Tasty.HUnit
import Test.QuickCheck
weightSpec :: TestTree
weightSpec = testGroup "Linear.Constraints.Weight"
[ testGroup "Addition"
[ QC.testProperty "a + -a = 0" prop_self_add_negate_zero
, QC.testProperty "[a + a + a .. a]_n ~ n `mult` a]" prop_self_add_n_mult
]
, testGroup "Subtraction"
[ QC.testProperty "a - a = 0" prop_self_sub_zero
, QC.testProperty "a = -(-a)" prop_self_double_negation
]
, testGroup "General"
[ QC.testProperty "is Compact" prop_self_no_trailing_zero
]
]
prop_self_add_negate_zero :: Weight Rational -> Bool
prop_self_add_negate_zero xs = xs + (-xs) == 0
prop_self_add_n_mult :: Int -> Weight Rational -> Property
prop_self_add_n_mult n xs = n > 0 ==> sum (replicate n xs) == (fromIntegral n) `multWeight` xs
prop_self_sub_zero :: Weight Rational -> Bool
prop_self_sub_zero xs = xs - xs == 0
prop_self_double_negation :: Weight Rational -> Bool
prop_self_double_negation xs = xs == negate (negate xs)
prop_self_no_trailing_zero :: Weight Rational -> Weight Rational -> Bool
prop_self_no_trailing_zero xs ys =
noZero (toList $ xs + ys) && noZero (toList $ xs - ys)
where
noZero = snd . foldr noZero' ([],True)
noZero' 0 ([],_) = ([0], False)
noZero' x (xs,b) = (x:xs, b)
| athanclark/cassowary-haskell | test/Linear/Constraints/WeightSpec.hs | bsd-3-clause | 1,518 | 0 | 10 | 274 | 452 | 243 | 209 | -1 | -1 |
module Main where
import Control.Monad (when)
import System.Environment (getArgs)
import System.Exit (exitFailure)
import qualified SDL
import qualified SDL.Mixer as Mix
main :: IO ()
main = do
SDL.initialize [SDL.InitAudio]
Mix.withAudio Mix.defaultAudio 256 $ do
putStr "Available music decoders: "
print =<< Mix.musicDecoders
args <- getArgs
case args of
[] -> putStrLn "Usage: cabal run sdl2-mixer-music FILE" >> exitFailure
xs -> runExample $ head xs
SDL.quit
-- | Play the given file as a Music.
runExample :: FilePath -> IO ()
runExample path = do
music <- Mix.load path
print $ Mix.musicType music
Mix.whenMusicFinished $ putStrLn "Music finished playing!"
Mix.playMusic Mix.Once music
delayWhile Mix.playingMusic
Mix.free music
delayWhile :: IO Bool -> IO ()
delayWhile check = loop'
where
loop' = do
still <- check
when still $ SDL.delay 300 >> delayWhile check
| sbidin/sdl2-mixer | examples/Music.hs | bsd-3-clause | 956 | 0 | 14 | 215 | 300 | 144 | 156 | 30 | 2 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverlappingInstances #-}
module Main where
import Data.Maybe
newtype MonadIO m a = MonadIO {returnIO :: m a}
update :: Monad m => MonadIO m a -> MonadIO m ()
update mio = mio {returnIO = return ()}
newtype Thingy m = Thingy {thing :: m ()}
update' :: Monad m => Thingy m -> Thingy m
update' t = t { thing = return () }
thingDef :: Monad m => Thingy m
thingDef = Thingy $ return ()
data Witness a where
IntWitness :: Witness Int
BoolWitness :: Witness Bool
CharWitness :: Witness Char
NullWitness :: Witness a
class MyWitness a where
getWitness :: Witness a
instance MyWitness Char where getWitness = CharWitness
instance MyWitness Int where getWitness = IntWitness
instance MyWitness Bool where getWitness = BoolWitness
instance MyWitness a where getWitness = NullWitness
dCast :: Witness a -> Witness b -> a -> Maybe b
dCast IntWitness IntWitness a = Just a
dCast BoolWitness BoolWitness a = Just a
dCast CharWitness CharWitness a = Just a
dCast _ _ _ = Nothing
addIntList :: MyWitness a => a -> [Int] -> [Int]
addIntList x xs = let b = dCast getWitness IntWitness x
in case b of
Just n -> n:xs
Nothing -> xs
| dterei/Scraps | haskell/GADTCast.hs | bsd-3-clause | 1,313 | 0 | 10 | 348 | 436 | 225 | 211 | 34 | 2 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module ClientSpec (spec) where
import Data.Aeson
import Data.Default (def)
import Test.Hspec
import qualified Network.HTTP.Client as HTTP
import qualified Control.Exception as Exception
import Pact.ApiReq
import Pact.Types.API
import Pact.Types.Command
import Data.Text (Text)
import Pact.Server.API
import Pact.Server.Test
import Servant.Client
import Pact.Types.Runtime
import Pact.Types.PactValue
#if ! MIN_VERSION_servant_client(0,16,0)
type ClientError = ServantError
#endif
_testLogDir, _testConfigFilePath, _testPort, _serverPath :: String
_testLogDir = testDir ++ "test-log/"
_testConfigFilePath = testDir ++ "test-config.yaml"
_testPort = "8080"
_serverPath = "http://localhost:" ++ _testPort
bracket :: IO a -> IO a
bracket action = Exception.bracket
(flushDb >> startServer _testConfigFilePath)
(\a -> stopServer a >> flushDb)
(const action)
simpleServerCmd :: IO (Command Text)
simpleServerCmd = do
simpleKeys <- genKeys
mkExec "(+ 1 2)" Null def [(simpleKeys,[])] Nothing (Just "test1")
simpleServerCmdWithPactErr :: IO (Command Text)
simpleServerCmdWithPactErr = do
simpleKeys <- genKeys
mkExec "(+ 1 2 3)" Null def [(simpleKeys,[])] Nothing (Just "test1")
spec :: Spec
spec = describe "Servant API client tests" $ do
mgr <- runIO $ HTTP.newManager HTTP.defaultManagerSettings
url <- runIO $ parseBaseUrl _serverPath
let clientEnv = mkClientEnv mgr url
-- it "incorrectly runs a simple command privately" $ do
-- cmd <- simpleServerCmd
-- res <- runClientM (private (SubmitBatch [cmd])) clientEnv
-- let expt = Right (ApiFailure "Send private: payload must have address")
-- res `shouldBe` expt
it "correctly runs a simple command locally" $ do
cmd <- simpleServerCmd
res <- bracket $! do
r <- runClientM (localClient cmd) clientEnv
return r
let cmdPactResult = (PactResult . Right . PLiteral . LDecimal) 3
(_crResult <$> res) `shouldBe` (Right cmdPactResult)
it "correctly runs a simple command with pact error locally" $ do
cmd <- simpleServerCmdWithPactErr
res <- bracket $! do
r <- runClientM (localClient cmd) clientEnv
return r
(_crResult <$> res) `shouldSatisfy` (failWith ArgsError)
it "correctly runs a simple command publicly and listens to the result" $ do
cmd <- simpleServerCmd
let rk = cmdToRequestKey cmd
(res,res') <- bracket $! do
!res <- runClientM (sendClient (SubmitBatch [cmd])) clientEnv
!res' <- runClientM (listenClient (ListenerRequest rk)) clientEnv
-- print (res,res')
return (res,res')
res `shouldBe` (Right (RequestKeys [rk]))
let cmdData = (PactResult . Right . PLiteral . LDecimal) 3
case res' of
Left _ -> expectationFailure "client request failed"
Right r -> case r of
ListenTimeout _ -> expectationFailure "timeout"
ListenResponse lr -> _crResult lr `shouldBe` cmdData
it "correctly runs a simple command with pact error publicly and listens to the result" $ do
cmd <- simpleServerCmdWithPactErr
let rk = cmdToRequestKey cmd
(res,res') <- bracket $! do
!res <- runClientM (sendClient (SubmitBatch [cmd])) clientEnv
!res' <- runClientM (listenClient (ListenerRequest rk)) clientEnv
-- print (res,res')
return (res,res')
res `shouldBe` (Right (RequestKeys [rk]))
case res' of
Left _ -> expectationFailure "client request failed"
Right r -> case r of
ListenTimeout _ -> expectationFailure "timeout"
ListenResponse lr -> (Right $ _crResult lr) `shouldSatisfy` (failWith ArgsError)
failWith :: PactErrorType -> Either ClientError PactResult -> Bool
failWith errType res = case res of
Left _ -> False
Right res' -> case res' of
(PactResult (Left (PactError t _ _ _))) -> t == errType
_ -> False
| kadena-io/pact | tests/ClientSpec.hs | bsd-3-clause | 3,969 | 0 | 21 | 801 | 1,112 | 563 | 549 | 90 | 5 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
module Network.UDP.Pal.Reliable.Types where
import Control.Lens
import Data.Binary
import Data.Map.Strict (Map)
import GHC.Generics
import Control.Concurrent.STM
import Data.Time
-- Each packet is tagged with a monotonic sequence number.
-- On each transmission, we send all packets in order, over and over,
-- until we receive acknowledgement of their receipt.
newtype SeqNum = SeqNum { unSeqNum :: Int }
deriving (Eq, Show, Ord, Num, Enum, Binary)
newtype BundleNum = BundleNum { unBundleNum :: Int }
deriving (Eq, Show, Ord, Num, Enum, Binary)
-- These are the packets that are actually serialized over the wire
data WirePacket r = UnreliablePacket !BundleNum !r
| ReliablePacket !SeqNum !r
| ReliablePacketAck !SeqNum
| KeepAlive
deriving (Show, Generic)
instance (Binary r) => Binary (WirePacket r)
-- These are packets submitted to and received from the Transceiver
data AppPacket r = Unreliable ![r] | Reliable !r deriving Show
-- The data necessary to track the retransmission of
-- unacknowledged reliable packets.
data TransceiverState r = TransceiverState
{ _connNextSeqNumTo :: !SeqNum
, _connNextSeqNumFrom :: !SeqNum
, _connNextBundleNum :: !BundleNum
, _connUnacked :: !(Map SeqNum r)
, _connBundles :: !(Map BundleNum [r])
}
makeLenses ''TransceiverState
newTransceiverState :: Binary r => TransceiverState r
newTransceiverState = TransceiverState 0 0 0 mempty mempty
data Transceiver r = Transceiver
{ tcIncomingRawPackets :: TChan (WirePacket r)
, tcVerifiedPackets :: TChan (AppPacket r)
, tcOutgoingPackets :: TChan (AppPacket r)
, tcLastMessageTime :: TVar UTCTime
, tcShutdown :: IO ()
}
| lukexi/udp-pal | src/Network/UDP/Pal/Reliable/Types.hs | bsd-3-clause | 1,987 | 0 | 12 | 514 | 402 | 227 | 175 | 60 | 1 |
{-
Copyright 2010-2012 Cognimeta Inc.
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.
-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Database.Perdure(
module Database.Perdure.Persistent,
module Database.Perdure.Ref,
module Database.Perdure.Deref,
module Database.Perdure.Rev,
module Database.Perdure.SizeRef,
LocalStoreFile,
withFileStoreFile,
ReplicatedFile(..),
newCachedFile,
RootLocation,
defaultRootLocation,
PVar,
openPVar,
createPVar,
updatePVar,
updateInspectPVar
) where
import Prelude()
import Cgm.Prelude
import Database.Perdure.State
import Database.Perdure.Persistent
import Database.Perdure.Ref
import Database.Perdure.Deref
import Database.Perdure.Rev
import Database.Perdure.SizeRef
import qualified Database.Perdure.Cache as Cache
import Cgm.Control.Monad.State as M
import Cgm.Data.Typeable
import Control.Monad.Reader hiding (sequence)
import Cgm.Control.Concurrent.MVar
import Cgm.Data.Super
import Cgm.Data.Len
import Data.Word
import Database.Perdure.ReplicatedFile(ReplicatedFile(..))
import Database.Perdure.LocalStoreFile(withFileStoreFile, LocalStoreFile)
-- | Wraps a ReplicatedFile with a cache of a given size. The size is specified in bytes of serialized data, but the actual consumed
-- size may be a few times larger since the cache contains the deserialized data, which is often less compact than its serialized
-- representation.
newCachedFile :: Integer -> ReplicatedFile -> IO CachedFile
newCachedFile sz f = CachedFile f <$> newMVar (Cache.empty sz)
-- | At the moment this is the only way to create a rootLocation.
-- The root of the database will be located in one of two reserved locations at the start of the specified files.
defaultRootLocation :: CachedFile -> RootLocation
defaultRootLocation f = RootLocation f [RootAddress 0, RootAddress $ apply super rootAllocSize]
-- | Represents a persisted database. Contains a (ram-only) lock to sequence multithreaded operations,
-- so only one 'PVar' must be created per 'RootLocation'.
newtype PVar s = PVar (MVar (PState s))
-- | Creates a PVar with the specified initial state. Writes at the specified location, using the given maximum usable space (in bytes).
createPVar :: (Typeable s, Persistent s) => s -> Word64 -> RootLocation -> IO (PVar s)
createPVar s sz l = initState l (addSpan (sortedPair roots sz') emptySpace) s >>= fmap PVar . newMVar where
roots = 2 * apply super (getLen rootAllocSize)
sz' =
if sz <= roots
then error $ "createPVar needs a max size of at least " ++ show roots ++ " bytes"
else getLen (coarsenLen (unsafeLen (sz - roots) :: Len Word8 Word64) :: Len Word64 Word64)
-- | Attempts to open a PVar by reading at the given 'RootLocation'. Do not open the same location multiple times, share
-- the PVar instead.
openPVar :: (Typeable s, Persistent s) => RootLocation -> IO (Maybe (PVar s))
openPVar l = readState l >>= sequence . fmap (fmap PVar . newMVar)
-- | Persist a state change
updatePVar :: (Typeable s, Persistent s) => PVar s -> M.StateT s IO a -> IO a
updatePVar (PVar v) t = stateTModifyMVar v $ toStandardState $ updateState t
-- | This function allows read access to the bookkeeping structures of the database. The 'PState' type is subject to change.
updateInspectPVar :: (Typeable s, Persistent s) => PVar s -> M.StateT s (ReaderT (PState s) IO) a -> IO a
updateInspectPVar (PVar v) t = stateTModifyMVar v $ toStandardState $ updateStateRead t
| bitemyapp/perdure | src/Database/Perdure.hs | apache-2.0 | 3,921 | 0 | 14 | 623 | 745 | 416 | 329 | 54 | 2 |
{-# LANGUAGE GeneralizedNewtypeDeriving, OverloadedStrings #-}
module Protocol.Util where
import General.Persistence
( PersistentBlockHeader(..)
, PersistentUTXO(..)
)
import General.Hash (Hash(..))
import BitcoinCore.BlockHeaders
( BlockHeader(..)
, BlockVersion(..)
, Difficulty(..)
, Nonce(..)
, Timestamp(..)
, hashBlock
)
import BitcoinCore.MerkleTrees (MerkleHash(..))
import BitcoinCore.Transaction.Transactions
( Transaction(..)
, Value(..)
, outputScripts
, hashTransaction
, value
, outputs
)
import BitcoinCore.Transaction.Script
( Script(..)
, ScriptComponent(..)
, putScript
)
import Data.Maybe (fromJust)
import Data.Tuple (swap)
import Data.List (lookup)
import Data.ByteString (ByteString)
import Data.ByteString.Lazy (toStrict)
import Data.Binary (Binary(..))
import Data.Binary.Put (runPut, Put, putWord32le)
import Data.Binary.Get (Get, getWord32le)
import qualified Database.Persist.Sql as DB
import Control.Lens (Lens', (^.))
import Test.QuickCheck.Arbitrary (Arbitrary(..))
import Test.QuickCheck.Gen (elements, choose)
decodeBlockHeader :: PersistentBlockHeader -> BlockHeader
decodeBlockHeader
(PersistentBlockHeader
blockVersion
prevBlockHash
hash
merkleRoot
timestamp
difficulty
nonce) =
BlockHeader
(BlockVersion $ fromIntegral blockVersion)
(Hash prevBlockHash)
(MerkleHash merkleRoot)
(Timestamp . fromIntegral $ timestamp)
(Difficulty difficulty)
(Nonce nonce)
encodeBlockHeader :: BlockHeader -> PersistentBlockHeader
encodeBlockHeader
header@(BlockHeader
(BlockVersion blockVersion)
(Hash prevBlockHash)
(MerkleHash merkleRoot)
(Timestamp timestamp)
(Difficulty difficulty)
(Nonce nonce)) =
PersistentBlockHeader
(fromIntegral blockVersion)
prevBlockHash
(hash . hashBlock $ header)
merkleRoot
(fromIntegral . floor $ timestamp)
difficulty
nonce
data CCode
= REJECT_MALFORMED
| REJECT_INVALID
| REJECT_OBSOLETE
| REJECT_DUPLICATE
| REJECT_NONSTANDARD
| REJECT_DUST
| REJECT_INSUFFICIENTFEE
| REJECT_CHECKPOINT
deriving (Show, Eq)
instance Enum CCode where
fromEnum = fromJust . flip lookup ccodeTable
toEnum = fromJust . flip lookup (map swap ccodeTable)
ccodeTable :: [(CCode, Int)]
ccodeTable =
[ (REJECT_MALFORMED, 0x01)
, (REJECT_INVALID, 0x10)
, (REJECT_OBSOLETE, 0x11)
, (REJECT_DUPLICATE, 0x12)
, (REJECT_NONSTANDARD, 0x40)
, (REJECT_DUST, 0x41)
, (REJECT_INSUFFICIENTFEE, 0x42)
, (REJECT_CHECKPOINT, 0x43)]
getUTXOS :: [(Int, ByteString)] -> Transaction -> [PersistentUTXO]
getUTXOS indexedPubkeys transaction =
map
(\(pubkeyHashI, scriptI)
-> getPersistentUTXO transaction scriptI (outputScripts transaction !! scriptI) pubkeyHashI)
utxoIndices
where
indexedOutputScripts = zip [0..] (outputScripts transaction)
utxoIndices =
[ (pubkeyHashI, scriptI)
| (pubkeyHashI, pubkeyHash) <- indexedPubkeys
, (scriptI, script) <- indexedOutputScripts
, isRelevantScript pubkeyHash script ]
isRelevantScript :: ByteString -> Script -> Bool
isRelevantScript pubkeyHash (Script components) =
any isRelevantComponent components
where isRelevantComponent (Txt bs) = bs == pubkeyHash
isRelevantComponent (OP _) = False
getPersistentUTXO :: Transaction -> Int -> Script -> Int -> PersistentUTXO
getPersistentUTXO tx outIndex script keySetId' = PersistentUTXO
hash' outIndex scriptBS keySetId' val' isSpent' blockHash'
where
hash' = hash . hashTransaction $ tx
scriptBS = toStrict . runPut $ putScript script
Satoshis val' = ((tx^.outputs) !! outIndex)^.value
isSpent' = False
-- When creating a new UTXO, we assume it hasn't been spent yet
blockHash' = ""
-- Also don't initialize the block hash, assume it is not yet in a block
instance Arbitrary CCode where
arbitrary = elements . map fst $ ccodeTable
-- 0 based counting
-- genesis block has index 0
newtype BlockIndex = BlockIndex Int
deriving (Show, Eq, Ord, Num, Enum)
-- instance Ord BlockIndex where
-- (BlockIndex a) <= (BlockIndex b) = a <= b
toDbKey :: BlockIndex -> DB.Key PersistentBlockHeader
toDbKey (BlockIndex i) = DB.toSqlKey . fromIntegral $ i + 1
-- we add 1 since the db keys use 1 based counting
fromDbKey :: DB.Key PersistentBlockHeader -> BlockIndex
fromDbKey key = BlockIndex $ (fromIntegral . DB.fromSqlKey $ key) - 1
-- we subtract 1 since the db keys use 1 base counting
class HasLastBlock t where
lastBlock :: Lens' t BlockIndex
instance Binary BlockIndex where
put = putBlockIndex
get = getBlockIndex
getBlockIndex :: Get BlockIndex
getBlockIndex =
BlockIndex . fromIntegral <$> getWord32le
putBlockIndex :: BlockIndex -> Put
putBlockIndex (BlockIndex i) =
putWord32le . fromIntegral $ i
instance Arbitrary BlockIndex where
arbitrary = BlockIndex <$> choose (0, maxBlock)
where maxBlock = 0xffffffff -- 4 bytes
| clample/lamdabtc | backend/src/Protocol/Util.hs | bsd-3-clause | 4,965 | 0 | 11 | 924 | 1,293 | 736 | 557 | 141 | 2 |
{-# LANGUAGE CPP #-}
-------------------------------------------------------------------------------
--
-- | Dynamic flags
--
-- Most flags are dynamic flags, which means they can change from compilation
-- to compilation using @OPTIONS_GHC@ pragmas, and in a multi-session GHC each
-- session can be using different dynamic flags. Dynamic flags can also be set
-- at the prompt in GHCi.
--
-- (c) The University of Glasgow 2005
--
-------------------------------------------------------------------------------
{-# OPTIONS_GHC -fno-cse #-}
-- -fno-cse is needed for GLOBAL_VAR's to behave properly
module DynFlags (
-- * Dynamic flags and associated configuration types
DumpFlag(..),
GeneralFlag(..),
WarningFlag(..),
ExtensionFlag(..),
Language(..),
PlatformConstants(..),
FatalMessager, LogAction, FlushOut(..), FlushErr(..),
ProfAuto(..),
glasgowExtsFlags,
dopt, dopt_set, dopt_unset,
gopt, gopt_set, gopt_unset,
wopt, wopt_set, wopt_unset,
xopt, xopt_set, xopt_unset,
lang_set,
useUnicodeSyntax,
whenGeneratingDynamicToo, ifGeneratingDynamicToo,
whenCannotGenerateDynamicToo,
dynamicTooMkDynamicDynFlags,
DynFlags(..),
HasDynFlags(..), ContainsDynFlags(..),
RtsOptsEnabled(..),
HscTarget(..), isObjectTarget, defaultObjectTarget,
targetRetainsAllBindings,
GhcMode(..), isOneShot,
GhcLink(..), isNoLink,
PackageFlag(..), PackageArg(..), ModRenaming,
PkgConfRef(..),
Option(..), showOpt,
DynLibLoader(..),
fFlags, fWarningFlags, fLangFlags, xFlags,
dynFlagDependencies,
tablesNextToCode, mkTablesNextToCode,
printOutputForUser, printInfoForUser,
Way(..), mkBuildTag, wayRTSOnly, addWay', updateWays,
wayGeneralFlags, wayUnsetGeneralFlags,
-- ** Safe Haskell
SafeHaskellMode(..),
safeHaskellOn, safeImportsOn, safeLanguageOn, safeInferOn,
packageTrustOn,
safeDirectImpsReq, safeImplicitImpsReq,
unsafeFlags, unsafeFlagsForInfer,
-- ** System tool settings and locations
Settings(..),
targetPlatform,
ghcUsagePath, ghciUsagePath, topDir, tmpDir, rawSettings,
extraGccViaCFlags, systemPackageConfig,
pgm_L, pgm_P, pgm_F, pgm_c, pgm_s, pgm_a, pgm_l, pgm_dll, pgm_T,
pgm_sysman, pgm_windres, pgm_libtool, pgm_lo, pgm_lc,
opt_L, opt_P, opt_F, opt_c, opt_a, opt_l,
opt_windres, opt_lo, opt_lc,
-- ** Manipulating DynFlags
defaultDynFlags, -- Settings -> DynFlags
defaultWays,
interpWays,
initDynFlags, -- DynFlags -> IO DynFlags
defaultFatalMessager,
defaultLogAction,
defaultLogActionHPrintDoc,
defaultLogActionHPutStrDoc,
defaultFlushOut,
defaultFlushErr,
getOpts, -- DynFlags -> (DynFlags -> [a]) -> [a]
getVerbFlags,
updOptLevel,
setTmpDir,
setPackageKey,
-- ** Parsing DynFlags
parseDynamicFlagsCmdLine,
parseDynamicFilePragma,
parseDynamicFlagsFull,
-- ** Available DynFlags
allFlags,
flagsAll,
flagsDynamic,
flagsPackage,
supportedLanguagesAndExtensions,
languageExtensions,
-- ** DynFlags C compiler options
picCCOpts, picPOpts,
-- * Configuration of the stg-to-stg passes
StgToDo(..),
getStgToDo,
-- * Compiler configuration suitable for display to the user
compilerInfo,
#ifdef GHCI
rtsIsProfiled,
#endif
dynamicGhc,
#include "../includes/dist-derivedconstants/header/GHCConstantsHaskellExports.hs"
bLOCK_SIZE_W,
wORD_SIZE_IN_BITS,
tAG_MASK,
mAX_PTR_TAG,
tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD,
unsafeGlobalDynFlags, setUnsafeGlobalDynFlags,
-- * SSE and AVX
isSseEnabled,
isSse2Enabled,
isSse4_2Enabled,
isAvxEnabled,
isAvx2Enabled,
isAvx512cdEnabled,
isAvx512erEnabled,
isAvx512fEnabled,
isAvx512pfEnabled,
-- * Linker/compiler information
LinkerInfo(..),
CompilerInfo(..),
) where
#include "HsVersions.h"
import Platform
import PlatformConstants
import Module
import PackageConfig
import {-# SOURCE #-} Hooks
import {-# SOURCE #-} PrelNames ( mAIN )
import {-# SOURCE #-} Packages (PackageState)
import DriverPhases ( Phase(..), phaseInputExt )
import Config
import CmdLineParser
import Constants
import Panic
import Util
import Maybes ( orElse )
import MonadUtils
import qualified Pretty
import SrcLoc
import FastString
import Outputable
#ifdef GHCI
import Foreign.C ( CInt(..) )
import System.IO.Unsafe ( unsafeDupablePerformIO )
#endif
import {-# SOURCE #-} ErrUtils ( Severity(..), MsgDoc, mkLocMessage )
import System.IO.Unsafe ( unsafePerformIO )
import Data.IORef
import Control.Monad
import Data.Bits
import Data.Char
import Data.Int
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Word
import System.FilePath
import System.IO
import System.IO.Error
import Text.ParserCombinators.ReadP hiding (char)
import Text.ParserCombinators.ReadP as R
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import GHC.Foreign (withCString, peekCString)
-- -----------------------------------------------------------------------------
-- DynFlags
data DumpFlag
-- debugging flags
= Opt_D_dump_cmm
| Opt_D_dump_cmm_raw
-- All of the cmm subflags (there are a lot!) Automatically
-- enabled if you run -ddump-cmm
| Opt_D_dump_cmm_cfg
| Opt_D_dump_cmm_cbe
| Opt_D_dump_cmm_proc
| Opt_D_dump_cmm_sink
| Opt_D_dump_cmm_sp
| Opt_D_dump_cmm_procmap
| Opt_D_dump_cmm_split
| Opt_D_dump_cmm_info
| Opt_D_dump_cmm_cps
-- end cmm subflags
| Opt_D_dump_asm
| Opt_D_dump_asm_native
| Opt_D_dump_asm_liveness
| Opt_D_dump_asm_regalloc
| Opt_D_dump_asm_regalloc_stages
| Opt_D_dump_asm_conflicts
| Opt_D_dump_asm_stats
| Opt_D_dump_asm_expanded
| Opt_D_dump_llvm
| Opt_D_dump_core_stats
| Opt_D_dump_deriv
| Opt_D_dump_ds
| Opt_D_dump_foreign
| Opt_D_dump_inlinings
| Opt_D_dump_rule_firings
| Opt_D_dump_rule_rewrites
| Opt_D_dump_simpl_trace
| Opt_D_dump_occur_anal
| Opt_D_dump_parsed
| Opt_D_dump_rn
| Opt_D_dump_core_pipeline -- TODO FIXME: dump after simplifier stats
| Opt_D_dump_simpl
| Opt_D_dump_simpl_iterations
| Opt_D_dump_simpl_phases
| Opt_D_dump_spec
| Opt_D_dump_prep
| Opt_D_dump_stg
| Opt_D_dump_call_arity
| Opt_D_dump_stranal
| Opt_D_dump_strsigs
| Opt_D_dump_tc
| Opt_D_dump_types
| Opt_D_dump_rules
| Opt_D_dump_cse
| Opt_D_dump_worker_wrapper
| Opt_D_dump_rn_trace
| Opt_D_dump_rn_stats
| Opt_D_dump_opt_cmm
| Opt_D_dump_simpl_stats
| Opt_D_dump_cs_trace -- Constraint solver in type checker
| Opt_D_dump_tc_trace
| Opt_D_dump_if_trace
| Opt_D_dump_vt_trace
| Opt_D_dump_splices
| Opt_D_dump_BCOs
| Opt_D_dump_vect
| Opt_D_dump_ticked
| Opt_D_dump_rtti
| Opt_D_source_stats
| Opt_D_verbose_stg2stg
| Opt_D_dump_hi
| Opt_D_dump_hi_diffs
| Opt_D_dump_mod_cycles
| Opt_D_dump_mod_map
| Opt_D_dump_view_pattern_commoning
| Opt_D_verbose_core2core
deriving (Eq, Show, Enum)
-- | Enumerates the simple on-or-off dynamic flags
data GeneralFlag
= Opt_DumpToFile -- ^ Append dump output to files instead of stdout.
| Opt_D_faststring_stats
| Opt_D_dump_minimal_imports
| Opt_DoCoreLinting
| Opt_DoStgLinting
| Opt_DoCmmLinting
| Opt_DoAsmLinting
| Opt_NoLlvmMangler -- hidden flag
| Opt_WarnIsError -- -Werror; makes warnings fatal
| Opt_PrintExplicitForalls
| Opt_PrintExplicitKinds
-- optimisation opts
| Opt_CallArity
| Opt_Strictness
| Opt_LateDmdAnal
| Opt_KillAbsence
| Opt_KillOneShot
| Opt_FullLaziness
| Opt_FloatIn
| Opt_Specialise
| Opt_StaticArgumentTransformation
| Opt_CSE
| Opt_LiberateCase
| Opt_SpecConstr
| Opt_DoLambdaEtaExpansion
| Opt_IgnoreAsserts
| Opt_DoEtaReduction
| Opt_CaseMerge
| Opt_UnboxStrictFields
| Opt_UnboxSmallStrictFields
| Opt_DictsCheap
| Opt_EnableRewriteRules -- Apply rewrite rules during simplification
| Opt_Vectorise
| Opt_VectorisationAvoidance
| Opt_RegsGraph -- do graph coloring register allocation
| Opt_RegsIterative -- do iterative coalescing graph coloring register allocation
| Opt_PedanticBottoms -- Be picky about how we treat bottom
| Opt_LlvmTBAA -- Use LLVM TBAA infastructure for improving AA (hidden flag)
| Opt_LlvmPassVectorsInRegisters -- Pass SIMD vectors in registers (requires a patched LLVM) (hidden flag)
| Opt_IrrefutableTuples
| Opt_CmmSink
| Opt_CmmElimCommonBlocks
| Opt_OmitYields
| Opt_SimpleListLiterals
| Opt_FunToThunk -- allow WwLib.mkWorkerArgs to remove all value lambdas
| Opt_DictsStrict -- be strict in argument dictionaries
| Opt_DmdTxDictSel -- use a special demand transformer for dictionary selectors
| Opt_Loopification -- See Note [Self-recursive tail calls]
-- Interface files
| Opt_IgnoreInterfacePragmas
| Opt_OmitInterfacePragmas
| Opt_ExposeAllUnfoldings
| Opt_WriteInterface -- forces .hi files to be written even with -fno-code
-- profiling opts
| Opt_AutoSccsOnIndividualCafs
| Opt_ProfCountEntries
-- misc opts
| Opt_Pp
| Opt_ForceRecomp
| Opt_ExcessPrecision
| Opt_EagerBlackHoling
| Opt_NoHsMain
| Opt_SplitObjs
| Opt_StgStats
| Opt_HideAllPackages
| Opt_PrintBindResult
| Opt_Haddock
| Opt_HaddockOptions
| Opt_Hpc_No_Auto
| Opt_BreakOnException
| Opt_BreakOnError
| Opt_PrintEvldWithShow
| Opt_PrintBindContents
| Opt_GenManifest
| Opt_EmbedManifest
| Opt_EmitExternalCore
| Opt_SharedImplib
| Opt_BuildingCabalPackage
| Opt_IgnoreDotGhci
| Opt_GhciSandbox
| Opt_GhciHistory
| Opt_HelpfulErrors
| Opt_DeferTypeErrors
| Opt_Parallel
| Opt_GranMacros
| Opt_PIC
| Opt_SccProfilingOn
| Opt_Ticky
| Opt_Ticky_Allocd
| Opt_Ticky_LNE
| Opt_Ticky_Dyn_Thunk
| Opt_Static
| Opt_RPath
| Opt_RelativeDynlibPaths
| Opt_Hpc
| Opt_FlatCache
-- PreInlining is on by default. The option is there just to see how
-- bad things get if you turn it off!
| Opt_SimplPreInlining
-- output style opts
| Opt_ErrorSpans -- Include full span info in error messages,
-- instead of just the start position.
| Opt_PprCaseAsLet
-- Suppress all coercions, them replacing with '...'
| Opt_SuppressCoercions
| Opt_SuppressVarKinds
-- Suppress module id prefixes on variables.
| Opt_SuppressModulePrefixes
-- Suppress type applications.
| Opt_SuppressTypeApplications
-- Suppress info such as arity and unfoldings on identifiers.
| Opt_SuppressIdInfo
-- Suppress separate type signatures in core, but leave types on
-- lambda bound vars
| Opt_SuppressTypeSignatures
-- Suppress unique ids on variables.
-- Except for uniques, as some simplifier phases introduce new
-- variables that have otherwise identical names.
| Opt_SuppressUniques
-- temporary flags
| Opt_AutoLinkPackages
| Opt_ImplicitImportQualified
-- keeping stuff
| Opt_KeepHiDiffs
| Opt_KeepHcFiles
| Opt_KeepSFiles
| Opt_KeepTmpFiles
| Opt_KeepRawTokenStream
| Opt_KeepLlvmFiles
| Opt_BuildDynamicToo
-- safe haskell flags
| Opt_DistrustAllPackages
| Opt_PackageTrust
deriving (Eq, Show, Enum)
data WarningFlag =
Opt_WarnDuplicateExports
| Opt_WarnDuplicateConstraints
| Opt_WarnHiShadows
| Opt_WarnImplicitPrelude
| Opt_WarnIncompletePatterns
| Opt_WarnIncompleteUniPatterns
| Opt_WarnIncompletePatternsRecUpd
| Opt_WarnOverflowedLiterals
| Opt_WarnEmptyEnumerations
| Opt_WarnMissingFields
| Opt_WarnMissingImportList
| Opt_WarnMissingMethods
| Opt_WarnMissingSigs
| Opt_WarnMissingLocalSigs
| Opt_WarnNameShadowing
| Opt_WarnOverlappingPatterns
| Opt_WarnTypeDefaults
| Opt_WarnMonomorphism
| Opt_WarnUnusedBinds
| Opt_WarnUnusedImports
| Opt_WarnUnusedMatches
| Opt_WarnWarningsDeprecations
| Opt_WarnDeprecatedFlags
| Opt_WarnAMP
| Opt_WarnDodgyExports
| Opt_WarnDodgyImports
| Opt_WarnOrphans
| Opt_WarnAutoOrphans
| Opt_WarnIdentities
| Opt_WarnTabs
| Opt_WarnUnrecognisedPragmas
| Opt_WarnDodgyForeignImports
| Opt_WarnUnusedDoBind
| Opt_WarnWrongDoBind
| Opt_WarnAlternativeLayoutRuleTransitional
| Opt_WarnUnsafe
| Opt_WarnSafe
| Opt_WarnPointlessPragmas
| Opt_WarnUnsupportedCallingConventions
| Opt_WarnUnsupportedLlvmVersion
| Opt_WarnInlineRuleShadowing
| Opt_WarnTypedHoles
deriving (Eq, Show, Enum)
data Language = Haskell98 | Haskell2010
deriving Enum
-- | The various Safe Haskell modes
data SafeHaskellMode
= Sf_None
| Sf_Unsafe
| Sf_Trustworthy
| Sf_Safe
deriving (Eq)
instance Show SafeHaskellMode where
show Sf_None = "None"
show Sf_Unsafe = "Unsafe"
show Sf_Trustworthy = "Trustworthy"
show Sf_Safe = "Safe"
instance Outputable SafeHaskellMode where
ppr = text . show
data ExtensionFlag
= Opt_Cpp
| Opt_OverlappingInstances
| Opt_UndecidableInstances
| Opt_IncoherentInstances
| Opt_MonomorphismRestriction
| Opt_MonoPatBinds
| Opt_MonoLocalBinds
| Opt_RelaxedPolyRec -- Deprecated
| Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
| Opt_ForeignFunctionInterface
| Opt_UnliftedFFITypes
| Opt_InterruptibleFFI
| Opt_CApiFFI
| Opt_GHCForeignImportPrim
| Opt_JavaScriptFFI
| Opt_ParallelArrays -- Syntactic support for parallel arrays
| Opt_Arrows -- Arrow-notation syntax
| Opt_TemplateHaskell
| Opt_QuasiQuotes
| Opt_ImplicitParams
| Opt_ImplicitPrelude
| Opt_ScopedTypeVariables
| Opt_AllowAmbiguousTypes
| Opt_UnboxedTuples
| Opt_BangPatterns
| Opt_TypeFamilies
| Opt_OverloadedStrings
| Opt_OverloadedLists
| Opt_NumDecimals
| Opt_DisambiguateRecordFields
| Opt_RecordWildCards
| Opt_RecordPuns
| Opt_ViewPatterns
| Opt_GADTs
| Opt_GADTSyntax
| Opt_NPlusKPatterns
| Opt_DoAndIfThenElse
| Opt_RebindableSyntax
| Opt_ConstraintKinds
| Opt_PolyKinds -- Kind polymorphism
| Opt_DataKinds -- Datatype promotion
| Opt_InstanceSigs
| Opt_StandaloneDeriving
| Opt_DeriveDataTypeable
| Opt_AutoDeriveTypeable -- Automatic derivation of Typeable
| Opt_DeriveFunctor
| Opt_DeriveTraversable
| Opt_DeriveFoldable
| Opt_DeriveGeneric -- Allow deriving Generic/1
| Opt_DefaultSignatures -- Allow extra signatures for defmeths
| Opt_TypeSynonymInstances
| Opt_FlexibleContexts
| Opt_FlexibleInstances
| Opt_ConstrainedClassMethods
| Opt_MultiParamTypeClasses
| Opt_NullaryTypeClasses
| Opt_FunctionalDependencies
| Opt_UnicodeSyntax
| Opt_ExistentialQuantification
| Opt_MagicHash
| Opt_EmptyDataDecls
| Opt_KindSignatures
| Opt_RoleAnnotations
| Opt_ParallelListComp
| Opt_TransformListComp
| Opt_MonadComprehensions
| Opt_GeneralizedNewtypeDeriving
| Opt_RecursiveDo
| Opt_PostfixOperators
| Opt_TupleSections
| Opt_PatternGuards
| Opt_LiberalTypeSynonyms
| Opt_RankNTypes
| Opt_ImpredicativeTypes
| Opt_TypeOperators
| Opt_ExplicitNamespaces
| Opt_PackageImports
| Opt_ExplicitForAll
| Opt_AlternativeLayoutRule
| Opt_AlternativeLayoutRuleTransitional
| Opt_DatatypeContexts
| Opt_NondecreasingIndentation
| Opt_RelaxedLayout
| Opt_TraditionalRecordSyntax
| Opt_LambdaCase
| Opt_MultiWayIf
| Opt_BinaryLiterals
| Opt_NegativeLiterals
| Opt_EmptyCase
| Opt_PatternSynonyms
deriving (Eq, Enum, Show)
-- | Contains not only a collection of 'GeneralFlag's but also a plethora of
-- information relating to the compilation of a single file or GHC session
data DynFlags = DynFlags {
ghcMode :: GhcMode,
ghcLink :: GhcLink,
hscTarget :: HscTarget,
settings :: Settings,
verbosity :: Int, -- ^ Verbosity level: see Note [Verbosity levels]
optLevel :: Int, -- ^ Optimisation level
simplPhases :: Int, -- ^ Number of simplifier phases
maxSimplIterations :: Int, -- ^ Max simplifier iterations
shouldDumpSimplPhase :: Maybe String,
ruleCheck :: Maybe String,
strictnessBefore :: [Int], -- ^ Additional demand analysis
parMakeCount :: Maybe Int, -- ^ The number of modules to compile in parallel
-- in --make mode, where Nothing ==> compile as
-- many in parallel as there are CPUs.
enableTimeStats :: Bool, -- ^ Enable RTS timing statistics?
ghcHeapSize :: Maybe Int, -- ^ The heap size to set.
maxRelevantBinds :: Maybe Int, -- ^ Maximum number of bindings from the type envt
-- to show in type error messages
simplTickFactor :: Int, -- ^ Multiplier for simplifier ticks
specConstrThreshold :: Maybe Int, -- ^ Threshold for SpecConstr
specConstrCount :: Maybe Int, -- ^ Max number of specialisations for any one function
specConstrRecursive :: Int, -- ^ Max number of specialisations for recursive types
-- Not optional; otherwise ForceSpecConstr can diverge.
liberateCaseThreshold :: Maybe Int, -- ^ Threshold for LiberateCase
floatLamArgs :: Maybe Int, -- ^ Arg count for lambda floating
-- See CoreMonad.FloatOutSwitches
historySize :: Int,
cmdlineHcIncludes :: [String], -- ^ @\-\#includes@
importPaths :: [FilePath],
mainModIs :: Module,
mainFunIs :: Maybe String,
ctxtStkDepth :: Int, -- ^ Typechecker context stack depth
tyFunStkDepth :: Int, -- ^ Typechecker type function stack depth
thisPackage :: PackageKey, -- ^ name of package currently being compiled
-- ways
ways :: [Way], -- ^ Way flags from the command line
buildTag :: String, -- ^ The global \"way\" (e.g. \"p\" for prof)
rtsBuildTag :: String, -- ^ The RTS \"way\"
-- For object splitting
splitInfo :: Maybe (String,Int),
-- paths etc.
objectDir :: Maybe String,
dylibInstallName :: Maybe String,
hiDir :: Maybe String,
stubDir :: Maybe String,
dumpDir :: Maybe String,
objectSuf :: String,
hcSuf :: String,
hiSuf :: String,
canGenerateDynamicToo :: IORef Bool,
dynObjectSuf :: String,
dynHiSuf :: String,
-- Packages.isDllName needs to know whether a call is within a
-- single DLL or not. Normally it does this by seeing if the call
-- is to the same package, but for the ghc package, we split the
-- package between 2 DLLs. The dllSplit tells us which sets of
-- modules are in which package.
dllSplitFile :: Maybe FilePath,
dllSplit :: Maybe [Set String],
outputFile :: Maybe String,
dynOutputFile :: Maybe String,
outputHi :: Maybe String,
dynLibLoader :: DynLibLoader,
-- | This is set by 'DriverPipeline.runPipeline' based on where
-- its output is going.
dumpPrefix :: Maybe FilePath,
-- | Override the 'dumpPrefix' set by 'DriverPipeline.runPipeline'.
-- Set by @-ddump-file-prefix@
dumpPrefixForce :: Maybe FilePath,
ldInputs :: [Option],
includePaths :: [String],
libraryPaths :: [String],
frameworkPaths :: [String], -- used on darwin only
cmdlineFrameworks :: [String], -- ditto
rtsOpts :: Maybe String,
rtsOptsEnabled :: RtsOptsEnabled,
hpcDir :: String, -- ^ Path to store the .mix files
-- Plugins
pluginModNames :: [ModuleName],
pluginModNameOpts :: [(ModuleName,String)],
-- GHC API hooks
hooks :: Hooks,
-- For ghc -M
depMakefile :: FilePath,
depIncludePkgDeps :: Bool,
depExcludeMods :: [ModuleName],
depSuffixes :: [String],
-- Package flags
extraPkgConfs :: [PkgConfRef] -> [PkgConfRef],
-- ^ The @-package-db@ flags given on the command line, in the order
-- they appeared.
packageFlags :: [PackageFlag],
-- ^ The @-package@ and @-hide-package@ flags from the command-line
-- Package state
-- NB. do not modify this field, it is calculated by
-- Packages.initPackages and Packages.updatePackages.
pkgDatabase :: Maybe [PackageConfig],
pkgState :: PackageState,
-- Temporary files
-- These have to be IORefs, because the defaultCleanupHandler needs to
-- know what to clean when an exception happens
filesToClean :: IORef [FilePath],
dirsToClean :: IORef (Map FilePath FilePath),
filesToNotIntermediateClean :: IORef [FilePath],
-- The next available suffix to uniquely name a temp file, updated atomically
nextTempSuffix :: IORef Int,
-- Names of files which were generated from -ddump-to-file; used to
-- track which ones we need to truncate because it's our first run
-- through
generatedDumps :: IORef (Set FilePath),
-- hsc dynamic flags
dumpFlags :: IntSet,
generalFlags :: IntSet,
warningFlags :: IntSet,
-- Don't change this without updating extensionFlags:
language :: Maybe Language,
-- | Safe Haskell mode
safeHaskell :: SafeHaskellMode,
safeInfer :: Bool,
safeInferred :: Bool,
-- We store the location of where some extension and flags were turned on so
-- we can produce accurate error messages when Safe Haskell fails due to
-- them.
thOnLoc :: SrcSpan,
newDerivOnLoc :: SrcSpan,
overlapInstLoc :: SrcSpan,
pkgTrustOnLoc :: SrcSpan,
warnSafeOnLoc :: SrcSpan,
warnUnsafeOnLoc :: SrcSpan,
-- Don't change this without updating extensionFlags:
extensions :: [OnOff ExtensionFlag],
-- extensionFlags should always be equal to
-- flattenExtensionFlags language extensions
extensionFlags :: IntSet,
-- Unfolding control
-- See Note [Discounts and thresholds] in CoreUnfold
ufCreationThreshold :: Int,
ufUseThreshold :: Int,
ufFunAppDiscount :: Int,
ufDictDiscount :: Int,
ufKeenessFactor :: Float,
ufDearOp :: Int,
maxWorkerArgs :: Int,
ghciHistSize :: Int,
-- | MsgDoc output action: use "ErrUtils" instead of this if you can
log_action :: LogAction,
flushOut :: FlushOut,
flushErr :: FlushErr,
haddockOptions :: Maybe String,
ghciScripts :: [String],
-- Output style options
pprUserLength :: Int,
pprCols :: Int,
traceLevel :: Int, -- Standard level is 1. Less verbose is 0.
useUnicode :: Bool,
-- | what kind of {-# SCC #-} to add automatically
profAuto :: ProfAuto,
interactivePrint :: Maybe String,
llvmVersion :: IORef Int,
nextWrapperNum :: IORef (ModuleEnv Int),
-- | Machine dependant flags (-m<blah> stuff)
sseVersion :: Maybe (Int, Int), -- (major, minor)
avx :: Bool,
avx2 :: Bool,
avx512cd :: Bool, -- Enable AVX-512 Conflict Detection Instructions.
avx512er :: Bool, -- Enable AVX-512 Exponential and Reciprocal Instructions.
avx512f :: Bool, -- Enable AVX-512 instructions.
avx512pf :: Bool, -- Enable AVX-512 PreFetch Instructions.
-- | Run-time linker information (what options we need, etc.)
rtldInfo :: IORef (Maybe LinkerInfo),
-- | Run-time compiler information
rtccInfo :: IORef (Maybe CompilerInfo),
-- Constants used to control the amount of optimization done.
-- | Max size, in bytes, of inline array allocations.
maxInlineAllocSize :: Int,
-- | Only inline memcpy if it generates no more than this many
-- pseudo (roughly: Cmm) instructions.
maxInlineMemcpyInsns :: Int,
-- | Only inline memset if it generates no more than this many
-- pseudo (roughly: Cmm) instructions.
maxInlineMemsetInsns :: Int
}
class HasDynFlags m where
getDynFlags :: m DynFlags
class ContainsDynFlags t where
extractDynFlags :: t -> DynFlags
replaceDynFlags :: t -> DynFlags -> t
data ProfAuto
= NoProfAuto -- ^ no SCC annotations added
| ProfAutoAll -- ^ top-level and nested functions are annotated
| ProfAutoTop -- ^ top-level functions annotated only
| ProfAutoExports -- ^ exported functions annotated only
| ProfAutoCalls -- ^ annotate call-sites
deriving (Enum)
data Settings = Settings {
sTargetPlatform :: Platform, -- Filled in by SysTools
sGhcUsagePath :: FilePath, -- Filled in by SysTools
sGhciUsagePath :: FilePath, -- ditto
sTopDir :: FilePath,
sTmpDir :: String, -- no trailing '/'
-- You shouldn't need to look things up in rawSettings directly.
-- They should have their own fields instead.
sRawSettings :: [(String, String)],
sExtraGccViaCFlags :: [String],
sSystemPackageConfig :: FilePath,
sLdSupportsCompactUnwind :: Bool,
sLdSupportsBuildId :: Bool,
sLdSupportsFilelist :: Bool,
sLdIsGnuLd :: Bool,
-- commands for particular phases
sPgm_L :: String,
sPgm_P :: (String,[Option]),
sPgm_F :: String,
sPgm_c :: (String,[Option]),
sPgm_s :: (String,[Option]),
sPgm_a :: (String,[Option]),
sPgm_l :: (String,[Option]),
sPgm_dll :: (String,[Option]),
sPgm_T :: String,
sPgm_sysman :: String,
sPgm_windres :: String,
sPgm_libtool :: String,
sPgm_lo :: (String,[Option]), -- LLVM: opt llvm optimiser
sPgm_lc :: (String,[Option]), -- LLVM: llc static compiler
-- options for particular phases
sOpt_L :: [String],
sOpt_P :: [String],
sOpt_F :: [String],
sOpt_c :: [String],
sOpt_a :: [String],
sOpt_l :: [String],
sOpt_windres :: [String],
sOpt_lo :: [String], -- LLVM: llvm optimiser
sOpt_lc :: [String], -- LLVM: llc static compiler
sPlatformConstants :: PlatformConstants
}
targetPlatform :: DynFlags -> Platform
targetPlatform dflags = sTargetPlatform (settings dflags)
ghcUsagePath :: DynFlags -> FilePath
ghcUsagePath dflags = sGhcUsagePath (settings dflags)
ghciUsagePath :: DynFlags -> FilePath
ghciUsagePath dflags = sGhciUsagePath (settings dflags)
topDir :: DynFlags -> FilePath
topDir dflags = sTopDir (settings dflags)
tmpDir :: DynFlags -> String
tmpDir dflags = sTmpDir (settings dflags)
rawSettings :: DynFlags -> [(String, String)]
rawSettings dflags = sRawSettings (settings dflags)
extraGccViaCFlags :: DynFlags -> [String]
extraGccViaCFlags dflags = sExtraGccViaCFlags (settings dflags)
systemPackageConfig :: DynFlags -> FilePath
systemPackageConfig dflags = sSystemPackageConfig (settings dflags)
pgm_L :: DynFlags -> String
pgm_L dflags = sPgm_L (settings dflags)
pgm_P :: DynFlags -> (String,[Option])
pgm_P dflags = sPgm_P (settings dflags)
pgm_F :: DynFlags -> String
pgm_F dflags = sPgm_F (settings dflags)
pgm_c :: DynFlags -> (String,[Option])
pgm_c dflags = sPgm_c (settings dflags)
pgm_s :: DynFlags -> (String,[Option])
pgm_s dflags = sPgm_s (settings dflags)
pgm_a :: DynFlags -> (String,[Option])
pgm_a dflags = sPgm_a (settings dflags)
pgm_l :: DynFlags -> (String,[Option])
pgm_l dflags = sPgm_l (settings dflags)
pgm_dll :: DynFlags -> (String,[Option])
pgm_dll dflags = sPgm_dll (settings dflags)
pgm_T :: DynFlags -> String
pgm_T dflags = sPgm_T (settings dflags)
pgm_sysman :: DynFlags -> String
pgm_sysman dflags = sPgm_sysman (settings dflags)
pgm_windres :: DynFlags -> String
pgm_windres dflags = sPgm_windres (settings dflags)
pgm_libtool :: DynFlags -> String
pgm_libtool dflags = sPgm_libtool (settings dflags)
pgm_lo :: DynFlags -> (String,[Option])
pgm_lo dflags = sPgm_lo (settings dflags)
pgm_lc :: DynFlags -> (String,[Option])
pgm_lc dflags = sPgm_lc (settings dflags)
opt_L :: DynFlags -> [String]
opt_L dflags = sOpt_L (settings dflags)
opt_P :: DynFlags -> [String]
opt_P dflags = concatMap (wayOptP (targetPlatform dflags)) (ways dflags)
++ sOpt_P (settings dflags)
opt_F :: DynFlags -> [String]
opt_F dflags = sOpt_F (settings dflags)
opt_c :: DynFlags -> [String]
opt_c dflags = concatMap (wayOptc (targetPlatform dflags)) (ways dflags)
++ sOpt_c (settings dflags)
opt_a :: DynFlags -> [String]
opt_a dflags = sOpt_a (settings dflags)
opt_l :: DynFlags -> [String]
opt_l dflags = concatMap (wayOptl (targetPlatform dflags)) (ways dflags)
++ sOpt_l (settings dflags)
opt_windres :: DynFlags -> [String]
opt_windres dflags = sOpt_windres (settings dflags)
opt_lo :: DynFlags -> [String]
opt_lo dflags = sOpt_lo (settings dflags)
opt_lc :: DynFlags -> [String]
opt_lc dflags = sOpt_lc (settings dflags)
-- | The target code type of the compilation (if any).
--
-- Whenever you change the target, also make sure to set 'ghcLink' to
-- something sensible.
--
-- 'HscNothing' can be used to avoid generating any output, however, note
-- that:
--
-- * If a program uses Template Haskell the typechecker may try to run code
-- from an imported module. This will fail if no code has been generated
-- for this module. You can use 'GHC.needsTemplateHaskell' to detect
-- whether this might be the case and choose to either switch to a
-- different target or avoid typechecking such modules. (The latter may be
-- preferable for security reasons.)
--
data HscTarget
= HscC -- ^ Generate C code.
| HscAsm -- ^ Generate assembly using the native code generator.
| HscLlvm -- ^ Generate assembly using the llvm code generator.
| HscInterpreted -- ^ Generate bytecode. (Requires 'LinkInMemory')
| HscNothing -- ^ Don't generate any code. See notes above.
deriving (Eq, Show)
-- | Will this target result in an object file on the disk?
isObjectTarget :: HscTarget -> Bool
isObjectTarget HscC = True
isObjectTarget HscAsm = True
isObjectTarget HscLlvm = True
isObjectTarget _ = False
-- | Does this target retain *all* top-level bindings for a module,
-- rather than just the exported bindings, in the TypeEnv and compiled
-- code (if any)? In interpreted mode we do this, so that GHCi can
-- call functions inside a module. In HscNothing mode we also do it,
-- so that Haddock can get access to the GlobalRdrEnv for a module
-- after typechecking it.
targetRetainsAllBindings :: HscTarget -> Bool
targetRetainsAllBindings HscInterpreted = True
targetRetainsAllBindings HscNothing = True
targetRetainsAllBindings _ = False
-- | The 'GhcMode' tells us whether we're doing multi-module
-- compilation (controlled via the "GHC" API) or one-shot
-- (single-module) compilation. This makes a difference primarily to
-- the "Finder": in one-shot mode we look for interface files for
-- imported modules, but in multi-module mode we look for source files
-- in order to check whether they need to be recompiled.
data GhcMode
= CompManager -- ^ @\-\-make@, GHCi, etc.
| OneShot -- ^ @ghc -c Foo.hs@
| MkDepend -- ^ @ghc -M@, see "Finder" for why we need this
deriving Eq
instance Outputable GhcMode where
ppr CompManager = ptext (sLit "CompManager")
ppr OneShot = ptext (sLit "OneShot")
ppr MkDepend = ptext (sLit "MkDepend")
isOneShot :: GhcMode -> Bool
isOneShot OneShot = True
isOneShot _other = False
-- | What to do in the link step, if there is one.
data GhcLink
= NoLink -- ^ Don't link at all
| LinkBinary -- ^ Link object code into a binary
| LinkInMemory -- ^ Use the in-memory dynamic linker (works for both
-- bytecode and object code).
| LinkDynLib -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
| LinkStaticLib -- ^ Link objects into a static lib
deriving (Eq, Show)
isNoLink :: GhcLink -> Bool
isNoLink NoLink = True
isNoLink _ = False
data PackageArg = PackageArg String
| PackageIdArg String
| PackageKeyArg String
deriving (Eq, Show)
type ModRenaming = Maybe [(String, String)]
data PackageFlag
= ExposePackage PackageArg ModRenaming
| HidePackage String
| IgnorePackage String
| TrustPackage String
| DistrustPackage String
deriving (Eq, Show)
defaultHscTarget :: Platform -> HscTarget
defaultHscTarget = defaultObjectTarget
-- | The 'HscTarget' value corresponding to the default way to create
-- object files on the current platform.
defaultObjectTarget :: Platform -> HscTarget
defaultObjectTarget platform
| platformUnregisterised platform = HscC
| cGhcWithNativeCodeGen == "YES" = HscAsm
| otherwise = HscLlvm
tablesNextToCode :: DynFlags -> Bool
tablesNextToCode dflags
= mkTablesNextToCode (platformUnregisterised (targetPlatform dflags))
-- Determines whether we will be compiling
-- info tables that reside just before the entry code, or with an
-- indirection to the entry code. See TABLES_NEXT_TO_CODE in
-- includes/rts/storage/InfoTables.h.
mkTablesNextToCode :: Bool -> Bool
mkTablesNextToCode unregisterised
= not unregisterised && cGhcEnableTablesNextToCode == "YES"
data DynLibLoader
= Deployable
| SystemDependent
deriving Eq
data RtsOptsEnabled = RtsOptsNone | RtsOptsSafeOnly | RtsOptsAll
deriving (Show)
-----------------------------------------------------------------------------
-- Ways
-- The central concept of a "way" is that all objects in a given
-- program must be compiled in the same "way". Certain options change
-- parameters of the virtual machine, eg. profiling adds an extra word
-- to the object header, so profiling objects cannot be linked with
-- non-profiling objects.
-- After parsing the command-line options, we determine which "way" we
-- are building - this might be a combination way, eg. profiling+threaded.
-- We then find the "build-tag" associated with this way, and this
-- becomes the suffix used to find .hi files and libraries used in
-- this compilation.
data Way
= WayCustom String -- for GHC API clients building custom variants
| WayThreaded
| WayDebug
| WayProf
| WayEventLog
| WayPar
| WayGran
| WayNDP
| WayDyn
deriving (Eq, Ord, Show)
allowed_combination :: [Way] -> Bool
allowed_combination way = and [ x `allowedWith` y
| x <- way, y <- way, x < y ]
where
-- Note ordering in these tests: the left argument is
-- <= the right argument, according to the Ord instance
-- on Way above.
-- dyn is allowed with everything
_ `allowedWith` WayDyn = True
WayDyn `allowedWith` _ = True
-- debug is allowed with everything
_ `allowedWith` WayDebug = True
WayDebug `allowedWith` _ = True
(WayCustom {}) `allowedWith` _ = True
WayProf `allowedWith` WayNDP = True
WayThreaded `allowedWith` WayProf = True
WayThreaded `allowedWith` WayEventLog = True
_ `allowedWith` _ = False
mkBuildTag :: [Way] -> String
mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
wayTag :: Way -> String
wayTag (WayCustom xs) = xs
wayTag WayThreaded = "thr"
wayTag WayDebug = "debug"
wayTag WayDyn = "dyn"
wayTag WayProf = "p"
wayTag WayEventLog = "l"
wayTag WayPar = "mp"
wayTag WayGran = "mg"
wayTag WayNDP = "ndp"
wayRTSOnly :: Way -> Bool
wayRTSOnly (WayCustom {}) = False
wayRTSOnly WayThreaded = True
wayRTSOnly WayDebug = True
wayRTSOnly WayDyn = False
wayRTSOnly WayProf = False
wayRTSOnly WayEventLog = True
wayRTSOnly WayPar = False
wayRTSOnly WayGran = False
wayRTSOnly WayNDP = False
wayDesc :: Way -> String
wayDesc (WayCustom xs) = xs
wayDesc WayThreaded = "Threaded"
wayDesc WayDebug = "Debug"
wayDesc WayDyn = "Dynamic"
wayDesc WayProf = "Profiling"
wayDesc WayEventLog = "RTS Event Logging"
wayDesc WayPar = "Parallel"
wayDesc WayGran = "GranSim"
wayDesc WayNDP = "Nested data parallelism"
-- Turn these flags on when enabling this way
wayGeneralFlags :: Platform -> Way -> [GeneralFlag]
wayGeneralFlags _ (WayCustom {}) = []
wayGeneralFlags _ WayThreaded = []
wayGeneralFlags _ WayDebug = []
wayGeneralFlags _ WayDyn = [Opt_PIC]
-- We could get away without adding -fPIC when compiling the
-- modules of a program that is to be linked with -dynamic; the
-- program itself does not need to be position-independent, only
-- the libraries need to be. HOWEVER, GHCi links objects into a
-- .so before loading the .so using the system linker. Since only
-- PIC objects can be linked into a .so, we have to compile even
-- modules of the main program with -fPIC when using -dynamic.
wayGeneralFlags _ WayProf = [Opt_SccProfilingOn]
wayGeneralFlags _ WayEventLog = []
wayGeneralFlags _ WayPar = [Opt_Parallel]
wayGeneralFlags _ WayGran = [Opt_GranMacros]
wayGeneralFlags _ WayNDP = []
-- Turn these flags off when enabling this way
wayUnsetGeneralFlags :: Platform -> Way -> [GeneralFlag]
wayUnsetGeneralFlags _ (WayCustom {}) = []
wayUnsetGeneralFlags _ WayThreaded = []
wayUnsetGeneralFlags _ WayDebug = []
wayUnsetGeneralFlags _ WayDyn = [-- There's no point splitting objects
-- when we're going to be dynamically
-- linking. Plus it breaks compilation
-- on OSX x86.
Opt_SplitObjs]
wayUnsetGeneralFlags _ WayProf = []
wayUnsetGeneralFlags _ WayEventLog = []
wayUnsetGeneralFlags _ WayPar = []
wayUnsetGeneralFlags _ WayGran = []
wayUnsetGeneralFlags _ WayNDP = []
wayExtras :: Platform -> Way -> DynFlags -> DynFlags
wayExtras _ (WayCustom {}) dflags = dflags
wayExtras _ WayThreaded dflags = dflags
wayExtras _ WayDebug dflags = dflags
wayExtras _ WayDyn dflags = dflags
wayExtras _ WayProf dflags = dflags
wayExtras _ WayEventLog dflags = dflags
wayExtras _ WayPar dflags = exposePackage' "concurrent" dflags
wayExtras _ WayGran dflags = exposePackage' "concurrent" dflags
wayExtras _ WayNDP dflags = setExtensionFlag' Opt_ParallelArrays
$ setGeneralFlag' Opt_Vectorise dflags
wayOptc :: Platform -> Way -> [String]
wayOptc _ (WayCustom {}) = []
wayOptc platform WayThreaded = case platformOS platform of
OSOpenBSD -> ["-pthread"]
OSNetBSD -> ["-pthread"]
_ -> []
wayOptc _ WayDebug = []
wayOptc _ WayDyn = []
wayOptc _ WayProf = ["-DPROFILING"]
wayOptc _ WayEventLog = ["-DTRACING"]
wayOptc _ WayPar = ["-DPAR", "-w"]
wayOptc _ WayGran = ["-DGRAN"]
wayOptc _ WayNDP = []
wayOptl :: Platform -> Way -> [String]
wayOptl _ (WayCustom {}) = []
wayOptl platform WayThreaded =
case platformOS platform of
-- FreeBSD's default threading library is the KSE-based M:N libpthread,
-- which GHC has some problems with. It's currently not clear whether
-- the problems are our fault or theirs, but it seems that using the
-- alternative 1:1 threading library libthr works around it:
OSFreeBSD -> ["-lthr"]
OSOpenBSD -> ["-pthread"]
OSNetBSD -> ["-pthread"]
_ -> []
wayOptl _ WayDebug = []
wayOptl _ WayDyn = []
wayOptl _ WayProf = []
wayOptl _ WayEventLog = []
wayOptl _ WayPar = ["-L${PVM_ROOT}/lib/${PVM_ARCH}",
"-lpvm3",
"-lgpvm3"]
wayOptl _ WayGran = []
wayOptl _ WayNDP = []
wayOptP :: Platform -> Way -> [String]
wayOptP _ (WayCustom {}) = []
wayOptP _ WayThreaded = []
wayOptP _ WayDebug = []
wayOptP _ WayDyn = []
wayOptP _ WayProf = ["-DPROFILING"]
wayOptP _ WayEventLog = ["-DTRACING"]
wayOptP _ WayPar = ["-D__PARALLEL_HASKELL__"]
wayOptP _ WayGran = ["-D__GRANSIM__"]
wayOptP _ WayNDP = []
whenGeneratingDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
whenGeneratingDynamicToo dflags f = ifGeneratingDynamicToo dflags f (return ())
ifGeneratingDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
ifGeneratingDynamicToo dflags f g = generateDynamicTooConditional dflags f g g
whenCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
whenCannotGenerateDynamicToo dflags f
= ifCannotGenerateDynamicToo dflags f (return ())
ifCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
ifCannotGenerateDynamicToo dflags f g
= generateDynamicTooConditional dflags g f g
generateDynamicTooConditional :: MonadIO m
=> DynFlags -> m a -> m a -> m a -> m a
generateDynamicTooConditional dflags canGen cannotGen notTryingToGen
= if gopt Opt_BuildDynamicToo dflags
then do let ref = canGenerateDynamicToo dflags
b <- liftIO $ readIORef ref
if b then canGen else cannotGen
else notTryingToGen
dynamicTooMkDynamicDynFlags :: DynFlags -> DynFlags
dynamicTooMkDynamicDynFlags dflags0
= let dflags1 = addWay' WayDyn dflags0
dflags2 = dflags1 {
outputFile = dynOutputFile dflags1,
hiSuf = dynHiSuf dflags1,
objectSuf = dynObjectSuf dflags1
}
dflags3 = updateWays dflags2
dflags4 = gopt_unset dflags3 Opt_BuildDynamicToo
in dflags4
-----------------------------------------------------------------------------
-- | Used by 'GHC.runGhc' to partially initialize a new 'DynFlags' value
initDynFlags :: DynFlags -> IO DynFlags
initDynFlags dflags = do
let -- We can't build with dynamic-too on Windows, as labels before
-- the fork point are different depending on whether we are
-- building dynamically or not.
platformCanGenerateDynamicToo
= platformOS (targetPlatform dflags) /= OSMinGW32
refCanGenerateDynamicToo <- newIORef platformCanGenerateDynamicToo
refNextTempSuffix <- newIORef 0
refFilesToClean <- newIORef []
refDirsToClean <- newIORef Map.empty
refFilesToNotIntermediateClean <- newIORef []
refGeneratedDumps <- newIORef Set.empty
refLlvmVersion <- newIORef 28
refRtldInfo <- newIORef Nothing
refRtccInfo <- newIORef Nothing
wrapperNum <- newIORef emptyModuleEnv
canUseUnicode <- do let enc = localeEncoding
str = "‘’"
(withCString enc str $ \cstr ->
do str' <- peekCString enc cstr
return (str == str'))
`catchIOError` \_ -> return False
return dflags{
canGenerateDynamicToo = refCanGenerateDynamicToo,
nextTempSuffix = refNextTempSuffix,
filesToClean = refFilesToClean,
dirsToClean = refDirsToClean,
filesToNotIntermediateClean = refFilesToNotIntermediateClean,
generatedDumps = refGeneratedDumps,
llvmVersion = refLlvmVersion,
nextWrapperNum = wrapperNum,
useUnicode = canUseUnicode,
rtldInfo = refRtldInfo,
rtccInfo = refRtccInfo
}
-- | The normal 'DynFlags'. Note that they is not suitable for use in this form
-- and must be fully initialized by 'GHC.runGhc' first.
defaultDynFlags :: Settings -> DynFlags
defaultDynFlags mySettings =
DynFlags {
ghcMode = CompManager,
ghcLink = LinkBinary,
hscTarget = defaultHscTarget (sTargetPlatform mySettings),
verbosity = 0,
optLevel = 0,
simplPhases = 2,
maxSimplIterations = 4,
shouldDumpSimplPhase = Nothing,
ruleCheck = Nothing,
maxRelevantBinds = Just 6,
simplTickFactor = 100,
specConstrThreshold = Just 2000,
specConstrCount = Just 3,
specConstrRecursive = 3,
liberateCaseThreshold = Just 2000,
floatLamArgs = Just 0, -- Default: float only if no fvs
historySize = 20,
strictnessBefore = [],
parMakeCount = Just 1,
enableTimeStats = False,
ghcHeapSize = Nothing,
cmdlineHcIncludes = [],
importPaths = ["."],
mainModIs = mAIN,
mainFunIs = Nothing,
ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
tyFunStkDepth = mAX_TYPE_FUNCTION_REDUCTION_DEPTH,
thisPackage = mainPackageKey,
objectDir = Nothing,
dylibInstallName = Nothing,
hiDir = Nothing,
stubDir = Nothing,
dumpDir = Nothing,
objectSuf = phaseInputExt StopLn,
hcSuf = phaseInputExt HCc,
hiSuf = "hi",
canGenerateDynamicToo = panic "defaultDynFlags: No canGenerateDynamicToo",
dynObjectSuf = "dyn_" ++ phaseInputExt StopLn,
dynHiSuf = "dyn_hi",
dllSplitFile = Nothing,
dllSplit = Nothing,
pluginModNames = [],
pluginModNameOpts = [],
hooks = emptyHooks,
outputFile = Nothing,
dynOutputFile = Nothing,
outputHi = Nothing,
dynLibLoader = SystemDependent,
dumpPrefix = Nothing,
dumpPrefixForce = Nothing,
ldInputs = [],
includePaths = [],
libraryPaths = [],
frameworkPaths = [],
cmdlineFrameworks = [],
rtsOpts = Nothing,
rtsOptsEnabled = RtsOptsSafeOnly,
hpcDir = ".hpc",
extraPkgConfs = id,
packageFlags = [],
pkgDatabase = Nothing,
pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
ways = defaultWays mySettings,
buildTag = mkBuildTag (defaultWays mySettings),
rtsBuildTag = mkBuildTag (defaultWays mySettings),
splitInfo = Nothing,
settings = mySettings,
-- ghc -M values
depMakefile = "Makefile",
depIncludePkgDeps = False,
depExcludeMods = [],
depSuffixes = [],
-- end of ghc -M values
nextTempSuffix = panic "defaultDynFlags: No nextTempSuffix",
filesToClean = panic "defaultDynFlags: No filesToClean",
dirsToClean = panic "defaultDynFlags: No dirsToClean",
filesToNotIntermediateClean = panic "defaultDynFlags: No filesToNotIntermediateClean",
generatedDumps = panic "defaultDynFlags: No generatedDumps",
haddockOptions = Nothing,
dumpFlags = IntSet.empty,
generalFlags = IntSet.fromList (map fromEnum (defaultFlags mySettings)),
warningFlags = IntSet.fromList (map fromEnum standardWarnings),
ghciScripts = [],
language = Nothing,
safeHaskell = Sf_None,
safeInfer = True,
safeInferred = True,
thOnLoc = noSrcSpan,
newDerivOnLoc = noSrcSpan,
overlapInstLoc = noSrcSpan,
pkgTrustOnLoc = noSrcSpan,
warnSafeOnLoc = noSrcSpan,
warnUnsafeOnLoc = noSrcSpan,
extensions = [],
extensionFlags = flattenExtensionFlags Nothing [],
-- The ufCreationThreshold threshold must be reasonably high to
-- take account of possible discounts.
-- E.g. 450 is not enough in 'fulsom' for Interval.sqr to inline
-- into Csg.calc (The unfolding for sqr never makes it into the
-- interface file.)
ufCreationThreshold = 750,
ufUseThreshold = 60,
ufFunAppDiscount = 60,
-- Be fairly keen to inline a fuction if that means
-- we'll be able to pick the right method from a dictionary
ufDictDiscount = 30,
ufKeenessFactor = 1.5,
ufDearOp = 40,
maxWorkerArgs = 10,
ghciHistSize = 50, -- keep a log of length 50 by default
log_action = defaultLogAction,
flushOut = defaultFlushOut,
flushErr = defaultFlushErr,
pprUserLength = 5,
pprCols = 100,
useUnicode = False,
traceLevel = 1,
profAuto = NoProfAuto,
llvmVersion = panic "defaultDynFlags: No llvmVersion",
interactivePrint = Nothing,
nextWrapperNum = panic "defaultDynFlags: No nextWrapperNum",
sseVersion = Nothing,
avx = False,
avx2 = False,
avx512cd = False,
avx512er = False,
avx512f = False,
avx512pf = False,
rtldInfo = panic "defaultDynFlags: no rtldInfo",
rtccInfo = panic "defaultDynFlags: no rtccInfo",
maxInlineAllocSize = 128,
maxInlineMemcpyInsns = 32,
maxInlineMemsetInsns = 32
}
defaultWays :: Settings -> [Way]
defaultWays settings = if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings)
then [WayDyn]
else []
interpWays :: [Way]
interpWays = if dynamicGhc
then [WayDyn]
else []
--------------------------------------------------------------------------
type FatalMessager = String -> IO ()
type LogAction = DynFlags -> Severity -> SrcSpan -> PprStyle -> MsgDoc -> IO ()
defaultFatalMessager :: FatalMessager
defaultFatalMessager = hPutStrLn stderr
defaultLogAction :: LogAction
defaultLogAction dflags severity srcSpan style msg
= case severity of
SevOutput -> printSDoc msg style
SevDump -> printSDoc (msg $$ blankLine) style
SevInteractive -> putStrSDoc msg style
SevInfo -> printErrs msg style
SevFatal -> printErrs msg style
_ -> do hPutChar stderr '\n'
printErrs (mkLocMessage severity srcSpan msg) style
-- careful (#2302): printErrs prints in UTF-8,
-- whereas converting to string first and using
-- hPutStr would just emit the low 8 bits of
-- each unicode char.
where printSDoc = defaultLogActionHPrintDoc dflags stdout
printErrs = defaultLogActionHPrintDoc dflags stderr
putStrSDoc = defaultLogActionHPutStrDoc dflags stdout
defaultLogActionHPrintDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
defaultLogActionHPrintDoc dflags h d sty
= defaultLogActionHPutStrDoc dflags h (d $$ text "") sty
-- Adds a newline
defaultLogActionHPutStrDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
defaultLogActionHPutStrDoc dflags h d sty
= Pretty.printDoc_ Pretty.PageMode (pprCols dflags) h doc
where -- Don't add a newline at the end, so that successive
-- calls to this log-action can output all on the same line
doc = runSDoc d (initSDocContext dflags sty)
newtype FlushOut = FlushOut (IO ())
defaultFlushOut :: FlushOut
defaultFlushOut = FlushOut $ hFlush stdout
newtype FlushErr = FlushErr (IO ())
defaultFlushErr :: FlushErr
defaultFlushErr = FlushErr $ hFlush stderr
printOutputForUser :: DynFlags -> PrintUnqualified -> SDoc -> IO ()
printOutputForUser = printSevForUser SevOutput
printInfoForUser :: DynFlags -> PrintUnqualified -> SDoc -> IO ()
printInfoForUser = printSevForUser SevInfo
printSevForUser :: Severity -> DynFlags -> PrintUnqualified -> SDoc -> IO ()
printSevForUser sev dflags unqual doc
= log_action dflags dflags sev noSrcSpan (mkUserStyle unqual AllTheWay) doc
{-
Note [Verbosity levels]
~~~~~~~~~~~~~~~~~~~~~~~
0 | print errors & warnings only
1 | minimal verbosity: print "compiling M ... done." for each module.
2 | equivalent to -dshow-passes
3 | equivalent to existing "ghc -v"
4 | "ghc -v -ddump-most"
5 | "ghc -v -ddump-all"
-}
data OnOff a = On a
| Off a
-- OnOffs accumulate in reverse order, so we use foldr in order to
-- process them in the right order
flattenExtensionFlags :: Maybe Language -> [OnOff ExtensionFlag] -> IntSet
flattenExtensionFlags ml = foldr f defaultExtensionFlags
where f (On f) flags = IntSet.insert (fromEnum f) flags
f (Off f) flags = IntSet.delete (fromEnum f) flags
defaultExtensionFlags = IntSet.fromList (map fromEnum (languageExtensions ml))
languageExtensions :: Maybe Language -> [ExtensionFlag]
languageExtensions Nothing
-- Nothing => the default case
= Opt_NondecreasingIndentation -- This has been on by default for some time
: delete Opt_DatatypeContexts -- The Haskell' committee decided to
-- remove datatype contexts from the
-- language:
-- http://www.haskell.org/pipermail/haskell-prime/2011-January/003335.html
(languageExtensions (Just Haskell2010))
-- NB: MonoPatBinds is no longer the default
languageExtensions (Just Haskell98)
= [Opt_ImplicitPrelude,
Opt_MonomorphismRestriction,
Opt_NPlusKPatterns,
Opt_DatatypeContexts,
Opt_TraditionalRecordSyntax,
Opt_NondecreasingIndentation
-- strictly speaking non-standard, but we always had this
-- on implicitly before the option was added in 7.1, and
-- turning it off breaks code, so we're keeping it on for
-- backwards compatibility. Cabal uses -XHaskell98 by
-- default unless you specify another language.
]
languageExtensions (Just Haskell2010)
= [Opt_ImplicitPrelude,
Opt_MonomorphismRestriction,
Opt_DatatypeContexts,
Opt_TraditionalRecordSyntax,
Opt_EmptyDataDecls,
Opt_ForeignFunctionInterface,
Opt_PatternGuards,
Opt_DoAndIfThenElse,
Opt_RelaxedPolyRec]
-- | Test whether a 'DumpFlag' is set
dopt :: DumpFlag -> DynFlags -> Bool
dopt f dflags = (fromEnum f `IntSet.member` dumpFlags dflags)
|| (verbosity dflags >= 4 && enableIfVerbose f)
where enableIfVerbose Opt_D_dump_tc_trace = False
enableIfVerbose Opt_D_dump_rn_trace = False
enableIfVerbose Opt_D_dump_cs_trace = False
enableIfVerbose Opt_D_dump_if_trace = False
enableIfVerbose Opt_D_dump_vt_trace = False
enableIfVerbose Opt_D_dump_tc = False
enableIfVerbose Opt_D_dump_rn = False
enableIfVerbose Opt_D_dump_rn_stats = False
enableIfVerbose Opt_D_dump_hi_diffs = False
enableIfVerbose Opt_D_verbose_core2core = False
enableIfVerbose Opt_D_verbose_stg2stg = False
enableIfVerbose Opt_D_dump_splices = False
enableIfVerbose Opt_D_dump_rule_firings = False
enableIfVerbose Opt_D_dump_rule_rewrites = False
enableIfVerbose Opt_D_dump_simpl_trace = False
enableIfVerbose Opt_D_dump_rtti = False
enableIfVerbose Opt_D_dump_inlinings = False
enableIfVerbose Opt_D_dump_core_stats = False
enableIfVerbose Opt_D_dump_asm_stats = False
enableIfVerbose Opt_D_dump_types = False
enableIfVerbose Opt_D_dump_simpl_iterations = False
enableIfVerbose Opt_D_dump_ticked = False
enableIfVerbose Opt_D_dump_view_pattern_commoning = False
enableIfVerbose Opt_D_dump_mod_cycles = False
enableIfVerbose Opt_D_dump_mod_map = False
enableIfVerbose _ = True
-- | Set a 'DumpFlag'
dopt_set :: DynFlags -> DumpFlag -> DynFlags
dopt_set dfs f = dfs{ dumpFlags = IntSet.insert (fromEnum f) (dumpFlags dfs) }
-- | Unset a 'DumpFlag'
dopt_unset :: DynFlags -> DumpFlag -> DynFlags
dopt_unset dfs f = dfs{ dumpFlags = IntSet.delete (fromEnum f) (dumpFlags dfs) }
-- | Test whether a 'GeneralFlag' is set
gopt :: GeneralFlag -> DynFlags -> Bool
gopt f dflags = fromEnum f `IntSet.member` generalFlags dflags
-- | Set a 'GeneralFlag'
gopt_set :: DynFlags -> GeneralFlag -> DynFlags
gopt_set dfs f = dfs{ generalFlags = IntSet.insert (fromEnum f) (generalFlags dfs) }
-- | Unset a 'GeneralFlag'
gopt_unset :: DynFlags -> GeneralFlag -> DynFlags
gopt_unset dfs f = dfs{ generalFlags = IntSet.delete (fromEnum f) (generalFlags dfs) }
-- | Test whether a 'WarningFlag' is set
wopt :: WarningFlag -> DynFlags -> Bool
wopt f dflags = fromEnum f `IntSet.member` warningFlags dflags
-- | Set a 'WarningFlag'
wopt_set :: DynFlags -> WarningFlag -> DynFlags
wopt_set dfs f = dfs{ warningFlags = IntSet.insert (fromEnum f) (warningFlags dfs) }
-- | Unset a 'WarningFlag'
wopt_unset :: DynFlags -> WarningFlag -> DynFlags
wopt_unset dfs f = dfs{ warningFlags = IntSet.delete (fromEnum f) (warningFlags dfs) }
-- | Test whether a 'ExtensionFlag' is set
xopt :: ExtensionFlag -> DynFlags -> Bool
xopt f dflags = fromEnum f `IntSet.member` extensionFlags dflags
-- | Set a 'ExtensionFlag'
xopt_set :: DynFlags -> ExtensionFlag -> DynFlags
xopt_set dfs f
= let onoffs = On f : extensions dfs
in dfs { extensions = onoffs,
extensionFlags = flattenExtensionFlags (language dfs) onoffs }
-- | Unset a 'ExtensionFlag'
xopt_unset :: DynFlags -> ExtensionFlag -> DynFlags
xopt_unset dfs f
= let onoffs = Off f : extensions dfs
in dfs { extensions = onoffs,
extensionFlags = flattenExtensionFlags (language dfs) onoffs }
lang_set :: DynFlags -> Maybe Language -> DynFlags
lang_set dflags lang =
dflags {
language = lang,
extensionFlags = flattenExtensionFlags lang (extensions dflags)
}
useUnicodeSyntax :: DynFlags -> Bool
useUnicodeSyntax = xopt Opt_UnicodeSyntax
-- | Set the Haskell language standard to use
setLanguage :: Language -> DynP ()
setLanguage l = upd (`lang_set` Just l)
-- | Some modules have dependencies on others through the DynFlags rather than textual imports
dynFlagDependencies :: DynFlags -> [ModuleName]
dynFlagDependencies = pluginModNames
-- | Is the -fpackage-trust mode on
packageTrustOn :: DynFlags -> Bool
packageTrustOn = gopt Opt_PackageTrust
-- | Is Safe Haskell on in some way (including inference mode)
safeHaskellOn :: DynFlags -> Bool
safeHaskellOn dflags = safeHaskell dflags /= Sf_None || safeInferOn dflags
-- | Is the Safe Haskell safe language in use
safeLanguageOn :: DynFlags -> Bool
safeLanguageOn dflags = safeHaskell dflags == Sf_Safe
-- | Is the Safe Haskell safe inference mode active
safeInferOn :: DynFlags -> Bool
safeInferOn = safeInfer
-- | Test if Safe Imports are on in some form
safeImportsOn :: DynFlags -> Bool
safeImportsOn dflags = safeHaskell dflags == Sf_Unsafe ||
safeHaskell dflags == Sf_Trustworthy ||
safeHaskell dflags == Sf_Safe
-- | Set a 'Safe Haskell' flag
setSafeHaskell :: SafeHaskellMode -> DynP ()
setSafeHaskell s = updM f
where f dfs = do
let sf = safeHaskell dfs
safeM <- combineSafeFlags sf s
return $ case (s == Sf_Safe || s == Sf_Unsafe) of
True -> dfs { safeHaskell = safeM, safeInfer = False }
-- leave safe inferrence on in Trustworthy mode so we can warn
-- if it could have been inferred safe.
False -> dfs { safeHaskell = safeM }
-- | Are all direct imports required to be safe for this Safe Haskell mode?
-- Direct imports are when the code explicitly imports a module
safeDirectImpsReq :: DynFlags -> Bool
safeDirectImpsReq d = safeLanguageOn d
-- | Are all implicit imports required to be safe for this Safe Haskell mode?
-- Implicit imports are things in the prelude. e.g System.IO when print is used.
safeImplicitImpsReq :: DynFlags -> Bool
safeImplicitImpsReq d = safeLanguageOn d
-- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags.
-- This makes Safe Haskell very much a monoid but for now I prefer this as I don't
-- want to export this functionality from the module but do want to export the
-- type constructors.
combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode
combineSafeFlags a b | a == Sf_None = return b
| b == Sf_None = return a
| a == b = return a
| otherwise = addErr errm >> return (panic errm)
where errm = "Incompatible Safe Haskell flags! ("
++ show a ++ ", " ++ show b ++ ")"
-- | A list of unsafe flags under Safe Haskell. Tuple elements are:
-- * name of the flag
-- * function to get srcspan that enabled the flag
-- * function to test if the flag is on
-- * function to turn the flag off
unsafeFlags, unsafeFlagsForInfer
:: [(String, DynFlags -> SrcSpan, DynFlags -> Bool, DynFlags -> DynFlags)]
unsafeFlags = [("-XGeneralizedNewtypeDeriving", newDerivOnLoc,
xopt Opt_GeneralizedNewtypeDeriving,
flip xopt_unset Opt_GeneralizedNewtypeDeriving),
("-XTemplateHaskell", thOnLoc,
xopt Opt_TemplateHaskell,
flip xopt_unset Opt_TemplateHaskell)]
unsafeFlagsForInfer = unsafeFlags ++
-- TODO: Can we do better than this for inference?
[("-XOverlappingInstances", overlapInstLoc,
xopt Opt_OverlappingInstances,
flip xopt_unset Opt_OverlappingInstances)]
-- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order
getOpts :: DynFlags -- ^ 'DynFlags' to retrieve the options from
-> (DynFlags -> [a]) -- ^ Relevant record accessor: one of the @opt_*@ accessors
-> [a] -- ^ Correctly ordered extracted options
getOpts dflags opts = reverse (opts dflags)
-- We add to the options from the front, so we need to reverse the list
-- | Gets the verbosity flag for the current verbosity level. This is fed to
-- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included
getVerbFlags :: DynFlags -> [String]
getVerbFlags dflags
| verbosity dflags >= 4 = ["-v"]
| otherwise = []
setObjectDir, setHiDir, setStubDir, setDumpDir, setOutputDir,
setDynObjectSuf, setDynHiSuf,
setDylibInstallName,
setObjectSuf, setHiSuf, setHcSuf, parseDynLibLoaderMode,
setPgmP, addOptl, addOptc, addOptP,
addCmdlineFramework, addHaddockOpts, addGhciScript,
setInteractivePrint
:: String -> DynFlags -> DynFlags
setOutputFile, setDynOutputFile, setOutputHi, setDumpPrefixForce
:: Maybe String -> DynFlags -> DynFlags
setObjectDir f d = d{ objectDir = Just f}
setHiDir f d = d{ hiDir = Just f}
setStubDir f d = d{ stubDir = Just f, includePaths = f : includePaths d }
-- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
-- \#included from the .hc file when compiling via C (i.e. unregisterised
-- builds).
setDumpDir f d = d{ dumpDir = Just f}
setOutputDir f = setObjectDir f . setHiDir f . setStubDir f . setDumpDir f
setDylibInstallName f d = d{ dylibInstallName = Just f}
setObjectSuf f d = d{ objectSuf = f}
setDynObjectSuf f d = d{ dynObjectSuf = f}
setHiSuf f d = d{ hiSuf = f}
setDynHiSuf f d = d{ dynHiSuf = f}
setHcSuf f d = d{ hcSuf = f}
setOutputFile f d = d{ outputFile = f}
setDynOutputFile f d = d{ dynOutputFile = f}
setOutputHi f d = d{ outputHi = f}
addPluginModuleName :: String -> DynFlags -> DynFlags
addPluginModuleName name d = d { pluginModNames = (mkModuleName name) : (pluginModNames d) }
addPluginModuleNameOption :: String -> DynFlags -> DynFlags
addPluginModuleNameOption optflag d = d { pluginModNameOpts = (mkModuleName m, option) : (pluginModNameOpts d) }
where (m, rest) = break (== ':') optflag
option = case rest of
[] -> "" -- should probably signal an error
(_:plug_opt) -> plug_opt -- ignore the ':' from break
parseDynLibLoaderMode f d =
case splitAt 8 f of
("deploy", "") -> d{ dynLibLoader = Deployable }
("sysdep", "") -> d{ dynLibLoader = SystemDependent }
_ -> throwGhcException (CmdLineError ("Unknown dynlib loader: " ++ f))
setDumpPrefixForce f d = d { dumpPrefixForce = f}
-- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
-- Config.hs should really use Option.
setPgmP f = let (pgm:args) = words f in alterSettings (\s -> s { sPgm_P = (pgm, map Option args)})
addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s})
addOptc f = alterSettings (\s -> s { sOpt_c = f : sOpt_c s})
addOptP f = alterSettings (\s -> s { sOpt_P = f : sOpt_P s})
setDepMakefile :: FilePath -> DynFlags -> DynFlags
setDepMakefile f d = d { depMakefile = deOptDep f }
setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags
setDepIncludePkgDeps b d = d { depIncludePkgDeps = b }
addDepExcludeMod :: String -> DynFlags -> DynFlags
addDepExcludeMod m d
= d { depExcludeMods = mkModuleName (deOptDep m) : depExcludeMods d }
addDepSuffix :: FilePath -> DynFlags -> DynFlags
addDepSuffix s d = d { depSuffixes = deOptDep s : depSuffixes d }
-- XXX Legacy code:
-- We used to use "-optdep-flag -optdeparg", so for legacy applications
-- we need to strip the "-optdep" off of the arg
deOptDep :: String -> String
deOptDep x = case stripPrefix "-optdep" x of
Just rest -> rest
Nothing -> x
addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
addHaddockOpts f d = d{ haddockOptions = Just f}
addGhciScript f d = d{ ghciScripts = f : ghciScripts d}
setInteractivePrint f d = d{ interactivePrint = Just f}
-- -----------------------------------------------------------------------------
-- Command-line options
-- | When invoking external tools as part of the compilation pipeline, we
-- pass these a sequence of options on the command-line. Rather than
-- just using a list of Strings, we use a type that allows us to distinguish
-- between filepaths and 'other stuff'. The reason for this is that
-- this type gives us a handle on transforming filenames, and filenames only,
-- to whatever format they're expected to be on a particular platform.
data Option
= FileOption -- an entry that _contains_ filename(s) / filepaths.
String -- a non-filepath prefix that shouldn't be
-- transformed (e.g., "/out=")
String -- the filepath/filename portion
| Option String
deriving ( Eq )
showOpt :: Option -> String
showOpt (FileOption pre f) = pre ++ f
showOpt (Option s) = s
-----------------------------------------------------------------------------
-- Setting the optimisation level
updOptLevel :: Int -> DynFlags -> DynFlags
-- ^ Sets the 'DynFlags' to be appropriate to the optimisation level
updOptLevel n dfs
= dfs2{ optLevel = final_n }
where
final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
dfs1 = foldr (flip gopt_unset) dfs remove_gopts
dfs2 = foldr (flip gopt_set) dfs1 extra_gopts
extra_gopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
remove_gopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
-- -----------------------------------------------------------------------------
-- StgToDo: abstraction of stg-to-stg passes to run.
data StgToDo
= StgDoMassageForProfiling -- should be (next to) last
-- There's also setStgVarInfo, but its absolute "lastness"
-- is so critical that it is hardwired in (no flag).
| D_stg_stats
getStgToDo :: DynFlags -> [StgToDo]
getStgToDo dflags
= todo2
where
stg_stats = gopt Opt_StgStats dflags
todo1 = if stg_stats then [D_stg_stats] else []
todo2 | WayProf `elem` ways dflags
= StgDoMassageForProfiling : todo1
| otherwise
= todo1
{- **********************************************************************
%* *
DynFlags parser
%* *
%********************************************************************* -}
-- -----------------------------------------------------------------------------
-- Parsing the dynamic flags.
-- | Parse dynamic flags from a list of command line arguments. Returns the
-- the parsed 'DynFlags', the left-over arguments, and a list of warnings.
-- Throws a 'UsageError' if errors occurred during parsing (such as unknown
-- flags or missing arguments).
parseDynamicFlagsCmdLine :: MonadIO m => DynFlags -> [Located String]
-> m (DynFlags, [Located String], [Located String])
-- ^ Updated 'DynFlags', left-over arguments, and
-- list of warnings.
parseDynamicFlagsCmdLine = parseDynamicFlagsFull flagsAll True
-- | Like 'parseDynamicFlagsCmdLine' but does not allow the package flags
-- (-package, -hide-package, -ignore-package, -hide-all-packages, -package-db).
-- Used to parse flags set in a modules pragma.
parseDynamicFilePragma :: MonadIO m => DynFlags -> [Located String]
-> m (DynFlags, [Located String], [Located String])
-- ^ Updated 'DynFlags', left-over arguments, and
-- list of warnings.
parseDynamicFilePragma = parseDynamicFlagsFull flagsDynamic False
-- | Parses the dynamically set flags for GHC. This is the most general form of
-- the dynamic flag parser that the other methods simply wrap. It allows
-- saying which flags are valid flags and indicating if we are parsing
-- arguments from the command line or from a file pragma.
parseDynamicFlagsFull :: MonadIO m
=> [Flag (CmdLineP DynFlags)] -- ^ valid flags to match against
-> Bool -- ^ are the arguments from the command line?
-> DynFlags -- ^ current dynamic flags
-> [Located String] -- ^ arguments to parse
-> m (DynFlags, [Located String], [Located String])
parseDynamicFlagsFull activeFlags cmdline dflags0 args = do
-- XXX Legacy support code
-- We used to accept things like
-- optdep-f -optdepdepend
-- optdep-f -optdep depend
-- optdep -f -optdepdepend
-- optdep -f -optdep depend
-- but the spaces trip up proper argument handling. So get rid of them.
let f (L p "-optdep" : L _ x : xs) = (L p ("-optdep" ++ x)) : f xs
f (x : xs) = x : f xs
f xs = xs
args' = f args
let ((leftover, errs, warns), dflags1)
= runCmdLine (processArgs activeFlags args') dflags0
when (not (null errs)) $ liftIO $
throwGhcExceptionIO $ errorsToGhcException errs
-- check for disabled flags in safe haskell
let (dflags2, sh_warns) = safeFlagCheck cmdline dflags1
dflags3 = updateWays dflags2
theWays = ways dflags3
unless (allowed_combination theWays) $ liftIO $
throwGhcExceptionIO (CmdLineError ("combination not supported: " ++
intercalate "/" (map wayDesc theWays)))
let chooseOutput
| isJust (outputFile dflags3) -- Only iff user specified -o ...
, not (isJust (dynOutputFile dflags3)) -- but not -dyno
= return $ dflags3 { dynOutputFile = Just $ dynOut (fromJust $ outputFile dflags3) }
| otherwise
= return dflags3
where
dynOut = flip addExtension (dynObjectSuf dflags3) . dropExtension
dflags4 <- ifGeneratingDynamicToo dflags3 chooseOutput (return dflags3)
let (dflags5, consistency_warnings) = makeDynFlagsConsistent dflags4
dflags6 <- case dllSplitFile dflags5 of
Nothing -> return (dflags5 { dllSplit = Nothing })
Just f ->
case dllSplit dflags5 of
Just _ ->
-- If dllSplit is out of date then it would have
-- been set to Nothing. As it's a Just, it must be
-- up-to-date.
return dflags5
Nothing ->
do xs <- liftIO $ readFile f
let ss = map (Set.fromList . words) (lines xs)
return $ dflags5 { dllSplit = Just ss }
-- Set timer stats & heap size
when (enableTimeStats dflags6) $ liftIO enableTimingStats
case (ghcHeapSize dflags6) of
Just x -> liftIO (setHeapSize x)
_ -> return ()
liftIO $ setUnsafeGlobalDynFlags dflags6
return (dflags6, leftover, consistency_warnings ++ sh_warns ++ warns)
updateWays :: DynFlags -> DynFlags
updateWays dflags
= let theWays = sort $ nub $ ways dflags
f = if WayDyn `elem` theWays then unSetGeneralFlag'
else setGeneralFlag'
in f Opt_Static
$ dflags {
ways = theWays,
buildTag = mkBuildTag (filter (not . wayRTSOnly) theWays),
rtsBuildTag = mkBuildTag theWays
}
-- | Check (and potentially disable) any extensions that aren't allowed
-- in safe mode.
--
-- The bool is to indicate if we are parsing command line flags (false means
-- file pragma). This allows us to generate better warnings.
safeFlagCheck :: Bool -> DynFlags -> (DynFlags, [Located String])
safeFlagCheck _ dflags | safeLanguageOn dflags = (dflagsUnset, warns)
where
-- Handle illegal flags under safe language.
(dflagsUnset, warns) = foldl check_method (dflags, []) unsafeFlags
check_method (df, warns) (str,loc,test,fix)
| test df = (fix df, warns ++ safeFailure (loc df) str)
| otherwise = (df, warns)
safeFailure loc str
= [L loc $ str ++ " is not allowed in Safe Haskell; ignoring "
++ str]
safeFlagCheck cmdl dflags =
case (safeInferOn dflags) of
True | safeFlags -> (dflags', warn)
True -> (dflags' { safeInferred = False }, warn)
False -> (dflags', warn)
where
-- dynflags and warn for when -fpackage-trust by itself with no safe
-- haskell flag
(dflags', warn)
| safeHaskell dflags == Sf_None && not cmdl && packageTrustOn dflags
= (gopt_unset dflags Opt_PackageTrust, pkgWarnMsg)
| otherwise = (dflags, [])
pkgWarnMsg = [L (pkgTrustOnLoc dflags') $
"-fpackage-trust ignored;" ++
" must be specified with a Safe Haskell flag"]
safeFlags = all (\(_,_,t,_) -> not $ t dflags) unsafeFlagsForInfer
-- Have we inferred Unsafe?
-- See Note [HscMain . Safe Haskell Inference]
{- **********************************************************************
%* *
DynFlags specifications
%* *
%********************************************************************* -}
-- | All dynamic flags option strings. These are the user facing strings for
-- enabling and disabling options.
allFlags :: [String]
allFlags = map ('-':) $
[ flagName flag | flag <- dynamic_flags ++ package_flags, ok (flagOptKind flag) ] ++
map ("fno-"++) fflags ++
map ("f"++) fflags ++
map ("X"++) supportedExtensions
where ok (PrefixPred _ _) = False
ok _ = True
fflags = fflags0 ++ fflags1 ++ fflags2
fflags0 = [ name | (name, _, _) <- fFlags ]
fflags1 = [ name | (name, _, _) <- fWarningFlags ]
fflags2 = [ name | (name, _, _) <- fLangFlags ]
{-
- Below we export user facing symbols for GHC dynamic flags for use with the
- GHC API.
-}
-- All dynamic flags present in GHC.
flagsAll :: [Flag (CmdLineP DynFlags)]
flagsAll = package_flags ++ dynamic_flags
-- All dynamic flags, minus package flags, present in GHC.
flagsDynamic :: [Flag (CmdLineP DynFlags)]
flagsDynamic = dynamic_flags
-- ALl package flags present in GHC.
flagsPackage :: [Flag (CmdLineP DynFlags)]
flagsPackage = package_flags
--------------- The main flags themselves ------------------
dynamic_flags :: [Flag (CmdLineP DynFlags)]
dynamic_flags = [
Flag "n" (NoArg (addWarn "The -n flag is deprecated and no longer has any effect"))
, Flag "cpp" (NoArg (setExtensionFlag Opt_Cpp))
, Flag "F" (NoArg (setGeneralFlag Opt_Pp))
, Flag "#include"
(HasArg (\s -> do addCmdlineHCInclude s
addWarn "-#include and INCLUDE pragmas are deprecated: They no longer have any effect"))
, Flag "v" (OptIntSuffix setVerbosity)
, Flag "j" (OptIntSuffix (\n -> upd (\d -> d {parMakeCount = n})))
-- RTS options -------------------------------------------------------------
, Flag "H" (HasArg (\s -> upd (\d ->
d { ghcHeapSize = Just $ fromIntegral (decodeSize s)})))
, Flag "Rghc-timing" (NoArg (upd (\d -> d { enableTimeStats = True })))
------- ways ---------------------------------------------------------------
, Flag "prof" (NoArg (addWay WayProf))
, Flag "eventlog" (NoArg (addWay WayEventLog))
, Flag "parallel" (NoArg (addWay WayPar))
, Flag "gransim" (NoArg (addWay WayGran))
, Flag "smp" (NoArg (addWay WayThreaded >> deprecate "Use -threaded instead"))
, Flag "debug" (NoArg (addWay WayDebug))
, Flag "ndp" (NoArg (addWay WayNDP))
, Flag "threaded" (NoArg (addWay WayThreaded))
, Flag "ticky" (NoArg (setGeneralFlag Opt_Ticky >> addWay WayDebug))
-- -ticky enables ticky-ticky code generation, and also implies -debug which
-- is required to get the RTS ticky support.
----- Linker --------------------------------------------------------
, Flag "static" (NoArg removeWayDyn)
, Flag "dynamic" (NoArg (addWay WayDyn))
-- ignored for compat w/ gcc:
, Flag "rdynamic" (NoArg (return ()))
, Flag "relative-dynlib-paths" (NoArg (setGeneralFlag Opt_RelativeDynlibPaths))
------- Specific phases --------------------------------------------
-- need to appear before -pgmL to be parsed as LLVM flags.
, Flag "pgmlo" (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])})))
, Flag "pgmlc" (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])})))
, Flag "pgmL" (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f})))
, Flag "pgmP" (hasArg setPgmP)
, Flag "pgmF" (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f})))
, Flag "pgmc" (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[])})))
, Flag "pgms" (hasArg (\f -> alterSettings (\s -> s { sPgm_s = (f,[])})))
, Flag "pgma" (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])})))
, Flag "pgml" (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])})))
, Flag "pgmdll" (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])})))
, Flag "pgmwindres" (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f})))
, Flag "pgmlibtool" (hasArg (\f -> alterSettings (\s -> s { sPgm_libtool = f})))
-- need to appear before -optl/-opta to be parsed as LLVM flags.
, Flag "optlo" (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s})))
, Flag "optlc" (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s})))
, Flag "optL" (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s})))
, Flag "optP" (hasArg addOptP)
, Flag "optF" (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s})))
, Flag "optc" (hasArg addOptc)
, Flag "opta" (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s})))
, Flag "optl" (hasArg addOptl)
, Flag "optwindres" (hasArg (\f -> alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s})))
, Flag "split-objs"
(NoArg (if can_split
then setGeneralFlag Opt_SplitObjs
else addWarn "ignoring -fsplit-objs"))
-------- ghc -M -----------------------------------------------------
, Flag "dep-suffix" (hasArg addDepSuffix)
, Flag "dep-makefile" (hasArg setDepMakefile)
, Flag "include-pkg-deps" (noArg (setDepIncludePkgDeps True))
, Flag "exclude-module" (hasArg addDepExcludeMod)
-------- Linking ----------------------------------------------------
, Flag "no-link" (noArg (\d -> d{ ghcLink=NoLink }))
, Flag "shared" (noArg (\d -> d{ ghcLink=LinkDynLib }))
, Flag "staticlib" (noArg (\d -> d{ ghcLink=LinkStaticLib }))
, Flag "dynload" (hasArg parseDynLibLoaderMode)
, Flag "dylib-install-name" (hasArg setDylibInstallName)
-- -dll-split is an internal flag, used only during the GHC build
, Flag "dll-split" (hasArg (\f d -> d{ dllSplitFile = Just f, dllSplit = Nothing }))
------- Libraries ---------------------------------------------------
, Flag "L" (Prefix addLibraryPath)
, Flag "l" (hasArg (addLdInputs . Option . ("-l" ++)))
------- Frameworks --------------------------------------------------
-- -framework-path should really be -F ...
, Flag "framework-path" (HasArg addFrameworkPath)
, Flag "framework" (hasArg addCmdlineFramework)
------- Output Redirection ------------------------------------------
, Flag "odir" (hasArg setObjectDir)
, Flag "o" (sepArg (setOutputFile . Just))
, Flag "dyno" (sepArg (setDynOutputFile . Just))
, Flag "ohi" (hasArg (setOutputHi . Just ))
, Flag "osuf" (hasArg setObjectSuf)
, Flag "dynosuf" (hasArg setDynObjectSuf)
, Flag "hcsuf" (hasArg setHcSuf)
, Flag "hisuf" (hasArg setHiSuf)
, Flag "dynhisuf" (hasArg setDynHiSuf)
, Flag "hidir" (hasArg setHiDir)
, Flag "tmpdir" (hasArg setTmpDir)
, Flag "stubdir" (hasArg setStubDir)
, Flag "dumpdir" (hasArg setDumpDir)
, Flag "outputdir" (hasArg setOutputDir)
, Flag "ddump-file-prefix" (hasArg (setDumpPrefixForce . Just))
, Flag "dynamic-too" (NoArg (setGeneralFlag Opt_BuildDynamicToo))
------- Keeping temporary files -------------------------------------
-- These can be singular (think ghc -c) or plural (think ghc --make)
, Flag "keep-hc-file" (NoArg (setGeneralFlag Opt_KeepHcFiles))
, Flag "keep-hc-files" (NoArg (setGeneralFlag Opt_KeepHcFiles))
, Flag "keep-s-file" (NoArg (setGeneralFlag Opt_KeepSFiles))
, Flag "keep-s-files" (NoArg (setGeneralFlag Opt_KeepSFiles))
, Flag "keep-llvm-file" (NoArg (do setObjTarget HscLlvm
setGeneralFlag Opt_KeepLlvmFiles))
, Flag "keep-llvm-files" (NoArg (do setObjTarget HscLlvm
setGeneralFlag Opt_KeepLlvmFiles))
-- This only makes sense as plural
, Flag "keep-tmp-files" (NoArg (setGeneralFlag Opt_KeepTmpFiles))
------- Miscellaneous ----------------------------------------------
, Flag "no-auto-link-packages" (NoArg (unSetGeneralFlag Opt_AutoLinkPackages))
, Flag "no-hs-main" (NoArg (setGeneralFlag Opt_NoHsMain))
, Flag "with-rtsopts" (HasArg setRtsOpts)
, Flag "rtsopts" (NoArg (setRtsOptsEnabled RtsOptsAll))
, Flag "rtsopts=all" (NoArg (setRtsOptsEnabled RtsOptsAll))
, Flag "rtsopts=some" (NoArg (setRtsOptsEnabled RtsOptsSafeOnly))
, Flag "rtsopts=none" (NoArg (setRtsOptsEnabled RtsOptsNone))
, Flag "no-rtsopts" (NoArg (setRtsOptsEnabled RtsOptsNone))
, Flag "main-is" (SepArg setMainIs)
, Flag "haddock" (NoArg (setGeneralFlag Opt_Haddock))
, Flag "haddock-opts" (hasArg addHaddockOpts)
, Flag "hpcdir" (SepArg setOptHpcDir)
, Flag "ghci-script" (hasArg addGhciScript)
, Flag "interactive-print" (hasArg setInteractivePrint)
, Flag "ticky-allocd" (NoArg (setGeneralFlag Opt_Ticky_Allocd))
, Flag "ticky-LNE" (NoArg (setGeneralFlag Opt_Ticky_LNE))
, Flag "ticky-dyn-thunk" (NoArg (setGeneralFlag Opt_Ticky_Dyn_Thunk))
------- recompilation checker --------------------------------------
, Flag "recomp" (NoArg (do unSetGeneralFlag Opt_ForceRecomp
deprecate "Use -fno-force-recomp instead"))
, Flag "no-recomp" (NoArg (do setGeneralFlag Opt_ForceRecomp
deprecate "Use -fforce-recomp instead"))
------ HsCpp opts ---------------------------------------------------
, Flag "D" (AnySuffix (upd . addOptP))
, Flag "U" (AnySuffix (upd . addOptP))
------- Include/Import Paths ----------------------------------------
, Flag "I" (Prefix addIncludePath)
, Flag "i" (OptPrefix addImportPath)
------ Output style options -----------------------------------------
, Flag "dppr-user-length" (intSuffix (\n d -> d{ pprUserLength = n }))
, Flag "dppr-cols" (intSuffix (\n d -> d{ pprCols = n }))
, Flag "dtrace-level" (intSuffix (\n d -> d{ traceLevel = n }))
-- Suppress all that is suppressable in core dumps.
-- Except for uniques, as some simplifier phases introduce new varibles that
-- have otherwise identical names.
, Flag "dsuppress-all" (NoArg $ do setGeneralFlag Opt_SuppressCoercions
setGeneralFlag Opt_SuppressVarKinds
setGeneralFlag Opt_SuppressModulePrefixes
setGeneralFlag Opt_SuppressTypeApplications
setGeneralFlag Opt_SuppressIdInfo
setGeneralFlag Opt_SuppressTypeSignatures)
------ Debugging ----------------------------------------------------
, Flag "dstg-stats" (NoArg (setGeneralFlag Opt_StgStats))
, Flag "ddump-cmm" (setDumpFlag Opt_D_dump_cmm)
, Flag "ddump-cmm-raw" (setDumpFlag Opt_D_dump_cmm_raw)
, Flag "ddump-cmm-cfg" (setDumpFlag Opt_D_dump_cmm_cfg)
, Flag "ddump-cmm-cbe" (setDumpFlag Opt_D_dump_cmm_cbe)
, Flag "ddump-cmm-proc" (setDumpFlag Opt_D_dump_cmm_proc)
, Flag "ddump-cmm-sink" (setDumpFlag Opt_D_dump_cmm_sink)
, Flag "ddump-cmm-sp" (setDumpFlag Opt_D_dump_cmm_sp)
, Flag "ddump-cmm-procmap" (setDumpFlag Opt_D_dump_cmm_procmap)
, Flag "ddump-cmm-split" (setDumpFlag Opt_D_dump_cmm_split)
, Flag "ddump-cmm-info" (setDumpFlag Opt_D_dump_cmm_info)
, Flag "ddump-cmm-cps" (setDumpFlag Opt_D_dump_cmm_cps)
, Flag "ddump-core-stats" (setDumpFlag Opt_D_dump_core_stats)
, Flag "ddump-asm" (setDumpFlag Opt_D_dump_asm)
, Flag "ddump-asm-native" (setDumpFlag Opt_D_dump_asm_native)
, Flag "ddump-asm-liveness" (setDumpFlag Opt_D_dump_asm_liveness)
, Flag "ddump-asm-regalloc" (setDumpFlag Opt_D_dump_asm_regalloc)
, Flag "ddump-asm-conflicts" (setDumpFlag Opt_D_dump_asm_conflicts)
, Flag "ddump-asm-regalloc-stages" (setDumpFlag Opt_D_dump_asm_regalloc_stages)
, Flag "ddump-asm-stats" (setDumpFlag Opt_D_dump_asm_stats)
, Flag "ddump-asm-expanded" (setDumpFlag Opt_D_dump_asm_expanded)
, Flag "ddump-llvm" (NoArg (do setObjTarget HscLlvm
setDumpFlag' Opt_D_dump_llvm))
, Flag "ddump-deriv" (setDumpFlag Opt_D_dump_deriv)
, Flag "ddump-ds" (setDumpFlag Opt_D_dump_ds)
, Flag "ddump-foreign" (setDumpFlag Opt_D_dump_foreign)
, Flag "ddump-inlinings" (setDumpFlag Opt_D_dump_inlinings)
, Flag "ddump-rule-firings" (setDumpFlag Opt_D_dump_rule_firings)
, Flag "ddump-rule-rewrites" (setDumpFlag Opt_D_dump_rule_rewrites)
, Flag "ddump-simpl-trace" (setDumpFlag Opt_D_dump_simpl_trace)
, Flag "ddump-occur-anal" (setDumpFlag Opt_D_dump_occur_anal)
, Flag "ddump-parsed" (setDumpFlag Opt_D_dump_parsed)
, Flag "ddump-rn" (setDumpFlag Opt_D_dump_rn)
, Flag "ddump-core-pipeline" (setDumpFlag Opt_D_dump_core_pipeline)
, Flag "ddump-simpl" (setDumpFlag Opt_D_dump_simpl)
, Flag "ddump-simpl-iterations" (setDumpFlag Opt_D_dump_simpl_iterations)
, Flag "ddump-simpl-phases" (OptPrefix setDumpSimplPhases)
, Flag "ddump-spec" (setDumpFlag Opt_D_dump_spec)
, Flag "ddump-prep" (setDumpFlag Opt_D_dump_prep)
, Flag "ddump-stg" (setDumpFlag Opt_D_dump_stg)
, Flag "ddump-call-arity" (setDumpFlag Opt_D_dump_call_arity)
, Flag "ddump-stranal" (setDumpFlag Opt_D_dump_stranal)
, Flag "ddump-strsigs" (setDumpFlag Opt_D_dump_strsigs)
, Flag "ddump-tc" (setDumpFlag Opt_D_dump_tc)
, Flag "ddump-types" (setDumpFlag Opt_D_dump_types)
, Flag "ddump-rules" (setDumpFlag Opt_D_dump_rules)
, Flag "ddump-cse" (setDumpFlag Opt_D_dump_cse)
, Flag "ddump-worker-wrapper" (setDumpFlag Opt_D_dump_worker_wrapper)
, Flag "ddump-rn-trace" (setDumpFlag Opt_D_dump_rn_trace)
, Flag "ddump-if-trace" (setDumpFlag Opt_D_dump_if_trace)
, Flag "ddump-cs-trace" (setDumpFlag Opt_D_dump_cs_trace)
, Flag "ddump-tc-trace" (NoArg (do { setDumpFlag' Opt_D_dump_tc_trace
; setDumpFlag' Opt_D_dump_cs_trace }))
, Flag "ddump-vt-trace" (setDumpFlag Opt_D_dump_vt_trace)
, Flag "ddump-splices" (setDumpFlag Opt_D_dump_splices)
, Flag "ddump-rn-stats" (setDumpFlag Opt_D_dump_rn_stats)
, Flag "ddump-opt-cmm" (setDumpFlag Opt_D_dump_opt_cmm)
, Flag "ddump-simpl-stats" (setDumpFlag Opt_D_dump_simpl_stats)
, Flag "ddump-bcos" (setDumpFlag Opt_D_dump_BCOs)
, Flag "dsource-stats" (setDumpFlag Opt_D_source_stats)
, Flag "dverbose-core2core" (NoArg (do setVerbosity (Just 2)
setVerboseCore2Core))
, Flag "dverbose-stg2stg" (setDumpFlag Opt_D_verbose_stg2stg)
, Flag "ddump-hi" (setDumpFlag Opt_D_dump_hi)
, Flag "ddump-minimal-imports" (NoArg (setGeneralFlag Opt_D_dump_minimal_imports))
, Flag "ddump-vect" (setDumpFlag Opt_D_dump_vect)
, Flag "ddump-hpc" (setDumpFlag Opt_D_dump_ticked) -- back compat
, Flag "ddump-ticked" (setDumpFlag Opt_D_dump_ticked)
, Flag "ddump-mod-cycles" (setDumpFlag Opt_D_dump_mod_cycles)
, Flag "ddump-mod-map" (setDumpFlag Opt_D_dump_mod_map)
, Flag "ddump-view-pattern-commoning" (setDumpFlag Opt_D_dump_view_pattern_commoning)
, Flag "ddump-to-file" (NoArg (setGeneralFlag Opt_DumpToFile))
, Flag "ddump-hi-diffs" (setDumpFlag Opt_D_dump_hi_diffs)
, Flag "ddump-rtti" (setDumpFlag Opt_D_dump_rtti)
, Flag "dcore-lint" (NoArg (setGeneralFlag Opt_DoCoreLinting))
, Flag "dstg-lint" (NoArg (setGeneralFlag Opt_DoStgLinting))
, Flag "dcmm-lint" (NoArg (setGeneralFlag Opt_DoCmmLinting))
, Flag "dasm-lint" (NoArg (setGeneralFlag Opt_DoAsmLinting))
, Flag "dshow-passes" (NoArg (do forceRecompile
setVerbosity $ Just 2))
, Flag "dfaststring-stats" (NoArg (setGeneralFlag Opt_D_faststring_stats))
, Flag "dno-llvm-mangler" (NoArg (setGeneralFlag Opt_NoLlvmMangler)) -- hidden flag
------ Machine dependant (-m<blah>) stuff ---------------------------
, Flag "msse" (versionSuffix (\maj min d -> d{ sseVersion = Just (maj, min) }))
, Flag "mavx" (noArg (\d -> d{ avx = True }))
, Flag "mavx2" (noArg (\d -> d{ avx2 = True }))
, Flag "mavx512cd" (noArg (\d -> d{ avx512cd = True }))
, Flag "mavx512er" (noArg (\d -> d{ avx512er = True }))
, Flag "mavx512f" (noArg (\d -> d{ avx512f = True }))
, Flag "mavx512pf" (noArg (\d -> d{ avx512pf = True }))
------ Warning opts -------------------------------------------------
, Flag "W" (NoArg (mapM_ setWarningFlag minusWOpts))
, Flag "Werror" (NoArg (setGeneralFlag Opt_WarnIsError))
, Flag "Wwarn" (NoArg (unSetGeneralFlag Opt_WarnIsError))
, Flag "Wall" (NoArg (mapM_ setWarningFlag minusWallOpts))
, Flag "Wnot" (NoArg (do upd (\dfs -> dfs {warningFlags = IntSet.empty})
deprecate "Use -w instead"))
, Flag "w" (NoArg (upd (\dfs -> dfs {warningFlags = IntSet.empty})))
------ Plugin flags ------------------------------------------------
, Flag "fplugin-opt" (hasArg addPluginModuleNameOption)
, Flag "fplugin" (hasArg addPluginModuleName)
------ Optimisation flags ------------------------------------------
, Flag "O" (noArgM (setOptLevel 1))
, Flag "Onot" (noArgM (\dflags -> do deprecate "Use -O0 instead"
setOptLevel 0 dflags))
, Flag "Odph" (noArgM setDPHOpt)
, Flag "O" (optIntSuffixM (\mb_n -> setOptLevel (mb_n `orElse` 1)))
-- If the number is missing, use 1
, Flag "fmax-relevant-binds" (intSuffix (\n d -> d{ maxRelevantBinds = Just n }))
, Flag "fno-max-relevant-binds" (noArg (\d -> d{ maxRelevantBinds = Nothing }))
, Flag "fsimplifier-phases" (intSuffix (\n d -> d{ simplPhases = n }))
, Flag "fmax-simplifier-iterations" (intSuffix (\n d -> d{ maxSimplIterations = n }))
, Flag "fsimpl-tick-factor" (intSuffix (\n d -> d{ simplTickFactor = n }))
, Flag "fspec-constr-threshold" (intSuffix (\n d -> d{ specConstrThreshold = Just n }))
, Flag "fno-spec-constr-threshold" (noArg (\d -> d{ specConstrThreshold = Nothing }))
, Flag "fspec-constr-count" (intSuffix (\n d -> d{ specConstrCount = Just n }))
, Flag "fno-spec-constr-count" (noArg (\d -> d{ specConstrCount = Nothing }))
, Flag "fspec-constr-recursive" (intSuffix (\n d -> d{ specConstrRecursive = n }))
, Flag "fliberate-case-threshold" (intSuffix (\n d -> d{ liberateCaseThreshold = Just n }))
, Flag "fno-liberate-case-threshold" (noArg (\d -> d{ liberateCaseThreshold = Nothing }))
, Flag "frule-check" (sepArg (\s d -> d{ ruleCheck = Just s }))
, Flag "fcontext-stack" (intSuffix (\n d -> d{ ctxtStkDepth = n }))
, Flag "ftype-function-depth" (intSuffix (\n d -> d{ tyFunStkDepth = n }))
, Flag "fstrictness-before" (intSuffix (\n d -> d{ strictnessBefore = n : strictnessBefore d }))
, Flag "ffloat-lam-args" (intSuffix (\n d -> d{ floatLamArgs = Just n }))
, Flag "ffloat-all-lams" (noArg (\d -> d{ floatLamArgs = Nothing }))
, Flag "fhistory-size" (intSuffix (\n d -> d{ historySize = n }))
, Flag "funfolding-creation-threshold" (intSuffix (\n d -> d {ufCreationThreshold = n}))
, Flag "funfolding-use-threshold" (intSuffix (\n d -> d {ufUseThreshold = n}))
, Flag "funfolding-fun-discount" (intSuffix (\n d -> d {ufFunAppDiscount = n}))
, Flag "funfolding-dict-discount" (intSuffix (\n d -> d {ufDictDiscount = n}))
, Flag "funfolding-keeness-factor" (floatSuffix (\n d -> d {ufKeenessFactor = n}))
, Flag "fmax-worker-args" (intSuffix (\n d -> d {maxWorkerArgs = n}))
, Flag "fghci-hist-size" (intSuffix (\n d -> d {ghciHistSize = n}))
, Flag "fmax-inline-alloc-size" (intSuffix (\n d -> d{ maxInlineAllocSize = n }))
, Flag "fmax-inline-memcpy-insns" (intSuffix (\n d -> d{ maxInlineMemcpyInsns = n }))
, Flag "fmax-inline-memset-insns" (intSuffix (\n d -> d{ maxInlineMemsetInsns = n }))
------ Profiling ----------------------------------------------------
-- OLD profiling flags
, Flag "auto-all" (noArg (\d -> d { profAuto = ProfAutoAll } ))
, Flag "no-auto-all" (noArg (\d -> d { profAuto = NoProfAuto } ))
, Flag "auto" (noArg (\d -> d { profAuto = ProfAutoExports } ))
, Flag "no-auto" (noArg (\d -> d { profAuto = NoProfAuto } ))
, Flag "caf-all" (NoArg (setGeneralFlag Opt_AutoSccsOnIndividualCafs))
, Flag "no-caf-all" (NoArg (unSetGeneralFlag Opt_AutoSccsOnIndividualCafs))
-- NEW profiling flags
, Flag "fprof-auto" (noArg (\d -> d { profAuto = ProfAutoAll } ))
, Flag "fprof-auto-top" (noArg (\d -> d { profAuto = ProfAutoTop } ))
, Flag "fprof-auto-exported" (noArg (\d -> d { profAuto = ProfAutoExports } ))
, Flag "fprof-auto-calls" (noArg (\d -> d { profAuto = ProfAutoCalls } ))
, Flag "fno-prof-auto" (noArg (\d -> d { profAuto = NoProfAuto } ))
------ Compiler flags -----------------------------------------------
, Flag "fasm" (NoArg (setObjTarget HscAsm))
, Flag "fvia-c" (NoArg
(addWarn "The -fvia-c flag does nothing; it will be removed in a future GHC release"))
, Flag "fvia-C" (NoArg
(addWarn "The -fvia-C flag does nothing; it will be removed in a future GHC release"))
, Flag "fllvm" (NoArg (setObjTarget HscLlvm))
, Flag "fno-code" (NoArg (do upd $ \d -> d{ ghcLink=NoLink }
setTarget HscNothing))
, Flag "fbyte-code" (NoArg (setTarget HscInterpreted))
, Flag "fobject-code" (NoArg (setTargetWithPlatform defaultHscTarget))
, Flag "fglasgow-exts" (NoArg (enableGlasgowExts >> deprecate "Use individual extensions instead"))
, Flag "fno-glasgow-exts" (NoArg (disableGlasgowExts >> deprecate "Use individual extensions instead"))
------ Safe Haskell flags -------------------------------------------
, Flag "fpackage-trust" (NoArg setPackageTrust)
, Flag "fno-safe-infer" (noArg (\d -> d { safeInfer = False } ))
, Flag "fPIC" (NoArg (setGeneralFlag Opt_PIC))
, Flag "fno-PIC" (NoArg (unSetGeneralFlag Opt_PIC))
]
++ map (mkFlag turnOn "" setGeneralFlag ) negatableFlags
++ map (mkFlag turnOff "no-" unSetGeneralFlag) negatableFlags
++ map (mkFlag turnOn "d" setGeneralFlag ) dFlags
++ map (mkFlag turnOff "dno-" unSetGeneralFlag) dFlags
++ map (mkFlag turnOn "f" setGeneralFlag ) fFlags
++ map (mkFlag turnOff "fno-" unSetGeneralFlag) fFlags
++ map (mkFlag turnOn "f" setWarningFlag ) fWarningFlags
++ map (mkFlag turnOff "fno-" unSetWarningFlag) fWarningFlags
++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlags
++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlags
++ map (mkFlag turnOn "X" setExtensionFlag ) xFlags
++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlags
++ map (mkFlag turnOn "X" setLanguage) languageFlags
++ map (mkFlag turnOn "X" setSafeHaskell) safeHaskellFlags
++ [ Flag "XGenerics" (NoArg (deprecate "it does nothing; look into -XDefaultSignatures and -XDeriveGeneric for generic programming support."))
, Flag "XNoGenerics" (NoArg (deprecate "it does nothing; look into -XDefaultSignatures and -XDeriveGeneric for generic programming support.")) ]
package_flags :: [Flag (CmdLineP DynFlags)]
package_flags = [
------- Packages ----------------------------------------------------
Flag "package-db" (HasArg (addPkgConfRef . PkgConfFile))
, Flag "clear-package-db" (NoArg clearPkgConf)
, Flag "no-global-package-db" (NoArg removeGlobalPkgConf)
, Flag "no-user-package-db" (NoArg removeUserPkgConf)
, Flag "global-package-db" (NoArg (addPkgConfRef GlobalPkgConf))
, Flag "user-package-db" (NoArg (addPkgConfRef UserPkgConf))
-- backwards compat with GHC<=7.4 :
, Flag "package-conf" (HasArg $ \path -> do
addPkgConfRef (PkgConfFile path)
deprecate "Use -package-db instead")
, Flag "no-user-package-conf" (NoArg $ do
removeUserPkgConf
deprecate "Use -no-user-package-db instead")
, Flag "package-name" (HasArg $ \name -> do
upd (setPackageKey name)
deprecate "Use -this-package-key instead")
, Flag "this-package-key" (hasArg setPackageKey)
, Flag "package-id" (HasArg exposePackageId)
, Flag "package" (HasArg exposePackage)
, Flag "package-key" (HasArg exposePackageKey)
, Flag "hide-package" (HasArg hidePackage)
, Flag "hide-all-packages" (NoArg (setGeneralFlag Opt_HideAllPackages))
, Flag "ignore-package" (HasArg ignorePackage)
, Flag "syslib" (HasArg (\s -> do exposePackage s
deprecate "Use -package instead"))
, Flag "distrust-all-packages" (NoArg (setGeneralFlag Opt_DistrustAllPackages))
, Flag "trust" (HasArg trustPackage)
, Flag "distrust" (HasArg distrustPackage)
]
type TurnOnFlag = Bool -- True <=> we are turning the flag on
-- False <=> we are turning the flag off
turnOn :: TurnOnFlag; turnOn = True
turnOff :: TurnOnFlag; turnOff = False
type FlagSpec flag
= ( String -- Flag in string form
, flag -- Flag in internal form
, TurnOnFlag -> DynP ()) -- Extra action to run when the flag is found
-- Typically, emit a warning or error
mkFlag :: TurnOnFlag -- ^ True <=> it should be turned on
-> String -- ^ The flag prefix
-> (flag -> DynP ()) -- ^ What to do when the flag is found
-> FlagSpec flag -- ^ Specification of this particular flag
-> Flag (CmdLineP DynFlags)
mkFlag turn_on flagPrefix f (name, flag, extra_action)
= Flag (flagPrefix ++ name) (NoArg (f flag >> extra_action turn_on))
deprecatedForExtension :: String -> TurnOnFlag -> DynP ()
deprecatedForExtension lang turn_on
= deprecate ("use -X" ++ flag ++ " or pragma {-# LANGUAGE " ++ flag ++ " #-} instead")
where
flag | turn_on = lang
| otherwise = "No"++lang
useInstead :: String -> TurnOnFlag -> DynP ()
useInstead flag turn_on
= deprecate ("Use -f" ++ no ++ flag ++ " instead")
where
no = if turn_on then "" else "no-"
nop :: TurnOnFlag -> DynP ()
nop _ = return ()
-- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
fWarningFlags :: [FlagSpec WarningFlag]
fWarningFlags = [
( "warn-dodgy-foreign-imports", Opt_WarnDodgyForeignImports, nop ),
( "warn-dodgy-exports", Opt_WarnDodgyExports, nop ),
( "warn-dodgy-imports", Opt_WarnDodgyImports, nop ),
( "warn-overflowed-literals", Opt_WarnOverflowedLiterals, nop ),
( "warn-empty-enumerations", Opt_WarnEmptyEnumerations, nop ),
( "warn-duplicate-exports", Opt_WarnDuplicateExports, nop ),
( "warn-duplicate-constraints", Opt_WarnDuplicateConstraints, nop ),
( "warn-hi-shadowing", Opt_WarnHiShadows, nop ),
( "warn-implicit-prelude", Opt_WarnImplicitPrelude, nop ),
( "warn-incomplete-patterns", Opt_WarnIncompletePatterns, nop ),
( "warn-incomplete-uni-patterns", Opt_WarnIncompleteUniPatterns, nop ),
( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd, nop ),
( "warn-missing-fields", Opt_WarnMissingFields, nop ),
( "warn-missing-import-lists", Opt_WarnMissingImportList, nop ),
( "warn-missing-methods", Opt_WarnMissingMethods, nop ),
( "warn-missing-signatures", Opt_WarnMissingSigs, nop ),
( "warn-missing-local-sigs", Opt_WarnMissingLocalSigs, nop ),
( "warn-name-shadowing", Opt_WarnNameShadowing, nop ),
( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns, nop ),
( "warn-type-defaults", Opt_WarnTypeDefaults, nop ),
( "warn-monomorphism-restriction", Opt_WarnMonomorphism, nop ),
( "warn-unused-binds", Opt_WarnUnusedBinds, nop ),
( "warn-unused-imports", Opt_WarnUnusedImports, nop ),
( "warn-unused-matches", Opt_WarnUnusedMatches, nop ),
( "warn-warnings-deprecations", Opt_WarnWarningsDeprecations, nop ),
( "warn-deprecations", Opt_WarnWarningsDeprecations, nop ),
( "warn-deprecated-flags", Opt_WarnDeprecatedFlags, nop ),
( "warn-amp", Opt_WarnAMP,
\_ -> deprecate "it has no effect, and will be removed in GHC 7.12" ),
( "warn-orphans", Opt_WarnOrphans, nop ),
( "warn-identities", Opt_WarnIdentities, nop ),
( "warn-auto-orphans", Opt_WarnAutoOrphans, nop ),
( "warn-tabs", Opt_WarnTabs, nop ),
( "warn-typed-holes", Opt_WarnTypedHoles, nop ),
( "warn-unrecognised-pragmas", Opt_WarnUnrecognisedPragmas, nop ),
( "warn-unused-do-bind", Opt_WarnUnusedDoBind, nop ),
( "warn-wrong-do-bind", Opt_WarnWrongDoBind, nop ),
( "warn-alternative-layout-rule-transitional", Opt_WarnAlternativeLayoutRuleTransitional, nop ),
( "warn-unsafe", Opt_WarnUnsafe, setWarnUnsafe ),
( "warn-safe", Opt_WarnSafe, setWarnSafe ),
( "warn-pointless-pragmas", Opt_WarnPointlessPragmas, nop ),
( "warn-unsupported-calling-conventions", Opt_WarnUnsupportedCallingConventions, nop ),
( "warn-inline-rule-shadowing", Opt_WarnInlineRuleShadowing, nop ),
( "warn-unsupported-llvm-version", Opt_WarnUnsupportedLlvmVersion, nop ) ]
-- | These @-\<blah\>@ flags can all be reversed with @-no-\<blah\>@
negatableFlags :: [FlagSpec GeneralFlag]
negatableFlags = [
( "ignore-dot-ghci", Opt_IgnoreDotGhci, nop ) ]
-- | These @-d\<blah\>@ flags can all be reversed with @-dno-\<blah\>@
dFlags :: [FlagSpec GeneralFlag]
dFlags = [
( "suppress-coercions", Opt_SuppressCoercions, nop),
( "suppress-var-kinds", Opt_SuppressVarKinds, nop),
( "suppress-module-prefixes", Opt_SuppressModulePrefixes, nop),
( "suppress-type-applications", Opt_SuppressTypeApplications, nop),
( "suppress-idinfo", Opt_SuppressIdInfo, nop),
( "suppress-type-signatures", Opt_SuppressTypeSignatures, nop),
( "suppress-uniques", Opt_SuppressUniques, nop),
( "ppr-case-as-let", Opt_PprCaseAsLet, nop)]
-- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
fFlags :: [FlagSpec GeneralFlag]
fFlags = [
( "error-spans", Opt_ErrorSpans, nop ),
( "print-explicit-foralls", Opt_PrintExplicitForalls, nop ),
( "print-explicit-kinds", Opt_PrintExplicitKinds, nop ),
( "call-arity", Opt_CallArity, nop ),
( "strictness", Opt_Strictness, nop ),
( "late-dmd-anal", Opt_LateDmdAnal, nop ),
( "specialise", Opt_Specialise, nop ),
( "float-in", Opt_FloatIn, nop ),
( "static-argument-transformation", Opt_StaticArgumentTransformation, nop ),
( "full-laziness", Opt_FullLaziness, nop ),
( "liberate-case", Opt_LiberateCase, nop ),
( "spec-constr", Opt_SpecConstr, nop ),
( "cse", Opt_CSE, nop ),
( "pedantic-bottoms", Opt_PedanticBottoms, nop ),
( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas, nop ),
( "omit-interface-pragmas", Opt_OmitInterfacePragmas, nop ),
( "write-interface", Opt_WriteInterface, nop ),
( "expose-all-unfoldings", Opt_ExposeAllUnfoldings, nop ),
( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion, nop ),
( "ignore-asserts", Opt_IgnoreAsserts, nop ),
( "do-eta-reduction", Opt_DoEtaReduction, nop ),
( "case-merge", Opt_CaseMerge, nop ),
( "unbox-strict-fields", Opt_UnboxStrictFields, nop ),
( "unbox-small-strict-fields", Opt_UnboxSmallStrictFields, nop ),
( "dicts-cheap", Opt_DictsCheap, nop ),
( "excess-precision", Opt_ExcessPrecision, nop ),
( "eager-blackholing", Opt_EagerBlackHoling, nop ),
( "print-bind-result", Opt_PrintBindResult, nop ),
( "force-recomp", Opt_ForceRecomp, nop ),
( "hpc-no-auto", Opt_Hpc_No_Auto, nop ),
( "rewrite-rules", Opt_EnableRewriteRules, useInstead "enable-rewrite-rules" ),
( "enable-rewrite-rules", Opt_EnableRewriteRules, nop ),
( "break-on-exception", Opt_BreakOnException, nop ),
( "break-on-error", Opt_BreakOnError, nop ),
( "print-evld-with-show", Opt_PrintEvldWithShow, nop ),
( "print-bind-contents", Opt_PrintBindContents, nop ),
( "vectorise", Opt_Vectorise, nop ),
( "vectorisation-avoidance", Opt_VectorisationAvoidance, nop ),
( "regs-graph", Opt_RegsGraph, nop ),
( "regs-iterative", Opt_RegsIterative, nop ),
( "llvm-tbaa", Opt_LlvmTBAA, nop), -- hidden flag
( "llvm-pass-vectors-in-regs", Opt_LlvmPassVectorsInRegisters, nop), -- hidden flag
( "irrefutable-tuples", Opt_IrrefutableTuples, nop ),
( "cmm-sink", Opt_CmmSink, nop ),
( "cmm-elim-common-blocks", Opt_CmmElimCommonBlocks, nop ),
( "omit-yields", Opt_OmitYields, nop ),
( "simple-list-literals", Opt_SimpleListLiterals, nop ),
( "fun-to-thunk", Opt_FunToThunk, nop ),
( "gen-manifest", Opt_GenManifest, nop ),
( "embed-manifest", Opt_EmbedManifest, nop ),
( "ext-core", Opt_EmitExternalCore,
\_ -> deprecate "it has no effect, and will be removed in GHC 7.12" ),
( "shared-implib", Opt_SharedImplib, nop ),
( "ghci-sandbox", Opt_GhciSandbox, nop ),
( "ghci-history", Opt_GhciHistory, nop ),
( "helpful-errors", Opt_HelpfulErrors, nop ),
( "defer-type-errors", Opt_DeferTypeErrors, nop ),
( "building-cabal-package", Opt_BuildingCabalPackage, nop ),
( "implicit-import-qualified", Opt_ImplicitImportQualified, nop ),
( "prof-count-entries", Opt_ProfCountEntries, nop ),
( "prof-cafs", Opt_AutoSccsOnIndividualCafs, nop ),
( "hpc", Opt_Hpc, nop ),
( "pre-inlining", Opt_SimplPreInlining, nop ),
( "flat-cache", Opt_FlatCache, nop ),
( "use-rpaths", Opt_RPath, nop ),
( "kill-absence", Opt_KillAbsence, nop),
( "kill-one-shot", Opt_KillOneShot, nop),
( "dicts-strict", Opt_DictsStrict, nop ),
( "dmd-tx-dict-sel", Opt_DmdTxDictSel, nop ),
( "loopification", Opt_Loopification, nop )
]
-- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
fLangFlags :: [FlagSpec ExtensionFlag]
fLangFlags = [
( "th", Opt_TemplateHaskell,
\on -> deprecatedForExtension "TemplateHaskell" on
>> checkTemplateHaskellOk on ),
( "fi", Opt_ForeignFunctionInterface,
deprecatedForExtension "ForeignFunctionInterface" ),
( "ffi", Opt_ForeignFunctionInterface,
deprecatedForExtension "ForeignFunctionInterface" ),
( "arrows", Opt_Arrows,
deprecatedForExtension "Arrows" ),
( "implicit-prelude", Opt_ImplicitPrelude,
deprecatedForExtension "ImplicitPrelude" ),
( "bang-patterns", Opt_BangPatterns,
deprecatedForExtension "BangPatterns" ),
( "monomorphism-restriction", Opt_MonomorphismRestriction,
deprecatedForExtension "MonomorphismRestriction" ),
( "mono-pat-binds", Opt_MonoPatBinds,
deprecatedForExtension "MonoPatBinds" ),
( "extended-default-rules", Opt_ExtendedDefaultRules,
deprecatedForExtension "ExtendedDefaultRules" ),
( "implicit-params", Opt_ImplicitParams,
deprecatedForExtension "ImplicitParams" ),
( "scoped-type-variables", Opt_ScopedTypeVariables,
deprecatedForExtension "ScopedTypeVariables" ),
( "parr", Opt_ParallelArrays,
deprecatedForExtension "ParallelArrays" ),
( "PArr", Opt_ParallelArrays,
deprecatedForExtension "ParallelArrays" ),
( "allow-overlapping-instances", Opt_OverlappingInstances,
deprecatedForExtension "OverlappingInstances" ),
( "allow-undecidable-instances", Opt_UndecidableInstances,
deprecatedForExtension "UndecidableInstances" ),
( "allow-incoherent-instances", Opt_IncoherentInstances,
deprecatedForExtension "IncoherentInstances" )
]
supportedLanguages :: [String]
supportedLanguages = [ name | (name, _, _) <- languageFlags ]
supportedLanguageOverlays :: [String]
supportedLanguageOverlays = [ name | (name, _, _) <- safeHaskellFlags ]
supportedExtensions :: [String]
supportedExtensions = [ name' | (name, _, _) <- xFlags, name' <- [name, "No" ++ name] ]
supportedLanguagesAndExtensions :: [String]
supportedLanguagesAndExtensions =
supportedLanguages ++ supportedLanguageOverlays ++ supportedExtensions
-- | These -X<blah> flags cannot be reversed with -XNo<blah>
languageFlags :: [FlagSpec Language]
languageFlags = [
( "Haskell98", Haskell98, nop ),
( "Haskell2010", Haskell2010, nop )
]
-- | These -X<blah> flags cannot be reversed with -XNo<blah>
-- They are used to place hard requirements on what GHC Haskell language
-- features can be used.
safeHaskellFlags :: [FlagSpec SafeHaskellMode]
safeHaskellFlags = [mkF Sf_Unsafe, mkF Sf_Trustworthy, mkF Sf_Safe]
where mkF flag = (show flag, flag, nop)
-- | These -X<blah> flags can all be reversed with -XNo<blah>
xFlags :: [FlagSpec ExtensionFlag]
xFlags = [
( "CPP", Opt_Cpp, nop ),
( "PostfixOperators", Opt_PostfixOperators, nop ),
( "TupleSections", Opt_TupleSections, nop ),
( "PatternGuards", Opt_PatternGuards, nop ),
( "UnicodeSyntax", Opt_UnicodeSyntax, nop ),
( "MagicHash", Opt_MagicHash, nop ),
( "ExistentialQuantification", Opt_ExistentialQuantification, nop ),
( "KindSignatures", Opt_KindSignatures, nop ),
( "RoleAnnotations", Opt_RoleAnnotations, nop ),
( "EmptyDataDecls", Opt_EmptyDataDecls, nop ),
( "ParallelListComp", Opt_ParallelListComp, nop ),
( "TransformListComp", Opt_TransformListComp, nop ),
( "MonadComprehensions", Opt_MonadComprehensions, nop),
( "ForeignFunctionInterface", Opt_ForeignFunctionInterface, nop ),
( "UnliftedFFITypes", Opt_UnliftedFFITypes, nop ),
( "InterruptibleFFI", Opt_InterruptibleFFI, nop ),
( "CApiFFI", Opt_CApiFFI, nop ),
( "GHCForeignImportPrim", Opt_GHCForeignImportPrim, nop ),
( "JavaScriptFFI", Opt_JavaScriptFFI, nop ),
( "LiberalTypeSynonyms", Opt_LiberalTypeSynonyms, nop ),
( "PolymorphicComponents", Opt_RankNTypes, nop),
( "Rank2Types", Opt_RankNTypes, nop),
( "RankNTypes", Opt_RankNTypes, nop ),
( "ImpredicativeTypes", Opt_ImpredicativeTypes, nop),
( "TypeOperators", Opt_TypeOperators, nop ),
( "ExplicitNamespaces", Opt_ExplicitNamespaces, nop ),
( "RecursiveDo", Opt_RecursiveDo, nop ), -- Enables 'mdo' and 'rec'
( "DoRec", Opt_RecursiveDo,
deprecatedForExtension "RecursiveDo" ),
( "Arrows", Opt_Arrows, nop ),
( "ParallelArrays", Opt_ParallelArrays, nop ),
( "TemplateHaskell", Opt_TemplateHaskell, checkTemplateHaskellOk ),
( "QuasiQuotes", Opt_QuasiQuotes, nop ),
( "ImplicitPrelude", Opt_ImplicitPrelude, nop ),
( "RecordWildCards", Opt_RecordWildCards, nop ),
( "NamedFieldPuns", Opt_RecordPuns, nop ),
( "RecordPuns", Opt_RecordPuns,
deprecatedForExtension "NamedFieldPuns" ),
( "DisambiguateRecordFields", Opt_DisambiguateRecordFields, nop ),
( "OverloadedStrings", Opt_OverloadedStrings, nop ),
( "NumDecimals", Opt_NumDecimals, nop),
( "OverloadedLists", Opt_OverloadedLists, nop),
( "GADTs", Opt_GADTs, nop ),
( "GADTSyntax", Opt_GADTSyntax, nop ),
( "ViewPatterns", Opt_ViewPatterns, nop ),
( "TypeFamilies", Opt_TypeFamilies, nop ),
( "BangPatterns", Opt_BangPatterns, nop ),
( "MonomorphismRestriction", Opt_MonomorphismRestriction, nop ),
( "NPlusKPatterns", Opt_NPlusKPatterns, nop ),
( "DoAndIfThenElse", Opt_DoAndIfThenElse, nop ),
( "RebindableSyntax", Opt_RebindableSyntax, nop ),
( "ConstraintKinds", Opt_ConstraintKinds, nop ),
( "PolyKinds", Opt_PolyKinds, nop ),
( "DataKinds", Opt_DataKinds, nop ),
( "InstanceSigs", Opt_InstanceSigs, nop ),
( "MonoPatBinds", Opt_MonoPatBinds,
\ turn_on -> when turn_on $ deprecate "Experimental feature now removed; has no effect" ),
( "ExplicitForAll", Opt_ExplicitForAll, nop ),
( "AlternativeLayoutRule", Opt_AlternativeLayoutRule, nop ),
( "AlternativeLayoutRuleTransitional",Opt_AlternativeLayoutRuleTransitional, nop ),
( "DatatypeContexts", Opt_DatatypeContexts,
\ turn_on -> when turn_on $ deprecate "It was widely considered a misfeature, and has been removed from the Haskell language." ),
( "NondecreasingIndentation", Opt_NondecreasingIndentation, nop ),
( "RelaxedLayout", Opt_RelaxedLayout, nop ),
( "TraditionalRecordSyntax", Opt_TraditionalRecordSyntax, nop ),
( "LambdaCase", Opt_LambdaCase, nop ),
( "MultiWayIf", Opt_MultiWayIf, nop ),
( "MonoLocalBinds", Opt_MonoLocalBinds, nop ),
( "RelaxedPolyRec", Opt_RelaxedPolyRec,
\ turn_on -> unless turn_on
$ deprecate "You can't turn off RelaxedPolyRec any more" ),
( "ExtendedDefaultRules", Opt_ExtendedDefaultRules, nop ),
( "ImplicitParams", Opt_ImplicitParams, nop ),
( "ScopedTypeVariables", Opt_ScopedTypeVariables, nop ),
( "AllowAmbiguousTypes", Opt_AllowAmbiguousTypes, nop),
( "PatternSignatures", Opt_ScopedTypeVariables,
deprecatedForExtension "ScopedTypeVariables" ),
( "UnboxedTuples", Opt_UnboxedTuples, nop ),
( "StandaloneDeriving", Opt_StandaloneDeriving, nop ),
( "DeriveDataTypeable", Opt_DeriveDataTypeable, nop ),
( "AutoDeriveTypeable", Opt_AutoDeriveTypeable, nop ),
( "DeriveFunctor", Opt_DeriveFunctor, nop ),
( "DeriveTraversable", Opt_DeriveTraversable, nop ),
( "DeriveFoldable", Opt_DeriveFoldable, nop ),
( "DeriveGeneric", Opt_DeriveGeneric, nop ),
( "DefaultSignatures", Opt_DefaultSignatures, nop ),
( "TypeSynonymInstances", Opt_TypeSynonymInstances, nop ),
( "FlexibleContexts", Opt_FlexibleContexts, nop ),
( "FlexibleInstances", Opt_FlexibleInstances, nop ),
( "ConstrainedClassMethods", Opt_ConstrainedClassMethods, nop ),
( "MultiParamTypeClasses", Opt_MultiParamTypeClasses, nop ),
( "NullaryTypeClasses", Opt_NullaryTypeClasses,
deprecatedForExtension "MultiParamTypeClasses" ),
( "FunctionalDependencies", Opt_FunctionalDependencies, nop ),
( "GeneralizedNewtypeDeriving", Opt_GeneralizedNewtypeDeriving, setGenDeriving ),
( "OverlappingInstances", Opt_OverlappingInstances,
\ turn_on -> when turn_on
$ deprecate "instead use per-instance pragmas OVERLAPPING/OVERLAPPABLE/OVERLAPS" ),
( "UndecidableInstances", Opt_UndecidableInstances, nop ),
( "IncoherentInstances", Opt_IncoherentInstances, nop ),
( "PackageImports", Opt_PackageImports, nop ),
( "BinaryLiterals", Opt_BinaryLiterals, nop ),
( "NegativeLiterals", Opt_NegativeLiterals, nop ),
( "EmptyCase", Opt_EmptyCase, nop ),
( "PatternSynonyms", Opt_PatternSynonyms, nop )
]
defaultFlags :: Settings -> [GeneralFlag]
defaultFlags settings
= [ Opt_AutoLinkPackages,
Opt_SharedImplib,
Opt_OmitYields,
Opt_GenManifest,
Opt_EmbedManifest,
Opt_PrintBindContents,
Opt_GhciSandbox,
Opt_GhciHistory,
Opt_HelpfulErrors,
Opt_ProfCountEntries,
Opt_SimplPreInlining,
Opt_FlatCache,
Opt_RPath
]
++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
-- The default -O0 options
++ default_PIC platform
++ (if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings)
then wayGeneralFlags platform WayDyn
else [])
where platform = sTargetPlatform settings
default_PIC :: Platform -> [GeneralFlag]
default_PIC platform =
case (platformOS platform, platformArch platform) of
(OSDarwin, ArchX86_64) -> [Opt_PIC]
_ -> []
impliedFlags :: [(ExtensionFlag, TurnOnFlag, ExtensionFlag)]
impliedFlags
= [ (Opt_RankNTypes, turnOn, Opt_ExplicitForAll)
, (Opt_ScopedTypeVariables, turnOn, Opt_ExplicitForAll)
, (Opt_LiberalTypeSynonyms, turnOn, Opt_ExplicitForAll)
, (Opt_ExistentialQuantification, turnOn, Opt_ExplicitForAll)
, (Opt_FlexibleInstances, turnOn, Opt_TypeSynonymInstances)
, (Opt_FunctionalDependencies, turnOn, Opt_MultiParamTypeClasses)
, (Opt_RebindableSyntax, turnOff, Opt_ImplicitPrelude) -- NB: turn off!
, (Opt_GADTs, turnOn, Opt_GADTSyntax)
, (Opt_GADTs, turnOn, Opt_MonoLocalBinds)
, (Opt_TypeFamilies, turnOn, Opt_MonoLocalBinds)
, (Opt_TypeFamilies, turnOn, Opt_KindSignatures) -- Type families use kind signatures
, (Opt_PolyKinds, turnOn, Opt_KindSignatures) -- Ditto polymorphic kinds
-- AutoDeriveTypeable is not very useful without DeriveDataTypeable
, (Opt_AutoDeriveTypeable, turnOn, Opt_DeriveDataTypeable)
-- We turn this on so that we can export associated type
-- type synonyms in subordinates (e.g. MyClass(type AssocType))
, (Opt_TypeFamilies, turnOn, Opt_ExplicitNamespaces)
, (Opt_TypeOperators, turnOn, Opt_ExplicitNamespaces)
, (Opt_ImpredicativeTypes, turnOn, Opt_RankNTypes)
-- Record wild-cards implies field disambiguation
-- Otherwise if you write (C {..}) you may well get
-- stuff like " 'a' not in scope ", which is a bit silly
-- if the compiler has just filled in field 'a' of constructor 'C'
, (Opt_RecordWildCards, turnOn, Opt_DisambiguateRecordFields)
, (Opt_ParallelArrays, turnOn, Opt_ParallelListComp)
-- An implicit parameter constraint, `?x::Int`, is desugared into
-- `IP "x" Int`, which requires a flexible context/instance.
, (Opt_ImplicitParams, turnOn, Opt_FlexibleContexts)
, (Opt_ImplicitParams, turnOn, Opt_FlexibleInstances)
, (Opt_JavaScriptFFI, turnOn, Opt_InterruptibleFFI)
, (Opt_DeriveTraversable, turnOn, Opt_DeriveFunctor)
, (Opt_DeriveTraversable, turnOn, Opt_DeriveFoldable)
]
optLevelFlags :: [([Int], GeneralFlag)]
optLevelFlags
= [ ([0], Opt_IgnoreInterfacePragmas)
, ([0], Opt_OmitInterfacePragmas)
, ([1,2], Opt_IgnoreAsserts)
, ([1,2], Opt_EnableRewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
-- in PrelRules
, ([1,2], Opt_DoEtaReduction)
, ([1,2], Opt_CaseMerge)
, ([1,2], Opt_CallArity)
, ([1,2], Opt_Strictness)
, ([1,2], Opt_CSE)
, ([1,2], Opt_FullLaziness)
, ([1,2], Opt_Specialise)
, ([1,2], Opt_FloatIn)
, ([1,2], Opt_UnboxSmallStrictFields)
, ([2], Opt_LiberateCase)
, ([2], Opt_SpecConstr)
-- XXX disabled, see #7192
-- , ([2], Opt_RegsGraph)
, ([0,1,2], Opt_LlvmTBAA)
, ([1,2], Opt_CmmSink)
, ([1,2], Opt_CmmElimCommonBlocks)
, ([1,2], Opt_Loopification)
, ([0,1,2], Opt_DmdTxDictSel)
-- , ([2], Opt_StaticArgumentTransformation)
-- Max writes: I think it's probably best not to enable SAT with -O2 for the
-- 6.10 release. The version of SAT in HEAD at the moment doesn't incorporate
-- several improvements to the heuristics, and I'm concerned that without
-- those changes SAT will interfere with some attempts to write "high
-- performance Haskell", as we saw in some posts on Haskell-Cafe earlier
-- this year. In particular, the version in HEAD lacks the tail call
-- criterion, so many things that look like reasonable loops will be
-- turned into functions with extra (unneccesary) thunk creation.
, ([0,1,2], Opt_DoLambdaEtaExpansion)
-- This one is important for a tiresome reason:
-- we want to make sure that the bindings for data
-- constructors are eta-expanded. This is probably
-- a good thing anyway, but it seems fragile.
, ([0,1,2], Opt_VectorisationAvoidance)
]
-- -----------------------------------------------------------------------------
-- Standard sets of warning options
standardWarnings :: [WarningFlag]
standardWarnings
= [ Opt_WarnOverlappingPatterns,
Opt_WarnWarningsDeprecations,
Opt_WarnDeprecatedFlags,
Opt_WarnTypedHoles,
Opt_WarnUnrecognisedPragmas,
Opt_WarnPointlessPragmas,
Opt_WarnDuplicateConstraints,
Opt_WarnDuplicateExports,
Opt_WarnOverflowedLiterals,
Opt_WarnEmptyEnumerations,
Opt_WarnMissingFields,
Opt_WarnMissingMethods,
Opt_WarnWrongDoBind,
Opt_WarnUnsupportedCallingConventions,
Opt_WarnDodgyForeignImports,
Opt_WarnInlineRuleShadowing,
Opt_WarnAlternativeLayoutRuleTransitional,
Opt_WarnUnsupportedLlvmVersion
]
minusWOpts :: [WarningFlag]
-- Things you get with -W
minusWOpts
= standardWarnings ++
[ Opt_WarnUnusedBinds,
Opt_WarnUnusedMatches,
Opt_WarnUnusedImports,
Opt_WarnIncompletePatterns,
Opt_WarnDodgyExports,
Opt_WarnDodgyImports
]
minusWallOpts :: [WarningFlag]
-- Things you get with -Wall
minusWallOpts
= minusWOpts ++
[ Opt_WarnTypeDefaults,
Opt_WarnNameShadowing,
Opt_WarnMissingSigs,
Opt_WarnHiShadows,
Opt_WarnOrphans,
Opt_WarnUnusedDoBind
]
enableGlasgowExts :: DynP ()
enableGlasgowExts = do setGeneralFlag Opt_PrintExplicitForalls
mapM_ setExtensionFlag glasgowExtsFlags
disableGlasgowExts :: DynP ()
disableGlasgowExts = do unSetGeneralFlag Opt_PrintExplicitForalls
mapM_ unSetExtensionFlag glasgowExtsFlags
glasgowExtsFlags :: [ExtensionFlag]
glasgowExtsFlags = [
Opt_ForeignFunctionInterface
, Opt_UnliftedFFITypes
, Opt_ImplicitParams
, Opt_ScopedTypeVariables
, Opt_UnboxedTuples
, Opt_TypeSynonymInstances
, Opt_StandaloneDeriving
, Opt_DeriveDataTypeable
, Opt_DeriveFunctor
, Opt_DeriveFoldable
, Opt_DeriveTraversable
, Opt_DeriveGeneric
, Opt_FlexibleContexts
, Opt_FlexibleInstances
, Opt_ConstrainedClassMethods
, Opt_MultiParamTypeClasses
, Opt_FunctionalDependencies
, Opt_MagicHash
, Opt_ExistentialQuantification
, Opt_UnicodeSyntax
, Opt_PostfixOperators
, Opt_PatternGuards
, Opt_LiberalTypeSynonyms
, Opt_RankNTypes
, Opt_TypeOperators
, Opt_ExplicitNamespaces
, Opt_RecursiveDo
, Opt_ParallelListComp
, Opt_EmptyDataDecls
, Opt_KindSignatures
, Opt_GeneralizedNewtypeDeriving ]
#ifdef GHCI
-- Consult the RTS to find whether GHC itself has been built profiled
-- If so, you can't use Template Haskell
foreign import ccall unsafe "rts_isProfiled" rtsIsProfiledIO :: IO CInt
rtsIsProfiled :: Bool
rtsIsProfiled = unsafeDupablePerformIO rtsIsProfiledIO /= 0
#endif
#ifdef GHCI
-- Consult the RTS to find whether GHC itself has been built with
-- dynamic linking. This can't be statically known at compile-time,
-- because we build both the static and dynamic versions together with
-- -dynamic-too.
foreign import ccall unsafe "rts_isDynamic" rtsIsDynamicIO :: IO CInt
dynamicGhc :: Bool
dynamicGhc = unsafeDupablePerformIO rtsIsDynamicIO /= 0
#else
dynamicGhc :: Bool
dynamicGhc = False
#endif
setWarnSafe :: Bool -> DynP ()
setWarnSafe True = getCurLoc >>= \l -> upd (\d -> d { warnSafeOnLoc = l })
setWarnSafe False = return ()
setWarnUnsafe :: Bool -> DynP ()
setWarnUnsafe True = getCurLoc >>= \l -> upd (\d -> d { warnUnsafeOnLoc = l })
setWarnUnsafe False = return ()
setPackageTrust :: DynP ()
setPackageTrust = do
setGeneralFlag Opt_PackageTrust
l <- getCurLoc
upd $ \d -> d { pkgTrustOnLoc = l }
setGenDeriving :: TurnOnFlag -> DynP ()
setGenDeriving True = getCurLoc >>= \l -> upd (\d -> d { newDerivOnLoc = l })
setGenDeriving False = return ()
checkTemplateHaskellOk :: TurnOnFlag -> DynP ()
#ifdef GHCI
checkTemplateHaskellOk turn_on
| turn_on && rtsIsProfiled
= addErr "You can't use Template Haskell with a profiled compiler"
| otherwise
= getCurLoc >>= \l -> upd (\d -> d { thOnLoc = l })
#else
-- In stage 1, Template Haskell is simply illegal, except with -M
-- We don't bleat with -M because there's no problem with TH there,
-- and in fact GHC's build system does ghc -M of the DPH libraries
-- with a stage1 compiler
checkTemplateHaskellOk turn_on
| turn_on = do dfs <- liftEwM getCmdLineState
case ghcMode dfs of
MkDepend -> return ()
_ -> addErr msg
| otherwise = return ()
where
msg = "Template Haskell requires GHC with interpreter support\n Perhaps you are using a stage-1 compiler?"
#endif
{- **********************************************************************
%* *
DynFlags constructors
%* *
%********************************************************************* -}
type DynP = EwM (CmdLineP DynFlags)
upd :: (DynFlags -> DynFlags) -> DynP ()
upd f = liftEwM (do dflags <- getCmdLineState
putCmdLineState $! f dflags)
updM :: (DynFlags -> DynP DynFlags) -> DynP ()
updM f = do dflags <- liftEwM getCmdLineState
dflags' <- f dflags
liftEwM $ putCmdLineState $! dflags'
--------------- Constructor functions for OptKind -----------------
noArg :: (DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
noArg fn = NoArg (upd fn)
noArgM :: (DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags)
noArgM fn = NoArg (updM fn)
hasArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
hasArg fn = HasArg (upd . fn)
sepArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
sepArg fn = SepArg (upd . fn)
intSuffix :: (Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
intSuffix fn = IntSuffix (\n -> upd (fn n))
floatSuffix :: (Float -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
floatSuffix fn = FloatSuffix (\n -> upd (fn n))
optIntSuffixM :: (Maybe Int -> DynFlags -> DynP DynFlags)
-> OptKind (CmdLineP DynFlags)
optIntSuffixM fn = OptIntSuffix (\mi -> updM (fn mi))
versionSuffix :: (Int -> Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
versionSuffix fn = VersionSuffix (\maj min -> upd (fn maj min))
setDumpFlag :: DumpFlag -> OptKind (CmdLineP DynFlags)
setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag)
--------------------------
addWay :: Way -> DynP ()
addWay w = upd (addWay' w)
addWay' :: Way -> DynFlags -> DynFlags
addWay' w dflags0 = let platform = targetPlatform dflags0
dflags1 = dflags0 { ways = w : ways dflags0 }
dflags2 = wayExtras platform w dflags1
dflags3 = foldr setGeneralFlag' dflags2
(wayGeneralFlags platform w)
dflags4 = foldr unSetGeneralFlag' dflags3
(wayUnsetGeneralFlags platform w)
in dflags4
removeWayDyn :: DynP ()
removeWayDyn = upd (\dfs -> dfs { ways = filter (WayDyn /=) (ways dfs) })
--------------------------
setGeneralFlag, unSetGeneralFlag :: GeneralFlag -> DynP ()
setGeneralFlag f = upd (setGeneralFlag' f)
unSetGeneralFlag f = upd (unSetGeneralFlag' f)
setGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags
setGeneralFlag' f dflags = gopt_set dflags f
unSetGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags
unSetGeneralFlag' f dflags = gopt_unset dflags f
--------------------------
setWarningFlag, unSetWarningFlag :: WarningFlag -> DynP ()
setWarningFlag f = upd (\dfs -> wopt_set dfs f)
unSetWarningFlag f = upd (\dfs -> wopt_unset dfs f)
--------------------------
setExtensionFlag, unSetExtensionFlag :: ExtensionFlag -> DynP ()
setExtensionFlag f = upd (setExtensionFlag' f)
unSetExtensionFlag f = upd (unSetExtensionFlag' f)
setExtensionFlag', unSetExtensionFlag' :: ExtensionFlag -> DynFlags -> DynFlags
setExtensionFlag' f dflags = foldr ($) (xopt_set dflags f) deps
where
deps = [ if turn_on then setExtensionFlag' d
else unSetExtensionFlag' d
| (f', turn_on, d) <- impliedFlags, f' == f ]
-- When you set f, set the ones it implies
-- NB: use setExtensionFlag recursively, in case the implied flags
-- implies further flags
unSetExtensionFlag' f dflags = xopt_unset dflags f
-- When you un-set f, however, we don't un-set the things it implies
-- (except for -fno-glasgow-exts, which is treated specially)
--------------------------
alterSettings :: (Settings -> Settings) -> DynFlags -> DynFlags
alterSettings f dflags = dflags { settings = f (settings dflags) }
--------------------------
setDumpFlag' :: DumpFlag -> DynP ()
setDumpFlag' dump_flag
= do upd (\dfs -> dopt_set dfs dump_flag)
when want_recomp forceRecompile
where -- Certain dumpy-things are really interested in what's going
-- on during recompilation checking, so in those cases we
-- don't want to turn it off.
want_recomp = dump_flag `notElem` [Opt_D_dump_if_trace,
Opt_D_dump_hi_diffs]
forceRecompile :: DynP ()
-- Whenver we -ddump, force recompilation (by switching off the
-- recompilation checker), else you don't see the dump! However,
-- don't switch it off in --make mode, else *everything* gets
-- recompiled which probably isn't what you want
forceRecompile = do dfs <- liftEwM getCmdLineState
when (force_recomp dfs) (setGeneralFlag Opt_ForceRecomp)
where
force_recomp dfs = isOneShot (ghcMode dfs)
setVerboseCore2Core :: DynP ()
setVerboseCore2Core = do setDumpFlag' Opt_D_verbose_core2core
upd (\dfs -> dfs { shouldDumpSimplPhase = Nothing })
setDumpSimplPhases :: String -> DynP ()
setDumpSimplPhases s = do forceRecompile
upd (\dfs -> dfs { shouldDumpSimplPhase = Just spec })
where
spec = case s of { ('=' : s') -> s'; _ -> s }
setVerbosity :: Maybe Int -> DynP ()
setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
addCmdlineHCInclude :: String -> DynP ()
addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
data PkgConfRef
= GlobalPkgConf
| UserPkgConf
| PkgConfFile FilePath
addPkgConfRef :: PkgConfRef -> DynP ()
addPkgConfRef p = upd $ \s -> s { extraPkgConfs = (p:) . extraPkgConfs s }
removeUserPkgConf :: DynP ()
removeUserPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotUser . extraPkgConfs s }
where
isNotUser UserPkgConf = False
isNotUser _ = True
removeGlobalPkgConf :: DynP ()
removeGlobalPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotGlobal . extraPkgConfs s }
where
isNotGlobal GlobalPkgConf = False
isNotGlobal _ = True
clearPkgConf :: DynP ()
clearPkgConf = upd $ \s -> s { extraPkgConfs = const [] }
parsePackageFlag :: (String -> PackageArg) -- type of argument
-> String -- string to parse
-> PackageFlag
parsePackageFlag constr str = case filter ((=="").snd) (readP_to_S parse str) of
[(r, "")] -> r
_ -> throwGhcException $ CmdLineError ("Can't parse package flag: " ++ str)
where parse = do
pkg <- munch1 (\c -> isAlphaNum c || c `elem` ":-_.")
(do _ <- tok $ R.char '('
rns <- tok $ sepBy parseItem (tok $ R.char ',')
_ <- tok $ R.char ')'
return (ExposePackage (constr pkg) (Just rns))
+++
return (ExposePackage (constr pkg) Nothing))
parseMod = munch1 (\c -> isAlphaNum c || c `elem` ".")
parseItem = do
orig <- tok $ parseMod
(do _ <- tok $ string "as"
new <- tok $ parseMod
return (orig, new)
+++
return (orig, orig))
tok m = skipSpaces >> m
exposePackage, exposePackageId, exposePackageKey, hidePackage, ignorePackage,
trustPackage, distrustPackage :: String -> DynP ()
exposePackage p = upd (exposePackage' p)
exposePackageId p =
upd (\s -> s{ packageFlags =
parsePackageFlag PackageIdArg p : packageFlags s })
exposePackageKey p =
upd (\s -> s{ packageFlags =
parsePackageFlag PackageKeyArg p : packageFlags s })
hidePackage p =
upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
ignorePackage p =
upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
trustPackage p = exposePackage p >> -- both trust and distrust also expose a package
upd (\s -> s{ packageFlags = TrustPackage p : packageFlags s })
distrustPackage p = exposePackage p >>
upd (\s -> s{ packageFlags = DistrustPackage p : packageFlags s })
exposePackage' :: String -> DynFlags -> DynFlags
exposePackage' p dflags
= dflags { packageFlags =
parsePackageFlag PackageArg p : packageFlags dflags }
setPackageKey :: String -> DynFlags -> DynFlags
setPackageKey p s = s{ thisPackage = stringToPackageKey p }
-- If we're linking a binary, then only targets that produce object
-- code are allowed (requests for other target types are ignored).
setTarget :: HscTarget -> DynP ()
setTarget l = setTargetWithPlatform (const l)
setTargetWithPlatform :: (Platform -> HscTarget) -> DynP ()
setTargetWithPlatform f = upd set
where
set dfs = let l = f (targetPlatform dfs)
in if ghcLink dfs /= LinkBinary || isObjectTarget l
then dfs{ hscTarget = l }
else dfs
-- Changes the target only if we're compiling object code. This is
-- used by -fasm and -fllvm, which switch from one to the other, but
-- not from bytecode to object-code. The idea is that -fasm/-fllvm
-- can be safely used in an OPTIONS_GHC pragma.
setObjTarget :: HscTarget -> DynP ()
setObjTarget l = updM set
where
set dflags
| isObjectTarget (hscTarget dflags)
= return $ dflags { hscTarget = l }
| otherwise = return dflags
setOptLevel :: Int -> DynFlags -> DynP DynFlags
setOptLevel n dflags
| hscTarget dflags == HscInterpreted && n > 0
= do addWarn "-O conflicts with --interactive; -O ignored."
return dflags
| otherwise
= return (updOptLevel n dflags)
-- -Odph is equivalent to
--
-- -O2 optimise as much as possible
-- -fmax-simplifier-iterations20 this is necessary sometimes
-- -fsimplifier-phases=3 we use an additional simplifier phase for fusion
--
setDPHOpt :: DynFlags -> DynP DynFlags
setDPHOpt dflags = setOptLevel 2 (dflags { maxSimplIterations = 20
, simplPhases = 3
})
setMainIs :: String -> DynP ()
setMainIs arg
| not (null main_fn) && isLower (head main_fn)
-- The arg looked like "Foo.Bar.baz"
= upd $ \d -> d{ mainFunIs = Just main_fn,
mainModIs = mkModule mainPackageKey (mkModuleName main_mod) }
| isUpper (head arg) -- The arg looked like "Foo" or "Foo.Bar"
= upd $ \d -> d{ mainModIs = mkModule mainPackageKey (mkModuleName arg) }
| otherwise -- The arg looked like "baz"
= upd $ \d -> d{ mainFunIs = Just arg }
where
(main_mod, main_fn) = splitLongestPrefix arg (== '.')
addLdInputs :: Option -> DynFlags -> DynFlags
addLdInputs p dflags = dflags{ldInputs = ldInputs dflags ++ [p]}
-----------------------------------------------------------------------------
-- Paths & Libraries
addImportPath, addLibraryPath, addIncludePath, addFrameworkPath :: FilePath -> DynP ()
-- -i on its own deletes the import paths
addImportPath "" = upd (\s -> s{importPaths = []})
addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
addLibraryPath p =
upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
addIncludePath p =
upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
addFrameworkPath p =
upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
#ifndef mingw32_TARGET_OS
split_marker :: Char
split_marker = ':' -- not configurable (ToDo)
#endif
splitPathList :: String -> [String]
splitPathList s = filter notNull (splitUp s)
-- empty paths are ignored: there might be a trailing
-- ':' in the initial list, for example. Empty paths can
-- cause confusion when they are translated into -I options
-- for passing to gcc.
where
#ifndef mingw32_TARGET_OS
splitUp xs = split split_marker xs
#else
-- Windows: 'hybrid' support for DOS-style paths in directory lists.
--
-- That is, if "foo:bar:baz" is used, this interpreted as
-- consisting of three entries, 'foo', 'bar', 'baz'.
-- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
-- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
--
-- Notice that no attempt is made to fully replace the 'standard'
-- split marker ':' with the Windows / DOS one, ';'. The reason being
-- that this will cause too much breakage for users & ':' will
-- work fine even with DOS paths, if you're not insisting on being silly.
-- So, use either.
splitUp [] = []
splitUp (x:':':div:xs) | div `elem` dir_markers
= ((x:':':div:p): splitUp rs)
where
(p,rs) = findNextPath xs
-- we used to check for existence of the path here, but that
-- required the IO monad to be threaded through the command-line
-- parser which is quite inconvenient. The
splitUp xs = cons p (splitUp rs)
where
(p,rs) = findNextPath xs
cons "" xs = xs
cons x xs = x:xs
-- will be called either when we've consumed nought or the
-- "<Drive>:/" part of a DOS path, so splitting is just a Q of
-- finding the next split marker.
findNextPath xs =
case break (`elem` split_markers) xs of
(p, _:ds) -> (p, ds)
(p, xs) -> (p, xs)
split_markers :: [Char]
split_markers = [':', ';']
dir_markers :: [Char]
dir_markers = ['/', '\\']
#endif
-- -----------------------------------------------------------------------------
-- tmpDir, where we store temporary files.
setTmpDir :: FilePath -> DynFlags -> DynFlags
setTmpDir dir = alterSettings (\s -> s { sTmpDir = normalise dir })
-- we used to fix /cygdrive/c/.. on Windows, but this doesn't
-- seem necessary now --SDM 7/2/2008
-----------------------------------------------------------------------------
-- RTS opts
setRtsOpts :: String -> DynP ()
setRtsOpts arg = upd $ \ d -> d {rtsOpts = Just arg}
setRtsOptsEnabled :: RtsOptsEnabled -> DynP ()
setRtsOptsEnabled arg = upd $ \ d -> d {rtsOptsEnabled = arg}
-----------------------------------------------------------------------------
-- Hpc stuff
setOptHpcDir :: String -> DynP ()
setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
-----------------------------------------------------------------------------
-- Via-C compilation stuff
-- There are some options that we need to pass to gcc when compiling
-- Haskell code via C, but are only supported by recent versions of
-- gcc. The configure script decides which of these options we need,
-- and puts them in the "settings" file in $topdir. The advantage of
-- having these in a separate file is that the file can be created at
-- install-time depending on the available gcc version, and even
-- re-generated later if gcc is upgraded.
--
-- The options below are not dependent on the version of gcc, only the
-- platform.
picCCOpts :: DynFlags -> [String]
picCCOpts dflags
= case platformOS (targetPlatform dflags) of
OSDarwin
-- Apple prefers to do things the other way round.
-- PIC is on by default.
-- -mdynamic-no-pic:
-- Turn off PIC code generation.
-- -fno-common:
-- Don't generate "common" symbols - these are unwanted
-- in dynamic libraries.
| gopt Opt_PIC dflags -> ["-fno-common", "-U__PIC__", "-D__PIC__"]
| otherwise -> ["-mdynamic-no-pic"]
OSMinGW32 -- no -fPIC for Windows
| gopt Opt_PIC dflags -> ["-U__PIC__", "-D__PIC__"]
| otherwise -> []
_
-- we need -fPIC for C files when we are compiling with -dynamic,
-- otherwise things like stub.c files don't get compiled
-- correctly. They need to reference data in the Haskell
-- objects, but can't without -fPIC. See
-- http://ghc.haskell.org/trac/ghc/wiki/Commentary/PositionIndependentCode
| gopt Opt_PIC dflags || not (gopt Opt_Static dflags) ->
["-fPIC", "-U__PIC__", "-D__PIC__"]
| otherwise -> []
picPOpts :: DynFlags -> [String]
picPOpts dflags
| gopt Opt_PIC dflags = ["-U__PIC__", "-D__PIC__"]
| otherwise = []
-- -----------------------------------------------------------------------------
-- Splitting
can_split :: Bool
can_split = cSupportsSplitObjs == "YES"
-- -----------------------------------------------------------------------------
-- Compiler Info
compilerInfo :: DynFlags -> [(String, String)]
compilerInfo dflags
= -- We always make "Project name" be first to keep parsing in
-- other languages simple, i.e. when looking for other fields,
-- you don't have to worry whether there is a leading '[' or not
("Project name", cProjectName)
-- Next come the settings, so anything else can be overridden
-- in the settings file (as "lookup" uses the first match for the
-- key)
: rawSettings dflags
++ [("Project version", cProjectVersion),
("Booter version", cBooterVersion),
("Stage", cStage),
("Build platform", cBuildPlatformString),
("Host platform", cHostPlatformString),
("Target platform", cTargetPlatformString),
("Have interpreter", cGhcWithInterpreter),
("Object splitting supported", cSupportsSplitObjs),
("Have native code generator", cGhcWithNativeCodeGen),
("Support SMP", cGhcWithSMP),
("Tables next to code", cGhcEnableTablesNextToCode),
("RTS ways", cGhcRTSWays),
("Support dynamic-too", if isWindows then "NO" else "YES"),
("Support parallel --make", "YES"),
("Support reexported-modules", "YES"),
("Uses package keys", "YES"),
("Dynamic by default", if dYNAMIC_BY_DEFAULT dflags
then "YES" else "NO"),
("GHC Dynamic", if dynamicGhc
then "YES" else "NO"),
("Leading underscore", cLeadingUnderscore),
("Debug on", show debugIsOn),
("LibDir", topDir dflags),
("Global Package DB", systemPackageConfig dflags)
]
where
isWindows = platformOS (targetPlatform dflags) == OSMinGW32
#include "../includes/dist-derivedconstants/header/GHCConstantsHaskellWrappers.hs"
bLOCK_SIZE_W :: DynFlags -> Int
bLOCK_SIZE_W dflags = bLOCK_SIZE dflags `quot` wORD_SIZE dflags
wORD_SIZE_IN_BITS :: DynFlags -> Int
wORD_SIZE_IN_BITS dflags = wORD_SIZE dflags * 8
tAG_MASK :: DynFlags -> Int
tAG_MASK dflags = (1 `shiftL` tAG_BITS dflags) - 1
mAX_PTR_TAG :: DynFlags -> Int
mAX_PTR_TAG = tAG_MASK
-- Might be worth caching these in targetPlatform?
tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD :: DynFlags -> Integer
tARGET_MIN_INT dflags
= case platformWordSize (targetPlatform dflags) of
4 -> toInteger (minBound :: Int32)
8 -> toInteger (minBound :: Int64)
w -> panic ("tARGET_MIN_INT: Unknown platformWordSize: " ++ show w)
tARGET_MAX_INT dflags
= case platformWordSize (targetPlatform dflags) of
4 -> toInteger (maxBound :: Int32)
8 -> toInteger (maxBound :: Int64)
w -> panic ("tARGET_MAX_INT: Unknown platformWordSize: " ++ show w)
tARGET_MAX_WORD dflags
= case platformWordSize (targetPlatform dflags) of
4 -> toInteger (maxBound :: Word32)
8 -> toInteger (maxBound :: Word64)
w -> panic ("tARGET_MAX_WORD: Unknown platformWordSize: " ++ show w)
-- Whenever makeDynFlagsConsistent does anything, it starts over, to
-- ensure that a later change doesn't invalidate an earlier check.
-- Be careful not to introduce potential loops!
makeDynFlagsConsistent :: DynFlags -> (DynFlags, [Located String])
makeDynFlagsConsistent dflags
-- Disable -dynamic-too on Windows (#8228, #7134, #5987)
| os == OSMinGW32 && gopt Opt_BuildDynamicToo dflags
= let dflags' = gopt_unset dflags Opt_BuildDynamicToo
warn = "-dynamic-too is not supported on Windows"
in loop dflags' warn
| hscTarget dflags == HscC &&
not (platformUnregisterised (targetPlatform dflags))
= if cGhcWithNativeCodeGen == "YES"
then let dflags' = dflags { hscTarget = HscAsm }
warn = "Compiler not unregisterised, so using native code generator rather than compiling via C"
in loop dflags' warn
else let dflags' = dflags { hscTarget = HscLlvm }
warn = "Compiler not unregisterised, so using LLVM rather than compiling via C"
in loop dflags' warn
| hscTarget dflags == HscAsm &&
platformUnregisterised (targetPlatform dflags)
= loop (dflags { hscTarget = HscC })
"Compiler unregisterised, so compiling via C"
| hscTarget dflags == HscAsm &&
cGhcWithNativeCodeGen /= "YES"
= let dflags' = dflags { hscTarget = HscLlvm }
warn = "No native code generator, so using LLVM"
in loop dflags' warn
| hscTarget dflags == HscLlvm &&
not ((arch == ArchX86_64) && (os == OSLinux || os == OSDarwin || os == OSFreeBSD)) &&
not ((isARM arch) && (os == OSLinux)) &&
(not (gopt Opt_Static dflags) || gopt Opt_PIC dflags)
= if cGhcWithNativeCodeGen == "YES"
then let dflags' = dflags { hscTarget = HscAsm }
warn = "Using native code generator rather than LLVM, as LLVM is incompatible with -fPIC and -dynamic on this platform"
in loop dflags' warn
else throwGhcException $ CmdLineError "Can't use -fPIC or -dynamic on this platform"
| os == OSDarwin &&
arch == ArchX86_64 &&
not (gopt Opt_PIC dflags)
= loop (gopt_set dflags Opt_PIC)
"Enabling -fPIC as it is always on for this platform"
| otherwise = (dflags, [])
where loc = mkGeneralSrcSpan (fsLit "when making flags consistent")
loop updated_dflags warning
= case makeDynFlagsConsistent updated_dflags of
(dflags', ws) -> (dflags', L loc warning : ws)
platform = targetPlatform dflags
arch = platformArch platform
os = platformOS platform
--------------------------------------------------------------------------
-- Do not use unsafeGlobalDynFlags!
--
-- unsafeGlobalDynFlags is a hack, necessary because we need to be able
-- to show SDocs when tracing, but we don't always have DynFlags
-- available.
--
-- Do not use it if you can help it. You may get the wrong value!
GLOBAL_VAR(v_unsafeGlobalDynFlags, panic "v_unsafeGlobalDynFlags: not initialised", DynFlags)
unsafeGlobalDynFlags :: DynFlags
unsafeGlobalDynFlags = unsafePerformIO $ readIORef v_unsafeGlobalDynFlags
setUnsafeGlobalDynFlags :: DynFlags -> IO ()
setUnsafeGlobalDynFlags = writeIORef v_unsafeGlobalDynFlags
-- -----------------------------------------------------------------------------
-- SSE and AVX
-- TODO: Instead of using a separate predicate (i.e. isSse2Enabled) to
-- check if SSE is enabled, we might have x86-64 imply the -msse2
-- flag.
isSseEnabled :: DynFlags -> Bool
isSseEnabled dflags = case platformArch (targetPlatform dflags) of
ArchX86_64 -> True
ArchX86 -> sseVersion dflags >= Just (1,0)
_ -> False
isSse2Enabled :: DynFlags -> Bool
isSse2Enabled dflags = case platformArch (targetPlatform dflags) of
ArchX86_64 -> -- SSE2 is fixed on for x86_64. It would be
-- possible to make it optional, but we'd need to
-- fix at least the foreign call code where the
-- calling convention specifies the use of xmm regs,
-- and possibly other places.
True
ArchX86 -> sseVersion dflags >= Just (2,0)
_ -> False
isSse4_2Enabled :: DynFlags -> Bool
isSse4_2Enabled dflags = sseVersion dflags >= Just (4,2)
isAvxEnabled :: DynFlags -> Bool
isAvxEnabled dflags = avx dflags || avx2 dflags || avx512f dflags
isAvx2Enabled :: DynFlags -> Bool
isAvx2Enabled dflags = avx2 dflags || avx512f dflags
isAvx512cdEnabled :: DynFlags -> Bool
isAvx512cdEnabled dflags = avx512cd dflags
isAvx512erEnabled :: DynFlags -> Bool
isAvx512erEnabled dflags = avx512er dflags
isAvx512fEnabled :: DynFlags -> Bool
isAvx512fEnabled dflags = avx512f dflags
isAvx512pfEnabled :: DynFlags -> Bool
isAvx512pfEnabled dflags = avx512pf dflags
-- -----------------------------------------------------------------------------
-- Linker/compiler information
-- LinkerInfo contains any extra options needed by the system linker.
data LinkerInfo
= GnuLD [Option]
| GnuGold [Option]
| DarwinLD [Option]
| SolarisLD [Option]
| UnknownLD
deriving Eq
-- CompilerInfo tells us which C compiler we're using
data CompilerInfo
= GCC
| Clang
| AppleClang
| AppleClang51
| UnknownCC
deriving Eq
-- -----------------------------------------------------------------------------
-- RTS hooks
-- Convert sizes like "3.5M" into integers
decodeSize :: String -> Integer
decodeSize str
| c == "" = truncate n
| c == "K" || c == "k" = truncate (n * 1000)
| c == "M" || c == "m" = truncate (n * 1000 * 1000)
| c == "G" || c == "g" = truncate (n * 1000 * 1000 * 1000)
| otherwise = throwGhcException (CmdLineError ("can't decode size: " ++ str))
where (m, c) = span pred str
n = readRational m
pred c = isDigit c || c == '.'
foreign import ccall unsafe "setHeapSize" setHeapSize :: Int -> IO ()
foreign import ccall unsafe "enableTimingStats" enableTimingStats :: IO ()
| lukexi/ghc | compiler/main/DynFlags.hs | bsd-3-clause | 161,443 | 0 | 34 | 44,575 | 31,347 | 17,654 | 13,693 | -1 | -1 |
{-# LANGUAGE CPP, GeneralizedNewtypeDeriving, OverloadedStrings #-}
module Haste.Binary.Types (
Blob (..), BlobData (..),
blobSize, blobDataSize, toByteString, fromByteString, toBlob, strToBlob
) where
import Haste.Prim
import Haste.Foreign
import qualified Data.ByteString.Lazy as BS
#ifndef __HASTE__
import qualified Data.ByteString.UTF8 as BU
#else
import System.IO.Unsafe
#endif
#ifdef __HASTE__
-- | In a browser context, BlobData is essentially a DataView, with an
-- accompanying offset and length for fast slicing.
-- In a server context, it is simply a 'BS.ByteString'.
data BlobData = BlobData Int Int JSAny
-- | A JavaScript Blob on the client, a 'BS.ByteString' on the server.
newtype Blob = Blob JSAny deriving (ToAny, FromAny)
-- | The size, in bytes, of the contents of the given blob.
blobSize :: Blob -> Int
blobSize = unsafePerformIO . ffi "(function(b){return b.size;})"
-- | The size, in bytes, of the contents of the given blob data.
blobDataSize :: BlobData -> Int
blobDataSize (BlobData _ len _) = len
-- | Convert a BlobData to a ByteString. Only usable server-side.
toByteString :: BlobData -> BS.ByteString
toByteString =
error "Haste.Binary.Types.toByteString called in browser context!"
-- | Convert a ByteString to a BlobData. Only usable server-side.
fromByteString :: BS.ByteString -> BlobData
fromByteString =
error "Haste.Binary.Types.toByteString called in browser context!"
-- | Convert a piece of BlobData back into a Blob.
toBlob :: BlobData -> Blob
toBlob (BlobData 0 len buf) =
case newBlob buf of
b | blobSize b > len -> sliceBlob b 0 len
| otherwise -> b
toBlob (BlobData off len buf) =
sliceBlob (newBlob buf) off (off+len)
-- | Create a Blob from a JSString.
strToBlob :: JSString -> Blob
strToBlob = newBlob . toAny
sliceBlob :: Blob -> Int -> Int -> Blob
sliceBlob b off len = unsafePerformIO $ jsSlice b off len
jsSlice :: Blob -> Int -> Int -> IO Blob
jsSlice = ffi "(function(b,off,len){return b.slice(off,len);})"
newBlob :: JSAny -> Blob
newBlob = unsafePerformIO . jsNewBlob
jsNewBlob :: JSAny -> IO Blob
jsNewBlob =
ffi "(function(b){try {return new Blob([b]);} catch (e) {return new Blob([b.buffer]);}})"
#else
-- | In a browser context, BlobData is essentially a DataView, with an
-- accompanying offset and length for fast slicing.
-- In a server context, it is simply a 'BS.ByteString'.
newtype BlobData = BlobData BS.ByteString
-- | A JavaScript Blob on the client, a 'BS.ByteString' on the server.
newtype Blob = Blob BS.ByteString
-- Never used except for type checking
clientOnly :: a
clientOnly = error "ToAny/FromAny only usable client-side!"
instance ToAny BlobData where toAny = clientOnly
instance FromAny BlobData where fromAny = clientOnly
instance ToAny Blob where toAny = clientOnly
instance FromAny Blob where fromAny = clientOnly
-- | The size, in bytes, of the contents of the given blob.
blobSize :: Blob -> Int
blobSize (Blob b) = fromIntegral $ BS.length b
-- | The size, in bytes, of the contents of the given blob data.
blobDataSize :: BlobData -> Int
blobDataSize (BlobData bd) = fromIntegral $ BS.length bd
-- | Convert a BlobData to a ByteString. Only usable server-side.
toByteString :: BlobData -> BS.ByteString
toByteString (BlobData bd) = bd
-- | Convert a ByteString to a BlobData. Only usable server-side.
fromByteString :: BS.ByteString -> BlobData
fromByteString = BlobData
-- | Convert a piece of BlobData back into a Blob.
toBlob :: BlobData -> Blob
toBlob (BlobData bs) = Blob bs
-- | Create a Blob from a JSString.
strToBlob :: JSString -> Blob
strToBlob s = Blob $ BS.fromChunks [BU.fromString $ fromJSStr s]
#endif
| kranich/haste-compiler | libraries/haste-lib/src/Haste/Binary/Types.hs | bsd-3-clause | 3,677 | 0 | 12 | 640 | 435 | 243 | 192 | 28 | 1 |
-- | Define a package-local alternative Prelude
module Prelude (return, print, elem) where
import GHC.List
import System.IO
import Control.Monad
| hvr/base-noprelude | examples/ex1/src/Prelude.hs | bsd-3-clause | 146 | 0 | 4 | 20 | 31 | 20 | 11 | 4 | 0 |
{-# Language RecordWildCards, OverloadedStrings, DeriveDataTypeable #-}
module Language.Bing(
BingLanguage(..),
BingContext,
BingError(..),
ClientId,
ClientSecret,
checkToken,
evalBing,
execBing,
getAccessToken,
getAccessTokenEither,
getBingCtx,
runBing,
runExceptT,
translate,
translateM) where
import qualified Network.Wreq as N
import Network.Wreq.Types (Postable)
import Control.Lens
import Data.ByteString (ByteString)
import Data.ByteString.Char8 (pack,unpack)
import Control.Monad.Catch
import Data.Typeable (Typeable)
import Control.Monad.IO.Class
import Network.HTTP.Client (HttpException)
import qualified Control.Exception as E
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BLC
import Data.Aeson
import Control.Monad (mzero)
import Control.Applicative ((<$>),(<*>))
import Data.Monoid
import Control.Applicative
import Data.DateTime
import Data.String (IsString)
import Data.Text (Text)
import qualified Data.Text as T
import Network.URL (decString)
import Text.XML.Light.Input
import Text.XML.Light.Types
import Text.XML.Light.Proc
import Data.List (find)
import qualified Data.Text.Encoding as TE
import qualified Data.Text.IO as TIO
import System.IO.Unsafe (unsafePerformIO)
import Control.Monad.Trans.Class
import Control.Monad.IO.Class
type ClientId = ByteString
type ClientSecret = ByteString
data BingError = BingError ByteString
deriving (Typeable, Show)
-- | The languages available for Microsoft Translator
data BingLanguage = Afrikaans
| Arabic
| Bosnian
| Bulgarian
| Catalan
| ChineseSimplified
| ChineseTraditional
| Croatian
| Czech
| Danish
| Dutch
| English
| Estonian
| Finnish
| French
| German
| Greek
| HaitianCreole
| Hebrew
| Hindi
| HmongDaw
| Hungarian
| Indonesian
| Italian
| Japanese
| Kiswahili
| Klingon
| KlingonPIqaD
| Korean
| Latvian
| Lithuanian
| Malay
| Maltese
| Norwegian
| Persian
| Polish
| Portuguese
| QueretaroOtomi
| Romanian
| Russian
| SerbianCyrillic
| SerbianLatin
| Slovak
| Slovenian
| Spanish
| Swedish
| Thai
| Turkish
| Ukrainian
| Urdu
| Vietnamese
| Welsh
| YucatecMaya
-- | Conversion function from Language to language code
toSym :: IsString a => BingLanguage -> a
toSym Afrikaans = "af"
toSym Arabic = "ar"
toSym Bosnian = "bs-Latn"
toSym Bulgarian = "bg"
toSym Catalan = "ca"
toSym ChineseSimplified = "zh-CHS"
toSym ChineseTraditional = "zh-CHT"
toSym Croatian = "hr"
toSym Czech = "cs"
toSym Danish = "da"
toSym Dutch = "nl"
toSym English = "en"
toSym Estonian = "et"
toSym Finnish = "fi"
toSym French = "fr"
toSym German = "de"
toSym Greek = "el"
toSym HaitianCreole = "ht"
toSym Hebrew = "he"
toSym Hindi = "hi"
toSym HmongDaw = "mww"
toSym Hungarian = "hu"
toSym Indonesian = "id"
toSym Italian = "it"
toSym Japanese = "ja"
toSym Kiswahili = "sw"
toSym Klingon = "tlh"
toSym KlingonPIqaD = "tlh-Qaak"
toSym Korean = "ko"
toSym Latvian = "lv"
toSym Lithuanian = "lt"
toSym Malay = "ms"
toSym Maltese = "mt"
toSym Norwegian = "no"
toSym Persian = "fa"
toSym Polish = "pl"
toSym Portuguese = "pt"
toSym QueretaroOtomi = "otq"
toSym Romanian = "ro"
toSym Russian = "ru"
toSym SerbianCyrillic = "sr-Cyrl"
toSym SerbianLatin = "sr-Latn"
toSym Slovak = "sk"
toSym Slovenian = "sl"
toSym Spanish = "es"
toSym Swedish = "sv"
toSym Thai = "th"
toSym Turkish = "tr"
toSym Ukrainian = "uk"
toSym Urdu = "ur"
toSym Vietnamese = "vi"
toSym Welsh = "cy"
toSym YucatecMaya = "yua"
data AccessToken = AccessToken {
tokenType :: ByteString,
token :: ByteString,
expires :: Integer,
scope :: ByteString
} deriving Show
data BingContext = BCTX {
accessToken :: AccessToken,
inception :: DateTime,
clientId :: ByteString,
clientSecret :: ByteString
} deriving (Show,Typeable)
newtype BingMonad m a = BM {runBing :: BingContext -> ExceptT BingError m a}
instance (Monad m, MonadIO m) => Monad (BingMonad m) where
m >>= f = BM (\ctx' -> do
ctx <- checkToken ctx'
res <- runBing m ctx
runBing (f res) ctx)
return a = BM $ \ctx -> return a
instance (Monad m, MonadIO m) => Functor (BingMonad m) where
fmap f bm = do
v <- bm
return $ f v
instance (Monad m, MonadIO m) => Applicative (BingMonad m) where
pure a = return a
a <*> b = do
a' <- a
b' <- b
return (a' b')
instance MonadTrans BingMonad where
lift m = BM $ \ctx -> lift m
instance MonadIO m => MonadIO (BingMonad m) where
liftIO io = BM $ \ctx -> liftIO io
instance FromJSON AccessToken where
parseJSON (Object v) = build <$>
v .: "token_type" <*>
v .: "access_token" <*>
((v .: "expires_in") >>= getNum) <*>
v .: "scope"
where
getNum str = case decode (BLC.pack str) of
Just n -> return n
Nothing -> mzero
build :: String -> String -> Integer -> String -> AccessToken
build v1 v2 v3 v4 = AccessToken (pack v1) (pack v2) v3 (pack v4)
parseJSON _ = mzero
instance Exception BingError
scopeArg = ("scope" :: ByteString)
N.:= ("http://api.microsofttranslator.com" :: ByteString)
grantType = ("grant_type" :: ByteString)
N.:= ("client_credentials" :: ByteString)
tokenAuthPage :: String
tokenAuthPage = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"
translateUrl :: String
translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate"
-- translateUrl = "http://requestb.in/14zmco81"
translateArgs text from to = [
("text" N.:= (text :: ByteString)),
("from" N.:= (toSym from :: ByteString)),
("to" N.:= (toSym to :: ByteString))
]
bingAction :: MonadIO m => IO (N.Response BL.ByteString) -> ExceptT BingError m (N.Response BL.ByteString)
bingAction action = do
res <- lift $ (liftIO $ (E.try action :: IO (Either HttpException (N.Response BL.ByteString))))
case res of
Right res -> return res
Left ex -> throwE $ BingError $ pack $ show ex
post url postable = bingAction (N.post url postable)
postWith opts url postable = bingAction (N.postWith opts url postable)
getWithAuth opts' url = withContext $ \BCTX{..} -> do
let opts = opts' & N.header "Authorization" .~ ["Bearer " <> token accessToken]
bingAction (N.getWith opts url)
-- | Request a new access token from Azure using the specified client
-- id and client secret
getAccessToken :: MonadIO m => ByteString -> ByteString -> ExceptT BingError m BingContext
getAccessToken clientId clientSecret = do
req <- post tokenAuthPage [
"client_id" N.:= clientId,
"client_secret" N.:= clientSecret,
scopeArg,
grantType
]
r <- liftIO $ N.asJSON req
let t = r ^. N.responseBody
t' <- liftIO $ getCurrentTime
return $ BCTX{
accessToken = t,
inception = t',
clientId = clientId,
clientSecret = clientSecret
}
-- | Check if the access token of the running BingAction is still
-- valid. If the token has expired, renews the token automatically
checkToken :: MonadIO m => BingContext -> ExceptT BingError m BingContext
checkToken ctx@BCTX{..} = do
t <- liftIO $ getCurrentTime
if diffSeconds t inception > expires accessToken - 100 then do
BCTX{accessToken = tk} <- getAccessToken clientId clientSecret
t' <- liftIO $ getCurrentTime
return $ ctx{accessToken = tk, inception = t'}
else
return $ ctx
withContext = BM
-- | Action that translates text inside a BingMonad context.
translateM :: MonadIO m => Text -> BingLanguage -> BingLanguage -> BingMonad m Text
translateM text from to = do
let opts = N.defaults & N.param "from" .~ [toSym from :: Text]
& N.param "to" .~ [toSym to]
& N.param "contentType" .~ ["text/plain"]
& N.param "category" .~ ["general"]
& N.param "text" .~ [text]
res <- getWithAuth opts translateUrl
let trans = parseXML $ (TE.decodeUtf8 $ BLC.toStrict $ res ^. N.responseBody)
case find (\n -> case n of
Elem e -> "string" == (qName $ elName e)
_ -> False) trans of
Just (Elem e) -> return $ T.pack $ strContent e
_ -> BM $ \_ -> throwE $ BingError $ pack $ show res
-- | Helper function that evaluates a BingMonad action. It simply
-- requests and access token and uses the token for evaluation.
evalBing :: MonadIO m => ClientId -> ClientSecret -> BingMonad m a -> m (Either BingError a)
evalBing clientId clientSecret action = runExceptT $ do
t <- getAccessToken clientId clientSecret
runBing action t
getBingCtx :: Monad m => BingMonad m BingContext
getBingCtx = BM {runBing = \ctx -> return ctx}
execBing :: MonadIO m => BingContext -> BingMonad m a -> m (Either BingError (a,BingContext))
execBing ctx action = runExceptT $ do
flip runBing ctx $ do
res <- action
ctx <- getBingCtx
return (res,ctx)
getAccessTokenEither :: ClientId -> ClientSecret -> IO (Either BingError BingContext)
getAccessTokenEither clientId clientSecret = runExceptT $ getAccessToken clientId clientSecret
-- | Toplevel wrapper that translates a text. It is only recommended if translation
-- is invoked less often than every 10 minutes since it always
-- requests a new access token. For better performance use
-- translateM, runBing and getAccessToken
translate :: ClientId -> ClientSecret -> Text -> BingLanguage -> BingLanguage -> IO (Either BingError Text)
translate cid cs text from to = evalBing cid cs (translateM text from to)
| netogallo/Microsoft-Translator-Haskell | src/Language/Bing.hs | bsd-3-clause | 10,430 | 0 | 21 | 2,884 | 2,906 | 1,554 | 1,352 | 284 | 3 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[HsBinds]{Abstract syntax: top-level bindings and signatures}
Datatype for: @BindGroup@, @Bind@, @Sig@, @Bind@.
-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
-- in module PlaceHolder
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE BangPatterns #-}
module HsBinds where
import {-# SOURCE #-} HsExpr ( pprExpr, LHsExpr,
MatchGroup, pprFunBind,
GRHSs, pprPatBind )
import {-# SOURCE #-} HsPat ( LPat )
import PlaceHolder ( PostTc,PostRn,DataId )
import HsTypes
import PprCore ()
import CoreSyn
import TcEvidence
import Type
import Name
import NameSet
import BasicTypes
import Outputable
import SrcLoc
import Var
import Bag
import FastString
import BooleanFormula (LBooleanFormula)
import DynFlags
import Data.Data hiding ( Fixity )
import Data.List hiding ( foldr )
import Data.Ord
import Data.Foldable ( Foldable(..) )
{-
************************************************************************
* *
\subsection{Bindings: @BindGroup@}
* *
************************************************************************
Global bindings (where clauses)
-}
-- During renaming, we need bindings where the left-hand sides
-- have been renamed but the the right-hand sides have not.
-- the ...LR datatypes are parametrized by two id types,
-- one for the left and one for the right.
-- Other than during renaming, these will be the same.
type HsLocalBinds id = HsLocalBindsLR id id
-- | Bindings in a 'let' expression
-- or a 'where' clause
data HsLocalBindsLR idL idR
= HsValBinds (HsValBindsLR idL idR)
-- There should be no pattern synonyms in the HsValBindsLR
-- These are *local* (not top level) bindings
-- The parser accepts them, however, leaving the the
-- renamer to report them
| HsIPBinds (HsIPBinds idR)
| EmptyLocalBinds
deriving (Typeable)
deriving instance (DataId idL, DataId idR)
=> Data (HsLocalBindsLR idL idR)
type HsValBinds id = HsValBindsLR id id
-- | Value bindings (not implicit parameters)
-- Used for both top level and nested bindings
-- May contain pattern synonym bindings
data HsValBindsLR idL idR
= -- | Before renaming RHS; idR is always RdrName
-- Not dependency analysed
-- Recursive by default
ValBindsIn
(LHsBindsLR idL idR) [LSig idR]
-- | After renaming RHS; idR can be Name or Id
-- Dependency analysed,
-- later bindings in the list may depend on earlier
-- ones.
| ValBindsOut
[(RecFlag, LHsBinds idL)]
[LSig Name]
deriving (Typeable)
deriving instance (DataId idL, DataId idR)
=> Data (HsValBindsLR idL idR)
type LHsBind id = LHsBindLR id id
type LHsBinds id = LHsBindsLR id id
type HsBind id = HsBindLR id id
type LHsBindsLR idL idR = Bag (LHsBindLR idL idR)
type LHsBindLR idL idR = Located (HsBindLR idL idR)
data HsBindLR idL idR
= -- | FunBind is used for both functions @f x = e@
-- and variables @f = \x -> e@
--
-- Reason 1: Special case for type inference: see 'TcBinds.tcMonoBinds'.
--
-- Reason 2: Instance decls can only have FunBinds, which is convenient.
-- If you change this, you'll need to change e.g. rnMethodBinds
--
-- But note that the form @f :: a->a = ...@
-- parses as a pattern binding, just like
-- @(f :: a -> a) = ... @
--
-- 'ApiAnnotation.AnnKeywordId's
--
-- - 'ApiAnnotation.AnnFunId', attached to each element of fun_matches
--
-- - 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere',
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
-- For details on above see note [Api annotations] in ApiAnnotation
FunBind {
fun_id :: Located idL, -- Note [fun_id in Match] in HsExpr
fun_matches :: MatchGroup idR (LHsExpr idR), -- ^ The payload
fun_co_fn :: HsWrapper, -- ^ Coercion from the type of the MatchGroup to the type of
-- the Id. Example:
--
-- @
-- f :: Int -> forall a. a -> a
-- f x y = y
-- @
--
-- Then the MatchGroup will have type (Int -> a' -> a')
-- (with a free type variable a'). The coercion will take
-- a CoreExpr of this type and convert it to a CoreExpr of
-- type Int -> forall a'. a' -> a'
-- Notice that the coercion captures the free a'.
bind_fvs :: PostRn idL NameSet, -- ^ After the renamer, this contains
-- the locally-bound
-- free variables of this defn.
-- See Note [Bind free vars]
fun_tick :: [Tickish Id] -- ^ Ticks to put on the rhs, if any
}
-- | The pattern is never a simple variable;
-- That case is done by FunBind
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnBang',
-- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere',
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
-- For details on above see note [Api annotations] in ApiAnnotation
| PatBind {
pat_lhs :: LPat idL,
pat_rhs :: GRHSs idR (LHsExpr idR),
pat_rhs_ty :: PostTc idR Type, -- ^ Type of the GRHSs
bind_fvs :: PostRn idL NameSet, -- ^ See Note [Bind free vars]
pat_ticks :: ([Tickish Id], [[Tickish Id]])
-- ^ Ticks to put on the rhs, if any, and ticks to put on
-- the bound variables.
}
-- | Dictionary binding and suchlike.
-- All VarBinds are introduced by the type checker
| VarBind {
var_id :: idL,
var_rhs :: LHsExpr idR, -- ^ Located only for consistency
var_inline :: Bool -- ^ True <=> inline this binding regardless
-- (used for implication constraints only)
}
| AbsBinds { -- Binds abstraction; TRANSLATION
abs_tvs :: [TyVar],
abs_ev_vars :: [EvVar], -- ^ Includes equality constraints
-- | AbsBinds only gets used when idL = idR after renaming,
-- but these need to be idL's for the collect... code in HsUtil
-- to have the right type
abs_exports :: [ABExport idL],
-- | Evidence bindings
-- Why a list? See TcInstDcls
-- Note [Typechecking plan for instance declarations]
abs_ev_binds :: [TcEvBinds],
-- | Typechecked user bindings
abs_binds :: LHsBinds idL
}
| AbsBindsSig { -- Simpler form of AbsBinds, used with a type sig
-- in tcPolyCheck. Produces simpler desugaring and
-- is necessary to avoid #11405, comment:3.
abs_tvs :: [TyVar],
abs_ev_vars :: [EvVar],
abs_sig_export :: idL, -- like abe_poly
abs_sig_prags :: TcSpecPrags,
abs_sig_ev_bind :: TcEvBinds, -- no list needed here
abs_sig_bind :: LHsBind idL -- always only one, and it's always a
-- FunBind
}
| PatSynBind (PatSynBind idL idR)
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnPattern',
-- 'ApiAnnotation.AnnLarrow','ApiAnnotation.AnnEqual',
-- 'ApiAnnotation.AnnWhere'
-- 'ApiAnnotation.AnnOpen' @'{'@,'ApiAnnotation.AnnClose' @'}'@
-- For details on above see note [Api annotations] in ApiAnnotation
deriving (Typeable)
deriving instance (DataId idL, DataId idR)
=> Data (HsBindLR idL idR)
-- Consider (AbsBinds tvs ds [(ftvs, poly_f, mono_f) binds]
--
-- Creates bindings for (polymorphic, overloaded) poly_f
-- in terms of monomorphic, non-overloaded mono_f
--
-- Invariants:
-- 1. 'binds' binds mono_f
-- 2. ftvs is a subset of tvs
-- 3. ftvs includes all tyvars free in ds
--
-- See Note [AbsBinds]
data ABExport id
= ABE { abe_poly :: id -- ^ Any INLINE pragmas is attached to this Id
, abe_mono :: id
, abe_inst_wrap :: HsWrapper -- ^ See Note [AbsBinds wrappers]
-- ^ Shape: abe_mono ~ abe_insted
, abe_wrap :: HsWrapper -- ^ See Note [AbsBinds wrappers]
-- Shape: (forall abs_tvs. abs_ev_vars => abe_insted) ~ abe_poly
, abe_prags :: TcSpecPrags -- ^ SPECIALISE pragmas
} deriving (Data, Typeable)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnPattern',
-- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnLarrow'
-- 'ApiAnnotation.AnnWhere','ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnClose' @'}'@,
-- For details on above see note [Api annotations] in ApiAnnotation
data PatSynBind idL idR
= PSB { psb_id :: Located idL, -- ^ Name of the pattern synonym
psb_fvs :: PostRn idR NameSet, -- ^ See Note [Bind free vars]
psb_args :: HsPatSynDetails (Located idR), -- ^ Formal parameter names
psb_def :: LPat idR, -- ^ Right-hand side
psb_dir :: HsPatSynDir idR -- ^ Directionality
} deriving (Typeable)
deriving instance (DataId idL, DataId idR)
=> Data (PatSynBind idL idR)
{-
Note [AbsBinds]
~~~~~~~~~~~~~~~
The AbsBinds constructor is used in the output of the type checker, to record
*typechecked* and *generalised* bindings. Consider a module M, with this
top-level binding, where there is no type signature for M.reverse,
M.reverse [] = []
M.reverse (x:xs) = M.reverse xs ++ [x]
In Hindley-Milner, a recursive binding is typechecked with the *recursive* uses
being *monomorphic*. So after typechecking *and* desugaring we will get something
like this
M.reverse :: forall a. [a] -> [a]
= /\a. letrec
reverse :: [a] -> [a] = \xs -> case xs of
[] -> []
(x:xs) -> reverse xs ++ [x]
in reverse
Notice that 'M.reverse' is polymorphic as expected, but there is a local
definition for plain 'reverse' which is *monomorphic*. The type variable
'a' scopes over the entire letrec.
That's after desugaring. What about after type checking but before
desugaring? That's where AbsBinds comes in. It looks like this:
AbsBinds { abs_tvs = [a]
, abs_exports = [ABE { abe_poly = M.reverse :: forall a. [a] -> [a],
, abe_mono = reverse :: [a] -> [a]}]
, abs_binds = { reverse :: [a] -> [a]
= \xs -> case xs of
[] -> []
(x:xs) -> reverse xs ++ [x] } }
Here,
* abs_tvs says what type variables are abstracted over the binding group,
just 'a' in this case.
* abs_binds is the *monomorphic* bindings of the group
* abs_exports describes how to get the polymorphic Id 'M.reverse' from the
monomorphic one 'reverse'
Notice that the *original* function (the polymorphic one you thought
you were defining) appears in the abe_poly field of the
abs_exports. The bindings in abs_binds are for fresh, local, Ids with
a *monomorphic* Id.
If there is a group of mutually recursive (see Note [Polymorphic
recursion]) functions without type signatures, we get one AbsBinds
with the monomorphic versions of the bindings in abs_binds, and one
element of abe_exports for each variable bound in the mutually
recursive group. This is true even for pattern bindings. Example:
(f,g) = (\x -> x, f)
After type checking we get
AbsBinds { abs_tvs = [a]
, abs_exports = [ ABE { abe_poly = M.f :: forall a. a -> a
, abe_mono = f :: a -> a }
, ABE { abe_poly = M.g :: forall a. a -> a
, abe_mono = g :: a -> a }]
, abs_binds = { (f,g) = (\x -> x, f) }
Note [Polymorphic recursion]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
Rec { f x = ...(g ef)...
; g :: forall a. [a] -> [a]
; g y = ...(f eg)... }
These bindings /are/ mutually recursive (f calls g, and g calls f).
But we can use the type signature for g to break the recursion,
like this:
1. Add g :: forall a. [a] -> [a] to the type environment
2. Typecheck the definition of f, all by itself,
including generalising it to find its most general
type, say f :: forall b. b -> b -> [b]
3. Extend the type environment with that type for f
4. Typecheck the definition of g, all by itself,
checking that it has the type claimed by its signature
Steps 2 and 4 each generate a separate AbsBinds, so we end
up with
Rec { AbsBinds { ...for f ... }
; AbsBinds { ...for g ... } }
This approach allows both f and to call each other
polymorphically, even though only g has a signature.
We get an AbsBinds that encompasses multiple source-program
bindings only when
* Each binding in the group has at least one binder that
lacks a user type signature
* The group forms a strongly connected component
Note [AbsBinds wrappers]
~~~~~~~~~~~~~~~~~~~~~~~~
Consider
(f,g) = (\x.x, \y.y)
This ultimately desugars to something like this:
tup :: forall a b. (a->a, b->b)
tup = /\a b. (\x:a.x, \y:b.y)
f :: forall a. a -> a
f = /\a. case tup a Any of
(fm::a->a,gm:Any->Any) -> fm
...similarly for g...
The abe_wrap field deals with impedance-matching between
(/\a b. case tup a b of { (f,g) -> f })
and the thing we really want, which may have fewer type
variables. The action happens in TcBinds.mkExport.
For abe_inst_wrap, consider this:
x = (*)
The abe_mono type will be forall a. Num a => a -> a -> a
because no instantiation happens during typechecking. Before inferring
a final type, we must instantiate this. See Note [Instantiate when inferring
a type] in TcBinds. The abe_inst_wrap takes the uninstantiated abe_mono type
to a proper instantiated type. In this case, the "abe_insted" is
(b -> b -> b). Note that the value of "abe_insted" isn't important; it's
just an intermediate form as we're going from abe_mono to abe_poly. See also
the desugaring code in DsBinds.
It's conceivable that we could combine the two wrappers, but note that there
is a gap: neither wrapper tacks on the tvs and dicts from the outer AbsBinds.
These bits are added manually in desugaring. (See DsBinds.dsHsBind.) A problem
that would arise in combining them is that zonking becomes more challenging:
we want to zonk the tvs and dicts in the AbsBinds, but then we end up re-zonking
when we zonk the ABExport. And -- worse -- the combined wrapper would have
the tvs and dicts in binding positions, so they would shadow the original
tvs and dicts. This is all resolvable with some plumbing, but it seems simpler
just to keep the two wrappers distinct.
Note [Bind free vars]
~~~~~~~~~~~~~~~~~~~~~
The bind_fvs field of FunBind and PatBind records the free variables
of the definition. It is used for two purposes
a) Dependency analysis prior to type checking
(see TcBinds.tc_group)
b) Deciding whether we can do generalisation of the binding
(see TcBinds.decideGeneralisationPlan)
Specifically,
* bind_fvs includes all free vars that are defined in this module
(including top-level things and lexically scoped type variables)
* bind_fvs excludes imported vars; this is just to keep the set smaller
* Before renaming, and after typechecking, the field is unused;
it's just an error thunk
-}
instance (OutputableBndr idL, OutputableBndr idR) => Outputable (HsLocalBindsLR idL idR) where
ppr (HsValBinds bs) = ppr bs
ppr (HsIPBinds bs) = ppr bs
ppr EmptyLocalBinds = empty
instance (OutputableBndr idL, OutputableBndr idR) => Outputable (HsValBindsLR idL idR) where
ppr (ValBindsIn binds sigs)
= pprDeclList (pprLHsBindsForUser binds sigs)
ppr (ValBindsOut sccs sigs)
= getPprStyle $ \ sty ->
if debugStyle sty then -- Print with sccs showing
vcat (map ppr sigs) $$ vcat (map ppr_scc sccs)
else
pprDeclList (pprLHsBindsForUser (unionManyBags (map snd sccs)) sigs)
where
ppr_scc (rec_flag, binds) = pp_rec rec_flag <+> pprLHsBinds binds
pp_rec Recursive = text "rec"
pp_rec NonRecursive = text "nonrec"
pprLHsBinds :: (OutputableBndr idL, OutputableBndr idR) => LHsBindsLR idL idR -> SDoc
pprLHsBinds binds
| isEmptyLHsBinds binds = empty
| otherwise = pprDeclList (map ppr (bagToList binds))
pprLHsBindsForUser :: (OutputableBndr idL, OutputableBndr idR, OutputableBndr id2)
=> LHsBindsLR idL idR -> [LSig id2] -> [SDoc]
-- pprLHsBindsForUser is different to pprLHsBinds because
-- a) No braces: 'let' and 'where' include a list of HsBindGroups
-- and we don't want several groups of bindings each
-- with braces around
-- b) Sort by location before printing
-- c) Include signatures
pprLHsBindsForUser binds sigs
= map snd (sort_by_loc decls)
where
decls :: [(SrcSpan, SDoc)]
decls = [(loc, ppr sig) | L loc sig <- sigs] ++
[(loc, ppr bind) | L loc bind <- bagToList binds]
sort_by_loc decls = sortBy (comparing fst) decls
pprDeclList :: [SDoc] -> SDoc -- Braces with a space
-- Print a bunch of declarations
-- One could choose { d1; d2; ... }, using 'sep'
-- or d1
-- d2
-- ..
-- using vcat
-- At the moment we chose the latter
-- Also we do the 'pprDeeperList' thing.
pprDeclList ds = pprDeeperList vcat ds
------------
emptyLocalBinds :: HsLocalBindsLR a b
emptyLocalBinds = EmptyLocalBinds
isEmptyLocalBinds :: HsLocalBindsLR a b -> Bool
isEmptyLocalBinds (HsValBinds ds) = isEmptyValBinds ds
isEmptyLocalBinds (HsIPBinds ds) = isEmptyIPBinds ds
isEmptyLocalBinds EmptyLocalBinds = True
isEmptyValBinds :: HsValBindsLR a b -> Bool
isEmptyValBinds (ValBindsIn ds sigs) = isEmptyLHsBinds ds && null sigs
isEmptyValBinds (ValBindsOut ds sigs) = null ds && null sigs
emptyValBindsIn, emptyValBindsOut :: HsValBindsLR a b
emptyValBindsIn = ValBindsIn emptyBag []
emptyValBindsOut = ValBindsOut [] []
emptyLHsBinds :: LHsBindsLR idL idR
emptyLHsBinds = emptyBag
isEmptyLHsBinds :: LHsBindsLR idL idR -> Bool
isEmptyLHsBinds = isEmptyBag
------------
plusHsValBinds :: HsValBinds a -> HsValBinds a -> HsValBinds a
plusHsValBinds (ValBindsIn ds1 sigs1) (ValBindsIn ds2 sigs2)
= ValBindsIn (ds1 `unionBags` ds2) (sigs1 ++ sigs2)
plusHsValBinds (ValBindsOut ds1 sigs1) (ValBindsOut ds2 sigs2)
= ValBindsOut (ds1 ++ ds2) (sigs1 ++ sigs2)
plusHsValBinds _ _
= panic "HsBinds.plusHsValBinds"
{-
What AbsBinds means
~~~~~~~~~~~~~~~~~~~
AbsBinds tvs
[d1,d2]
[(tvs1, f1p, f1m),
(tvs2, f2p, f2m)]
BIND
means
f1p = /\ tvs -> \ [d1,d2] -> letrec DBINDS and BIND
in fm
gp = ...same again, with gm instead of fm
This is a pretty bad translation, because it duplicates all the bindings.
So the desugarer tries to do a better job:
fp = /\ [a,b] -> \ [d1,d2] -> case tp [a,b] [d1,d2] of
(fm,gm) -> fm
..ditto for gp..
tp = /\ [a,b] -> \ [d1,d2] -> letrec DBINDS and BIND
in (fm,gm)
-}
instance (OutputableBndr idL, OutputableBndr idR) => Outputable (HsBindLR idL idR) where
ppr mbind = ppr_monobind mbind
ppr_monobind :: (OutputableBndr idL, OutputableBndr idR) => HsBindLR idL idR -> SDoc
ppr_monobind (PatBind { pat_lhs = pat, pat_rhs = grhss })
= pprPatBind pat grhss
ppr_monobind (VarBind { var_id = var, var_rhs = rhs })
= sep [pprBndr CaseBind var, nest 2 $ equals <+> pprExpr (unLoc rhs)]
ppr_monobind (FunBind { fun_id = fun,
fun_co_fn = wrap,
fun_matches = matches,
fun_tick = ticks })
= pprTicks empty (if null ticks then empty
else text "-- ticks = " <> ppr ticks)
$$ ifPprDebug (pprBndr LetBind (unLoc fun))
$$ pprFunBind (unLoc fun) matches
$$ ifPprDebug (ppr wrap)
ppr_monobind (PatSynBind psb) = ppr psb
ppr_monobind (AbsBinds { abs_tvs = tyvars, abs_ev_vars = dictvars
, abs_exports = exports, abs_binds = val_binds
, abs_ev_binds = ev_binds })
= sdocWithDynFlags $ \ dflags ->
if gopt Opt_PrintTypecheckerElaboration dflags then
-- Show extra information (bug number: #10662)
hang (text "AbsBinds" <+> brackets (interpp'SP tyvars)
<+> brackets (interpp'SP dictvars))
2 $ braces $ vcat
[ text "Exports:" <+>
brackets (sep (punctuate comma (map ppr exports)))
, text "Exported types:" <+>
vcat [pprBndr LetBind (abe_poly ex) | ex <- exports]
, text "Binds:" <+> pprLHsBinds val_binds
, text "Evidence:" <+> ppr ev_binds ]
else
pprLHsBinds val_binds
ppr_monobind (AbsBindsSig { abs_tvs = tyvars
, abs_ev_vars = dictvars
, abs_sig_ev_bind = ev_bind
, abs_sig_bind = bind })
= sdocWithDynFlags $ \ dflags ->
if gopt Opt_PrintTypecheckerElaboration dflags then
hang (text "AbsBindsSig" <+> brackets (interpp'SP tyvars)
<+> brackets (interpp'SP dictvars))
2 $ braces $ vcat
[ text "Bind:" <+> ppr bind
, text "Evidence:" <+> ppr ev_bind ]
else
ppr bind
instance (OutputableBndr id) => Outputable (ABExport id) where
ppr (ABE { abe_wrap = wrap, abe_inst_wrap = inst_wrap
, abe_poly = gbl, abe_mono = lcl, abe_prags = prags })
= vcat [ ppr gbl <+> text "<=" <+> ppr lcl
, nest 2 (pprTcSpecPrags prags)
, nest 2 (ppr wrap)
, nest 2 (ppr inst_wrap)]
instance (OutputableBndr idL, OutputableBndr idR) => Outputable (PatSynBind idL idR) where
ppr (PSB{ psb_id = L _ psyn, psb_args = details, psb_def = pat, psb_dir = dir })
= ppr_lhs <+> ppr_rhs
where
ppr_lhs = text "pattern" <+> ppr_details
ppr_simple syntax = syntax <+> ppr pat
ppr_details = case details of
InfixPatSyn v1 v2 -> hsep [ppr v1, pprInfixOcc psyn, ppr v2]
PrefixPatSyn vs -> hsep (pprPrefixOcc psyn : map ppr vs)
RecordPatSyn vs ->
pprPrefixOcc psyn
<> braces (sep (punctuate comma (map ppr vs)))
ppr_rhs = case dir of
Unidirectional -> ppr_simple (text "<-")
ImplicitBidirectional -> ppr_simple equals
ExplicitBidirectional mg -> ppr_simple (text "<-") <+> ptext (sLit "where") $$
(nest 2 $ pprFunBind psyn mg)
pprTicks :: SDoc -> SDoc -> SDoc
-- Print stuff about ticks only when -dppr-debug is on, to avoid
-- them appearing in error messages (from the desugarer); see Trac # 3263
-- Also print ticks in dumpStyle, so that -ddump-hpc actually does
-- something useful.
pprTicks pp_no_debug pp_when_debug
= getPprStyle (\ sty -> if debugStyle sty || dumpStyle sty
then pp_when_debug
else pp_no_debug)
{-
************************************************************************
* *
Implicit parameter bindings
* *
************************************************************************
-}
data HsIPBinds id
= IPBinds
[LIPBind id]
TcEvBinds -- Only in typechecker output; binds
-- uses of the implicit parameters
deriving (Typeable)
deriving instance (DataId id) => Data (HsIPBinds id)
isEmptyIPBinds :: HsIPBinds id -> Bool
isEmptyIPBinds (IPBinds is ds) = null is && isEmptyTcEvBinds ds
type LIPBind id = Located (IPBind id)
-- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when in a
-- list
-- For details on above see note [Api annotations] in ApiAnnotation
-- | Implicit parameter bindings.
--
-- These bindings start off as (Left "x") in the parser and stay
-- that way until after type-checking when they are replaced with
-- (Right d), where "d" is the name of the dictionary holding the
-- evidence for the implicit parameter.
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnEqual'
-- For details on above see note [Api annotations] in ApiAnnotation
data IPBind id
= IPBind (Either (Located HsIPName) id) (LHsExpr id)
deriving (Typeable)
deriving instance (DataId name) => Data (IPBind name)
instance (OutputableBndr id) => Outputable (HsIPBinds id) where
ppr (IPBinds bs ds) = pprDeeperList vcat (map ppr bs)
$$ ifPprDebug (ppr ds)
instance (OutputableBndr id) => Outputable (IPBind id) where
ppr (IPBind lr rhs) = name <+> equals <+> pprExpr (unLoc rhs)
where name = case lr of
Left (L _ ip) -> pprBndr LetBind ip
Right id -> pprBndr LetBind id
{-
************************************************************************
* *
\subsection{@Sig@: type signatures and value-modifying user pragmas}
* *
************************************************************************
It is convenient to lump ``value-modifying'' user-pragmas (e.g.,
``specialise this function to these four types...'') in with type
signatures. Then all the machinery to move them into place, etc.,
serves for both.
-}
type LSig name = Located (Sig name)
-- | Signatures and pragmas
data Sig name
= -- | An ordinary type signature
--
-- > f :: Num a => a -> a
--
-- After renaming, this list of Names contains the named and unnamed
-- wildcards brought into scope by this signature. For a signature
-- @_ -> _a -> Bool@, the renamer will give the unnamed wildcard @_@
-- a freshly generated name, e.g. @_w@. @_w@ and the named wildcard @_a@
-- are then both replaced with fresh meta vars in the type. Their names
-- are stored in the type signature that brought them into scope, in
-- this third field to be more specific.
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon',
-- 'ApiAnnotation.AnnComma'
-- For details on above see note [Api annotations] in ApiAnnotation
TypeSig
[Located name] -- LHS of the signature; e.g. f,g,h :: blah
(LHsSigWcType name) -- RHS of the signature; can have wildcards
-- | A pattern synonym type signature
--
-- > pattern Single :: () => (Show a) => a -> [a]
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnPattern',
-- 'ApiAnnotation.AnnDcolon','ApiAnnotation.AnnForall'
-- 'ApiAnnotation.AnnDot','ApiAnnotation.AnnDarrow'
-- For details on above see note [Api annotations] in ApiAnnotation
| PatSynSig (Located name) (LHsSigType name)
-- P :: forall a b. Prov => Req => ty
-- | A signature for a class method
-- False: ordinary class-method signature
-- True: default class method signature
-- e.g. class C a where
-- op :: a -> a -- Ordinary
-- default op :: Eq a => a -> a -- Generic default
-- No wildcards allowed here
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDefault',
-- 'ApiAnnotation.AnnDcolon'
| ClassOpSig Bool [Located name] (LHsSigType name)
-- | A type signature in generated code, notably the code
-- generated for record selectors. We simply record
-- the desired Id itself, replete with its name, type
-- and IdDetails. Otherwise it's just like a type
-- signature: there should be an accompanying binding
| IdSig Id
-- | An ordinary fixity declaration
--
-- > infixl 8 ***
--
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnInfix',
-- 'ApiAnnotation.AnnVal'
-- For details on above see note [Api annotations] in ApiAnnotation
| FixSig (FixitySig name)
-- | An inline pragma
--
-- > {#- INLINE f #-}
--
-- - 'ApiAnnotation.AnnKeywordId' :
-- 'ApiAnnotation.AnnOpen' @'{-\# INLINE'@ and @'['@,
-- 'ApiAnnotation.AnnClose','ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnTilde',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| InlineSig (Located name) -- Function name
InlinePragma -- Never defaultInlinePragma
-- | A specialisation pragma
--
-- > {-# SPECIALISE f :: Int -> Int #-}
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnOpen' @'{-\# SPECIALISE'@ and @'['@,
-- 'ApiAnnotation.AnnTilde',
-- 'ApiAnnotation.AnnVal',
-- 'ApiAnnotation.AnnClose' @']'@ and @'\#-}'@,
-- 'ApiAnnotation.AnnDcolon'
-- For details on above see note [Api annotations] in ApiAnnotation
| SpecSig (Located name) -- Specialise a function or datatype ...
[LHsSigType name] -- ... to these types
InlinePragma -- The pragma on SPECIALISE_INLINE form.
-- If it's just defaultInlinePragma, then we said
-- SPECIALISE, not SPECIALISE_INLINE
-- | A specialisation pragma for instance declarations only
--
-- > {-# SPECIALISE instance Eq [Int] #-}
--
-- (Class tys); should be a specialisation of the
-- current instance declaration
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnInstance','ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| SpecInstSig SourceText (LHsSigType name)
-- Note [Pragma source text] in BasicTypes
-- | A minimal complete definition pragma
--
-- > {-# MINIMAL a | (b, c | (d | e)) #-}
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnVbar','ApiAnnotation.AnnComma',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| MinimalSig SourceText (LBooleanFormula (Located name))
-- Note [Pragma source text] in BasicTypes
deriving (Typeable)
deriving instance (DataId name) => Data (Sig name)
type LFixitySig name = Located (FixitySig name)
data FixitySig name = FixitySig [Located name] Fixity
deriving (Data, Typeable)
-- | TsSpecPrags conveys pragmas from the type checker to the desugarer
data TcSpecPrags
= IsDefaultMethod -- ^ Super-specialised: a default method should
-- be macro-expanded at every call site
| SpecPrags [LTcSpecPrag]
deriving (Data, Typeable)
type LTcSpecPrag = Located TcSpecPrag
data TcSpecPrag
= SpecPrag
Id
HsWrapper
InlinePragma
-- ^ The Id to be specialised, an wrapper that specialises the
-- polymorphic function, and inlining spec for the specialised function
deriving (Data, Typeable)
noSpecPrags :: TcSpecPrags
noSpecPrags = SpecPrags []
hasSpecPrags :: TcSpecPrags -> Bool
hasSpecPrags (SpecPrags ps) = not (null ps)
hasSpecPrags IsDefaultMethod = False
isDefaultMethod :: TcSpecPrags -> Bool
isDefaultMethod IsDefaultMethod = True
isDefaultMethod (SpecPrags {}) = False
isFixityLSig :: LSig name -> Bool
isFixityLSig (L _ (FixSig {})) = True
isFixityLSig _ = False
isTypeLSig :: LSig name -> Bool -- Type signatures
isTypeLSig (L _(TypeSig {})) = True
isTypeLSig (L _(ClassOpSig {})) = True
isTypeLSig (L _(IdSig {})) = True
isTypeLSig _ = False
isSpecLSig :: LSig name -> Bool
isSpecLSig (L _(SpecSig {})) = True
isSpecLSig _ = False
isSpecInstLSig :: LSig name -> Bool
isSpecInstLSig (L _ (SpecInstSig {})) = True
isSpecInstLSig _ = False
isPragLSig :: LSig name -> Bool
-- Identifies pragmas
isPragLSig (L _ (SpecSig {})) = True
isPragLSig (L _ (InlineSig {})) = True
isPragLSig _ = False
isInlineLSig :: LSig name -> Bool
-- Identifies inline pragmas
isInlineLSig (L _ (InlineSig {})) = True
isInlineLSig _ = False
isMinimalLSig :: LSig name -> Bool
isMinimalLSig (L _ (MinimalSig {})) = True
isMinimalLSig _ = False
hsSigDoc :: Sig name -> SDoc
hsSigDoc (TypeSig {}) = text "type signature"
hsSigDoc (PatSynSig {}) = text "pattern synonym signature"
hsSigDoc (ClassOpSig is_deflt _ _)
| is_deflt = text "default type signature"
| otherwise = text "class method signature"
hsSigDoc (IdSig {}) = text "id signature"
hsSigDoc (SpecSig {}) = text "SPECIALISE pragma"
hsSigDoc (InlineSig _ prag) = ppr (inlinePragmaSpec prag) <+> text "pragma"
hsSigDoc (SpecInstSig {}) = text "SPECIALISE instance pragma"
hsSigDoc (FixSig {}) = text "fixity declaration"
hsSigDoc (MinimalSig {}) = text "MINIMAL pragma"
{-
Check if signatures overlap; this is used when checking for duplicate
signatures. Since some of the signatures contain a list of names, testing for
equality is not enough -- we have to check if they overlap.
-}
instance (OutputableBndr name) => Outputable (Sig name) where
ppr sig = ppr_sig sig
ppr_sig :: OutputableBndr name => Sig name -> SDoc
ppr_sig (TypeSig vars ty) = pprVarSig (map unLoc vars) (ppr ty)
ppr_sig (ClassOpSig is_deflt vars ty)
| is_deflt = text "default" <+> pprVarSig (map unLoc vars) (ppr ty)
| otherwise = pprVarSig (map unLoc vars) (ppr ty)
ppr_sig (IdSig id) = pprVarSig [id] (ppr (varType id))
ppr_sig (FixSig fix_sig) = ppr fix_sig
ppr_sig (SpecSig var ty inl)
= pragBrackets (pprSpec (unLoc var) (interpp'SP ty) inl)
ppr_sig (InlineSig var inl) = pragBrackets (ppr inl <+> pprPrefixOcc (unLoc var))
ppr_sig (SpecInstSig _ ty)
= pragBrackets (text "SPECIALIZE instance" <+> ppr ty)
ppr_sig (MinimalSig _ bf) = pragBrackets (pprMinimalSig bf)
ppr_sig (PatSynSig name sig_ty)
= text "pattern" <+> pprPrefixOcc (unLoc name) <+> dcolon
<+> ppr sig_ty
pprPatSynSig :: (OutputableBndr name)
=> name -> Bool -> SDoc -> Maybe SDoc -> Maybe SDoc -> SDoc -> SDoc
pprPatSynSig ident _is_bidir tvs req prov ty
= text "pattern" <+> pprPrefixOcc ident <+> dcolon <+>
tvs <+> context <+> ty
where
context = case (req, prov) of
(Nothing, Nothing) -> empty
(Nothing, Just prov) -> parens empty <+> darrow <+> prov <+> darrow
(Just req, Nothing) -> req <+> darrow
(Just req, Just prov) -> req <+> darrow <+> prov <+> darrow
instance OutputableBndr name => Outputable (FixitySig name) where
ppr (FixitySig names fixity) = sep [ppr fixity, pprops]
where
pprops = hsep $ punctuate comma (map (pprInfixOcc . unLoc) names)
pragBrackets :: SDoc -> SDoc
pragBrackets doc = text "{-#" <+> doc <+> ptext (sLit "#-}")
pprVarSig :: (OutputableBndr id) => [id] -> SDoc -> SDoc
pprVarSig vars pp_ty = sep [pprvars <+> dcolon, nest 2 pp_ty]
where
pprvars = hsep $ punctuate comma (map pprPrefixOcc vars)
pprSpec :: (OutputableBndr id) => id -> SDoc -> InlinePragma -> SDoc
pprSpec var pp_ty inl = text "SPECIALIZE" <+> pp_inl <+> pprVarSig [var] pp_ty
where
pp_inl | isDefaultInlinePragma inl = empty
| otherwise = ppr inl
pprTcSpecPrags :: TcSpecPrags -> SDoc
pprTcSpecPrags IsDefaultMethod = text "<default method>"
pprTcSpecPrags (SpecPrags ps) = vcat (map (ppr . unLoc) ps)
instance Outputable TcSpecPrag where
ppr (SpecPrag var _ inl) = pprSpec var (text "<type>") inl
pprMinimalSig :: OutputableBndr name => LBooleanFormula (Located name) -> SDoc
pprMinimalSig (L _ bf) = text "MINIMAL" <+> ppr (fmap unLoc bf)
{-
************************************************************************
* *
\subsection[PatSynBind]{A pattern synonym definition}
* *
************************************************************************
-}
data HsPatSynDetails a
= InfixPatSyn a a
| PrefixPatSyn [a]
| RecordPatSyn [RecordPatSynField a]
deriving (Typeable, Data)
-- See Note [Record PatSyn Fields]
data RecordPatSynField a
= RecordPatSynField {
recordPatSynSelectorId :: a -- Selector name visible in rest of the file
, recordPatSynPatVar :: a
-- Filled in by renamer, the name used internally
-- by the pattern
} deriving (Typeable, Data)
{-
Note [Record PatSyn Fields]
Consider the following two pattern synonyms.
pattern P x y = ([x,True], [y,'v'])
pattern Q{ x, y } =([x,True], [y,'v'])
In P, we just have two local binders, x and y.
In Q, we have local binders but also top-level record selectors
x :: ([Bool], [Char]) -> Bool and similarly for y.
It would make sense to support record-like syntax
pattern Q{ x=x1, y=y1 } = ([x1,True], [y1,'v'])
when we have a different name for the local and top-level binder
the distinction between the two names clear
-}
instance Functor RecordPatSynField where
fmap f (RecordPatSynField visible hidden) =
RecordPatSynField (f visible) (f hidden)
instance Outputable a => Outputable (RecordPatSynField a) where
ppr (RecordPatSynField v _) = ppr v
instance Foldable RecordPatSynField where
foldMap f (RecordPatSynField visible hidden) =
f visible `mappend` f hidden
instance Traversable RecordPatSynField where
traverse f (RecordPatSynField visible hidden) =
RecordPatSynField <$> f visible <*> f hidden
instance Functor HsPatSynDetails where
fmap f (InfixPatSyn left right) = InfixPatSyn (f left) (f right)
fmap f (PrefixPatSyn args) = PrefixPatSyn (fmap f args)
fmap f (RecordPatSyn args) = RecordPatSyn (map (fmap f) args)
instance Foldable HsPatSynDetails where
foldMap f (InfixPatSyn left right) = f left `mappend` f right
foldMap f (PrefixPatSyn args) = foldMap f args
foldMap f (RecordPatSyn args) = foldMap (foldMap f) args
foldl1 f (InfixPatSyn left right) = left `f` right
foldl1 f (PrefixPatSyn args) = Data.List.foldl1 f args
foldl1 f (RecordPatSyn args) =
Data.List.foldl1 f (map (Data.Foldable.foldl1 f) args)
foldr1 f (InfixPatSyn left right) = left `f` right
foldr1 f (PrefixPatSyn args) = Data.List.foldr1 f args
foldr1 f (RecordPatSyn args) =
Data.List.foldr1 f (map (Data.Foldable.foldr1 f) args)
length (InfixPatSyn _ _) = 2
length (PrefixPatSyn args) = Data.List.length args
length (RecordPatSyn args) = Data.List.length args
null (InfixPatSyn _ _) = False
null (PrefixPatSyn args) = Data.List.null args
null (RecordPatSyn args) = Data.List.null args
toList (InfixPatSyn left right) = [left, right]
toList (PrefixPatSyn args) = args
toList (RecordPatSyn args) = foldMap toList args
instance Traversable HsPatSynDetails where
traverse f (InfixPatSyn left right) = InfixPatSyn <$> f left <*> f right
traverse f (PrefixPatSyn args) = PrefixPatSyn <$> traverse f args
traverse f (RecordPatSyn args) = RecordPatSyn <$> traverse (traverse f) args
data HsPatSynDir id
= Unidirectional
| ImplicitBidirectional
| ExplicitBidirectional (MatchGroup id (LHsExpr id))
deriving (Typeable)
deriving instance (DataId id) => Data (HsPatSynDir id)
| nushio3/ghc | compiler/hsSyn/HsBinds.hs | bsd-3-clause | 40,952 | 0 | 18 | 11,693 | 6,407 | 3,449 | 2,958 | 428 | 4 |
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module Hakyll.Web.Paginate
( PageNumber
, Paginate (..)
, buildPaginateWith
, paginateEvery
, paginateRules
, paginateContext
) where
--------------------------------------------------------------------------------
import Control.Monad (forM_)
import qualified Data.Map as M
import Data.Monoid (mconcat)
import qualified Data.Set as S
--------------------------------------------------------------------------------
import Hakyll.Core.Compiler
import Hakyll.Core.Identifier
import Hakyll.Core.Identifier.Pattern
import Hakyll.Core.Item
import Hakyll.Core.Metadata
import Hakyll.Core.Rules
import Hakyll.Web.Html
import Hakyll.Web.Template.Context
--------------------------------------------------------------------------------
type PageNumber = Int
--------------------------------------------------------------------------------
-- | Data about paginators
data Paginate = Paginate
{ paginateMap :: M.Map PageNumber [Identifier]
, paginateMakeId :: PageNumber -> Identifier
, paginateDependency :: Dependency
} deriving (Show)
--------------------------------------------------------------------------------
paginateNumPages :: Paginate -> Int
paginateNumPages = M.size . paginateMap
--------------------------------------------------------------------------------
paginateEvery :: Int -> [a] -> [[a]]
paginateEvery n = go
where
go [] = []
go xs = let (y, ys) = splitAt n xs in y : go ys
--------------------------------------------------------------------------------
buildPaginateWith
:: MonadMetadata m
=> ([Identifier] -> m [[Identifier]]) -- ^ Group items into pages
-> Pattern -- ^ Select items to paginate
-> (PageNumber -> Identifier) -- ^ Identifiers for the pages
-> m Paginate
buildPaginateWith grouper pattern makeId = do
ids <- getMatches pattern
idGroups <- grouper ids
let idsSet = S.fromList ids
return Paginate
{ paginateMap = M.fromList (zip [1 ..] idGroups)
, paginateMakeId = makeId
, paginateDependency = PatternDependency pattern idsSet
}
--------------------------------------------------------------------------------
paginateRules :: Paginate -> (PageNumber -> Pattern -> Rules ()) -> Rules ()
paginateRules paginator rules =
forM_ (M.toList $ paginateMap paginator) $ \(idx, identifiers) ->
rulesExtraDependencies [paginateDependency paginator] $
create [paginateMakeId paginator idx] $
rules idx $ fromList identifiers
--------------------------------------------------------------------------------
-- | Get the identifier for a certain page by passing in the page number.
paginatePage :: Paginate -> PageNumber -> Maybe Identifier
paginatePage pag pageNumber
| pageNumber < 1 = Nothing
| pageNumber > (paginateNumPages pag) = Nothing
| otherwise = Just $ paginateMakeId pag pageNumber
--------------------------------------------------------------------------------
-- | A default paginate context which provides the following keys:
--
--
paginateContext :: Paginate -> PageNumber -> Context a
paginateContext pag currentPage = mconcat
[ field "firstPageNum" $ \_ -> otherPage 1 >>= num
, field "firstPageUrl" $ \_ -> otherPage 1 >>= url
, field "previousPageNum" $ \_ -> otherPage (currentPage - 1) >>= num
, field "previousPageUrl" $ \_ -> otherPage (currentPage - 1) >>= url
, field "nextPageNum" $ \_ -> otherPage (currentPage + 1) >>= num
, field "nextPageUrl" $ \_ -> otherPage (currentPage + 1) >>= url
, field "lastPageNum" $ \_ -> otherPage lastPage >>= num
, field "lastPageUrl" $ \_ -> otherPage lastPage >>= url
, field "currentPageNum" $ \i -> thisPage i >>= num
, field "currentPageUrl" $ \i -> thisPage i >>= url
, constField "numPages" $ show $ paginateNumPages pag
]
where
lastPage = paginateNumPages pag
thisPage i = return (currentPage, itemIdentifier i)
otherPage n
| n == currentPage = fail $ "This is the current page: " ++ show n
| otherwise = case paginatePage pag n of
Nothing -> fail $ "No such page: " ++ show n
Just i -> return (n, i)
num :: (Int, Identifier) -> Compiler String
num = return . show . fst
url :: (Int, Identifier) -> Compiler String
url (n, i) = getRoute i >>= \mbR -> case mbR of
Just r -> return $ toUrl r
Nothing -> fail $ "No URL for page: " ++ show n
| Minoru/hakyll | src/Hakyll/Web/Paginate.hs | bsd-3-clause | 4,988 | 0 | 13 | 1,292 | 1,143 | 606 | 537 | 83 | 3 |
{-# OPTIONS -fglasgow-exts #-}
-- This one made GHC 6.4 loop becuause Unify.unify
-- didn't deal correctly with unifying
-- a :=: Foo a
-- where
-- type Foo a = a
module ShouldSucceed where
newtype PRef a = PRef a
type Drop1 a = a
class Ref a r | a -> r where readRef :: a -> r
instance Ref (PRef a) (Drop1 a) where readRef (PRef v) = v
| hvr/jhc | regress/tests/1_typecheck/2_pass/ghc/uncat/tc195.hs | mit | 344 | 0 | 8 | 79 | 88 | 52 | 36 | -1 | -1 |
-- GSoC 2015 - Haskell bindings for OpenCog.
{-# LANGUAGE DataKinds #-}
module PlnRules (
plnRuleEquivalenceHack
, plnRuleEliminateNeutralElementHack
, plnRuleEliminateDanglingJunctorHack
, plnRuleAndHack
, plnRuleForAllHack
, plnRuleAverageHack
) where
import OpenCog.AtomSpace (Atom(..),AtomType(BindT),stv,noTv,(|>),(\>))
plnRuleEquivalenceHack :: Atom BindT
plnRuleEquivalenceHack = BindLink
(VariableList [])
(ImplicationLink noTv
(EvaluationLink noTv
(PredicateNode "take" noTv)
(ListLink
|> QuoteLink (VariableNode "X")
\> PredicateNode "treatment-1" noTv
)
)
(EvaluationLink noTv
(PredicateNode "take" noTv)
(ListLink
|> QuoteLink (VariableNode "X")
\> PredicateNode "compound-A" noTv
)
)
)
(ImplicationLink (stv 1 1)
(PredicateNode "take-treatment-1" noTv)
(PredicateNode "take-compound-A" noTv)
)
plnRuleEliminateNeutralElementHack :: Atom BindT
plnRuleEliminateNeutralElementHack = BindLink
(VariableList [])
(ImplicationLink noTv
(AndLink noTv
|> EvaluationLink noTv
(PredicateNode "take" noTv)
(ListLink
|> QuoteLink (VariableNode "X")
\> PredicateNode "treatment-1" noTv
)
\> EvaluationLink noTv
(PredicateNode "contain" noTv)
(ListLink
|> PredicateNode "treatment-1" noTv
\> PredicateNode "compound-A" noTv
)
)
(EvaluationLink noTv
(PredicateNode "take" noTv)
(ListLink
|> QuoteLink (VariableNode "X")
\> PredicateNode "compound-A" noTv
)
)
)
(ImplicationLink (stv 1 1)
(AndLink noTv
\> EvaluationLink noTv
(PredicateNode "take" noTv)
(ListLink
|> VariableNode "X"
\> PredicateNode "treatment-1" noTv
)
)
(EvaluationLink noTv
(PredicateNode "take" noTv)
(ListLink
|> VariableNode "X"
\> PredicateNode "compound-A" noTv
)
)
)
plnRuleEliminateDanglingJunctorHack :: Atom BindT
plnRuleEliminateDanglingJunctorHack = BindLink
(VariableList [])
(ImplicationLink noTv
(AndLink noTv
\> EvaluationLink noTv
(PredicateNode "take" noTv)
(ListLink
|> QuoteLink (VariableNode "X")
\> PredicateNode "treatment-1" noTv
)
)
(EvaluationLink noTv
(PredicateNode "take" noTv)
(ListLink
|> QuoteLink (VariableNode "X")
\> PredicateNode "compound-A" noTv
)
)
)
(ImplicationLink (stv 1 1)
(EvaluationLink noTv
(PredicateNode "take" noTv)
(ListLink
|> VariableNode "X"
\> PredicateNode "treatment-1" noTv
)
)
(EvaluationLink noTv
(PredicateNode "take" noTv)
(ListLink
|> VariableNode "X"
\> PredicateNode "compound-A" noTv
)
)
)
plnRuleAndHack :: Atom BindT
plnRuleAndHack = BindLink
(VariableList [])
(AndLink noTv
|> EvaluationLink noTv
(PredicateNode "take" noTv)
(ListLink
|> QuoteLink (VariableNode "X")
\> VariableNode "Y"
)
\> EvaluationLink noTv
(PredicateNode "contain" noTv)
(ListLink
|> VariableNode "Y"
\> VariableNode "Z"
)
)
(AndLink (stv 1 1)
|> EvaluationLink noTv
(PredicateNode "take" noTv)
(ListLink
|> VariableNode "X"
\> VariableNode "Y"
)
\> EvaluationLink noTv
(PredicateNode "contain" noTv)
(ListLink
|> VariableNode "Y"
\> VariableNode "Z"
)
)
plnRuleForAllHack :: Atom BindT
plnRuleForAllHack = BindLink
(VariableList [])
(ForAllLink noTv
(ListLink
|> QuoteLink (VariableNode "X")
|> QuoteLink (VariableNode "Y")
\> QuoteLink (VariableNode "Z")
)
(ImplicationLink noTv
(AndLink noTv
|> EvaluationLink noTv
(PredicateNode "take" noTv)
(ListLink
|> QuoteLink (VariableNode "X")
\> QuoteLink (VariableNode "Y")
)
\> EvaluationLink noTv
(PredicateNode "contain" noTv)
(ListLink
|> QuoteLink (VariableNode "Y")
\> QuoteLink (VariableNode "Z")
)
)
(EvaluationLink noTv
(PredicateNode "take" noTv)
(ListLink
|> QuoteLink (VariableNode "X")
\> QuoteLink (VariableNode "Z")
)
)
)
)
(ImplicationLink (stv 1 1)
(AndLink noTv
|> EvaluationLink noTv
(PredicateNode "take" noTv)
(ListLink
|> VariableNode "X"
\> PredicateNode "treatment-1" noTv
)
\> EvaluationLink noTv
(PredicateNode "contain" noTv)
(ListLink
|> PredicateNode "treatment-1" noTv
\> PredicateNode "compound-A" noTv
)
)
(EvaluationLink noTv
(PredicateNode "take" noTv)
(ListLink
|> VariableNode "X"
\> PredicateNode "compound-A" noTv
)
)
)
plnRuleAverageHack :: Atom BindT
plnRuleAverageHack = BindLink
(VariableList [])
(AverageLink noTv
(QuoteLink (VariableNode "X"))
(ImplicationLink noTv
(MemberLink noTv
(QuoteLink (VariableNode "X"))
(ConceptNode "injury-recovery-speed-predicates" noTv)
)
(ImplicationLink noTv
(PredicateNode "is-well-hydrated" noTv)
(QuoteLink (VariableNode "X"))
)
)
)
(ImplicationLink (stv 0.7 0.6)
(MemberLink noTv
(PredicateNode "recovery-speed-of-injury-alpha" noTv)
(ConceptNode "injury-recovery-speed-predicates" noTv)
)
(ImplicationLink noTv
(PredicateNode "is-well-hydrated" noTv)
(PredicateNode "recovery-speed-of-injury-alpha" noTv)
)
)
| ruiting/opencog | examples/pln/moses-pln-synergy/haskell/PlnRules.hs | agpl-3.0 | 7,130 | 0 | 19 | 3,122 | 1,480 | 735 | 745 | 170 | 1 |
{-# LANGUAGE MagicHash #-}
module LiteralsTest2 where
x,y :: Int
x = 0003
y = 0x04
s :: String
s = "\x20"
c :: Char
c = '\x20'
d :: Double
d = 0.00
blah = x
where
charH = '\x41'#
intH = 0004#
wordH = 005##
floatH = 3.20#
doubleH = 04.16##
x = 1
| sgillespie/ghc | testsuite/tests/ghc-api/annotations-literals/LiteralsTest2.hs | bsd-3-clause | 276 | 0 | 6 | 87 | 89 | 55 | 34 | 18 | 1 |
-- file: ch03/ShapeUnion.hs
-- From chapter 3, http://book.realworldhaskell.org/read/defining-types-streamlining-functions.html
type Vector = (Double, Double)
data Shape = Circle Vector Double
| Poly [Vector]
| Sgoettschkes/learning | haskell/RealWorldHaskell/ch03/ShapeUnion.hs | mit | 215 | 0 | 7 | 28 | 34 | 21 | 13 | 3 | 0 |
{-# LANGUAGE ScopedTypeVariables #-}
module Main (main) where
import Control.Applicative
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as L
import Data.Maybe
import Data.MessagePack
import Test.QuickCheck
import Test.Tasty
import Test.Tasty.QuickCheck
main :: IO ()
main = defaultMain tests
instance Arbitrary a => Arbitrary (Assoc a) where
arbitrary = Assoc <$> arbitrary
instance Arbitrary S.ByteString where
arbitrary = S.pack <$> arbitrary
instance Arbitrary L.ByteString where
arbitrary = L.pack <$> arbitrary
mid :: MessagePack a => a -> a
mid = fromJust . unpack . pack
tests :: TestTree
tests =
testGroup "Identity Properties"
[ testProperty "int" $
\(a :: Int) -> a == mid a
, testProperty "nil" $
\(a :: ()) -> a == mid a
, testProperty "bool" $
\(a :: Bool) -> a == mid a
, testProperty "double" $
\(a :: Double) -> a == mid a
, testProperty "string" $
\(a :: String) -> a == mid a
, testProperty "bytestring" $
\(a :: S.ByteString) -> a == mid a
, testProperty "lazy-bytestring" $
\(a :: L.ByteString) -> a == mid a
, testProperty "[int]" $
\(a :: [Int]) -> a == mid a
, testProperty "[string]" $
\(a :: [String]) -> a == mid a
, testProperty "(int, int)" $
\(a :: (Int, Int)) -> a == mid a
, testProperty "(int, int, int)" $
\(a :: (Int, Int, Int)) -> a == mid a
, testProperty "(int, int, int, int)" $
\(a :: (Int, Int, Int, Int)) -> a == mid a
, testProperty "(int, int, int, int, int)" $
\(a :: (Int, Int, Int, Int, Int)) -> a == mid a
, testProperty "[(int, double)]" $
\(a :: [(Int, Double)]) -> a == mid a
, testProperty "[(string, string)]" $
\(a :: [(String, String)]) -> a == mid a
, testProperty "Assoc [(string, int)]" $
\(a :: Assoc [(String, Int)]) -> a == mid a
]
| voidlizard/ntced-tcp-proxy | contrib/msgpack/test/test.hs | mit | 1,978 | 0 | 13 | 558 | 742 | 404 | 338 | 55 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-| @shell@s out.
-}
module Workflow.OSX.Screenshot where
import Workflow.OSX.Extra
import Turtle
--import Control.Monad.Managed
import Codec.Picture
{-| Temporary file template.
@= "workflow-osx.XXXXXX"@
-}
__temporary__ :: Text
__temporary__ = "workflow-osx.XXXXXX.png"
{-| Takes screen shot of the whole screen (as PNG, no delay, no sound).
@shell@s out.
@.png@
-}
takeScreenshot :: IO (Either String DynamicImage)
takeScreenshot = with (mktempfile "/tmp" __temporary__) $ \path -> do
shells (format ("screencapture -x -tpng -T0 -o "%fp) path) empty -- NOTE throws ProcFailed
i <- liftIO $ readImage (fp2s path)
return i
{-
<https://hackage.haskell.org/package/JuicyPixels-3.2.7.1/docs/Codec-Picture.html#t:DynamicImage>
-}
| sboosali/workflow-osx | workflow-osx/sources/Workflow/OSX/Screenshot.hs | mit | 782 | 0 | 13 | 112 | 128 | 70 | 58 | 12 | 1 |
{-# LANGUAGE OverloadedStrings, CPP #-}
{-# LANGUAGE NamedFieldPuns #-}
module Network.Wai.Handler.Warp.HTTP2.Types where
import Data.ByteString.Builder (Builder)
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative ((<$>),(<*>))
#endif
import Control.Concurrent (forkIO)
import Control.Concurrent.STM
import Control.Exception (SomeException)
import Control.Monad (void)
import Control.Reaper
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.IntMap.Strict (IntMap, IntMap)
import qualified Data.IntMap.Strict as M
import qualified Network.HTTP.Types as H
import Network.Wai (Request, Response)
import Network.Wai.Handler.Warp.IORef
import Network.Wai.Handler.Warp.Types
import Network.HTTP2
import Network.HTTP2.Priority
import Network.HPACK
----------------------------------------------------------------
http2ver :: H.HttpVersion
http2ver = H.HttpVersion 2 0
isHTTP2 :: Transport -> Bool
isHTTP2 TCP = False
isHTTP2 tls = useHTTP2
where
useHTTP2 = case tlsNegotiatedProtocol tls of
Nothing -> False
Just proto -> "h2-" `BS.isPrefixOf` proto
----------------------------------------------------------------
data Input = Input Stream Request
----------------------------------------------------------------
data Control a = CFinish
| CNext a
| CNone
instance Show (Control a) where
show CFinish = "CFinish"
show (CNext _) = "CNext"
show CNone = "CNone"
type DynaNext = WindowSize -> IO Next
type BytesFilled = Int
data Next = Next BytesFilled (Control DynaNext)
data Output = OFinish
| OGoaway ByteString
| OFrame ByteString
| OResponse Stream Response Aux
| ONext Stream DynaNext
outputStream :: Output -> Stream
outputStream (OResponse strm _ _) = strm
outputStream (ONext strm _) = strm
outputStream _ = error "outputStream"
----------------------------------------------------------------
data Sequence = SFinish
| SFlush
| SBuilder Builder
data Sync = SyncNone
| SyncFinish
| SyncNext Output
data Aux = Oneshot Bool
| Persist (TBQueue Sequence) (TVar Sync)
----------------------------------------------------------------
-- | The context for HTTP/2 connection.
data Context = Context {
http2settings :: IORef Settings
, streamTable :: StreamTable
, concurrency :: IORef Int
-- | RFC 7540 says "Other frames (from any stream) MUST NOT
-- occur between the HEADERS frame and any CONTINUATION
-- frames that might follow". This field is used to implement
-- this requirement.
, continued :: IORef (Maybe StreamId)
, currentStreamId :: IORef StreamId
, inputQ :: TQueue Input
, outputQ :: PriorityTree Output
, encodeDynamicTable :: IORef DynamicTable
, decodeDynamicTable :: IORef DynamicTable
, connectionWindow :: TVar WindowSize
}
----------------------------------------------------------------
newContext :: IO Context
newContext = Context <$> newIORef defaultSettings
<*> initialize 10 -- fixme: hard coding: 10
<*> newIORef 0
<*> newIORef Nothing
<*> newIORef 0
<*> newTQueueIO
<*> newPriorityTree
<*> (newDynamicTableForEncoding defaultDynamicTableSize >>= newIORef)
<*> (newDynamicTableForDecoding defaultDynamicTableSize >>= newIORef)
<*> newTVarIO defaultInitialWindowSize
clearContext :: Context -> IO ()
clearContext ctx = void $ reaperStop $ streamTable ctx
----------------------------------------------------------------
data OpenState =
JustOpened
| Continued [HeaderBlockFragment]
Int -- Total size
Int -- The number of continuation frames
Bool -- End of stream
Priority
| NoBody HeaderList Priority
| HasBody HeaderList Priority
| Body (TQueue ByteString)
data ClosedCode = Finished
| Killed
| Reset ErrorCodeId
| ResetByMe SomeException
deriving Show
data StreamState =
Idle
| Open OpenState
| HalfClosed
| Closed ClosedCode
isIdle :: StreamState -> Bool
isIdle Idle = True
isIdle _ = False
isOpen :: StreamState -> Bool
isOpen Open{} = True
isOpen _ = False
isHalfClosed :: StreamState -> Bool
isHalfClosed HalfClosed = True
isHalfClosed _ = False
isClosed :: StreamState -> Bool
isClosed Closed{} = True
isClosed _ = False
instance Show StreamState where
show Idle = "Idle"
show Open{} = "Open"
show HalfClosed = "HalfClosed"
show (Closed e) = "Closed: " ++ show e
----------------------------------------------------------------
data Stream = Stream {
streamNumber :: StreamId
, streamState :: IORef StreamState
-- Next two fields are for error checking.
, streamContentLength :: IORef (Maybe Int)
, streamBodyLength :: IORef Int
, streamWindow :: TVar WindowSize
, streamPriority :: IORef Priority
}
instance Show Stream where
show s = show (streamNumber s)
newStream :: StreamId -> WindowSize -> IO Stream
newStream sid win = Stream sid <$> newIORef Idle
<*> newIORef Nothing
<*> newIORef 0
<*> newTVarIO win
<*> newIORef defaultPriority
----------------------------------------------------------------
opened :: Context -> Stream -> IO ()
opened Context{concurrency} Stream{streamState} = do
atomicModifyIORef' concurrency (\x -> (x+1,()))
writeIORef streamState (Open JustOpened)
closed :: Context -> Stream -> ClosedCode -> IO ()
closed Context{concurrency} Stream{streamState} cc = do
atomicModifyIORef' concurrency (\x -> (x-1,()))
writeIORef streamState (Closed cc)
----------------------------------------------------------------
type StreamTable = Reaper (IntMap Stream) (M.Key, Stream)
initialize :: Int -> IO StreamTable
initialize duration = mkReaper settings
where
settings = defaultReaperSettings {
reaperAction = clean
, reaperDelay = duration * 1000000
, reaperCons = uncurry M.insert
, reaperNull = M.null
, reaperEmpty = M.empty
}
clean :: IntMap Stream -> IO (IntMap Stream -> IntMap Stream)
clean old = do
new <- M.fromAscList <$> prune oldlist []
return $ M.union new
where
oldlist = M.toDescList old
prune [] lst = return lst
prune (x@(_,s):xs) lst = do
st <- readIORef (streamState s)
if isClosed st then
prune xs lst
else
prune xs (x:lst)
insert :: StreamTable -> M.Key -> Stream -> IO ()
insert strmtbl k v = reaperAdd strmtbl (k,v)
search :: StreamTable -> M.Key -> IO (Maybe Stream)
search strmtbl k = M.lookup k <$> reaperRead strmtbl
-- INVARIANT: streams in the output queue have non-zero window size.
enqueueWhenWindowIsOpen :: PriorityTree Output -> Output -> IO ()
enqueueWhenWindowIsOpen outQ out = do
let strm = outputStream out
atomically $ do
x <- readTVar $ streamWindow strm
check (x > 0)
pri <- readIORef $ streamPriority strm
enqueue outQ out pri
enqueueOrSpawnTemporaryWaiter :: Stream -> PriorityTree Output -> Output -> IO ()
enqueueOrSpawnTemporaryWaiter strm outQ out = do
sw <- atomically $ readTVar $ streamWindow strm
if sw == 0 then
-- This waiter waits only for the stream window.
void $ forkIO $ enqueueWhenWindowIsOpen outQ out
else do
pri <- readIORef $ streamPriority strm
enqueue outQ out pri
| iquiw/wai | warp/Network/Wai/Handler/Warp/HTTP2/Types.hs | mit | 7,860 | 0 | 15 | 2,059 | 1,909 | 1,016 | 893 | 181 | 3 |
{-# LANGUAGE ScopedTypeVariables #-}
-- | Add a bunch of checkers for testing properties of different algebraic
-- structures and relations
module Test.QuickCheck.Classes.Extra
( module Test.QuickCheck.Classes
-- | Algebraic structures
, group
, abelian
, ring
, commutativeRing
, field
-- | Relations
, complement
, strictTotalOrd
) where
import Data.Group (invert, Group, Abelian)
import Data.Monoid (Sum(..), Product)
import Test.QuickCheck.Extra (Arbitrary, (<=>), (==>))
import Test.QuickCheck.Modifiers (NonZero)
import Test.QuickCheck.Checkers (commutes, transitive, EqProp, (=-=), BinRel)
import Test.QuickCheck.Classes
import Test.Tasty.Extra (testGroup, TestTree, testTreeFromBatch, testTreeFromNamedBatch)
import Test.Tasty.QuickCheck (testProperty, Property, Gen, property, forAll)
distributesL :: EqProp a => (a -> a -> a) -> (a -> a -> a) -> a -> a -> a -> Property
distributesL (*:) (+:) a b c = a *: (b +: c) =-= (a *: b) +: (a *: c)
distributesR :: EqProp a => (a -> a -> a) -> (a -> a -> a) -> a -> a -> a -> Property
distributesR (*:) = distributesL (flip (*:))
distributes :: (Arbitrary a, EqProp a, Show a) => String -> (a -> a -> a) -> (a -> a -> a) -> TestTree
distributes s (*:) (+:) = testGroup s ts
where ts = [testProperty "left distributes" (distributesL (*:) (+:)),
testProperty "right distributes" (distributesR (*:) (+:))]
group :: forall a. (Arbitrary a, EqProp a, Group a, Show a) => String -> a -> TestTree
group s _ = testGroup s ts
where
ts = [ testTreeFromBatch (monoid (undefined :: a))
, testProperty "left inverse element" (\(x :: a) -> x <> invert x =-= mempty)
, testProperty "right inverse element" (\(x :: a) -> invert x <> x =-= mempty)
]
abelian :: forall a. (Arbitrary a, EqProp a, Abelian a, Show a) => String -> a -> TestTree
abelian s _ = testGroup s ts
where
ts = [ group "group" (undefined :: a)
, testProperty "commutative" (commutes ((<>) :: a -> a -> a))
]
ring :: forall a. (Arbitrary a, EqProp a, Num a, Show a) => String -> a -> TestTree
ring s _ = testGroup s ts
where
ts = [ abelian "abelian under Sum" (undefined :: Sum a)
, testTreeFromNamedBatch "monoid under product" (monoid (undefined :: Product a))
, distributes "* distributes over +" (*) ((+) :: a -> a -> a)
]
commutativeRing :: forall a. (Arbitrary a, EqProp a, Num a, Show a) => String -> a -> TestTree
commutativeRing s _ = testGroup s ts
where ts = [ring "ring" (undefined :: a),
testProperty "* commutes" (commutes ((*) :: a -> a -> a))]
-- TODO: Reduce the Ord constraint to an Eq constraint on the new quickcheck
-- release
field :: forall a. (Arbitrary a, EqProp a, Fractional a, Show a, Ord a) => String -> a -> TestTree
field s _ = testGroup s ts
where ts = [abelian "Abelian under Sum" (undefined :: Sum a),
abelian "Abelian under Product NonZero" (undefined :: Product (NonZero a)),
distributes "* distributes over +" (*) ((+) :: a -> a -> a)]
complement :: forall a. (Arbitrary a, EqProp a, Show a) =>
String -> (a -> Gen a) -> BinRel a -> BinRel a -> TestTree
complement s gen r1 r2 = testGroup s ts
where ts = [testProperty "strictOrd"
(property $ \ a ->
forAll (gen a) $ \ b ->
a `r1` b <=> not (a `r2` b))
]
strictTotalOrd
:: forall a
. (Arbitrary a, EqProp a, Eq a, Show a)
=> String
-> (a -> Gen a)
-> BinRel a
-> TestTree
strictTotalOrd s gen r = testGroup s ts
where
ts =
[ testProperty "irreflexive" (property $ \a -> not (a `r` a))
, testProperty "transitive" $ transitive r gen
, testProperty
"connected"
( property
$ \a -> forAll (gen a) $ \b -> (a /= b) ==> (a `r` b) || (b `r` a)
)
]
| expipiplus1/exact-real | test/Test/QuickCheck/Classes/Extra.hs | mit | 3,846 | 0 | 17 | 959 | 1,498 | 832 | 666 | 71 | 1 |
module Graphics.Vty.ReactiveBanana where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import Data.Maybe
import Graphics.Vty hiding (Event)
import Reactive.Banana
import Reactive.Banana.Frameworks
import qualified Graphics.Vty as V
type VEvent = V.Event
eventChan :: Vty -> IO (TChan VEvent)
eventChan v = do
eventChan <- newTChanIO
forkIO $ forever $ do
e <- nextEvent v
atomically $ writeTChan eventChan e
return eventChan
eventFromChan :: TChan a -> MomentIO (Event a)
eventFromChan chan = do
(event, handle) <- newEvent
liftIO $ forkIO $ forever $ do
a <- atomically $ tryReadTChan chan
case a of
Just x -> handle x
_ -> return ()
threadDelay $ 10 ^ 5
return event
tickEvent :: MomentIO (Event ())
tickEvent = do
(event, handle) <- newEvent
liftIO $ forkIO $ forever $ handle () >> threadDelay (3*10^4)
return event
blocking :: TChan Bool -> IO ()
blocking bChan = do
bool <- atomically $ tryReadTChan bChan
case bool of
Just True -> return ()
_ -> threadDelay (10^4) >> blocking bChan
drawChan :: Vty -> TChan (Maybe Picture) -> IO ()
drawChan v dChan = void $ forkIO $ forever $ do
pic <- atomically $ tryReadTChan dChan
case pic of
Just (Just x) -> update v x
_ -> return ()
threadDelay $ 10^5
makeVtyNetwork :: Vty -> (Event VEvent -> MomentIO (Behavior (Maybe Picture)))
-> IO ()
makeVtyNetwork v func = do
stopChan <- newTChanIO
updateChan <- newTChanIO
network <- compile $ do
events <- liftIO (eventChan v) >>= eventFromChan
outPic <- func events
tickE <- tickEvent
reactimate $ (atomically . writeTChan stopChan . isNothing) <$> (outPic <@ tickE)
reactimate $ (updateMaybe v) <$> (outPic <@ tickE)
actuate network
drawChan v updateChan
blocking stopChan
shutdown v
isKey :: Key -> VEvent -> Bool
isKey b (EvKey a _) = a == b
updateMaybe v (Just x) = update v x
updateMaybe _ _ = return ()
| edwardwas/vty-banana | src/Graphics/Vty/ReactiveBanana.hs | mit | 2,079 | 0 | 16 | 556 | 797 | 382 | 415 | 64 | 2 |
{-|
Module : Network.TokenBucket.Client
Description : Client for Token Bucket Server
Copyright : (c) Stack Builders Inc. 2014
License : MIT
Maintainer : justin@stackbuilders.com
Stability : experimental
Portability : unknown
Connects to a Token Bucket Server and requests tokens from the
specified bucket.
-}
module Network.TokenBucket.Client (connect, get) where
import GHC.IO.Handle ( Handle
, BufferMode(..)
, hGetLine
, hPutStr
, hClose
, hSetBuffering )
import Data.Pool (Pool(..), createPool, withResource)
import Network
-- | Connects to the given host, using a connection pool.
connect :: String
-- ^ Host name running the token bucket server
-> PortNumber
-- ^ Port number the token bucket service is running on
-> IO (Pool Handle)
-- ^ A pool of handles to the token bucket server
connect host port =
createPool (createConnection host port) destroyConnection 1 30 50
-- | Tries to get a token from the given bucket.
get :: Pool Handle -- ^ The pool of connections to the token bucket server
-> String -- ^ The name of a token bucket
-> IO (Either String Bool)
-- ^ The result of the token bucket server request, or the String error from
-- the server
get pool bucket = do
withResource pool (requestToken bucket)
requestToken :: String -> Handle -> IO (Either String Bool)
requestToken bucket handle = do
_ <- hPutStr handle $ "get " ++ bucket ++ "\r\n"
line <- hGetLine handle
return $ case line of
"1" -> Right True
"0" -> Right False
_ -> Left line
createConnection :: String -> PortNumber -> IO Handle
createConnection host port = do
hdl <- connectTo host (PortNumber port)
hSetBuffering hdl LineBuffering
return hdl
destroyConnection :: Handle -> IO ()
destroyConnection hdl = hClose hdl
| stackbuilders/token-bucket | src/Network/TokenBucket/Client.hs | mit | 1,928 | 0 | 11 | 510 | 367 | 190 | 177 | 34 | 3 |
-- |
-- Module : PostgresWebsockets.Config
-- Description : Manages PostgresWebsockets configuration options.
--
-- This module provides a helper function to read the command line
-- arguments using the AppConfig type to store
-- them. It also can be used to define other middleware configuration that
-- may be delegated to some sort of external configuration.
module PostgresWebsockets.Config
( prettyVersion,
loadConfig,
warpSettings,
AppConfig (..),
)
where
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base64 as B64
import Data.String (IsString (..))
import Data.Text (intercalate, pack, replace, strip, stripPrefix)
import Data.Version (versionBranch)
import Env
import Network.Wai.Handler.Warp
import Paths_postgres_websockets (version)
import Protolude hiding (intercalate, optional, replace, toS, (<>))
import Protolude.Conv
-- | Config file settings for the server
data AppConfig = AppConfig
{ configDatabase :: Text,
configPath :: Maybe Text,
configHost :: Text,
configPort :: Int,
configListenChannel :: Text,
configMetaChannel :: Maybe Text,
configJwtSecret :: ByteString,
configJwtSecretIsBase64 :: Bool,
configPool :: Int,
configRetries :: Int,
configReconnectInterval :: Maybe Int,
configCertificateFile :: Maybe Text,
configKeyFile :: Maybe Text
}
deriving (Show)
-- | User friendly version number
prettyVersion :: Text
prettyVersion = intercalate "." $ map show $ versionBranch version
-- | Load all postgres-websockets config from Environment variables. This can be used to use just the middleware or to feed into warpSettings
loadConfig :: IO AppConfig
loadConfig =
readOptions
>>= verifyTLSConfig
>>= loadSecretFile
>>= loadDatabaseURIFile
-- | Given a shutdown handler and an AppConfig builds a Warp Settings to start a stand-alone server
warpSettings :: (IO () -> IO ()) -> AppConfig -> Settings
warpSettings waitForShutdown AppConfig {..} =
setHost (fromString $ toS configHost)
. setPort configPort
. setServerName (toS $ "postgres-websockets/" <> prettyVersion)
. setTimeout 3600
. setInstallShutdownHandler waitForShutdown
. setGracefulShutdownTimeout (Just 5)
$ defaultSettings
-- private
-- | Function to read and parse options from the environment
readOptions :: IO AppConfig
readOptions =
Env.parse (header "You need to configure some environment variables to start the service.") $
AppConfig <$> var (str <=< nonempty) "PGWS_DB_URI" (help "String to connect to PostgreSQL")
<*> optional (var str "PGWS_ROOT_PATH" (help "Root path to serve static files, unset to disable."))
<*> var str "PGWS_HOST" (def "*4" <> helpDef show <> help "Address the server will listen for websocket connections")
<*> var auto "PGWS_PORT" (def 3000 <> helpDef show <> help "Port the server will listen for websocket connections")
<*> var str "PGWS_LISTEN_CHANNEL" (def "postgres-websockets-listener" <> helpDef show <> help "Master channel used in the database to send or read messages in any notification channel")
<*> optional (var str "PGWS_META_CHANNEL" (help "Websockets channel used to send events about the server state changes."))
<*> var str "PGWS_JWT_SECRET" (help "Secret used to sign JWT tokens used to open communications channels")
<*> var auto "PGWS_JWT_SECRET_BASE64" (def False <> helpDef show <> help "Indicate whether the JWT secret should be decoded from a base64 encoded string")
<*> var auto "PGWS_POOL_SIZE" (def 10 <> helpDef show <> help "How many connection to the database should be used by the connection pool")
<*> var auto "PGWS_RETRIES" (def 5 <> helpDef show <> help "How many times it should try to connect to the database on startup before exiting with an error")
<*> optional (var auto "PGWS_CHECK_LISTENER_INTERVAL" (helpDef show <> help "Interval for supervisor thread to check if listener connection is alive. 0 to disable it."))
<*> optional (var str "PGWS_CERTIFICATE_FILE" (helpDef show <> help "Certificate file to serve secure websockets connection (wss)."))
<*> optional (var str "PGWS_KEY_FILE" (helpDef show <> help "Key file to serve secure websockets connection (wss)."))
verifyTLSConfig :: AppConfig -> IO AppConfig
verifyTLSConfig conf@AppConfig {..} = do
when (isJust configCertificateFile /= isJust configKeyFile) $
panic "PGWS_TLS_CERTIFICATE and PGWS_TLS_KEY must be set in tandem"
pure conf
loadDatabaseURIFile :: AppConfig -> IO AppConfig
loadDatabaseURIFile conf@AppConfig {..} =
case stripPrefix "@" configDatabase of
Nothing -> pure conf
Just filename -> setDatabase . strip <$> readFile (toS filename)
where
setDatabase uri = conf {configDatabase = uri}
loadSecretFile :: AppConfig -> IO AppConfig
loadSecretFile conf = extractAndTransform secret
where
secret = decodeUtf8 $ configJwtSecret conf
isB64 = configJwtSecretIsBase64 conf
extractAndTransform :: Text -> IO AppConfig
extractAndTransform s =
fmap setSecret $
transformString isB64
=<< case stripPrefix "@" s of
Nothing -> return . encodeUtf8 $ s
Just filename -> chomp <$> BS.readFile (toS filename)
where
chomp bs = fromMaybe bs (BS.stripSuffix "\n" bs)
-- Turns the Base64url encoded JWT into Base64
transformString :: Bool -> ByteString -> IO ByteString
transformString False t = return t
transformString True t =
case B64.decode $ encodeUtf8 $ strip $ replaceUrlChars $ decodeUtf8 t of
Left errMsg -> panic $ pack errMsg
Right bs -> return bs
setSecret bs = conf {configJwtSecret = bs}
-- replace: Replace every occurrence of one substring with another
replaceUrlChars =
replace "_" "/" . replace "-" "+" . replace "." "="
| diogob/postgrest-ws | src/PostgresWebsockets/Config.hs | mit | 5,852 | 0 | 21 | 1,158 | 1,256 | 645 | 611 | -1 | -1 |
module QuickCheckHelper where
import Control.Applicative
import Language.DSKanren
import Test.QuickCheck hiding ((===))
data RPred = Conj RPred RPred
| Disconj RPred RPred
| Eq Term Term
| Neq Term Term
| Tigger
| Eeyore
deriving Show
toPredicate :: RPred -> Predicate
toPredicate t =
case t of
Conj l r -> conj (toPredicate l) (toPredicate r)
Disconj l r -> disconj (toPredicate l) (toPredicate r)
Eq l r -> l === r
Neq l r -> l =/= r
Tigger -> success
Eeyore -> failure
hasSolution :: Predicate -> Bool
hasSolution = runFor1
where runFor1 p = case run (const p) of
_ : _ -> True
[] -> False
mkTerm :: [Term] -> Gen Term
mkTerm vars = frequency $
case vars of
[] -> closedConstructs
_ -> (20, elements vars) : closedConstructs
where closedConstructs = [ (50, Atom <$> (listOf . elements $ ['a' .. 'z']))
, (5, Pair <$> mkTerm vars <*> mkTerm vars)]
mkPred :: [Term] -> Gen RPred
mkPred vars = -- TODO, Fit fresh in here somehow
oneof
[ Disconj <$> mkPred vars <*> mkPred vars
, Conj <$> mkPred vars <*> mkPred vars
, Eq <$> mkTerm vars <*> mkTerm vars
, Neq <$> mkTerm vars <*> mkTerm vars
, elements [Tigger, Eeyore]]
two :: Applicative f => f a -> f (a, a)
two f = (,) <$> f <*> f
three :: Applicative f => f a -> f (a, a, a)
three f = (,,) <$> f <*> f <*> f
forTerm :: Testable a => (Term -> a) -> Property
forTerm = forAll (mkTerm [currentGoal])
forTerm2 :: Testable a => (Term -> Term -> a) -> Property
forTerm2 p = forAll (two $ mkTerm [currentGoal]) $ \(l, r) -> p l r
forTerm3 :: Testable a => (Term -> Term -> Term -> a) -> Property
forTerm3 p = forAll (three $ mkTerm [currentGoal]) $ \(l, m, r) -> p l m r
forPred :: Testable a => (Predicate -> a) -> Property
forPred = forAll (mkPred [currentGoal]) . (. toPredicate)
forPred2 :: Testable a => (Predicate -> Predicate -> a) -> Property
forPred2 p = forAll (two $ mkPred [currentGoal]) $
\(l, r) -> p (toPredicate l) (toPredicate r)
forPred3 :: Testable a => (Predicate -> Predicate -> Predicate -> a) -> Property
forPred3 p = forAll (three $ mkPred [currentGoal]) $
\(l, m, r) -> p (toPredicate l) (toPredicate m) (toPredicate r)
| jozefg/ds-kanren | test/QuickCheckHelper.hs | mit | 2,304 | 0 | 12 | 616 | 989 | 517 | 472 | 58 | 6 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.HTMLImageElement
(js_setName, setName, js_getName, getName, js_setAlign, setAlign,
js_getAlign, getAlign, js_setAlt, setAlt, js_getAlt, getAlt,
js_setBorder, setBorder, js_getBorder, getBorder,
js_setCrossOrigin, setCrossOrigin, js_getCrossOrigin,
getCrossOrigin, js_setHeight, setHeight, js_getHeight, getHeight,
js_setHspace, setHspace, js_getHspace, getHspace, js_setIsMap,
setIsMap, js_getIsMap, getIsMap, js_setLongDesc, setLongDesc,
js_getLongDesc, getLongDesc, js_setSrc, setSrc, js_getSrc, getSrc,
js_setSrcset, setSrcset, js_getSrcset, getSrcset, js_setSizes,
setSizes, js_getSizes, getSizes, js_getCurrentSrc, getCurrentSrc,
js_setUseMap, setUseMap, js_getUseMap, getUseMap, js_setVspace,
setVspace, js_getVspace, getVspace, js_setWidth, setWidth,
js_getWidth, getWidth, js_getComplete, getComplete, js_setLowsrc,
setLowsrc, js_getLowsrc, getLowsrc, js_getNaturalHeight,
getNaturalHeight, js_getNaturalWidth, getNaturalWidth, js_getX,
getX, js_getY, getY, HTMLImageElement, castToHTMLImageElement,
gTypeHTMLImageElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"name\"] = $2;" js_setName ::
HTMLImageElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.name Mozilla HTMLImageElement.name documentation>
setName ::
(MonadIO m, ToJSString val) => HTMLImageElement -> val -> m ()
setName self val = liftIO (js_setName (self) (toJSString val))
foreign import javascript unsafe "$1[\"name\"]" js_getName ::
HTMLImageElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.name Mozilla HTMLImageElement.name documentation>
getName ::
(MonadIO m, FromJSString result) => HTMLImageElement -> m result
getName self = liftIO (fromJSString <$> (js_getName (self)))
foreign import javascript unsafe "$1[\"align\"] = $2;" js_setAlign
:: HTMLImageElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.align Mozilla HTMLImageElement.align documentation>
setAlign ::
(MonadIO m, ToJSString val) => HTMLImageElement -> val -> m ()
setAlign self val = liftIO (js_setAlign (self) (toJSString val))
foreign import javascript unsafe "$1[\"align\"]" js_getAlign ::
HTMLImageElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.align Mozilla HTMLImageElement.align documentation>
getAlign ::
(MonadIO m, FromJSString result) => HTMLImageElement -> m result
getAlign self = liftIO (fromJSString <$> (js_getAlign (self)))
foreign import javascript unsafe "$1[\"alt\"] = $2;" js_setAlt ::
HTMLImageElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.alt Mozilla HTMLImageElement.alt documentation>
setAlt ::
(MonadIO m, ToJSString val) => HTMLImageElement -> val -> m ()
setAlt self val = liftIO (js_setAlt (self) (toJSString val))
foreign import javascript unsafe "$1[\"alt\"]" js_getAlt ::
HTMLImageElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.alt Mozilla HTMLImageElement.alt documentation>
getAlt ::
(MonadIO m, FromJSString result) => HTMLImageElement -> m result
getAlt self = liftIO (fromJSString <$> (js_getAlt (self)))
foreign import javascript unsafe "$1[\"border\"] = $2;"
js_setBorder :: HTMLImageElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.border Mozilla HTMLImageElement.border documentation>
setBorder ::
(MonadIO m, ToJSString val) => HTMLImageElement -> val -> m ()
setBorder self val = liftIO (js_setBorder (self) (toJSString val))
foreign import javascript unsafe "$1[\"border\"]" js_getBorder ::
HTMLImageElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.border Mozilla HTMLImageElement.border documentation>
getBorder ::
(MonadIO m, FromJSString result) => HTMLImageElement -> m result
getBorder self = liftIO (fromJSString <$> (js_getBorder (self)))
foreign import javascript unsafe "$1[\"crossOrigin\"] = $2;"
js_setCrossOrigin :: HTMLImageElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.crossOrigin Mozilla HTMLImageElement.crossOrigin documentation>
setCrossOrigin ::
(MonadIO m, ToJSString val) => HTMLImageElement -> val -> m ()
setCrossOrigin self val
= liftIO (js_setCrossOrigin (self) (toJSString val))
foreign import javascript unsafe "$1[\"crossOrigin\"]"
js_getCrossOrigin :: HTMLImageElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.crossOrigin Mozilla HTMLImageElement.crossOrigin documentation>
getCrossOrigin ::
(MonadIO m, FromJSString result) => HTMLImageElement -> m result
getCrossOrigin self
= liftIO (fromJSString <$> (js_getCrossOrigin (self)))
foreign import javascript unsafe "$1[\"height\"] = $2;"
js_setHeight :: HTMLImageElement -> Int -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.height Mozilla HTMLImageElement.height documentation>
setHeight :: (MonadIO m) => HTMLImageElement -> Int -> m ()
setHeight self val = liftIO (js_setHeight (self) val)
foreign import javascript unsafe "$1[\"height\"]" js_getHeight ::
HTMLImageElement -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.height Mozilla HTMLImageElement.height documentation>
getHeight :: (MonadIO m) => HTMLImageElement -> m Int
getHeight self = liftIO (js_getHeight (self))
foreign import javascript unsafe "$1[\"hspace\"] = $2;"
js_setHspace :: HTMLImageElement -> Int -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.hspace Mozilla HTMLImageElement.hspace documentation>
setHspace :: (MonadIO m) => HTMLImageElement -> Int -> m ()
setHspace self val = liftIO (js_setHspace (self) val)
foreign import javascript unsafe "$1[\"hspace\"]" js_getHspace ::
HTMLImageElement -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.hspace Mozilla HTMLImageElement.hspace documentation>
getHspace :: (MonadIO m) => HTMLImageElement -> m Int
getHspace self = liftIO (js_getHspace (self))
foreign import javascript unsafe "$1[\"isMap\"] = $2;" js_setIsMap
:: HTMLImageElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.isMap Mozilla HTMLImageElement.isMap documentation>
setIsMap :: (MonadIO m) => HTMLImageElement -> Bool -> m ()
setIsMap self val = liftIO (js_setIsMap (self) val)
foreign import javascript unsafe "($1[\"isMap\"] ? 1 : 0)"
js_getIsMap :: HTMLImageElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.isMap Mozilla HTMLImageElement.isMap documentation>
getIsMap :: (MonadIO m) => HTMLImageElement -> m Bool
getIsMap self = liftIO (js_getIsMap (self))
foreign import javascript unsafe "$1[\"longDesc\"] = $2;"
js_setLongDesc :: HTMLImageElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.longDesc Mozilla HTMLImageElement.longDesc documentation>
setLongDesc ::
(MonadIO m, ToJSString val) => HTMLImageElement -> val -> m ()
setLongDesc self val
= liftIO (js_setLongDesc (self) (toJSString val))
foreign import javascript unsafe "$1[\"longDesc\"]" js_getLongDesc
:: HTMLImageElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.longDesc Mozilla HTMLImageElement.longDesc documentation>
getLongDesc ::
(MonadIO m, FromJSString result) => HTMLImageElement -> m result
getLongDesc self
= liftIO (fromJSString <$> (js_getLongDesc (self)))
foreign import javascript unsafe "$1[\"src\"] = $2;" js_setSrc ::
HTMLImageElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.src Mozilla HTMLImageElement.src documentation>
setSrc ::
(MonadIO m, ToJSString val) => HTMLImageElement -> val -> m ()
setSrc self val = liftIO (js_setSrc (self) (toJSString val))
foreign import javascript unsafe "$1[\"src\"]" js_getSrc ::
HTMLImageElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.src Mozilla HTMLImageElement.src documentation>
getSrc ::
(MonadIO m, FromJSString result) => HTMLImageElement -> m result
getSrc self = liftIO (fromJSString <$> (js_getSrc (self)))
foreign import javascript unsafe "$1[\"srcset\"] = $2;"
js_setSrcset :: HTMLImageElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.srcset Mozilla HTMLImageElement.srcset documentation>
setSrcset ::
(MonadIO m, ToJSString val) => HTMLImageElement -> val -> m ()
setSrcset self val = liftIO (js_setSrcset (self) (toJSString val))
foreign import javascript unsafe "$1[\"srcset\"]" js_getSrcset ::
HTMLImageElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.srcset Mozilla HTMLImageElement.srcset documentation>
getSrcset ::
(MonadIO m, FromJSString result) => HTMLImageElement -> m result
getSrcset self = liftIO (fromJSString <$> (js_getSrcset (self)))
foreign import javascript unsafe "$1[\"sizes\"] = $2;" js_setSizes
:: HTMLImageElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.sizes Mozilla HTMLImageElement.sizes documentation>
setSizes ::
(MonadIO m, ToJSString val) => HTMLImageElement -> val -> m ()
setSizes self val = liftIO (js_setSizes (self) (toJSString val))
foreign import javascript unsafe "$1[\"sizes\"]" js_getSizes ::
HTMLImageElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.sizes Mozilla HTMLImageElement.sizes documentation>
getSizes ::
(MonadIO m, FromJSString result) => HTMLImageElement -> m result
getSizes self = liftIO (fromJSString <$> (js_getSizes (self)))
foreign import javascript unsafe "$1[\"currentSrc\"]"
js_getCurrentSrc :: HTMLImageElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.currentSrc Mozilla HTMLImageElement.currentSrc documentation>
getCurrentSrc ::
(MonadIO m, FromJSString result) => HTMLImageElement -> m result
getCurrentSrc self
= liftIO (fromJSString <$> (js_getCurrentSrc (self)))
foreign import javascript unsafe "$1[\"useMap\"] = $2;"
js_setUseMap :: HTMLImageElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.useMap Mozilla HTMLImageElement.useMap documentation>
setUseMap ::
(MonadIO m, ToJSString val) => HTMLImageElement -> val -> m ()
setUseMap self val = liftIO (js_setUseMap (self) (toJSString val))
foreign import javascript unsafe "$1[\"useMap\"]" js_getUseMap ::
HTMLImageElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.useMap Mozilla HTMLImageElement.useMap documentation>
getUseMap ::
(MonadIO m, FromJSString result) => HTMLImageElement -> m result
getUseMap self = liftIO (fromJSString <$> (js_getUseMap (self)))
foreign import javascript unsafe "$1[\"vspace\"] = $2;"
js_setVspace :: HTMLImageElement -> Int -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.vspace Mozilla HTMLImageElement.vspace documentation>
setVspace :: (MonadIO m) => HTMLImageElement -> Int -> m ()
setVspace self val = liftIO (js_setVspace (self) val)
foreign import javascript unsafe "$1[\"vspace\"]" js_getVspace ::
HTMLImageElement -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.vspace Mozilla HTMLImageElement.vspace documentation>
getVspace :: (MonadIO m) => HTMLImageElement -> m Int
getVspace self = liftIO (js_getVspace (self))
foreign import javascript unsafe "$1[\"width\"] = $2;" js_setWidth
:: HTMLImageElement -> Int -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.width Mozilla HTMLImageElement.width documentation>
setWidth :: (MonadIO m) => HTMLImageElement -> Int -> m ()
setWidth self val = liftIO (js_setWidth (self) val)
foreign import javascript unsafe "$1[\"width\"]" js_getWidth ::
HTMLImageElement -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.width Mozilla HTMLImageElement.width documentation>
getWidth :: (MonadIO m) => HTMLImageElement -> m Int
getWidth self = liftIO (js_getWidth (self))
foreign import javascript unsafe "($1[\"complete\"] ? 1 : 0)"
js_getComplete :: HTMLImageElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.complete Mozilla HTMLImageElement.complete documentation>
getComplete :: (MonadIO m) => HTMLImageElement -> m Bool
getComplete self = liftIO (js_getComplete (self))
foreign import javascript unsafe "$1[\"lowsrc\"] = $2;"
js_setLowsrc :: HTMLImageElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.lowsrc Mozilla HTMLImageElement.lowsrc documentation>
setLowsrc ::
(MonadIO m, ToJSString val) => HTMLImageElement -> val -> m ()
setLowsrc self val = liftIO (js_setLowsrc (self) (toJSString val))
foreign import javascript unsafe "$1[\"lowsrc\"]" js_getLowsrc ::
HTMLImageElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.lowsrc Mozilla HTMLImageElement.lowsrc documentation>
getLowsrc ::
(MonadIO m, FromJSString result) => HTMLImageElement -> m result
getLowsrc self = liftIO (fromJSString <$> (js_getLowsrc (self)))
foreign import javascript unsafe "$1[\"naturalHeight\"]"
js_getNaturalHeight :: HTMLImageElement -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.naturalHeight Mozilla HTMLImageElement.naturalHeight documentation>
getNaturalHeight :: (MonadIO m) => HTMLImageElement -> m Int
getNaturalHeight self = liftIO (js_getNaturalHeight (self))
foreign import javascript unsafe "$1[\"naturalWidth\"]"
js_getNaturalWidth :: HTMLImageElement -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.naturalWidth Mozilla HTMLImageElement.naturalWidth documentation>
getNaturalWidth :: (MonadIO m) => HTMLImageElement -> m Int
getNaturalWidth self = liftIO (js_getNaturalWidth (self))
foreign import javascript unsafe "$1[\"x\"]" js_getX ::
HTMLImageElement -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.x Mozilla HTMLImageElement.x documentation>
getX :: (MonadIO m) => HTMLImageElement -> m Int
getX self = liftIO (js_getX (self))
foreign import javascript unsafe "$1[\"y\"]" js_getY ::
HTMLImageElement -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.y Mozilla HTMLImageElement.y documentation>
getY :: (MonadIO m) => HTMLImageElement -> m Int
getY self = liftIO (js_getY (self)) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/HTMLImageElement.hs | mit | 16,234 | 260 | 10 | 2,424 | 3,486 | 1,873 | 1,613 | 213 | 1 |
module Tach.Wavelet.Types where
import Tach.Wavelet.Types.Internal
| smurphy8/tach | core-types/tach-wavelet-types/src/Tach/Wavelet/Types.hs | mit | 68 | 0 | 4 | 6 | 14 | 10 | 4 | 2 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sagemaker-endpointconfig.html
module Stratosphere.Resources.SageMakerEndpointConfig where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.SageMakerEndpointConfigProductionVariant
import Stratosphere.ResourceProperties.Tag
-- | Full data type definition for SageMakerEndpointConfig. See
-- 'sageMakerEndpointConfig' for a more convenient constructor.
data SageMakerEndpointConfig =
SageMakerEndpointConfig
{ _sageMakerEndpointConfigEndpointConfigName :: Maybe (Val Text)
, _sageMakerEndpointConfigKmsKeyId :: Maybe (Val Text)
, _sageMakerEndpointConfigProductionVariants :: [SageMakerEndpointConfigProductionVariant]
, _sageMakerEndpointConfigTags :: Maybe [Tag]
} deriving (Show, Eq)
instance ToResourceProperties SageMakerEndpointConfig where
toResourceProperties SageMakerEndpointConfig{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::SageMaker::EndpointConfig"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ fmap (("EndpointConfigName",) . toJSON) _sageMakerEndpointConfigEndpointConfigName
, fmap (("KmsKeyId",) . toJSON) _sageMakerEndpointConfigKmsKeyId
, (Just . ("ProductionVariants",) . toJSON) _sageMakerEndpointConfigProductionVariants
, fmap (("Tags",) . toJSON) _sageMakerEndpointConfigTags
]
}
-- | Constructor for 'SageMakerEndpointConfig' containing required fields as
-- arguments.
sageMakerEndpointConfig
:: [SageMakerEndpointConfigProductionVariant] -- ^ 'smecProductionVariants'
-> SageMakerEndpointConfig
sageMakerEndpointConfig productionVariantsarg =
SageMakerEndpointConfig
{ _sageMakerEndpointConfigEndpointConfigName = Nothing
, _sageMakerEndpointConfigKmsKeyId = Nothing
, _sageMakerEndpointConfigProductionVariants = productionVariantsarg
, _sageMakerEndpointConfigTags = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sagemaker-endpointconfig.html#cfn-sagemaker-endpointconfig-endpointconfigname
smecEndpointConfigName :: Lens' SageMakerEndpointConfig (Maybe (Val Text))
smecEndpointConfigName = lens _sageMakerEndpointConfigEndpointConfigName (\s a -> s { _sageMakerEndpointConfigEndpointConfigName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sagemaker-endpointconfig.html#cfn-sagemaker-endpointconfig-kmskeyid
smecKmsKeyId :: Lens' SageMakerEndpointConfig (Maybe (Val Text))
smecKmsKeyId = lens _sageMakerEndpointConfigKmsKeyId (\s a -> s { _sageMakerEndpointConfigKmsKeyId = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sagemaker-endpointconfig.html#cfn-sagemaker-endpointconfig-productionvariants
smecProductionVariants :: Lens' SageMakerEndpointConfig [SageMakerEndpointConfigProductionVariant]
smecProductionVariants = lens _sageMakerEndpointConfigProductionVariants (\s a -> s { _sageMakerEndpointConfigProductionVariants = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sagemaker-endpointconfig.html#cfn-sagemaker-endpointconfig-tags
smecTags :: Lens' SageMakerEndpointConfig (Maybe [Tag])
smecTags = lens _sageMakerEndpointConfigTags (\s a -> s { _sageMakerEndpointConfigTags = a })
| frontrowed/stratosphere | library-gen/Stratosphere/Resources/SageMakerEndpointConfig.hs | mit | 3,448 | 0 | 15 | 351 | 464 | 269 | 195 | 42 | 1 |
import XMonad
import XMonad.Actions.SpawnOn
import XMonad.Config.Desktop
import XMonad.Layout.Spacing
import XMonad.Layout.ThreeColumns
import XMonad.Layout.NoBorders
import XMonad.Layout.Gaps
import XMonad.Layout.PerWorkspace
import XMonad.Hooks.FadeInactive
import XMonad.Hooks.DynamicLog
import XMonad.Hooks.ManageDocks
import XMonad.Util.Run
import System.IO
import Data.Time.Clock.POSIX
import System.Directory
import System.FilePath
------------
-- COLORS --
------------
primaryColor = "#E0444F"
bgColor = "#2F2A30"
fgColor = "#B9B9B9"
-----------
-- FONTS --
-----------
mainFont = "xft:Monoid:pixelsize=12:antialias=true:hinting=true"
------------------
-- BASIC CONFIG --
------------------
baseConfig = desktopConfig
myTerminal = "urxvt"
myModMask = mod4Mask
myBorderWidth = 3
myFocusedBorderColor = primaryColor
myNormalBorderColor = bgColor
getXMobarConfig = do
homeDir <- getHomeDirectory
return $ homeDir </> ".xmobarrc"
getWallpaperDir = do
homeDir <- getHomeDirectory
return $ homeDir </> "Pictures/wallpapers"
-------------
-- LAYOUTS --
-------------
gapLayout = gaps [(U, 20)]
spacedLayout = spacing 10
tiledLayout ratio =
spacedLayout $
Tall nmaster delta ratio where
nmaster = 1
delta = 5/100
fullLayout =
noBorders Full
defaultLayout =
gapLayout $
tiledLayout (2/3) |||
Mirror (tiledLayout (1/2)) |||
fullLayout
gimpLayout =
gapLayout $
spacedLayout $
ThreeCol 2 (3/100) (3/4)
mediaLayout =
gapLayout $
tiledLayout (1/2) |||
tiledLayout (2/3) |||
fullLayout
devLayout =
gapLayout $
tiledLayout (1/2) |||
tiledLayout (2/3)
----------------
-- WORKSPACES --
----------------
-- I:home II:dev III:media IV:gimp
myWorkspaces = ["I", "II", "III", "IV"]
myLayoutHook =
onWorkspaces ["II"] devLayout $
onWorkspaces ["III"] mediaLayout $
onWorkspaces ["IV"] gimpLayout $
defaultLayout
------------------
-- STARTUP HOOK --
------------------
myStartupHook = do
spawnOn "III" "nuvolaplayer3"
spawnOn "II" "urxvt"
spawnOn "IV" "gimp"
spawnOn "II" "atom"
-----------------
-- MANAGEHOOKS --
-----------------
myManageHook = composeAll
[ className =? "Gimp" --> doShift "IV"
, className =? "Nuvolaplayer3" --> doShift "III"
, className =? "Atom" --> doShift "II"
]
--------------------
-- SETUP DEFAULTS --
--------------------
defaults = baseConfig
{ modMask = myModMask
, terminal = myTerminal
, borderWidth = myBorderWidth
, layoutHook = myLayoutHook
, workspaces = myWorkspaces
, manageHook = composeAll
[ manageSpawn
, myManageHook
, manageHook defaultConfig
]
, focusedBorderColor = myFocusedBorderColor
, normalBorderColor = myNormalBorderColor
, startupHook = myStartupHook
}
----------
-- BARS --
----------
dmenuCommand = "dmenu"
genXMobarCommand = do
xConfig <- getXMobarConfig
return $ "xmobar --bgcolor=" ++ bgColor ++
" --fgcolor=" ++ fgColor ++
" --font=" ++ mainFont ++
" " ++ xConfig
----------------
-- BACKGROUND --
----------------
genBackgroundCommand = do
wallpaperDir <- getWallpaperDir
image <- chooseItem . listDirectory $ wallpaperDir
homeDir <- getHomeDirectory
return $ "feh --bg-fill "++ homeDir ++"/Pictures/wallpapers/"++ image
-------------
-- COMPTON --
-------------
genComptonCommand = do
homeDir <- getHomeDirectory
return $ "compton --config "++ homeDir ++"/.config/compton.conf"
----------
-- MAIN --
----------
main = do
comptonCommand <- genComptonCommand
comptonproc <- spawnPipe comptonCommand
xmobarCommand <- genXMobarCommand
xmproc <- spawnPipe xmobarCommand
bgCommand <- genBackgroundCommand
bgproc <- spawnPipe bgCommand
xmonad defaults
{ logHook = fadeInactiveLogHook 0.85 >> dynamicLogWithPP xmobarPP
{ ppOutput = hPutStrLn xmproc
, ppTitle = xmobarColor fgColor "" . shorten 75
, ppLayout = const ""
, ppCurrent = xmobarColor primaryColor ""
, ppVisible = xmobarColor fgColor ""
, ppHiddenNoWindows = const ""
, ppWsSep = " "
, ppSep = " "
}
}
-----------------------
-- UTILITY FUNCTIONS --
-----------------------
chooseItem :: IO [ String ] -> IO String
chooseItem list = do
time <- getPOSIXTime
l <- list
return $ l !! (mod (round time) (length l))
| quentunahelper/Black-Rainbow-XMonad-Theme | xmonad.hs | mit | 4,159 | 68 | 15 | 660 | 1,096 | 596 | 500 | 124 | 1 |
{-# LANGUAGE OverloadedStrings,FlexibleInstances #-}
-- |The NSString class declares the programmatic interface for an object that manages
-- immutable strings. An immutable string is a text string that is defined when it
-- is created and subsequently cannot be changed. NSString is implemented to represent
-- an array of Unicode characters, in other words, a text string.
module Cocoa.NSString where
import Cocoa
import Data.String
import Foreign.C
import System.IO.Unsafe(unsafePerformIO)
-- * Types
-- |'IsNSObject' compatable wrapper for NSStrings
data TyNSString a = TyNSString Id
-- * Functions
-- |Create a new 'NSString'
newNSString :: String -> IO (TyNSString Id)
newNSString val = do
cStr <- newCString val >>= cstr2id
nsstr <- "NSString" $<- "alloc"
toNSString $ (nsstr $<<- "initWithUTF8String:") [cStr]
-- |Create a new 'NSString'
-- this function uses 'unsafePerformIO'
newNSString' :: String -> TyNSString Id
newNSString' val = unsafePerformIO $ newNSString val
-- |Checks equality of two 'NSString', uses /isEqualToString:/ internally.
isEqualToString :: TyNSString Id -> TyNSString Id -> IO Bool
isEqualToString str1 str2 = do
nsbool <- (idVal str1 $<<- "isEqualToString:") [idVal str2] >>= id2bool
return (nsboolToBool nsbool)
-- |Checks equality of two 'NSString', uses /isEqualToString:/ internally.
-- this function uses 'unsafePerformIO'
isEqualToString' :: TyNSString Id -> TyNSString Id -> Bool
isEqualToString' str1 str2 = unsafePerformIO (str1 `isEqualToString` str2)
-- TODO: A way to group all the NSObject instances under the one set of functions
-- using pattern matching? or ADT w/ DataTypes?
-- |Retrieve the underlying 'Id' type from an 'NSObject'
getStringId :: TyNSString a -> Id
getStringId (TyNSString a) = a
-- |Wrap 'IO' 'Id' object in 'TyNSString'
toNSString :: IO Id -> IO (TyNSString Id)
toNSString obj = obj >>= \o -> return (TyNSString o)
-- |Convert an 'NSString' to an 'IO' 'String'
nsstringToString :: TyNSString Id -> IO String
nsstringToString str = do
cStr <- idVal str $<- "UTF8String"
id2cstr cStr >>= peekCString
-- instances
-- | when checking equality of 'NSString' run 'isEqualToString''
instance Eq (TyNSString Id) where
(==) x y = x `isEqualToString'` y
-- |Overload strings for ('NSString' 'Id') with 'newNSString''
instance IsString (TyNSString Id) where
fromString = newNSString'
-- |'NSString' encases an 'Id'
instance IsNSObject (TyNSString Id) where
idVal = getStringId
| aktowns/pdfkiths | Cocoa/nsstring.hs | mit | 2,481 | 0 | 12 | 405 | 466 | 245 | 221 | 34 | 1 |
-- Functiile care pot fi folosite sunt descrise la sfarsitul fisierului
-- categoria A - functii de baza
-- categoria B - functii din biblioteci (fara map, filter, fold)
-- categoria C - map, filter, fold
import Data.Char
import Test.QuickCheck
type Cifra = Int
type Numar = [Cifra]
-- In acest test vom implementa cateva operatii pe numere mari.
-- O Cifra este un numar intreg intre 0 si 9.
-- Un Numar este o lista de Cifre. E.g., [2,1,4]
-- Numarul intreg reprezentat de un Numar n este obtinut
-- prin alipirea cifrelor lui n de la stanga la dreapta,
-- ignorand cifrele de 0 de la inceputul numarului.
-- E.g., numarul corespunzator lui [0, 0, 0, 2, 1, 4] este 214.
-- Prin conventie lista vida de cifre [] poate reprezenta nr. 0
-- 1a (0,5p). Scrieti o functie care date fiind un Numar n si o lungime l,
-- adauga l cifre de 0 la stanga lui n.
-- E.g., lungimePlus [2, 1, 4] 3 = [0, 0, 0, 2, 1, 4]
lungimePlus :: Numar -> Int -> Numar
lungimePlus nr l = replicate l 0 ++ nr
-- 1b (1p). Scrieti o functie care ia ca argument o pereche de numere
-- si calculeaza perechea de numere cu numar egal de cifre
-- obtinuta prin adaugarea de zerouri la stanga numerelor date ca argument.
-- E.g., normalizeazaLungime ([1,2], [3,4,5,6]) = ([0,0,1,2], [3,4,5,6])
-- E.g., normalizeazaLungime ([1,2], []) = ([1,2], [0,0])
normalizeazaLungime :: (Numar, Numar) -> (Numar, Numar)
normalizeazaLungime (nr1, nr2)
| length nr1 > length nr2 = (nr1, lungimePlus nr2 (length nr1 - length nr2))
| length nr1 < length nr2 = (lungimePlus nr1 (length nr2 - length nr1), nr2)
| otherwise = (nr1, nr2)
-- 2a (0,75p). Scrieti o functie care ia doua Numere *de aceeasi lungime* ca argumente
-- si verifica daca primul Numar este mai mic sau egal cu al doilea.
-- Puteti folosi doar recursie si functii din categoria A
-- E.g., [1,2,3] `lteN` [1,2,1] = False
-- E.g., [0,2,3] `lteN` [1,2,1] = True
lteN :: Numar -> Numar -> Bool
lten [] [] = True
lteN (x:xs) (y:ys)
| x < y = True
| x > y = False
| otherwise = lteN xs ys
-- 2b (0,25p). Scrieti o functie care ia doua Numere ca argumente
-- si verifica daca primul Numar este mai mic sau egal cu al doilea
lte :: Numar -> Numar -> Bool
lte nr1 nr2 = uncurry lteN (normalizeazaLungime (nr1, nr2))
-- Testing
lte' :: Numar -> Numar -> Bool
lte' nr1 nr2 = uncurry lteN (curry normalizeazaLungime nr1 nr2)
-- 3a (1p). Scrieti o functie care primeste ca argument o lista de
-- numere naturale intre 0 si 81, reprezentand rezultatele brute
-- ale unei operatii asupra unui numar, si calculeaza o pereche
-- formata dintr-o Cifra c si o lista de cifre cs, unde cs are aceeasi
-- lungime ca lista initiala, fiind obtinuta prin propagarea
-- depasirilor de cifre de la dreapta la stanga, iar c este cifra
-- care reprezinta depasirea in plus.
-- E.g. propagaFold' [1, 1] = (0, [1, 1]) -- obtinut din 10 + 1
-- E.g. propagaFold' [1, 10] = (0, [2, 0]) -- obtinut din 19 + 1
-- E.g. propagaFold' [10, 1] = (1, [0, 1]) -- obtinut din 30 + 71
-- E.g. propagaFold' [81, 81] = (8, [9, 1]) -- obtinut din 9*99
-- Folositi doar functii din categoriile A, B, si C
-- Fara recursie sau descrieri de liste.
propagaFold' :: [Int] -> (Cifra, [Cifra])
propagaFold' xs
| last xs > 9 = undefined
-- 3b (0,5p). Scrieti o functie care primeste ca argument o lista
-- de numere naturale ca la (3a) si calculeaza numarul corespunzator ei
-- obtinut prin propagarea depasirilor.
-- E.g. propagaFold [1, 1] = [0, 1, 1] -- obtinut din 10 + 1
-- E.g. propagaFold [1, 10] = [0, 2, 0] -- obtinut din 19 + 1
-- E.g. propagaFold [10, 1] = [1, 1, 1] -- obtinut din 30 + 71
-- E.g. propagaFold [81, 81] = [8, 9, 1] -- obtinut din 9*99
propagaFold :: [Int] -> Numar
propagaFold = undefined
-- 4a (0,75p). Scrieti o functie care primeste ca argument doua liste de cifre
-- *de lungime egala* cs1 si cs2, si calculeaza lista de intregi cs
-- cu proprietatea ca pentru toti i, cs !! i == cs1 !! i + cs2 !! i
--
-- E.g., [7,2,3] `plusLista` [4,5,7] = [11,7,10]
-- Folositi doar recursie si functii din categoria A
plusLista :: [Cifra] -> [Cifra] -> [Int]
plusLista [] [] = []
plusLista (x:xs) (y:ys) = x + y : plusLista xs ys
-- 4b (0,25p). Scrieti o functie care primeste ca argument doua Numere
-- si calculeaza suma lor
-- E.g., [7,2,3] `plus` [4,5,7] = [1,1,8,0]
-- E.g., [7,3] `plus` [4,5,7] = [5,3,0]
plus :: Numar -> Numar -> Numar
plus = undefined
-- 5a (0,75p). Scrieti o functie care primeste ca argument doua liste de cifre
-- *de lungime egala* cs1 si cs2, si calculeaza lista de intregi cs
-- cu proprietatea ca pentru toti i, cs !! i == cs1 !! i + cs2 !! i
-- E.g., [7,2,3] `minusLista` [4,5,7] = [3,-3,-4]
-- Folositi doar descrieri de liste si functii din categoriile A si B
-- Fara recursie
minusLista :: [Cifra] -> [Cifra] -> [Int]
minusLista xs ys = [x - y | (x, y) <- zip xs ys]
-- 5b (0,25p). Scrieti o functie care primeste ca argument doua Numere
-- si calculeaza diferenta lor, daca primul este mai mare sau egal decat al doilea.
-- In caz contrar, esueaza cu mesajul "Numere negative neimplementate"
-- E.g., [7,2,3] `minus` [4,5,7] = [2,6,6]
-- E.g., [7,3] `minus` [4,5,7] *** Exception: Numere negative neimplementate
minus :: Numar -> Numar -> Numar
minus = undefined
-- 6a (0,75p). Scrieti o functie care primeste ca argument o Cifra c si un Numar n
-- si calculeaza Numarul obtinut prin inmultirea lui n cu c.
-- E.g., 4 `mulC` [1,0,4] = [4,1,6]
-- E.g., 9 `mulC` [9,9] = [8,9,1]
-- Folositi doar functii din categoriile A, B, si C, si functiile definite mai sus.
-- Fara recursie sau descrieri de liste.
mulC :: Cifra -> Numar -> Numar
mulC = undefined
-- 6b (0,25). Scrieti o functie care primeste ca argument un Numar n
-- si calculeaza Numarul obtinut prin inmultirea lui n cu 10.
-- E.g., mul10 [3,4,5] = [3,4,5,0]
-- E.g., mul10 [3,5] = [3,5,0]
mul10 :: Numar -> Numar
mul10 nr = nr ++ [0]
-- 7 (2p). Scrieti o functie care primeste ca argument doua Numere
-- si calculeaza Numarul obtinut prin imultirea celor doua numere.
-- E.g., [1,2] `mul` [5,3] = [6,3,6]
-- E.g., [9,9,9] `mul` [9,9,9] = [9,9,8,0,0,1]
-- (32 de simboluri)
mul :: Numar -> Numar -> Numar
mul = undefined
{- Catcgoria A. Functii de baza
div, mod :: Integral a => a -> a -> a
even, odd :: Integral a => a -> Bool
(+), (*), (-), (/) :: Num a => a -> a -> a
(<), (<=), (>), (>=) :: Ord => a -> a -> Bool
(==), (/=) :: Eq a => a -> a -> Bool
(&&), (||) :: Bool -> Bool -> Bool
not :: Bool -> Bool
max, min :: Ord a => a -> a -> a
isAlpha, isAlphaNum, isLower, isUpper, isDigit :: Char -> Bool
toLower, toUpper :: Char -> Char
ord :: Char -> Int
chr :: Int -> Char
Intervale
[first..], [first,second..], [first..last], [first,second..last]
-}
{- Categoria B. Funetii din biblioteci
sum, product :: (Num a) => [a] -> a
sum [1.0,2.0,3.0] = 6.0
product [1,2,3,4] = 24
and, or :: [Bool] -> Bool
and [True,False,True] = False
or [True,False,True] = True
maximum, minimum :: (Ord a) => [a] -> a
maximum [3,1,4,2] = 4
minimum [3,1,4,2] = 1
reverse :: [a] -> [a]
reverse "goodbye" = "eybdoog"
concat :: [[a]] -> [a]
concat ["go","od","bye"] = "goodbye"
(++) :: [a] -> [a] -> [a]
"good" ++ "bye" = "goodbye"
(!!) :: [a] -> Int -> a
[9,7,5] !! 1 = 7
length :: [a] -> Int
length [9,7,5] = 3
head :: [a] -> a
head "goodbye" = 'g'
tail :: [a] -> [a]
tail "goodbye" = "oodbye"
init :: [a] -> [a]
init "goodbye" = "goodby"
last :: [a] -> a
last "goodbye" = 'e'
takeWhile :: (a->Bool) -> [a] -> [a]
takeWhile isLower "goodBye" = "good"
take :: Int -> [a] -> [a]
take 4 "goodbye" = "good"
dropWhile :: (a->Bool) -> [a] -> [a]
dropWhile isLower "goodBye" = "Bye"
drop :: Int -> [a] -> [a]
drop 4 "goodbye" = "bye"
elem :: (Eq a) => a -> [a] -> Bool
elem 'd' "goodbye" = True
replicate :: Int -> a -> [a]
replicate 5 '*' = "*****"
zip :: [a] -> [b] -> [(a,b)]
zip [1,2,3,4] [1,4,9] = [(1,1),(2,4),(3,9)
-}
{- Categoria C. Map, Filter, Fold
map :: (a -> b) -> [a] -> [b]
map (+3) [1,2] = [4,5]
filter :: (a -> Bool) -> [a] -> [a]
filter even [1,2,3,4] = [2,4]
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr max 0 [1,2,3,4] = 4
(.) :: (b -> c) -> (a -> b) -> a -> c
($) :: (a -> b) -> a -> b
(*2) . (+3) $ 7 = 20
flip :: (a -> b -> c) -> b -> a -> c
flip (-) 2 3 = 1
curry :: ((a, b) -> c) -> a -> b -> c
curry snd 1 2 = 2
uncurry :: a -> b -> c -> (a, b) -> c
uncurry (*) (3,7) = 21
-}
| PavelClaudiuStefan/FMI | An_3_Semestru_1/ProgramareDeclarativa/Laboratoare/Laborator6/pregatire-testare.hs | cc0-1.0 | 8,920 | 0 | 10 | 2,301 | 732 | 426 | 306 | 41 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.