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
----------------------------------------------------------------------------- -- StaticMonad: Static environment for Monad -- -- Part of `Typing Haskell in Haskell', version of November 23, 2000 -- Copyright (c) Mark P Jones and the Oregon Graduate Institute -- of Science and Technology, 1999-2000 -- -- This program is distributed as Free Software under the terms -- in the file "License" that is included in the distribution -- of this software, copies of which may be obtained from: -- http://www.cse.ogi.edu/~mpj/thih/ -- ----------------------------------------------------------------------------- module Thih.Static.Monad (module Thih.Static.Prim, module Thih.Static.Prelude, module Thih.Static.Monad) where import Thih.Static.Prim import Thih.Static.Prelude ----------------------------------------------------------------------------- -- Monad classes: monadClasses = addClass "MonadPlus" [cMonad] <:> instances instsMonadPlus instsMonadPlus = [mkInst [] ([] :=> isIn1 cMonadPlus tMaybe), mkInst [] ([] :=> isIn1 cMonadPlus tList)] cMonadPlus = "MonadPlus" mzeroMfun = "mzero" :>: (Forall [Kfun Star Star, Star] ([isIn1 cMonadPlus (TGen 0)] :=> (TAp (TGen 0) (TGen 1)))) mplusMfun = "mplus" :>: (Forall [Kfun Star Star, Star] ([isIn1 cMonadPlus (TGen 0)] :=> (TAp (TGen 0) (TGen 1) `fn` TAp (TGen 0) (TGen 1) `fn` TAp (TGen 0) (TGen 1)))) -----------------------------------------------------------------------------
yu-i9/thih
src/Thih/Static/Monad.hs
bsd-3-clause
1,687
0
15
430
320
181
139
19
1
-- | Peano-style natural numbers. {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE UndecidableInstances #-} module Data.Type.Nat where import Data.Functor import Data.Proxy import Data.Singletons.TH import Data.Typeable import Data.Type.Equality import GHC.Exts (Constraint) import Language.Haskell.TH import Language.Haskell.TH.Quote -- | Peano-style natural numbers. -- -- Mainly useful as promoted index. -- -- There's a 'QuasiQuoter' that allows you to write down natural number -- literals in expressions, patterns and types (promoted). Example: -- -- >>> [nat| 3 |] -- Suc (Suc (Suc Zero)) -- >>> :t [nat| 3 |] -- [nat| 3 |] :: Nat -- >>> :k [nat| 3 |] -- [nat| 3 |] :: Nat -- data Nat = Zero | Suc Nat deriving (Show, Read, Eq, Ord, Typeable) genSingletons [''Nat] singEqInstance ''Nat singDecideInstance ''Nat type N0 = Zero type N1 = Suc N0 type N2 = Suc N1 type N3 = Suc N2 type N4 = Suc N3 type N5 = Suc N4 type N6 = Suc N5 type N7 = Suc N6 type N8 = Suc N7 type N9 = Suc N8 type N10 = Suc N9 -- | A 'QuasiQuoter' for literals of type 'Nat'. -- -- See the documentation of 'Nat' for further details. -- nat :: QuasiQuoter nat = QuasiQuoter { quoteExp = natExp , quotePat = natPat , quoteType = natType , quoteDec = error "cannot quote nat in Dec" } where natExp :: String -> Q Exp natExp s = go (read s) where go :: Integer -> Q Exp go 0 = [| Zero |] go n = [| Suc $(go (n - 1)) |] natPat :: String -> Q Pat natPat s = go (read s) where go :: Integer -> Q Pat go 0 = [p| Zero |] go n = [p| Suc $(go (n - 1)) |] natType :: String -> Q Type natType s = go (read s) where go :: Integer -> Q Type go 0 = [t| Zero |] go n = [t| Suc $(go (n - 1)) |] deriving instance Eq (SNat n) deriving instance Ord (SNat n) deriving instance Show (SNat n) -- | A 'QuasiQuoter' for literals of type 'SNat'. -- -- This quasiquoter can be used in expressions and in patterns. -- -- Examples: -- -- >>> [snat| 3 |] -- SSuc (SSuc (SSuc SZero)) -- >>> :t [snat| 3 |] -- [snat| 3 |] :: Sing ('Suc ('Suc ('Suc 'Zero))) -- >>> :t [snat| 2 |] -- [snat| 2 |] :: Sing ('Suc ('Suc 'Zero)) -- snat :: QuasiQuoter snat = QuasiQuoter { quoteExp = snatExp , quotePat = snatPat , quoteType = error "cannot quote snat in Type" , quoteDec = error "cannot quote snat in Dec" } where snatExp :: String -> Q Exp snatExp s = go (read s) where go :: Integer -> Q Exp go 0 = [| SZero |] go n = [| SSuc $(go (n - 1)) |] snatPat :: String -> Q Pat snatPat s = go (read s) where go :: Integer -> Q Pat go 0 = [p| SZero |] go n = [p| SSuc $(go (n - 1)) |] -- | Kind-specialized synonym for 'SingI'. type SNatI = SNatI' SingI type SNatI' (n :: Nat -> Constraint) = n -- | Type-specialized synonym for 'sing'. sNat :: SNatI n => SNat n sNat = sing -- | General induction principle for 'Nat'-indexed types. ind :: forall r n. r Zero -> (forall n. r n -> r (Suc n)) -> SNat n -> r n ind zero suc = go where go :: forall n. SNat n -> r n go SZero = zero go (SSuc n) = suc (go n) -- | Standard type-level addition on natural numbers. -- -- > Zero + n = n -- > Suc m + n = Suc (m + n) -- type family (+) (m :: Nat) (n :: Nat) :: Nat type instance (+) Zero n = n type instance (+) (Suc m) n = Suc (m + n) -- | "Accumulating" type-level addition on natural numbers. -- -- > Zero + n = n -- > Suc m + n = n + Suc m -- type family PlusAcc (n :: Nat) (acc :: Nat) :: Nat type instance PlusAcc Zero acc = acc type instance PlusAcc (Suc n) acc = PlusAcc n (Suc acc) thmPlusZero :: SNat n -> (n + Zero) :~: n thmPlusZero SZero = Refl thmPlusZero (SSuc s) = gcastWith (thmPlusZero s) Refl thmPlusSuc :: SNat m -> SNat n -> (m + Suc n) :~: (Suc (m + n)) thmPlusSuc SZero _ = Refl thmPlusSuc (SSuc s) n = gcastWith (thmPlusSuc s n) Refl newtype Shift (r :: Nat -> *) (n :: Nat) where Shift :: r (Suc n) -> Shift r n deriving instance Show (r (Suc n)) => Show (Shift r n) unShift :: Shift r n -> r (Suc n) unShift (Shift x) = x
kosmikus/tilt
src/Data/Type/Nat.hs
bsd-3-clause
4,219
0
13
1,172
1,274
717
557
-1
-1
-- | Some additional functions on top of "System.FSNotify". -- -- Example of compiling scss files with compass -- -- @ -- compass :: WatchManager -> FilePath -> IO () -- compass man dir = do -- putStrLn $ "compass " ++ encodeString dir -- treeExtExists man dir "scss" $ \fp -> -- when ("deploy" `notElem` splitDirectories fp) $ do -- let d = encodeString $ head (splitDirectories rel) -- system "cd " ++ d ++ "&& bundle exec compass compile" -- return () -- @ module System.FSNotify.Devel ( treeExtAny, treeExtExists, doAllEvents, allEvents, existsEvents ) where import Prelude hiding (FilePath) import Data.Text import System.FilePath import System.FSNotify import System.FSNotify.Path (hasThisExtension) -- | In the given directory tree, watch for any 'Added' and 'Modified' -- events (but ignore 'Removed' events) for files with the given file -- extension treeExtExists :: WatchManager -> FilePath -- ^ Directory to watch -> Text -- ^ extension -> (FilePath -> IO ()) -- ^ action to run on file -> IO StopListening treeExtExists man dir ext action = watchTree man dir (existsEvents $ flip hasThisExtension ext) (doAllEvents action) -- | In the given directory tree, watch for any events for files with the -- given file extension treeExtAny :: WatchManager -> FilePath -- ^ Directory to watch -> Text -- ^ extension -> (FilePath -> IO ()) -- ^ action to run on file -> IO StopListening treeExtAny man dir ext action = watchTree man dir (allEvents $ flip hasThisExtension ext) (doAllEvents action) -- | Turn a 'FilePath' callback into an 'Event' callback that ignores the -- 'Event' type and timestamp doAllEvents :: Monad m => (FilePath -> m ()) -> Event -> m () doAllEvents action event = case event of Added f _ -> action f Modified f _ -> action f Removed f _ -> action f -- | Turn a 'FilePath' predicate into an 'Event' predicate that accepts -- only 'Added' and 'Modified' event types existsEvents :: (FilePath -> Bool) -> (Event -> Bool) existsEvents filt event = case event of Added f _ -> filt f Modified f _ -> filt f Removed _ _ -> False -- | Turn a 'FilePath' predicate into an 'Event' predicate that accepts -- any event types allEvents :: (FilePath -> Bool) -> (Event -> Bool) allEvents filt event = case event of Added f _ -> filt f Modified f _ -> filt f Removed f _ -> filt f
tomv564/hfsnotify
src/System/FSNotify/Devel.hs
bsd-3-clause
2,460
0
12
570
492
263
229
41
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} module Lib ( startApp ) where import Control.Lens import Control.Monad.Except import Control.Monad.Reader import Data.Aeson import Data.Aeson.TH import Data.Aeson.Encode.Pretty (encodePretty) import Data.Default import Data.Maybe import qualified Data.ByteString.Lazy as BL import Data.Pool import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Database.Neo4j as Neo import Network.Wai import Network.Wai.Handler.Warp import Servant import Api.Project import Api.Common import Configuration import qualified Graph.Project as Project type Api = ProjectApi newtype App a = App { runApp :: ReaderT (Pool Neo.Connection) (ExceptT ServantErr IO) a } deriving ( Monad , Functor , Applicative , MonadReader (Pool Neo.Connection) , MonadIO , MonadError ServantErr ) -------------------------------------------------------------------------------- -- Servant setup. startApp :: Configuration -> IO () startApp (Configuration host port user pass) = let hostBs = TE.encodeUtf8 host userBs = TE.encodeUtf8 user passBs = TE.encodeUtf8 pass in do pool <- createPool (Neo.newAuthConnection hostBs port (userBs, passBs)) (\c -> putStrLn "Destroying... Haha not!" ) -- fixme, destroy connections! 6 10 10 run 8080 (app pool) app :: Pool Neo.Connection -> Application app conn = serve api (readerServer conn) api :: Proxy Api api = Proxy readerServer :: Pool Neo.Connection -> Server Api readerServer pool = enter (runAppT pool) readerServerT readerServerT :: ServerT Api App readerServerT = listProjects :<|> createProject -- | Transform our App type back into a Handler. runAppT :: Pool Neo.Connection -> App :~> Handler runAppT pool = Nat (flip runReaderT pool . runApp) -------------------------------------------------------------------------------- -- | Api Implementation. listProjects :: Maybe Offset -> Maybe Limit -> App (Paged [ProjectSummary]) listProjects maybeOffset maybeLimit = do let offset = fromMaybe def maybeOffset let limit = fromMaybe def maybeLimit pool <- ask eitherResult <- liftIO (Project.listProjects pool offset limit) case eitherResult of Right ps -> pure $ (consPage ps) offset limit Left err -> throwError (err500 { errBody = BL.fromStrict (TE.encodeUtf8 err) }) where consPage projects | null projects == False = Paged (Just projects) | otherwise = Paged (Nothing) createProject :: ProjectName -> App () createProject name = do pool <- ask eitherResult <- liftIO (Project.createProject pool name) case eitherResult of Right _ -> pure () Left err -> throwError (err500 { errBody = BL.fromStrict (TE.encodeUtf8 err) })
vulgr/vulgr
src/Lib.hs
bsd-3-clause
3,027
0
17
658
818
429
389
77
2
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} ------------------------------------------------------------------------------- -- -- | 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(..), WarnReason(..), Language(..), PlatformConstants(..), FatalMessager, LogAction, FlushOut(..), FlushErr(..), ProfAuto(..), glasgowExtsFlags, dopt, dopt_set, dopt_unset, gopt, gopt_set, gopt_unset, setGeneralFlag', unSetGeneralFlag', wopt, wopt_set, wopt_unset, xopt, xopt_set, xopt_unset, lang_set, useUnicodeSyntax, whenGeneratingDynamicToo, ifGeneratingDynamicToo, whenCannotGenerateDynamicToo, dynamicTooMkDynamicDynFlags, DynFlags(..), FlagSpec(..), HasDynFlags(..), ContainsDynFlags(..), RtsOptsEnabled(..), HscTarget(..), isObjectTarget, defaultObjectTarget, targetRetainsAllBindings, GhcMode(..), isOneShot, GhcLink(..), isNoLink, PackageFlag(..), PackageArg(..), ModRenaming(..), IgnorePackageFlag(..), TrustFlag(..), PkgConfRef(..), Option(..), showOpt, DynLibLoader(..), fFlags, fLangFlags, xFlags, wWarningFlags, dynFlagDependencies, tablesNextToCode, mkTablesNextToCode, SigOf, getSigOf, makeDynFlagsConsistent, 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, programName, projectVersion, ghcUsagePath, ghciUsagePath, topDir, tmpDir, rawSettings, versionedAppDir, extraGccViaCFlags, systemPackageConfig, pgm_L, pgm_P, pgm_F, pgm_c, pgm_s, pgm_a, pgm_l, pgm_dll, pgm_T, pgm_windres, pgm_libtool, pgm_lo, pgm_lc, pgm_i, opt_L, opt_P, opt_F, opt_c, opt_a, opt_l, opt_i, opt_windres, opt_lo, opt_lc, -- ** Manipulating DynFlags defaultDynFlags, -- Settings -> DynFlags defaultWays, interpWays, interpreterProfiled, interpreterDynamic, initDynFlags, -- DynFlags -> IO DynFlags defaultFatalMessager, defaultLogAction, defaultLogActionHPrintDoc, defaultLogActionHPutStrDoc, defaultFlushOut, defaultFlushErr, getOpts, -- DynFlags -> (DynFlags -> [a]) -> [a] getVerbFlags, updOptLevel, setTmpDir, setUnitId, interpretPackageEnv, -- ** Parsing DynFlags parseDynamicFlagsCmdLine, parseDynamicFilePragma, parseDynamicFlagsFull, -- ** Available DynFlags allNonDeprecatedFlags, flagsAll, flagsDynamic, flagsPackage, flagsForCompletion, supportedLanguagesAndExtensions, languageExtensions, -- ** DynFlags C compiler options picCCOpts, picPOpts, -- * 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, emptyPackageState) import DriverPhases ( Phase(..), phaseInputExt ) import Config import CmdLineParser import Constants import Panic import Util import Maybes import MonadUtils import qualified Pretty import SrcLoc import BasicTypes ( IntWithInf, treatZeroAsInf ) import FastString import Outputable import Foreign.C ( CInt(..) ) import System.IO.Unsafe ( unsafeDupablePerformIO ) import {-# SOURCE #-} ErrUtils ( Severity(..), MsgDoc, mkLocMessageAnn ) import System.IO.Unsafe ( unsafePerformIO ) import Data.IORef import Control.Arrow ((&&&)) import Control.Monad import Control.Monad.Trans.Class import Control.Monad.Trans.Writer import Control.Monad.Trans.Reader import Control.Monad.Trans.Except import Control.Exception (throwIO) import Data.Bits import Data.Char import Data.Int import Data.List import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import Data.Word import System.FilePath import System.Directory import System.Environment (getEnv) 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) import qualified GHC.LanguageExtensions as LangExt -- Note [Updating flag description in the User's Guide] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- If you modify anything in this file please make sure that your changes are -- described in the User's Guide. Usually at least two sections need to be -- updated: -- -- * Flag Reference section generated from the modules in -- utils/mkUserGuidePart/Options -- -- * Flag description in docs/users_guide/using.rst provides a detailed -- explanation of flags' usage. -- Note [Supporting CLI completion] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- The command line interface completion (in for example bash) is an easy way -- for the developer to learn what flags are available from GHC. -- GHC helps by separating which flags are available when compiling with GHC, -- and which flags are available when using GHCi. -- A flag is assumed to either work in both these modes, or only in one of them. -- When adding or changing a flag, please consider for which mode the flag will -- have effect, and annotate it accordingly. For Flags use defFlag, defGhcFlag, -- defGhciFlag, and for FlagSpec use flagSpec or flagGhciSpec. -- Note [Adding a language extension] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- There are a few steps to adding (or removing) a language extension, -- -- * Adding the extension to GHC.LanguageExtensions -- -- The Extension type in libraries/ghc-boot/GHC/LanguageExtensions.hs is -- the canonical list of language extensions known by GHC. -- -- * Adding a flag to DynFlags.xFlags -- -- This is fairly self-explanatory. The name should be concise, memorable, -- and consistent with any previous implementations of the similar idea in -- other Haskell compilers. -- -- * Adding the flag to the documentation -- -- This is the same as any other flag. See -- Note [Updating flag description in the User's Guide] -- -- * Adding the flag to Cabal -- -- The Cabal library has its own list of all language extensions supported -- by all major compilers. This is the list that user code being uploaded -- to Hackage is checked against to ensure language extension validity. -- Consequently, it is very important that this list remains up-to-date. -- -- To this end, there is a testsuite test (testsuite/tests/driver/T4437.hs) -- whose job it is to ensure these GHC's extensions are consistent with -- Cabal. -- -- The recommended workflow is, -- -- 1. Temporarily add your new language extension to the -- expectedGhcOnlyExtensions list in T4437 to ensure the test doesn't -- break while Cabal is updated. -- -- 2. After your GHC change is accepted, submit a Cabal pull request adding -- your new extension to Cabal's list (found in -- Cabal/Language/Haskell/Extension.hs). -- -- 3. After your Cabal change is accepted, let the GHC developers know so -- they can update the Cabal submodule and remove the extensions from -- expectedGhcOnlyExtensions. -- -- * Adding the flag to the GHC Wiki -- -- There is a change log tracking language extension additions and removals -- on the GHC wiki: https://ghc.haskell.org/trac/ghc/wiki/LanguagePragmaHistory -- -- See Trac #4437 and #8176. -- ----------------------------------------------------------------------------- -- DynFlags data DumpFlag -- See Note [Updating flag description in the User's Guide] -- 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_switch | 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_simpl | Opt_D_dump_simpl_iterations | Opt_D_dump_spec | Opt_D_dump_prep | Opt_D_dump_stg | Opt_D_dump_call_arity | Opt_D_dump_stranal | Opt_D_dump_str_signatures | 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_th_dec_file | 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 | Opt_D_dump_debug deriving (Eq, Show, Enum) -- | Enumerates the simple on-or-off dynamic flags data GeneralFlag -- See Note [Updating flag description in the User's Guide] = 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_DoAnnotationLinting | Opt_NoLlvmMangler -- hidden flag | Opt_WarnIsError -- -Werror; makes warnings fatal | Opt_ShowWarnGroups -- Show the group a warning belongs to | Opt_PrintExplicitForalls | Opt_PrintExplicitKinds | Opt_PrintExplicitCoercions | Opt_PrintEqualityRelations | Opt_PrintUnicodeSyntax | Opt_PrintExpandedSynonyms | Opt_PrintPotentialInstances | Opt_PrintTypecheckerElaboration -- optimisation opts | Opt_CallArity | Opt_Strictness | Opt_LateDmdAnal | Opt_KillAbsence | Opt_KillOneShot | Opt_FullLaziness | Opt_FloatIn | Opt_Specialise | Opt_SpecialiseAggressively | Opt_CrossModuleSpecialise | 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_LlvmFillUndefWithGarbage -- Testing for undef bugs (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] | Opt_CprAnal | Opt_WorkerWrapper -- 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_SplitSections | Opt_StgStats | Opt_HideAllPackages | Opt_HideAllPluginPackages | Opt_PrintBindResult | Opt_Haddock | Opt_HaddockOptions | Opt_BreakOnException | Opt_BreakOnError | Opt_PrintEvldWithShow | Opt_PrintBindContents | Opt_GenManifest | Opt_EmbedManifest | Opt_SharedImplib | Opt_BuildingCabalPackage | Opt_IgnoreDotGhci | Opt_GhciSandbox | Opt_GhciHistory | Opt_HelpfulErrors | Opt_DeferTypeErrors | Opt_DeferTypedHoles | Opt_PIC | Opt_SccProfilingOn | Opt_Ticky | Opt_Ticky_Allocd | Opt_Ticky_LNE | Opt_Ticky_Dyn_Thunk | Opt_RPath | Opt_RelativeDynlibPaths | Opt_Hpc | Opt_FlatCache | Opt_ExternalInterpreter | Opt_OptimalApplicativeDo -- 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 | Opt_PprShowTicks -- 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_SuppressUnfoldings -- Suppress the details of even stable unfoldings | 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) -- | Used when outputting warnings: if a reason is given, it is -- displayed. If a warning isn't controlled by a flag, this is made -- explicit at the point of use. data WarnReason = NoReason | Reason !WarningFlag data WarningFlag = -- See Note [Updating flag description in the User's Guide] Opt_WarnDuplicateExports | Opt_WarnDuplicateConstraints | Opt_WarnRedundantConstraints | Opt_WarnHiShadows | Opt_WarnImplicitPrelude | Opt_WarnIncompletePatterns | Opt_WarnIncompleteUniPatterns | Opt_WarnIncompletePatternsRecUpd | Opt_WarnOverflowedLiterals | Opt_WarnEmptyEnumerations | Opt_WarnMissingFields | Opt_WarnMissingImportList | Opt_WarnMissingMethods | Opt_WarnMissingSignatures | Opt_WarnMissingLocalSignatures | Opt_WarnNameShadowing | Opt_WarnOverlappingPatterns | Opt_WarnTypeDefaults | Opt_WarnMonomorphism | Opt_WarnUnusedTopBinds | Opt_WarnUnusedLocalBinds | Opt_WarnUnusedPatternBinds | Opt_WarnUnusedImports | Opt_WarnUnusedMatches | Opt_WarnUnusedTypePatterns | Opt_WarnUnusedForalls | Opt_WarnContextQuantification -- remove in 8.2 | Opt_WarnWarningsDeprecations | Opt_WarnDeprecatedFlags | Opt_WarnAMP -- Introduced in GHC 7.8, obsolete since 7.10 | Opt_WarnMissingMonadFailInstances -- since 8.0 | Opt_WarnSemigroup -- since 8.0 | 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_WarnTrustworthySafe | Opt_WarnMissedSpecs | Opt_WarnAllMissedSpecs | Opt_WarnUnsupportedCallingConventions | Opt_WarnUnsupportedLlvmVersion | Opt_WarnInlineRuleShadowing | Opt_WarnTypedHoles | Opt_WarnPartialTypeSignatures | Opt_WarnMissingExportedSignatures | Opt_WarnUntickedPromotedConstructors | Opt_WarnDerivingTypeable | Opt_WarnDeferredTypeErrors | Opt_WarnNonCanonicalMonadInstances -- since 8.0 | Opt_WarnNonCanonicalMonadFailInstances -- since 8.0 | Opt_WarnNonCanonicalMonoidInstances -- since 8.0 | Opt_WarnMissingPatternSynonymSignatures -- since 8.0 | Opt_WarnUnrecognisedWarningFlags -- since 8.0 deriving (Eq, Show, Enum) data Language = Haskell98 | Haskell2010 deriving (Eq, Enum, Show) instance Outputable Language where ppr = text . show -- | 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 type SigOf = Map ModuleName Module getSigOf :: DynFlags -> ModuleName -> Maybe Module getSigOf dflags n = Map.lookup n (sigOf dflags) -- | 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, -- See Note [Signature parameters in TcGblEnv and DynFlags] sigOf :: SigOf, -- ^ Compiling an hs-boot against impl. verbosity :: Int, -- ^ Verbosity level: see Note [Verbosity levels] optLevel :: Int, -- ^ Optimisation level debugLevel :: Int, -- ^ How much debug information to produce simplPhases :: Int, -- ^ Number of simplifier phases maxSimplIterations :: Int, -- ^ Max simplifier iterations maxPmCheckIterations :: Int, -- ^ Max no iterations for pm checking 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, importPaths :: [FilePath], mainModIs :: Module, mainFunIs :: Maybe String, reductionDepth :: IntWithInf, -- ^ Typechecker maximum stack depth solverIterations :: IntWithInf, -- ^ Number of iterations in the constraints solver -- Typically only 1 is needed thisPackage :: UnitId, -- ^ key 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, rtsOptsSuggestions :: Bool, hpcDir :: String, -- ^ Path to store the .mix files -- Plugins pluginModNames :: [ModuleName], pluginModNameOpts :: [(ModuleName,String)], frontendPluginOpts :: [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. ignorePackageFlags :: [IgnorePackageFlag], -- ^ The @-ignore-package@ flags from the command line packageFlags :: [PackageFlag], -- ^ The @-package@ and @-hide-package@ flags from the command-line pluginPackageFlags :: [PackageFlag], -- ^ The @-plugin-package-id@ flags from command line trustFlags :: [TrustFlag], -- ^ The @-trust@ and @-distrust@ flags packageEnv :: Maybe FilePath, -- ^ Filepath to the package environment file (if overriding default) -- Package state -- NB. do not modify this field, it is calculated by -- Packages.initPackages pkgDatabase :: Maybe [(FilePath, [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, incoherentOnLoc :: SrcSpan, pkgTrustOnLoc :: SrcSpan, warnSafeOnLoc :: SrcSpan, warnUnsafeOnLoc :: SrcSpan, trustworthyOnLoc :: SrcSpan, -- Don't change this without updating extensionFlags: extensions :: [OnOff LangExt.Extension], -- extensionFlags should always be equal to -- flattenExtensionFlags language extensions -- LangExt.Extension is defined in libraries/ghc-boot so that it can be used -- by template-haskell 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, -- | GHCi scripts specified by -ghci-script, in reverse order 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, nextWrapperNum :: IORef (ModuleEnv Int), -- | Machine dependant flags (-m<blah> stuff) sseVersion :: Maybe SseVersion, 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, -- | Reverse the order of error messages in GHC/GHCi reverseErrors :: Bool, -- | Unique supply configuration for testing build determinism initialUnique :: Int, uniqueIncrement :: Int } class HasDynFlags m where getDynFlags :: m DynFlags {- It would be desirable to have the more generalised instance (MonadTrans t, Monad m, HasDynFlags m) => HasDynFlags (t m) where getDynFlags = lift getDynFlags instance definition. However, that definition would overlap with the `HasDynFlags (GhcT m)` instance. Instead we define instances for a couple of common Monad transformers explicitly. -} instance (Monoid a, Monad m, HasDynFlags m) => HasDynFlags (WriterT a m) where getDynFlags = lift getDynFlags instance (Monad m, HasDynFlags m) => HasDynFlags (ReaderT a m) where getDynFlags = lift getDynFlags instance (Monad m, HasDynFlags m) => HasDynFlags (MaybeT m) where getDynFlags = lift getDynFlags instance (Monad m, HasDynFlags m) => HasDynFlags (ExceptT e m) where getDynFlags = lift getDynFlags class ContainsDynFlags t where extractDynFlags :: t -> DynFlags 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 (Eq,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 '/' sProgramName :: String, sProjectVersion :: String, -- 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_windres :: String, sPgm_libtool :: String, sPgm_lo :: (String,[Option]), -- LLVM: opt llvm optimiser sPgm_lc :: (String,[Option]), -- LLVM: llc static compiler sPgm_i :: String, -- 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 sOpt_i :: [String], -- iserv options sPlatformConstants :: PlatformConstants } targetPlatform :: DynFlags -> Platform targetPlatform dflags = sTargetPlatform (settings dflags) programName :: DynFlags -> String programName dflags = sProgramName (settings dflags) projectVersion :: DynFlags -> String projectVersion dflags = sProjectVersion (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_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) pgm_i :: DynFlags -> String pgm_i dflags = sPgm_i (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) opt_i :: DynFlags -> [String] opt_i dflags = sOpt_i (settings dflags) -- | The directory for this version of ghc in the user's app directory -- (typically something like @~/.ghc/x86_64-linux-7.6.3@) -- versionedAppDir :: DynFlags -> MaybeT IO FilePath versionedAppDir dflags = do -- Make sure we handle the case the HOME isn't set (see #11678) appdir <- tryMaybeT $ getAppUserDataDirectory (programName dflags) return $ appdir </> versionedFilePath dflags -- | A filepath like @x86_64-linux-7.6.3@ with the platform string to use when -- constructing platform-version-dependent files that need to co-exist. -- versionedFilePath :: DynFlags -> FilePath versionedFilePath dflags = TARGET_ARCH ++ '-':TARGET_OS ++ '-':projectVersion dflags -- NB: This functionality is reimplemented in Cabal, so if you -- change it, be sure to update Cabal. -- | 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 = text "CompManager" ppr OneShot = text "OneShot" ppr MkDepend = text "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 -- | We accept flags which make packages visible, but how they select -- the package varies; this data type reflects what selection criterion -- is used. data PackageArg = PackageArg String -- ^ @-package@, by 'PackageName' | UnitIdArg String -- ^ @-package-id@, by 'UnitId' deriving (Eq, Show) -- | Represents the renaming that may be associated with an exposed -- package, e.g. the @rns@ part of @-package "foo (rns)"@. -- -- Here are some example parsings of the package flags (where -- a string literal is punned to be a 'ModuleName': -- -- * @-package foo@ is @ModRenaming True []@ -- * @-package foo ()@ is @ModRenaming False []@ -- * @-package foo (A)@ is @ModRenaming False [("A", "A")]@ -- * @-package foo (A as B)@ is @ModRenaming False [("A", "B")]@ -- * @-package foo with (A as B)@ is @ModRenaming True [("A", "B")]@ data ModRenaming = ModRenaming { modRenamingWithImplicit :: Bool, -- ^ Bring all exposed modules into scope? modRenamings :: [(ModuleName, ModuleName)] -- ^ Bring module @m@ into scope -- under name @n@. } deriving (Eq) -- | Flags for manipulating the set of non-broken packages. newtype IgnorePackageFlag = IgnorePackage String -- ^ @-ignore-package@ deriving (Eq) -- | Flags for manipulating package trust. data TrustFlag = TrustPackage String -- ^ @-trust@ | DistrustPackage String -- ^ @-distrust@ deriving (Eq) -- | Flags for manipulating packages visibility. data PackageFlag = ExposePackage String PackageArg ModRenaming -- ^ @-package@, @-package-id@ | HidePackage String -- ^ @-hide-package@ deriving (Eq) -- NB: equality instance is used by InteractiveUI to test if -- package flags have changed. 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 | 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 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" wayRTSOnly :: Way -> Bool wayRTSOnly (WayCustom {}) = False wayRTSOnly WayThreaded = True wayRTSOnly WayDebug = True wayRTSOnly WayDyn = False wayRTSOnly WayProf = False wayRTSOnly WayEventLog = True wayDesc :: Way -> String wayDesc (WayCustom xs) = xs wayDesc WayThreaded = "Threaded" wayDesc WayDebug = "Debug" wayDesc WayDyn = "Dynamic" wayDesc WayProf = "Profiling" wayDesc WayEventLog = "RTS Event Logging" -- 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 = [] -- 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, -- If splitobjs wasn't useful for this, -- assume sections aren't either. Opt_SplitSections] wayUnsetGeneralFlags _ WayProf = [] wayUnsetGeneralFlags _ WayEventLog = [] 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"] 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 = [] wayOptP :: Platform -> Way -> [String] wayOptP _ (WayCustom {}) = [] wayOptP _ WayThreaded = [] wayOptP _ WayDebug = [] wayOptP _ WayDyn = [] wayOptP _ WayProf = ["-DPROFILING"] wayOptP _ WayEventLog = ["-DTRACING"] 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 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, nextWrapperNum = wrapperNum, useUnicode = canUseUnicode, rtldInfo = refRtldInfo, rtccInfo = refRtccInfo } -- | The normal 'DynFlags'. Note that they are not suitable for use in this form -- and must be fully initialized by 'GHC.runGhc' first. defaultDynFlags :: Settings -> DynFlags defaultDynFlags mySettings = -- See Note [Updating flag description in the User's Guide] DynFlags { ghcMode = CompManager, ghcLink = LinkBinary, hscTarget = defaultHscTarget (sTargetPlatform mySettings), sigOf = Map.empty, verbosity = 0, optLevel = 0, debugLevel = 0, simplPhases = 2, maxSimplIterations = 4, maxPmCheckIterations = 10000000, 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, importPaths = ["."], mainModIs = mAIN, mainFunIs = Nothing, reductionDepth = treatZeroAsInf mAX_REDUCTION_DEPTH, solverIterations = treatZeroAsInf mAX_SOLVER_ITERATIONS, thisPackage = mainUnitId, 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 = [], frontendPluginOpts = [], hooks = emptyHooks, outputFile = Nothing, dynOutputFile = Nothing, outputHi = Nothing, dynLibLoader = SystemDependent, dumpPrefix = Nothing, dumpPrefixForce = Nothing, ldInputs = [], includePaths = [], libraryPaths = [], frameworkPaths = [], cmdlineFrameworks = [], rtsOpts = Nothing, rtsOptsEnabled = RtsOptsSafeOnly, rtsOptsSuggestions = True, hpcDir = ".hpc", extraPkgConfs = id, packageFlags = [], pluginPackageFlags = [], ignorePackageFlags = [], trustFlags = [], packageEnv = Nothing, pkgDatabase = Nothing, -- This gets filled in with GHC.setSessionDynFlags pkgState = emptyPackageState, 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, incoherentOnLoc = noSrcSpan, pkgTrustOnLoc = noSrcSpan, warnSafeOnLoc = noSrcSpan, warnUnsafeOnLoc = noSrcSpan, trustworthyOnLoc = 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 function 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, 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, initialUnique = 0, uniqueIncrement = 1, reverseErrors = False } defaultWays :: Settings -> [Way] defaultWays settings = if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings) then [WayDyn] else [] interpWays :: [Way] interpWays | dynamicGhc = [WayDyn] | rtsIsProfiled = [WayProf] | otherwise = [] interpreterProfiled :: DynFlags -> Bool interpreterProfiled dflags | gopt Opt_ExternalInterpreter dflags = gopt Opt_SccProfilingOn dflags | otherwise = rtsIsProfiled interpreterDynamic :: DynFlags -> Bool interpreterDynamic dflags | gopt Opt_ExternalInterpreter dflags = WayDyn `elem` ways dflags | otherwise = dynamicGhc -------------------------------------------------------------------------- type FatalMessager = String -> IO () type LogAction = DynFlags -> WarnReason -> Severity -> SrcSpan -> PprStyle -> MsgDoc -> IO () defaultFatalMessager :: FatalMessager defaultFatalMessager = hPutStrLn stderr defaultLogAction :: LogAction defaultLogAction dflags reason 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 message 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 -- Pretty print the warning flag, if any (#10752) message = mkLocMessageAnn flagMsg severity srcSpan msg flagMsg = case reason of NoReason -> Nothing Reason flag -> (\spec -> "-W" ++ flagSpecName spec ++ flagGrp flag) <$> flagSpecOf flag flagGrp flag | gopt Opt_ShowWarnGroups dflags = case smallestGroups flag of [] -> "" groups -> " (in " ++ intercalate ", " (map ("-W"++) groups) ++ ")" | otherwise = "" 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 {- 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 deriving (Eq, Show) instance Outputable a => Outputable (OnOff a) where ppr (On x) = text "On" <+> ppr x ppr (Off x) = text "Off" <+> ppr x -- OnOffs accumulate in reverse order, so we use foldr in order to -- process them in the right order flattenExtensionFlags :: Maybe Language -> [OnOff LangExt.Extension] -> 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 -> [LangExt.Extension] languageExtensions Nothing -- Nothing => the default case = LangExt.NondecreasingIndentation -- This has been on by default for some time : delete LangExt.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) = [LangExt.ImplicitPrelude, LangExt.MonomorphismRestriction, LangExt.NPlusKPatterns, LangExt.DatatypeContexts, LangExt.TraditionalRecordSyntax, LangExt.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) = [LangExt.ImplicitPrelude, LangExt.MonomorphismRestriction, LangExt.DatatypeContexts, LangExt.TraditionalRecordSyntax, LangExt.EmptyDataDecls, LangExt.ForeignFunctionInterface, LangExt.PatternGuards, LangExt.DoAndIfThenElse, LangExt.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_th_dec_file = 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 'LangExt.Extension' is set xopt :: LangExt.Extension -> DynFlags -> Bool xopt f dflags = fromEnum f `IntSet.member` extensionFlags dflags -- | Set a 'LangExt.Extension' xopt_set :: DynFlags -> LangExt.Extension -> DynFlags xopt_set dfs f = let onoffs = On f : extensions dfs in dfs { extensions = onoffs, extensionFlags = flattenExtensionFlags (language dfs) onoffs } -- | Unset a 'LangExt.Extension' xopt_unset :: DynFlags -> LangExt.Extension -> 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) } -- | An internal helper to check whether to use unicode syntax for output. -- -- Note: You should very likely be using 'Outputable.unicodeSyntax' instead -- of this function. useUnicodeSyntax :: DynFlags -> Bool useUnicodeSyntax = gopt Opt_PrintUnicodeSyntax -- | 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 case s of Sf_Safe -> return $ dfs { safeHaskell = safeM, safeInfer = False } -- leave safe inferrence on in Trustworthy mode so we can warn -- if it could have been inferred safe. Sf_Trustworthy -> do l <- getCurLoc return $ dfs { safeHaskell = safeM, trustworthyOnLoc = l } -- leave safe inference on in Unsafe mode as well. _ -> return $ 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 >> pure a 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 LangExt.GeneralizedNewtypeDeriving, flip xopt_unset LangExt.GeneralizedNewtypeDeriving) , ("-XTemplateHaskell", thOnLoc, xopt LangExt.TemplateHaskell, flip xopt_unset LangExt.TemplateHaskell) ] unsafeFlagsForInfer = unsafeFlags -- | 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} parseSigOf :: String -> SigOf parseSigOf str = case filter ((=="").snd) (readP_to_S parse str) of [(r, "")] -> r _ -> throwGhcException $ CmdLineError ("Can't parse -sig-of: " ++ str) where parse = Map.fromList <$> sepBy parseEntry (R.char ',') parseEntry = do n <- tok $ parseModuleName -- ToDo: deprecate this 'is' syntax? tok $ ((string "is" >> return ()) +++ (R.char '=' >> return ())) m <- tok $ parseModule return (n, m) parseModule = do pk <- munch1 (\c -> isAlphaNum c || c `elem` "-_.") _ <- R.char ':' m <- parseModuleName return (mkModule (stringToUnitId pk) m) tok m = skipSpaces >> m setSigOf :: String -> DynFlags -> DynFlags setSigOf s d = d { sigOf = parseSigOf s } 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 addFrontendPluginOption :: String -> DynFlags -> DynFlags addFrontendPluginOption s d = d { frontendPluginOpts = s : frontendPluginOpts d } 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 = f } setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags setDepIncludePkgDeps b d = d { depIncludePkgDeps = b } addDepExcludeMod :: String -> DynFlags -> DynFlags addDepExcludeMod m d = d { depExcludeMods = mkModuleName m : depExcludeMods d } addDepSuffix :: FilePath -> DynFlags -> DynFlags addDepSuffix s d = d { depSuffixes = s : depSuffixes d } 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 ] {- ********************************************************************** %* * 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 let ((leftover, errs, warns), dflags1) = runCmdLine (processArgs activeFlags args) dflags0 -- See Note [Handling errors when parsing commandline flags] unless (null errs) $ liftIO $ throwGhcExceptionIO $ errorsToGhcException . map (showPpr dflags0 . getLoc &&& unLoc) $ 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 in 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"] -- Have we inferred Unsafe? See Note [HscMain . Safe Haskell Inference] safeFlags = all (\(_,_,t,_) -> not $ t dflags) unsafeFlagsForInfer {- ********************************************************************** %* * DynFlags specifications %* * %********************************************************************* -} -- | All dynamic flags option strings without the deprecated ones. -- These are the user facing strings for enabling and disabling options. allNonDeprecatedFlags :: [String] allNonDeprecatedFlags = allFlagsDeps False -- | All flags with possibility to filter deprecated ones allFlagsDeps :: Bool -> [String] allFlagsDeps keepDeprecated = [ '-':flagName flag | (deprecated, flag) <- flagsAllDeps , ok (flagOptKind flag) , keepDeprecated || not (isDeprecated deprecated)] where ok (PrefixPred _ _) = False ok _ = True isDeprecated Deprecated = True isDeprecated _ = False {- - 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 = map snd flagsAllDeps -- All dynamic flags present in GHC with deprecation information. flagsAllDeps :: [(Deprecation, Flag (CmdLineP DynFlags))] flagsAllDeps = package_flags_deps ++ dynamic_flags_deps -- All dynamic flags, minus package flags, present in GHC. flagsDynamic :: [Flag (CmdLineP DynFlags)] flagsDynamic = map snd dynamic_flags_deps -- ALl package flags present in GHC. flagsPackage :: [Flag (CmdLineP DynFlags)] flagsPackage = map snd package_flags_deps ----------------Helpers to make flags and keep deprecation information---------- type FlagMaker m = String -> OptKind m -> Flag m type DynFlagMaker = FlagMaker (CmdLineP DynFlags) data Deprecation = Deprecated | NotDeprecated -- Make a non-deprecated flag make_ord_flag :: DynFlagMaker -> String -> OptKind (CmdLineP DynFlags) -> (Deprecation, Flag (CmdLineP DynFlags)) make_ord_flag fm name kind = (NotDeprecated, fm name kind) -- Make a deprecated flag make_dep_flag :: DynFlagMaker -> String -> OptKind (CmdLineP DynFlags) -> String -> (Deprecation, Flag (CmdLineP DynFlags)) make_dep_flag fm name kind message = (Deprecated, fm name $ add_dep_message kind message) add_dep_message :: OptKind (CmdLineP DynFlags) -> String -> OptKind (CmdLineP DynFlags) add_dep_message (NoArg f) message = NoArg $ f >> deprecate message add_dep_message (HasArg f) message = HasArg $ \s -> f s >> deprecate message add_dep_message (SepArg f) message = SepArg $ \s -> f s >> deprecate message add_dep_message (Prefix f) message = Prefix $ \s -> f s >> deprecate message add_dep_message (OptPrefix f) message = OptPrefix $ \s -> f s >> deprecate message add_dep_message (OptIntSuffix f) message = OptIntSuffix $ \oi -> f oi >> deprecate message add_dep_message (IntSuffix f) message = IntSuffix $ \i -> f i >> deprecate message add_dep_message (FloatSuffix f) message = FloatSuffix $ \fl -> f fl >> deprecate message add_dep_message (PassFlag f) message = PassFlag $ \s -> f s >> deprecate message add_dep_message (AnySuffix f) message = AnySuffix $ \s -> f s >> deprecate message add_dep_message (PrefixPred pred f) message = PrefixPred pred $ \s -> f s >> deprecate message add_dep_message (AnySuffixPred pred f) message = AnySuffixPred pred $ \s -> f s >> deprecate message ----------------------- The main flags themselves ------------------------------ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] dynamic_flags_deps :: [(Deprecation, Flag (CmdLineP DynFlags))] dynamic_flags_deps = [ make_dep_flag defFlag "n" (NoArg $ return ()) "The -n flag is deprecated and no longer has any effect" , make_ord_flag defFlag "cpp" (NoArg (setExtensionFlag LangExt.Cpp)) , make_ord_flag defFlag "F" (NoArg (setGeneralFlag Opt_Pp)) , (Deprecated, defFlag "#include" (HasArg (\_s -> addWarn ("-#include and INCLUDE pragmas are " ++ "deprecated: They no longer have any effect")))) , make_ord_flag defFlag "v" (OptIntSuffix setVerbosity) , make_ord_flag defGhcFlag "j" (OptIntSuffix (\n -> upd (\d -> d {parMakeCount = n}))) , make_ord_flag defFlag "sig-of" (sepArg setSigOf) -- RTS options ------------------------------------------------------------- , make_ord_flag defFlag "H" (HasArg (\s -> upd (\d -> d { ghcHeapSize = Just $ fromIntegral (decodeSize s)}))) , make_ord_flag defFlag "Rghc-timing" (NoArg (upd (\d -> d { enableTimeStats = True }))) ------- ways --------------------------------------------------------------- , make_ord_flag defGhcFlag "prof" (NoArg (addWay WayProf)) , make_ord_flag defGhcFlag "eventlog" (NoArg (addWay WayEventLog)) , make_dep_flag defGhcFlag "smp" (NoArg $ addWay WayThreaded) "Use -threaded instead" , make_ord_flag defGhcFlag "debug" (NoArg (addWay WayDebug)) , make_ord_flag defGhcFlag "threaded" (NoArg (addWay WayThreaded)) , make_ord_flag defGhcFlag "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 -------------------------------------------------------- , make_ord_flag defGhcFlag "static" (NoArg removeWayDyn) , make_ord_flag defGhcFlag "dynamic" (NoArg (addWay WayDyn)) , make_ord_flag defGhcFlag "rdynamic" $ noArg $ #ifdef linux_HOST_OS addOptl "-rdynamic" #elif defined (mingw32_HOST_OS) addOptl "-Wl,--export-all-symbols" #else -- ignored for compat w/ gcc: id #endif , make_ord_flag defGhcFlag "relative-dynlib-paths" (NoArg (setGeneralFlag Opt_RelativeDynlibPaths)) ------- Specific phases -------------------------------------------- -- need to appear before -pgmL to be parsed as LLVM flags. , make_ord_flag defFlag "pgmlo" (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])}))) , make_ord_flag defFlag "pgmlc" (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])}))) , make_ord_flag defFlag "pgmi" (hasArg (\f -> alterSettings (\s -> s { sPgm_i = f}))) , make_ord_flag defFlag "pgmL" (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f}))) , make_ord_flag defFlag "pgmP" (hasArg setPgmP) , make_ord_flag defFlag "pgmF" (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f}))) , make_ord_flag defFlag "pgmc" (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[])}))) , make_ord_flag defFlag "pgms" (hasArg (\f -> alterSettings (\s -> s { sPgm_s = (f,[])}))) , make_ord_flag defFlag "pgma" (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])}))) , make_ord_flag defFlag "pgml" (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])}))) , make_ord_flag defFlag "pgmdll" (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])}))) , make_ord_flag defFlag "pgmwindres" (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f}))) , make_ord_flag defFlag "pgmlibtool" (hasArg (\f -> alterSettings (\s -> s { sPgm_libtool = f}))) -- need to appear before -optl/-opta to be parsed as LLVM flags. , make_ord_flag defFlag "optlo" (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s}))) , make_ord_flag defFlag "optlc" (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s}))) , make_ord_flag defFlag "opti" (hasArg (\f -> alterSettings (\s -> s { sOpt_i = f : sOpt_i s}))) , make_ord_flag defFlag "optL" (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s}))) , make_ord_flag defFlag "optP" (hasArg addOptP) , make_ord_flag defFlag "optF" (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s}))) , make_ord_flag defFlag "optc" (hasArg addOptc) , make_ord_flag defFlag "opta" (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s}))) , make_ord_flag defFlag "optl" (hasArg addOptl) , make_ord_flag defFlag "optwindres" (hasArg (\f -> alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s}))) , make_ord_flag defGhcFlag "split-objs" (NoArg (if can_split then setGeneralFlag Opt_SplitObjs else addWarn "ignoring -fsplit-objs")) , make_ord_flag defGhcFlag "split-sections" (noArgM (\dflags -> do if platformHasSubsectionsViaSymbols (targetPlatform dflags) then do addErr $ "-split-sections is not useful on this platform " ++ "since it always uses subsections via symbols." return dflags else return (gopt_set dflags Opt_SplitSections))) -------- ghc -M ----------------------------------------------------- , make_ord_flag defGhcFlag "dep-suffix" (hasArg addDepSuffix) , make_ord_flag defGhcFlag "dep-makefile" (hasArg setDepMakefile) , make_ord_flag defGhcFlag "include-pkg-deps" (noArg (setDepIncludePkgDeps True)) , make_ord_flag defGhcFlag "exclude-module" (hasArg addDepExcludeMod) -------- Linking ---------------------------------------------------- , make_ord_flag defGhcFlag "no-link" (noArg (\d -> d { ghcLink=NoLink })) , make_ord_flag defGhcFlag "shared" (noArg (\d -> d { ghcLink=LinkDynLib })) , make_ord_flag defGhcFlag "staticlib" (noArg (\d -> d { ghcLink=LinkStaticLib })) , make_ord_flag defGhcFlag "dynload" (hasArg parseDynLibLoaderMode) , make_ord_flag defGhcFlag "dylib-install-name" (hasArg setDylibInstallName) -- -dll-split is an internal flag, used only during the GHC build , make_ord_flag defHiddenFlag "dll-split" (hasArg (\f d -> d { dllSplitFile = Just f, dllSplit = Nothing })) ------- Libraries --------------------------------------------------- , make_ord_flag defFlag "L" (Prefix addLibraryPath) , make_ord_flag defFlag "l" (hasArg (addLdInputs . Option . ("-l" ++))) ------- Frameworks -------------------------------------------------- -- -framework-path should really be -F ... , make_ord_flag defFlag "framework-path" (HasArg addFrameworkPath) , make_ord_flag defFlag "framework" (hasArg addCmdlineFramework) ------- Output Redirection ------------------------------------------ , make_ord_flag defGhcFlag "odir" (hasArg setObjectDir) , make_ord_flag defGhcFlag "o" (sepArg (setOutputFile . Just)) , make_ord_flag defGhcFlag "dyno" (sepArg (setDynOutputFile . Just)) , make_ord_flag defGhcFlag "ohi" (hasArg (setOutputHi . Just )) , make_ord_flag defGhcFlag "osuf" (hasArg setObjectSuf) , make_ord_flag defGhcFlag "dynosuf" (hasArg setDynObjectSuf) , make_ord_flag defGhcFlag "hcsuf" (hasArg setHcSuf) , make_ord_flag defGhcFlag "hisuf" (hasArg setHiSuf) , make_ord_flag defGhcFlag "dynhisuf" (hasArg setDynHiSuf) , make_ord_flag defGhcFlag "hidir" (hasArg setHiDir) , make_ord_flag defGhcFlag "tmpdir" (hasArg setTmpDir) , make_ord_flag defGhcFlag "stubdir" (hasArg setStubDir) , make_ord_flag defGhcFlag "dumpdir" (hasArg setDumpDir) , make_ord_flag defGhcFlag "outputdir" (hasArg setOutputDir) , make_ord_flag defGhcFlag "ddump-file-prefix" (hasArg (setDumpPrefixForce . Just)) , make_ord_flag defGhcFlag "dynamic-too" (NoArg (setGeneralFlag Opt_BuildDynamicToo)) ------- Keeping temporary files ------------------------------------- -- These can be singular (think ghc -c) or plural (think ghc --make) , make_ord_flag defGhcFlag "keep-hc-file" (NoArg (setGeneralFlag Opt_KeepHcFiles)) , make_ord_flag defGhcFlag "keep-hc-files" (NoArg (setGeneralFlag Opt_KeepHcFiles)) , make_ord_flag defGhcFlag "keep-s-file" (NoArg (setGeneralFlag Opt_KeepSFiles)) , make_ord_flag defGhcFlag "keep-s-files" (NoArg (setGeneralFlag Opt_KeepSFiles)) , make_ord_flag defGhcFlag "keep-llvm-file" (NoArg $ setObjTarget HscLlvm >> setGeneralFlag Opt_KeepLlvmFiles) , make_ord_flag defGhcFlag "keep-llvm-files" (NoArg $ setObjTarget HscLlvm >> setGeneralFlag Opt_KeepLlvmFiles) -- This only makes sense as plural , make_ord_flag defGhcFlag "keep-tmp-files" (NoArg (setGeneralFlag Opt_KeepTmpFiles)) ------- Miscellaneous ---------------------------------------------- , make_ord_flag defGhcFlag "no-auto-link-packages" (NoArg (unSetGeneralFlag Opt_AutoLinkPackages)) , make_ord_flag defGhcFlag "no-hs-main" (NoArg (setGeneralFlag Opt_NoHsMain)) , make_ord_flag defGhcFlag "with-rtsopts" (HasArg setRtsOpts) , make_ord_flag defGhcFlag "rtsopts" (NoArg (setRtsOptsEnabled RtsOptsAll)) , make_ord_flag defGhcFlag "rtsopts=all" (NoArg (setRtsOptsEnabled RtsOptsAll)) , make_ord_flag defGhcFlag "rtsopts=some" (NoArg (setRtsOptsEnabled RtsOptsSafeOnly)) , make_ord_flag defGhcFlag "rtsopts=none" (NoArg (setRtsOptsEnabled RtsOptsNone)) , make_ord_flag defGhcFlag "no-rtsopts" (NoArg (setRtsOptsEnabled RtsOptsNone)) , make_ord_flag defGhcFlag "no-rtsopts-suggestions" (noArg (\d -> d {rtsOptsSuggestions = False})) , make_ord_flag defGhcFlag "main-is" (SepArg setMainIs) , make_ord_flag defGhcFlag "haddock" (NoArg (setGeneralFlag Opt_Haddock)) , make_ord_flag defGhcFlag "haddock-opts" (hasArg addHaddockOpts) , make_ord_flag defGhcFlag "hpcdir" (SepArg setOptHpcDir) , make_ord_flag defGhciFlag "ghci-script" (hasArg addGhciScript) , make_ord_flag defGhciFlag "interactive-print" (hasArg setInteractivePrint) , make_ord_flag defGhcFlag "ticky-allocd" (NoArg (setGeneralFlag Opt_Ticky_Allocd)) , make_ord_flag defGhcFlag "ticky-LNE" (NoArg (setGeneralFlag Opt_Ticky_LNE)) , make_ord_flag defGhcFlag "ticky-dyn-thunk" (NoArg (setGeneralFlag Opt_Ticky_Dyn_Thunk)) ------- recompilation checker -------------------------------------- , make_dep_flag defGhcFlag "recomp" (NoArg $ unSetGeneralFlag Opt_ForceRecomp) "Use -fno-force-recomp instead" , make_dep_flag defGhcFlag "no-recomp" (NoArg $ setGeneralFlag Opt_ForceRecomp) "Use -fforce-recomp instead" , make_ord_flag defFlag "freverse-errors" (noArg (\d -> d {reverseErrors = True} )) , make_ord_flag defFlag "fno-reverse-errors" (noArg (\d -> d {reverseErrors = False} )) ------ HsCpp opts --------------------------------------------------- , make_ord_flag defFlag "D" (AnySuffix (upd . addOptP)) , make_ord_flag defFlag "U" (AnySuffix (upd . addOptP)) ------- Include/Import Paths ---------------------------------------- , make_ord_flag defFlag "I" (Prefix addIncludePath) , make_ord_flag defFlag "i" (OptPrefix addImportPath) ------ Output style options ----------------------------------------- , make_ord_flag defFlag "dppr-user-length" (intSuffix (\n d -> d { pprUserLength = n })) , make_ord_flag defFlag "dppr-cols" (intSuffix (\n d -> d { pprCols = n })) , make_ord_flag defGhcFlag "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 variables that -- have otherwise identical names. , make_ord_flag defGhcFlag "dsuppress-all" (NoArg $ do setGeneralFlag Opt_SuppressCoercions setGeneralFlag Opt_SuppressVarKinds setGeneralFlag Opt_SuppressModulePrefixes setGeneralFlag Opt_SuppressTypeApplications setGeneralFlag Opt_SuppressIdInfo setGeneralFlag Opt_SuppressTypeSignatures) ------ Debugging ---------------------------------------------------- , make_ord_flag defGhcFlag "dstg-stats" (NoArg (setGeneralFlag Opt_StgStats)) , make_ord_flag defGhcFlag "ddump-cmm" (setDumpFlag Opt_D_dump_cmm) , make_ord_flag defGhcFlag "ddump-cmm-raw" (setDumpFlag Opt_D_dump_cmm_raw) , make_ord_flag defGhcFlag "ddump-cmm-cfg" (setDumpFlag Opt_D_dump_cmm_cfg) , make_ord_flag defGhcFlag "ddump-cmm-cbe" (setDumpFlag Opt_D_dump_cmm_cbe) , make_ord_flag defGhcFlag "ddump-cmm-switch" (setDumpFlag Opt_D_dump_cmm_switch) , make_ord_flag defGhcFlag "ddump-cmm-proc" (setDumpFlag Opt_D_dump_cmm_proc) , make_ord_flag defGhcFlag "ddump-cmm-sink" (setDumpFlag Opt_D_dump_cmm_sink) , make_ord_flag defGhcFlag "ddump-cmm-sp" (setDumpFlag Opt_D_dump_cmm_sp) , make_ord_flag defGhcFlag "ddump-cmm-procmap" (setDumpFlag Opt_D_dump_cmm_procmap) , make_ord_flag defGhcFlag "ddump-cmm-split" (setDumpFlag Opt_D_dump_cmm_split) , make_ord_flag defGhcFlag "ddump-cmm-info" (setDumpFlag Opt_D_dump_cmm_info) , make_ord_flag defGhcFlag "ddump-cmm-cps" (setDumpFlag Opt_D_dump_cmm_cps) , make_ord_flag defGhcFlag "ddump-core-stats" (setDumpFlag Opt_D_dump_core_stats) , make_ord_flag defGhcFlag "ddump-asm" (setDumpFlag Opt_D_dump_asm) , make_ord_flag defGhcFlag "ddump-asm-native" (setDumpFlag Opt_D_dump_asm_native) , make_ord_flag defGhcFlag "ddump-asm-liveness" (setDumpFlag Opt_D_dump_asm_liveness) , make_ord_flag defGhcFlag "ddump-asm-regalloc" (setDumpFlag Opt_D_dump_asm_regalloc) , make_ord_flag defGhcFlag "ddump-asm-conflicts" (setDumpFlag Opt_D_dump_asm_conflicts) , make_ord_flag defGhcFlag "ddump-asm-regalloc-stages" (setDumpFlag Opt_D_dump_asm_regalloc_stages) , make_ord_flag defGhcFlag "ddump-asm-stats" (setDumpFlag Opt_D_dump_asm_stats) , make_ord_flag defGhcFlag "ddump-asm-expanded" (setDumpFlag Opt_D_dump_asm_expanded) , make_ord_flag defGhcFlag "ddump-llvm" (NoArg $ setObjTarget HscLlvm >> setDumpFlag' Opt_D_dump_llvm) , make_ord_flag defGhcFlag "ddump-deriv" (setDumpFlag Opt_D_dump_deriv) , make_ord_flag defGhcFlag "ddump-ds" (setDumpFlag Opt_D_dump_ds) , make_ord_flag defGhcFlag "ddump-foreign" (setDumpFlag Opt_D_dump_foreign) , make_ord_flag defGhcFlag "ddump-inlinings" (setDumpFlag Opt_D_dump_inlinings) , make_ord_flag defGhcFlag "ddump-rule-firings" (setDumpFlag Opt_D_dump_rule_firings) , make_ord_flag defGhcFlag "ddump-rule-rewrites" (setDumpFlag Opt_D_dump_rule_rewrites) , make_ord_flag defGhcFlag "ddump-simpl-trace" (setDumpFlag Opt_D_dump_simpl_trace) , make_ord_flag defGhcFlag "ddump-occur-anal" (setDumpFlag Opt_D_dump_occur_anal) , make_ord_flag defGhcFlag "ddump-parsed" (setDumpFlag Opt_D_dump_parsed) , make_ord_flag defGhcFlag "ddump-rn" (setDumpFlag Opt_D_dump_rn) , make_ord_flag defGhcFlag "ddump-simpl" (setDumpFlag Opt_D_dump_simpl) , make_ord_flag defGhcFlag "ddump-simpl-iterations" (setDumpFlag Opt_D_dump_simpl_iterations) , make_ord_flag defGhcFlag "ddump-spec" (setDumpFlag Opt_D_dump_spec) , make_ord_flag defGhcFlag "ddump-prep" (setDumpFlag Opt_D_dump_prep) , make_ord_flag defGhcFlag "ddump-stg" (setDumpFlag Opt_D_dump_stg) , make_ord_flag defGhcFlag "ddump-call-arity" (setDumpFlag Opt_D_dump_call_arity) , make_ord_flag defGhcFlag "ddump-stranal" (setDumpFlag Opt_D_dump_stranal) , make_ord_flag defGhcFlag "ddump-str-signatures" (setDumpFlag Opt_D_dump_str_signatures) , make_ord_flag defGhcFlag "ddump-tc" (setDumpFlag Opt_D_dump_tc) , make_ord_flag defGhcFlag "ddump-types" (setDumpFlag Opt_D_dump_types) , make_ord_flag defGhcFlag "ddump-rules" (setDumpFlag Opt_D_dump_rules) , make_ord_flag defGhcFlag "ddump-cse" (setDumpFlag Opt_D_dump_cse) , make_ord_flag defGhcFlag "ddump-worker-wrapper" (setDumpFlag Opt_D_dump_worker_wrapper) , make_ord_flag defGhcFlag "ddump-rn-trace" (setDumpFlag Opt_D_dump_rn_trace) , make_ord_flag defGhcFlag "ddump-if-trace" (setDumpFlag Opt_D_dump_if_trace) , make_ord_flag defGhcFlag "ddump-cs-trace" (setDumpFlag Opt_D_dump_cs_trace) , make_ord_flag defGhcFlag "ddump-tc-trace" (NoArg (do setDumpFlag' Opt_D_dump_tc_trace setDumpFlag' Opt_D_dump_cs_trace)) , make_ord_flag defGhcFlag "ddump-vt-trace" (setDumpFlag Opt_D_dump_vt_trace) , make_ord_flag defGhcFlag "ddump-splices" (setDumpFlag Opt_D_dump_splices) , make_ord_flag defGhcFlag "dth-dec-file" (setDumpFlag Opt_D_th_dec_file) , make_ord_flag defGhcFlag "ddump-rn-stats" (setDumpFlag Opt_D_dump_rn_stats) , make_ord_flag defGhcFlag "ddump-opt-cmm" (setDumpFlag Opt_D_dump_opt_cmm) , make_ord_flag defGhcFlag "ddump-simpl-stats" (setDumpFlag Opt_D_dump_simpl_stats) , make_ord_flag defGhcFlag "ddump-bcos" (setDumpFlag Opt_D_dump_BCOs) , make_ord_flag defGhcFlag "dsource-stats" (setDumpFlag Opt_D_source_stats) , make_ord_flag defGhcFlag "dverbose-core2core" (NoArg $ setVerbosity (Just 2) >> setVerboseCore2Core) , make_ord_flag defGhcFlag "dverbose-stg2stg" (setDumpFlag Opt_D_verbose_stg2stg) , make_ord_flag defGhcFlag "ddump-hi" (setDumpFlag Opt_D_dump_hi) , make_ord_flag defGhcFlag "ddump-minimal-imports" (NoArg (setGeneralFlag Opt_D_dump_minimal_imports)) , make_ord_flag defGhcFlag "ddump-vect" (setDumpFlag Opt_D_dump_vect) , make_ord_flag defGhcFlag "ddump-hpc" (setDumpFlag Opt_D_dump_ticked) -- back compat , make_ord_flag defGhcFlag "ddump-ticked" (setDumpFlag Opt_D_dump_ticked) , make_ord_flag defGhcFlag "ddump-mod-cycles" (setDumpFlag Opt_D_dump_mod_cycles) , make_ord_flag defGhcFlag "ddump-mod-map" (setDumpFlag Opt_D_dump_mod_map) , make_ord_flag defGhcFlag "ddump-view-pattern-commoning" (setDumpFlag Opt_D_dump_view_pattern_commoning) , make_ord_flag defGhcFlag "ddump-to-file" (NoArg (setGeneralFlag Opt_DumpToFile)) , make_ord_flag defGhcFlag "ddump-hi-diffs" (setDumpFlag Opt_D_dump_hi_diffs) , make_ord_flag defGhcFlag "ddump-rtti" (setDumpFlag Opt_D_dump_rtti) , make_ord_flag defGhcFlag "dcore-lint" (NoArg (setGeneralFlag Opt_DoCoreLinting)) , make_ord_flag defGhcFlag "dstg-lint" (NoArg (setGeneralFlag Opt_DoStgLinting)) , make_ord_flag defGhcFlag "dcmm-lint" (NoArg (setGeneralFlag Opt_DoCmmLinting)) , make_ord_flag defGhcFlag "dasm-lint" (NoArg (setGeneralFlag Opt_DoAsmLinting)) , make_ord_flag defGhcFlag "dannot-lint" (NoArg (setGeneralFlag Opt_DoAnnotationLinting)) , make_ord_flag defGhcFlag "dshow-passes" (NoArg $ forceRecompile >> (setVerbosity $ Just 2)) , make_ord_flag defGhcFlag "dfaststring-stats" (NoArg (setGeneralFlag Opt_D_faststring_stats)) , make_ord_flag defGhcFlag "dno-llvm-mangler" (NoArg (setGeneralFlag Opt_NoLlvmMangler)) -- hidden flag , make_ord_flag defGhcFlag "ddump-debug" (setDumpFlag Opt_D_dump_debug) ------ Machine dependant (-m<blah>) stuff --------------------------- , make_ord_flag defGhcFlag "msse" (noArg (\d -> d { sseVersion = Just SSE1 })) , make_ord_flag defGhcFlag "msse2" (noArg (\d -> d { sseVersion = Just SSE2 })) , make_ord_flag defGhcFlag "msse3" (noArg (\d -> d { sseVersion = Just SSE3 })) , make_ord_flag defGhcFlag "msse4" (noArg (\d -> d { sseVersion = Just SSE4 })) , make_ord_flag defGhcFlag "msse4.2" (noArg (\d -> d { sseVersion = Just SSE42 })) , make_ord_flag defGhcFlag "mavx" (noArg (\d -> d { avx = True })) , make_ord_flag defGhcFlag "mavx2" (noArg (\d -> d { avx2 = True })) , make_ord_flag defGhcFlag "mavx512cd" (noArg (\d -> d { avx512cd = True })) , make_ord_flag defGhcFlag "mavx512er" (noArg (\d -> d { avx512er = True })) , make_ord_flag defGhcFlag "mavx512f" (noArg (\d -> d { avx512f = True })) , make_ord_flag defGhcFlag "mavx512pf" (noArg (\d -> d { avx512pf = True })) ------ Warning opts ------------------------------------------------- , make_ord_flag defFlag "W" (NoArg (mapM_ setWarningFlag minusWOpts)) , make_ord_flag defFlag "Werror" (NoArg (setGeneralFlag Opt_WarnIsError)) , make_ord_flag defFlag "Wwarn" (NoArg (unSetGeneralFlag Opt_WarnIsError)) , make_dep_flag defFlag "Wnot" (NoArg (upd (\d -> d {warningFlags = IntSet.empty}))) "Use -w or -Wno-everything instead" , make_ord_flag defFlag "w" (NoArg (upd (\d -> d {warningFlags = IntSet.empty}))) -- New-style uniform warning sets -- -- Note that -Weverything > -Wall > -Wextra > -Wdefault > -Wno-everything , make_ord_flag defFlag "Weverything" (NoArg (mapM_ setWarningFlag minusWeverythingOpts)) , make_ord_flag defFlag "Wno-everything" (NoArg (upd (\d -> d {warningFlags = IntSet.empty}))) , make_ord_flag defFlag "Wall" (NoArg (mapM_ setWarningFlag minusWallOpts)) , make_ord_flag defFlag "Wno-all" (NoArg (mapM_ unSetWarningFlag minusWallOpts)) , make_ord_flag defFlag "Wextra" (NoArg (mapM_ setWarningFlag minusWOpts)) , make_ord_flag defFlag "Wno-extra" (NoArg (mapM_ unSetWarningFlag minusWOpts)) , make_ord_flag defFlag "Wdefault" (NoArg (mapM_ setWarningFlag standardWarnings)) , make_ord_flag defFlag "Wno-default" (NoArg (mapM_ unSetWarningFlag standardWarnings)) , make_ord_flag defFlag "Wcompat" (NoArg (mapM_ setWarningFlag minusWcompatOpts)) , make_ord_flag defFlag "Wno-compat" (NoArg (mapM_ unSetWarningFlag minusWcompatOpts)) ------ Plugin flags ------------------------------------------------ , make_ord_flag defGhcFlag "fplugin-opt" (hasArg addPluginModuleNameOption) , make_ord_flag defGhcFlag "fplugin" (hasArg addPluginModuleName) , make_ord_flag defGhcFlag "ffrontend-opt" (hasArg addFrontendPluginOption) ------ Optimisation flags ------------------------------------------ , make_ord_flag defGhcFlag "O" (noArgM (setOptLevel 1)) , make_dep_flag defGhcFlag "Onot" (noArgM $ setOptLevel 0 ) "Use -O0 instead" , make_ord_flag defGhcFlag "Odph" (noArgM setDPHOpt) , make_ord_flag defGhcFlag "O" (optIntSuffixM (\mb_n -> setOptLevel (mb_n `orElse` 1))) -- If the number is missing, use 1 , make_ord_flag defFlag "fmax-relevant-binds" (intSuffix (\n d -> d { maxRelevantBinds = Just n })) , make_ord_flag defFlag "fno-max-relevant-binds" (noArg (\d -> d { maxRelevantBinds = Nothing })) , make_ord_flag defFlag "fsimplifier-phases" (intSuffix (\n d -> d { simplPhases = n })) , make_ord_flag defFlag "fmax-simplifier-iterations" (intSuffix (\n d -> d { maxSimplIterations = n })) , make_ord_flag defFlag "fmax-pmcheck-iterations" (intSuffix (\n d -> d{ maxPmCheckIterations = n })) , make_ord_flag defFlag "fsimpl-tick-factor" (intSuffix (\n d -> d { simplTickFactor = n })) , make_ord_flag defFlag "fspec-constr-threshold" (intSuffix (\n d -> d { specConstrThreshold = Just n })) , make_ord_flag defFlag "fno-spec-constr-threshold" (noArg (\d -> d { specConstrThreshold = Nothing })) , make_ord_flag defFlag "fspec-constr-count" (intSuffix (\n d -> d { specConstrCount = Just n })) , make_ord_flag defFlag "fno-spec-constr-count" (noArg (\d -> d { specConstrCount = Nothing })) , make_ord_flag defFlag "fspec-constr-recursive" (intSuffix (\n d -> d { specConstrRecursive = n })) , make_ord_flag defFlag "fliberate-case-threshold" (intSuffix (\n d -> d { liberateCaseThreshold = Just n })) , make_ord_flag defFlag "fno-liberate-case-threshold" (noArg (\d -> d { liberateCaseThreshold = Nothing })) , make_ord_flag defFlag "frule-check" (sepArg (\s d -> d { ruleCheck = Just s })) , make_ord_flag defFlag "freduction-depth" (intSuffix (\n d -> d { reductionDepth = treatZeroAsInf n })) , make_ord_flag defFlag "fconstraint-solver-iterations" (intSuffix (\n d -> d { solverIterations = treatZeroAsInf n })) , (Deprecated, defFlag "fcontext-stack" (intSuffixM (\n d -> do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead" ; return $ d { reductionDepth = treatZeroAsInf n } }))) , (Deprecated, defFlag "ftype-function-depth" (intSuffixM (\n d -> do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead" ; return $ d { reductionDepth = treatZeroAsInf n } }))) , make_ord_flag defFlag "fstrictness-before" (intSuffix (\n d -> d { strictnessBefore = n : strictnessBefore d })) , make_ord_flag defFlag "ffloat-lam-args" (intSuffix (\n d -> d { floatLamArgs = Just n })) , make_ord_flag defFlag "ffloat-all-lams" (noArg (\d -> d { floatLamArgs = Nothing })) , make_ord_flag defFlag "fhistory-size" (intSuffix (\n d -> d { historySize = n })) , make_ord_flag defFlag "funfolding-creation-threshold" (intSuffix (\n d -> d {ufCreationThreshold = n})) , make_ord_flag defFlag "funfolding-use-threshold" (intSuffix (\n d -> d {ufUseThreshold = n})) , make_ord_flag defFlag "funfolding-fun-discount" (intSuffix (\n d -> d {ufFunAppDiscount = n})) , make_ord_flag defFlag "funfolding-dict-discount" (intSuffix (\n d -> d {ufDictDiscount = n})) , make_ord_flag defFlag "funfolding-keeness-factor" (floatSuffix (\n d -> d {ufKeenessFactor = n})) , make_ord_flag defFlag "fmax-worker-args" (intSuffix (\n d -> d {maxWorkerArgs = n})) , make_ord_flag defGhciFlag "fghci-hist-size" (intSuffix (\n d -> d {ghciHistSize = n})) , make_ord_flag defGhcFlag "fmax-inline-alloc-size" (intSuffix (\n d -> d { maxInlineAllocSize = n })) , make_ord_flag defGhcFlag "fmax-inline-memcpy-insns" (intSuffix (\n d -> d { maxInlineMemcpyInsns = n })) , make_ord_flag defGhcFlag "fmax-inline-memset-insns" (intSuffix (\n d -> d { maxInlineMemsetInsns = n })) , make_ord_flag defGhcFlag "dinitial-unique" (intSuffix (\n d -> d { initialUnique = n })) , make_ord_flag defGhcFlag "dunique-increment" (intSuffix (\n d -> d { uniqueIncrement = n })) ------ Profiling ---------------------------------------------------- -- OLD profiling flags , make_ord_flag defGhcFlag "auto-all" (noArg (\d -> d { profAuto = ProfAutoAll } )) , make_ord_flag defGhcFlag "no-auto-all" (noArg (\d -> d { profAuto = NoProfAuto } )) , make_ord_flag defGhcFlag "auto" (noArg (\d -> d { profAuto = ProfAutoExports } )) , make_ord_flag defGhcFlag "no-auto" (noArg (\d -> d { profAuto = NoProfAuto } )) , make_ord_flag defGhcFlag "caf-all" (NoArg (setGeneralFlag Opt_AutoSccsOnIndividualCafs)) , make_ord_flag defGhcFlag "no-caf-all" (NoArg (unSetGeneralFlag Opt_AutoSccsOnIndividualCafs)) -- NEW profiling flags , make_ord_flag defGhcFlag "fprof-auto" (noArg (\d -> d { profAuto = ProfAutoAll } )) , make_ord_flag defGhcFlag "fprof-auto-top" (noArg (\d -> d { profAuto = ProfAutoTop } )) , make_ord_flag defGhcFlag "fprof-auto-exported" (noArg (\d -> d { profAuto = ProfAutoExports } )) , make_ord_flag defGhcFlag "fprof-auto-calls" (noArg (\d -> d { profAuto = ProfAutoCalls } )) , make_ord_flag defGhcFlag "fno-prof-auto" (noArg (\d -> d { profAuto = NoProfAuto } )) ------ Compiler flags ----------------------------------------------- , make_ord_flag defGhcFlag "fasm" (NoArg (setObjTarget HscAsm)) , make_ord_flag defGhcFlag "fvia-c" (NoArg (addWarn $ "The -fvia-c flag does nothing; " ++ "it will be removed in a future GHC release")) , make_ord_flag defGhcFlag "fvia-C" (NoArg (addWarn $ "The -fvia-C flag does nothing; " ++ "it will be removed in a future GHC release")) , make_ord_flag defGhcFlag "fllvm" (NoArg (setObjTarget HscLlvm)) , make_ord_flag defFlag "fno-code" (NoArg ((upd $ \d -> d { ghcLink=NoLink }) >> setTarget HscNothing)) , make_ord_flag defFlag "fbyte-code" (NoArg (setTarget HscInterpreted)) , make_ord_flag defFlag "fobject-code" (NoArg (setTargetWithPlatform defaultHscTarget)) , make_dep_flag defFlag "fglasgow-exts" (NoArg enableGlasgowExts) "Use individual extensions instead" , make_dep_flag defFlag "fno-glasgow-exts" (NoArg disableGlasgowExts) "Use individual extensions instead" , make_ord_flag defFlag "Wunused-binds" (NoArg enableUnusedBinds) , make_ord_flag defFlag "Wno-unused-binds" (NoArg disableUnusedBinds) , make_ord_flag defHiddenFlag "fwarn-unused-binds" (NoArg enableUnusedBinds) , make_ord_flag defHiddenFlag "fno-warn-unused-binds" (NoArg disableUnusedBinds) ------ Safe Haskell flags ------------------------------------------- , make_ord_flag defFlag "fpackage-trust" (NoArg setPackageTrust) , make_ord_flag defFlag "fno-safe-infer" (noArg (\d -> d { safeInfer = False })) , make_ord_flag defGhcFlag "fPIC" (NoArg (setGeneralFlag Opt_PIC)) , make_ord_flag defGhcFlag "fno-PIC" (NoArg (unSetGeneralFlag Opt_PIC)) ------ Debugging flags ---------------------------------------------- , make_ord_flag defGhcFlag "g" (OptIntSuffix setDebugLevel) ] ++ map (mkFlag turnOn "" setGeneralFlag ) negatableFlagsDeps ++ map (mkFlag turnOff "no-" unSetGeneralFlag ) negatableFlagsDeps ++ map (mkFlag turnOn "d" setGeneralFlag ) dFlagsDeps ++ map (mkFlag turnOff "dno-" unSetGeneralFlag ) dFlagsDeps ++ map (mkFlag turnOn "f" setGeneralFlag ) fFlagsDeps ++ map (mkFlag turnOff "fno-" unSetGeneralFlag ) fFlagsDeps ++ map (mkFlag turnOn "W" setWarningFlag ) wWarningFlagsDeps ++ map (mkFlag turnOff "Wno-" unSetWarningFlag ) wWarningFlagsDeps ++ map (mkFlag turnOn "fwarn-" setWarningFlag . hideFlag) wWarningFlagsDeps ++ map (mkFlag turnOff "fno-warn-" unSetWarningFlag . hideFlag) wWarningFlagsDeps ++ [ (NotDeprecated, unrecognisedWarning "W") , (NotDeprecated, unrecognisedWarning "fwarn-") , (NotDeprecated, unrecognisedWarning "fno-warn-") ] ++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlagsDeps ++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlagsDeps ++ map (mkFlag turnOn "X" setExtensionFlag ) xFlagsDeps ++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlagsDeps ++ map (mkFlag turnOn "X" setLanguage ) languageFlagsDeps ++ map (mkFlag turnOn "X" setSafeHaskell ) safeHaskellFlagsDeps ++ [ make_dep_flag defFlag "XGenerics" (NoArg $ return ()) ("it does nothing; look into -XDefaultSignatures " ++ "and -XDeriveGeneric for generic programming support.") , make_dep_flag defFlag "XNoGenerics" (NoArg $ return ()) ("it does nothing; look into -XDefaultSignatures and " ++ "-XDeriveGeneric for generic programming support.") ] -- | This is where we handle unrecognised warning flags. We only issue a warning -- if -Wunrecognised-warning-flags is set. See Trac #11429 for context. unrecognisedWarning :: String -> Flag (CmdLineP DynFlags) unrecognisedWarning prefix = defFlag prefix (Prefix action) where action :: String -> EwM (CmdLineP DynFlags) () action flag = do f <- wopt Opt_WarnUnrecognisedWarningFlags <$> liftEwM getCmdLineState when f $ addWarn $ "unrecognised warning flag: -" ++ prefix ++ flag -- See Note [Supporting CLI completion] package_flags_deps :: [(Deprecation, Flag (CmdLineP DynFlags))] package_flags_deps = [ ------- Packages ---------------------------------------------------- make_ord_flag defFlag "package-db" (HasArg (addPkgConfRef . PkgConfFile)) , make_ord_flag defFlag "clear-package-db" (NoArg clearPkgConf) , make_ord_flag defFlag "no-global-package-db" (NoArg removeGlobalPkgConf) , make_ord_flag defFlag "no-user-package-db" (NoArg removeUserPkgConf) , make_ord_flag defFlag "global-package-db" (NoArg (addPkgConfRef GlobalPkgConf)) , make_ord_flag defFlag "user-package-db" (NoArg (addPkgConfRef UserPkgConf)) -- backwards compat with GHC<=7.4 : , make_dep_flag defFlag "package-conf" (HasArg $ addPkgConfRef . PkgConfFile) "Use -package-db instead" , make_dep_flag defFlag "no-user-package-conf" (NoArg removeUserPkgConf) "Use -no-user-package-db instead" , make_ord_flag defGhcFlag "package-name" (HasArg $ \name -> do upd (setUnitId name)) -- TODO: Since we JUST deprecated -- -this-package-key, let's keep this -- undeprecated for another cycle. -- Deprecate this eventually. -- deprecate "Use -this-unit-id instead") , make_dep_flag defGhcFlag "this-package-key" (HasArg $ upd . setUnitId) "Use -this-unit-id instead" , make_ord_flag defGhcFlag "this-unit-id" (hasArg setUnitId) , make_ord_flag defFlag "package" (HasArg exposePackage) , make_ord_flag defFlag "plugin-package-id" (HasArg exposePluginPackageId) , make_ord_flag defFlag "plugin-package" (HasArg exposePluginPackage) , make_ord_flag defFlag "package-id" (HasArg exposePackageId) , make_ord_flag defFlag "hide-package" (HasArg hidePackage) , make_ord_flag defFlag "hide-all-packages" (NoArg (setGeneralFlag Opt_HideAllPackages)) , make_ord_flag defFlag "hide-all-plugin-packages" (NoArg (setGeneralFlag Opt_HideAllPluginPackages)) , make_ord_flag defFlag "package-env" (HasArg setPackageEnv) , make_ord_flag defFlag "ignore-package" (HasArg ignorePackage) , make_dep_flag defFlag "syslib" (HasArg exposePackage) "Use -package instead" , make_ord_flag defFlag "distrust-all-packages" (NoArg (setGeneralFlag Opt_DistrustAllPackages)) , make_ord_flag defFlag "trust" (HasArg trustPackage) , make_ord_flag defFlag "distrust" (HasArg distrustPackage) ] where setPackageEnv env = upd $ \s -> s { packageEnv = Just env } -- | Make a list of flags for shell completion. -- Filter all available flags into two groups, for interactive GHC vs all other. flagsForCompletion :: Bool -> [String] flagsForCompletion isInteractive = [ '-':flagName flag | flag <- flagsAll , modeFilter (flagGhcMode flag) ] where modeFilter AllModes = True modeFilter OnlyGhci = isInteractive modeFilter OnlyGhc = not isInteractive modeFilter HiddenFlag = False 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 data FlagSpec flag = FlagSpec { flagSpecName :: String -- ^ Flag in string form , flagSpecFlag :: flag -- ^ Flag in internal form , flagSpecAction :: (TurnOnFlag -> DynP ()) -- ^ Extra action to run when the flag is found -- Typically, emit a warning or error , flagSpecGhcMode :: GhcFlagMode -- ^ In which ghc mode the flag has effect } -- | Define a new flag. flagSpec :: String -> flag -> (Deprecation, FlagSpec flag) flagSpec name flag = flagSpec' name flag nop -- | Define a new flag with an effect. flagSpec' :: String -> flag -> (TurnOnFlag -> DynP ()) -> (Deprecation, FlagSpec flag) flagSpec' name flag act = (NotDeprecated, FlagSpec name flag act AllModes) -- | Define a new deprecated flag with an effect. depFlagSpecOp :: String -> flag -> (TurnOnFlag -> DynP ()) -> String -> (Deprecation, FlagSpec flag) depFlagSpecOp name flag act dep = (Deprecated, snd (flagSpec' name flag (\f -> act f >> deprecate dep))) -- | Define a new deprecated flag. depFlagSpec :: String -> flag -> String -> (Deprecation, FlagSpec flag) depFlagSpec name flag dep = depFlagSpecOp name flag nop dep -- | Define a new deprecated flag with an effect where the deprecation message -- depends on the flag value depFlagSpecOp' :: String -> flag -> (TurnOnFlag -> DynP ()) -> (TurnOnFlag -> String) -> (Deprecation, FlagSpec flag) depFlagSpecOp' name flag act dep = (Deprecated, FlagSpec name flag (\f -> act f >> (deprecate $ dep f)) AllModes) -- | Define a new deprecated flag where the deprecation message -- depends on the flag value depFlagSpec' :: String -> flag -> (TurnOnFlag -> String) -> (Deprecation, FlagSpec flag) depFlagSpec' name flag dep = depFlagSpecOp' name flag nop dep -- | Define a new deprecated flag where the deprecation message -- is shown depending on the flag value depFlagSpecCond :: String -> flag -> (TurnOnFlag -> Bool) -> String -> (Deprecation, FlagSpec flag) depFlagSpecCond name flag cond dep = (Deprecated, FlagSpec name flag (\f -> when (cond f) $ deprecate dep) AllModes) -- | Define a new flag for GHCi. flagGhciSpec :: String -> flag -> (Deprecation, FlagSpec flag) flagGhciSpec name flag = flagGhciSpec' name flag nop -- | Define a new flag for GHCi with an effect. flagGhciSpec' :: String -> flag -> (TurnOnFlag -> DynP ()) -> (Deprecation, FlagSpec flag) flagGhciSpec' name flag act = (NotDeprecated, FlagSpec name flag act OnlyGhci) -- | Define a new flag invisible to CLI completion. flagHiddenSpec :: String -> flag -> (Deprecation, FlagSpec flag) flagHiddenSpec name flag = flagHiddenSpec' name flag nop -- | Define a new flag invisible to CLI completion with an effect. flagHiddenSpec' :: String -> flag -> (TurnOnFlag -> DynP ()) -> (Deprecation, FlagSpec flag) flagHiddenSpec' name flag act = (NotDeprecated, FlagSpec name flag act HiddenFlag) -- | Hide a 'FlagSpec' from being displayed in @--show-options@. -- -- This is for example useful for flags that are obsolete, but should not -- (yet) be deprecated for compatibility reasons. hideFlag :: (Deprecation, FlagSpec a) -> (Deprecation, FlagSpec a) hideFlag (dep, fs) = (dep, fs { flagSpecGhcMode = HiddenFlag }) mkFlag :: TurnOnFlag -- ^ True <=> it should be turned on -> String -- ^ The flag prefix -> (flag -> DynP ()) -- ^ What to do when the flag is found -> (Deprecation, FlagSpec flag) -- ^ Specification of -- this particular flag -> (Deprecation, Flag (CmdLineP DynFlags)) mkFlag turn_on flagPrefix f (dep, (FlagSpec name flag extra_action mode)) = (dep, Flag (flagPrefix ++ name) (NoArg (f flag >> extra_action turn_on)) mode) deprecatedForExtension :: String -> TurnOnFlag -> String deprecatedForExtension lang turn_on = "use -X" ++ flag ++ " or pragma {-# LANGUAGE " ++ flag ++ " #-} instead" where flag | turn_on = lang | otherwise = "No" ++ lang useInstead :: String -> TurnOnFlag -> String useInstead flag turn_on = "Use -f" ++ no ++ flag ++ " instead" where no = if turn_on then "" else "no-" nop :: TurnOnFlag -> DynP () nop _ = return () -- | Find the 'FlagSpec' for a 'WarningFlag'. flagSpecOf :: WarningFlag -> Maybe (FlagSpec WarningFlag) flagSpecOf flag = listToMaybe $ filter check wWarningFlags where check fs = flagSpecFlag fs == flag -- | These @-W\<blah\>@ flags can all be reversed with @-Wno-\<blah\>@ wWarningFlags :: [FlagSpec WarningFlag] wWarningFlags = map snd wWarningFlagsDeps wWarningFlagsDeps :: [(Deprecation, FlagSpec WarningFlag)] wWarningFlagsDeps = [ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] -- Please keep the list of flags below sorted alphabetically flagSpec "alternative-layout-rule-transitional" Opt_WarnAlternativeLayoutRuleTransitional, depFlagSpec "amp" Opt_WarnAMP "it has no effect", depFlagSpec "auto-orphans" Opt_WarnAutoOrphans "it has no effect", flagSpec "deferred-type-errors" Opt_WarnDeferredTypeErrors, flagSpec "deprecations" Opt_WarnWarningsDeprecations, flagSpec "deprecated-flags" Opt_WarnDeprecatedFlags, flagSpec "deriving-typeable" Opt_WarnDerivingTypeable, flagSpec "dodgy-exports" Opt_WarnDodgyExports, flagSpec "dodgy-foreign-imports" Opt_WarnDodgyForeignImports, flagSpec "dodgy-imports" Opt_WarnDodgyImports, flagSpec "empty-enumerations" Opt_WarnEmptyEnumerations, depFlagSpec "context-quantification" Opt_WarnContextQuantification "it is subsumed by an error message that cannot be disabled", depFlagSpec "duplicate-constraints" Opt_WarnDuplicateConstraints "it is subsumed by -Wredundant-constraints", flagSpec "redundant-constraints" Opt_WarnRedundantConstraints, flagSpec "duplicate-exports" Opt_WarnDuplicateExports, flagSpec "hi-shadowing" Opt_WarnHiShadows, flagSpec "implicit-prelude" Opt_WarnImplicitPrelude, flagSpec "incomplete-patterns" Opt_WarnIncompletePatterns, flagSpec "incomplete-record-updates" Opt_WarnIncompletePatternsRecUpd, flagSpec "incomplete-uni-patterns" Opt_WarnIncompleteUniPatterns, flagSpec "inline-rule-shadowing" Opt_WarnInlineRuleShadowing, flagSpec "identities" Opt_WarnIdentities, flagSpec "missing-fields" Opt_WarnMissingFields, flagSpec "missing-import-lists" Opt_WarnMissingImportList, depFlagSpec "missing-local-sigs" Opt_WarnMissingLocalSignatures "it is replaced by -Wmissing-local-signatures", flagSpec "missing-local-signatures" Opt_WarnMissingLocalSignatures, flagSpec "missing-methods" Opt_WarnMissingMethods, flagSpec "missing-monadfail-instances" Opt_WarnMissingMonadFailInstances, flagSpec "semigroup" Opt_WarnSemigroup, flagSpec "missing-signatures" Opt_WarnMissingSignatures, depFlagSpec "missing-exported-sigs" Opt_WarnMissingExportedSignatures "it is replaced by -Wmissing-exported-signatures", flagSpec "missing-exported-signatures" Opt_WarnMissingExportedSignatures, flagSpec "monomorphism-restriction" Opt_WarnMonomorphism, flagSpec "name-shadowing" Opt_WarnNameShadowing, flagSpec "noncanonical-monad-instances" Opt_WarnNonCanonicalMonadInstances, flagSpec "noncanonical-monadfail-instances" Opt_WarnNonCanonicalMonadFailInstances, flagSpec "noncanonical-monoid-instances" Opt_WarnNonCanonicalMonoidInstances, flagSpec "orphans" Opt_WarnOrphans, flagSpec "overflowed-literals" Opt_WarnOverflowedLiterals, flagSpec "overlapping-patterns" Opt_WarnOverlappingPatterns, flagSpec "missed-specialisations" Opt_WarnMissedSpecs, flagSpec "all-missed-specialisations" Opt_WarnAllMissedSpecs, flagSpec' "safe" Opt_WarnSafe setWarnSafe, flagSpec "trustworthy-safe" Opt_WarnTrustworthySafe, flagSpec "tabs" Opt_WarnTabs, flagSpec "type-defaults" Opt_WarnTypeDefaults, flagSpec "typed-holes" Opt_WarnTypedHoles, flagSpec "partial-type-signatures" Opt_WarnPartialTypeSignatures, flagSpec "unrecognised-pragmas" Opt_WarnUnrecognisedPragmas, flagSpec' "unsafe" Opt_WarnUnsafe setWarnUnsafe, flagSpec "unsupported-calling-conventions" Opt_WarnUnsupportedCallingConventions, flagSpec "unsupported-llvm-version" Opt_WarnUnsupportedLlvmVersion, flagSpec "unticked-promoted-constructors" Opt_WarnUntickedPromotedConstructors, flagSpec "unused-do-bind" Opt_WarnUnusedDoBind, flagSpec "unused-foralls" Opt_WarnUnusedForalls, flagSpec "unused-imports" Opt_WarnUnusedImports, flagSpec "unused-local-binds" Opt_WarnUnusedLocalBinds, flagSpec "unused-matches" Opt_WarnUnusedMatches, flagSpec "unused-pattern-binds" Opt_WarnUnusedPatternBinds, flagSpec "unused-top-binds" Opt_WarnUnusedTopBinds, flagSpec "unused-type-patterns" Opt_WarnUnusedTypePatterns, flagSpec "warnings-deprecations" Opt_WarnWarningsDeprecations, flagSpec "wrong-do-bind" Opt_WarnWrongDoBind, flagSpec "missing-pattern-synonym-signatures" Opt_WarnMissingPatternSynonymSignatures, flagSpec "unrecognised-warning-flags" Opt_WarnUnrecognisedWarningFlags ] -- | These @-\<blah\>@ flags can all be reversed with @-no-\<blah\>@ negatableFlagsDeps :: [(Deprecation, FlagSpec GeneralFlag)] negatableFlagsDeps = [ flagGhciSpec "ignore-dot-ghci" Opt_IgnoreDotGhci ] -- | These @-d\<blah\>@ flags can all be reversed with @-dno-\<blah\>@ dFlagsDeps :: [(Deprecation, FlagSpec GeneralFlag)] dFlagsDeps = [ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] -- Please keep the list of flags below sorted alphabetically flagSpec "ppr-case-as-let" Opt_PprCaseAsLet, flagSpec "ppr-ticks" Opt_PprShowTicks, flagSpec "suppress-coercions" Opt_SuppressCoercions, flagSpec "suppress-idinfo" Opt_SuppressIdInfo, flagSpec "suppress-unfoldings" Opt_SuppressUnfoldings, flagSpec "suppress-module-prefixes" Opt_SuppressModulePrefixes, flagSpec "suppress-type-applications" Opt_SuppressTypeApplications, flagSpec "suppress-type-signatures" Opt_SuppressTypeSignatures, flagSpec "suppress-uniques" Opt_SuppressUniques, flagSpec "suppress-var-kinds" Opt_SuppressVarKinds] -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@ fFlags :: [FlagSpec GeneralFlag] fFlags = map snd fFlagsDeps fFlagsDeps :: [(Deprecation, FlagSpec GeneralFlag)] fFlagsDeps = [ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] -- Please keep the list of flags below sorted alphabetically flagGhciSpec "break-on-error" Opt_BreakOnError, flagGhciSpec "break-on-exception" Opt_BreakOnException, flagSpec "building-cabal-package" Opt_BuildingCabalPackage, flagSpec "call-arity" Opt_CallArity, flagSpec "case-merge" Opt_CaseMerge, flagSpec "cmm-elim-common-blocks" Opt_CmmElimCommonBlocks, flagSpec "cmm-sink" Opt_CmmSink, flagSpec "cse" Opt_CSE, flagSpec "cpr-anal" Opt_CprAnal, flagSpec "defer-type-errors" Opt_DeferTypeErrors, flagSpec "defer-typed-holes" Opt_DeferTypedHoles, flagSpec "dicts-cheap" Opt_DictsCheap, flagSpec "dicts-strict" Opt_DictsStrict, flagSpec "dmd-tx-dict-sel" Opt_DmdTxDictSel, flagSpec "do-eta-reduction" Opt_DoEtaReduction, flagSpec "do-lambda-eta-expansion" Opt_DoLambdaEtaExpansion, flagSpec "eager-blackholing" Opt_EagerBlackHoling, flagSpec "embed-manifest" Opt_EmbedManifest, flagSpec "enable-rewrite-rules" Opt_EnableRewriteRules, flagSpec "error-spans" Opt_ErrorSpans, flagSpec "excess-precision" Opt_ExcessPrecision, flagSpec "expose-all-unfoldings" Opt_ExposeAllUnfoldings, flagSpec "external-interpreter" Opt_ExternalInterpreter, flagSpec "flat-cache" Opt_FlatCache, flagSpec "float-in" Opt_FloatIn, flagSpec "force-recomp" Opt_ForceRecomp, flagSpec "full-laziness" Opt_FullLaziness, flagSpec "fun-to-thunk" Opt_FunToThunk, flagSpec "gen-manifest" Opt_GenManifest, flagSpec "ghci-history" Opt_GhciHistory, flagSpec "ghci-sandbox" Opt_GhciSandbox, flagSpec "helpful-errors" Opt_HelpfulErrors, flagSpec "hpc" Opt_Hpc, flagSpec "ignore-asserts" Opt_IgnoreAsserts, flagSpec "ignore-interface-pragmas" Opt_IgnoreInterfacePragmas, flagGhciSpec "implicit-import-qualified" Opt_ImplicitImportQualified, flagSpec "irrefutable-tuples" Opt_IrrefutableTuples, flagSpec "kill-absence" Opt_KillAbsence, flagSpec "kill-one-shot" Opt_KillOneShot, flagSpec "late-dmd-anal" Opt_LateDmdAnal, flagSpec "liberate-case" Opt_LiberateCase, flagHiddenSpec "llvm-pass-vectors-in-regs" Opt_LlvmPassVectorsInRegisters, flagHiddenSpec "llvm-tbaa" Opt_LlvmTBAA, flagHiddenSpec "llvm-fill-undef-with-garbage" Opt_LlvmFillUndefWithGarbage, flagSpec "loopification" Opt_Loopification, flagSpec "omit-interface-pragmas" Opt_OmitInterfacePragmas, flagSpec "omit-yields" Opt_OmitYields, flagSpec "optimal-applicative-do" Opt_OptimalApplicativeDo, flagSpec "pedantic-bottoms" Opt_PedanticBottoms, flagSpec "pre-inlining" Opt_SimplPreInlining, flagGhciSpec "print-bind-contents" Opt_PrintBindContents, flagGhciSpec "print-bind-result" Opt_PrintBindResult, flagGhciSpec "print-evld-with-show" Opt_PrintEvldWithShow, flagSpec "print-explicit-foralls" Opt_PrintExplicitForalls, flagSpec "print-explicit-kinds" Opt_PrintExplicitKinds, flagSpec "print-explicit-coercions" Opt_PrintExplicitCoercions, flagSpec "print-equality-relations" Opt_PrintEqualityRelations, flagSpec "print-unicode-syntax" Opt_PrintUnicodeSyntax, flagSpec "print-expanded-synonyms" Opt_PrintExpandedSynonyms, flagSpec "print-potential-instances" Opt_PrintPotentialInstances, flagSpec "print-typechecker-elaboration" Opt_PrintTypecheckerElaboration, flagSpec "prof-cafs" Opt_AutoSccsOnIndividualCafs, flagSpec "prof-count-entries" Opt_ProfCountEntries, flagSpec "regs-graph" Opt_RegsGraph, flagSpec "regs-iterative" Opt_RegsIterative, depFlagSpec' "rewrite-rules" Opt_EnableRewriteRules (useInstead "enable-rewrite-rules"), flagSpec "shared-implib" Opt_SharedImplib, flagSpec "simple-list-literals" Opt_SimpleListLiterals, flagSpec "spec-constr" Opt_SpecConstr, flagSpec "specialise" Opt_Specialise, flagSpec "specialise-aggressively" Opt_SpecialiseAggressively, flagSpec "cross-module-specialise" Opt_CrossModuleSpecialise, flagSpec "static-argument-transformation" Opt_StaticArgumentTransformation, flagSpec "strictness" Opt_Strictness, flagSpec "use-rpaths" Opt_RPath, flagSpec "write-interface" Opt_WriteInterface, flagSpec "unbox-small-strict-fields" Opt_UnboxSmallStrictFields, flagSpec "unbox-strict-fields" Opt_UnboxStrictFields, flagSpec "vectorisation-avoidance" Opt_VectorisationAvoidance, flagSpec "vectorise" Opt_Vectorise, flagSpec "worker-wrapper" Opt_WorkerWrapper, flagSpec "show-warning-groups" Opt_ShowWarnGroups ] -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@ fLangFlags :: [FlagSpec LangExt.Extension] fLangFlags = map snd fLangFlagsDeps fLangFlagsDeps :: [(Deprecation, FlagSpec LangExt.Extension)] fLangFlagsDeps = [ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] depFlagSpecOp' "th" LangExt.TemplateHaskell checkTemplateHaskellOk (deprecatedForExtension "TemplateHaskell"), depFlagSpec' "fi" LangExt.ForeignFunctionInterface (deprecatedForExtension "ForeignFunctionInterface"), depFlagSpec' "ffi" LangExt.ForeignFunctionInterface (deprecatedForExtension "ForeignFunctionInterface"), depFlagSpec' "arrows" LangExt.Arrows (deprecatedForExtension "Arrows"), depFlagSpec' "implicit-prelude" LangExt.ImplicitPrelude (deprecatedForExtension "ImplicitPrelude"), depFlagSpec' "bang-patterns" LangExt.BangPatterns (deprecatedForExtension "BangPatterns"), depFlagSpec' "monomorphism-restriction" LangExt.MonomorphismRestriction (deprecatedForExtension "MonomorphismRestriction"), depFlagSpec' "mono-pat-binds" LangExt.MonoPatBinds (deprecatedForExtension "MonoPatBinds"), depFlagSpec' "extended-default-rules" LangExt.ExtendedDefaultRules (deprecatedForExtension "ExtendedDefaultRules"), depFlagSpec' "implicit-params" LangExt.ImplicitParams (deprecatedForExtension "ImplicitParams"), depFlagSpec' "scoped-type-variables" LangExt.ScopedTypeVariables (deprecatedForExtension "ScopedTypeVariables"), depFlagSpec' "parr" LangExt.ParallelArrays (deprecatedForExtension "ParallelArrays"), depFlagSpec' "PArr" LangExt.ParallelArrays (deprecatedForExtension "ParallelArrays"), depFlagSpec' "allow-overlapping-instances" LangExt.OverlappingInstances (deprecatedForExtension "OverlappingInstances"), depFlagSpec' "allow-undecidable-instances" LangExt.UndecidableInstances (deprecatedForExtension "UndecidableInstances"), depFlagSpec' "allow-incoherent-instances" LangExt.IncoherentInstances (deprecatedForExtension "IncoherentInstances") ] supportedLanguages :: [String] supportedLanguages = map (flagSpecName . snd) languageFlagsDeps supportedLanguageOverlays :: [String] supportedLanguageOverlays = map (flagSpecName . snd) safeHaskellFlagsDeps supportedExtensions :: [String] supportedExtensions = concatMap toFlagSpecNamePair xFlags where toFlagSpecNamePair flg #ifndef GHCI -- make sure that `ghc --supported-extensions` omits -- "TemplateHaskell" when it's known to be unsupported. See also -- GHC #11102 for rationale | flagSpecFlag flg == LangExt.TemplateHaskell = [noName] #endif | otherwise = [name, noName] where noName = "No" ++ name name = flagSpecName flg supportedLanguagesAndExtensions :: [String] supportedLanguagesAndExtensions = supportedLanguages ++ supportedLanguageOverlays ++ supportedExtensions -- | These -X<blah> flags cannot be reversed with -XNo<blah> languageFlagsDeps :: [(Deprecation, FlagSpec Language)] languageFlagsDeps = [ flagSpec "Haskell98" Haskell98, flagSpec "Haskell2010" Haskell2010 ] -- | 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. safeHaskellFlagsDeps :: [(Deprecation, FlagSpec SafeHaskellMode)] safeHaskellFlagsDeps = [mkF Sf_Unsafe, mkF Sf_Trustworthy, mkF Sf_Safe] where mkF flag = flagSpec (show flag) flag -- | These -X<blah> flags can all be reversed with -XNo<blah> xFlags :: [FlagSpec LangExt.Extension] xFlags = map snd xFlagsDeps xFlagsDeps :: [(Deprecation, FlagSpec LangExt.Extension)] xFlagsDeps = [ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] -- See Note [Adding a language extension] -- Please keep the list of flags below sorted alphabetically flagSpec "AllowAmbiguousTypes" LangExt.AllowAmbiguousTypes, flagSpec "AlternativeLayoutRule" LangExt.AlternativeLayoutRule, flagSpec "AlternativeLayoutRuleTransitional" LangExt.AlternativeLayoutRuleTransitional, flagSpec "Arrows" LangExt.Arrows, flagSpec "AutoDeriveTypeable" LangExt.AutoDeriveTypeable, flagSpec "BangPatterns" LangExt.BangPatterns, flagSpec "BinaryLiterals" LangExt.BinaryLiterals, flagSpec "CApiFFI" LangExt.CApiFFI, flagSpec "CPP" LangExt.Cpp, flagSpec "ConstrainedClassMethods" LangExt.ConstrainedClassMethods, flagSpec "ConstraintKinds" LangExt.ConstraintKinds, flagSpec "DataKinds" LangExt.DataKinds, depFlagSpecCond "DatatypeContexts" LangExt.DatatypeContexts id ("It was widely considered a misfeature, " ++ "and has been removed from the Haskell language."), flagSpec "DefaultSignatures" LangExt.DefaultSignatures, flagSpec "DeriveAnyClass" LangExt.DeriveAnyClass, flagSpec "DeriveDataTypeable" LangExt.DeriveDataTypeable, flagSpec "DeriveFoldable" LangExt.DeriveFoldable, flagSpec "DeriveFunctor" LangExt.DeriveFunctor, flagSpec "DeriveGeneric" LangExt.DeriveGeneric, flagSpec "DeriveLift" LangExt.DeriveLift, flagSpec "DeriveTraversable" LangExt.DeriveTraversable, flagSpec "DisambiguateRecordFields" LangExt.DisambiguateRecordFields, flagSpec "DoAndIfThenElse" LangExt.DoAndIfThenElse, depFlagSpec' "DoRec" LangExt.RecursiveDo (deprecatedForExtension "RecursiveDo"), flagSpec "DuplicateRecordFields" LangExt.DuplicateRecordFields, flagSpec "EmptyCase" LangExt.EmptyCase, flagSpec "EmptyDataDecls" LangExt.EmptyDataDecls, flagSpec "ExistentialQuantification" LangExt.ExistentialQuantification, flagSpec "ExplicitForAll" LangExt.ExplicitForAll, flagSpec "ExplicitNamespaces" LangExt.ExplicitNamespaces, flagSpec "ExtendedDefaultRules" LangExt.ExtendedDefaultRules, flagSpec "FlexibleContexts" LangExt.FlexibleContexts, flagSpec "FlexibleInstances" LangExt.FlexibleInstances, flagSpec "ForeignFunctionInterface" LangExt.ForeignFunctionInterface, flagSpec "FunctionalDependencies" LangExt.FunctionalDependencies, flagSpec "GADTSyntax" LangExt.GADTSyntax, flagSpec "GADTs" LangExt.GADTs, flagSpec "GHCForeignImportPrim" LangExt.GHCForeignImportPrim, flagSpec' "GeneralizedNewtypeDeriving" LangExt.GeneralizedNewtypeDeriving setGenDeriving, flagSpec "ImplicitParams" LangExt.ImplicitParams, flagSpec "ImplicitPrelude" LangExt.ImplicitPrelude, flagSpec "ImpredicativeTypes" LangExt.ImpredicativeTypes, flagSpec' "IncoherentInstances" LangExt.IncoherentInstances setIncoherentInsts, flagSpec "TypeFamilyDependencies" LangExt.TypeFamilyDependencies, flagSpec "InstanceSigs" LangExt.InstanceSigs, flagSpec "ApplicativeDo" LangExt.ApplicativeDo, flagSpec "InterruptibleFFI" LangExt.InterruptibleFFI, flagSpec "JavaScriptFFI" LangExt.JavaScriptFFI, flagSpec "KindSignatures" LangExt.KindSignatures, flagSpec "LambdaCase" LangExt.LambdaCase, flagSpec "LiberalTypeSynonyms" LangExt.LiberalTypeSynonyms, flagSpec "MagicHash" LangExt.MagicHash, flagSpec "MonadComprehensions" LangExt.MonadComprehensions, flagSpec "MonadFailDesugaring" LangExt.MonadFailDesugaring, flagSpec "MonoLocalBinds" LangExt.MonoLocalBinds, depFlagSpecCond "MonoPatBinds" LangExt.MonoPatBinds id "Experimental feature now removed; has no effect", flagSpec "MonomorphismRestriction" LangExt.MonomorphismRestriction, flagSpec "MultiParamTypeClasses" LangExt.MultiParamTypeClasses, flagSpec "MultiWayIf" LangExt.MultiWayIf, flagSpec "NPlusKPatterns" LangExt.NPlusKPatterns, flagSpec "NamedFieldPuns" LangExt.RecordPuns, flagSpec "NamedWildCards" LangExt.NamedWildCards, flagSpec "NegativeLiterals" LangExt.NegativeLiterals, flagSpec "NondecreasingIndentation" LangExt.NondecreasingIndentation, depFlagSpec' "NullaryTypeClasses" LangExt.NullaryTypeClasses (deprecatedForExtension "MultiParamTypeClasses"), flagSpec "NumDecimals" LangExt.NumDecimals, depFlagSpecOp "OverlappingInstances" LangExt.OverlappingInstances setOverlappingInsts "instead use per-instance pragmas OVERLAPPING/OVERLAPPABLE/OVERLAPS", flagSpec "OverloadedLabels" LangExt.OverloadedLabels, flagSpec "OverloadedLists" LangExt.OverloadedLists, flagSpec "OverloadedStrings" LangExt.OverloadedStrings, flagSpec "PackageImports" LangExt.PackageImports, flagSpec "ParallelArrays" LangExt.ParallelArrays, flagSpec "ParallelListComp" LangExt.ParallelListComp, flagSpec "PartialTypeSignatures" LangExt.PartialTypeSignatures, flagSpec "PatternGuards" LangExt.PatternGuards, depFlagSpec' "PatternSignatures" LangExt.ScopedTypeVariables (deprecatedForExtension "ScopedTypeVariables"), flagSpec "PatternSynonyms" LangExt.PatternSynonyms, flagSpec "PolyKinds" LangExt.PolyKinds, flagSpec "PolymorphicComponents" LangExt.RankNTypes, flagSpec "PostfixOperators" LangExt.PostfixOperators, flagSpec "QuasiQuotes" LangExt.QuasiQuotes, flagSpec "Rank2Types" LangExt.RankNTypes, flagSpec "RankNTypes" LangExt.RankNTypes, flagSpec "RebindableSyntax" LangExt.RebindableSyntax, depFlagSpec' "RecordPuns" LangExt.RecordPuns (deprecatedForExtension "NamedFieldPuns"), flagSpec "RecordWildCards" LangExt.RecordWildCards, flagSpec "RecursiveDo" LangExt.RecursiveDo, flagSpec "RelaxedLayout" LangExt.RelaxedLayout, depFlagSpecCond "RelaxedPolyRec" LangExt.RelaxedPolyRec not "You can't turn off RelaxedPolyRec any more", flagSpec "RoleAnnotations" LangExt.RoleAnnotations, flagSpec "ScopedTypeVariables" LangExt.ScopedTypeVariables, flagSpec "StandaloneDeriving" LangExt.StandaloneDeriving, flagSpec "StaticPointers" LangExt.StaticPointers, flagSpec "Strict" LangExt.Strict, flagSpec "StrictData" LangExt.StrictData, flagSpec' "TemplateHaskell" LangExt.TemplateHaskell checkTemplateHaskellOk, flagSpec "TemplateHaskellQuotes" LangExt.TemplateHaskellQuotes, flagSpec "TraditionalRecordSyntax" LangExt.TraditionalRecordSyntax, flagSpec "TransformListComp" LangExt.TransformListComp, flagSpec "TupleSections" LangExt.TupleSections, flagSpec "TypeApplications" LangExt.TypeApplications, flagSpec "TypeInType" LangExt.TypeInType, flagSpec "TypeFamilies" LangExt.TypeFamilies, flagSpec "TypeOperators" LangExt.TypeOperators, flagSpec "TypeSynonymInstances" LangExt.TypeSynonymInstances, flagSpec "UnboxedTuples" LangExt.UnboxedTuples, flagSpec "UndecidableInstances" LangExt.UndecidableInstances, flagSpec "UndecidableSuperClasses" LangExt.UndecidableSuperClasses, flagSpec "UnicodeSyntax" LangExt.UnicodeSyntax, flagSpec "UnliftedFFITypes" LangExt.UnliftedFFITypes, flagSpec "ViewPatterns" LangExt.ViewPatterns ] defaultFlags :: Settings -> [GeneralFlag] defaultFlags settings -- See Note [Updating flag description in the User's Guide] = [ Opt_AutoLinkPackages, Opt_EmbedManifest, Opt_FlatCache, Opt_GenManifest, Opt_GhciHistory, Opt_GhciSandbox, Opt_HelpfulErrors, Opt_OmitYields, Opt_PrintBindContents, Opt_ProfCountEntries, Opt_RPath, Opt_SharedImplib, Opt_SimplPreInlining ] ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns] -- The default -O0 options ++ default_PIC platform ++ concatMap (wayGeneralFlags platform) (defaultWays settings) where platform = sTargetPlatform settings default_PIC :: Platform -> [GeneralFlag] default_PIC platform = case (platformOS platform, platformArch platform) of (OSDarwin, ArchX86_64) -> [Opt_PIC] (OSOpenBSD, ArchX86_64) -> [Opt_PIC] -- Due to PIE support in -- OpenBSD since 5.3 release -- (1 May 2013) we need to -- always generate PIC. See -- #10597 for more -- information. _ -> [] -- General flags that are switched on/off when other general flags are switched -- on impliedGFlags :: [(GeneralFlag, TurnOnFlag, GeneralFlag)] impliedGFlags = [(Opt_DeferTypeErrors, turnOn, Opt_DeferTypedHoles) ,(Opt_Strictness, turnOn, Opt_WorkerWrapper) ] -- General flags that are switched on/off when other general flags are switched -- off impliedOffGFlags :: [(GeneralFlag, TurnOnFlag, GeneralFlag)] impliedOffGFlags = [(Opt_Strictness, turnOff, Opt_WorkerWrapper)] impliedXFlags :: [(LangExt.Extension, TurnOnFlag, LangExt.Extension)] impliedXFlags -- See Note [Updating flag description in the User's Guide] = [ (LangExt.RankNTypes, turnOn, LangExt.ExplicitForAll) , (LangExt.ScopedTypeVariables, turnOn, LangExt.ExplicitForAll) , (LangExt.LiberalTypeSynonyms, turnOn, LangExt.ExplicitForAll) , (LangExt.ExistentialQuantification, turnOn, LangExt.ExplicitForAll) , (LangExt.FlexibleInstances, turnOn, LangExt.TypeSynonymInstances) , (LangExt.FunctionalDependencies, turnOn, LangExt.MultiParamTypeClasses) , (LangExt.MultiParamTypeClasses, turnOn, LangExt.ConstrainedClassMethods) -- c.f. Trac #7854 , (LangExt.TypeFamilyDependencies, turnOn, LangExt.TypeFamilies) , (LangExt.RebindableSyntax, turnOff, LangExt.ImplicitPrelude) -- NB: turn off! , (LangExt.GADTs, turnOn, LangExt.GADTSyntax) , (LangExt.GADTs, turnOn, LangExt.MonoLocalBinds) , (LangExt.TypeFamilies, turnOn, LangExt.MonoLocalBinds) , (LangExt.TypeFamilies, turnOn, LangExt.KindSignatures) -- Type families use kind signatures , (LangExt.PolyKinds, turnOn, LangExt.KindSignatures) -- Ditto polymorphic kinds , (LangExt.TypeInType, turnOn, LangExt.DataKinds) , (LangExt.TypeInType, turnOn, LangExt.PolyKinds) , (LangExt.TypeInType, turnOn, LangExt.KindSignatures) -- AutoDeriveTypeable is not very useful without DeriveDataTypeable , (LangExt.AutoDeriveTypeable, turnOn, LangExt.DeriveDataTypeable) -- We turn this on so that we can export associated type -- type synonyms in subordinates (e.g. MyClass(type AssocType)) , (LangExt.TypeFamilies, turnOn, LangExt.ExplicitNamespaces) , (LangExt.TypeOperators, turnOn, LangExt.ExplicitNamespaces) , (LangExt.ImpredicativeTypes, turnOn, LangExt.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' , (LangExt.RecordWildCards, turnOn, LangExt.DisambiguateRecordFields) , (LangExt.ParallelArrays, turnOn, LangExt.ParallelListComp) , (LangExt.JavaScriptFFI, turnOn, LangExt.InterruptibleFFI) , (LangExt.DeriveTraversable, turnOn, LangExt.DeriveFunctor) , (LangExt.DeriveTraversable, turnOn, LangExt.DeriveFoldable) -- Duplicate record fields require field disambiguation , (LangExt.DuplicateRecordFields, turnOn, LangExt.DisambiguateRecordFields) , (LangExt.TemplateHaskell, turnOn, LangExt.TemplateHaskellQuotes) , (LangExt.Strict, turnOn, LangExt.StrictData) , (LangExt.TypeApplications, turnOn, LangExt.AllowAmbiguousTypes) ] -- Note [Documenting optimisation flags] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- If you change the list of flags enabled for particular optimisation levels -- please remember to update the User's Guide. The relevant files are: -- -- * utils/mkUserGuidePart/Options/ -- * docs/users_guide/using.rst -- -- The first contains the Flag Refrence section, which breifly lists all -- available flags. The second contains a detailed description of the -- flags. Both places should contain information whether a flag is implied by -- -O0, -O or -O2. optLevelFlags :: [([Int], GeneralFlag)] optLevelFlags -- see Note [Documenting optimisation flags] = [ ([0,1,2], Opt_DoLambdaEtaExpansion) , ([0,1,2], Opt_DoEtaReduction) -- See Note [Eta-reduction in -O0] , ([0,1,2], Opt_DmdTxDictSel) , ([0,1,2], Opt_LlvmTBAA) , ([0,1,2], Opt_VectorisationAvoidance) -- 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], Opt_IgnoreInterfacePragmas) , ([0], Opt_OmitInterfacePragmas) , ([1,2], Opt_CallArity) , ([1,2], Opt_CaseMerge) , ([1,2], Opt_CmmElimCommonBlocks) , ([1,2], Opt_CmmSink) , ([1,2], Opt_CSE) , ([1,2], Opt_EnableRewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules] -- in PrelRules , ([1,2], Opt_FloatIn) , ([1,2], Opt_FullLaziness) , ([1,2], Opt_IgnoreAsserts) , ([1,2], Opt_Loopification) , ([1,2], Opt_Specialise) , ([1,2], Opt_CrossModuleSpecialise) , ([1,2], Opt_Strictness) , ([1,2], Opt_UnboxSmallStrictFields) , ([1,2], Opt_CprAnal) , ([1,2], Opt_WorkerWrapper) , ([2], Opt_LiberateCase) , ([2], Opt_SpecConstr) -- , ([2], Opt_RegsGraph) -- RegsGraph suffers performance regression. See #7679 -- , ([2], Opt_StaticArgumentTransformation) -- Static Argument Transformation needs investigation. See #9374 ] {- Note [Eta-reduction in -O0] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Trac #11562 showed an example which tripped an ASSERT in CoreToStg; a function was marked as MayHaveCafRefs when in fact it obviously didn't. Reason was: * Eta reduction wasn't happening in the simplifier, but it was happening in CorePrep, on $fBla = MkDict (/\a. K a) * Result: rhsIsStatic told TidyPgm that $fBla might have CAF refs but the eta-reduced version (MkDict K) obviously doesn't Simple solution: just let the simplifier do eta-reduction even in -O0. After all, CorePrep does it unconditionally! Not a big deal, but removes an assertion failure. -} -- ----------------------------------------------------------------------------- -- Standard sets of warning options -- Note [Documenting warning flags] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- If you change the list of warning enabled by default -- please remember to update the User's Guide. The relevant file is: -- -- * utils/mkUserGuidePart/ -- * docs/users_guide/using-warnings.rst -- | Warning groups. -- -- As all warnings are in the Weverything set, it is ignored when -- displaying to the user which group a warning is in. warningGroups :: [(String, [WarningFlag])] warningGroups = [ ("compat", minusWcompatOpts) , ("unused-binds", unusedBindsFlags) , ("default", standardWarnings) , ("extra", minusWOpts) , ("all", minusWallOpts) , ("everything", minusWeverythingOpts) ] -- | Warning group hierarchies, where there is an explicit inclusion -- relation. -- -- Each inner list is a hierarchy of warning groups, ordered from -- smallest to largest, where each group is a superset of the one -- before it. -- -- Separating this from 'warningGroups' allows for multiple -- hierarchies with no inherent relation to be defined. -- -- The special-case Weverything group is not included. warningHierarchies :: [[String]] warningHierarchies = hierarchies ++ map (:[]) rest where hierarchies = [["default", "extra", "all"]] rest = filter (`notElem` "everything" : concat hierarchies) $ map fst warningGroups -- | Find the smallest group in every hierarchy which a warning -- belongs to, excluding Weverything. smallestGroups :: WarningFlag -> [String] smallestGroups flag = mapMaybe go warningHierarchies where -- Because each hierarchy is arranged from smallest to largest, -- the first group we find in a hierarchy which contains the flag -- is the smallest. go (group:rest) = fromMaybe (go rest) $ do flags <- lookup group warningGroups guard (flag `elem` flags) pure (Just group) go [] = Nothing -- | Warnings enabled unless specified otherwise standardWarnings :: [WarningFlag] standardWarnings -- see Note [Documenting warning flags] = [ Opt_WarnOverlappingPatterns, Opt_WarnWarningsDeprecations, Opt_WarnDeprecatedFlags, Opt_WarnDeferredTypeErrors, Opt_WarnTypedHoles, Opt_WarnPartialTypeSignatures, Opt_WarnUnrecognisedPragmas, Opt_WarnDuplicateExports, Opt_WarnOverflowedLiterals, Opt_WarnEmptyEnumerations, Opt_WarnMissingFields, Opt_WarnMissingMethods, Opt_WarnWrongDoBind, Opt_WarnUnsupportedCallingConventions, Opt_WarnDodgyForeignImports, Opt_WarnInlineRuleShadowing, Opt_WarnAlternativeLayoutRuleTransitional, Opt_WarnUnsupportedLlvmVersion, Opt_WarnTabs, Opt_WarnUnrecognisedWarningFlags ] -- | Things you get with -W minusWOpts :: [WarningFlag] minusWOpts = standardWarnings ++ [ Opt_WarnUnusedTopBinds, Opt_WarnUnusedLocalBinds, Opt_WarnUnusedPatternBinds, Opt_WarnUnusedMatches, Opt_WarnUnusedForalls, Opt_WarnUnusedImports, Opt_WarnIncompletePatterns, Opt_WarnDodgyExports, Opt_WarnDodgyImports ] -- | Things you get with -Wall minusWallOpts :: [WarningFlag] minusWallOpts = minusWOpts ++ [ Opt_WarnTypeDefaults, Opt_WarnNameShadowing, Opt_WarnMissingSignatures, Opt_WarnHiShadows, Opt_WarnOrphans, Opt_WarnUnusedDoBind, Opt_WarnTrustworthySafe, Opt_WarnUntickedPromotedConstructors, Opt_WarnMissingPatternSynonymSignatures, Opt_WarnRedundantConstraints ] -- | Things you get with -Weverything, i.e. *all* known warnings flags minusWeverythingOpts :: [WarningFlag] minusWeverythingOpts = [ toEnum 0 .. ] -- | Things you get with -Wcompat. -- -- This is intended to group together warnings that will be enabled by default -- at some point in the future, so that library authors eager to make their -- code future compatible to fix issues before they even generate warnings. minusWcompatOpts :: [WarningFlag] minusWcompatOpts = [ Opt_WarnMissingMonadFailInstances , Opt_WarnSemigroup , Opt_WarnNonCanonicalMonoidInstances ] enableUnusedBinds :: DynP () enableUnusedBinds = mapM_ setWarningFlag unusedBindsFlags disableUnusedBinds :: DynP () disableUnusedBinds = mapM_ unSetWarningFlag unusedBindsFlags -- Things you get with -Wunused-binds unusedBindsFlags :: [WarningFlag] unusedBindsFlags = [ Opt_WarnUnusedTopBinds , Opt_WarnUnusedLocalBinds , Opt_WarnUnusedPatternBinds ] enableGlasgowExts :: DynP () enableGlasgowExts = do setGeneralFlag Opt_PrintExplicitForalls mapM_ setExtensionFlag glasgowExtsFlags disableGlasgowExts :: DynP () disableGlasgowExts = do unSetGeneralFlag Opt_PrintExplicitForalls mapM_ unSetExtensionFlag glasgowExtsFlags glasgowExtsFlags :: [LangExt.Extension] glasgowExtsFlags = [ LangExt.ConstrainedClassMethods , LangExt.DeriveDataTypeable , LangExt.DeriveFoldable , LangExt.DeriveFunctor , LangExt.DeriveGeneric , LangExt.DeriveTraversable , LangExt.EmptyDataDecls , LangExt.ExistentialQuantification , LangExt.ExplicitNamespaces , LangExt.FlexibleContexts , LangExt.FlexibleInstances , LangExt.ForeignFunctionInterface , LangExt.FunctionalDependencies , LangExt.GeneralizedNewtypeDeriving , LangExt.ImplicitParams , LangExt.KindSignatures , LangExt.LiberalTypeSynonyms , LangExt.MagicHash , LangExt.MultiParamTypeClasses , LangExt.ParallelListComp , LangExt.PatternGuards , LangExt.PostfixOperators , LangExt.RankNTypes , LangExt.RecursiveDo , LangExt.ScopedTypeVariables , LangExt.StandaloneDeriving , LangExt.TypeOperators , LangExt.TypeSynonymInstances , LangExt.UnboxedTuples , LangExt.UnicodeSyntax , LangExt.UnliftedFFITypes ] foreign import ccall unsafe "rts_isProfiled" rtsIsProfiledIO :: IO CInt -- | Was the runtime system built with profiling enabled? rtsIsProfiled :: Bool rtsIsProfiled = unsafeDupablePerformIO rtsIsProfiledIO /= 0 #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 () setOverlappingInsts :: TurnOnFlag -> DynP () setOverlappingInsts False = return () setOverlappingInsts True = do l <- getCurLoc upd (\d -> d { overlapInstLoc = l }) setIncoherentInsts :: TurnOnFlag -> DynP () setIncoherentInsts False = return () setIncoherentInsts True = do l <- getCurLoc upd (\d -> d { incoherentOnLoc = l }) checkTemplateHaskellOk :: TurnOnFlag -> DynP () #ifdef GHCI checkTemplateHaskellOk _turn_on = 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)) intSuffixM :: (Int -> DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags) intSuffixM fn = IntSuffix (\n -> updM (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)) 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 = foldr setGeneralFlag' dflags1 (wayGeneralFlags platform w) dflags3 = foldr unSetGeneralFlag' dflags2 (wayUnsetGeneralFlags platform w) in dflags3 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 = foldr ($) (gopt_set dflags f) deps where deps = [ if turn_on then setGeneralFlag' d else unSetGeneralFlag' d | (f', turn_on, d) <- impliedGFlags, f' == f ] -- When you set f, set the ones it implies -- NB: use setGeneralFlag recursively, in case the implied flags -- implies further flags unSetGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags unSetGeneralFlag' f dflags = foldr ($) (gopt_unset dflags f) deps where deps = [ if turn_on then setGeneralFlag' d else unSetGeneralFlag' d | (f', turn_on, d) <- impliedOffGFlags, f' == f ] -- In general, when you un-set f, we don't un-set the things it implies. -- There are however some exceptions, e.g., -fno-strictness implies -- -fno-worker-wrapper. -- -- NB: use unSetGeneralFlag' recursively, in case the implied off flags -- imply further flags. -------------------------- setWarningFlag, unSetWarningFlag :: WarningFlag -> DynP () setWarningFlag f = upd (\dfs -> wopt_set dfs f) unSetWarningFlag f = upd (\dfs -> wopt_unset dfs f) -------------------------- setExtensionFlag, unSetExtensionFlag :: LangExt.Extension -> DynP () setExtensionFlag f = upd (setExtensionFlag' f) unSetExtensionFlag f = upd (unSetExtensionFlag' f) setExtensionFlag', unSetExtensionFlag' :: LangExt.Extension -> 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) <- impliedXFlags, 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 = setDumpFlag' Opt_D_verbose_core2core setVerbosity :: Maybe Int -> DynP () setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 }) setDebugLevel :: Maybe Int -> DynP () setDebugLevel mb_n = upd (\dfs -> dfs{ debugLevel = mb_n `orElse` 2 }) 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 [] } parseModuleName :: ReadP ModuleName parseModuleName = fmap mkModuleName $ munch1 (\c -> isAlphaNum c || c `elem` "_.") parsePackageFlag :: String -- the flag -> (String -> PackageArg) -- type of argument -> String -- string to parse -> PackageFlag parsePackageFlag flag constr str = case filter ((=="").snd) (readP_to_S parse str) of [(r, "")] -> r _ -> throwGhcException $ CmdLineError ("Can't parse package flag: " ++ str) where doc = flag ++ " " ++ str parse = do pkg <- tok $ munch1 (\c -> isAlphaNum c || c `elem` ":-_.") let mk_expose = ExposePackage doc (constr pkg) ( do _ <- tok $ string "with" fmap (mk_expose . ModRenaming True) parseRns <++ fmap (mk_expose . ModRenaming False) parseRns <++ return (mk_expose (ModRenaming True []))) parseRns = do _ <- tok $ R.char '(' rns <- tok $ sepBy parseItem (tok $ R.char ',') _ <- tok $ R.char ')' return rns parseItem = do orig <- tok $ parseModuleName (do _ <- tok $ string "as" new <- tok $ parseModuleName return (orig, new) +++ return (orig, orig)) tok m = m >>= \x -> skipSpaces >> return x exposePackage, exposePackageId, hidePackage, exposePluginPackage, exposePluginPackageId, ignorePackage, trustPackage, distrustPackage :: String -> DynP () exposePackage p = upd (exposePackage' p) exposePackageId p = upd (\s -> s{ packageFlags = parsePackageFlag "-package-id" UnitIdArg p : packageFlags s }) exposePluginPackage p = upd (\s -> s{ pluginPackageFlags = parsePackageFlag "-plugin-package" PackageArg p : pluginPackageFlags s }) exposePluginPackageId p = upd (\s -> s{ pluginPackageFlags = parsePackageFlag "-plugin-package-id" UnitIdArg p : pluginPackageFlags s }) hidePackage p = upd (\s -> s{ packageFlags = HidePackage p : packageFlags s }) ignorePackage p = upd (\s -> s{ ignorePackageFlags = IgnorePackage p : ignorePackageFlags s }) trustPackage p = exposePackage p >> -- both trust and distrust also expose a package upd (\s -> s{ trustFlags = TrustPackage p : trustFlags s }) distrustPackage p = exposePackage p >> upd (\s -> s{ trustFlags = DistrustPackage p : trustFlags s }) exposePackage' :: String -> DynFlags -> DynFlags exposePackage' p dflags = dflags { packageFlags = parsePackageFlag "-package" PackageArg p : packageFlags dflags } setUnitId :: String -> DynFlags -> DynFlags setUnitId p s = s{ thisPackage = stringToUnitId p } -- ----------------------------------------------------------------------------- -- | Find the package environment (if one exists) -- -- We interpret the package environment as a set of package flags; to be -- specific, if we find a package environment file like -- -- > clear-package-db -- > global-package-db -- > package-db blah/package.conf.d -- > package-id id1 -- > package-id id2 -- -- we interpret this as -- -- > [ -hide-all-packages -- > , -clear-package-db -- > , -global-package-db -- > , -package-db blah/package.conf.d -- > , -package-id id1 -- > , -package-id id2 -- > ] -- -- There's also an older syntax alias for package-id, which is just an -- unadorned package id -- -- > id1 -- > id2 -- interpretPackageEnv :: DynFlags -> IO DynFlags interpretPackageEnv dflags = do mPkgEnv <- runMaybeT $ msum $ [ getCmdLineArg >>= \env -> msum [ probeEnvFile env , probeEnvName env , cmdLineError env ] , getEnvVar >>= \env -> msum [ probeEnvFile env , probeEnvName env , envError env ] , notIfHideAllPackages >> msum [ findLocalEnvFile >>= probeEnvFile , probeEnvName defaultEnvName ] ] case mPkgEnv of Nothing -> -- No environment found. Leave DynFlags unchanged. return dflags Just envfile -> do content <- readFile envfile let setFlags :: DynP () setFlags = do setGeneralFlag Opt_HideAllPackages parseEnvFile envfile content (_, dflags') = runCmdLine (runEwM setFlags) dflags return dflags' where -- Loading environments (by name or by location) namedEnvPath :: String -> MaybeT IO FilePath namedEnvPath name = do appdir <- versionedAppDir dflags return $ appdir </> "environments" </> name probeEnvName :: String -> MaybeT IO FilePath probeEnvName name = probeEnvFile =<< namedEnvPath name probeEnvFile :: FilePath -> MaybeT IO FilePath probeEnvFile path = do guard =<< liftMaybeT (doesFileExist path) return path parseEnvFile :: FilePath -> String -> DynP () parseEnvFile envfile = mapM_ parseEntry . lines where parseEntry str = case words str of ["package-db", db] -> addPkgConfRef (PkgConfFile (envdir </> db)) -- relative package dbs are interpreted relative to the env file where envdir = takeDirectory envfile ["clear-package-db"] -> clearPkgConf ["global-package-db"] -> addPkgConfRef GlobalPkgConf ["user-package-db"] -> addPkgConfRef UserPkgConf ["package-id", pkgid] -> exposePackageId pkgid -- and the original syntax introduced in 7.10: [pkgid] -> exposePackageId pkgid [] -> return () _ -> throwGhcException $ CmdLineError $ "Can't parse environment file entry: " ++ envfile ++ ": " ++ str -- Various ways to define which environment to use getCmdLineArg :: MaybeT IO String getCmdLineArg = MaybeT $ return $ packageEnv dflags getEnvVar :: MaybeT IO String getEnvVar = do mvar <- liftMaybeT $ try $ getEnv "GHC_ENVIRONMENT" case mvar of Right var -> return var Left err -> if isDoesNotExistError err then mzero else liftMaybeT $ throwIO err notIfHideAllPackages :: MaybeT IO () notIfHideAllPackages = guard (not (gopt Opt_HideAllPackages dflags)) defaultEnvName :: String defaultEnvName = "default" -- e.g. .ghc.environment.x86_64-linux-7.6.3 localEnvFileName :: FilePath localEnvFileName = ".ghc.environment" <.> versionedFilePath dflags -- Search for an env file, starting in the current dir and looking upwards. -- Fail if we get to the users home dir or the filesystem root. That is, -- we don't look for an env file in the user's home dir. The user-wide -- env lives in ghc's versionedAppDir/environments/default findLocalEnvFile :: MaybeT IO FilePath findLocalEnvFile = do curdir <- liftMaybeT getCurrentDirectory homedir <- tryMaybeT getHomeDirectory let probe dir | isDrive dir || dir == homedir = mzero probe dir = do let file = dir </> localEnvFileName exists <- liftMaybeT (doesFileExist file) if exists then return file else probe (takeDirectory dir) probe curdir -- Error reporting cmdLineError :: String -> MaybeT IO a cmdLineError env = liftMaybeT . throwGhcExceptionIO . CmdLineError $ "Package environment " ++ show env ++ " not found" envError :: String -> MaybeT IO a envError env = liftMaybeT . throwGhcExceptionIO . CmdLineError $ "Package environment " ++ show env ++ " (specified in GHC_ENVIRIONMENT) not found" -- 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 = return (updOptLevel n dflags) checkOptLevel :: Int -> DynFlags -> Either String DynFlags checkOptLevel n dflags | hscTarget dflags == HscInterpreted && n > 0 = Left "-O conflicts with --interactive; -O ignored." | otherwise = Right 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 mainUnitId (mkModuleName main_mod) } | isUpper (head arg) -- The arg looked like "Foo" or "Foo.Bar" = upd $ \d -> d { mainModIs = mkModule mainUnitId (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 || WayDyn `elem` ways 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", projectVersion dflags), ("Project Git commit id", cProjectGitCommitId), ("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), ("RTS expects libdw", showBool cGhcRtsWithLibdw), -- Whether or not we support @-dynamic-too@ ("Support dynamic-too", showBool $ not isWindows), -- Whether or not we support the @-j@ flag with @--make@. ("Support parallel --make", "YES"), -- Whether or not we support "Foo from foo-0.1-XXX:Foo" syntax in -- installed package info. ("Support reexported-modules", "YES"), -- Whether or not we support extended @-package foo (Foo)@ syntax. ("Support thinning and renaming package flags", "YES"), -- If true, we require that the 'id' field in installed package info -- match what is passed to the @-this-unit-id@ flag for modules -- built in it ("Requires unified installed package IDs", "YES"), -- Whether or not we support the @-this-package-key@ flag. Prefer -- "Uses unit IDs" over it. ("Uses package keys", "YES"), -- Whether or not we support the @-this-unit-id@ flag ("Uses unit IDs", "YES"), -- Whether or not GHC compiles libraries as dynamic by default ("Dynamic by default", showBool $ dYNAMIC_BY_DEFAULT dflags), -- Whether or not GHC was compiled using -dynamic ("GHC Dynamic", showBool dynamicGhc), -- Whether or not GHC was compiled using -prof ("GHC Profiled", showBool rtsIsProfiled), ("Leading underscore", cLeadingUnderscore), ("Debug on", show debugIsOn), ("LibDir", topDir dflags), -- The path of the global package database used by GHC ("Global Package DB", systemPackageConfig dflags) ] where showBool True = "YES" showBool False = "NO" 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) {- ----------------------------------------------------------------------------- Note [DynFlags consistency] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There are a number of number of DynFlags configurations which either do not make sense or lead to unimplemented or buggy codepaths in the compiler. makeDynFlagsConsistent is responsible for verifying the validity of a set of DynFlags, fixing any issues, and reporting them back to the caller. GHCi and -O --------------- When using optimization, the compiler can introduce several things (such as unboxed tuples) into the intermediate code, which GHCi later chokes on since the bytecode interpreter can't handle this (and while this is arguably a bug these aren't handled, there are no plans to fix it.) While the driver pipeline always checks for this particular erroneous combination when parsing flags, we also need to check when we update the flags; this is because API clients may parse flags but update the DynFlags afterwords, before finally running code inside a session (see T10052 and #10052). -} -- | Resolve any internal inconsistencies in a set of 'DynFlags'. -- Returns the consistent 'DynFlags' as well as a list of warnings -- to report to the user. makeDynFlagsConsistent :: DynFlags -> (DynFlags, [Located String]) -- 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 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 | gopt Opt_Hpc dflags && hscTarget dflags == HscInterpreted = let dflags' = gopt_unset dflags Opt_Hpc warn = "Hpc can't be used with byte-code interpreter. Ignoring -fhpc." 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)) && (gopt Opt_PIC dflags || WayDyn `elem` ways 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" | Left err <- checkOptLevel (optLevel dflags) dflags = loop (updOptLevel 0 dflags) err | LinkInMemory <- ghcLink dflags , not (gopt Opt_ExternalInterpreter dflags) , rtsIsProfiled , isObjectTarget (hscTarget dflags) , WayProf `notElem` ways dflags = loop dflags{ways = WayProf : ways dflags} "Enabling -prof, because -fobject-code is enabled and GHCi is profiled" | 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, or this -- panic! 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. data SseVersion = SSE1 | SSE2 | SSE3 | SSE4 | SSE42 deriving (Eq, Ord) isSseEnabled :: DynFlags -> Bool isSseEnabled dflags = case platformArch (targetPlatform dflags) of ArchX86_64 -> True ArchX86 -> sseVersion dflags >= Just SSE1 _ -> 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 SSE2 _ -> False isSse4_2Enabled :: DynFlags -> Bool isSse4_2Enabled dflags = sseVersion dflags >= Just SSE42 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] | AixLD [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 ()
mcschroeder/ghc
compiler/main/DynFlags.hs
bsd-3-clause
208,853
0
37
55,774
37,565
20,590
16,975
-1
-1
{-# OPTIONS -Wall -Werror #-} -- #hide module Data.Time.LocalTime.TimeOfDay ( -- * Time of day TimeOfDay(..),midnight,midday, utcToLocalTimeOfDay,localToUTCTimeOfDay, timeToTimeOfDay,timeOfDayToTime, dayFractionToTimeOfDay,timeOfDayToDayFraction ) where import Data.Time.LocalTime.TimeZone import Data.Time.Calendar.Private import Data.Time.Clock import Data.Fixed -- | Time of day as represented in hour, minute and second (with picoseconds), typically used to express local time of day. data TimeOfDay = TimeOfDay { -- | range 0 - 23 todHour :: Int, -- | range 0 - 59 todMin :: Int, -- | Note that 0 <= todSec < 61, accomodating leap seconds. -- Any local minute may have a leap second, since leap seconds happen in all zones simultaneously todSec :: Pico } deriving (Eq,Ord) -- | Hour zero midnight :: TimeOfDay midnight = TimeOfDay 0 0 0 -- | Hour twelve midday :: TimeOfDay midday = TimeOfDay 12 0 0 instance Show TimeOfDay where show (TimeOfDay h m s) = (show2 h) ++ ":" ++ (show2 m) ++ ":" ++ (show2Fixed s) -- | Convert a ToD in UTC to a ToD in some timezone, together with a day adjustment. utcToLocalTimeOfDay :: TimeZone -> TimeOfDay -> (Integer,TimeOfDay) utcToLocalTimeOfDay zone (TimeOfDay h m s) = (fromIntegral (div h' 24),TimeOfDay (mod h' 24) (mod m' 60) s) where m' = m + timeZoneMinutes zone h' = h + (div m' 60) -- | Convert a ToD in some timezone to a ToD in UTC, together with a day adjustment. localToUTCTimeOfDay :: TimeZone -> TimeOfDay -> (Integer,TimeOfDay) localToUTCTimeOfDay zone = utcToLocalTimeOfDay (minutesToTimeZone (negate (timeZoneMinutes zone))) posixDayLength :: DiffTime posixDayLength = fromInteger 86400 -- | Get a TimeOfDay given a time since midnight. -- Time more than 24h will be converted to leap-seconds. timeToTimeOfDay :: DiffTime -> TimeOfDay timeToTimeOfDay dt | dt >= posixDayLength = TimeOfDay 23 59 (60 + (realToFrac (dt - posixDayLength))) timeToTimeOfDay dt = TimeOfDay (fromInteger h) (fromInteger m) s where s' = realToFrac dt s = mod' s' 60 m' = div' s' 60 m = mod' m' 60 h = div' m' 60 -- | Find out how much time since midnight a given TimeOfDay is. timeOfDayToTime :: TimeOfDay -> DiffTime timeOfDayToTime (TimeOfDay h m s) = ((fromIntegral h) * 60 + (fromIntegral m)) * 60 + (realToFrac s) -- | Get a TimeOfDay given the fraction of a day since midnight. dayFractionToTimeOfDay :: Rational -> TimeOfDay dayFractionToTimeOfDay df = timeToTimeOfDay (realToFrac (df * 86400)) -- | Get the fraction of a day since midnight given a TimeOfDay. timeOfDayToDayFraction :: TimeOfDay -> Rational timeOfDayToDayFraction tod = realToFrac (timeOfDayToTime tod / posixDayLength)
FranklinChen/hugs98-plus-Sep2006
packages/time/Data/Time/LocalTime/TimeOfDay.hs
bsd-3-clause
2,674
14
12
461
658
359
299
44
1
{-# LANGUAGE QuasiQuotes #-} import LiquidHaskell bar = 0 [lq| assume (Prelude.++) :: [a] -> [a] -> [a] |]
spinda/liquidhaskell
tests/gsoc15/unknown/pos/Foo.hs
bsd-3-clause
114
0
4
26
17
11
6
4
1
{-# LANGUAGE CPP, RankNTypes, PolyKinds, DataKinds, TypeOperators, TypeFamilies, FlexibleContexts, UndecidableInstances, GADTs, TypeApplications #-} {-# OPTIONS_GHC -Wno-orphans #-} #if __GLASGOW_HASKELL__ < 806 {-# LANGUAGE TypeInType #-} #endif #if __GLASGOW_HASKELL__ >= 810 {-# LANGUAGE StandaloneKindSignatures #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Data.Singletons.Decide -- Copyright : (C) 2013 Richard Eisenberg -- License : BSD-style (see LICENSE) -- Maintainer : Ryan Scott -- Stability : experimental -- Portability : non-portable -- -- Defines the class 'SDecide', allowing for decidable equality over singletons. -- ---------------------------------------------------------------------------- module Data.Singletons.Decide ( -- * The SDecide class SDecide(..), -- * Supporting definitions (:~:)(..), Void, Refuted, Decision(..), decideEquality, decideCoercion ) where import Data.Kind import Data.Singletons import Data.Type.Coercion import Data.Type.Equality import Data.Void ---------------------------------------------------------------------- ---- SDecide --------------------------------------------------------- ---------------------------------------------------------------------- -- | Because we can never create a value of type 'Void', a function that type-checks -- at @a -> Void@ shows that objects of type @a@ can never exist. Thus, we say that -- @a@ is 'Refuted' #if __GLASGOW_HASKELL__ >= 810 type Refuted :: Type -> Type #endif type Refuted a = (a -> Void) -- | A 'Decision' about a type @a@ is either a proof of existence or a proof that @a@ -- cannot exist. #if __GLASGOW_HASKELL__ >= 810 type Decision :: Type -> Type #endif data Decision a = Proved a -- ^ Witness for @a@ | Disproved (Refuted a) -- ^ Proof that no @a@ exists -- | Members of the 'SDecide' "kind" class support decidable equality. Instances -- of this class are generated alongside singleton definitions for datatypes that -- derive an 'Eq' instance. #if __GLASGOW_HASKELL__ >= 810 type SDecide :: Type -> Constraint #endif class SDecide k where -- | Compute a proof or disproof of equality, given two singletons. (%~) :: forall (a :: k) (b :: k). Sing a -> Sing b -> Decision (a :~: b) infix 4 %~ -- | A suitable default implementation for 'testEquality' that leverages -- 'SDecide'. decideEquality :: forall k (a :: k) (b :: k). SDecide k => Sing a -> Sing b -> Maybe (a :~: b) decideEquality a b = case a %~ b of Proved Refl -> Just Refl Disproved _ -> Nothing instance SDecide k => TestEquality (WrappedSing :: k -> Type) where testEquality (WrapSing s1) (WrapSing s2) = decideEquality s1 s2 -- | A suitable default implementation for 'testCoercion' that leverages -- 'SDecide'. decideCoercion :: forall k (a :: k) (b :: k). SDecide k => Sing a -> Sing b -> Maybe (Coercion a b) decideCoercion a b = case a %~ b of Proved Refl -> Just Coercion Disproved _ -> Nothing instance SDecide k => TestCoercion (WrappedSing :: k -> Type) where testCoercion (WrapSing s1) (WrapSing s2) = decideCoercion s1 s2
goldfirere/singletons
singletons/src/Data/Singletons/Decide.hs
bsd-3-clause
3,234
2
12
616
542
316
226
36
2
{-# LANGUAGE OverloadedStrings, FlexibleContexts, PackageImports #-} import Control.Applicative import Control.Arrow import Control.Monad import "monads-tf" Control.Monad.State import "monads-tf" Control.Monad.Error import Control.Monad.Trans.Control import Control.Concurrent hiding (yield) import Control.Concurrent.STM import Data.Pipe import Data.Pipe.IO (debug) import Data.Pipe.ByteString import Data.Pipe.TChan import Data.Char import Data.UUID import System.Random import Network import Network.Sasl import Network.XMPiPe.Core.C2S.Server import Network.PeyoTLS.ReadFile import Network.PeyoTLS.TChan.Server import "crypto-random" Crypto.Random import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC import qualified Network.Sasl.ScramSha1.Server as SS1 import qualified Network.Sasl.DigestMd5.Server as DM5 main :: IO () main = do userlist <- atomically $ newTVar [] soc <- listenOn $ PortNumber 5222 ca <- readCertificateStore ["certs/cacert.sample_pem"] k <- readKey "certs/localhost.sample_key" c <- readCertificateChain ["certs/localhost.sample_crt"] g0 <- cprgCreate <$> createEntropyPool :: IO SystemRNG (`evalStateT` g0) . forever $ lift (accept soc) >>= \(h, _, _) -> liftBaseDiscard forkIO $ do g <- StateT $ return . cprgFork ch <- lift $ atomically newTChan us <- map toASCIIBytes . randoms <$> lift getStdGen _us' <- (`execStateT` us) . runPipe $ fromHandle h =$= starttls "localhost" =$= toHandle h (Just cn, (inp, otp)) <- lift $ open h ["TLS_RSA_WITH_AES_128_CBC_SHA"] [(k, c)] (Just ca) g lift . print $ cn "Yoshikuni" lift . print $ cn "Yoshio" let ck nm = cn (capitalize nm) || nm == "yoshio" (Just ns, st) <- (`runStateT` initXSt) . runPipe $ do fromTChan inp =$= debug =$= sasl "localhost" (retrieves ck) =$= toTChan otp fromTChan inp =$= bind "localhost" [] =@= toTChan otp let u = user st; sl = selector userlist lift . atomically $ modifyTVar userlist ((u, ch) :) void . liftBaseDiscard forkIO . runPipe_ $ fromTChan ch =$= output =$= toTChan otp lift . runPipe_ $ fromTChan inp =$= debug =$= input ns =$= select u =$= toTChansM sl capitalize :: String -> String capitalize (c : cs) = toUpper c : cs capitalize "" = "" initXSt :: XSt initXSt = XSt { user = Jid "" "localhost" Nothing, rands = repeat "00DEADBEEF00", sSt = [ ("realm", "localhost"), ("qop", "auth"), ("charset", "utf-8"), ("algorithm", "md5-sess") ] } type Pairs a = [(a, a)] data XSt = XSt { user :: Jid, rands :: [BS.ByteString], sSt :: Pairs BS.ByteString } instance XmppState XSt where getXmppState xs = (user xs, rands xs) putXmppState (usr, rl) xs = xs { user = usr, rands = rl } instance SaslState XSt where getSaslState XSt { user = Jid n _ _, rands = nnc : _, sSt = ss } = ("username", n) : ("nonce", nnc) : ("snonce", nnc) : ss getSaslState _ = error "XSt.getSaslState: null random list" putSaslState ss xs@XSt { user = Jid _ d r, rands = _ : rs } = xs { user = Jid n d r, rands = rs, sSt = ss } where Just n = lookup "username" ss putSaslState _ _ = error "XSt.getSaslState: null random list" selector :: TVar [(Jid, TChan Mpi)] -> IO [(Jid -> Bool, TChan Mpi)] selector ul = map (first eq) <$> atomically (readTVar ul) where eq (Jid u d _) (Jid v e Nothing) = u == v && d == e eq j k = j == k select :: Monad m => Jid -> Pipe Mpi (Jid, Mpi) m () select f = (await >>=) . maybe (return ()) $ \mpi -> case mpi of End -> yield (f, End) Message tgs@Tags { tagTo = Just to } b -> yield (to, Message tgs { tagFrom = Just f } b) >> select f Iq tgs@Tags { tagTo = Just to } b -> yield (to, Iq tgs { tagFrom = Just f } b) >> select f _ -> select f retrieves :: (MonadError m, SaslError (ErrorType m)) => (String -> Bool) -> [Retrieve m] retrieves ck = [ RTScramSha1 retrieveSS1, RTDigestMd5 retrieveDM5, RTExternal $ retrieveExternal ck] retrieveSS1 :: (MonadError m, SaslError (ErrorType m)) => BS.ByteString -> m (BS.ByteString, BS.ByteString, BS.ByteString, Int) retrieveSS1 "yoshikuni" = return (slt, stk, svk, i) where slt = "pepper"; i = 4492; (stk, svk) = SS1.salt "password" slt i retrieveSS1 "yoshio" = return (slt, stk, svk, i) where slt = "sugar"; i = 4492; (stk, svk) = SS1.salt "password" slt i retrieveSS1 _ = throwError $ fromSaslError NotAuthorized "bad" retrieveDM5 :: (MonadError m, SaslError (ErrorType m)) => BS.ByteString -> m BS.ByteString retrieveDM5 "yoshikuni" = return $ DM5.mkStored "yoshikuni" "localhost" "password" retrieveDM5 "yoshio" = return $ DM5.mkStored "yoshio" "localhost" "password" retrieveDM5 _ = throwError $ fromSaslError NotAuthorized "auth failure" retrieveExternal :: (MonadError m, SaslError (ErrorType m)) => (String -> Bool) -> BS.ByteString -> m () retrieveExternal ck nm = if ck $ BSC.unpack nm then return () else throwError $ fromSaslError NotAuthorized "auth failure"
YoshikuniJujo/forest
subprojects/xml-push/try/xmppServerTls.hs
bsd-3-clause
4,859
34
20
878
1,955
1,036
919
111
4
module Main where import Criterion.Main import Control.Applicative import Control.Monad.IO.Class (liftIO) import Data.Vector (Vector) import qualified Data.Vector as V import NoteScript import Prosper hiding (Money) import Prosper.MarketDataUser import Prosper.Monad withMDUser :: (User -> Prosper a) -> Prosper a withMDUser f = mdUser <$> getMarketDataUser >>= f principalOnActive :: Vector Note -> Money principalOnActive = V.sum . V.map principalBalance vectorBench :: Prosper Money vectorBench = withMDUser $ \n -> liftIO $ do ns <- notes n return (principalOnActive ns) main :: IO () main = do ps <- initializeProsper "prosper.cfg" let runBench = nfIO . runProsper ps defaultMain [ bgroup "Principal on Active Notes" [ bench "Vectors" (runBench vectorBench) ] ]
WraithM/notescript
bench/RunBench.hs
bsd-3-clause
952
0
13
294
249
131
118
25
1
{-# OPTIONS_GHC -Wall #-} ----------------------------------------------------------------------------- -- | -- Module : Main -- Copyright : (c) Masahiro Sakai 2007-2014 -- License : BSD3-style (see LICENSE) -- -- Maintainer: [email protected] -- Stability : experimental -- Portability : non-portable module Main where import Control.Monad import Haste import Report main :: IO () main = do withElems ["button-translate-input", "button-translate-sample", "input", "output", "sample"] $ \[button1, button2, input, output, sample] -> do let update s = do clearChildren output e <- newTextElem (report s) addChild e output _ <- onEvent input OnKeyPress $ \c -> do when (c == fromEnum '\r' || c == fromEnum '\n') $ do update =<< getProp input "value" _ <- button1 `onEvent` OnClick $ \_ _ -> do update =<< getProp input "value" _ <- button2 `onEvent` OnClick $ \_ _ -> do update =<< getProp sample "value" return ()
msakai/ptq
haste/ptq.hs
lgpl-2.1
1,024
0
22
243
271
140
131
20
1
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE TemplateHaskell #-} -- | Native Haskell value construction from K3 literals. module Language.K3.Runtime.Literal where import Control.Applicative ( (<$>), (<*>) ) import Control.Concurrent.MVar import Control.Monad.IO.Class import Data.Word (Word8) import Language.K3.Core.Annotation import Language.K3.Core.Common import Language.K3.Core.Literal import Language.K3.Runtime.Engine bool :: K3 Literal -> EngineM a Bool bool (tag -> LBool b) = return b bool _ = throwEngineError $ EngineError "Invalid boolean literal" byte :: K3 Literal -> EngineM a Word8 byte (tag -> LByte b) = return b byte _ = throwEngineError $ EngineError "Invalid byte literal" int :: K3 Literal -> EngineM a Int int (tag -> LInt i) = return i int _ = throwEngineError $ EngineError "Invalid int literal" real :: K3 Literal -> EngineM a Double real (tag -> LReal r) = return r real _ = throwEngineError $ EngineError "Invalid real literal" string :: K3 Literal -> EngineM a String string (tag -> LString s) = return s string _ = throwEngineError $ EngineError "Invalid string literal" none :: K3 Literal -> EngineM a (Maybe b) none (tag -> LNone _) = return Nothing none _ = throwEngineError $ EngineError "Invalid option literal" some :: (K3 Literal -> EngineM a b) -> K3 Literal -> EngineM a (Maybe b) some f (details -> (LSome, [x], _)) = f x >>= return . Just some _ _ = throwEngineError $ EngineError "Invalid option literal" option :: (K3 Literal -> EngineM a b) -> K3 Literal -> EngineM a (Maybe b) option _ l@(tag -> LNone _) = none l option someF l@(tag -> LSome) = some someF l option _ _ = throwEngineError $ EngineError "Invalid option literal" indirection :: (K3 Literal -> EngineM a b) -> K3 Literal -> EngineM a (MVar b) indirection f (details -> (LIndirect, [x], _)) = f x >>= liftIO . newMVar indirection _ _ = throwEngineError $ EngineError "Invalid indirection literal" tuple :: ([K3 Literal] -> EngineM a b) -> K3 Literal -> EngineM a b tuple f (details -> (LTuple, ch, _)) = f ch tuple _ _ = throwEngineError $ EngineError "Invalid tuple literal" record :: ([(Identifier, K3 Literal)] -> EngineM a b) -> K3 Literal -> EngineM a b record f (details -> (LRecord ids, ch, _)) = f $ zip ids ch record _ _ = throwEngineError $ EngineError "Invalid record literal" -- TODO: native collection construction empty :: (() -> EngineM a b) -> K3 Literal -> EngineM a b empty f (details -> (LEmpty _, [], _)) = f () empty _ _ = throwEngineError $ EngineError "Invalid empty collection literal" -- TODO: native collection construction collection :: ([K3 Literal] -> EngineM a b) -> K3 Literal -> EngineM a b collection f (details -> (LCollection _, elems, _)) = f elems collection _ _ = throwEngineError $ EngineError "Invalid collection literal" anyCollection :: ([K3 Literal] -> EngineM a b) -> K3 Literal -> EngineM a b anyCollection f (tag -> LEmpty _) = f [] anyCollection f (details -> (LCollection _, elems, _)) = f elems anyCollection _ _ = throwEngineError $ EngineError "Invalid collection literal" address :: K3 Literal -> EngineM a Address address (details -> (LAddress, [h,p], _)) = Address <$> ((,) <$> string h <*> int p) address _ = throwEngineError $ EngineError "Invalid address literal"
DaMSL/K3
src/Language/K3/Runtime/Literal.hs
apache-2.0
3,248
0
10
571
1,273
648
625
58
1
{-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE MultiParamTypeClasses #-} #if __GLASGOW_HASKELL__ < 710 {-# LANGUAGE OverlappingInstances #-} #define OVERLAPPING_PRAGMA #else #define OVERLAPPING_PRAGMA {-# OVERLAPPING #-} #endif #ifdef TRUSTWORTHY {-# LANGUAGE Trustworthy #-} -- template-haskell #endif #ifndef MIN_VERSION_template_haskell #define MIN_VERSION_template_haskell(x,y,z) 1 #endif #ifndef MIN_VERSION_free #define MIN_VERSION_free(x,y,z) 1 #endif ------------------------------------------------------------------------------- -- | -- Module : Control.Lens.Plated -- Copyright : (C) 2012-15 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <[email protected]> -- Stability : provisional -- Portability : Rank2Types -- -- The name \"plate\" stems originally from \"boilerplate\", which was the term -- used by the \"Scrap Your Boilerplate\" papers, and later inherited by Neil -- Mitchell's \"Uniplate\". -- -- <http://community.haskell.org/~ndm/uniplate/> -- -- The combinators in here are designed to be compatible with and subsume the -- @uniplate@ API with the notion of a 'Traversal' replacing -- a 'Data.Data.Lens.uniplate' or 'Data.Data.Lens.biplate'. -- -- By implementing these combinators in terms of 'plate' instead of -- 'Data.Data.Lens.uniplate' additional type safety is gained, as the user is -- no longer responsible for maintaining invariants such as the number of -- children they received. -- -- Note: The @Biplate@ is /deliberately/ excluded from the API here, with the -- intention that you replace them with either explicit traversals, or by using the -- @On@ variants of the combinators below with 'Data.Data.Lens.biplate' from -- @Data.Data.Lens@. As a design, it forced the user into too many situations where -- they had to choose between correctness and ease of use, and it was brittle in the -- face of competing imports. -- -- The sensible use of these combinators makes some simple assumptions. Notably, any -- of the @On@ combinators are expecting a 'Traversal', 'Setter' or 'Fold' -- to play the role of the 'Data.Data.Lens.biplate' combinator, and so when the -- types of the contents and the container match, they should be the 'id' 'Traversal', -- 'Setter' or 'Fold'. -- -- It is often beneficial to use the combinators in this module with the combinators -- from @Data.Data.Lens@ or @GHC.Generics.Lens@ to make it easier to automatically -- derive definitions for 'plate', or to derive custom traversals. ------------------------------------------------------------------------------- module Control.Lens.Plated ( -- * Uniplate Plated(..) -- * Uniplate Combinators , children , rewrite, rewriteOf, rewriteOn, rewriteOnOf , rewriteM, rewriteMOf, rewriteMOn, rewriteMOnOf , universe, universeOf, universeOn, universeOnOf , cosmos, cosmosOf, cosmosOn, cosmosOnOf , transform, transformOf, transformOn, transformOnOf , transformM, transformMOf, transformMOn, transformMOnOf , contexts, contextsOf, contextsOn, contextsOnOf , holes, holesOn, holesOnOf , para, paraOf , (...), deep -- * Compos -- $compos , composOpFold -- * Parts , parts -- * Generics , gplate , GPlated ) where import Control.Applicative import Control.Comonad.Cofree import qualified Control.Comonad.Trans.Cofree as CoTrans import Control.Lens.Fold import Control.Lens.Getter import Control.Lens.Indexed import Control.Lens.Internal.Context import Control.Lens.Type import Control.Lens.Setter import Control.Lens.Traversal import Control.Monad.Free as Monad import Control.Monad.Free.Church as Church import Control.Monad.Trans.Free as Trans #if !(MIN_VERSION_free(4,6,0)) import Control.MonadPlus.Free as MonadPlus #endif import qualified Language.Haskell.TH as TH import Data.Data import Data.Data.Lens import Data.Monoid import Data.Tree import GHC.Generics #ifdef HLINT {-# ANN module "HLint: ignore Reduce duplication" #-} #endif -- | A 'Plated' type is one where we know how to extract its immediate self-similar children. -- -- /Example 1/: -- -- @ -- import Control.Applicative -- import Control.Lens -- import Control.Lens.Plated -- import Data.Data -- import Data.Data.Lens ('Data.Data.Lens.uniplate') -- @ -- -- @ -- data Expr -- = Val 'Int' -- | Neg Expr -- | Add Expr Expr -- deriving ('Eq','Ord','Show','Read','Data','Typeable') -- @ -- -- @ -- instance 'Plated' Expr where -- 'plate' f (Neg e) = Neg '<$>' f e -- 'plate' f (Add a b) = Add '<$>' f a '<*>' f b -- 'plate' _ a = 'pure' a -- @ -- -- /or/ -- -- @ -- instance 'Plated' Expr where -- 'plate' = 'Data.Data.Lens.uniplate' -- @ -- -- /Example 2/: -- -- @ -- import Control.Applicative -- import Control.Lens -- import Control.Lens.Plated -- import Data.Data -- import Data.Data.Lens ('Data.Data.Lens.uniplate') -- @ -- -- @ -- data Tree a -- = Bin (Tree a) (Tree a) -- | Tip a -- deriving ('Eq','Ord','Show','Read','Data','Typeable') -- @ -- -- @ -- instance 'Plated' (Tree a) where -- 'plate' f (Bin l r) = Bin '<$>' f l '<*>' f r -- 'plate' _ t = 'pure' t -- @ -- -- /or/ -- -- @ -- instance 'Data' a => 'Plated' (Tree a) where -- 'plate' = 'uniplate' -- @ -- -- Note the big distinction between these two implementations. -- -- The former will only treat children directly in this tree as descendents, -- the latter will treat trees contained in the values under the tips also -- as descendants! -- -- When in doubt, pick a 'Traversal' and just use the various @...Of@ combinators -- rather than pollute 'Plated' with orphan instances! -- -- If you want to find something unplated and non-recursive with 'Data.Data.Lens.biplate' -- use the @...OnOf@ variant with 'ignored', though those usecases are much better served -- in most cases by using the existing 'Lens' combinators! e.g. -- -- @ -- 'toListOf' 'biplate' ≡ 'universeOnOf' 'biplate' 'ignored' -- @ -- -- This same ability to explicitly pass the 'Traversal' in question is why there is no -- analogue to uniplate's @Biplate@. -- -- Moreover, since we can allow custom traversals, we implement reasonable defaults for -- polymorphic data types, that only 'Control.Traversable.traverse' into themselves, and /not/ their -- polymorphic arguments. class Plated a where -- | 'Traversal' of the immediate children of this structure. -- -- If you're using GHC 7.2 or newer and your type has a 'Data' instance, -- 'plate' will default to 'uniplate' and you can choose to not override -- it with your own definition. plate :: Traversal' a a #ifndef HLINT default plate :: Data a => Traversal' a a plate = uniplate #endif instance Plated [a] where plate f (x:xs) = (x:) <$> f xs plate _ [] = pure [] instance Traversable f => Plated (Monad.Free f a) where plate f (Monad.Free as) = Monad.Free <$> traverse f as plate _ x = pure x instance (Traversable f, Traversable m) => Plated (Trans.FreeT f m a) where plate f (Trans.FreeT xs) = Trans.FreeT <$> traverse (traverse f) xs #if !(MIN_VERSION_free(4,6,0)) instance Traversable f => Plated (MonadPlus.Free f a) where plate f (MonadPlus.Free as) = MonadPlus.Free <$> traverse f as plate f (MonadPlus.Plus as) = MonadPlus.Plus <$> traverse f as plate _ x = pure x #endif instance Traversable f => Plated (Church.F f a) where plate f = fmap Church.toF . plate (fmap Church.fromF . f . Church.toF) . Church.fromF -- -- This one can't work -- -- instance (Traversable f, Traversable m) => Plated (ChurchT.FT f m a) where -- plate f = fmap ChurchT.toFT . plate (fmap ChurchT.fromFT . f . ChurchT.toFT) . ChurchT.fromFT instance (Traversable f, Traversable w) => Plated (CoTrans.CofreeT f w a) where plate f (CoTrans.CofreeT xs) = CoTrans.CofreeT <$> traverse (traverse f) xs instance Traversable f => Plated (Cofree f a) where plate f (a :< as) = (:<) a <$> traverse f as instance Plated (Tree a) where plate f (Node a as) = Node a <$> traverse f as {- Default uniplate instances -} instance Plated TH.Exp instance Plated TH.Dec instance Plated TH.Con instance Plated TH.Type #if !(MIN_VERSION_template_haskell(2,8,0)) instance Plated TH.Kind -- in 2.8 Kind is an alias for Type #endif instance Plated TH.Stmt instance Plated TH.Pat infixr 9 ... -- | Compose through a plate (...) :: (Applicative f, Plated c) => LensLike f s t c c -> Over p f c c a b -> Over p f s t a b l ... m = l . plate . m {-# INLINE (...) #-} -- | Try to apply a traversal to all transitive descendants of a 'Plated' container, but -- do not recurse through matching descendants. -- -- @ -- 'deep' :: 'Plated' s => 'Fold' s a -> 'Fold' s a -- 'deep' :: 'Plated' s => 'IndexedFold' s a -> 'IndexedFold' s a -- 'deep' :: 'Plated' s => 'Traversal' s s a b -> 'Traversal' s s a b -- 'deep' :: 'Plated' s => 'IndexedTraversal' s s a b -> 'IndexedTraversal' s s a b -- @ deep :: (Conjoined p, Applicative f, Plated s) => Traversing p f s s a b -> Over p f s s a b deep = deepOf plate ------------------------------------------------------------------------------- -- Children ------------------------------------------------------------------------------- -- | Extract the immediate descendants of a 'Plated' container. -- -- @ -- 'children' ≡ 'toListOf' 'plate' -- @ children :: Plated a => a -> [a] children = toListOf plate {-# INLINE children #-} ------------------------------------------------------------------------------- -- Rewriting ------------------------------------------------------------------------------- -- | Rewrite by applying a rule everywhere you can. Ensures that the rule cannot -- be applied anywhere in the result: -- -- @ -- propRewrite r x = 'all' ('Data.Just.isNothing' '.' r) ('universe' ('rewrite' r x)) -- @ -- -- Usually 'transform' is more appropriate, but 'rewrite' can give better -- compositionality. Given two single transformations @f@ and @g@, you can -- construct @\a -> f a `mplus` g a@ which performs both rewrites until a fixed point. rewrite :: Plated a => (a -> Maybe a) -> a -> a rewrite = rewriteOf plate {-# INLINE rewrite #-} -- | Rewrite by applying a rule everywhere you can. Ensures that the rule cannot -- be applied anywhere in the result: -- -- @ -- propRewriteOf l r x = 'all' ('Data.Just.isNothing' '.' r) ('universeOf' l ('rewriteOf' l r x)) -- @ -- -- Usually 'transformOf' is more appropriate, but 'rewriteOf' can give better -- compositionality. Given two single transformations @f@ and @g@, you can -- construct @\a -> f a `mplus` g a@ which performs both rewrites until a fixed point. -- -- @ -- 'rewriteOf' :: 'Control.Lens.Iso.Iso'' a a -> (a -> 'Maybe' a) -> a -> a -- 'rewriteOf' :: 'Lens'' a a -> (a -> 'Maybe' a) -> a -> a -- 'rewriteOf' :: 'Traversal'' a a -> (a -> 'Maybe' a) -> a -> a -- 'rewriteOf' :: 'Setter'' a a -> (a -> 'Maybe' a) -> a -> a -- @ rewriteOf :: ASetter' a a -> (a -> Maybe a) -> a -> a rewriteOf l f = go where go = transformOf l (\x -> maybe x go (f x)) {-# INLINE rewriteOf #-} -- | Rewrite recursively over part of a larger structure. -- -- @ -- 'rewriteOn' :: 'Plated' a => 'Control.Lens.Iso.Iso'' s a -> (a -> 'Maybe' a) -> s -> s -- 'rewriteOn' :: 'Plated' a => 'Lens'' s a -> (a -> 'Maybe' a) -> s -> s -- 'rewriteOn' :: 'Plated' a => 'Traversal'' s a -> (a -> 'Maybe' a) -> s -> s -- 'rewriteOn' :: 'Plated' a => 'ASetter'' s a -> (a -> 'Maybe' a) -> s -> s -- @ rewriteOn :: Plated a => ASetter s t a a -> (a -> Maybe a) -> s -> t rewriteOn b = over b . rewrite {-# INLINE rewriteOn #-} -- | Rewrite recursively over part of a larger structure using a specified 'Setter'. -- -- @ -- 'rewriteOnOf' :: 'Plated' a => 'Control.Lens.Iso.Iso'' s a -> 'Control.Lens.Iso.Iso'' a a -> (a -> 'Maybe' a) -> s -> s -- 'rewriteOnOf' :: 'Plated' a => 'Lens'' s a -> 'Lens'' a a -> (a -> 'Maybe' a) -> s -> s -- 'rewriteOnOf' :: 'Plated' a => 'Traversal'' s a -> 'Traversal'' a a -> (a -> 'Maybe' a) -> s -> s -- 'rewriteOnOf' :: 'Plated' a => 'Setter'' s a -> 'Setter'' a a -> (a -> 'Maybe' a) -> s -> s -- @ rewriteOnOf :: ASetter s t a a -> ASetter' a a -> (a -> Maybe a) -> s -> t rewriteOnOf b l = over b . rewriteOf l {-# INLINE rewriteOnOf #-} -- | Rewrite by applying a monadic rule everywhere you can. Ensures that the rule cannot -- be applied anywhere in the result. rewriteM :: (Monad m, Plated a) => (a -> m (Maybe a)) -> a -> m a rewriteM = rewriteMOf plate {-# INLINE rewriteM #-} -- | Rewrite by applying a monadic rule everywhere you recursing with a user-specified 'Traversal'. -- Ensures that the rule cannot be applied anywhere in the result. rewriteMOf :: Monad m => LensLike' (WrappedMonad m) a a -> (a -> m (Maybe a)) -> a -> m a rewriteMOf l f = go where go = transformMOf l (\x -> f x >>= maybe (return x) go) {-# INLINE rewriteMOf #-} -- | Rewrite by applying a monadic rule everywhere inside of a structure located by a user-specified 'Traversal'. -- Ensures that the rule cannot be applied anywhere in the result. rewriteMOn :: (Monad m, Plated a) => LensLike (WrappedMonad m) s t a a -> (a -> m (Maybe a)) -> s -> m t rewriteMOn b = mapMOf b . rewriteM {-# INLINE rewriteMOn #-} -- | Rewrite by applying a monadic rule everywhere inside of a structure located by a user-specified 'Traversal', -- using a user-specified 'Traversal' for recursion. Ensures that the rule cannot be applied anywhere in the result. rewriteMOnOf :: Monad m => LensLike (WrappedMonad m) s t a a -> LensLike' (WrappedMonad m) a a -> (a -> m (Maybe a)) -> s -> m t rewriteMOnOf b l = mapMOf b . rewriteMOf l {-# INLINE rewriteMOnOf #-} ------------------------------------------------------------------------------- -- Universe ------------------------------------------------------------------------------- -- | Retrieve all of the transitive descendants of a 'Plated' container, including itself. universe :: Plated a => a -> [a] universe = universeOf plate {-# INLINE universe #-} -- | Given a 'Fold' that knows how to locate immediate children, retrieve all of the transitive descendants of a node, including itself. -- -- @ -- 'universeOf' :: 'Fold' a a -> a -> [a] -- @ universeOf :: Getting [a] a a -> a -> [a] universeOf l = go where go a = a : foldMapOf l go a {-# INLINE universeOf #-} -- | Given a 'Fold' that knows how to find 'Plated' parts of a container retrieve them and all of their descendants, recursively. universeOn :: Plated a => Getting [a] s a -> s -> [a] universeOn b = universeOnOf b plate {-# INLINE universeOn #-} -- | Given a 'Fold' that knows how to locate immediate children, retrieve all of the transitive descendants of a node, including itself that lie -- in a region indicated by another 'Fold'. -- -- @ -- 'toListOf' l ≡ 'universeOnOf' l 'ignored' -- @ universeOnOf :: Getting [a] s a -> Getting [a] a a -> s -> [a] universeOnOf b = foldMapOf b . universeOf {-# INLINE universeOnOf #-} -- | Fold over all transitive descendants of a 'Plated' container, including itself. cosmos :: Plated a => Fold a a cosmos = cosmosOf plate {-# INLINE cosmos #-} -- | Given a 'Fold' that knows how to locate immediate children, fold all of the transitive descendants of a node, including itself. -- -- @ -- 'cosmosOf' :: 'Fold' a a -> 'Fold' a a -- @ cosmosOf :: (Applicative f, Contravariant f) => LensLike' f a a -> LensLike' f a a cosmosOf d f s = f s *> d (cosmosOf d f) s {-# INLINE cosmosOf #-} -- | Given a 'Fold' that knows how to find 'Plated' parts of a container fold them and all of their descendants, recursively. -- -- @ -- 'cosmosOn' :: 'Plated' a => 'Fold' s a -> 'Fold' s a -- @ cosmosOn :: (Applicative f, Contravariant f, Plated a) => LensLike' f s a -> LensLike' f s a cosmosOn d = cosmosOnOf d plate {-# INLINE cosmosOn #-} -- | Given a 'Fold' that knows how to locate immediate children, fold all of the transitive descendants of a node, including itself that lie -- in a region indicated by another 'Fold'. -- -- @ -- 'cosmosOnOf' :: 'Fold' s a -> 'Fold' a a -> 'Fold' s a -- @ cosmosOnOf :: (Applicative f, Contravariant f) => LensLike' f s a -> LensLike' f a a -> LensLike' f s a cosmosOnOf d p = d . cosmosOf p {-# INLINE cosmosOnOf #-} ------------------------------------------------------------------------------- -- Transformation ------------------------------------------------------------------------------- -- | Transform every element in the tree, in a bottom-up manner. -- -- For example, replacing negative literals with literals: -- -- @ -- negLits = 'transform' $ \\x -> case x of -- Neg (Lit i) -> Lit ('negate' i) -- _ -> x -- @ transform :: Plated a => (a -> a) -> a -> a transform = transformOf plate {-# INLINE transform #-} -- | Transform every element in the tree in a bottom-up manner over a region indicated by a 'Setter'. -- -- @ -- 'transformOn' :: 'Plated' a => 'Traversal'' s a -> (a -> a) -> s -> s -- 'transformOn' :: 'Plated' a => 'Setter'' s a -> (a -> a) -> s -> s -- @ transformOn :: Plated a => ASetter s t a a -> (a -> a) -> s -> t transformOn b = over b . transform {-# INLINE transformOn #-} -- | Transform every element by recursively applying a given 'Setter' in a bottom-up manner. -- -- @ -- 'transformOf' :: 'Traversal'' a a -> (a -> a) -> a -> a -- 'transformOf' :: 'Setter'' a a -> (a -> a) -> a -> a -- @ transformOf :: ASetter' a a -> (a -> a) -> a -> a transformOf l f = go where go = f . over l go {-# INLINE transformOf #-} -- | Transform every element in a region indicated by a 'Setter' by recursively applying another 'Setter' -- in a bottom-up manner. -- -- @ -- 'transformOnOf' :: 'Setter'' s a -> 'Traversal'' a a -> (a -> a) -> s -> s -- 'transformOnOf' :: 'Setter'' s a -> 'Setter'' a a -> (a -> a) -> s -> s -- @ transformOnOf :: ASetter s t a a -> ASetter' a a -> (a -> a) -> s -> t transformOnOf b l = over b . transformOf l {-# INLINE transformOnOf #-} -- | Transform every element in the tree, in a bottom-up manner, monadically. transformM :: (Monad m, Plated a) => (a -> m a) -> a -> m a transformM = transformMOf plate {-# INLINE transformM #-} -- | Transform every element in the tree in a region indicated by a supplied 'Traversal', in a bottom-up manner, monadically. -- -- @ -- 'transformMOn' :: ('Monad' m, 'Plated' a) => 'Traversal'' s a -> (a -> m a) -> s -> m s -- @ transformMOn :: (Monad m, Plated a) => LensLike (WrappedMonad m) s t a a -> (a -> m a) -> s -> m t transformMOn b = mapMOf b . transformM {-# INLINE transformMOn #-} -- | Transform every element in a tree using a user supplied 'Traversal' in a bottom-up manner with a monadic effect. -- -- @ -- 'transformMOf' :: 'Monad' m => 'Traversal'' a a -> (a -> m a) -> a -> m a -- @ transformMOf :: Monad m => LensLike' (WrappedMonad m) a a -> (a -> m a) -> a -> m a transformMOf l f = go where go t = mapMOf l go t >>= f {-# INLINE transformMOf #-} -- | Transform every element in a tree that lies in a region indicated by a supplied 'Traversal', walking with a user supplied 'Traversal' in -- a bottom-up manner with a monadic effect. -- -- @ -- 'transformMOnOf' :: 'Monad' m => 'Traversal'' s a -> 'Traversal'' a a -> (a -> m a) -> s -> m s -- @ transformMOnOf :: Monad m => LensLike (WrappedMonad m) s t a a -> LensLike' (WrappedMonad m) a a -> (a -> m a) -> s -> m t transformMOnOf b l = mapMOf b . transformMOf l {-# INLINE transformMOnOf #-} ------------------------------------------------------------------------------- -- Holes and Contexts ------------------------------------------------------------------------------- -- | Return a list of all of the editable contexts for every location in the structure, recursively. -- -- @ -- propUniverse x = 'universe' x '==' 'map' 'Control.Comonad.Store.Class.pos' ('contexts' x) -- propId x = 'all' ('==' x) ['Control.Lens.Internal.Context.extract' w | w <- 'contexts' x] -- @ -- -- @ -- 'contexts' ≡ 'contextsOf' 'plate' -- @ contexts :: Plated a => a -> [Context a a a] contexts = contextsOf plate {-# INLINE contexts #-} -- | Return a list of all of the editable contexts for every location in the structure, recursively, using a user-specified 'Traversal' to walk each layer. -- -- @ -- propUniverse l x = 'universeOf' l x '==' 'map' 'Control.Comonad.Store.Class.pos' ('contextsOf' l x) -- propId l x = 'all' ('==' x) ['Control.Lens.Internal.Context.extract' w | w <- 'contextsOf' l x] -- @ -- -- @ -- 'contextsOf' :: 'Traversal'' a a -> a -> ['Context' a a a] -- @ contextsOf :: ATraversal' a a -> a -> [Context a a a] contextsOf l x = sell x : f (map context (holesOf l x)) where f xs = do Context ctx child <- xs Context cont y <- contextsOf l child return $ Context (ctx . cont) y {-# INLINE contextsOf #-} -- | Return a list of all of the editable contexts for every location in the structure in an areas indicated by a user supplied 'Traversal', recursively using 'plate'. -- -- @ -- 'contextsOn' b ≡ 'contextsOnOf' b 'plate' -- @ -- -- @ -- 'contextsOn' :: 'Plated' a => 'Traversal'' s a -> s -> ['Context' a a s] -- @ contextsOn :: Plated a => ATraversal s t a a -> s -> [Context a a t] contextsOn b = contextsOnOf b plate {-# INLINE contextsOn #-} -- | Return a list of all of the editable contexts for every location in the structure in an areas indicated by a user supplied 'Traversal', recursively using -- another user-supplied 'Traversal' to walk each layer. -- -- @ -- 'contextsOnOf' :: 'Traversal'' s a -> 'Traversal'' a a -> s -> ['Context' a a s] -- @ contextsOnOf :: ATraversal s t a a -> ATraversal' a a -> s -> [Context a a t] contextsOnOf b l = f . map context . holesOf b where f xs = do Context ctx child <- xs Context cont y <- contextsOf l child return $ Context (ctx . cont) y {-# INLINE contextsOnOf #-} -- | The one-level version of 'context'. This extracts a list of the immediate children as editable contexts. -- -- Given a context you can use 'Control.Comonad.Store.Class.pos' to see the values, 'Control.Comonad.Store.Class.peek' at what the structure would be like with an edited result, or simply 'Control.Lens.Internal.Context.extract' the original structure. -- -- @ -- propChildren x = 'children' l x '==' 'map' 'Control.Comonad.Store.Class.pos' ('holes' l x) -- propId x = 'all' ('==' x) ['Control.Lens.Internal.Context.extract' w | w <- 'holes' l x] -- @ -- -- @ -- 'holes' = 'holesOf' 'plate' -- @ holes :: Plated a => a -> [Pretext (->) a a a] holes = holesOf plate {-# INLINE holes #-} -- | An alias for 'holesOf', provided for consistency with the other combinators. -- -- @ -- 'holesOn' ≡ 'holesOf' -- @ -- -- @ -- 'holesOn' :: 'Iso'' s a -> s -> ['Pretext' (->) a a s] -- 'holesOn' :: 'Lens'' s a -> s -> ['Pretext' (->) a a s] -- 'holesOn' :: 'Traversal'' s a -> s -> ['Pretext' (->) a a s] -- 'holesOn' :: 'IndexedLens'' i s a -> s -> ['Pretext' ('Control.Lens.Internal.Indexed.Indexed' i) a a s] -- 'holesOn' :: 'IndexedTraversal'' i s a -> s -> ['Pretext' ('Control.Lens.Internal.Indexed.Indexed' i) a a s] -- @ holesOn :: Conjoined p => Optical p (->) (Bazaar p a a) s t a a -> s -> [Pretext p a a t] holesOn = holesOf {-# INLINE holesOn #-} -- | Extract one level of 'holes' from a container in a region specified by one 'Traversal', using another. -- -- @ -- 'holesOnOf' b l ≡ 'holesOf' (b '.' l) -- @ -- -- @ -- 'holesOnOf' :: 'Iso'' s a -> 'Iso'' a a -> s -> ['Pretext' (->) a a s] -- 'holesOnOf' :: 'Lens'' s a -> 'Lens'' a a -> s -> ['Pretext' (->) a a s] -- 'holesOnOf' :: 'Traversal'' s a -> 'Traversal'' a a -> s -> ['Pretext' (->) a a s] -- 'holesOnOf' :: 'Lens'' s a -> 'IndexedLens'' i a a -> s -> ['Pretext' ('Control.Lens.Internal.Indexed.Indexed' i) a a s] -- 'holesOnOf' :: 'Traversal'' s a -> 'IndexedTraversal'' i a a -> s -> ['Pretext' ('Control.Lens.Internal.Indexed.Indexed' i) a a s] -- @ holesOnOf :: Conjoined p => LensLike (Bazaar p r r) s t a b -> Optical p (->) (Bazaar p r r) a b r r -> s -> [Pretext p r r t] holesOnOf b l = holesOf (b . l) {-# INLINE holesOnOf #-} ------------------------------------------------------------------------------- -- Paramorphisms ------------------------------------------------------------------------------- -- | Perform a fold-like computation on each value, technically a paramorphism. -- -- @ -- 'paraOf' :: 'Fold' a a -> (a -> [r] -> r) -> a -> r -- @ paraOf :: Getting (Endo [a]) a a -> (a -> [r] -> r) -> a -> r paraOf l f = go where go a = f a (go <$> toListOf l a) {-# INLINE paraOf #-} -- | Perform a fold-like computation on each value, technically a paramorphism. -- -- @ -- 'para' ≡ 'paraOf' 'plate' -- @ para :: Plated a => (a -> [r] -> r) -> a -> r para = paraOf plate {-# INLINE para #-} ------------------------------------------------------------------------------- -- Compos ------------------------------------------------------------------------------- -- $compos -- -- Provided for compatibility with Björn Bringert's @compos@ library. -- -- Note: Other operations from compos that were inherited by @uniplate@ are /not/ included -- to avoid having even more redundant names for the same operators. For comparison: -- -- @ -- 'composOpMonoid' ≡ 'foldMapOf' 'plate' -- 'composOpMPlus' f ≡ 'msumOf' ('plate' '.' 'to' f) -- 'composOp' ≡ 'descend' ≡ 'over' 'plate' -- 'composOpM' ≡ 'descendM' ≡ 'mapMOf' 'plate' -- 'composOpM_' ≡ 'descendM_' ≡ 'mapMOf_' 'plate' -- @ -- | Fold the immediate children of a 'Plated' container. -- -- @ -- 'composOpFold' z c f = 'foldrOf' 'plate' (c '.' f) z -- @ composOpFold :: Plated a => b -> (b -> b -> b) -> (a -> b) -> a -> b composOpFold z c f = foldrOf plate (c . f) z {-# INLINE composOpFold #-} ------------------------------------------------------------------------------- -- Parts ------------------------------------------------------------------------------- -- | The original @uniplate@ combinator, implemented in terms of 'Plated' as a 'Lens'. -- -- @ -- 'parts' ≡ 'partsOf' 'plate' -- @ -- -- The resulting 'Lens' is safer to use as it ignores 'over-application' and deals gracefully with under-application, -- but it is only a proper 'Lens' if you don't change the list 'length'! parts :: Plated a => Lens' a [a] parts = partsOf plate {-# INLINE parts #-} ------------------------------------------------------------------------------- -- Generics ------------------------------------------------------------------------------- -- | Implement 'plate' operation for a type using its 'Generic' instance. gplate :: (Generic a, GPlated a (Rep a)) => Traversal' a a gplate f x = GHC.Generics.to <$> gplate' f (GHC.Generics.from x) {-# INLINE gplate #-} class GPlated a g where gplate' :: Traversal' (g p) a instance GPlated a f => GPlated a (M1 i c f) where gplate' f (M1 x) = M1 <$> gplate' f x {-# INLINE gplate' #-} instance (GPlated a f, GPlated a g) => GPlated a (f :+: g) where gplate' f (L1 x) = L1 <$> gplate' f x gplate' f (R1 x) = R1 <$> gplate' f x {-# INLINE gplate' #-} instance (GPlated a f, GPlated a g) => GPlated a (f :*: g) where gplate' f (x :*: y) = (:*:) <$> gplate' f x <*> gplate' f y {-# INLINE gplate' #-} instance OVERLAPPING_PRAGMA GPlated a (K1 i a) where gplate' f (K1 x) = K1 <$> f x {-# INLINE gplate' #-} instance GPlated a (K1 i b) where gplate' _ = pure {-# INLINE gplate' #-} instance GPlated a U1 where gplate' _ = pure {-# INLINE gplate' #-} instance GPlated a V1 where gplate' _ v = v `seq` error "GPlated/V1" {-# INLINE gplate' #-}
Gabriel439/lens
src/Control/Lens/Plated.hs
bsd-3-clause
27,699
0
13
5,320
4,254
2,404
1,850
229
1
module ShowIssue where import qualified Github.Issues as Github main = do possibleIssue <- Github.issue "thoughtbot" "paperclip" 549 putStrLn $ either (\e -> "Error: " ++ show e) formatIssue possibleIssue formatIssue issue = (Github.githubOwnerLogin $ Github.issueUser issue) ++ " opened this issue " ++ (show $ Github.fromDate $ Github.issueCreatedAt issue) ++ "\n" ++ (Github.issueState issue) ++ " with " ++ (show $ Github.issueComments issue) ++ " comments" ++ "\n\n" ++ (Github.issueTitle issue)
jwiegley/github
samples/Issues/ShowIssue.hs
bsd-3-clause
570
0
17
140
166
85
81
14
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE DataKinds #-} import Data.ML import Data.Attoparsec.Text import Data.Text (Text) import Data.Total.Array.Subset import System.Exit import Data.Foldable import Control.Monad import qualified Data.Set as Set import qualified Data.Text as Text import Data.Typeable import qualified Data.Text.IO as Text import Data.Vector (Vector) import qualified Data.Vector as Vector import Data.Bifunctor import Data.Char import Data.Monoid (All(..), Sum(..)) import Data.Function import Data.Random import Data.Reflection -------------------------------------------------------------------------------- -- Model -------------------------------------------------------------------------------- type TreeBank = Tree (Const Text) type Sentiment = Scalar type WordVec = V 5 type WordLookup s = Index (TotalSubsetArray s Text) WordVec type Combinator = AffineMap (Product WordVec WordVec) WordVec :>> Over WordVec Tanh type Fold s = TreeAlgebra (WordLookup s) Combinator type SentimentModel s = Cata TreeBank (Fold s) :>> AffineMap WordVec Sentiment :>> Over Sentiment Sigmoid -------------------------------------------------------------------------------- -- Cost function -------------------------------------------------------------------------------- cost :: Subset s Text => Cost (SentimentModel s) cost = Cost cost' + 0.1 * l2reg where cost' x _ = getScalar $ getSum $ foldMap (Sum . j) x j (a, e) = let y = a - e in y * y -------------------------------------------------------------------------------- -- Driver -------------------------------------------------------------------------------- driver :: Subset s Text => DataSet (SentimentModel s) Double -> DataSet (SentimentModel s) Double -> Proxy s -> Driver (SentimentModel s) Double () driver trainingSet testSet _ = do setCostFun cost setTrainingSet trainingSet setTestSet testSet load "models/global_warming.bm" timed (train 30) test isOk save "models/global_warming.bm" -------------------------------------------------------------------------------- -- Parsing -------------------------------------------------------------------------------- data Class = NA | Yes | No deriving (Eq) type Tweet = (Text, (Class, Double)) tweetParser :: Parser Tweet tweetParser = do t <- quoted char ',' c <- char '"' *> cls <* char '"' char ',' s <- double endOfLine return (t, (c, s)) where quoted = char '"' *> takeTill (=='"') <* char '"' cls = string "N/A" *> pure NA <|> string "Yes" *> pure Yes <|> string "No" *> pure No tweetsParser :: Parser [Tweet] tweetsParser = do tweets <- many tweetParser endOfInput return tweets loadTweets :: IO [Tweet] loadTweets = do content <- Text.readFile "data/global_warming.csv" let result = parseOnly tweetsParser content either die return result -------------------------------------------------------------------------------- -- Preprocessing -------------------------------------------------------------------------------- tokenize :: Text -> [Text] tokenize = Text.words . Text.toLower . Text.filter (\c -> isAlphaNum c || isSpace c) isOk :: Sentiment Double -> Sentiment Double -> CountCorrect isOk x y = if getAll (foldMap All $ ((==) `on` realToClass) <$> x <*> y) then correct else incorrect classToReal :: Class -> Double classToReal NA = 0.5 classToReal Yes = 1 classToReal No = 0 realToClass :: Double -> Class realToClass x | x >= 0 && x < 1/3 = No | x >= 1/3 && x < 2/3 = NA | x >= 2/3 && x <= 1 = Yes | otherwise = error "wrong class" -------------------------------------------------------------------------------- -- Main -------------------------------------------------------------------------------- main :: IO () main = do -- Load the data and shuffle it. tweets <- loadTweets tweets' <- sample $ shuffle tweets -- Tokenize the sentences. let tweets'' = fmap (first tokenize) tweets' wordSet = Set.fromList ("STOP" : join (fmap fst tweets'')) -- Prepare the data set. let dataSet = Vector.fromList $ fmap (bimap (listToTree (Const "STOP") . fmap Const) (Scalar . classToReal . fst)) $ tweets'' (trainingSet, testSet) = Vector.splitAt 4500 dataSet -- Run the driver. reify wordSet $ runDriverT . driver trainingSet testSet
bitemyapp/machine-learning
example/GlobalWarming.hs
mit
4,833
0
19
1,071
1,247
647
600
109
2
module String00001 where s = "There's trailing spaces after this backslash \ \Trust me, they're there!"
charleso/intellij-haskforce
tests/gold/parser/String00001.hs
apache-2.0
111
6
4
23
21
13
8
2
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module TrieMap( CoreMap, emptyCoreMap, extendCoreMap, lookupCoreMap, foldCoreMap, TypeMap, emptyTypeMap, extendTypeMap, lookupTypeMap, foldTypeMap, LooseTypeMap, MaybeMap, ListMap, TrieMap(..), insertTM, deleteTM ) where import CoreSyn import Coercion import Literal import Name import Type import TyCoRep import Var import UniqFM import Unique( Unique ) import FastString(FastString) import qualified Data.Map as Map import qualified Data.IntMap as IntMap import VarEnv import NameEnv import Outputable import Control.Monad( (>=>) ) {- This module implements TrieMaps, which are finite mappings whose key is a structured value like a CoreExpr or Type. The code is very regular and boilerplate-like, but there is some neat handling of *binders*. In effect they are deBruijn numbered on the fly. The regular pattern for handling TrieMaps on data structures was first described (to my knowledge) in Connelly and Morris's 1995 paper "A generalization of the Trie Data Structure"; there is also an accessible description of the idea in Okasaki's book "Purely Functional Data Structures", Section 10.3.2 ************************************************************************ * * The TrieMap class * * ************************************************************************ -} type XT a = Maybe a -> Maybe a -- How to alter a non-existent elt (Nothing) -- or an existing elt (Just) class TrieMap m where type Key m :: * emptyTM :: m a lookupTM :: forall b. Key m -> m b -> Maybe b alterTM :: forall b. Key m -> XT b -> m b -> m b mapTM :: (a->b) -> m a -> m b foldTM :: (a -> b -> b) -> m a -> b -> b -- The unusual argument order here makes -- it easy to compose calls to foldTM; -- see for example fdE below insertTM :: TrieMap m => Key m -> a -> m a -> m a insertTM k v m = alterTM k (\_ -> Just v) m deleteTM :: TrieMap m => Key m -> m a -> m a deleteTM k m = alterTM k (\_ -> Nothing) m ---------------------- -- Recall that -- Control.Monad.(>=>) :: (a -> Maybe b) -> (b -> Maybe c) -> a -> Maybe c (>.>) :: (a -> b) -> (b -> c) -> a -> c -- Reverse function composition (do f first, then g) infixr 1 >.> (f >.> g) x = g (f x) infixr 1 |>, |>> (|>) :: a -> (a->b) -> b -- Reverse application x |> f = f x ---------------------- (|>>) :: TrieMap m2 => (XT (m2 a) -> m1 (m2 a) -> m1 (m2 a)) -> (m2 a -> m2 a) -> m1 (m2 a) -> m1 (m2 a) (|>>) f g = f (Just . g . deMaybe) deMaybe :: TrieMap m => Maybe (m a) -> m a deMaybe Nothing = emptyTM deMaybe (Just m) = m {- ************************************************************************ * * IntMaps * * ************************************************************************ -} instance TrieMap IntMap.IntMap where type Key IntMap.IntMap = Int emptyTM = IntMap.empty lookupTM k m = IntMap.lookup k m alterTM = xtInt foldTM k m z = IntMap.fold k z m mapTM f m = IntMap.map f m xtInt :: Int -> XT a -> IntMap.IntMap a -> IntMap.IntMap a xtInt k f m = IntMap.alter f k m instance Ord k => TrieMap (Map.Map k) where type Key (Map.Map k) = k emptyTM = Map.empty lookupTM = Map.lookup alterTM k f m = Map.alter f k m foldTM k m z = Map.fold k z m mapTM f m = Map.map f m instance TrieMap UniqFM where type Key UniqFM = Unique emptyTM = emptyUFM lookupTM k m = lookupUFM m k alterTM k f m = alterUFM f m k foldTM k m z = foldUFM k z m mapTM f m = mapUFM f m {- ************************************************************************ * * Maybes * * ************************************************************************ If m is a map from k -> val then (MaybeMap m) is a map from (Maybe k) -> val -} data MaybeMap m a = MM { mm_nothing :: Maybe a, mm_just :: m a } instance TrieMap m => TrieMap (MaybeMap m) where type Key (MaybeMap m) = Maybe (Key m) emptyTM = MM { mm_nothing = Nothing, mm_just = emptyTM } lookupTM = lkMaybe lookupTM alterTM = xtMaybe alterTM foldTM = fdMaybe mapTM = mapMb mapMb :: TrieMap m => (a->b) -> MaybeMap m a -> MaybeMap m b mapMb f (MM { mm_nothing = mn, mm_just = mj }) = MM { mm_nothing = fmap f mn, mm_just = mapTM f mj } lkMaybe :: (forall b. k -> m b -> Maybe b) -> Maybe k -> MaybeMap m a -> Maybe a lkMaybe _ Nothing = mm_nothing lkMaybe lk (Just x) = mm_just >.> lk x xtMaybe :: (forall b. k -> XT b -> m b -> m b) -> Maybe k -> XT a -> MaybeMap m a -> MaybeMap m a xtMaybe _ Nothing f m = m { mm_nothing = f (mm_nothing m) } xtMaybe tr (Just x) f m = m { mm_just = mm_just m |> tr x f } fdMaybe :: TrieMap m => (a -> b -> b) -> MaybeMap m a -> b -> b fdMaybe k m = foldMaybe k (mm_nothing m) . foldTM k (mm_just m) {- ************************************************************************ * * Lists * * ************************************************************************ -} data ListMap m a = LM { lm_nil :: Maybe a , lm_cons :: m (ListMap m a) } instance TrieMap m => TrieMap (ListMap m) where type Key (ListMap m) = [Key m] emptyTM = LM { lm_nil = Nothing, lm_cons = emptyTM } lookupTM = lkList lookupTM alterTM = xtList alterTM foldTM = fdList mapTM = mapList mapList :: TrieMap m => (a->b) -> ListMap m a -> ListMap m b mapList f (LM { lm_nil = mnil, lm_cons = mcons }) = LM { lm_nil = fmap f mnil, lm_cons = mapTM (mapTM f) mcons } lkList :: TrieMap m => (forall b. k -> m b -> Maybe b) -> [k] -> ListMap m a -> Maybe a lkList _ [] = lm_nil lkList lk (x:xs) = lm_cons >.> lk x >=> lkList lk xs xtList :: TrieMap m => (forall b. k -> XT b -> m b -> m b) -> [k] -> XT a -> ListMap m a -> ListMap m a xtList _ [] f m = m { lm_nil = f (lm_nil m) } xtList tr (x:xs) f m = m { lm_cons = lm_cons m |> tr x |>> xtList tr xs f } fdList :: forall m a b. TrieMap m => (a -> b -> b) -> ListMap m a -> b -> b fdList k m = foldMaybe k (lm_nil m) . foldTM (fdList k) (lm_cons m) foldMaybe :: (a -> b -> b) -> Maybe a -> b -> b foldMaybe _ Nothing b = b foldMaybe k (Just a) b = k a b {- ************************************************************************ * * Basic maps * * ************************************************************************ -} lkNamed :: NamedThing n => n -> NameEnv a -> Maybe a lkNamed n env = lookupNameEnv env (getName n) xtNamed :: NamedThing n => n -> XT a -> NameEnv a -> NameEnv a xtNamed tc f m = alterNameEnv f m (getName tc) ------------------------ type LiteralMap a = Map.Map Literal a emptyLiteralMap :: LiteralMap a emptyLiteralMap = emptyTM lkLit :: Literal -> LiteralMap a -> Maybe a lkLit = lookupTM xtLit :: Literal -> XT a -> LiteralMap a -> LiteralMap a xtLit = alterTM {- ************************************************************************ * * GenMap * * ************************************************************************ Note [Compressed TrieMap] ~~~~~~~~~~~~~~~~~~~~~~~~~ The GenMap constructor augments TrieMaps with leaf compression. This helps solve the performance problem detailed in #9960: suppose we have a handful H of entries in a TrieMap, each with a very large key, size K. If you fold over such a TrieMap you'd expect time O(H). That would certainly be true of an association list! But with TrieMap we actually have to navigate down a long singleton structure to get to the elements, so it takes time O(K*H). This can really hurt on many type-level computation benchmarks: see for example T9872d. The point of a TrieMap is that you need to navigate to the point where only one key remains, and then things should be fast. So the point of a SingletonMap is that, once we are down to a single (key,value) pair, we stop and just use SingletonMap. 'EmptyMap' provides an even more basic (but essential) optimization: if there is nothing in the map, don't bother building out the (possibly infinite) recursive TrieMap structure! -} data GenMap m a = EmptyMap | SingletonMap (Key m) a | MultiMap (m a) instance (Outputable a, Outputable (m a)) => Outputable (GenMap m a) where ppr EmptyMap = text "Empty map" ppr (SingletonMap _ v) = text "Singleton map" <+> ppr v ppr (MultiMap m) = ppr m -- TODO undecidable instance instance (Eq (Key m), TrieMap m) => TrieMap (GenMap m) where type Key (GenMap m) = Key m emptyTM = EmptyMap lookupTM = lkG alterTM = xtG foldTM = fdG mapTM = mapG -- NB: Be careful about RULES and type families (#5821). So we should make sure -- to specify @Key TypeMapX@ (and not @DeBruijn Type@, the reduced form) {-# SPECIALIZE lkG :: Key TypeMapX -> TypeMapG a -> Maybe a #-} {-# SPECIALIZE lkG :: Key CoercionMapX -> CoercionMapG a -> Maybe a #-} {-# SPECIALIZE lkG :: Key CoreMapX -> CoreMapG a -> Maybe a #-} lkG :: (Eq (Key m), TrieMap m) => Key m -> GenMap m a -> Maybe a lkG _ EmptyMap = Nothing lkG k (SingletonMap k' v') | k == k' = Just v' | otherwise = Nothing lkG k (MultiMap m) = lookupTM k m {-# SPECIALIZE xtG :: Key TypeMapX -> XT a -> TypeMapG a -> TypeMapG a #-} {-# SPECIALIZE xtG :: Key CoercionMapX -> XT a -> CoercionMapG a -> CoercionMapG a #-} {-# SPECIALIZE xtG :: Key CoreMapX -> XT a -> CoreMapG a -> CoreMapG a #-} xtG :: (Eq (Key m), TrieMap m) => Key m -> XT a -> GenMap m a -> GenMap m a xtG k f EmptyMap = case f Nothing of Just v -> SingletonMap k v Nothing -> EmptyMap xtG k f m@(SingletonMap k' v') | k' == k -- The new key matches the (single) key already in the tree. Hence, -- apply @f@ to @Just v'@ and build a singleton or empty map depending -- on the 'Just'/'Nothing' response respectively. = case f (Just v') of Just v'' -> SingletonMap k' v'' Nothing -> EmptyMap | otherwise -- We've hit a singleton tree for a different key than the one we are -- searching for. Hence apply @f@ to @Nothing@. If result is @Nothing@ then -- we can just return the old map. If not, we need a map with *two* -- entries. The easiest way to do that is to insert two items into an empty -- map of type @m a@. = case f Nothing of Nothing -> m Just v -> emptyTM |> alterTM k' (const (Just v')) >.> alterTM k (const (Just v)) >.> MultiMap xtG k f (MultiMap m) = MultiMap (alterTM k f m) {-# SPECIALIZE mapG :: (a -> b) -> TypeMapG a -> TypeMapG b #-} {-# SPECIALIZE mapG :: (a -> b) -> CoercionMapG a -> CoercionMapG b #-} {-# SPECIALIZE mapG :: (a -> b) -> CoreMapG a -> CoreMapG b #-} mapG :: TrieMap m => (a -> b) -> GenMap m a -> GenMap m b mapG _ EmptyMap = EmptyMap mapG f (SingletonMap k v) = SingletonMap k (f v) mapG f (MultiMap m) = MultiMap (mapTM f m) {-# SPECIALIZE fdG :: (a -> b -> b) -> TypeMapG a -> b -> b #-} {-# SPECIALIZE fdG :: (a -> b -> b) -> CoercionMapG a -> b -> b #-} {-# SPECIALIZE fdG :: (a -> b -> b) -> CoreMapG a -> b -> b #-} fdG :: TrieMap m => (a -> b -> b) -> GenMap m a -> b -> b fdG _ EmptyMap = \z -> z fdG k (SingletonMap _ v) = \z -> k v z fdG k (MultiMap m) = foldTM k m {- ************************************************************************ * * CoreMap * * ************************************************************************ Note [Binders] ~~~~~~~~~~~~~~ * In general we check binders as late as possible because types are less likely to differ than expression structure. That's why cm_lam :: CoreMapG (TypeMapG a) rather than cm_lam :: TypeMapG (CoreMapG a) * We don't need to look at the type of some binders, notalby - the case binder in (Case _ b _ _) - the binders in an alternative because they are totally fixed by the context Note [Empty case alternatives] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * For a key (Case e b ty (alt:alts)) we don't need to look the return type 'ty', because every alternative has that type. * For a key (Case e b ty []) we MUST look at the return type 'ty', because otherwise (Case (error () "urk") _ Int []) would compare equal to (Case (error () "urk") _ Bool []) which is utterly wrong (Trac #6097) We could compare the return type regardless, but the wildly common case is that it's unnecessary, so we have two fields (cm_case and cm_ecase) for the two possibilities. Only cm_ecase looks at the type. See also Note [Empty case alternatives] in CoreSyn. -} -- | @CoreMap a@ is a map from 'CoreExpr' to @a@. If you are a client, this -- is the type you want. newtype CoreMap a = CoreMap (CoreMapG a) instance TrieMap CoreMap where type Key CoreMap = CoreExpr emptyTM = CoreMap emptyTM lookupTM k (CoreMap m) = lookupTM (deBruijnize k) m alterTM k f (CoreMap m) = CoreMap (alterTM (deBruijnize k) f m) foldTM k (CoreMap m) = foldTM k m mapTM f (CoreMap m) = CoreMap (mapTM f m) -- | @CoreMapG a@ is a map from @DeBruijn CoreExpr@ to @a@. The extended -- key makes it suitable for recursive traversal, since it can track binders, -- but it is strictly internal to this module. If you are including a 'CoreMap' -- inside another 'TrieMap', this is the type you want. type CoreMapG = GenMap CoreMapX -- | @CoreMapX a@ is the base map from @DeBruijn CoreExpr@ to @a@, but without -- the 'GenMap' optimization. data CoreMapX a = CM { cm_var :: VarMap a , cm_lit :: LiteralMap a , cm_co :: CoercionMapG a , cm_type :: TypeMapG a , cm_cast :: CoreMapG (CoercionMapG a) , cm_tick :: CoreMapG (TickishMap a) , cm_app :: CoreMapG (CoreMapG a) , cm_lam :: CoreMapG (BndrMap a) -- Note [Binders] , cm_letn :: CoreMapG (CoreMapG (BndrMap a)) , cm_letr :: ListMap CoreMapG (CoreMapG (ListMap BndrMap a)) , cm_case :: CoreMapG (ListMap AltMap a) , cm_ecase :: CoreMapG (TypeMapG a) -- Note [Empty case alternatives] } instance Eq (DeBruijn CoreExpr) where D env1 e1 == D env2 e2 = go e1 e2 where go (Var v1) (Var v2) = case (lookupCME env1 v1, lookupCME env2 v2) of (Just b1, Just b2) -> b1 == b2 (Nothing, Nothing) -> v1 == v2 _ -> False go (Lit lit1) (Lit lit2) = lit1 == lit2 go (Type t1) (Type t2) = D env1 t1 == D env2 t2 go (Coercion co1) (Coercion co2) = D env1 co1 == D env2 co2 go (Cast e1 co1) (Cast e2 co2) = D env1 co1 == D env2 co2 && go e1 e2 go (App f1 a1) (App f2 a2) = go f1 f2 && go a1 a2 -- This seems a bit dodgy, see 'eqTickish' go (Tick n1 e1) (Tick n2 e2) = n1 == n2 && go e1 e2 go (Lam b1 e1) (Lam b2 e2) = D env1 (varType b1) == D env2 (varType b2) && D (extendCME env1 b1) e1 == D (extendCME env2 b2) e2 go (Let (NonRec v1 r1) e1) (Let (NonRec v2 r2) e2) = go r1 r2 && D (extendCME env1 v1) e1 == D (extendCME env2 v2) e2 go (Let (Rec ps1) e1) (Let (Rec ps2) e2) = length ps1 == length ps2 && D env1' rs1 == D env2' rs2 && D env1' e1 == D env2' e2 where (bs1,rs1) = unzip ps1 (bs2,rs2) = unzip ps2 env1' = extendCMEs env1 bs1 env2' = extendCMEs env2 bs2 go (Case e1 b1 t1 a1) (Case e2 b2 t2 a2) | null a1 -- See Note [Empty case alternatives] = null a2 && go e1 e2 && D env1 t1 == D env2 t2 | otherwise = go e1 e2 && D (extendCME env1 b1) a1 == D (extendCME env2 b2) a2 go _ _ = False emptyE :: CoreMapX a emptyE = CM { cm_var = emptyTM, cm_lit = emptyLiteralMap , cm_co = emptyTM, cm_type = emptyTM , cm_cast = emptyTM, cm_app = emptyTM , cm_lam = emptyTM, cm_letn = emptyTM , cm_letr = emptyTM, cm_case = emptyTM , cm_ecase = emptyTM, cm_tick = emptyTM } instance TrieMap CoreMapX where type Key CoreMapX = DeBruijn CoreExpr emptyTM = emptyE lookupTM = lkE alterTM = xtE foldTM = fdE mapTM = mapE -------------------------- mapE :: (a->b) -> CoreMapX a -> CoreMapX b mapE f (CM { cm_var = cvar, cm_lit = clit , cm_co = cco, cm_type = ctype , cm_cast = ccast , cm_app = capp , cm_lam = clam, cm_letn = cletn , cm_letr = cletr, cm_case = ccase , cm_ecase = cecase, cm_tick = ctick }) = CM { cm_var = mapTM f cvar, cm_lit = mapTM f clit , cm_co = mapTM f cco, cm_type = mapTM f ctype , cm_cast = mapTM (mapTM f) ccast, cm_app = mapTM (mapTM f) capp , cm_lam = mapTM (mapTM f) clam, cm_letn = mapTM (mapTM (mapTM f)) cletn , cm_letr = mapTM (mapTM (mapTM f)) cletr, cm_case = mapTM (mapTM f) ccase , cm_ecase = mapTM (mapTM f) cecase, cm_tick = mapTM (mapTM f) ctick } -------------------------- lookupCoreMap :: CoreMap a -> CoreExpr -> Maybe a lookupCoreMap cm e = lookupTM e cm extendCoreMap :: CoreMap a -> CoreExpr -> a -> CoreMap a extendCoreMap m e v = alterTM e (\_ -> Just v) m foldCoreMap :: (a -> b -> b) -> b -> CoreMap a -> b foldCoreMap k z m = foldTM k m z emptyCoreMap :: CoreMap a emptyCoreMap = emptyTM instance Outputable a => Outputable (CoreMap a) where ppr m = text "CoreMap elts" <+> ppr (foldTM (:) m []) ------------------------- fdE :: (a -> b -> b) -> CoreMapX a -> b -> b fdE k m = foldTM k (cm_var m) . foldTM k (cm_lit m) . foldTM k (cm_co m) . foldTM k (cm_type m) . foldTM (foldTM k) (cm_cast m) . foldTM (foldTM k) (cm_tick m) . foldTM (foldTM k) (cm_app m) . foldTM (foldTM k) (cm_lam m) . foldTM (foldTM (foldTM k)) (cm_letn m) . foldTM (foldTM (foldTM k)) (cm_letr m) . foldTM (foldTM k) (cm_case m) . foldTM (foldTM k) (cm_ecase m) -- lkE: lookup in trie for expressions lkE :: DeBruijn CoreExpr -> CoreMapX a -> Maybe a lkE (D env expr) cm = go expr cm where go (Var v) = cm_var >.> lkVar env v go (Lit l) = cm_lit >.> lkLit l go (Type t) = cm_type >.> lkG (D env t) go (Coercion c) = cm_co >.> lkG (D env c) go (Cast e c) = cm_cast >.> lkG (D env e) >=> lkG (D env c) go (Tick tickish e) = cm_tick >.> lkG (D env e) >=> lkTickish tickish go (App e1 e2) = cm_app >.> lkG (D env e2) >=> lkG (D env e1) go (Lam v e) = cm_lam >.> lkG (D (extendCME env v) e) >=> lkBndr env v go (Let (NonRec b r) e) = cm_letn >.> lkG (D env r) >=> lkG (D (extendCME env b) e) >=> lkBndr env b go (Let (Rec prs) e) = let (bndrs,rhss) = unzip prs env1 = extendCMEs env bndrs in cm_letr >.> lkList (lkG . D env1) rhss >=> lkG (D env1 e) >=> lkList (lkBndr env1) bndrs go (Case e b ty as) -- See Note [Empty case alternatives] | null as = cm_ecase >.> lkG (D env e) >=> lkG (D env ty) | otherwise = cm_case >.> lkG (D env e) >=> lkList (lkA (extendCME env b)) as xtE :: DeBruijn CoreExpr -> XT a -> CoreMapX a -> CoreMapX a xtE (D env (Var v)) f m = m { cm_var = cm_var m |> xtVar env v f } xtE (D env (Type t)) f m = m { cm_type = cm_type m |> xtG (D env t) f } xtE (D env (Coercion c)) f m = m { cm_co = cm_co m |> xtG (D env c) f } xtE (D _ (Lit l)) f m = m { cm_lit = cm_lit m |> xtLit l f } xtE (D env (Cast e c)) f m = m { cm_cast = cm_cast m |> xtG (D env e) |>> xtG (D env c) f } xtE (D env (Tick t e)) f m = m { cm_tick = cm_tick m |> xtG (D env e) |>> xtTickish t f } xtE (D env (App e1 e2)) f m = m { cm_app = cm_app m |> xtG (D env e2) |>> xtG (D env e1) f } xtE (D env (Lam v e)) f m = m { cm_lam = cm_lam m |> xtG (D (extendCME env v) e) |>> xtBndr env v f } xtE (D env (Let (NonRec b r) e)) f m = m { cm_letn = cm_letn m |> xtG (D (extendCME env b) e) |>> xtG (D env r) |>> xtBndr env b f } xtE (D env (Let (Rec prs) e)) f m = m { cm_letr = let (bndrs,rhss) = unzip prs env1 = extendCMEs env bndrs in cm_letr m |> xtList (xtG . D env1) rhss |>> xtG (D env1 e) |>> xtList (xtBndr env1) bndrs f } xtE (D env (Case e b ty as)) f m | null as = m { cm_ecase = cm_ecase m |> xtG (D env e) |>> xtG (D env ty) f } | otherwise = m { cm_case = cm_case m |> xtG (D env e) |>> let env1 = extendCME env b in xtList (xtA env1) as f } -- TODO: this seems a bit dodgy, see 'eqTickish' type TickishMap a = Map.Map (Tickish Id) a lkTickish :: Tickish Id -> TickishMap a -> Maybe a lkTickish = lookupTM xtTickish :: Tickish Id -> XT a -> TickishMap a -> TickishMap a xtTickish = alterTM ------------------------ data AltMap a -- A single alternative = AM { am_deflt :: CoreMapG a , am_data :: NameEnv (CoreMapG a) , am_lit :: LiteralMap (CoreMapG a) } instance TrieMap AltMap where type Key AltMap = CoreAlt emptyTM = AM { am_deflt = emptyTM , am_data = emptyNameEnv , am_lit = emptyLiteralMap } lookupTM = lkA emptyCME alterTM = xtA emptyCME foldTM = fdA mapTM = mapA instance Eq (DeBruijn CoreAlt) where D env1 a1 == D env2 a2 = go a1 a2 where go (DEFAULT, _, rhs1) (DEFAULT, _, rhs2) = D env1 rhs1 == D env2 rhs2 go (LitAlt lit1, _, rhs1) (LitAlt lit2, _, rhs2) = lit1 == lit2 && D env1 rhs1 == D env2 rhs2 go (DataAlt dc1, bs1, rhs1) (DataAlt dc2, bs2, rhs2) = dc1 == dc2 && D (extendCMEs env1 bs1) rhs1 == D (extendCMEs env2 bs2) rhs2 go _ _ = False mapA :: (a->b) -> AltMap a -> AltMap b mapA f (AM { am_deflt = adeflt, am_data = adata, am_lit = alit }) = AM { am_deflt = mapTM f adeflt , am_data = mapNameEnv (mapTM f) adata , am_lit = mapTM (mapTM f) alit } lkA :: CmEnv -> CoreAlt -> AltMap a -> Maybe a lkA env (DEFAULT, _, rhs) = am_deflt >.> lkG (D env rhs) lkA env (LitAlt lit, _, rhs) = am_lit >.> lkLit lit >=> lkG (D env rhs) lkA env (DataAlt dc, bs, rhs) = am_data >.> lkNamed dc >=> lkG (D (extendCMEs env bs) rhs) xtA :: CmEnv -> CoreAlt -> XT a -> AltMap a -> AltMap a xtA env (DEFAULT, _, rhs) f m = m { am_deflt = am_deflt m |> xtG (D env rhs) f } xtA env (LitAlt l, _, rhs) f m = m { am_lit = am_lit m |> xtLit l |>> xtG (D env rhs) f } xtA env (DataAlt d, bs, rhs) f m = m { am_data = am_data m |> xtNamed d |>> xtG (D (extendCMEs env bs) rhs) f } fdA :: (a -> b -> b) -> AltMap a -> b -> b fdA k m = foldTM k (am_deflt m) . foldTM (foldTM k) (am_data m) . foldTM (foldTM k) (am_lit m) {- ************************************************************************ * * Coercions * * ************************************************************************ -} -- We should really never care about the contents of a coercion. Instead, -- just look up the coercion's type. newtype CoercionMap a = CoercionMap (CoercionMapG a) instance TrieMap CoercionMap where type Key CoercionMap = Coercion emptyTM = CoercionMap emptyTM lookupTM k (CoercionMap m) = lookupTM (deBruijnize k) m alterTM k f (CoercionMap m) = CoercionMap (alterTM (deBruijnize k) f m) foldTM k (CoercionMap m) = foldTM k m mapTM f (CoercionMap m) = CoercionMap (mapTM f m) type CoercionMapG = GenMap CoercionMapX newtype CoercionMapX a = CoercionMapX (TypeMapX a) instance TrieMap CoercionMapX where type Key CoercionMapX = DeBruijn Coercion emptyTM = CoercionMapX emptyTM lookupTM = lkC alterTM = xtC foldTM f (CoercionMapX core_tm) = foldTM f core_tm mapTM f (CoercionMapX core_tm) = CoercionMapX (mapTM f core_tm) instance Eq (DeBruijn Coercion) where D env1 co1 == D env2 co2 = D env1 (coercionType co1) == D env2 (coercionType co2) lkC :: DeBruijn Coercion -> CoercionMapX a -> Maybe a lkC (D env co) (CoercionMapX core_tm) = lkT (D env $ coercionType co) core_tm xtC :: DeBruijn Coercion -> XT a -> CoercionMapX a -> CoercionMapX a xtC (D env co) f (CoercionMapX m) = CoercionMapX (xtT (D env $ coercionType co) f m) {- ************************************************************************ * * Types * * ************************************************************************ -} -- | @TypeMapG a@ is a map from @DeBruijn Type@ to @a@. The extended -- key makes it suitable for recursive traversal, since it can track binders, -- but it is strictly internal to this module. If you are including a 'TypeMap' -- inside another 'TrieMap', this is the type you want. Note that this -- lookup does not do a kind-check. Thus, all keys in this map must have -- the same kind. type TypeMapG = GenMap TypeMapX -- | @TypeMapX a@ is the base map from @DeBruijn Type@ to @a@, but without the -- 'GenMap' optimization. data TypeMapX a = TM { tm_var :: VarMap a , tm_app :: TypeMapG (TypeMapG a) , tm_tycon :: NameEnv a , tm_forall :: TypeMapG (BndrMap a) -- See Note [Binders] , tm_tylit :: TyLitMap a , tm_coerce :: Maybe a } -- Note that there is no tyconapp case; see Note [Equality on AppTys] in Type -- | squeeze out any synonyms, convert Constraint to *, and change TyConApps -- to nested AppTys. Why the last one? See Note [Equality on AppTys] in Type trieMapView :: Type -> Maybe Type trieMapView ty | Just ty' <- coreViewOneStarKind ty = Just ty' trieMapView (TyConApp tc tys@(_:_)) = Just $ foldl AppTy (TyConApp tc []) tys trieMapView (ForAllTy (Anon arg) res) = Just ((TyConApp funTyCon [] `AppTy` arg) `AppTy` res) trieMapView _ = Nothing instance TrieMap TypeMapX where type Key TypeMapX = DeBruijn Type emptyTM = emptyT lookupTM = lkT alterTM = xtT foldTM = fdT mapTM = mapT instance Eq (DeBruijn Type) where env_t@(D env t) == env_t'@(D env' t') | Just new_t <- coreViewOneStarKind t = D env new_t == env_t' | Just new_t' <- coreViewOneStarKind t' = env_t == D env' new_t' | otherwise = case (t, t') of (CastTy t1 _, _) -> D env t1 == D env t' (_, CastTy t1' _) -> D env t == D env t1' (TyVarTy v, TyVarTy v') -> case (lookupCME env v, lookupCME env' v') of (Just bv, Just bv') -> bv == bv' (Nothing, Nothing) -> v == v' _ -> False -- See Note [Equality on AppTys] in Type (AppTy t1 t2, s) | Just (t1', t2') <- repSplitAppTy_maybe s -> D env t1 == D env' t1' && D env t2 == D env' t2' (s, AppTy t1' t2') | Just (t1, t2) <- repSplitAppTy_maybe s -> D env t1 == D env' t1' && D env t2 == D env' t2' (ForAllTy (Anon t1) t2, ForAllTy (Anon t1') t2') -> D env t1 == D env' t1' && D env t2 == D env' t2' (TyConApp tc tys, TyConApp tc' tys') -> tc == tc' && D env tys == D env' tys' (LitTy l, LitTy l') -> l == l' (ForAllTy (Named tv _) ty, ForAllTy (Named tv' _) ty') -> D env (tyVarKind tv) == D env' (tyVarKind tv') && D (extendCME env tv) ty == D (extendCME env' tv') ty' (CoercionTy {}, CoercionTy {}) -> True _ -> False instance Outputable a => Outputable (TypeMapG a) where ppr m = text "TypeMap elts" <+> ppr (foldTM (:) m []) emptyT :: TypeMapX a emptyT = TM { tm_var = emptyTM , tm_app = EmptyMap , tm_tycon = emptyNameEnv , tm_forall = EmptyMap , tm_tylit = emptyTyLitMap , tm_coerce = Nothing } mapT :: (a->b) -> TypeMapX a -> TypeMapX b mapT f (TM { tm_var = tvar, tm_app = tapp, tm_tycon = ttycon , tm_forall = tforall, tm_tylit = tlit , tm_coerce = tcoerce }) = TM { tm_var = mapTM f tvar , tm_app = mapTM (mapTM f) tapp , tm_tycon = mapNameEnv f ttycon , tm_forall = mapTM (mapTM f) tforall , tm_tylit = mapTM f tlit , tm_coerce = fmap f tcoerce } ----------------- lkT :: DeBruijn Type -> TypeMapX a -> Maybe a lkT (D env ty) m = go ty m where go ty | Just ty' <- trieMapView ty = go ty' go (TyVarTy v) = tm_var >.> lkVar env v go (AppTy t1 t2) = tm_app >.> lkG (D env t1) >=> lkG (D env t2) go (TyConApp tc []) = tm_tycon >.> lkNamed tc go ty@(TyConApp _ (_:_)) = pprPanic "lkT TyConApp" (ppr ty) go (LitTy l) = tm_tylit >.> lkTyLit l go (ForAllTy (Named tv _) ty) = tm_forall >.> lkG (D (extendCME env tv) ty) >=> lkBndr env tv go ty@(ForAllTy (Anon _) _) = pprPanic "lkT FunTy" (ppr ty) go (CastTy t _) = go t go (CoercionTy {}) = tm_coerce ----------------- xtT :: DeBruijn Type -> XT a -> TypeMapX a -> TypeMapX a xtT (D env ty) f m | Just ty' <- trieMapView ty = xtT (D env ty') f m xtT (D env (TyVarTy v)) f m = m { tm_var = tm_var m |> xtVar env v f } xtT (D env (AppTy t1 t2)) f m = m { tm_app = tm_app m |> xtG (D env t1) |>> xtG (D env t2) f } xtT (D _ (TyConApp tc [])) f m = m { tm_tycon = tm_tycon m |> xtNamed tc f } xtT (D _ (LitTy l)) f m = m { tm_tylit = tm_tylit m |> xtTyLit l f } xtT (D env (CastTy t _)) f m = xtT (D env t) f m xtT (D _ (CoercionTy {})) f m = m { tm_coerce = tm_coerce m |> f } xtT (D env (ForAllTy (Named tv _) ty)) f m = m { tm_forall = tm_forall m |> xtG (D (extendCME env tv) ty) |>> xtBndr env tv f } xtT (D _ ty@(TyConApp _ (_:_))) _ _ = pprPanic "xtT TyConApp" (ppr ty) xtT (D _ ty@(ForAllTy (Anon _) _)) _ _ = pprPanic "xtT FunTy" (ppr ty) fdT :: (a -> b -> b) -> TypeMapX a -> b -> b fdT k m = foldTM k (tm_var m) . foldTM (foldTM k) (tm_app m) . foldTM k (tm_tycon m) . foldTM (foldTM k) (tm_forall m) . foldTyLit k (tm_tylit m) . foldMaybe k (tm_coerce m) ------------------------ data TyLitMap a = TLM { tlm_number :: Map.Map Integer a , tlm_string :: Map.Map FastString a } instance TrieMap TyLitMap where type Key TyLitMap = TyLit emptyTM = emptyTyLitMap lookupTM = lkTyLit alterTM = xtTyLit foldTM = foldTyLit mapTM = mapTyLit emptyTyLitMap :: TyLitMap a emptyTyLitMap = TLM { tlm_number = Map.empty, tlm_string = Map.empty } mapTyLit :: (a->b) -> TyLitMap a -> TyLitMap b mapTyLit f (TLM { tlm_number = tn, tlm_string = ts }) = TLM { tlm_number = Map.map f tn, tlm_string = Map.map f ts } lkTyLit :: TyLit -> TyLitMap a -> Maybe a lkTyLit l = case l of NumTyLit n -> tlm_number >.> Map.lookup n StrTyLit n -> tlm_string >.> Map.lookup n xtTyLit :: TyLit -> XT a -> TyLitMap a -> TyLitMap a xtTyLit l f m = case l of NumTyLit n -> m { tlm_number = tlm_number m |> Map.alter f n } StrTyLit n -> m { tlm_string = tlm_string m |> Map.alter f n } foldTyLit :: (a -> b -> b) -> TyLitMap a -> b -> b foldTyLit l m = flip (Map.fold l) (tlm_string m) . flip (Map.fold l) (tlm_number m) ------------------------------------------------- -- | @TypeMap a@ is a map from 'Type' to @a@. If you are a client, this -- is the type you want. The keys in this map may have different kinds. newtype TypeMap a = TypeMap (TypeMapG (TypeMapG a)) lkTT :: DeBruijn Type -> TypeMap a -> Maybe a lkTT (D env ty) (TypeMap m) = lkG (D env $ typeKind ty) m >>= lkG (D env ty) xtTT :: DeBruijn Type -> XT a -> TypeMap a -> TypeMap a xtTT (D env ty) f (TypeMap m) = TypeMap (m |> xtG (D env $ typeKind ty) |>> xtG (D env ty) f) -- Below are some client-oriented functions which operate on 'TypeMap'. instance TrieMap TypeMap where type Key TypeMap = Type emptyTM = TypeMap emptyTM lookupTM k m = lkTT (deBruijnize k) m alterTM k f m = xtTT (deBruijnize k) f m foldTM k (TypeMap m) = foldTM (foldTM k) m mapTM f (TypeMap m) = TypeMap (mapTM (mapTM f) m) foldTypeMap :: (a -> b -> b) -> b -> TypeMap a -> b foldTypeMap k z m = foldTM k m z emptyTypeMap :: TypeMap a emptyTypeMap = emptyTM lookupTypeMap :: TypeMap a -> Type -> Maybe a lookupTypeMap cm t = lookupTM t cm extendTypeMap :: TypeMap a -> Type -> a -> TypeMap a extendTypeMap m t v = alterTM t (const (Just v)) m -- | A 'LooseTypeMap' doesn't do a kind-check. Thus, when lookup up (t |> g), -- you'll find entries inserted under (t), even if (g) is non-reflexive. newtype LooseTypeMap a = LooseTypeMap (TypeMapG a) instance TrieMap LooseTypeMap where type Key LooseTypeMap = Type emptyTM = LooseTypeMap emptyTM lookupTM k (LooseTypeMap m) = lookupTM (deBruijnize k) m alterTM k f (LooseTypeMap m) = LooseTypeMap (alterTM (deBruijnize k) f m) foldTM f (LooseTypeMap m) = foldTM f m mapTM f (LooseTypeMap m) = LooseTypeMap (mapTM f m) {- ************************************************************************ * * Variables * * ************************************************************************ -} type BoundVar = Int -- Bound variables are deBruijn numbered type BoundVarMap a = IntMap.IntMap a data CmEnv = CME { cme_next :: BoundVar , cme_env :: VarEnv BoundVar } emptyCME :: CmEnv emptyCME = CME { cme_next = 0, cme_env = emptyVarEnv } extendCME :: CmEnv -> Var -> CmEnv extendCME (CME { cme_next = bv, cme_env = env }) v = CME { cme_next = bv+1, cme_env = extendVarEnv env v bv } extendCMEs :: CmEnv -> [Var] -> CmEnv extendCMEs env vs = foldl extendCME env vs lookupCME :: CmEnv -> Var -> Maybe BoundVar lookupCME (CME { cme_env = env }) v = lookupVarEnv env v -- | @DeBruijn a@ represents @a@ modulo alpha-renaming. This is achieved -- by equipping the value with a 'CmEnv', which tracks an on-the-fly deBruijn -- numbering. This allows us to define an 'Eq' instance for @DeBruijn a@, even -- if this was not (easily) possible for @a@. Note: we purposely don't -- export the constructor. Make a helper function if you find yourself -- needing it. data DeBruijn a = D CmEnv a -- | Synthesizes a @DeBruijn a@ from an @a@, by assuming that there are no -- bound binders (an empty 'CmEnv'). This is usually what you want if there -- isn't already a 'CmEnv' in scope. deBruijnize :: a -> DeBruijn a deBruijnize = D emptyCME instance Eq (DeBruijn a) => Eq (DeBruijn [a]) where D _ [] == D _ [] = True D env (x:xs) == D env' (x':xs') = D env x == D env' x' && D env xs == D env' xs' _ == _ = False --------- Variable binders ------------- -- | A 'BndrMap' is a 'TypeMapG' which allows us to distinguish between -- binding forms whose binders have different types. For example, -- if we are doing a 'TrieMap' lookup on @\(x :: Int) -> ()@, we should -- not pick up an entry in the 'TrieMap' for @\(x :: Bool) -> ()@: -- we can disambiguate this by matching on the type (or kind, if this -- a binder in a type) of the binder. type BndrMap = TypeMapG -- Note [Binders] -- ~~~~~~~~~~~~~~ -- We need to use 'BndrMap' for 'Coercion', 'CoreExpr' AND 'Type', since all -- of these data types have binding forms. lkBndr :: CmEnv -> Var -> BndrMap a -> Maybe a lkBndr env v m = lkG (D env (varType v)) m xtBndr :: CmEnv -> Var -> XT a -> BndrMap a -> BndrMap a xtBndr env v f = xtG (D env (varType v)) f --------- Variable occurrence ------------- data VarMap a = VM { vm_bvar :: BoundVarMap a -- Bound variable , vm_fvar :: VarEnv a } -- Free variable instance TrieMap VarMap where type Key VarMap = Var emptyTM = VM { vm_bvar = IntMap.empty, vm_fvar = emptyVarEnv } lookupTM = lkVar emptyCME alterTM = xtVar emptyCME foldTM = fdVar mapTM = mapVar mapVar :: (a->b) -> VarMap a -> VarMap b mapVar f (VM { vm_bvar = bv, vm_fvar = fv }) = VM { vm_bvar = mapTM f bv, vm_fvar = mapVarEnv f fv } lkVar :: CmEnv -> Var -> VarMap a -> Maybe a lkVar env v | Just bv <- lookupCME env v = vm_bvar >.> lookupTM bv | otherwise = vm_fvar >.> lkFreeVar v xtVar :: CmEnv -> Var -> XT a -> VarMap a -> VarMap a xtVar env v f m | Just bv <- lookupCME env v = m { vm_bvar = vm_bvar m |> xtInt bv f } | otherwise = m { vm_fvar = vm_fvar m |> xtFreeVar v f } fdVar :: (a -> b -> b) -> VarMap a -> b -> b fdVar k m = foldTM k (vm_bvar m) . foldTM k (vm_fvar m) lkFreeVar :: Var -> VarEnv a -> Maybe a lkFreeVar var env = lookupVarEnv env var xtFreeVar :: Var -> XT a -> VarEnv a -> VarEnv a xtFreeVar v f m = alterVarEnv f m v
tjakway/ghcjvm
compiler/coreSyn/TrieMap.hs
bsd-3-clause
39,875
0
18
13,037
12,583
6,373
6,210
652
11
import Debug.Trace newtype Id a = Id a unId True _ = Nothing -- make lazy unId False (Just (Id x)) = (Just x) unId False Nothing = Nothing {-# NOINLINE unId #-} val n = trace "evaluated once, as it should" (Just (Id n)) {-# NOINLINE val #-} foo b n = unId b (val n) {-# NOINLINE foo #-} main = print (foo False 1)
ezyang/ghc
testsuite/tests/simplStg/should_run/T13536.hs
bsd-3-clause
320
0
9
73
129
67
62
11
1
{-# LANGUAGE BangPatterns #-} data Test = Test !Int {-# NOINLINE f #-} f a = Test (a + 1) main = let (Test x) = f 1 in print x
ezyang/ghc
testsuite/tests/rts/T8308/T8308.hs
bsd-3-clause
129
0
10
33
60
29
31
7
1
{-# LANGUAGE TypeFamilies #-} module T11164b where import T11164a data instance T Int = MkT
ezyang/ghc
testsuite/tests/rename/should_compile/T11164b.hs
bsd-3-clause
94
0
5
17
20
12
8
4
0
{-# LANGUAGE TypeSynonymInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {- BlockId module should probably go away completely, being superseded by Label -} module BlockId ( BlockId, mkBlockId -- ToDo: BlockId should be abstract, but it isn't yet , BlockSet, BlockEnv , IsSet(..), setInsertList, setDeleteList, setUnions , IsMap(..), mapInsertList, mapDeleteList, mapUnions , emptyBlockSet, emptyBlockMap , blockLbl, infoTblLbl, retPtLbl ) where import CLabel import IdInfo import Name import Outputable import Unique import Compiler.Hoopl as Hoopl hiding (Unique) import Compiler.Hoopl.Internals (uniqueToLbl, lblToUnique) ---------------------------------------------------------------- --- Block Ids, their environments, and their sets {- Note [Unique BlockId] ~~~~~~~~~~~~~~~~~~~~~~~~ Although a 'BlockId' is a local label, for reasons of implementation, 'BlockId's must be unique within an entire compilation unit. The reason is that each local label is mapped to an assembly-language label, and in most assembly languages allow, a label is visible throughout the entire compilation unit in which it appears. -} type BlockId = Hoopl.Label instance Uniquable BlockId where getUnique label = getUnique (lblToUnique label) instance Outputable BlockId where ppr label = ppr (getUnique label) mkBlockId :: Unique -> BlockId mkBlockId unique = uniqueToLbl $ intToUnique $ getKey unique retPtLbl :: BlockId -> CLabel retPtLbl label = mkReturnPtLabel $ getUnique label blockLbl :: BlockId -> CLabel blockLbl label = mkEntryLabel (mkFCallName (getUnique label) "block") NoCafRefs infoTblLbl :: BlockId -> CLabel infoTblLbl label = mkInfoTableLabel (mkFCallName (getUnique label) "block") NoCafRefs -- Block environments: Id blocks type BlockEnv a = Hoopl.LabelMap a instance Outputable a => Outputable (BlockEnv a) where ppr = ppr . mapToList emptyBlockMap :: BlockEnv a emptyBlockMap = mapEmpty -- Block sets type BlockSet = Hoopl.LabelSet instance Outputable BlockSet where ppr = ppr . setElems emptyBlockSet :: BlockSet emptyBlockSet = setEmpty
urbanslug/ghc
compiler/cmm/BlockId.hs
bsd-3-clause
2,087
0
9
317
388
221
167
39
1
{-# LANGUAGE PartialTypeSignatures #-} module NamedWildcardsEnabled where foo :: Eq a => a -> (a, _) foo x = (x, x) test = foo id -- As id (forall a. a -> a) doesn't implement Eq, the we cannot apply -- foo with it. This test checks that foo gets the annotated type, -- including constraints, not just the inferred type.
urbanslug/ghc
testsuite/tests/partial-sigs/should_fail/AnnotatedConstraint.hs
bsd-3-clause
324
0
7
64
52
31
21
5
1
{-# LANGUAGE TemplateHaskell #-} -- Test Trac #2386 module T2386 where import T2386_Lib foo = $(makeOne)
siddhanathan/ghc
testsuite/tests/th/T2386.hs
bsd-3-clause
109
0
6
20
18
12
6
4
1
{-# LANGUAGE GADTs #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} -- Test for trac #366 -- The C2 case is impossible due to the types module ShouldCompile where data T a where C1 :: T Char C2 :: T Float exhaustive :: T Char -> Char exhaustive C1 = ' '
wxwxwwxxx/ghc
testsuite/tests/typecheck/should_compile/tc215.hs
bsd-3-clause
269
0
6
62
49
29
20
8
1
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE PartialTypeSignatures #-} module Data.Array.Accelerate.TypeLits ( -- * Types AccScalar, AccVector, AccMatrix, -- * Classes AccFunctor(..), -- * Constructors mkMatrix, mkVector, mkScalar, unsafeMkMatrix, unsafeMkVector, unMatrix, unVector, unScalar, identityMatrix, zeroV, zeroM, -- * Functions -- ** Scalar & X (.*^), (./^), (.*#), (./#), -- ** AccMatrix & Vector (#*^), (^*#), -- ** AccVector & Vector (^+^), (^-^), (^*^), -- ** AccMatrix & Matrix (#+#), (#-#), (#*#), (#**.), -- ** Utility functions transpose, zipWithV, zipWithM, ) where import qualified Data.Array.Accelerate as A import Data.Proxy (Proxy(..)) import GHC.TypeLits (KnownNat, natVal) import Data.Array.Accelerate.TypeLits.Internal import Data.Array.Accelerate ( (:.)((:.)) , Exp , DIM2, DIM3, Z(Z) , Elt , All(All), Any(Any)) identityMatrix :: forall n a. (KnownNat n, Num a, A.Num a, Elt a) => AccMatrix n n a -- | constructor for the nxn dimensional identity matrix, given by -- -- > ⎛ 1 0 … 0 0 ⎞ -- > ⎜ 0 1 … 0 0 ⎟ -- > ⎜ . . . ⎟ -- > ⎜ . . . ⎟ -- > ⎜ . . . ⎟ -- > ⎜ 0 0 … 1 0 ⎟ -- > ⎝ 0 0 … 0 1 ⎠ identityMatrix = AccMatrix $ A.use $ A.fromFunction (Z:.n':.n') aux where aux :: DIM2 -> a aux (Z:.i:.j) = if i == j then 1 else 0 n' = fromIntegral $ natVal (Proxy :: Proxy n) zeroV :: forall n a. (KnownNat n, Num a, A.Num a, Elt a) => AccVector n a -- | constructor for the n dimensional zero vector, given by -- -- > ⎛ 0 ⎞ -- > ⎜ . ⎟ -- > ⎜ . ⎟ -- > ⎜ . ⎟ -- > ⎜ . ⎟ -- > ⎜ . ⎟ -- > ⎝ 0 ⎠ zeroV = unsafeMkVector $ replicate n' 0 where n' = fromIntegral $ natVal (Proxy :: Proxy n) zeroM :: forall m n a. (KnownNat m, KnownNat n, Num a, A.Num a, Elt a) => AccMatrix m n a -- | constructor for the mxn dimensional zero matrix, given by -- -- > ⎛ 0 0 … 0 0 ⎞ -- > ⎜ 0 0 … 0 0 ⎟ -- > ⎜ . . . . ⎟ -- > ⎜ 0 0 … 0 0 ⎟ -- > ⎝ 0 0 … 0 0 ⎠ zeroM = unsafeMkMatrix $ replicate (m'*n') 0 where n' = fromIntegral $ natVal (Proxy :: Proxy n) m' = fromIntegral $ natVal (Proxy :: Proxy m) (#*^) :: forall m n a. (KnownNat m, KnownNat n, A.Num a, Elt a) => AccMatrix m n a -> AccVector n a -> AccVector n a -- | the usual matrix-vector product -- -- > ⎛ w₁₁ w₁₂ … w₁ₙ ⎞ ⎛x₁⎞ ⎛ w₁₁*x₁ + w₁₂*x₂ + … w₁ₙ*xₙ ⎞ -- > ⎜ w₂₁ w₂₂ … w₂ₙ ⎟ ⎜x₂⎟ ⎜ w₂₁*x₁ + w₂₂*x₂ + … w₂ₙ*xₙ ⎟ -- > ⎜ . . . ⎟ ⎜. ⎟ ⎜ . . . ⎟ -- > ⎜ . . . ⎟ ✕ ⎜. ⎟ = ⎜ . . . ⎟ -- > ⎜ . . . ⎟ ⎜. ⎟ ⎜ . . . ⎟ -- > ⎜ . . . ⎟ ⎜. ⎟ ⎜ . . . ⎟ -- > ⎝ wₘ₁ wₘ₂ … wₘₙ ⎠ ⎝xₙ⎠ ⎝ wₘ₁*x₁ + wₘ₂*x₂ + … wₘₙ*xₙ ⎠ ma #*^ va = let ma' = unMatrix ma va' = unVector va in AccVector $ A.fold1 (+) $ A.zipWith (*) ma' (A.replicate (A.lift $ Z :. m' :. All) va') where m' = fromIntegral $ natVal (Proxy :: Proxy m) :: Int infixl 7 #*^ (^*#) :: forall m n a. (KnownNat m, KnownNat n, A.Num a, Elt a) => AccVector m a -> AccMatrix m n a -> AccVector n a -- | the usual vector-matrix product -- -- > ⎛x₁⎞T ⎛w₁₁ w₁₂ … w₁ₙ ⎞ ⎛ x₁*w₁₁ + x₂*w₁₂ + … xₙ*w₁ₙ ⎞ -- > ⎜x₂⎟ ⎜w₂₁ w₂₂ … w₂ₙ ⎟ ⎜ x₁*w₂₁ + x₂*w₂₂ + … xₙ*w₂ₙ ⎟ -- > ⎜. ⎟ ⎜ . . . ⎟ ⎜ . . . ⎟ -- > ⎜. ⎟ ✕ ⎜ . . . ⎟ = ⎜ . . . ⎟ -- > ⎜. ⎟ ⎜ . . . ⎟ ⎜ . . . ⎟ -- > ⎜. ⎟ ⎜ . . . ⎟ ⎜ . . . ⎟ -- > ⎝xₘ⎠ ⎝wₘ₁ wₘ₂ … wₘₙ ⎠ ⎝ x₁*wₘ₁ + x₂*wₘ₂ + … xₙ*wₘₙ ⎠ va ^*# ma = let va' = unVector va ma' = unMatrix ma in AccVector $ A.fold1 (+) $ A.zipWith (*) (A.replicate (A.lift $ Z :. n' :. All) va') ma' where n' = fromIntegral $ natVal (Proxy :: Proxy n) :: Int infixr 7 ^*# (^+^) :: forall n a. (KnownNat n, A.Num a, Elt a) => AccVector n a -> AccVector n a -> AccVector n a -- | the usual vector addition -- -- > ⎛v₁⎞ ⎛w₁⎞ ⎛ v₁+w₁ ⎞ -- > ⎜v₂⎟ ⎜w₂⎟ ⎜ v₂+w₁ ⎟ -- > ⎜. ⎟ ⎜. ⎟ ⎜ . ⎟ -- > ⎜. ⎟ + ⎜. ⎟ = ⎜ . ⎟ -- > ⎜. ⎟ ⎜. ⎟ ⎜ . ⎟ -- > ⎜. ⎟ ⎜. ⎟ ⎜ . ⎟ -- > ⎝vₙ⎠ ⎝wₙ⎠ ⎝ vₙ+wₙ ⎠ v ^+^ w = AccVector $ A.zipWith (+) (unVector v) (unVector w) -- | the usual vector subtraction -- -- > ⎛v₁⎞ ⎛w₁⎞ ⎛ v₁-w₁ ⎞ -- > ⎜v₂⎟ ⎜w₂⎟ ⎜ v₂-w₁ ⎟ -- > ⎜. ⎟ ⎜. ⎟ ⎜ . ⎟ -- > ⎜. ⎟ - ⎜. ⎟ = ⎜ . ⎟ -- > ⎜. ⎟ ⎜. ⎟ ⎜ . ⎟ -- > ⎜. ⎟ ⎜. ⎟ ⎜ . ⎟ -- > ⎝vₙ⎠ ⎝wₙ⎠ ⎝ vₙ-wₙ ⎠ (^-^) :: forall n a. (KnownNat n, A.Num a, Elt a) => AccVector n a -> AccVector n a -> AccVector n a v ^-^ w = AccVector $ A.zipWith (-) (unVector v) (unVector w) infixl 6 ^+^ infixl 6 ^-^ (^*^) :: forall n a. (KnownNat n, A.Num a, Elt a) => AccVector n a -> AccVector n a -> AccScalar a -- | the usual inner product of two vectors -- -- > ⎛v₁⎞ ⎛w₁⎞ -- > ⎜v₂⎟ ⎜w₂⎟ -- > ⎜. ⎟ ⎜. ⎟ -- > ⎜. ⎟ * ⎜. ⎟ = v₁*w₁ + v₂*w₁ + … + vₙ*wₙ -- > ⎜. ⎟ ⎜. ⎟ -- > ⎜. ⎟ ⎜. ⎟ -- > ⎝vₙ⎠ ⎝wₙ⎠ v ^*^ w = AccScalar $ A.sum $ A.zipWith (*) (unVector v) (unVector w) infixl 7 ^*^ (#+#) :: forall m n a. (KnownNat m, KnownNat n, A.Num a, Elt a) => AccMatrix m n a -> AccMatrix m n a -> AccMatrix m n a -- | the usual matrix addition/subtraction -- -- > ⎛ v₁₁ v₁₂ … v₁ₙ ⎞ ⎛ w₁₁ w₁₂ … w₁ₙ ⎞ ⎛ v₁₁+w₁₁ v₁₂+w₁₂ … v₁ₙ+w₁ₙ ⎞ -- > ⎜ v₂₁ v₂₂ … v₂ₙ ⎟ ⎜ w₂₁ w₂₂ … w₂ₙ ⎟ ⎜ v₂₁+w₂₁ v₂₂+w₂₂ … v₂ₙ+w₂ₙ ⎟ -- > ⎜ . . . ⎟ ⎜ . . . ⎟ ⎜ . . . ⎟ -- > ⎜ . . . ⎟ + ⎜ . . . ⎟ = ⎜ . . . ⎟ -- > ⎜ . . . ⎟ ⎜ . . . ⎟ ⎜ . . . ⎟ -- > ⎜ . . . ⎟ ⎜ . . . ⎟ ⎜ . . . ⎟ -- > ⎝ vₘ₁ vₘ₂ … vₘₙ ⎠ ⎝ wₘ₁ wₘ₂ … wₘₙ ⎠ ⎝ vₘ₁+wₘ₁ wₘ₂+vₘ₂ … vₘₙ+wₘₙ ⎠ v #+# w = AccMatrix $ A.zipWith (+) (unMatrix v) (unMatrix w) (#-#) :: forall m n a. (KnownNat m, KnownNat n, A.Num a, Elt a) => AccMatrix m n a -> AccMatrix m n a -> AccMatrix m n a -- | the usual matrix addition/subtraction -- -- > ⎛ v₁₁ v₁₂ … v₁ₙ ⎞ ⎛ w₁₁ w₁₂ … w₁ₙ ⎞ ⎛ v₁₁+w₁₁ v₁₂+w₁₂ … v₁ₙ+w₁ₙ ⎞ -- > ⎜ v₂₁ v₂₂ … v₂ₙ ⎟ ⎜ w₂₁ w₂₂ … w₂ₙ ⎟ ⎜ v₂₁+w₂₁ v₂₂+w₂₂ … v₂ₙ+w₂ₙ ⎟ -- > ⎜ . . . ⎟ ⎜ . . . ⎟ ⎜ . . . ⎟ -- > ⎜ . . . ⎟ + ⎜ . . . ⎟ = ⎜ . . . ⎟ -- > ⎜ . . . ⎟ ⎜ . . . ⎟ ⎜ . . . ⎟ -- > ⎜ . . . ⎟ ⎜ . . . ⎟ ⎜ . . . ⎟ -- > ⎝ vₘ₁ vₘ₂ … vₘₙ ⎠ ⎝ wₘ₁ wₘ₂ … wₘₙ ⎠ ⎝ vₘ₁+wₘ₁ wₘ₂+vₘ₂ … vₘₙ+wₘₙ ⎠ v #-# w = AccMatrix $ A.zipWith (-) (unMatrix v) (unMatrix w) infixl 6 #+# infixl 6 #-# (#*#) :: forall k m n a. (KnownNat k, KnownNat m, KnownNat n, A.Num a, Elt a) => AccMatrix k m a -> AccMatrix m n a -> AccMatrix k n a -- | the usual matrix multiplication -- -- > ⎛ v₁₁ v₁₂ … v₁ₘ ⎞ ⎛ w₁₁ w₁₂ … w₁ₙ ⎞ ⎛ (v₁₁*w₁₁+v₁₂*w₂₁+…+v₁ₘ*wₘ₁) . . . (v₁₁*w₁ₙ+v₁₂*w₂ₙ+…+v₁ₘ*wₘₙ) ⎞ -- > ⎜ v₂₁ v₂₂ … v₂ₘ ⎟ ⎜ w₂₁ w₂₂ … w₂ₙ ⎟ ⎜ . . ⎟ -- > ⎜ . . . ⎟ ⎜ . . . ⎟ ⎜ . . ⎟ -- > ⎜ . . . ⎟ * ⎜ . . . ⎟ = ⎜ . . ⎟ -- > ⎜ . . . ⎟ ⎜ . . . ⎟ ⎜ . . ⎟ -- > ⎜ . . . ⎟ ⎜ . . . ⎟ ⎜ . . ⎟ -- > ⎝ vₖ₁ vₖ₂ … vₖₘ ⎠ ⎝ wₘ₁ wₘ₂ … wₘₙ ⎠ ⎝ (vₖ₁*w₁₁+vₖ₂*w₂₁+…+vₖₘ*wₘ₁) . . . (vₖ₁*w₁ₙ+vₖ₂*w₂ₙ+…+vₖₘ*wₘₙ) ⎠ v #*# w = AccMatrix $ A.fold1 (+) $ A.backpermute (A.lift $ Z:.ek:.en:.em ) reindex $ A.zipWith (*) v' w' where [k',m',n'] = map fromIntegral [ natVal (Proxy :: Proxy k) , natVal (Proxy :: Proxy m) , natVal (Proxy :: Proxy n)] :: [Int] [ek,em,en] = map fromIntegral [k',m',n'] :: [Exp Int] v' = A.replicate (A.lift $ Any:.All:.All:.k') (unMatrix v) w' = A.replicate (A.lift $ Any:.n':.All:.All) (unMatrix w) reindex :: Exp DIM3 -> Exp DIM3 reindex ix = let (Z:.i:.t:.j) = A.unlift ix in A.lift (Z:.i:.j:.t :: Z :. Exp Int :. Exp Int :. Exp Int) infixl 7 #*# (.*^) :: forall n a. (KnownNat n, A.Num a, Elt a) => Exp a -> AccVector n a -> AccVector n a -- | the usual multiplication of a scalar with a vector -- -- > ⎛x₁⎞ ⎛ a*x₁ ⎞ -- > ⎜x₂⎟ ⎜ a*x₂ ⎟ -- > ⎜. ⎟ ⎜ . ⎟ -- > a • ⎜. ⎟ = ⎜ . ⎟ -- > ⎜. ⎟ ⎜ . ⎟ -- > ⎜. ⎟ ⎜ . ⎟ -- > ⎝xₙ⎠ ⎝ a*xₙ ⎠ a .*^ v = let v' = unVector v in AccVector $ A.map (* a) v' (./^) :: forall n a. (KnownNat n, A.Floating a, Elt a) => Exp a -> AccVector n a -> AccVector n a -- | a convenient helper deviding every element of a vector -- -- > ⎛x₁⎞ ⎛ x₁/a ⎞ -- > ⎜x₂⎟ ⎜ x₂/a ⎟ -- > ⎜. ⎟ ⎜ . ⎟ -- > a / ⎜. ⎟ = ⎜ . ⎟ -- > ⎜. ⎟ ⎜ . ⎟ -- > ⎜. ⎟ ⎜ . ⎟ -- > ⎝xₙ⎠ ⎝ xₙ/a ⎠ a ./^ v = let v' = unVector v in AccVector $ A.map (/ a) v' infixl 7 .*^ infixl 7 ./^ (.*#) :: forall m n a. (KnownNat m, KnownNat n, A.Num a, Elt a) => Exp a -> AccMatrix m n a -> AccMatrix m n a -- | the usual multiplication of a scalar with a matrix -- -- > ⎛ w₁₁ w₁₂ … w₁ₙ ⎞ ⎛ a*w₁₁ a*w₁₂ … a*w₁ₙ ⎞ -- > ⎜ w₂₁ w₂₂ … w₂ₙ ⎟ ⎜ a*w₂₁ a*w₂₂ … a*w₂ₙ ⎟ -- > ⎜ . . . ⎟ ⎜ . . . ⎟ -- > a • ⎜ . . . ⎟ = ⎜ . . . ⎟ -- > ⎜ . . . ⎟ ⎜ . . . ⎟ -- > ⎜ . . . ⎟ ⎜ . . . ⎟ -- > ⎝ wₘ₁ wₘ₂ … wₘₙ ⎠ ⎝ a*wₘ₁ a*wₘ₂ … a*wₘₙ ⎠ a .*# v = let v' = unMatrix v in AccMatrix $ A.map (* a) v' (./#) :: forall m n a. (KnownNat m ,KnownNat n, A.Floating a, Elt a) => Exp a -> AccMatrix m n a -> AccMatrix m n a -- | a convenient helper deviding every element of a matrix -- -- > ⎛ w₁₁ w₁₂ … w₁ₙ ⎞ ⎛ w₁₁/a w₁₂/a … w₁ₙ/a ⎞ -- > ⎜ w₂₁ w₂₂ … w₂ₙ ⎟ ⎜ w₂₁/a w₂₂/a … w₂ₙ/a ⎟ -- > ⎜ . . . ⎟ ⎜ . . . ⎟ -- > a / ⎜ . . . ⎟ = ⎜ . . . ⎟ -- > ⎜ . . . ⎟ ⎜ . . . ⎟ -- > ⎜ . . . ⎟ ⎜ . . . ⎟ -- > ⎝ wₘ₁ wₘ₂ … wₘₙ ⎠ ⎝ wₘ₁/a wₘ₂/a … wₘₙ/a ⎠ a ./# v = let v' = unMatrix v in AccMatrix $ A.map (/ a) v' infixl 7 .*# infixl 7 ./# (#**.) :: forall n a. (KnownNat n, A.Num a, Num a, Elt a) => AccMatrix n n a -> Int -> AccMatrix n n a -- | the exponentiation of a square matrix with an `Int`. Negative exponents -- raise an error - as inverse matrices are not yet implemented. -- -- > ⎛ v₁₁ v₁₂ … v₁ₙ ⎞ k -- > ⎜ v₂₁ v₂₂ … v₂ₙ ⎟ -- > ⎜ . . . ⎟ -- > ⎜ . . . ⎟ -- > ⎜ . . . ⎟ -- > ⎜ . . . ⎟ -- > ⎝ vₙ₁ vₙ₂ … vₙₙ ⎠ _ #**. 0 = identityMatrix v #**. 1 = v v #**. i | i < 0 = error $ "no negative exponents allowed in matrix exponetiation," ++ "inverse function not yet implemented" | otherwise = (v#**. (i-1)) #*# v infixr 8 #**. transpose :: forall m n a. (KnownNat m, KnownNat n, Elt a) => AccMatrix m n a -> AccMatrix n m a -- | transpose for matrices - note the dimension of the matrix change. transpose = AccMatrix . A.transpose . unMatrix zipWithM :: forall m n a b c. (KnownNat m, KnownNat n, Elt a, Elt b, Elt c) => (Exp a -> Exp b -> Exp c) -> AccMatrix m n a -> AccMatrix m n b -> AccMatrix m n c -- | the pendant of the usual zipWith function for matrices, but can only be -- used with the same dimensions for both input zipWithM f ma mb = AccMatrix $ A.zipWith f (unMatrix ma) (unMatrix mb) zipWithV :: forall n a b c. (KnownNat n, Elt a, Elt b, Elt c) => (Exp a -> Exp b -> Exp c) -> AccVector n a -> AccVector n b -> AccVector n c -- | the pendant of the usual zipWith function for vectors, but can only be -- used with the same dimensions for both input zipWithV f ma mb = AccVector $ A.zipWith f (unVector ma) (unVector mb)
epsilonhalbe/accelerate-typelits
src/Data/Array/Accelerate/TypeLits.hs
isc
15,279
0
15
5,719
2,992
1,673
1,319
152
2
module Main where fib :: Integer -> Integer fib 0 = 1 fib 1 = 1 fib x = fib(x - 1) + fib(x - 2) main = print(fib(8))
skywind3000/language
haskell/fib.hs
mit
149
0
8
61
78
41
37
6
1
module Main where import qualified Data.Map as M import System.Environment (getArgs) import System.Exit (exitFailure) import System.IO (hPrint, stderr) import qualified Language.CFrp.Syntax as S import Language.CFrp.Parser (parseProgramString) import Language.CFrp.TypeInf (typeInf) import Language.CFrp.KNormal (kNormalize) import Language.CFrp.Closure (closureConvert) import Language.CFrp.CodeGen (codeGen) die :: Show a => a -> IO () die e = hPrint stderr e >> exitFailure main :: IO () main = do path:_ <- getArgs src <- readFile path case parseProgramString path src of Left err -> die err Right (decls, expr) -> do let (inputEnv, importEnv, codes) = partitionDecls decls case typeInf (M.map fst $ inputEnv `M.union` importEnv) expr of Left err -> die err Right texpr -> do let c = closureConvert $ kNormalize texpr mapM_ putStrLn $ codeGen (M.map snd inputEnv) (M.map snd importEnv) codes c type Env = M.Map String (S.Type, String) partitionDecls :: [S.ParsedDecl] -> (Env, Env, [String]) partitionDecls [] = (M.empty, M.empty, []) partitionDecls (S.InputD hSym t cSym _ : xs) = let (ienv, menv, codes) = partitionDecls xs in (M.insert hSym (t, cSym) ienv, menv, codes) partitionDecls (S.ImportD hSym t cSym _ : xs) = let (ienv, menv, codes) = partitionDecls xs in (ienv, M.insert hSym (t, cSym) menv, codes) partitionDecls (S.EmbedD code _ : xs) = let (ienv, menv, codes) = partitionDecls xs in (ienv, menv, code:codes)
psg-titech/cfrp
Main.hs
mit
1,508
0
21
295
631
336
295
38
3
{-# LANGUAGE RecordWildCards #-} module Learning.IOHMM ( IOHMM (..) , LogLikelihood , init , withEmission , euclideanDistance , viterbi , baumWelch , baumWelch' , simulate ) where import Control.Applicative ( (<$>) ) import Control.Arrow ( first ) import Data.List ( elemIndex ) import Data.Maybe ( fromJust ) import Data.Random.Distribution ( rvar ) import qualified Data.Random.Distribution.Categorical as C ( Categorical, fromList, normalizeCategoricalPs ) import Data.Random.Distribution.Extra ( pmf ) import Data.Random.RVar ( RVar ) import qualified Data.Vector as V ( elemIndex, fromList, map, toList, unsafeIndex ) import qualified Data.Vector.Generic as G ( convert ) import qualified Data.Vector.Unboxed as U ( fromList, zip ) import qualified Numeric.LinearAlgebra.Data as H ( (!), fromList, fromLists, toList ) import qualified Numeric.LinearAlgebra.HMatrix as H ( tr ) import Learning.IOHMM.Internal ( LogLikelihood ) import qualified Learning.IOHMM.Internal as I import Prelude hiding ( init ) -- | Parameter set of the input-output hidden Markov model with discrete emission. -- This 'IOHMM' assumes that the inputs affect only the transition -- probabilities. The model schema is as follows. -- -- @ -- x_0 x_1 x_n -- | | -- v v -- z_0 -> z_1 -> ... -> z_n -- | | | -- v v v -- y_0 y_1 y_n -- @ -- -- Here, @[x_0, x_1, ..., x_n]@ are given inputs, @[z_0, z_1, ..., z_n]@ -- are hidden states, and @[y_0, y_1, ..., y_n]@ are observed outputs. -- @z_0@ is determined by the 'initialStateDist'. -- For @i = 1, ..., n@, @z_i@ is determined by the 'transitionDist' -- conditioned by @x_i@ and @z_{i-1}@. -- For @i = 0, ..., n@, @y_i@ is determined by the 'emissionDist' -- conditioned by @z_i@. data IOHMM i s o = IOHMM { inputs :: [i] , states :: [s] , outputs :: [o] , initialStateDist :: C.Categorical Double s -- ^ Categorical distribution of initial state , transitionDist :: i -> s -> C.Categorical Double s -- ^ Categorical distribution of next state -- conditioned by the input and previous state , emissionDist :: s -> C.Categorical Double o -- ^ Categorical distribution of output conditioned -- by the hidden state } instance (Show i, Show s, Show o) => Show (IOHMM i s o) where show IOHMM {..} = "IOHMM {inputs = " ++ show inputs ++ ", states = " ++ show states ++ ", outputs = " ++ show outputs ++ ", initialStateDist = " ++ show initialStateDist ++ ", transitionDist = " ++ show [(transitionDist i s, (i, s)) | i <- inputs, s <- states] ++ ", emissionDist = " ++ show [(emissionDist s, s) | s <- states] ++ "}" -- | @init inputs states outputs@ returns a random variable of models with the -- @inputs@, @states@, and @outputs@, wherein parameters are sampled from uniform -- distributions. init :: (Eq i, Eq s, Eq o) => [i] -> [s] -> [o] -> RVar (IOHMM i s o) init is ss os = fromInternal is ss os <$> I.init (length is) (length ss) (length os) -- | @withEmission model xs ys@ returns a model in which the -- 'emissionDist' is updated by re-estimations using the inputs @xs@ and -- outputs @ys@. The 'emissionDist' is set to be normalized histograms -- each of which is calculated from segumentations of @ys@ based on the -- Viterbi state path. -- If the lengths of @xs@ and @ys@ are different, the longer one is cut -- by the length of the shorter one. withEmission :: (Eq i, Eq s, Eq o) => IOHMM i s o -> [i] -> [o] -> IOHMM i s o withEmission (model @ IOHMM {..}) xs ys = fromInternal inputs states outputs $ I.withEmission model' $ U.zip xs' ys' where inputs' = V.fromList inputs outputs' = V.fromList outputs model' = toInternal model xs' = U.fromList $ fromJust $ mapM (`V.elemIndex` inputs') xs ys' = U.fromList $ fromJust $ mapM (`V.elemIndex` outputs') ys -- | Return the Euclidean distance between two models that have the same -- inputs, states, and outputs. euclideanDistance :: (Eq i, Eq s, Eq o) => IOHMM i s o -> IOHMM i s o -> Double euclideanDistance model1 model2 = checkTwoModelsIn "euclideanDistance" model1 model2 `seq` I.euclideanDistance model1' model2' where model1' = toInternal model1 model2' = toInternal model2 -- | @viterbi model xs ys@ performs the Viterbi algorithm using the inputs -- @xs@ and outputs @ys@, and returns the most likely state path and its -- log likelihood. -- If the lengths of @xs@ and @ys@ are different, the longer one is cut -- by the length of the shorter one. viterbi :: (Eq i, Eq s, Eq o) => IOHMM i s o -> [i] -> [o] -> ([s], LogLikelihood) viterbi (model @ IOHMM {..}) xs ys = checkModelIn "viterbi" model `seq` checkDataIn "viterbi" model xs ys `seq` first toStates $ I.viterbi model' $ U.zip xs' ys' where inputs' = V.fromList inputs states' = V.fromList states outputs' = V.fromList outputs model' = toInternal model xs' = U.fromList $ fromJust $ mapM (`V.elemIndex` inputs') xs ys' = U.fromList $ fromJust $ mapM (`V.elemIndex` outputs') ys toStates = V.toList . V.map (V.unsafeIndex states') . G.convert -- | @baumWelch model xs ys@ iteratively performs the Baum-Welch algorithm -- using the inputs @xs@ and outputs @ys@, and returns a list of updated -- models and their corresponding log likelihoods. -- If the lengths of @xs@ and @ys@ are different, the longer one is cut -- by the length of the shorter one. baumWelch :: (Eq i, Eq s, Eq o) => IOHMM i s o -> [i] -> [o] -> [(IOHMM i s o, LogLikelihood)] baumWelch (model @ IOHMM {..}) xs ys = checkModelIn "baumWelch" model `seq` checkDataIn "baumWelch" model xs ys `seq` map (first $ fromInternal inputs states outputs) $ I.baumWelch model' $ U.zip xs' ys' where inputs' = V.fromList inputs outputs' = V.fromList outputs model' = toInternal model xs' = U.fromList $ fromJust $ mapM (`V.elemIndex` inputs') xs ys' = U.fromList $ fromJust $ mapM (`V.elemIndex` outputs') ys -- | @baumWelch' model xs@ performs the Baum-Welch algorithm using the -- inputs @xs@ and outputs @ys@, and returns a model locally maximizing -- its log likelihood. baumWelch' :: (Eq i, Eq s, Eq o) => IOHMM i s o -> [i] -> [o] -> (IOHMM i s o, LogLikelihood) baumWelch' (model @ IOHMM {..}) xs ys = checkModelIn "baumWelch" model `seq` checkDataIn "baumWelch" model xs ys `seq` first (fromInternal inputs states outputs) $ I.baumWelch' model' $ U.zip xs' ys' where inputs' = V.fromList inputs outputs' = V.fromList outputs model' = toInternal model xs' = U.fromList $ fromJust $ mapM (`V.elemIndex` inputs') xs ys' = U.fromList $ fromJust $ mapM (`V.elemIndex` outputs') ys -- | @simulate model xs@ generates a Markov process coinciding with the -- inputs @xs@ using the @model@, and returns its state path and observed -- outputs. simulate :: IOHMM i s o -> [i] -> RVar ([s], [o]) simulate IOHMM {..} xs | null xs = return ([], []) | otherwise = do s0 <- rvar initialStateDist y0 <- rvar $ emissionDist s0 unzip . ((s0, y0) :) <$> sim s0 (tail xs) where sim _ [] = return [] sim s (x:xs') = do s' <- rvar $ transitionDist x s y' <- rvar $ emissionDist s' ((s', y') :) <$> sim s' xs' -- | Check if the model is valid in the sense of whether the 'states' and -- 'outputs' are not empty. checkModelIn :: String -> IOHMM i s o -> () checkModelIn fun IOHMM {..} | null inputs = errorIn fun "empty inputs" | null states = errorIn fun "empty states" | null outputs = errorIn fun "empty outputs" | otherwise = () -- | Check if the two models have the same inputs, states, and outputs. checkTwoModelsIn :: (Eq i, Eq s, Eq o) => String -> IOHMM i s o -> IOHMM i s o -> () checkTwoModelsIn fun model model' | is /= is' = errorIn fun "inputs disagree" | ss /= ss' = errorIn fun "states disagree" | os /= os' = errorIn fun "outputs disagree" | otherwise = () where is = inputs model is' = inputs model' ss = states model ss' = states model' os = outputs model os' = outputs model' -- | Check if all the elements of the given inputs (outputs) are contained -- in the 'inputs' ('outputs') of the model. checkDataIn :: (Eq i, Eq o) => String -> IOHMM i s o -> [i] -> [o] -> () checkDataIn fun IOHMM {..} xs ys | any (`notElem` inputs) xs = errorIn fun "illegal input data" | any (`notElem` outputs) ys = errorIn fun "illegal output data" | any (`notElem` xs) inputs = errorIn fun "insufficient input data" | otherwise = () -- | Convert internal 'IOHMM' to 'IOHMM'. fromInternal :: (Eq i, Eq s, Eq o) => [i] -> [s] -> [o] -> I.IOHMM -> IOHMM i s o fromInternal is ss os I.IOHMM {..} = IOHMM { inputs = is , states = ss , outputs = os , initialStateDist = C.fromList pi0' , transitionDist = \i s -> case (elemIndex i is, elemIndex s ss) of (Nothing, _) -> C.fromList [] (_, Nothing) -> C.fromList [] (Just j, Just k) -> C.fromList $ w' j k , emissionDist = \s -> case elemIndex s ss of Nothing -> C.fromList [] Just i -> C.fromList $ phi' i } where pi0' = zip (H.toList initialStateDist) ss w' j k = zip (H.toList $ V.unsafeIndex transitionDist j H.! k) ss phi' i = zip (H.toList $ H.tr emissionDistT H.! i) os -- | Convert 'IOHMM' to internal 'IOHMM'. The 'initialStateDist'', -- 'transitionDist'', and 'emissionDistT'' are normalized. toInternal :: (Eq i, Eq s, Eq o) => IOHMM i s o -> I.IOHMM toInternal IOHMM {..} = I.IOHMM { I.nInputs = length inputs , I.nStates = length states , I.nOutputs = length outputs , I.initialStateDist = pi0 , I.transitionDist = w , I.emissionDistT = phi' } where pi0_ = C.normalizeCategoricalPs initialStateDist w_ i = C.normalizeCategoricalPs . transitionDist i phi_ = C.normalizeCategoricalPs . emissionDist pi0 = H.fromList [pmf pi0_ s | s <- states] w = V.fromList $ map (\i -> H.fromLists [[pmf (w_ i s) s' | s' <- states] | s <- states]) inputs phi' = H.fromLists [[pmf (phi_ s) o | s <- states] | o <- outputs] errorIn :: String -> String -> a errorIn fun msg = error $ "Learning.IOHMM." ++ fun ++ ": " ++ msg
mnacamura/learning-hmm
src/Learning/IOHMM.hs
mit
12,080
13
19
4,175
2,934
1,584
1,350
152
4
{-| Module : EU4.Missions Description : Feature handler for Europa Universalis IV missions -} module EU4.Missions where import Control.Monad.Except (MonadError (..)) import Data.Text (Text) import qualified Data.Text as T import System.FilePath (FilePath) import Text.PrettyPrint.Leijen.Text (Doc) import Abstract -- everything import SettingsTypes (PPT) processMission :: MonadError Text m => GenericStatement -> PPT g m [Either Text (FilePath, Doc)] processMission _ = throwError "not implemented"
HairyDude/pdxparse
src/EU4/Missions.hs
mit
511
0
10
74
124
74
50
-1
-1
module Sudoku.TaskReader ( parseTask, readTask ) where import Sudoku.Sudoku import Data.Char (isDigit,isSpace) import System.IO (readFile) import Control.Applicative((<$>),(<*>)) -- | Replace all non-relevant chars with spaces for the sake of simpler parsing. cook :: [Char] -> [Char] cook = foldr (\x a -> replace x : a) [] where replace x = if isDigit x || isSpace x then x else ' ' -- | Open file and get its contents as puzzle. parseInt :: String -> [[Int]] parseInt = map ( map read . filter ( (&&) <$> all isDigit <*> not . null) . words) . filter (any isDigit) . lines . cook parseTask :: String -> [Cell Int] parseTask = getTask . parseInt readTask :: FilePath -> IO [Cell Int] readTask name = parseTask <$> readFile name
sukhmel/experiments.haskell
Sudoku/TaskReader.hs
mit
889
0
17
288
271
149
122
23
2
/*Owner & Copyrights: Vance King Saxbe. A.*//* Copyright (c) <2014> Author Vance King Saxbe. A, and contributors Power Dominion Enterprise, Precieux Consulting and other contributors. Modelled, Architected and designed by Vance King Saxbe. A. with the geeks from GoldSax Consulting and GoldSax Technologies email @[email protected]. Development teams from Power Dominion Enterprise, Precieux Consulting. Project sponsored by GoldSax Foundation, GoldSax Group and executed by GoldSax Manager.*/{-# Modelled, Architected and designed by Vance King Saxbe. A. with the geeks from GoldSax Consulting, GoldSax Money, GoldSax Treasury, GoldSax Finance, GoldSax Banking and GoldSax Technologies email @[email protected]. Development teams from Power Dominion Enterprise, Precieux Consulting. This Engagement sponsored by GoldSax Foundation, GoldSax Group and executed by GoldSax Manager. LANGUAGE DeriveFunctor #-} module GoldSaxMachineModule16.FreeMonads where import Control.Monad.Free import Data.Char import Data.List newtype ClientId = ClientId Integer deriving Show data Client = Client { clientName :: String } deriving Show data AdminOp r = GetClient ClientId (Client -> r) | SaveClient ClientId Client r | NewClient Client (ClientId -> r) deriving Functor type Admin = Free AdminOp getClient :: ClientId -> Admin Client getClient i = liftF $ GetClient i id saveClient :: ClientId -> Client -> Admin () saveClient i c = liftF $ SaveClient i c () newClient :: Client -> Admin ClientId newClient c = liftF $ NewClient c id exampleAdmin :: String -> Admin String exampleAdmin s = do i <- newClient $ Client s n <- fmap clientName $ getClient i return $ map toUpper n runAdmin :: Admin a -> ([(Integer,Client)],a) runAdmin m = runAdmin' m [] where runAdmin' (Free (GetClient (ClientId i) n)) l = let Just c = lookup i l in runAdmin' (n c) l runAdmin' (Free (SaveClient (ClientId i) c n)) l = let l' = deleteBy (\(j,_) (k,_) -> j == k) (i, c) l in runAdmin' n $ (i,c):l' runAdmin' (Free (NewClient c n)) [] = runAdmin' (n $ ClientId 1) [(1,c)] runAdmin' (Free (NewClient c n)) l = let (i',_) = maximumBy (\(j,_) (k,_) -> compare j k) l in runAdmin' (n $ ClientId (i' + 1)) $ (i' + 1,c):l runAdmin' (Pure c) l = (l, c) /*email to provide support at [email protected], [email protected], For donations please write to [email protected]*/
VanceKingSaxbeA/GoldSaxMachineStore
GoldSaxMachineModule16/src/Chapter16/FreeMonads.hs
mit
2,644
23
16
610
900
463
437
34
5
-- 4h main = print $ answer 1 2 answer :: Int -> Int -> Int answer t n | length (factors t) > 500 = t | otherwise = answer (t+n) (n+1) factors :: Int -> [Int] factors n = [ x | x <- [1..n], n `mod` x == 0 ]
lekto/haskell
Project-Euler-Solutions/problem0012.hs
mit
220
0
11
66
136
70
66
6
1
module Vector ( Vector, Dimension, innerProduct, (|*|), l2Norm, vectorSum, (|+|), scalaProduct, sign, ) where type Vector = [Double] type Dimension = Int innerProduct :: Vector -> Vector -> Double innerProduct x y = sum $ zipWith (*) x y (|*|) :: Vector -> Vector -> Double x |*| y = x `innerProduct` y vectorSum :: Vector -> Vector -> Vector vectorSum = zipWith (+) (|+|) :: Vector -> Vector -> Vector x |+| y = x `vectorSum` y scalaProduct :: Double -> Vector -> Vector scalaProduct x = map (*x) l2Norm :: Vector -> Double l2Norm x = sum $ map (^2) x sign :: Double -> Double sign x = if x >= 0 then 1.0 else -1.0
kenkov/nlp
haskell/learn/Vector.hs
mit
660
0
7
163
265
153
112
26
2
module Graphics.DrawGL.Util where import Data.Maybe import Graphics.DrawGL.Fold import Graphics.DrawGL.Internal import Graphics.DrawGL.Types fromPolar :: (Angle, Radius) -> Point fromPolar (a, r) = (-sin a * r, cos a * r) between :: Ord a => (a,a) -> a -> a between (min, max) v | v < min = min | v > max = max | otherwise = v boundingBox :: Shape -> (Point, Point) boundingBox = fromJust . foldShape step Nothing where step Nothing (Vertex p) = Just (p,p) step (Just ((minx,miny),(maxx,maxy))) (Vertex (x,y)) = Just ((min x minx, min y miny), ((max x maxx, max y maxy)))
shangaslammi/hdrawgl
src/Graphics/DrawGL/Util.hs
mit
611
1
11
137
301
165
136
17
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE UnicodeSyntax #-} module MasterPlan.Arbitrary () where import qualified Data.List.NonEmpty as NE import Data.Maybe (isNothing) import MasterPlan.Data import Test.QuickCheck import Test.QuickCheck.Instances () instance Arbitrary ProjectProperties where arbitrary = let s = getASCIIString <$> arbitrary maybeStr x = if null x then Nothing else Just x os = oneof [pure Nothing, maybeStr <$> s] titleG = Just <$> elements [[x] | x <- ['a'..'z']] in ProjectProperties <$> titleG <*> os <*> os <*> os shrink p = (if isNothing (description p) then [] else [p { description = Nothing }]) ++ (if isNothing (url p) then [] else [p { url = Nothing }]) ++ (if isNothing (owner p) then [] else [p { owner = Nothing }]) instance Arbitrary (Project a) where arbitrary = let shrinkFactor n = 3 * n `quot` 5 unitGen = elements [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] in frequency [ (1, Sum defaultProjectProps <$> scale shrinkFactor arbitrary) , (1, Product defaultProjectProps <$> scale shrinkFactor arbitrary) , (1, Sequence defaultProjectProps <$> scale shrinkFactor arbitrary) , (2, Atomic <$> arbitrary <*> (Cost <$> elements [0, 1 .. 100]) <*> (Trust <$> unitGen) <*> (Progress <$> unitGen)) ] shrink (Sum _ ps) = NE.toList ps shrink (Product _ ps) = NE.toList ps shrink (Sequence _ ps) = NE.toList ps shrink _ = []
rodrigosetti/master-plan
test/MasterPlan/Arbitrary.hs
mit
1,708
0
17
564
563
309
254
33
0
module Fao.Utils where import Data.List (deleteBy, foldl') import Data.Function (on) import Control.Monad (msum) import Control.Monad.Trans.Maybe import System.Log.FastLogger import System.IO.Unsafe (unsafePerformIO) import qualified Data.Set as S import Fao.Types findM :: (Monad m) => (a -> m (Maybe b)) -> [a] -> m (Maybe b) findM f = runMaybeT . msum . map (MaybeT . f) tileAt :: Board -> Pos -> Maybe Tile tileAt b p@(Pos x y) = if inBoard b p then Just $ boardTiles b !! idx else Nothing where idx = x * boardSize b + y isMineTileAt :: Board -> Pos -> Bool isMineTileAt board pos = case tileAt board pos of Just (MineTile _) -> True _ -> False inBoard :: Board -> Pos -> Bool inBoard b (Pos x y) = let s = boardSize b in x >= 0 && x < s && y >= 0 && y < s tilePosition :: Board -> [(Tile, Pos)] tilePosition (Board size tiles _ _) = zip tiles [Pos x y | x <- [0..size-1], y <- [0..size-1]] -- http://en.wikipedia.org/wiki/Taxicab_geometry manhattan :: Distance manhattan (Pos row1 col1) (Pos row2 col2) = abs (row1 - row2) + abs (col1 - col2) dirFromPos :: Pos -> Pos -> Dir dirFromPos (Pos fx fy) (Pos tx ty) = let x = tx - fx y = ty - fy in case (x, y) of (-1, 0) -> North (1, 0) -> South (0, -1) -> West (0, 1) -> East _ -> Stay adjacentTiles :: Board -> Pos -> S.Set Pos adjacentTiles board (Pos x y) = S.fromList $ foldl' (\ps p -> if inBoard board p then p:ps else ps) [] [Pos x $ y+1, Pos x $ y-1, Pos (x+1) y, Pos (x-1) y] -- get all heroes except our own one getEnemies :: Vindinium -> [Hero] getEnemies s = let hero = vindiniumHero s in deleteBy ((==) `on` heroId) hero (gameHeroes $ vindiniumGame s) isEnemyNearby :: Vindinium -> Pos -> Bool isEnemyNearby state pos = let board = gameBoard $ vindiniumGame state enemies = getEnemies state in pos `S.member` S.unions (map (adjacentTiles board . heroPos) enemies) {-# NOINLINE globalLogger #-} globalLogger :: LoggerSet globalLogger = unsafePerformIO $ newFileLoggerSet defaultBufSize "./debug.log"
ksaveljev/vindinium-bot
Fao/Utils.hs
mit
2,123
0
13
524
928
490
438
54
5
module Lib ( someFunc ) where import qualified Network.Wreq as Wreq import Data.Text (pack, unpack) import Control.Lens as Lens someFunc :: IO () someFunc = do r <- Wreq.get "http://httpbin.org/get" print (r ^. Wreq.responseBody) -- someFunc = do r <- Wreq.get "http://httpbin.org/get" -- r ^. Wreq.responseStatus -- putStrLn "someFunc" --
tripattern/haskell
restClient/src/Lib.hs
mit
379
0
10
89
82
48
34
8
1
module Cafe.CLI.Transformer ( CLI , runCLI , runDB , cliEventStore , cliGloballyOrderedEventStore ) where import Control.Monad.Reader import Database.Persist.Sql import Eventful import Eventful.Store.Sqlite type CLI = ReaderT ConnectionPool IO -- | Main entry point into a CLI program. runCLI :: ConnectionPool -> CLI a -> IO a runCLI pool action' = runReaderT action' pool -- | Run a given database action by using the connection pool from the Reader -- monad. runDB :: SqlPersistT IO a -> CLI a runDB query = do pool <- ask liftIO $ runSqlPool query pool cliEventStore :: (MonadIO m) => EventStore JSONString (SqlPersistT m) cliEventStore = sqliteEventStore defaultSqlEventStoreConfig cliGloballyOrderedEventStore :: (MonadIO m) => GloballyOrderedEventStore JSONString (SqlPersistT m) cliGloballyOrderedEventStore = sqlGloballyOrderedEventStore defaultSqlEventStoreConfig
jdreaver/eventful
examples/cafe/src/Cafe/CLI/Transformer.hs
mit
897
0
8
139
203
109
94
21
1
-- Boiled Eggs -- http://www.codewars.com/kata/52b5247074ea613a09000164/ module BoiledEggs where cookingTime :: Integer -> Integer cookingTime 0 = 0 cookingTime n = 5 * (1 + (n-1) `div` 8)
gafiatulin/codewars
src/7 kyu/BoiledEggs.hs
mit
191
0
10
29
55
32
23
4
1
module Graphics.Urho3D.Graphics.Internal.DebugRenderer( DebugRenderer , debugRendererCntx ) where import qualified Language.C.Inline as C import qualified Language.C.Inline.Context as C import qualified Language.C.Types as C import qualified Data.Map as Map -- | Debug geometry rendering component. Should be added only to the root scene node. data DebugRenderer debugRendererCntx :: C.Context debugRendererCntx = mempty { C.ctxTypesTable = Map.fromList [ (C.TypeName "DebugRenderer", [t| DebugRenderer |]) ] }
Teaspot-Studio/Urho3D-Haskell
src/Graphics/Urho3D/Graphics/Internal/DebugRenderer.hs
mit
542
0
11
93
102
70
32
-1
-1
{-# LANGUAGE OverloadedStrings #-} module KaitenZushi (server) where import Data.Aeson ((.=)) import Data.Aeson.Types import Control.Applicative import Control.Monad (mzero) import Control.Monad.Trans.State.Strict (StateT) import qualified Data.Aeson as Aeson import qualified Data.Text as Text import qualified Network.SocketIO as SocketIO import qualified Snap.Core as Snap --------------------------------------------------------- data SushiNeta = SushiNeta Text.Text instance Aeson.FromJSON SushiNeta where parseJSON (Object v) = SushiNeta <$> v .: "neta" parseJSON _ = mzero instance Aeson.ToJSON SushiNeta where toJSON (SushiNeta neta) = Aeson.object [ "neta" .= neta ] --------------------------------------------------------- server :: StateT SocketIO.RoutingTable Snap.Snap () server = do SocketIO.on "place" $ \(SushiNeta neta) -> SocketIO.broadcast "placed" (SushiNeta neta)
jewel12/KaitenZushi
KaitenZushi.hs
mit
912
0
11
124
236
136
100
22
1
-- The maximum sum value of ranges -- Simple version -- https://www.codewars.com/kata/583d10c03f02f41462000137 module Kata.MaxSumValRanges (maxSum) where import qualified Data.Vector as V maxSum :: [Int] -> [(Int,Int)] -> Int maxSum arr = maximum . map (\(s, e) -> V.sum . V.slice s (e - s + 1) $ v) where v = V.fromList arr
gafiatulin/codewars
src/6 kyu/MaxSumValRanges.hs
mit
332
0
14
60
115
66
49
5
1
module OidTable where import Data.Word import qualified Data.ByteString.Lazy as LB import Graphics.PDF import Control.Monad hiding (forM_) import Data.Foldable (forM_) import Data.List.Split import Text.Printf import Control.Arrow ((***)) import Codec.Compression.Zlib import OidCode import KnownCodes import Utils import Types oidTable :: Conf -> String -> [(String, Word16)] -> LB.ByteString oidTable conf title entries | entriesPerPage < 1 = error "OID codes too large to fit on a single page" | otherwise = pdfByteString docInfo a4rect $ do -- Replace codes by images entries' <- forM entries $ \(d,rc) -> case code2RawCode rc of Nothing -> return (d, Nothing) Just c -> do let twp = tilePixelSize (cDPI conf) (cPixelSize conf) let tw = fromIntegral twp / px image <- createPDFRawImageFromByteString twp twp False FlateDecode $ compressWith defaultCompressParams { compressLevel = defaultCompression } $ genRawPixels twp twp conf $ c pat <- createColoredTiling 0 0 tw tw tw tw NoDistortion $ do applyMatrix $ scale (1/px) (1/px) drawXObject image return (d, Just pat) let chunks = chunksOf entriesPerPage entries' let totalPages = length chunks forM_ (zip [1::Int ..] chunks) $ \(pageNum, thisPage) -> do page <- addPage Nothing drawWithPage page $ do displayFormattedText titleRect NormalParagraph titleFont $ do setJustification Centered paragraph $ txt title displayFormattedText footerRect NormalParagraph footerFont $ do setJustification LeftJustification paragraph $ txt $ "Created by tttool-" ++ tttoolVersion displayFormattedText footerRect NormalParagraph footerFont $ do setJustification RightJustification paragraph $ txt $ printf "%d/%d" pageNum totalPages forM_ (zip thisPage positions) $ \((e,mbi),p) -> do withNewContext $ do applyMatrix $ translate (align p) forM_ mbi $ \i -> withNewContext $ do setColoredFillPattern i fill (Rectangle (0 :+ (- alignToPx imageHeight)) (imageWidth :+ 0)) withNewContext $ do applyMatrix $ translate (0 :+ (-imageHeight - subtitleSep)) let fontRect = Rectangle (0 :+ (-subtitleHeight)) (imageWidth :+ 0) addShape fontRect setAsClipPath displayFormattedText fontRect NormalParagraph bodyFont $ do paragraph $ txt e where docInfo = standardDocInfo { author=toPDFString $ "tttool-" ++ tttoolVersion , compressed = False } -- Configure-dependent dimensions (all in pt) (imageWidth,imageHeight) = (*mm) *** (*mm) $ fromIntegral *** fromIntegral $cCodeDim conf -- Static dimensions (all in pt) -- Page paddings padTop, padLeft, padBot, padRight :: Double padTop = 1*cm padBot = 1*cm padLeft = 2*cm padRight = 2*cm titleHeight = 1*cm titleSep = 0.5*cm footerHeight = 0.5*cm footerSep = 0.5*cm imageSepH = 0.4*cm imageSepV = 0.2*cm subtitleHeight = 0.4*cm subtitleSep = 0.2*cm -- Derived dimensions (all in pt) titleRect = Rectangle (padLeft :+ (a4h - padTop - titleHeight)) ((a4w - padRight) :+ (a4h - padTop)) titleFont = Font (PDFFont Helvetica 12) black black footerRect = Rectangle (padLeft :+ padBot) ((a4w - padRight) :+ (padBot + footerHeight)) footerFont = Font (PDFFont Helvetica 8) black black bodyFont = Font (PDFFont Helvetica 8) black black bodyWidth = a4w - padLeft - padRight bodyHeight = a4h - padTop - titleHeight - titleSep - footerSep - footerHeight - padBot positions = map (+(padLeft :+ (padBot + footerHeight + footerSep))) $ calcPositions bodyWidth bodyHeight imageWidth (imageHeight + subtitleSep + subtitleHeight) imageSepH imageSepV entriesPerPage = length positions -- Derived dimensions (all in pixels) imageWidthPx = floor (imageWidth * px) imageHeightPx = floor (imageHeight * px) -- config-dependent conversion factors px :: Double px = fromIntegral (cDPI conf) / 72 -- Makes sure the given point is at a coordinate that is a multiple -- of an pixel align :: Point -> Point align pos = alignToPx (realPart pos) :+ (a4h - alignToPx (a4h - imagPart pos)) -- Makes sure the given distance is an interal mulitple of a pixel alignToPx :: Double -> Double alignToPx x = fromIntegral (floor (x * px)) / px calcPositions :: Double -- ^ total width -> Double -- ^ total height -> Double -- ^ entry width -> Double -- ^ entry height -> Double -- ^ pad width -> Double -- ^ pad height -> [Point] calcPositions tw th ew eh pw ph = [ x :+ (th - y) | y <- ys , x <- xs] where xs = [0,ew+pw..tw-ew] ys = [0,eh+ph..th-eh] -- Conversation factor cm :: Double cm = 28.3465 mm :: Double mm = 2.83465 -- A4 dimensions a4w, a4h :: Double a4w = 595 a4h = 842 a4rect :: PDFRect a4rect = PDFRect 0 0 595 842
entropia/tip-toi-reveng
src/OidTable.hs
mit
5,535
1
34
1,771
1,553
812
741
119
2
{-# LANGUAGE OverloadedStrings, OverloadedLists, LambdaCase #-} module Text.EasyJson.Parser where import Control.Applicative import Control.Monad.Identity import qualified Data.HashMap.Strict as H import Data.Monoid import Data.Text (Text, pack, unpack) import qualified Data.Text as T import qualified Data.Vector as V import Text.Parsec hiding (many, (<|>)) import Text.EasyJson.AST type ParserState = () type Parser = ParsecT String ParserState Identity sstring :: String -> Parser String sstring = lexeme . string schar :: Char -> Parser Char schar = lexeme . char lexeme :: Parser a -> Parser a lexeme p = p <* spaces pJson :: Parser Json pJson = choice [Number <$> pNumber, String <$> pString, false, true, null, array, object] where enclose l r p = between (schar l) (schar r) $ p `sepEndBy` schar ',' array = Array . V.fromList <$> enclose '[' ']' pJson object = Object . H.fromList <$> enclose '{' '}' keyval keyval = (,) <$> pString <*> (schar ':' *> pJson) false = sstring "false" >> return (Bool False) true = sstring "true" >> return (Bool True) null = sstring "null" *> return Null pNumber :: Parser Double pNumber = lexeme $ fmap read $ do first <- many1 digit option first $ do dot <- char '.' rest <- many1 digit return $ first <> [dot] <> rest pString :: Parser Text pString = lexeme $ do start <- char '"' <|> char '\'' loop start [] where loop stop acc = do option (pack $ reverse acc) $ anyChar >>= \case c | c == stop -> return $ pack $ reverse acc '\\' -> anyChar >>= \case 'n' -> add '\n' 'r' -> add '\r' 't' -> add '\r' 'b' -> add '\r' '\\' -> add '\\' '"' -> add '"' '\'' -> add '\'' c -> unexpected $ "Unrecognized escape sequence: \\" <> [c] c -> add c where add c = loop stop (c : acc) parseIt :: String -> Either ParseError Json parseIt = parse (pJson <* eof) ""
thinkpad20/easyjson
src/Text/EasyJson/Parser.hs
mit
1,974
0
18
507
738
379
359
56
10
module Handler.Sandbox where import Import getSandboxR :: Handler Html getSandboxR = defaultLayout $ do setTitle' "サンドボックス" addScript $ StaticR js_sandbox_js $(widgetFile "sandbox")
jabaraster/minibas-web
Handler/Sandbox.hs
mit
210
0
10
36
52
25
27
7
1
-- KMeans2.hs {-# LANGUAGE TemplateHaskell #-} import Control.Lens import Chapter6.Vector import Data.List import qualified Data.Map as M data KMeansState e v = KMeansState { _centroids :: [v], _points :: [e] , _err :: Double, _threshold :: Double , _steps :: Int } makeLenses ''KMeansState clusterAssignmentPhase :: (Vector v, Vectorizable e v) => [v] -> [e] -> M.Map v [e] clusterAssignmentPhase centroids points = let initialMap = M.fromList $ zip centroids (repeat []) in foldr (\p m -> let chosenCentroid = minimumBy (\x y -> compare (distance x $ toVector p) (distance y $ toVector p)) centroids in M.adjust (p:) chosenCentroid m) initialMap points initializeState :: (Int -> [e] -> [v]) -> Int -> [e] -> Double -> KMeansState e v initializeState i n pts t = KMeansState (i n pts) pts (1.0/0.0) t 0 kMeans :: (Vector v, Vectorizable e v) => (Int -> [e] -> [v]) -> Int -> [e] -> Double -> [v] kMeans i n pts t = view centroids $ kMeans' (initializeState i n pts t) kMeans' :: (Vector v, Vectorizable e v) => KMeansState e v -> KMeansState e v kMeans' state = let assignments = clusterAssignments state state1 = state & centroids.traversed %~ (\c -> centroid $ fmap toVector $ M.findWithDefault [] c assignments) state2 = state1 & err .~ sum (zipWith distance (state^.centroids) (state1^.centroids)) state3 = state2 & steps +~ 1 in if state3^.err < state3^.threshold then state3 else kMeans' state3 clusterAssignments :: (Vector v, Vectorizable e v) => KMeansState e v -> M.Map v [e] clusterAssignments state = let cs = view centroids state pts = view points state in clusterAssignmentPhase cs pts
hnfmr/beginning_haskell
chapter6/src/Chapter6/KMeans2.hs
mit
1,915
0
20
584
696
364
332
-1
-1
#!/usr/bin/env stack {- stack runghc --verbosity info --package hledger --package Chart --package Chart-diagrams --package cmdargs --package colour --package data-default --package here --package safe --package text -} {-# OPTIONS_GHC -Wno-missing-signatures -Wno-unused-do-bind #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} import Control.Monad import Data.Colour import Data.Colour.Names hiding (red,green) import Data.Colour.RGBSpace import Data.Colour.RGBSpace.HSL (hsl) import Data.Colour.SRGB.Linear (rgb) import Data.Default import Data.List import Data.Maybe import Data.Ord import Data.String.Here import qualified Data.Text as T import Graphics.Rendering.Chart import Graphics.Rendering.Chart.Backend.Diagrams import Safe import System.Console.CmdArgs.Explicit import System.Exit import Hledger.Cli hiding (num,green,is,balance) defchartoutput = "hledger.svg" defchartitems = 10 defchartsize = "600x400" ------------------------------------------------------------------------------ cmdmode = hledgerCommandMode [here| chart Generate a pie chart for the top account balances with the same sign, in SVG format. Based on the old hledger-chart package, this is not yet useful. It's supposed to show only balances of one sign, but this might be broken. |] [flagReq ["chart-output","o"] (\s opts -> Right $ setopt "chart-output" s opts) "IMGFILE" ("output filename (default: "++defchartoutput++")") ,flagReq ["chart-items"] (\s opts -> Right $ setopt "chart-items" s opts) "N" ("number of accounts to show (default: "++show defchartitems++")") ,flagReq ["chart-size"] (\s opts -> Right $ setopt "chart-size" s opts) "WIDTHxHEIGHT" ("image size (default: "++defchartsize++")") ] [generalflagsgroup1] [] ([], Just $ argsFlag "[QUERY]") ------------------------------------------------------------------------------ data ChartOpts = ChartOpts { chart_output_ :: FilePath ,chart_items_ :: Int ,chart_size_ :: String ,cliopts_ :: CliOpts } deriving (Show) defchartopts = ChartOpts def def def defcliopts getHledgerChartOpts :: IO ChartOpts getHledgerChartOpts = do cliopts <- getHledgerCliOpts cmdmode return defchartopts { chart_output_ = fromMaybe defchartoutput $ maybestringopt "debug-chart" $ rawopts_ cliopts ,chart_items_ = fromMaybe defchartitems $ maybeintopt "debug-items" $ rawopts_ cliopts ,chart_size_ = fromMaybe defchartsize $ maybestringopt "debug-size" $ rawopts_ cliopts ,cliopts_ = cliopts } main :: IO () main = do chopts <- getHledgerChartOpts d <- getCurrentDay j <- defaultJournal let ropts = (reportopts_ $ cliopts_ chopts) let balreport = singleBalanceReport ropts (queryFromOpts d ropts) j let go -- | "--help" `elem` (rawopts_ $ cliopts_ chopts) = putStr (showModeHelp chartmode) >> exitSuccess -- | "--version" `elem` (rawopts_ $ cliopts_ chopts) = putStrLn progversion >> exitSuccess | otherwise = withJournalAndChartOptsDo chopts (writeChart balreport) go -- copied from hledger-web withJournalAndChartOptsDo :: ChartOpts -> (ChartOpts -> Journal -> IO ()) -> IO () withJournalAndChartOptsDo opts cmd = do f <- head `fmap` journalFilePathFromOpts (cliopts_ opts) readJournalFile Nothing Nothing True f >>= either error' (cmd opts . journalApplyAliases (aliasesFromOpts $ cliopts_ opts)) -- | Generate an image with the pie chart and write it to a file writeChart :: BalanceReport -> ChartOpts -> Journal -> IO () writeChart balreport opts j = do -- d <- getCurrentDay if null $ jtxns j then putStrLn "This journal has no transactions, can't make a chart." >> exitFailure else do let chart = genPie opts balreport let fileoptions = def -- FileOptions (fromIntegral w, fromIntegral h) SVG loadSansSerifFonts renderableToFile fileoptions filename (toRenderable chart) return () where filename = chart_output_ opts -- (w,h) = parseSize $ chart_size_ opts -- ropts = reportopts_ $ cliopts_ opts -- | Parse image size from a command-line option -- parseSize :: String -> (Int,Int) -- parseSize str = (read w, read h) -- where -- x = fromMaybe (error' "Size should be in WIDTHxHEIGHT format") $ findIndex (=='x') str -- (w,_:h) = splitAt x str -- | Generate pie chart genPie :: ChartOpts -> BalanceReport -> PieLayout genPie opts (items, _total) = def { _pie_background = solidFillStyle $ opaque $ white , _pie_plot = pie_chart } where pie_chart = def { _pie_data = map (uncurry accountPieItem) chartitems , _pie_start_angle = (-90) , _pie_colors = mkColours hue , _pie_label_style = def{_font_size=12} } chartitems = dbg1 "chart" $ top num samesignitems :: [(AccountName, Double)] (samesignitems, sign) = sameSignNonZero items top n t = topn ++ [other] where (topn,rest) = splitAt n $ reverse $ sortBy (comparing snd) t other = ("other", sum $ map snd rest) num = chart_items_ opts hue = if sign > 0 then red else green where (red, green) = (0, 110) -- copts = cliopts_ opts -- ropts = reportopts_ copts -- | Select the nonzero items with same sign as the first, and make -- them positive. Also return a 1 or -1 corresponding to the original sign. sameSignNonZero :: [BalanceReportItem] -> ([(AccountName, Double)], Int) sameSignNonZero is | null nzs = ([], 1) | otherwise = (map pos $ filter (test.fourth4) nzs, sign) where nzs = filter ((/=0).fourth4) is pos (acct,_,_,Mixed as) = (acct, abs $ read $ show $ maybe 0 aquantity $ headMay as) sign = if fourth4 (head nzs) >= 0 then 1 else (-1) test = if sign > 0 then (>0) else (<0) -- | Convert all quantities of MixedAccount to a single commodity -- amountValue :: MixedAmount -> Double -- amountValue = quantity . mixedAmountWithCommodity unknown -- | Generate a tree of account names together with their balances. -- The balance of account is decremented by the balance of its subaccounts -- which are drawn on the chart. -- balances :: Tree Account -> Tree (AccountName, Double) -- balances (Node rootAcc subAccs) = Node newroot newsubs -- where -- newroot = (aname rootAcc, -- amountValue $ -- aibalance rootAcc - (sum . map (aibalance . root)) subAccs) -- newsubs = map balances subAccs -- | Build a single pie chart item accountPieItem :: AccountName -> Double -> PieItem accountPieItem accname balance = PieItem (T.unpack accname) offset balance where offset = 0 -- | Generate an infinite color list suitable for charts. mkColours :: Double -> [AlphaColour Double] mkColours hue = cycle $ [opaque $ rgbToColour $ hsl h s l | (h,s,l) <- liftM3 (,,) [hue] [0.7] [0.1,0.2..0.7] ] rgbToColour :: (Fractional a) => RGB a -> Colour a rgbToColour (RGB r g b) = rgb r g b
mstksg/hledger
bin/hledger-chart.hs
gpl-3.0
7,106
0
14
1,588
1,546
847
699
105
3
module Handler.Register (getRegisterR, getRegisterEnrollR, getEnrollR, postEnrollR, postRegisterR, postRegisterEnrollR) where import Import import Yesod.Form.Bootstrap3 import Util.Database import Util.Data getRegister :: ([Entity Course] -> UserId -> Html -> MForm Handler (FormResult (Maybe UserData), Widget)) -> Route App -> Text -> Handler Html getRegister theform theaction ident = do userId <- fromIdent ident time <- liftIO getCurrentTime courseEntities <- runDB $ selectList [CourseStartDate <. time, CourseEndDate >. time] [] (widget,enctype) <- generateFormPost (theform courseEntities userId) defaultLayout $ do setTitle "Carnap - Registration" $(widgetFile "register") postRegister :: ([Entity Course] -> UserId -> Html -> MForm Handler (FormResult (Maybe UserData), Widget)) -> Text -> Handler Html postRegister theform ident = do userId <- fromIdent ident time <- liftIO getCurrentTime courseEntities <- runDB $ selectList [CourseStartDate <. time, CourseEndDate >. time] [] ((result,widget),enctype) <- runFormPost (theform courseEntities userId) case result of FormSuccess (Just userdata) -> do msuccess <- tryInsert userdata case msuccess of Just _ -> do deleteSession "enrolling-in" redirect (UserR ident) Nothing -> defaultLayout clashPage FormSuccess Nothing -> do setMessage "Class not found - link may be incorrect or expired. Please enroll manually." redirect (RegisterR ident) _ -> defaultLayout errorPage where errorPage = [whamlet| <div.container> <p> Looks like something went wrong with that form <p> <a href=@{RegisterR ident}>Try again? |] clashPage = [whamlet| <div.container> <p> Looks like you're already registered. <p> <a href=@{UserR ident}>Go to your user page? |] getRegisterR :: Text -> Handler Html getRegisterR ident = getRegister registrationForm (RegisterR ident) ident getEnrollR :: Text -> Handler Html getEnrollR classname = do setSession "enrolling-in" classname Entity uid user <- requireAuth mclass <- runDB $ getBy (UniqueCourse classname) mud <- runDB $ getBy $ UniqueUserData uid case mud of Nothing -> redirect (RegisterEnrollR classname (userIdent user)) Just (Entity udid ud) -> case (mclass, userDataEnrolledIn ud) of (Just (Entity cid course), Just ecid) -> do if cid == ecid then redirect HomeR else defaultLayout (reenrollPage course user) (Just (Entity cid course), Nothing) -> do defaultLayout (confirm course) (Nothing,_) -> setMessage "no course with that title" >> notFound where reenrollPage course user = [whamlet| <div.container> <h2>It looks like you're already enrolled. <p>Do you want to change your enrollment and join #{courseTitle course}? <p>Changing your enrollment will not cause you to lose any saved work. You can rejoin your previous class by changing your enrollment settings at the bottom of your # <a href=@{UserR (userIdent user)}>user page# . <p> <form action="" method="post"> <button name="change-enrollment" value="change"> Change Enrollment |] confirm course = [whamlet| <div.container> <p>Do you want to join #{courseTitle course}? <p> <form action="" method="post"> <button name="change-enrollment" value="change"> Join #{courseTitle course} |] postEnrollR :: Text -> Handler Html postEnrollR classname = do (Entity uid _) <- requireAuth (mclass, mudent) <- runDB $ (,) <$> getBy (UniqueCourse classname) <*> getBy (UniqueUserData uid) case (mclass, mudent) of (Nothing,_) -> setMessage "no course with that title" >> notFound (_,Nothing) -> setMessage "no user data (do you need to register?)" >> notFound (Just (Entity cid course), Just (Entity udid _)) -> do runDB $ update udid [UserDataEnrolledIn =. Just cid] setMessage $ "Enrollment change complete" redirect HomeR --registration with enrollment built into the path getRegisterEnrollR :: Text -> Text -> Handler Html getRegisterEnrollR theclass ident = getRegister (enrollmentForm theclass) (RegisterEnrollR theclass ident) ident postRegisterR :: Text -> Handler Html postRegisterR = postRegister registrationForm postRegisterEnrollR :: Text -> Text -> Handler Html postRegisterEnrollR theclass = postRegister (enrollmentForm theclass) registrationForm :: [Entity Course] -> UserId -> Html -> MForm Handler (FormResult (Maybe UserData), Widget) registrationForm courseEntities userId = do renderBootstrap3 BootstrapBasicForm $ fixedId <$> areq textField "First name " Nothing <*> areq textField "Last name " Nothing <*> areq (selectFieldList courses) "enrolled in " Nothing where fixedId x y z = Just $ UserData x y z Nothing userId courses = ("No Course", Nothing) : map (\e -> (courseTitle $ entityVal e, Just $ entityKey e)) courseEntities enrollmentForm :: Text -> [Entity Course] -> UserId -> Html -> MForm Handler (FormResult (Maybe UserData), Widget) enrollmentForm classtitle courseEntities userId = do renderBootstrap3 BootstrapBasicForm $ fixedId <$> areq textField "First name " Nothing <*> areq textField "Last name " Nothing where fixedId x y = case course of Just c -> Just $ UserData x y (Just c) Nothing userId Nothing -> Nothing course = case filter (\e -> classtitle == courseTitle (entityVal e)) courseEntities of [] -> Nothing e:_ -> Just $ entityKey e
gleachkr/Carnap
Carnap-Server/Handler/Register.hs
gpl-3.0
7,231
0
19
2,828
1,492
737
755
-1
-1
module Parser.Program where import Text.Parsec import Text.Parsec.Expr import Text.Parsec.Char import Text.Parsec.Token import Text.Parsec.String import Parser.Declarations data Program = Program [ObjectDeclaration] deriving Show parseProgram :: Parser Program parseProgram = fmap Program (many parseObjectDeclaration) mergePrograms :: Program -> Program -> Program mergePrograms (Program decls1) (Program decls2) = Program (decls1 ++ decls2)
w0301/preon-lang-compiler
src/Parser/Program.hs
gpl-3.0
453
0
7
59
124
70
54
14
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.AdSenseHost -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Generates performance reports, generates ad codes, and provides -- publisher management capabilities for AdSense Hosts. -- -- /See:/ <https://developers.google.com/adsense/host/ AdSense Host API Reference> module Network.Google.AdSenseHost ( -- * Service Configuration adSenseHostService -- * OAuth Scopes , adSenseHostScope -- * API Declaration , AdSenseHostAPI -- * Resources -- ** adsensehost.accounts.adclients.get , module Network.Google.Resource.AdSenseHost.Accounts.AdClients.Get -- ** adsensehost.accounts.adclients.list , module Network.Google.Resource.AdSenseHost.Accounts.AdClients.List -- ** adsensehost.accounts.adunits.delete , module Network.Google.Resource.AdSenseHost.Accounts.AdUnits.Delete -- ** adsensehost.accounts.adunits.get , module Network.Google.Resource.AdSenseHost.Accounts.AdUnits.Get -- ** adsensehost.accounts.adunits.getAdCode , module Network.Google.Resource.AdSenseHost.Accounts.AdUnits.GetAdCode -- ** adsensehost.accounts.adunits.insert , module Network.Google.Resource.AdSenseHost.Accounts.AdUnits.Insert -- ** adsensehost.accounts.adunits.list , module Network.Google.Resource.AdSenseHost.Accounts.AdUnits.List -- ** adsensehost.accounts.adunits.patch , module Network.Google.Resource.AdSenseHost.Accounts.AdUnits.Patch -- ** adsensehost.accounts.adunits.update , module Network.Google.Resource.AdSenseHost.Accounts.AdUnits.Update -- ** adsensehost.accounts.get , module Network.Google.Resource.AdSenseHost.Accounts.Get -- ** adsensehost.accounts.list , module Network.Google.Resource.AdSenseHost.Accounts.List -- ** adsensehost.accounts.reports.generate , module Network.Google.Resource.AdSenseHost.Accounts.Reports.Generate -- ** adsensehost.adclients.get , module Network.Google.Resource.AdSenseHost.AdClients.Get -- ** adsensehost.adclients.list , module Network.Google.Resource.AdSenseHost.AdClients.List -- ** adsensehost.associationsessions.start , module Network.Google.Resource.AdSenseHost.AssociationSessions.Start -- ** adsensehost.associationsessions.verify , module Network.Google.Resource.AdSenseHost.AssociationSessions.Verify -- ** adsensehost.customchannels.delete , module Network.Google.Resource.AdSenseHost.CustomChannels.Delete -- ** adsensehost.customchannels.get , module Network.Google.Resource.AdSenseHost.CustomChannels.Get -- ** adsensehost.customchannels.insert , module Network.Google.Resource.AdSenseHost.CustomChannels.Insert -- ** adsensehost.customchannels.list , module Network.Google.Resource.AdSenseHost.CustomChannels.List -- ** adsensehost.customchannels.patch , module Network.Google.Resource.AdSenseHost.CustomChannels.Patch -- ** adsensehost.customchannels.update , module Network.Google.Resource.AdSenseHost.CustomChannels.Update -- ** adsensehost.reports.generate , module Network.Google.Resource.AdSenseHost.Reports.Generate -- ** adsensehost.urlchannels.delete , module Network.Google.Resource.AdSenseHost.URLChannels.Delete -- ** adsensehost.urlchannels.insert , module Network.Google.Resource.AdSenseHost.URLChannels.Insert -- ** adsensehost.urlchannels.list , module Network.Google.Resource.AdSenseHost.URLChannels.List -- * Types -- ** AdClients , AdClients , adClients , acEtag , acNextPageToken , acKind , acItems -- ** AssociationSession , AssociationSession , associationSession , asStatus , asKind , asWebsiteLocale , asUserLocale , asAccountId , asProductCodes , asId , asWebsiteURL , asRedirectURL -- ** AssociationSessionsStartProductCode , AssociationSessionsStartProductCode (..) -- ** Accounts , Accounts , accounts , aEtag , aKind , aItems -- ** AdUnits , AdUnits , adUnits , auEtag , auNextPageToken , auKind , auItems -- ** URLChannels , URLChannels , urlChannels , ucEtag , ucNextPageToken , ucKind , ucItems -- ** CustomChannels , CustomChannels , customChannels , ccEtag , ccNextPageToken , ccKind , ccItems -- ** AdUnit , AdUnit , adUnit , auuStatus , auuMobileContentAdsSettings , auuKind , auuCustomStyle , auuName , auuContentAdsSettings , auuCode , auuId -- ** Report , Report , report , rKind , rAverages , rWarnings , rRows , rTotals , rHeaders , rTotalMatchedRows -- ** AdStyleFont , AdStyleFont , adStyleFont , asfSize , asfFamily -- ** Account , Account , account , accStatus , accKind , accName , accId -- ** AdUnitMobileContentAdsSettings , AdUnitMobileContentAdsSettings , adUnitMobileContentAdsSettings , aumcasSize , aumcasScriptingLanguage , aumcasMarkupLanguage , aumcasType -- ** AdStyleColors , AdStyleColors , adStyleColors , ascText , ascURL , ascBOrder , ascTitle , ascBackgRound -- ** AdUnitContentAdsSettingsBackupOption , AdUnitContentAdsSettingsBackupOption , adUnitContentAdsSettingsBackupOption , aucasboColor , aucasboURL , aucasboType -- ** AdClient , AdClient , adClient , adKind , adArcOptIn , adSupportsReporting , adId , adProductCode -- ** ReportHeadersItem , ReportHeadersItem , reportHeadersItem , rhiName , rhiCurrency , rhiType -- ** AdStyle , AdStyle , adStyle , assCorners , assKind , assFont , assColors -- ** CustomChannel , CustomChannel , customChannel , cKind , cName , cCode , cId -- ** URLChannel , URLChannel , urlChannel , urlcKind , urlcId , urlcURLPattern -- ** AdCode , AdCode , adCode , aaKind , aaAdCode -- ** AdUnitContentAdsSettings , AdUnitContentAdsSettings , adUnitContentAdsSettings , aucasBackupOption , aucasSize , aucasType ) where import Network.Google.AdSenseHost.Types import Network.Google.Prelude import Network.Google.Resource.AdSenseHost.Accounts.AdClients.Get import Network.Google.Resource.AdSenseHost.Accounts.AdClients.List import Network.Google.Resource.AdSenseHost.Accounts.AdUnits.Delete import Network.Google.Resource.AdSenseHost.Accounts.AdUnits.Get import Network.Google.Resource.AdSenseHost.Accounts.AdUnits.GetAdCode import Network.Google.Resource.AdSenseHost.Accounts.AdUnits.Insert import Network.Google.Resource.AdSenseHost.Accounts.AdUnits.List import Network.Google.Resource.AdSenseHost.Accounts.AdUnits.Patch import Network.Google.Resource.AdSenseHost.Accounts.AdUnits.Update import Network.Google.Resource.AdSenseHost.Accounts.Get import Network.Google.Resource.AdSenseHost.Accounts.List import Network.Google.Resource.AdSenseHost.Accounts.Reports.Generate import Network.Google.Resource.AdSenseHost.AdClients.Get import Network.Google.Resource.AdSenseHost.AdClients.List import Network.Google.Resource.AdSenseHost.AssociationSessions.Start import Network.Google.Resource.AdSenseHost.AssociationSessions.Verify import Network.Google.Resource.AdSenseHost.CustomChannels.Delete import Network.Google.Resource.AdSenseHost.CustomChannels.Get import Network.Google.Resource.AdSenseHost.CustomChannels.Insert import Network.Google.Resource.AdSenseHost.CustomChannels.List import Network.Google.Resource.AdSenseHost.CustomChannels.Patch import Network.Google.Resource.AdSenseHost.CustomChannels.Update import Network.Google.Resource.AdSenseHost.Reports.Generate import Network.Google.Resource.AdSenseHost.URLChannels.Delete import Network.Google.Resource.AdSenseHost.URLChannels.Insert import Network.Google.Resource.AdSenseHost.URLChannels.List {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the AdSense Host API service. type AdSenseHostAPI = AssociationSessionsVerifyResource :<|> AssociationSessionsStartResource :<|> AdClientsListResource :<|> AdClientsGetResource :<|> AccountsAdClientsListResource :<|> AccountsAdClientsGetResource :<|> AccountsReportsGenerateResource :<|> AccountsAdUnitsInsertResource :<|> AccountsAdUnitsListResource :<|> AccountsAdUnitsPatchResource :<|> AccountsAdUnitsGetResource :<|> AccountsAdUnitsGetAdCodeResource :<|> AccountsAdUnitsDeleteResource :<|> AccountsAdUnitsUpdateResource :<|> AccountsListResource :<|> AccountsGetResource :<|> ReportsGenerateResource :<|> URLChannelsInsertResource :<|> URLChannelsListResource :<|> URLChannelsDeleteResource :<|> CustomChannelsInsertResource :<|> CustomChannelsListResource :<|> CustomChannelsPatchResource :<|> CustomChannelsGetResource :<|> CustomChannelsDeleteResource :<|> CustomChannelsUpdateResource
rueshyna/gogol
gogol-adsense-host/gen/Network/Google/AdSenseHost.hs
mpl-2.0
9,857
0
29
2,096
1,104
811
293
217
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.Glacier.UploadMultipartPart -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- This operation uploads a part of an archive. You can upload archive -- parts in any order. You can also upload them in parallel. You can upload -- up to 10,000 parts for a multipart upload. -- -- Amazon Glacier rejects your upload part request if any of the following -- conditions is true: -- -- - __SHA256 tree hash does not match__To ensure that part data is not -- corrupted in transmission, you compute a SHA256 tree hash of the -- part and include it in your request. Upon receiving the part data, -- Amazon Glacier also computes a SHA256 tree hash. If these hash -- values don\'t match, the operation fails. For information about -- computing a SHA256 tree hash, see -- <http://docs.aws.amazon.com/amazonglacier/latest/dev/checksum-calculations.html Computing Checksums>. -- -- - __Part size does not match__The size of each part except the last -- must match the size specified in the corresponding -- InitiateMultipartUpload request. The size of the last part must be -- the same size as, or smaller than, the specified size. -- -- If you upload a part whose size is smaller than the part size you -- specified in your initiate multipart upload request and that part is -- not the last part, then the upload part request will succeed. -- However, the subsequent Complete Multipart Upload request will fail. -- -- - __Range does not align__The byte range value in the request does not -- align with the part size specified in the corresponding initiate -- request. For example, if you specify a part size of 4194304 bytes (4 -- MB), then 0 to 4194303 bytes (4 MB - 1) and 4194304 (4 MB) to -- 8388607 (8 MB - 1) are valid part ranges. However, if you set a -- range value of 2 MB to 6 MB, the range does not align with the part -- size and the upload will fail. -- -- This operation is idempotent. If you upload the same part multiple -- times, the data included in the most recent request overwrites the -- previously uploaded data. -- -- An AWS account has full permission to perform all operations (actions). -- However, AWS Identity and Access Management (IAM) users don\'t have any -- permissions by default. You must grant them explicit permission to -- perform specific actions. For more information, see -- <http://docs.aws.amazon.com/amazonglacier/latest/dev/using-iam-with-amazon-glacier.html Access Control Using AWS Identity and Access Management (IAM)>. -- -- For conceptual information and underlying REST API, go to -- <http://docs.aws.amazon.com/amazonglacier/latest/dev/uploading-archive-mpu.html Uploading Large Archives in Parts (Multipart Upload)> -- and -- <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-upload-part.html Upload Part> -- in the /Amazon Glacier Developer Guide/. -- -- /See:/ <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-UploadMultipartPart.html AWS API Reference> for UploadMultipartPart. module Network.AWS.Glacier.UploadMultipartPart ( -- * Creating a Request uploadMultipartPart , UploadMultipartPart -- * Request Lenses , umpChecksum , umpRange , umpAccountId , umpVaultName , umpUploadId , umpBody -- * Destructuring the Response , uploadMultipartPartResponse , UploadMultipartPartResponse -- * Response Lenses , umprsChecksum , umprsResponseStatus ) where import Network.AWS.Glacier.Types import Network.AWS.Glacier.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | Provides options to upload a part of an archive in a multipart upload -- operation. -- -- /See:/ 'uploadMultipartPart' smart constructor. data UploadMultipartPart = UploadMultipartPart' { _umpChecksum :: !(Maybe Text) , _umpRange :: !(Maybe Text) , _umpAccountId :: !Text , _umpVaultName :: !Text , _umpUploadId :: !Text , _umpBody :: !HashedBody } deriving (Show,Generic) -- | Creates a value of 'UploadMultipartPart' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'umpChecksum' -- -- * 'umpRange' -- -- * 'umpAccountId' -- -- * 'umpVaultName' -- -- * 'umpUploadId' -- -- * 'umpBody' uploadMultipartPart :: Text -- ^ 'umpAccountId' -> Text -- ^ 'umpVaultName' -> Text -- ^ 'umpUploadId' -> HashedBody -- ^ 'umpBody' -> UploadMultipartPart uploadMultipartPart pAccountId_ pVaultName_ pUploadId_ pBody_ = UploadMultipartPart' { _umpChecksum = Nothing , _umpRange = Nothing , _umpAccountId = pAccountId_ , _umpVaultName = pVaultName_ , _umpUploadId = pUploadId_ , _umpBody = pBody_ } -- | The SHA256 tree hash of the data being uploaded. umpChecksum :: Lens' UploadMultipartPart (Maybe Text) umpChecksum = lens _umpChecksum (\ s a -> s{_umpChecksum = a}); -- | Identifies the range of bytes in the assembled archive that will be -- uploaded in this part. Amazon Glacier uses this information to assemble -- the archive in the proper sequence. The format of this header follows -- RFC 2616. An example header is Content-Range:bytes 0-4194303\/*. umpRange :: Lens' UploadMultipartPart (Maybe Text) umpRange = lens _umpRange (\ s a -> s{_umpRange = a}); -- | The 'AccountId' value is the AWS account ID of the account that owns the -- vault. You can either specify an AWS account ID or optionally a single -- apos'-'apos (hyphen), in which case Amazon Glacier uses the AWS account -- ID associated with the credentials used to sign the request. If you use -- an account ID, do not include any hyphens (apos-apos) in the ID. umpAccountId :: Lens' UploadMultipartPart Text umpAccountId = lens _umpAccountId (\ s a -> s{_umpAccountId = a}); -- | The name of the vault. umpVaultName :: Lens' UploadMultipartPart Text umpVaultName = lens _umpVaultName (\ s a -> s{_umpVaultName = a}); -- | The upload ID of the multipart upload. umpUploadId :: Lens' UploadMultipartPart Text umpUploadId = lens _umpUploadId (\ s a -> s{_umpUploadId = a}); -- | The data to upload. umpBody :: Lens' UploadMultipartPart HashedBody umpBody = lens _umpBody (\ s a -> s{_umpBody = a}); instance AWSRequest UploadMultipartPart where type Rs UploadMultipartPart = UploadMultipartPartResponse request = putBody glacier response = receiveEmpty (\ s h x -> UploadMultipartPartResponse' <$> (h .#? "x-amz-sha256-tree-hash") <*> (pure (fromEnum s))) instance ToBody UploadMultipartPart where toBody = toBody . _umpBody instance ToHeaders UploadMultipartPart where toHeaders UploadMultipartPart'{..} = mconcat ["x-amz-sha256-tree-hash" =# _umpChecksum, "Content-Range" =# _umpRange] instance ToPath UploadMultipartPart where toPath UploadMultipartPart'{..} = mconcat ["/", toBS _umpAccountId, "/vaults/", toBS _umpVaultName, "/multipart-uploads/", toBS _umpUploadId] instance ToQuery UploadMultipartPart where toQuery = const mempty -- | Contains the Amazon Glacier response to your request. -- -- /See:/ 'uploadMultipartPartResponse' smart constructor. data UploadMultipartPartResponse = UploadMultipartPartResponse' { _umprsChecksum :: !(Maybe Text) , _umprsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'UploadMultipartPartResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'umprsChecksum' -- -- * 'umprsResponseStatus' uploadMultipartPartResponse :: Int -- ^ 'umprsResponseStatus' -> UploadMultipartPartResponse uploadMultipartPartResponse pResponseStatus_ = UploadMultipartPartResponse' { _umprsChecksum = Nothing , _umprsResponseStatus = pResponseStatus_ } -- | The SHA256 tree hash that Amazon Glacier computed for the uploaded part. umprsChecksum :: Lens' UploadMultipartPartResponse (Maybe Text) umprsChecksum = lens _umprsChecksum (\ s a -> s{_umprsChecksum = a}); -- | The response status code. umprsResponseStatus :: Lens' UploadMultipartPartResponse Int umprsResponseStatus = lens _umprsResponseStatus (\ s a -> s{_umprsResponseStatus = a});
olorin/amazonka
amazonka-glacier/gen/Network/AWS/Glacier/UploadMultipartPart.hs
mpl-2.0
9,114
0
13
1,851
959
593
366
117
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.YouTube.LiveChatMessages.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists live chat messages for a specific chat. -- -- /See:/ <https://developers.google.com/youtube/v3 YouTube Data API Reference> for @youtube.liveChatMessages.list@. module Network.Google.Resource.YouTube.LiveChatMessages.List ( -- * REST Resource LiveChatMessagesListResource -- * Creating a Request , liveChatMessagesList , LiveChatMessagesList -- * Request Lenses , lcmlPart , lcmlLiveChatId , lcmlHl , lcmlPageToken , lcmlMaxResults , lcmlProFileImageSize ) where import Network.Google.Prelude import Network.Google.YouTube.Types -- | A resource alias for @youtube.liveChatMessages.list@ method which the -- 'LiveChatMessagesList' request conforms to. type LiveChatMessagesListResource = "youtube" :> "v3" :> "liveChat" :> "messages" :> QueryParam "liveChatId" Text :> QueryParam "part" Text :> QueryParam "hl" Text :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "profileImageSize" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] LiveChatMessageListResponse -- | Lists live chat messages for a specific chat. -- -- /See:/ 'liveChatMessagesList' smart constructor. data LiveChatMessagesList = LiveChatMessagesList' { _lcmlPart :: !Text , _lcmlLiveChatId :: !Text , _lcmlHl :: !(Maybe Text) , _lcmlPageToken :: !(Maybe Text) , _lcmlMaxResults :: !(Textual Word32) , _lcmlProFileImageSize :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'LiveChatMessagesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lcmlPart' -- -- * 'lcmlLiveChatId' -- -- * 'lcmlHl' -- -- * 'lcmlPageToken' -- -- * 'lcmlMaxResults' -- -- * 'lcmlProFileImageSize' liveChatMessagesList :: Text -- ^ 'lcmlPart' -> Text -- ^ 'lcmlLiveChatId' -> LiveChatMessagesList liveChatMessagesList pLcmlPart_ pLcmlLiveChatId_ = LiveChatMessagesList' { _lcmlPart = pLcmlPart_ , _lcmlLiveChatId = pLcmlLiveChatId_ , _lcmlHl = Nothing , _lcmlPageToken = Nothing , _lcmlMaxResults = 500 , _lcmlProFileImageSize = Nothing } -- | The part parameter specifies the liveChatComment resource parts that the -- API response will include. Supported values are id and snippet. lcmlPart :: Lens' LiveChatMessagesList Text lcmlPart = lens _lcmlPart (\ s a -> s{_lcmlPart = a}) -- | The liveChatId parameter specifies the ID of the chat whose messages -- will be returned. lcmlLiveChatId :: Lens' LiveChatMessagesList Text lcmlLiveChatId = lens _lcmlLiveChatId (\ s a -> s{_lcmlLiveChatId = a}) -- | The hl parameter instructs the API to retrieve localized resource -- metadata for a specific application language that the YouTube website -- supports. The parameter value must be a language code included in the -- list returned by the i18nLanguages.list method. If localized resource -- details are available in that language, the resource\'s -- snippet.localized object will contain the localized values. However, if -- localized details are not available, the snippet.localized object will -- contain resource details in the resource\'s default language. lcmlHl :: Lens' LiveChatMessagesList (Maybe Text) lcmlHl = lens _lcmlHl (\ s a -> s{_lcmlHl = a}) -- | The pageToken parameter identifies a specific page in the result set -- that should be returned. In an API response, the nextPageToken property -- identify other pages that could be retrieved. lcmlPageToken :: Lens' LiveChatMessagesList (Maybe Text) lcmlPageToken = lens _lcmlPageToken (\ s a -> s{_lcmlPageToken = a}) -- | The maxResults parameter specifies the maximum number of messages that -- should be returned in the result set. lcmlMaxResults :: Lens' LiveChatMessagesList Word32 lcmlMaxResults = lens _lcmlMaxResults (\ s a -> s{_lcmlMaxResults = a}) . _Coerce -- | The profileImageSize parameter specifies the size of the user profile -- pictures that should be returned in the result set. Default: 88. lcmlProFileImageSize :: Lens' LiveChatMessagesList (Maybe Word32) lcmlProFileImageSize = lens _lcmlProFileImageSize (\ s a -> s{_lcmlProFileImageSize = a}) . mapping _Coerce instance GoogleRequest LiveChatMessagesList where type Rs LiveChatMessagesList = LiveChatMessageListResponse type Scopes LiveChatMessagesList = '["https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.force-ssl", "https://www.googleapis.com/auth/youtube.readonly"] requestClient LiveChatMessagesList'{..} = go (Just _lcmlLiveChatId) (Just _lcmlPart) _lcmlHl _lcmlPageToken (Just _lcmlMaxResults) _lcmlProFileImageSize (Just AltJSON) youTubeService where go = buildClient (Proxy :: Proxy LiveChatMessagesListResource) mempty
rueshyna/gogol
gogol-youtube/gen/Network/Google/Resource/YouTube/LiveChatMessages/List.hs
mpl-2.0
6,090
0
18
1,429
761
446
315
110
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.DialogFlow.Types -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.DialogFlow.Types ( -- * Service Configuration dialogFlowService -- * OAuth Scopes , dialogFlowScope , cloudPlatformScope -- * GoogleCloudDialogflowCxV3beta1GenericKnowledgeOperationMetadata , GoogleCloudDialogflowCxV3beta1GenericKnowledgeOperationMetadata , googleCloudDialogflowCxV3beta1GenericKnowledgeOperationMetadata , gcdcvgkomState -- * GoogleRpcStatus , GoogleRpcStatus , googleRpcStatus , grsDetails , grsCode , grsMessage -- * GoogleCloudDialogflowCxV3MatchMatchType , GoogleCloudDialogflowCxV3MatchMatchType (..) -- * GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedAction , GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedAction , googleCloudDialogflowV2beta1IntentMessageRbmSuggestedAction , gcdvimrsaText , gcdvimrsaShareLocation , gcdvimrsaOpenURL , gcdvimrsaDial , gcdvimrsaPostbackData -- * GoogleCloudDialogflowCxV3ExperimentResult , GoogleCloudDialogflowCxV3ExperimentResult , googleCloudDialogflowCxV3ExperimentResult , gcdcverVersionMetrics , gcdcverLastUpdateTime -- * GoogleCloudDialogflowCxV3ListVersionsResponse , GoogleCloudDialogflowCxV3ListVersionsResponse , googleCloudDialogflowCxV3ListVersionsResponse , gcdcvlvrNextPageToken , gcdcvlvrVersions -- * ProjectsLocationsAgentsTestCasesListView , ProjectsLocationsAgentsTestCasesListView (..) -- * GoogleCloudDialogflowV2IntentFollowupIntentInfo , GoogleCloudDialogflowV2IntentFollowupIntentInfo , googleCloudDialogflowV2IntentFollowupIntentInfo , gcdvifiiFollowupIntentName , gcdvifiiParentFollowupIntentName -- * GoogleCloudDialogflowV2beta1IntentMessageSimpleResponses , GoogleCloudDialogflowV2beta1IntentMessageSimpleResponses , googleCloudDialogflowV2beta1IntentMessageSimpleResponses , gcdvimsrSimpleResponses -- * GoogleCloudDialogflowCxV3ListContinuousTestResultsResponse , GoogleCloudDialogflowCxV3ListContinuousTestResultsResponse , googleCloudDialogflowCxV3ListContinuousTestResultsResponse , gcdcvlctrrNextPageToken , gcdcvlctrrContinuousTestResults -- * GoogleCloudDialogflowV2beta1IntentTrainingPhraseType , GoogleCloudDialogflowV2beta1IntentTrainingPhraseType (..) -- * GoogleCloudDialogflowV2beta1IntentMessageRbmStandaloneCardCardOrientation , GoogleCloudDialogflowV2beta1IntentMessageRbmStandaloneCardCardOrientation (..) -- * GoogleCloudDialogflowCxV3beta1ContinuousTestResultResult , GoogleCloudDialogflowCxV3beta1ContinuousTestResultResult (..) -- * GoogleCloudDialogflowV2beta1BatchUpdateIntentsResponse , GoogleCloudDialogflowV2beta1BatchUpdateIntentsResponse , googleCloudDialogflowV2beta1BatchUpdateIntentsResponse , gcdvbuirIntents -- * GoogleCloudDialogflowV2KnowledgeOperationMetadata , GoogleCloudDialogflowV2KnowledgeOperationMetadata , googleCloudDialogflowV2KnowledgeOperationMetadata , gcdvkomState -- * GoogleCloudDialogflowV2beta1IntentMessagePayload , GoogleCloudDialogflowV2beta1IntentMessagePayload , googleCloudDialogflowV2beta1IntentMessagePayload , gcdvimpAddtional -- * GoogleCloudDialogflowCxV3WebhookRequestIntentInfo , GoogleCloudDialogflowCxV3WebhookRequestIntentInfo , googleCloudDialogflowCxV3WebhookRequestIntentInfo , gcdcvwriiLastMatchedIntent , gcdcvwriiConfidence , gcdcvwriiParameters , gcdcvwriiDisplayName -- * GoogleCloudDialogflowCxV3ConversationTurn , GoogleCloudDialogflowCxV3ConversationTurn , googleCloudDialogflowCxV3ConversationTurn , gcdcvctUserInput , gcdcvctVirtualAgentOutput -- * GoogleCloudDialogflowCxV3beta1ResponseMessageLiveAgentHandoff , GoogleCloudDialogflowCxV3beta1ResponseMessageLiveAgentHandoff , googleCloudDialogflowCxV3beta1ResponseMessageLiveAgentHandoff , gcdcvrmlahMetadata -- * GoogleCloudDialogflowV2WebhookRequest , GoogleCloudDialogflowV2WebhookRequest , googleCloudDialogflowV2WebhookRequest , gcdvwrOriginalDetectIntentRequest , gcdvwrResponseId , gcdvwrQueryResult , gcdvwrSession -- * GoogleCloudDialogflowCxV3beta1ConversationTurnVirtualAgentOutputSessionParameters , GoogleCloudDialogflowCxV3beta1ConversationTurnVirtualAgentOutputSessionParameters , googleCloudDialogflowCxV3beta1ConversationTurnVirtualAgentOutputSessionParameters , gcdcvctvaospAddtional -- * GoogleCloudDialogflowV2beta1ConversationEvent , GoogleCloudDialogflowV2beta1ConversationEvent , googleCloudDialogflowV2beta1ConversationEvent , gcdvceErrorStatus , gcdvceConversation , gcdvceNewMessagePayload , gcdvceType -- * GoogleCloudDialogflowV2IntentMessageCarouselSelectItem , GoogleCloudDialogflowV2IntentMessageCarouselSelectItem , googleCloudDialogflowV2IntentMessageCarouselSelectItem , gcdvimcsiImage , gcdvimcsiTitle , gcdvimcsiDescription , gcdvimcsiInfo -- * GoogleCloudDialogflowCxV3beta1TextInput , GoogleCloudDialogflowCxV3beta1TextInput , googleCloudDialogflowCxV3beta1TextInput , gcdcvtiText -- * GoogleCloudDialogflowCxV3QueryResultWebhookPayloadsItem , GoogleCloudDialogflowCxV3QueryResultWebhookPayloadsItem , googleCloudDialogflowCxV3QueryResultWebhookPayloadsItem , gcdcvqrwpiAddtional -- * GoogleCloudDialogflowCxV3QueryParameters , GoogleCloudDialogflowCxV3QueryParameters , googleCloudDialogflowCxV3QueryParameters , gcdcvqpDisableWebhook , gcdcvqpCurrentPage , gcdcvqpPayload , gcdcvqpAnalyzeQueryTextSentiment , gcdcvqpWebhookHeaders , gcdcvqpParameters , gcdcvqpGeoLocation , gcdcvqpTimeZone , gcdcvqpSessionEntityTypes -- * GoogleCloudDialogflowCxV3SessionInfo , GoogleCloudDialogflowCxV3SessionInfo , googleCloudDialogflowCxV3SessionInfo , gcdcvsiParameters , gcdcvsiSession -- * GoogleCloudDialogflowV2IntentMessageBrowseCarouselCardBrowseCarouselCardItem , GoogleCloudDialogflowV2IntentMessageBrowseCarouselCardBrowseCarouselCardItem , googleCloudDialogflowV2IntentMessageBrowseCarouselCardBrowseCarouselCardItem , gcdvimbccbcciImage , gcdvimbccbcciOpenURIAction , gcdvimbccbcciFooter , gcdvimbccbcciTitle , gcdvimbccbcciDescription -- * GoogleCloudDialogflowCxV3RunTestCaseResponse , GoogleCloudDialogflowCxV3RunTestCaseResponse , googleCloudDialogflowCxV3RunTestCaseResponse , gcdcvrtcrResult -- * GoogleCloudDialogflowV2beta1IntentMessageRbmCardContentRbmMediaHeight , GoogleCloudDialogflowV2beta1IntentMessageRbmCardContentRbmMediaHeight (..) -- * GoogleCloudDialogflowCxV3DetectIntentResponse , GoogleCloudDialogflowCxV3DetectIntentResponse , googleCloudDialogflowCxV3DetectIntentResponse , gcdcvdirOutputAudioConfig , gcdcvdirResponseId , gcdcvdirAllowCancellation , gcdcvdirOutputAudio , gcdcvdirResponseType , gcdcvdirQueryResult -- * GoogleCloudDialogflowV2EventInput , GoogleCloudDialogflowV2EventInput , googleCloudDialogflowV2EventInput , gcdveiLanguageCode , gcdveiName , gcdveiParameters -- * GoogleCloudDialogflowV2IntentMessageSimpleResponse , GoogleCloudDialogflowV2IntentMessageSimpleResponse , googleCloudDialogflowV2IntentMessageSimpleResponse , gcdvimsrDisplayText , gcdvimsrSsml , gcdvimsrTextToSpeech -- * GoogleCloudDialogflowCxV3TestRunDifference , GoogleCloudDialogflowCxV3TestRunDifference , googleCloudDialogflowCxV3TestRunDifference , gcdcvtrdType , gcdcvtrdDescription -- * GoogleLongrunningOperationMetadata , GoogleLongrunningOperationMetadata , googleLongrunningOperationMetadata , glomAddtional -- * GoogleCloudDialogflowV2IntentMessageMediaContent , GoogleCloudDialogflowV2IntentMessageMediaContent , googleCloudDialogflowV2IntentMessageMediaContent , gcdvimmcMediaType , gcdvimmcMediaObjects -- * GoogleCloudDialogflowCxV3ExportTestCasesMetadata , GoogleCloudDialogflowCxV3ExportTestCasesMetadata , googleCloudDialogflowCxV3ExportTestCasesMetadata -- * GoogleCloudDialogflowCxV3RestoreAgentRequest , GoogleCloudDialogflowCxV3RestoreAgentRequest , googleCloudDialogflowCxV3RestoreAgentRequest , gcdcvrarAgentURI , gcdcvrarAgentContent , gcdcvrarRestoreOption -- * GoogleCloudDialogflowCxV3beta1CreateDocumentOperationMetadata , GoogleCloudDialogflowCxV3beta1CreateDocumentOperationMetadata , googleCloudDialogflowCxV3beta1CreateDocumentOperationMetadata , gcdcvcdomGenericMetadata -- * GoogleCloudDialogflowCxV3ResponseMessage , GoogleCloudDialogflowCxV3ResponseMessage , googleCloudDialogflowCxV3ResponseMessage , gcdcvrmOutputAudioText , gcdcvrmPlayAudio , gcdcvrmText , gcdcvrmLiveAgentHandoff , gcdcvrmConversationSuccess , gcdcvrmPayload , gcdcvrmEndInteraction , gcdcvrmMixedAudio -- * GoogleCloudDialogflowV2beta1IntentMessageColumnPropertiesHorizontalAlignment , GoogleCloudDialogflowV2beta1IntentMessageColumnPropertiesHorizontalAlignment (..) -- * GoogleCloudDialogflowV2AnnotatedMessagePart , GoogleCloudDialogflowV2AnnotatedMessagePart , googleCloudDialogflowV2AnnotatedMessagePart , gcdvampText , gcdvampEntityType , gcdvampFormattedValue -- * GoogleCloudDialogflowCxV3StartExperimentRequest , GoogleCloudDialogflowCxV3StartExperimentRequest , googleCloudDialogflowCxV3StartExperimentRequest -- * GoogleCloudDialogflowCxV3TextInput , GoogleCloudDialogflowCxV3TextInput , googleCloudDialogflowCxV3TextInput , gText -- * GoogleCloudDialogflowCxV3Page , GoogleCloudDialogflowCxV3Page , googleCloudDialogflowCxV3Page , gcdcvpEventHandlers , gcdcvpTransitionRoutes , gcdcvpName , gcdcvpTransitionRouteGroups , gcdcvpDisplayName , gcdcvpForm , gcdcvpEntryFulfillment -- * GoogleCloudDialogflowV2ConversationEvent , GoogleCloudDialogflowV2ConversationEvent , googleCloudDialogflowV2ConversationEvent , gErrorStatus , gConversation , gNewMessagePayload , gType -- * GoogleCloudDialogflowCxV3beta1RunTestCaseResponse , GoogleCloudDialogflowCxV3beta1RunTestCaseResponse , googleCloudDialogflowCxV3beta1RunTestCaseResponse , gResult -- * GoogleCloudDialogflowCxV3ResponseMessageConversationSuccessMetadata , GoogleCloudDialogflowCxV3ResponseMessageConversationSuccessMetadata , googleCloudDialogflowCxV3ResponseMessageConversationSuccessMetadata , gcdcvrmcsmAddtional -- * GoogleCloudDialogflowCxV3beta1AudioInput , GoogleCloudDialogflowCxV3beta1AudioInput , googleCloudDialogflowCxV3beta1AudioInput , gcdcvaiConfig , gcdcvaiAudio -- * GoogleCloudDialogflowCxV3ResponseMessageLiveAgentHandoff , GoogleCloudDialogflowCxV3ResponseMessageLiveAgentHandoff , googleCloudDialogflowCxV3ResponseMessageLiveAgentHandoff , gMetadata -- * GoogleCloudDialogflowCxV3beta1ResponseMessage , GoogleCloudDialogflowCxV3beta1ResponseMessage , googleCloudDialogflowCxV3beta1ResponseMessage , gooOutputAudioText , gooPlayAudio , gooText , gooLiveAgentHandoff , gooConversationSuccess , gooPayload , gooEndInteraction , gooMixedAudio -- * GoogleCloudDialogflowCxV3TrainFlowRequest , GoogleCloudDialogflowCxV3TrainFlowRequest , googleCloudDialogflowCxV3TrainFlowRequest -- * GoogleCloudDialogflowCxV3TestCaseResult , GoogleCloudDialogflowCxV3TestCaseResult , googleCloudDialogflowCxV3TestCaseResult , gcdcvtcrEnvironment , gcdcvtcrName , gcdcvtcrTestResult , gcdcvtcrTestTime , gcdcvtcrConversationTurns -- * GoogleCloudDialogflowCxV3CreateDocumentOperationMetadata , GoogleCloudDialogflowCxV3CreateDocumentOperationMetadata , googleCloudDialogflowCxV3CreateDocumentOperationMetadata , gGenericMetadata -- * GoogleCloudDialogflowCxV3ExperimentResultConfidenceInterval , GoogleCloudDialogflowCxV3ExperimentResultConfidenceInterval , googleCloudDialogflowCxV3ExperimentResultConfidenceInterval , gcdcverciUpperBound , gcdcverciLowerBound , gcdcverciRatio , gcdcverciConfidenceLevel -- * GoogleCloudDialogflowV2IntentTrainingPhrase , GoogleCloudDialogflowV2IntentTrainingPhrase , googleCloudDialogflowV2IntentTrainingPhrase , gcdvitpParts , gcdvitpName , gcdvitpTimesAddedCount , gcdvitpType -- * GoogleCloudDialogflowCxV3beta1TestRunDifference , GoogleCloudDialogflowCxV3beta1TestRunDifference , googleCloudDialogflowCxV3beta1TestRunDifference , gooType , gooDescription -- * GoogleCloudDialogflowCxV3SpeechToTextSettings , GoogleCloudDialogflowCxV3SpeechToTextSettings , googleCloudDialogflowCxV3SpeechToTextSettings , gcdcvsttsEnableSpeechAdaptation -- * GoogleCloudDialogflowCxV3beta1ExportTestCasesMetadata , GoogleCloudDialogflowCxV3beta1ExportTestCasesMetadata , googleCloudDialogflowCxV3beta1ExportTestCasesMetadata -- * GoogleCloudDialogflowCxV3ConversationTurnVirtualAgentOutputSessionParameters , GoogleCloudDialogflowCxV3ConversationTurnVirtualAgentOutputSessionParameters , googleCloudDialogflowCxV3ConversationTurnVirtualAgentOutputSessionParameters , gAddtional -- * GoogleCloudDialogflowCxV3beta1ResponseMessageMixedAudioSegment , GoogleCloudDialogflowCxV3beta1ResponseMessageMixedAudioSegment , googleCloudDialogflowCxV3beta1ResponseMessageMixedAudioSegment , gcdcvrmmasURI , gcdcvrmmasAudio , gcdcvrmmasAllowPlaybackInterruption -- * GoogleCloudDialogflowCxV3ListAgentsResponse , GoogleCloudDialogflowCxV3ListAgentsResponse , googleCloudDialogflowCxV3ListAgentsResponse , gcdcvlarNextPageToken , gcdcvlarAgents -- * GoogleCloudDialogflowCxV3beta1SessionInfo , GoogleCloudDialogflowCxV3beta1SessionInfo , googleCloudDialogflowCxV3beta1SessionInfo , gParameters , gSession -- * GoogleCloudDialogflowCxV3ListExperimentsResponse , GoogleCloudDialogflowCxV3ListExperimentsResponse , googleCloudDialogflowCxV3ListExperimentsResponse , gcdcvlerNextPageToken , gcdcvlerExperiments -- * GoogleCloudDialogflowV2beta1IntentMessageCarouselSelectItem , GoogleCloudDialogflowV2beta1IntentMessageCarouselSelectItem , googleCloudDialogflowV2beta1IntentMessageCarouselSelectItem , gImage , gTitle , gDescription , gInfo -- * GoogleCloudDialogflowCxV3SecuritySettings , GoogleCloudDialogflowCxV3SecuritySettings , googleCloudDialogflowCxV3SecuritySettings , gcdcvssRetentionWindowDays , gcdcvssRedactionStrategy , gcdcvssName , gcdcvssRedactionScope , gcdcvssDisplayName , gcdcvssPurgeDataTypes , gcdcvssInspectTemplate -- * GoogleCloudDialogflowV2IntentMessageBasicCard , GoogleCloudDialogflowV2IntentMessageBasicCard , googleCloudDialogflowV2IntentMessageBasicCard , gcdvimbcImage , gcdvimbcButtons , gcdvimbcSubtitle , gcdvimbcTitle , gcdvimbcFormattedText -- * GoogleCloudDialogflowV2beta1IntentMessageSimpleResponse , GoogleCloudDialogflowV2beta1IntentMessageSimpleResponse , googleCloudDialogflowV2beta1IntentMessageSimpleResponse , gDisplayText , gSsml , gTextToSpeech -- * GoogleCloudDialogflowCxV3EntityType , GoogleCloudDialogflowCxV3EntityType , googleCloudDialogflowCxV3EntityType , gcdcvetExcludedPhrases , gcdcvetRedact , gcdcvetEntities , gcdcvetKind , gcdcvetName , gcdcvetAutoExpansionMode , gcdcvetDisplayName , gcdcvetEnableFuzzyExtraction -- * GoogleCloudDialogflowCxV3OutputAudioConfig , GoogleCloudDialogflowCxV3OutputAudioConfig , googleCloudDialogflowCxV3OutputAudioConfig , gcdcvoacSampleRateHertz , gcdcvoacSynthesizeSpeechConfig , gcdcvoacAudioEncoding -- * GoogleCloudDialogflowCxV3GenericKnowledgeOperationMetadata , GoogleCloudDialogflowCxV3GenericKnowledgeOperationMetadata , googleCloudDialogflowCxV3GenericKnowledgeOperationMetadata , gState -- * GoogleCloudDialogflowV2beta1ImportDocumentsResponse , GoogleCloudDialogflowV2beta1ImportDocumentsResponse , googleCloudDialogflowV2beta1ImportDocumentsResponse , gcdvidrWarnings -- * GoogleCloudDialogflowV2beta1IntentMessageMediaContent , GoogleCloudDialogflowV2beta1IntentMessageMediaContent , googleCloudDialogflowV2beta1IntentMessageMediaContent , gMediaType , gMediaObjects -- * GoogleCloudDialogflowCxV3RunContinuousTestRequest , GoogleCloudDialogflowCxV3RunContinuousTestRequest , googleCloudDialogflowCxV3RunContinuousTestRequest -- * GoogleCloudDialogflowCxV3EntityTypeKind , GoogleCloudDialogflowCxV3EntityTypeKind (..) -- * GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItem , GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItem , googleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItem , gcdvimbccbccicImage , gcdvimbccbccicOpenURIAction , gcdvimbccbccicFooter , gcdvimbccbccicTitle , gcdvimbccbccicDescription -- * GoogleCloudDialogflowCxV3NluSettingsModelTrainingMode , GoogleCloudDialogflowCxV3NluSettingsModelTrainingMode (..) -- * GoogleCloudDialogflowCxV3MatchIntentRequest , GoogleCloudDialogflowCxV3MatchIntentRequest , googleCloudDialogflowCxV3MatchIntentRequest , gcdcvmirQueryInput , gcdcvmirQueryParams -- * GoogleCloudDialogflowCxV3WebhookResponsePayload , GoogleCloudDialogflowCxV3WebhookResponsePayload , googleCloudDialogflowCxV3WebhookResponsePayload , gcdcvwrpAddtional -- * GoogleCloudDialogflowV2Intent , GoogleCloudDialogflowV2Intent , googleCloudDialogflowV2Intent , gcdviDefaultResponsePlatforms , gcdviWebhookState , gcdviPriority , gcdviLiveAgentHandoff , gcdviAction , gcdviRootFollowupIntentName , gcdviName , gcdviEvents , gcdviParameters , gcdviDisplayName , gcdviInputContextNames , gcdviEndInteraction , gcdviMessages , gcdviParentFollowupIntentName , gcdviOutputContexts , gcdviTrainingPhrases , gcdviFollowupIntentInfo , gcdviIsFallback , gcdviMlDisabled , gcdviResetContexts -- * GoogleCloudDialogflowCxV3beta1IntentParameter , GoogleCloudDialogflowCxV3beta1IntentParameter , googleCloudDialogflowCxV3beta1IntentParameter , gcdcvipRedact , gcdcvipEntityType , gcdcvipId , gcdcvipIsList -- * GoogleCloudDialogflowCxV3ListIntentsResponse , GoogleCloudDialogflowCxV3ListIntentsResponse , googleCloudDialogflowCxV3ListIntentsResponse , gcdcvlirIntents , gcdcvlirNextPageToken -- * GoogleCloudDialogflowV2beta1IntentMessageRbmCardContent , GoogleCloudDialogflowV2beta1IntentMessageRbmCardContent , googleCloudDialogflowV2beta1IntentMessageRbmCardContent , gcdvimrccMedia , gcdvimrccSuggestions , gcdvimrccTitle , gcdvimrccDescription -- * GoogleCloudDialogflowCxV3VariantsHistory , GoogleCloudDialogflowCxV3VariantsHistory , googleCloudDialogflowCxV3VariantsHistory , gcdcvvhVersionVariants , gcdcvvhUpdateTime -- * GoogleCloudDialogflowV2MessageAnnotation , GoogleCloudDialogflowV2MessageAnnotation , googleCloudDialogflowV2MessageAnnotation , gcdvmaParts , gcdvmaContainEntities -- * GoogleCloudDialogflowCxV3Form , GoogleCloudDialogflowCxV3Form , googleCloudDialogflowCxV3Form , gcdcvfParameters -- * GoogleCloudDialogflowV2beta1FaqAnswerMetadata , GoogleCloudDialogflowV2beta1FaqAnswerMetadata , googleCloudDialogflowV2beta1FaqAnswerMetadata , gcdvfamAddtional -- * GoogleCloudDialogflowCxV3ValidateAgentRequest , GoogleCloudDialogflowCxV3ValidateAgentRequest , googleCloudDialogflowCxV3ValidateAgentRequest , gcdcvvarLanguageCode -- * GoogleCloudDialogflowV2beta1IntentMessageTableCardRow , GoogleCloudDialogflowV2beta1IntentMessageTableCardRow , googleCloudDialogflowV2beta1IntentMessageTableCardRow , gcdvimtcrCells , gcdvimtcrDividerAfter -- * GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedActionRbmSuggestedActionDial , GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedActionRbmSuggestedActionDial , googleCloudDialogflowV2beta1IntentMessageRbmSuggestedActionRbmSuggestedActionDial , gcdvimrsarsadPhoneNumber -- * GoogleCloudDialogflowCxV3WebhookRequestSentimentAnalysisResult , GoogleCloudDialogflowCxV3WebhookRequestSentimentAnalysisResult , googleCloudDialogflowCxV3WebhookRequestSentimentAnalysisResult , gcdcvwrsarScore , gcdcvwrsarMagnitude -- * GoogleCloudDialogflowV2beta1IntentMessageBasicCardButton , GoogleCloudDialogflowV2beta1IntentMessageBasicCardButton , googleCloudDialogflowV2beta1IntentMessageBasicCardButton , gcdvimbcbOpenURIAction , gcdvimbcbTitle -- * GoogleCloudDialogflowV2SentimentAnalysisResult , GoogleCloudDialogflowV2SentimentAnalysisResult , googleCloudDialogflowV2SentimentAnalysisResult , gcdvsarQueryTextSentiment -- * GoogleCloudDialogflowCxV3WebhookRequestFulfillmentInfo , GoogleCloudDialogflowCxV3WebhookRequestFulfillmentInfo , googleCloudDialogflowCxV3WebhookRequestFulfillmentInfo , gcdcvwrfiTag -- * GoogleCloudDialogflowCxV3EntityTypeAutoExpansionMode , GoogleCloudDialogflowCxV3EntityTypeAutoExpansionMode (..) -- * GoogleCloudDialogflowV2beta1IntentMessageRbmStandaloneCardThumbnailImageAlignment , GoogleCloudDialogflowV2beta1IntentMessageRbmStandaloneCardThumbnailImageAlignment (..) -- * GoogleCloudDialogflowCxV3LookupEnvironmentHistoryResponse , GoogleCloudDialogflowCxV3LookupEnvironmentHistoryResponse , googleCloudDialogflowCxV3LookupEnvironmentHistoryResponse , gcdcvlehrNextPageToken , gcdcvlehrEnvironments -- * GoogleCloudDialogflowCxV3ExportAgentResponse , GoogleCloudDialogflowCxV3ExportAgentResponse , googleCloudDialogflowCxV3ExportAgentResponse , gcdcvearAgentURI , gcdcvearAgentContent -- * GoogleCloudDialogflowCxV3OutputAudioConfigAudioEncoding , GoogleCloudDialogflowCxV3OutputAudioConfigAudioEncoding (..) -- * GoogleCloudDialogflowV2beta1SmartReplyAnswer , GoogleCloudDialogflowV2beta1SmartReplyAnswer , googleCloudDialogflowV2beta1SmartReplyAnswer , gcdvsraReply , gcdvsraAnswerRecord , gcdvsraConfidence -- * GoogleCloudDialogflowCxV3beta1ResponseMessageText , GoogleCloudDialogflowCxV3beta1ResponseMessageText , googleCloudDialogflowCxV3beta1ResponseMessageText , gcdcvrmtText , gcdcvrmtAllowPlaybackInterruption -- * GoogleCloudDialogflowCxV3beta1InputAudioConfigModelVariant , GoogleCloudDialogflowCxV3beta1InputAudioConfigModelVariant (..) -- * GoogleCloudDialogflowCxV3Agent , GoogleCloudDialogflowCxV3Agent , googleCloudDialogflowCxV3Agent , gcdcvaDefaultLanguageCode , gcdcvaEnableStackdriverLogging , gcdcvaStartFlow , gcdcvaSpeechToTextSettings , gcdcvaSecuritySettings , gcdcvaEnableSpellCorrection , gcdcvaName , gcdcvaAvatarURI , gcdcvaSupportedLanguageCodes , gcdcvaDisplayName , gcdcvaTimeZone , gcdcvaDescription -- * GoogleCloudDialogflowV2beta1MessageParticipantRole , GoogleCloudDialogflowV2beta1MessageParticipantRole (..) -- * GoogleCloudDialogflowCxV3beta1InputAudioConfig , GoogleCloudDialogflowCxV3beta1InputAudioConfig , googleCloudDialogflowCxV3beta1InputAudioConfig , gcdcviacPhraseHints , gcdcviacSampleRateHertz , gcdcviacModelVariant , gcdcviacSingleUtterance , gcdcviacEnableWordInfo , gcdcviacModel , gcdcviacAudioEncoding -- * GoogleCloudDialogflowCxV3beta1EventInput , GoogleCloudDialogflowCxV3beta1EventInput , googleCloudDialogflowCxV3beta1EventInput , gcdcveiEvent -- * GoogleCloudDialogflowCxV3ListPagesResponse , GoogleCloudDialogflowCxV3ListPagesResponse , googleCloudDialogflowCxV3ListPagesResponse , gcdcvlprNextPageToken , gcdcvlprPages -- * GoogleCloudDialogflowCxV3beta1WebhookRequestIntentInfoParameters , GoogleCloudDialogflowCxV3beta1WebhookRequestIntentInfoParameters , googleCloudDialogflowCxV3beta1WebhookRequestIntentInfoParameters , gcdcvwriipAddtional -- * GoogleCloudDialogflowV2beta1IntentMessageSuggestions , GoogleCloudDialogflowV2beta1IntentMessageSuggestions , googleCloudDialogflowV2beta1IntentMessageSuggestions , gcdvimsSuggestions -- * GoogleCloudDialogflowV2beta1IntentMessageColumnProperties , GoogleCloudDialogflowV2beta1IntentMessageColumnProperties , googleCloudDialogflowV2beta1IntentMessageColumnProperties , gcdvimcpHeader , gcdvimcpHorizontalAlignment -- * GoogleCloudDialogflowCxV3IntentLabels , GoogleCloudDialogflowCxV3IntentLabels , googleCloudDialogflowCxV3IntentLabels , gcdcvilAddtional -- * GoogleCloudDialogflowV2beta1KnowledgeAnswersAnswerMatchConfidenceLevel , GoogleCloudDialogflowV2beta1KnowledgeAnswersAnswerMatchConfidenceLevel (..) -- * GoogleCloudDialogflowCxV3ListEntityTypesResponse , GoogleCloudDialogflowCxV3ListEntityTypesResponse , googleCloudDialogflowCxV3ListEntityTypesResponse , gcdcvletrNextPageToken , gcdcvletrEntityTypes -- * GoogleCloudDialogflowCxV3beta1IntentInput , GoogleCloudDialogflowCxV3beta1IntentInput , googleCloudDialogflowCxV3beta1IntentInput , gcdcviiIntent -- * GoogleCloudDialogflowV2QueryResult , GoogleCloudDialogflowV2QueryResult , googleCloudDialogflowV2QueryResult , gcdvqrLanguageCode , gcdvqrAllRequiredParamsPresent , gcdvqrIntentDetectionConfidence , gcdvqrFulfillmentMessages , gcdvqrSpeechRecognitionConfidence , gcdvqrCancelsSlotFilling , gcdvqrAction , gcdvqrIntent , gcdvqrSentimentAnalysisResult , gcdvqrQueryText , gcdvqrFulfillmentText , gcdvqrParameters , gcdvqrWebhookPayload , gcdvqrOutputContexts , gcdvqrWebhookSource , gcdvqrDiagnosticInfo -- * GoogleCloudDialogflowCxV3WebhookResponseFulfillmentResponse , GoogleCloudDialogflowCxV3WebhookResponseFulfillmentResponse , googleCloudDialogflowCxV3WebhookResponseFulfillmentResponse , gcdcvwrfrMergeBehavior , gcdcvwrfrMessages -- * GoogleCloudDialogflowCxV3beta1ContinuousTestResult , GoogleCloudDialogflowCxV3beta1ContinuousTestResult , googleCloudDialogflowCxV3beta1ContinuousTestResult , gcdcvctrRunTime , gcdcvctrTestCaseResults , gcdcvctrResult , gcdcvctrName -- * GoogleCloudDialogflowV2Message , GoogleCloudDialogflowV2Message , googleCloudDialogflowV2Message , gcdvmLanguageCode , gcdvmParticipantRole , gcdvmContent , gcdvmMessageAnnotation , gcdvmName , gcdvmParticipant , gcdvmCreateTime -- * GoogleCloudDialogflowCxV3MatchParameters , GoogleCloudDialogflowCxV3MatchParameters , googleCloudDialogflowCxV3MatchParameters , gcdcvmpAddtional -- * GoogleCloudDialogflowV2IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenURLAction , GoogleCloudDialogflowV2IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenURLAction , googleCloudDialogflowV2IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenURLAction , gcdvimbccbcciouaURL , gcdvimbccbcciouaURLTypeHint -- * GoogleCloudDialogflowCxV3SessionEntityTypeEntityOverrideMode , GoogleCloudDialogflowCxV3SessionEntityTypeEntityOverrideMode (..) -- * GoogleCloudDialogflowV2beta1ArticleAnswer , GoogleCloudDialogflowV2beta1ArticleAnswer , googleCloudDialogflowV2beta1ArticleAnswer , gcdvaaURI , gcdvaaAnswerRecord , gcdvaaMetadata , gcdvaaTitle , gcdvaaSnippets -- * GoogleCloudDialogflowCxV3QueryResultParameters , GoogleCloudDialogflowCxV3QueryResultParameters , googleCloudDialogflowCxV3QueryResultParameters , gcdcvqrpAddtional -- * GoogleCloudDialogflowCxV3beta1WebhookRequest , GoogleCloudDialogflowCxV3beta1WebhookRequest , googleCloudDialogflowCxV3beta1WebhookRequest , gcdcvwrTriggerIntent , gcdcvwrLanguageCode , gcdcvwrPageInfo , gcdcvwrText , gcdcvwrSessionInfo , gcdcvwrPayload , gcdcvwrTriggerEvent , gcdcvwrSentimentAnalysisResult , gcdcvwrFulfillmentInfo , gcdcvwrIntentInfo , gcdcvwrDetectIntentResponseId , gcdcvwrMessages , gcdcvwrTranscript -- * GoogleTypeLatLng , GoogleTypeLatLng , googleTypeLatLng , gtllLatitude , gtllLongitude -- * GoogleCloudDialogflowCxV3Experiment , GoogleCloudDialogflowCxV3Experiment , googleCloudDialogflowCxV3Experiment , gcdcveState , gcdcveExperimentLength , gcdcveDefinition , gcdcveStartTime , gcdcveResult , gcdcveName , gcdcveEndTime , gcdcveDisplayName , gcdcveLastUpdateTime , gcdcveVariantsHistory , gcdcveDescription , gcdcveCreateTime -- * GoogleCloudDialogflowCxV3ListTestCaseResultsResponse , GoogleCloudDialogflowCxV3ListTestCaseResultsResponse , googleCloudDialogflowCxV3ListTestCaseResultsResponse , gcdcvltcrrNextPageToken , gcdcvltcrrTestCaseResults -- * GoogleCloudDialogflowCxV3CalculateCoverageResponse , GoogleCloudDialogflowCxV3CalculateCoverageResponse , googleCloudDialogflowCxV3CalculateCoverageResponse , gcdcvccrIntentCoverage , gcdcvccrRouteGroupCoverage , gcdcvccrAgent , gcdcvccrTransitionCoverage -- * GoogleCloudDialogflowCxV3beta1TestCaseError , GoogleCloudDialogflowCxV3beta1TestCaseError , googleCloudDialogflowCxV3beta1TestCaseError , gcdcvtceStatus , gcdcvtceTestCase -- * GoogleCloudDialogflowV2beta1SuggestArticlesResponse , GoogleCloudDialogflowV2beta1SuggestArticlesResponse , googleCloudDialogflowV2beta1SuggestArticlesResponse , gcdvsarContextSize , gcdvsarArticleAnswers , gcdvsarLatestMessage -- * GoogleCloudDialogflowCxV3ImportTestCasesMetadata , GoogleCloudDialogflowCxV3ImportTestCasesMetadata , googleCloudDialogflowCxV3ImportTestCasesMetadata , gcdcvitcmErrors -- * GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardImageDisplayOptions , GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardImageDisplayOptions (..) -- * GoogleCloudDialogflowV2IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenURLActionURLTypeHint , GoogleCloudDialogflowV2IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenURLActionURLTypeHint (..) -- * GoogleCloudDialogflowV2beta1WebhookResponse , GoogleCloudDialogflowV2beta1WebhookResponse , googleCloudDialogflowV2beta1WebhookResponse , gcdvwrFulfillmentMessages , gcdvwrLiveAgentHandoff , gcdvwrPayload , gcdvwrFulfillmentText , gcdvwrSource , gcdvwrEndInteraction , gcdvwrOutputContexts , gcdvwrFollowupEventInput , gcdvwrSessionEntityTypes -- * GoogleCloudDialogflowCxV3beta1PageInfoFormInfoParameterInfo , GoogleCloudDialogflowCxV3beta1PageInfoFormInfoParameterInfo , googleCloudDialogflowCxV3beta1PageInfoFormInfoParameterInfo , gcdcvpifipiJustCollected , gcdcvpifipiState , gcdcvpifipiValue , gcdcvpifipiRequired , gcdcvpifipiDisplayName -- * GoogleCloudDialogflowV2beta1IntentMessageMediaContentResponseMediaObject , GoogleCloudDialogflowV2beta1IntentMessageMediaContentResponseMediaObject , googleCloudDialogflowV2beta1IntentMessageMediaContentResponseMediaObject , gcdvimmcrmoIcon , gcdvimmcrmoName , gcdvimmcrmoContentURL , gcdvimmcrmoLargeImage , gcdvimmcrmoDescription -- * GoogleCloudDialogflowV2beta1EventInputParameters , GoogleCloudDialogflowV2beta1EventInputParameters , googleCloudDialogflowV2beta1EventInputParameters , gcdveipAddtional -- * GoogleCloudDialogflowCxV3EntityTypeExcludedPhrase , GoogleCloudDialogflowCxV3EntityTypeExcludedPhrase , googleCloudDialogflowCxV3EntityTypeExcludedPhrase , gcdcvetepValue -- * GoogleCloudDialogflowCxV3QueryInput , GoogleCloudDialogflowCxV3QueryInput , googleCloudDialogflowCxV3QueryInput , gcdcvqiEvent , gcdcvqiLanguageCode , gcdcvqiText , gcdcvqiIntent , gcdcvqiDtmf , gcdcvqiAudio -- * GoogleCloudDialogflowV2beta1OriginalDetectIntentRequestPayload , GoogleCloudDialogflowV2beta1OriginalDetectIntentRequestPayload , googleCloudDialogflowV2beta1OriginalDetectIntentRequestPayload , gcdvodirpAddtional -- * GoogleCloudDialogflowV2IntentMessageQuickReplies , GoogleCloudDialogflowV2IntentMessageQuickReplies , googleCloudDialogflowV2IntentMessageQuickReplies , gcdvimqrTitle , gcdvimqrQuickReplies -- * GoogleCloudDialogflowV2HumanAgentAssistantEvent , GoogleCloudDialogflowV2HumanAgentAssistantEvent , googleCloudDialogflowV2HumanAgentAssistantEvent , gcdvhaaeConversation , gcdvhaaeParticipant , gcdvhaaeSuggestionResults -- * GoogleCloudDialogflowV2IntentMessageMediaContentMediaType , GoogleCloudDialogflowV2IntentMessageMediaContentMediaType (..) -- * GoogleCloudDialogflowV2beta1KnowledgeAnswers , GoogleCloudDialogflowV2beta1KnowledgeAnswers , googleCloudDialogflowV2beta1KnowledgeAnswers , gcdvkaAnswers -- * GoogleCloudDialogflowCxV3MatchIntentResponse , GoogleCloudDialogflowCxV3MatchIntentResponse , googleCloudDialogflowCxV3MatchIntentResponse , gcdcvmirTriggerIntent , gcdcvmirCurrentPage , gcdcvmirText , gcdcvmirMatches , gcdcvmirTriggerEvent , gcdcvmirTranscript -- * GoogleCloudDialogflowV2beta1SuggestionResult , GoogleCloudDialogflowV2beta1SuggestionResult , googleCloudDialogflowV2beta1SuggestionResult , gcdvsrSuggestSmartRepliesResponse , gcdvsrError , gcdvsrSuggestFaqAnswersResponse , gcdvsrSuggestArticlesResponse -- * GoogleCloudDialogflowV2beta1IntentMessageCardButton , GoogleCloudDialogflowV2beta1IntentMessageCardButton , googleCloudDialogflowV2beta1IntentMessageCardButton , gcdvimcbText , gcdvimcbPostback -- * GoogleCloudDialogflowCxV3beta1BatchRunTestCasesResponse , GoogleCloudDialogflowCxV3beta1BatchRunTestCasesResponse , googleCloudDialogflowCxV3beta1BatchRunTestCasesResponse , gcdcvbrtcrResults -- * GoogleCloudDialogflowCxV3beta1FulfillmentConditionalCasesCase , GoogleCloudDialogflowCxV3beta1FulfillmentConditionalCasesCase , googleCloudDialogflowCxV3beta1FulfillmentConditionalCasesCase , gcdcvfcccCaseContent , gcdcvfcccCondition -- * GoogleCloudDialogflowV2beta1ContextParameters , GoogleCloudDialogflowV2beta1ContextParameters , googleCloudDialogflowV2beta1ContextParameters , gcdvcpAddtional -- * GoogleCloudDialogflowCxV3WebhookRequestPayload , GoogleCloudDialogflowCxV3WebhookRequestPayload , googleCloudDialogflowCxV3WebhookRequestPayload , gooAddtional -- * GoogleCloudDialogflowV2beta1IntentMessageListSelect , GoogleCloudDialogflowV2beta1IntentMessageListSelect , googleCloudDialogflowV2beta1IntentMessageListSelect , gcdvimlsItems , gcdvimlsSubtitle , gcdvimlsTitle -- * GoogleCloudDialogflowCxV3beta1RunContinuousTestMetadata , GoogleCloudDialogflowCxV3beta1RunContinuousTestMetadata , googleCloudDialogflowCxV3beta1RunContinuousTestMetadata , gcdcvrctmErrors -- * GoogleCloudDialogflowV2beta1IntentMessageTelephonyPlayAudio , GoogleCloudDialogflowV2beta1IntentMessageTelephonyPlayAudio , googleCloudDialogflowV2beta1IntentMessageTelephonyPlayAudio , gcdvimtpaAudioURI -- * GoogleCloudDialogflowCxV3ResponseMessageOutputAudioText , GoogleCloudDialogflowCxV3ResponseMessageOutputAudioText , googleCloudDialogflowCxV3ResponseMessageOutputAudioText , gcdcvrmoatText , gcdcvrmoatSsml , gcdcvrmoatAllowPlaybackInterruption -- * GoogleCloudDialogflowCxV3beta1InputAudioConfigAudioEncoding , GoogleCloudDialogflowCxV3beta1InputAudioConfigAudioEncoding (..) -- * GoogleCloudDialogflowCxV3ExperimentResultMetricType , GoogleCloudDialogflowCxV3ExperimentResultMetricType (..) -- * GoogleCloudDialogflowV2IntentTrainingPhrasePart , GoogleCloudDialogflowV2IntentTrainingPhrasePart , googleCloudDialogflowV2IntentTrainingPhrasePart , gcdvitppText , gcdvitppUserDefined , gcdvitppEntityType , gcdvitppAlias -- * GoogleCloudDialogflowV2beta1KnowledgeOperationMetadataState , GoogleCloudDialogflowV2beta1KnowledgeOperationMetadataState (..) -- * GoogleCloudDialogflowCxV3ExportAgentRequest , GoogleCloudDialogflowCxV3ExportAgentRequest , googleCloudDialogflowCxV3ExportAgentRequest , gAgentURI , gEnvironment -- * GoogleCloudDialogflowV2SuggestFaqAnswersResponse , GoogleCloudDialogflowV2SuggestFaqAnswersResponse , googleCloudDialogflowV2SuggestFaqAnswersResponse , gcdvsfarContextSize , gcdvsfarLatestMessage , gcdvsfarFaqAnswers -- * GoogleCloudDialogflowV2beta1IntentDefaultResponsePlatformsItem , GoogleCloudDialogflowV2beta1IntentDefaultResponsePlatformsItem (..) -- * GoogleCloudDialogflowCxV3ExperimentDefinition , GoogleCloudDialogflowCxV3ExperimentDefinition , googleCloudDialogflowCxV3ExperimentDefinition , gcdcvedVersionVariants , gcdcvedCondition -- * GoogleCloudDialogflowCxV3beta1ConversationTurnUserInput , GoogleCloudDialogflowCxV3beta1ConversationTurnUserInput , googleCloudDialogflowCxV3beta1ConversationTurnUserInput , gcdcvctuiEnableSentimentAnalysis , gcdcvctuiInput , gcdcvctuiIsWebhookEnabled , gcdcvctuiInjectedParameters -- * GoogleCloudDialogflowCxV3beta1EventHandler , GoogleCloudDialogflowCxV3beta1EventHandler , googleCloudDialogflowCxV3beta1EventHandler , gcdcvehEvent , gcdcvehTriggerFulfillment , gcdcvehName , gcdcvehTargetPage , gcdcvehTargetFlow -- * GoogleCloudDialogflowCxV3beta1TestCaseResultTestResult , GoogleCloudDialogflowCxV3beta1TestCaseResultTestResult (..) -- * GoogleCloudDialogflowV2beta1SuggestFaqAnswersResponse , GoogleCloudDialogflowV2beta1SuggestFaqAnswersResponse , googleCloudDialogflowV2beta1SuggestFaqAnswersResponse , gContextSize , gLatestMessage , gFaqAnswers -- * GoogleCloudDialogflowCxV3ListEnvironmentsResponse , GoogleCloudDialogflowCxV3ListEnvironmentsResponse , googleCloudDialogflowCxV3ListEnvironmentsResponse , gNextPageToken , gEnvironments -- * GoogleCloudDialogflowCxV3RunContinuousTestMetadata , GoogleCloudDialogflowCxV3RunContinuousTestMetadata , googleCloudDialogflowCxV3RunContinuousTestMetadata , gErrors -- * GoogleCloudDialogflowCxV3ExperimentResultMetricCountType , GoogleCloudDialogflowCxV3ExperimentResultMetricCountType (..) -- * GoogleProtobufEmpty , GoogleProtobufEmpty , googleProtobufEmpty -- * GoogleCloudDialogflowCxV3ListSessionEntityTypesResponse , GoogleCloudDialogflowCxV3ListSessionEntityTypesResponse , googleCloudDialogflowCxV3ListSessionEntityTypesResponse , gcdcvlSetrNextPageToken , gcdcvlSetrSessionEntityTypes -- * GoogleCloudDialogflowV2beta1WebhookResponsePayload , GoogleCloudDialogflowV2beta1WebhookResponsePayload , googleCloudDialogflowV2beta1WebhookResponsePayload , gcdvwrpAddtional -- * GoogleCloudDialogflowV2beta1IntentMessageQuickReplies , GoogleCloudDialogflowV2beta1IntentMessageQuickReplies , googleCloudDialogflowV2beta1IntentMessageQuickReplies , gcdvimqrsTitle , gcdvimqrsQuickReplies -- * GoogleCloudDialogflowV2IntentMessageLinkOutSuggestion , GoogleCloudDialogflowV2IntentMessageLinkOutSuggestion , googleCloudDialogflowV2IntentMessageLinkOutSuggestion , gcdvimlosURI , gcdvimlosDestinationName -- * GoogleCloudDialogflowCxV3TransitionRouteGroupCoverage , GoogleCloudDialogflowCxV3TransitionRouteGroupCoverage , googleCloudDialogflowCxV3TransitionRouteGroupCoverage , gcdcvtrgcCoverages , gcdcvtrgcCoverageScore -- * GoogleRpcStatusDetailsItem , GoogleRpcStatusDetailsItem , googleRpcStatusDetailsItem , grsdiAddtional -- * GoogleCloudDialogflowV2beta1BatchUpdateEntityTypesResponse , GoogleCloudDialogflowV2beta1BatchUpdateEntityTypesResponse , googleCloudDialogflowV2beta1BatchUpdateEntityTypesResponse , gcdvbuetrEntityTypes -- * GoogleCloudDialogflowCxV3beta1WebhookRequestPayload , GoogleCloudDialogflowCxV3beta1WebhookRequestPayload , googleCloudDialogflowCxV3beta1WebhookRequestPayload , gcdcvwrpcAddtional -- * GoogleCloudDialogflowV2ContextParameters , GoogleCloudDialogflowV2ContextParameters , googleCloudDialogflowV2ContextParameters , gcdvcpsAddtional -- * GoogleCloudDialogflowCxV3BatchRunTestCasesResponse , GoogleCloudDialogflowCxV3BatchRunTestCasesResponse , googleCloudDialogflowCxV3BatchRunTestCasesResponse , gResults -- * GoogleCloudDialogflowV2beta1IntentMessageRbmCarouselCard , GoogleCloudDialogflowV2beta1IntentMessageRbmCarouselCard , googleCloudDialogflowV2beta1IntentMessageRbmCarouselCard , gcdvimrccCardWidth , gcdvimrccCardContents -- * GoogleCloudDialogflowCxV3FulfillIntentResponse , GoogleCloudDialogflowCxV3FulfillIntentResponse , googleCloudDialogflowCxV3FulfillIntentResponse , gcdcvfirOutputAudioConfig , gcdcvfirResponseId , gcdcvfirOutputAudio , gcdcvfirQueryResult -- * GoogleCloudDialogflowV2IntentMessageTableCard , GoogleCloudDialogflowV2IntentMessageTableCard , googleCloudDialogflowV2IntentMessageTableCard , gcdvimtcImage , gcdvimtcButtons , gcdvimtcRows , gcdvimtcSubtitle , gcdvimtcColumnProperties , gcdvimtcTitle -- * GoogleCloudDialogflowCxV3FulfillmentConditionalCasesCase , GoogleCloudDialogflowCxV3FulfillmentConditionalCasesCase , googleCloudDialogflowCxV3FulfillmentConditionalCasesCase , gCaseContent , gCondition -- * GoogleCloudDialogflowCxV3beta1ImportFlowResponse , GoogleCloudDialogflowCxV3beta1ImportFlowResponse , googleCloudDialogflowCxV3beta1ImportFlowResponse , gcdcvifrFlow -- * GoogleCloudDialogflowCxV3beta1Intent , GoogleCloudDialogflowCxV3beta1Intent , googleCloudDialogflowCxV3beta1Intent , gcdcviPriority , gcdcviName , gcdcviParameters , gcdcviDisplayName , gcdcviLabels , gcdcviTrainingPhrases , gcdcviDescription , gcdcviIsFallback -- * GoogleCloudDialogflowCxV3InputAudioConfigAudioEncoding , GoogleCloudDialogflowCxV3InputAudioConfigAudioEncoding (..) -- * GoogleCloudDialogflowV2IntentMessageCardButton , GoogleCloudDialogflowV2IntentMessageCardButton , googleCloudDialogflowV2IntentMessageCardButton , gcdvimcbcText , gcdvimcbcPostback -- * GoogleCloudDialogflowCxV3ConversationTurnVirtualAgentOutput , GoogleCloudDialogflowCxV3ConversationTurnVirtualAgentOutput , googleCloudDialogflowCxV3ConversationTurnVirtualAgentOutput , gcdcvctvaoStatus , gcdcvctvaoCurrentPage , gcdcvctvaoSessionParameters , gcdcvctvaoDifferences , gcdcvctvaoTextResponses , gcdcvctvaoTriggeredIntent , gcdcvctvaoDiagnosticInfo -- * GoogleCloudDialogflowV2IntentMessageListSelect , GoogleCloudDialogflowV2IntentMessageListSelect , googleCloudDialogflowV2IntentMessageListSelect , gooItems , gooSubtitle , gooTitle -- * GoogleCloudDialogflowCxV3WebhookGenericWebService , GoogleCloudDialogflowCxV3WebhookGenericWebService , googleCloudDialogflowCxV3WebhookGenericWebService , gcdcvwgwsUsername , gcdcvwgwsURI , gcdcvwgwsPassword , gcdcvwgwsRequestHeaders -- * GoogleCloudDialogflowCxV3beta1GenericKnowledgeOperationMetadataState , GoogleCloudDialogflowCxV3beta1GenericKnowledgeOperationMetadataState (..) -- * GoogleCloudDialogflowV2beta1IntentMessageRbmCardContentRbmMedia , GoogleCloudDialogflowV2beta1IntentMessageRbmCardContentRbmMedia , googleCloudDialogflowV2beta1IntentMessageRbmCardContentRbmMedia , gcdvimrccrmHeight , gcdvimrccrmThumbnailURI , gcdvimrccrmFileURI -- * GoogleCloudDialogflowCxV3beta1TestConfig , GoogleCloudDialogflowCxV3beta1TestConfig , googleCloudDialogflowCxV3beta1TestConfig , gcdcvtcFlow , gcdcvtcTrackingParameters -- * GoogleCloudDialogflowCxV3ConversationTurnUserInput , GoogleCloudDialogflowCxV3ConversationTurnUserInput , googleCloudDialogflowCxV3ConversationTurnUserInput , gEnableSentimentAnalysis , gInput , gIsWebhookEnabled , gInjectedParameters -- * GoogleCloudDialogflowV2KnowledgeOperationMetadataState , GoogleCloudDialogflowV2KnowledgeOperationMetadataState (..) -- * GoogleCloudDialogflowCxV3ContinuousTestResult , GoogleCloudDialogflowCxV3ContinuousTestResult , googleCloudDialogflowCxV3ContinuousTestResult , gooRunTime , gooTestCaseResults , gooResult , gooName -- * GoogleCloudDialogflowCxV3InputAudioConfig , GoogleCloudDialogflowCxV3InputAudioConfig , googleCloudDialogflowCxV3InputAudioConfig , gPhraseHints , gSampleRateHertz , gModelVariant , gSingleUtterance , gEnableWordInfo , gModel , gAudioEncoding -- * GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenURLAction , GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenURLAction , googleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenURLAction , gcdvimbccbcciourlaURL , gcdvimbccbcciourlaURLTypeHint -- * GoogleCloudDialogflowV2MessageParticipantRole , GoogleCloudDialogflowV2MessageParticipantRole (..) -- * GoogleCloudDialogflowCxV3beta1RunContinuousTestResponse , GoogleCloudDialogflowCxV3beta1RunContinuousTestResponse , googleCloudDialogflowCxV3beta1RunContinuousTestResponse , gcdcvrctrContinuousTestResult -- * GoogleCloudDialogflowCxV3EventInput , GoogleCloudDialogflowCxV3EventInput , googleCloudDialogflowCxV3EventInput , gEvent -- * GoogleCloudDialogflowV2beta1IntentMessageCard , GoogleCloudDialogflowV2beta1IntentMessageCard , googleCloudDialogflowV2beta1IntentMessageCard , gcdvimcButtons , gcdvimcImageURI , gcdvimcSubtitle , gcdvimcTitle -- * GoogleCloudDialogflowV2IntentMessageSuggestions , GoogleCloudDialogflowV2IntentMessageSuggestions , googleCloudDialogflowV2IntentMessageSuggestions , gSuggestions -- * GoogleCloudDialogflowV2beta1IntentMessageBasicCardButtonOpenURIAction , GoogleCloudDialogflowV2beta1IntentMessageBasicCardButtonOpenURIAction , googleCloudDialogflowV2beta1IntentMessageBasicCardButtonOpenURIAction , gcdvimbcbouaURI -- * GoogleCloudDialogflowCxV3WebhookRequest , GoogleCloudDialogflowCxV3WebhookRequest , googleCloudDialogflowCxV3WebhookRequest , gcdcvwrcTriggerIntent , gcdcvwrcLanguageCode , gcdcvwrcPageInfo , gcdcvwrcText , gcdcvwrcSessionInfo , gcdcvwrcPayload , gcdcvwrcTriggerEvent , gcdcvwrcSentimentAnalysisResult , gcdcvwrcFulfillmentInfo , gcdcvwrcIntentInfo , gcdcvwrcDetectIntentResponseId , gcdcvwrcMessages , gcdcvwrcTranscript -- * GoogleCloudDialogflowV2IntentMessageBrowseCarouselCardImageDisplayOptions , GoogleCloudDialogflowV2IntentMessageBrowseCarouselCardImageDisplayOptions (..) -- * GoogleCloudDialogflowV2beta1IntentMessageSuggestion , GoogleCloudDialogflowV2beta1IntentMessageSuggestion , googleCloudDialogflowV2beta1IntentMessageSuggestion , gcdvimsTitle -- * GoogleCloudDialogflowCxV3Version , GoogleCloudDialogflowCxV3Version , googleCloudDialogflowCxV3Version , gcdcvvState , gcdcvvNluSettings , gcdcvvName , gcdcvvDisplayName , gcdcvvDescription , gcdcvvCreateTime -- * GoogleCloudDialogflowCxV3beta1WebhookResponseFulfillmentResponse , GoogleCloudDialogflowCxV3beta1WebhookResponseFulfillmentResponse , googleCloudDialogflowCxV3beta1WebhookResponseFulfillmentResponse , gMergeBehavior , gMessages -- * GoogleCloudDialogflowCxV3ValidationMessageResourceType , GoogleCloudDialogflowCxV3ValidationMessageResourceType (..) -- * GoogleCloudDialogflowCxV3InputAudioConfigModelVariant , GoogleCloudDialogflowCxV3InputAudioConfigModelVariant (..) -- * GoogleCloudDialogflowCxV3Fulfillment , GoogleCloudDialogflowCxV3Fulfillment , googleCloudDialogflowCxV3Fulfillment , gcdcvfTag , gcdcvfConditionalCases , gcdcvfReturnPartialResponses , gcdcvfMessages , gcdcvfWebhook , gcdcvfSetParameterActions -- * GoogleCloudDialogflowV2beta1OriginalDetectIntentRequest , GoogleCloudDialogflowV2beta1OriginalDetectIntentRequest , googleCloudDialogflowV2beta1OriginalDetectIntentRequest , gcdvodirPayload , gcdvodirVersion , gcdvodirSource -- * GoogleCloudDialogflowV2EventInputParameters , GoogleCloudDialogflowV2EventInputParameters , googleCloudDialogflowV2EventInputParameters , gcdveipsAddtional -- * GoogleCloudDialogflowCxV3WebhookGenericWebServiceRequestHeaders , GoogleCloudDialogflowCxV3WebhookGenericWebServiceRequestHeaders , googleCloudDialogflowCxV3WebhookGenericWebServiceRequestHeaders , gcdcvwgwsrhAddtional -- * GoogleCloudDialogflowCxV3SynthesizeSpeechConfig , GoogleCloudDialogflowCxV3SynthesizeSpeechConfig , googleCloudDialogflowCxV3SynthesizeSpeechConfig , gcdcvsscVolumeGainDB , gcdcvsscEffectsProFileId , gcdcvsscVoice , gcdcvsscSpeakingRate , gcdcvsscPitch -- * GoogleCloudDialogflowV2IntentMessagePlatform , GoogleCloudDialogflowV2IntentMessagePlatform (..) -- * GoogleCloudDialogflowCxV3beta1IntentLabels , GoogleCloudDialogflowCxV3beta1IntentLabels , googleCloudDialogflowCxV3beta1IntentLabels , gcdcvilsAddtional -- * GoogleCloudDialogflowCxV3WebhookRequestIntentInfoParameters , GoogleCloudDialogflowCxV3WebhookRequestIntentInfoParameters , googleCloudDialogflowCxV3WebhookRequestIntentInfoParameters , gcdcvwriipsAddtional -- * GoogleCloudDialogflowV3alpha1GenericKnowledgeOperationMetadataState , GoogleCloudDialogflowV3alpha1GenericKnowledgeOperationMetadataState (..) -- * GoogleCloudDialogflowCxV3ImportDocumentsResponse , GoogleCloudDialogflowCxV3ImportDocumentsResponse , googleCloudDialogflowCxV3ImportDocumentsResponse , gcdcvidrWarnings -- * GoogleCloudDialogflowV2IntentMessageMediaContentResponseMediaObject , GoogleCloudDialogflowV2IntentMessageMediaContentResponseMediaObject , googleCloudDialogflowV2IntentMessageMediaContentResponseMediaObject , gcdvimmcrmocIcon , gcdvimmcrmocName , gcdvimmcrmocContentURL , gcdvimmcrmocLargeImage , gcdvimmcrmocDescription -- * GoogleCloudDialogflowCxV3SessionInfoParameters , GoogleCloudDialogflowCxV3SessionInfoParameters , googleCloudDialogflowCxV3SessionInfoParameters , gcdcvsipAddtional -- * GoogleCloudDialogflowCxV3QueryParametersParameters , GoogleCloudDialogflowCxV3QueryParametersParameters , googleCloudDialogflowCxV3QueryParametersParameters , gcdcvqppAddtional -- * GoogleCloudDialogflowCxV3beta1BatchRunTestCasesMetadata , GoogleCloudDialogflowCxV3beta1BatchRunTestCasesMetadata , googleCloudDialogflowCxV3beta1BatchRunTestCasesMetadata , gcdcvbrtcmErrors -- * GoogleCloudDialogflowV2IntentMessageListSelectItem , GoogleCloudDialogflowV2IntentMessageListSelectItem , googleCloudDialogflowV2IntentMessageListSelectItem , gcdvimlsiImage , gcdvimlsiTitle , gcdvimlsiDescription , gcdvimlsiInfo -- * GoogleCloudDialogflowV2beta1MessageAnnotation , GoogleCloudDialogflowV2beta1MessageAnnotation , googleCloudDialogflowV2beta1MessageAnnotation , gParts , gContainEntities -- * GoogleCloudDialogflowCxV3PageInfoFormInfo , GoogleCloudDialogflowCxV3PageInfoFormInfo , googleCloudDialogflowCxV3PageInfoFormInfo , gcdcvpifiParameterInfo -- * GoogleCloudDialogflowCxV3beta1CreateVersionOperationMetadata , GoogleCloudDialogflowCxV3beta1CreateVersionOperationMetadata , googleCloudDialogflowCxV3beta1CreateVersionOperationMetadata , gcdcvcvomVersion -- * GoogleCloudDialogflowCxV3beta1ConversationTurnVirtualAgentOutputDiagnosticInfo , GoogleCloudDialogflowCxV3beta1ConversationTurnVirtualAgentOutputDiagnosticInfo , googleCloudDialogflowCxV3beta1ConversationTurnVirtualAgentOutputDiagnosticInfo , gcdcvctvaodiAddtional -- * GoogleCloudDialogflowCxV3beta1IntentTrainingPhrasePart , GoogleCloudDialogflowCxV3beta1IntentTrainingPhrasePart , googleCloudDialogflowCxV3beta1IntentTrainingPhrasePart , gcdcvitppParameterId , gcdcvitppText -- * GoogleCloudDialogflowCxV3ResponseMessageText , GoogleCloudDialogflowCxV3ResponseMessageText , googleCloudDialogflowCxV3ResponseMessageText , gcdcvrmtcText , gcdcvrmtcAllowPlaybackInterruption -- * GoogleCloudDialogflowCxV3beta1ResponseMessageConversationSuccess , GoogleCloudDialogflowCxV3beta1ResponseMessageConversationSuccess , googleCloudDialogflowCxV3beta1ResponseMessageConversationSuccess , gcdcvrmcsMetadata -- * GoogleCloudDialogflowCxV3PageInfoFormInfoParameterInfoState , GoogleCloudDialogflowCxV3PageInfoFormInfoParameterInfoState (..) -- * GoogleCloudDialogflowV2beta1IntentMessageRbmCarouselCardCardWidth , GoogleCloudDialogflowV2beta1IntentMessageRbmCarouselCardCardWidth (..) -- * GoogleCloudDialogflowCxV3ExportFlowResponse , GoogleCloudDialogflowCxV3ExportFlowResponse , googleCloudDialogflowCxV3ExportFlowResponse , gcdcvefrFlowContent , gcdcvefrFlowURI -- * GoogleCloudDialogflowCxV3beta1ResponseMessagePayload , GoogleCloudDialogflowCxV3beta1ResponseMessagePayload , googleCloudDialogflowCxV3beta1ResponseMessagePayload , gcdcvrmpAddtional -- * GoogleCloudDialogflowCxV3ResourceName , GoogleCloudDialogflowCxV3ResourceName , googleCloudDialogflowCxV3ResourceName , gcdcvrnName , gcdcvrnDisplayName -- * GoogleCloudDialogflowCxV3EnvironmentVersionConfig , GoogleCloudDialogflowCxV3EnvironmentVersionConfig , googleCloudDialogflowCxV3EnvironmentVersionConfig , gcdcvevcVersion -- * GoogleCloudDialogflowV3alpha1CreateDocumentOperationMetadata , GoogleCloudDialogflowV3alpha1CreateDocumentOperationMetadata , googleCloudDialogflowV3alpha1CreateDocumentOperationMetadata , gcdvcdomGenericMetadata -- * GoogleCloudDialogflowV2FaqAnswerMetadata , GoogleCloudDialogflowV2FaqAnswerMetadata , googleCloudDialogflowV2FaqAnswerMetadata , gcdvfamcAddtional -- * GoogleCloudDialogflowCxV3beta1WebhookRequestSentimentAnalysisResult , GoogleCloudDialogflowCxV3beta1WebhookRequestSentimentAnalysisResult , googleCloudDialogflowCxV3beta1WebhookRequestSentimentAnalysisResult , gScore , gMagnitude -- * GoogleCloudDialogflowV2IntentMessageTableCardRow , GoogleCloudDialogflowV2IntentMessageTableCardRow , googleCloudDialogflowV2IntentMessageTableCardRow , gCells , gDividerAfter -- * GoogleCloudDialogflowCxV3BatchDeleteTestCasesRequest , GoogleCloudDialogflowCxV3BatchDeleteTestCasesRequest , googleCloudDialogflowCxV3BatchDeleteTestCasesRequest , gcdcvbdtcrNames -- * GoogleCloudDialogflowCxV3SessionEntityType , GoogleCloudDialogflowCxV3SessionEntityType , googleCloudDialogflowCxV3SessionEntityType , gcdcvSetEntityOverrideMode , gcdcvSetEntities , gcdcvSetName -- * GoogleCloudDialogflowCxV3IntentParameter , GoogleCloudDialogflowCxV3IntentParameter , googleCloudDialogflowCxV3IntentParameter , gRedact , gEntityType , gId , gIsList -- * GoogleCloudDialogflowCxV3beta1WebhookRequestFulfillmentInfo , GoogleCloudDialogflowCxV3beta1WebhookRequestFulfillmentInfo , googleCloudDialogflowCxV3beta1WebhookRequestFulfillmentInfo , gTag -- * GoogleCloudDialogflowV3alpha1GenericKnowledgeOperationMetadata , GoogleCloudDialogflowV3alpha1GenericKnowledgeOperationMetadata , googleCloudDialogflowV3alpha1GenericKnowledgeOperationMetadata , gcdvgkomState -- * GoogleCloudDialogflowCxV3beta1ExportAgentResponse , GoogleCloudDialogflowCxV3beta1ExportAgentResponse , googleCloudDialogflowCxV3beta1ExportAgentResponse , gooAgentURI , gooAgentContent -- * GoogleCloudDialogflowCxV3ImportTestCasesRequest , GoogleCloudDialogflowCxV3ImportTestCasesRequest , googleCloudDialogflowCxV3ImportTestCasesRequest , gcdcvitcrContent , gcdcvitcrGcsURI -- * GoogleCloudDialogflowCxV3SecuritySettingsRedactionStrategy , GoogleCloudDialogflowCxV3SecuritySettingsRedactionStrategy (..) -- * GoogleCloudDialogflowCxV3beta1WebhookRequestIntentInfoIntentParameterValue , GoogleCloudDialogflowCxV3beta1WebhookRequestIntentInfoIntentParameterValue , googleCloudDialogflowCxV3beta1WebhookRequestIntentInfoIntentParameterValue , gcdcvwriiipvOriginalValue , gcdcvwriiipvResolvedValue -- * GoogleCloudDialogflowCxV3NluSettingsModelType , GoogleCloudDialogflowCxV3NluSettingsModelType (..) -- * GoogleCloudDialogflowV2beta1SentimentAnalysisResult , GoogleCloudDialogflowV2beta1SentimentAnalysisResult , googleCloudDialogflowV2beta1SentimentAnalysisResult , gQueryTextSentiment -- * GoogleCloudDialogflowCxV3PageInfo , GoogleCloudDialogflowCxV3PageInfo , googleCloudDialogflowCxV3PageInfo , gcdcvpiCurrentPage , gcdcvpiFormInfo -- * GoogleCloudDialogflowCxV3Environment , GoogleCloudDialogflowCxV3Environment , googleCloudDialogflowCxV3Environment , gcdcvecVersionConfigs , gcdcvecUpdateTime , gcdcvecName , gcdcvecDisplayName , gcdcvecDescription -- * GoogleCloudDialogflowCxV3ListFlowsResponse , GoogleCloudDialogflowCxV3ListFlowsResponse , googleCloudDialogflowCxV3ListFlowsResponse , gcdcvlfrNextPageToken , gcdcvlfrFlows -- * GoogleCloudDialogflowCxV3SecuritySettingsPurgeDataTypesItem , GoogleCloudDialogflowCxV3SecuritySettingsPurgeDataTypesItem (..) -- * GoogleCloudDialogflowCxV3FlowValidationResult , GoogleCloudDialogflowCxV3FlowValidationResult , googleCloudDialogflowCxV3FlowValidationResult , gcdcvfvrValidationMessages , gcdcvfvrUpdateTime , gcdcvfvrName -- * GoogleCloudDialogflowV2FaqAnswer , GoogleCloudDialogflowV2FaqAnswer , googleCloudDialogflowV2FaqAnswer , gcdvfaAnswerRecord , gcdvfaConfidence , gcdvfaAnswer , gcdvfaMetadata , gcdvfaSource , gcdvfaQuestion -- * GoogleCloudDialogflowCxV3ResponseMessageMixedAudioSegment , GoogleCloudDialogflowCxV3ResponseMessageMixedAudioSegment , googleCloudDialogflowCxV3ResponseMessageMixedAudioSegment , gURI , gAudio , gAllowPlaybackInterruption -- * GoogleCloudDialogflowCxV3beta1Page , GoogleCloudDialogflowCxV3beta1Page , googleCloudDialogflowCxV3beta1Page , gEventHandlers , gTransitionRoutes , gName , gTransitionRouteGroups , gDisplayName , gForm , gEntryFulfillment -- * GoogleCloudDialogflowCxV3beta1TestCaseResult , GoogleCloudDialogflowCxV3beta1TestCaseResult , googleCloudDialogflowCxV3beta1TestCaseResult , gcdcvtcrcEnvironment , gcdcvtcrcName , gcdcvtcrcTestResult , gcdcvtcrcTestTime , gcdcvtcrcConversationTurns -- * GoogleCloudDialogflowCxV3TestRunDifferenceType , GoogleCloudDialogflowCxV3TestRunDifferenceType (..) -- * GoogleCloudDialogflowV2QueryResultDiagnosticInfo , GoogleCloudDialogflowV2QueryResultDiagnosticInfo , googleCloudDialogflowV2QueryResultDiagnosticInfo , gcdvqrdiAddtional -- * GoogleCloudDialogflowCxV3EntityTypeEntity , GoogleCloudDialogflowCxV3EntityTypeEntity , googleCloudDialogflowCxV3EntityTypeEntity , gcdcveteValue , gcdcveteSynonyms -- * GoogleCloudDialogflowV2IntentMessageText , GoogleCloudDialogflowV2IntentMessageText , googleCloudDialogflowV2IntentMessageText , gcdvimtText -- * GoogleCloudDialogflowCxV3beta1ResponseMessageConversationSuccessMetadata , GoogleCloudDialogflowCxV3beta1ResponseMessageConversationSuccessMetadata , googleCloudDialogflowCxV3beta1ResponseMessageConversationSuccessMetadata , gcdcvrmcsmcAddtional -- * GoogleCloudDialogflowV2beta1SessionEntityTypeEntityOverrideMode , GoogleCloudDialogflowV2beta1SessionEntityTypeEntityOverrideMode (..) -- * GoogleCloudDialogflowCxV3ListTestCasesResponse , GoogleCloudDialogflowCxV3ListTestCasesResponse , googleCloudDialogflowCxV3ListTestCasesResponse , gcdcvltcrNextPageToken , gcdcvltcrTestCases -- * GoogleCloudDialogflowCxV3AudioInput , GoogleCloudDialogflowCxV3AudioInput , googleCloudDialogflowCxV3AudioInput , gooConfig , gooAudio -- * GoogleCloudDialogflowV2beta1QueryResultParameters , GoogleCloudDialogflowV2beta1QueryResultParameters , googleCloudDialogflowV2beta1QueryResultParameters , gcdvqrpAddtional -- * GoogleCloudDialogflowV2beta1IntentMessageBasicCard , GoogleCloudDialogflowV2beta1IntentMessageBasicCard , googleCloudDialogflowV2beta1IntentMessageBasicCard , gcdvimbccImage , gcdvimbccButtons , gcdvimbccSubtitle , gcdvimbccTitle , gcdvimbccFormattedText -- * GoogleCloudDialogflowCxV3beta1FulfillmentConditionalCases , GoogleCloudDialogflowCxV3beta1FulfillmentConditionalCases , googleCloudDialogflowCxV3beta1FulfillmentConditionalCases , gcdcvfccCases -- * GoogleCloudDialogflowCxV3StopExperimentRequest , GoogleCloudDialogflowCxV3StopExperimentRequest , googleCloudDialogflowCxV3StopExperimentRequest -- * GoogleCloudDialogflowV2beta1IntentTrainingPhrase , GoogleCloudDialogflowV2beta1IntentTrainingPhrase , googleCloudDialogflowV2beta1IntentTrainingPhrase , gcdvitpcParts , gcdvitpcName , gcdvitpcTimesAddedCount , gcdvitpcType -- * GoogleCloudDialogflowV2beta1ConversationEventType , GoogleCloudDialogflowV2beta1ConversationEventType (..) -- * GoogleCloudDialogflowCxV3WebhookResponse , GoogleCloudDialogflowCxV3WebhookResponse , googleCloudDialogflowCxV3WebhookResponse , gPageInfo , gSessionInfo , gPayload , gTargetPage , gTargetFlow , gFulfillmentResponse -- * GoogleCloudDialogflowCxV3beta1ConversationTurnUserInputInjectedParameters , GoogleCloudDialogflowCxV3beta1ConversationTurnUserInputInjectedParameters , googleCloudDialogflowCxV3beta1ConversationTurnUserInputInjectedParameters , gcdcvctuiipAddtional -- * GoogleCloudDialogflowCxV3ImportFlowRequestImportOption , GoogleCloudDialogflowCxV3ImportFlowRequestImportOption (..) -- * GoogleCloudDialogflowV3alpha1ReLoadDocumentOperationMetadata , GoogleCloudDialogflowV3alpha1ReLoadDocumentOperationMetadata , googleCloudDialogflowV3alpha1ReLoadDocumentOperationMetadata , gcdvrldomGenericMetadata -- * GoogleCloudDialogflowV3alpha1UpdateDocumentOperationMetadata , GoogleCloudDialogflowV3alpha1UpdateDocumentOperationMetadata , googleCloudDialogflowV3alpha1UpdateDocumentOperationMetadata , gcdvudomGenericMetadata -- * GoogleCloudDialogflowV3alpha1DeleteDocumentOperationMetadata , GoogleCloudDialogflowV3alpha1DeleteDocumentOperationMetadata , googleCloudDialogflowV3alpha1DeleteDocumentOperationMetadata , gcdvddomGenericMetadata -- * GoogleCloudDialogflowCxV3beta1ResponseMessageMixedAudio , GoogleCloudDialogflowCxV3beta1ResponseMessageMixedAudio , googleCloudDialogflowCxV3beta1ResponseMessageMixedAudio , gcdcvrmmaSegments -- * GoogleCloudDialogflowV2beta1KnowledgeAnswersAnswer , GoogleCloudDialogflowV2beta1KnowledgeAnswersAnswer , googleCloudDialogflowV2beta1KnowledgeAnswersAnswer , gcdvkaaMatchConfidence , gcdvkaaAnswer , gcdvkaaSource , gcdvkaaFaqQuestion , gcdvkaaMatchConfidenceLevel -- * GoogleCloudDialogflowCxV3ValidationMessage , GoogleCloudDialogflowCxV3ValidationMessage , googleCloudDialogflowCxV3ValidationMessage , gcdcvvmResourceType , gcdcvvmSeverity , gcdcvvmResources , gcdcvvmResourceNames , gcdcvvmDetail -- * GoogleCloudDialogflowV2beta1FaqAnswer , GoogleCloudDialogflowV2beta1FaqAnswer , googleCloudDialogflowV2beta1FaqAnswer , gooAnswerRecord , gooConfidence , gooAnswer , gooMetadata , gooSource , gooQuestion -- * GoogleCloudDialogflowV2beta1EventInput , GoogleCloudDialogflowV2beta1EventInput , googleCloudDialogflowV2beta1EventInput , gcdveicLanguageCode , gcdveicName , gcdveicParameters -- * GoogleCloudDialogflowCxV3beta1ConversationTurn , GoogleCloudDialogflowCxV3beta1ConversationTurn , googleCloudDialogflowCxV3beta1ConversationTurn , gUserInput , gVirtualAgentOutput -- * GoogleCloudDialogflowV2IntentMessagePayload , GoogleCloudDialogflowV2IntentMessagePayload , googleCloudDialogflowV2IntentMessagePayload , gcdvimpcAddtional -- * GoogleCloudDialogflowV2beta1KnowledgeOperationMetadata , GoogleCloudDialogflowV2beta1KnowledgeOperationMetadata , googleCloudDialogflowV2beta1KnowledgeOperationMetadata , gooState -- * GoogleCloudDialogflowV2beta1WebhookRequest , GoogleCloudDialogflowV2beta1WebhookRequest , googleCloudDialogflowV2beta1WebhookRequest , gooOriginalDetectIntentRequest , gooResponseId , gooAlternativeQueryResults , gooQueryResult , gooSession -- * GoogleCloudDialogflowV2IntentTrainingPhraseType , GoogleCloudDialogflowV2IntentTrainingPhraseType (..) -- * GoogleCloudDialogflowCxV3ContinuousTestResultResult , GoogleCloudDialogflowCxV3ContinuousTestResultResult (..) -- * GoogleCloudDialogflowV2ConversationEventType , GoogleCloudDialogflowV2ConversationEventType (..) -- * GoogleCloudDialogflowCxV3beta1WebhookRequestIntentInfo , GoogleCloudDialogflowCxV3beta1WebhookRequestIntentInfo , googleCloudDialogflowCxV3beta1WebhookRequestIntentInfo , gcdcvwriicLastMatchedIntent , gcdcvwriicConfidence , gcdcvwriicParameters , gcdcvwriicDisplayName -- * GoogleCloudDialogflowV2beta1IntentMessageText , GoogleCloudDialogflowV2beta1IntentMessageText , googleCloudDialogflowV2beta1IntentMessageText , gcdvimtcText -- * GoogleCloudDialogflowV2IntentMessageSimpleResponses , GoogleCloudDialogflowV2IntentMessageSimpleResponses , googleCloudDialogflowV2IntentMessageSimpleResponses , gSimpleResponses -- * GoogleCloudDialogflowCxV3RestoreAgentRequestRestoreOption , GoogleCloudDialogflowCxV3RestoreAgentRequestRestoreOption (..) -- * GoogleCloudDialogflowCxV3Webhook , GoogleCloudDialogflowCxV3Webhook , googleCloudDialogflowCxV3Webhook , gcdcvwGenericWebService , gcdcvwServiceDirectory , gcdcvwDisabled , gcdcvwName , gcdcvwDisplayName , gcdcvwTimeout -- * GoogleCloudDialogflowV2beta1IntentFollowupIntentInfo , GoogleCloudDialogflowV2beta1IntentFollowupIntentInfo , googleCloudDialogflowV2beta1IntentFollowupIntentInfo , gFollowupIntentName , gParentFollowupIntentName -- * GoogleCloudDialogflowCxV3ValidationMessageSeverity , GoogleCloudDialogflowCxV3ValidationMessageSeverity (..) -- * GoogleCloudDialogflowV2QueryResultParameters , GoogleCloudDialogflowV2QueryResultParameters , googleCloudDialogflowV2QueryResultParameters , gcdvqrpsAddtional -- * GoogleCloudDialogflowCxV3ListTransitionRouteGroupsResponse , GoogleCloudDialogflowCxV3ListTransitionRouteGroupsResponse , googleCloudDialogflowCxV3ListTransitionRouteGroupsResponse , gcdcvltrgrNextPageToken , gcdcvltrgrTransitionRouteGroups -- * GoogleCloudDialogflowCxV3DetectIntentResponseResponseType , GoogleCloudDialogflowCxV3DetectIntentResponseResponseType (..) -- * GoogleCloudDialogflowV2beta1QueryResultDiagnosticInfo , GoogleCloudDialogflowV2beta1QueryResultDiagnosticInfo , googleCloudDialogflowV2beta1QueryResultDiagnosticInfo , gcdvqrdicAddtional -- * GoogleCloudDialogflowCxV3ConversationTurnUserInputInjectedParameters , GoogleCloudDialogflowCxV3ConversationTurnUserInputInjectedParameters , googleCloudDialogflowCxV3ConversationTurnUserInputInjectedParameters , gcdcvctuiipsAddtional -- * GoogleCloudDialogflowV2BatchUpdateIntentsResponse , GoogleCloudDialogflowV2BatchUpdateIntentsResponse , googleCloudDialogflowV2BatchUpdateIntentsResponse , gIntents -- * GoogleCloudDialogflowCxV3FulfillmentConditionalCases , GoogleCloudDialogflowCxV3FulfillmentConditionalCases , googleCloudDialogflowCxV3FulfillmentConditionalCases , gCases -- * GoogleCloudDialogflowCxV3Match , GoogleCloudDialogflowCxV3Match , googleCloudDialogflowCxV3Match , gcdcvmEvent , gcdcvmMatchType , gcdcvmResolvedInput , gcdcvmConfidence , gcdcvmIntent , gcdcvmParameters -- * GoogleCloudDialogflowV2beta1AnnotatedMessagePart , GoogleCloudDialogflowV2beta1AnnotatedMessagePart , googleCloudDialogflowV2beta1AnnotatedMessagePart , gcdvampcText , gcdvampcEntityType , gcdvampcFormattedValue -- * GoogleCloudDialogflowCxV3beta1TestRunDifferenceType , GoogleCloudDialogflowCxV3beta1TestRunDifferenceType (..) -- * GoogleCloudDialogflowCxV3QueryResult , GoogleCloudDialogflowCxV3QueryResult , googleCloudDialogflowCxV3QueryResult , gcdcvqrTriggerIntent , gcdcvqrLanguageCode , gcdcvqrIntentDetectionConfidence , gcdcvqrCurrentPage , gcdcvqrText , gcdcvqrWebhookPayloads , gcdcvqrWebhookStatuses , gcdcvqrIntent , gcdcvqrTriggerEvent , gcdcvqrSentimentAnalysisResult , gcdcvqrParameters , gcdcvqrMatch , gcdcvqrResponseMessages , gcdcvqrTranscript , gcdcvqrDiagnosticInfo -- * GoogleCloudDialogflowCxV3AgentValidationResult , GoogleCloudDialogflowCxV3AgentValidationResult , googleCloudDialogflowCxV3AgentValidationResult , gcdcvavrFlowValidationResults , gcdcvavrName -- * GoogleCloudDialogflowV2IntentMessageColumnPropertiesHorizontalAlignment , GoogleCloudDialogflowV2IntentMessageColumnPropertiesHorizontalAlignment (..) -- * GoogleCloudDialogflowV2beta1SuggestSmartRepliesResponse , GoogleCloudDialogflowV2beta1SuggestSmartRepliesResponse , googleCloudDialogflowV2beta1SuggestSmartRepliesResponse , gcdvssrrSmartReplyAnswers , gcdvssrrContextSize , gcdvssrrLatestMessage -- * GoogleCloudDialogflowCxV3ResponseMessageMixedAudio , GoogleCloudDialogflowCxV3ResponseMessageMixedAudio , googleCloudDialogflowCxV3ResponseMessageMixedAudio , gSegments -- * GoogleCloudDialogflowCxV3beta1WebhookResponse , GoogleCloudDialogflowCxV3beta1WebhookResponse , googleCloudDialogflowCxV3beta1WebhookResponse , ggPageInfo , ggSessionInfo , ggPayload , ggTargetPage , ggTargetFlow , ggFulfillmentResponse -- * GoogleCloudDialogflowV2SessionEntityTypeEntityOverrideMode , GoogleCloudDialogflowV2SessionEntityTypeEntityOverrideMode (..) -- * GoogleCloudDialogflowV2beta1IntentMessage , GoogleCloudDialogflowV2beta1IntentMessage , googleCloudDialogflowV2beta1IntentMessage , gcdvimRbmStandaloneRichCard , gcdvimCard , gcdvimImage , gcdvimPlatform , gcdvimBrowseCarouselCard , gcdvimTableCard , gcdvimLinkOutSuggestion , gcdvimText , gcdvimCarouselSelect , gcdvimRbmText , gcdvimTelephonySynthesizeSpeech , gcdvimSimpleResponses , gcdvimPayload , gcdvimTelephonyTransferCall , gcdvimRbmCarouselRichCard , gcdvimSuggestions , gcdvimListSelect , gcdvimTelephonyPlayAudio , gcdvimMediaContent , gcdvimBasicCard , gcdvimQuickReplies -- * GoogleCloudDialogflowCxV3DeleteDocumentOperationMetadata , GoogleCloudDialogflowCxV3DeleteDocumentOperationMetadata , googleCloudDialogflowCxV3DeleteDocumentOperationMetadata , gcdcvddomGenericMetadata -- * GoogleCloudDialogflowCxV3IntentCoverageIntent , GoogleCloudDialogflowCxV3IntentCoverageIntent , googleCloudDialogflowCxV3IntentCoverageIntent , gcdcviciIntent , gcdcviciCovered -- * GoogleCloudDialogflowCxV3TransitionCoverageTransitionNode , GoogleCloudDialogflowCxV3TransitionCoverageTransitionNode , googleCloudDialogflowCxV3TransitionCoverageTransitionNode , gcdcvtctnFlow , gcdcvtctnPage -- * GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedActionRbmSuggestedActionShareLocation , GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedActionRbmSuggestedActionShareLocation , googleCloudDialogflowV2beta1IntentMessageRbmSuggestedActionRbmSuggestedActionShareLocation -- * GoogleCloudDialogflowCxV3TransitionCoverageTransition , GoogleCloudDialogflowCxV3TransitionCoverageTransition , googleCloudDialogflowCxV3TransitionCoverageTransition , gcdcvtctTransitionRoute , gcdcvtctEventHandler , gcdcvtctCovered , gcdcvtctSource , gcdcvtctIndex , gcdcvtctTarget -- * GoogleCloudDialogflowCxV3beta1PageInfoFormInfoParameterInfoState , GoogleCloudDialogflowCxV3beta1PageInfoFormInfoParameterInfoState (..) -- * GoogleCloudDialogflowCxV3VersionVariants , GoogleCloudDialogflowCxV3VersionVariants , googleCloudDialogflowCxV3VersionVariants , gcdcvvvVariants -- * GoogleCloudDialogflowCxV3WebhookRequestIntentInfoIntentParameterValue , GoogleCloudDialogflowCxV3WebhookRequestIntentInfoIntentParameterValue , googleCloudDialogflowCxV3WebhookRequestIntentInfoIntentParameterValue , gOriginalValue , gResolvedValue -- * GoogleCloudDialogflowV2IntentMessageSelectItemInfo , GoogleCloudDialogflowV2IntentMessageSelectItemInfo , googleCloudDialogflowV2IntentMessageSelectItemInfo , gcdvimsiiKey , gcdvimsiiSynonyms -- * GoogleCloudDialogflowCxV3CreateVersionOperationMetadata , GoogleCloudDialogflowCxV3CreateVersionOperationMetadata , googleCloudDialogflowCxV3CreateVersionOperationMetadata , gVersion -- * GoogleCloudDialogflowV2beta1Sentiment , GoogleCloudDialogflowV2beta1Sentiment , googleCloudDialogflowV2beta1Sentiment , gcdvsScore , gcdvsMagnitude -- * GoogleCloudDialogflowCxV3ExperimentState , GoogleCloudDialogflowCxV3ExperimentState (..) -- * GoogleCloudDialogflowCxV3ResponseMessageConversationSuccess , GoogleCloudDialogflowCxV3ResponseMessageConversationSuccess , googleCloudDialogflowCxV3ResponseMessageConversationSuccess , gcdcvrmcssMetadata -- * Xgafv , Xgafv (..) -- * GoogleCloudDialogflowCxV3ReLoadDocumentOperationMetadata , GoogleCloudDialogflowCxV3ReLoadDocumentOperationMetadata , googleCloudDialogflowCxV3ReLoadDocumentOperationMetadata , gcdcvrldomGenericMetadata -- * GoogleCloudDialogflowCxV3beta1ExportFlowResponse , GoogleCloudDialogflowCxV3beta1ExportFlowResponse , googleCloudDialogflowCxV3beta1ExportFlowResponse , gFlowContent , gFlowURI -- * GoogleCloudDialogflowCxV3beta1PageInfo , GoogleCloudDialogflowCxV3beta1PageInfo , googleCloudDialogflowCxV3beta1PageInfo , gCurrentPage , gFormInfo -- * GoogleCloudDialogflowV2beta1IntentMessageCarouselSelect , GoogleCloudDialogflowV2beta1IntentMessageCarouselSelect , googleCloudDialogflowV2beta1IntentMessageCarouselSelect , gcdvimcsItems -- * GoogleCloudDialogflowV2beta1Context , GoogleCloudDialogflowV2beta1Context , googleCloudDialogflowV2beta1Context , gcdvcLifespanCount , gcdvcName , gcdvcParameters -- * GoogleCloudDialogflowCxV3ResponseMessagePayload , GoogleCloudDialogflowCxV3ResponseMessagePayload , googleCloudDialogflowCxV3ResponseMessagePayload , gcdcvrmpcAddtional -- * GoogleCloudDialogflowCxV3UpdateDocumentOperationMetadata , GoogleCloudDialogflowCxV3UpdateDocumentOperationMetadata , googleCloudDialogflowCxV3UpdateDocumentOperationMetadata , gcdcvudomGenericMetadata -- * GoogleCloudDialogflowCxV3RunTestCaseMetadata , GoogleCloudDialogflowCxV3RunTestCaseMetadata , googleCloudDialogflowCxV3RunTestCaseMetadata -- * GoogleCloudDialogflowCxV3TestError , GoogleCloudDialogflowCxV3TestError , googleCloudDialogflowCxV3TestError , gcdcvteStatus , gcdcvteTestCase , gcdcvteTestTime -- * GoogleLongrunningOperationResponse , GoogleLongrunningOperationResponse , googleLongrunningOperationResponse , glorAddtional -- * GoogleCloudDialogflowCxV3TransitionRoute , GoogleCloudDialogflowCxV3TransitionRoute , googleCloudDialogflowCxV3TransitionRoute , gcdcvtrTriggerFulfillment , gcdcvtrIntent , gcdcvtrName , gcdcvtrTargetPage , gcdcvtrCondition , gcdcvtrTargetFlow -- * GoogleCloudDialogflowCxV3ResponseMessageLiveAgentHandoffMetadata , GoogleCloudDialogflowCxV3ResponseMessageLiveAgentHandoffMetadata , googleCloudDialogflowCxV3ResponseMessageLiveAgentHandoffMetadata , gcdcvrmlahmAddtional -- * GoogleCloudDialogflowCxV3TransitionRouteGroupCoverageCoverageTransition , GoogleCloudDialogflowCxV3TransitionRouteGroupCoverageCoverageTransition , googleCloudDialogflowCxV3TransitionRouteGroupCoverageCoverageTransition , gcdcvtrgcctTransitionRoute , gcdcvtrgcctCovered -- * GoogleCloudDialogflowCxV3ExportTestCasesResponse , GoogleCloudDialogflowCxV3ExportTestCasesResponse , googleCloudDialogflowCxV3ExportTestCasesResponse , gcdcvetcrContent , gcdcvetcrGcsURI -- * GoogleCloudDialogflowCxV3beta1ResponseMessageEndInteraction , GoogleCloudDialogflowCxV3beta1ResponseMessageEndInteraction , googleCloudDialogflowCxV3beta1ResponseMessageEndInteraction -- * GoogleCloudDialogflowCxV3beta1DtmfInput , GoogleCloudDialogflowCxV3beta1DtmfInput , googleCloudDialogflowCxV3beta1DtmfInput , gcdcvdiDigits , gcdcvdiFinishDigit -- * GoogleCloudDialogflowCxV3ConversationTurnVirtualAgentOutputDiagnosticInfo , GoogleCloudDialogflowCxV3ConversationTurnVirtualAgentOutputDiagnosticInfo , googleCloudDialogflowCxV3ConversationTurnVirtualAgentOutputDiagnosticInfo , gcdcvctvaodicAddtional -- * GoogleCloudDialogflowCxV3beta1WebhookResponseFulfillmentResponseMergeBehavior , GoogleCloudDialogflowCxV3beta1WebhookResponseFulfillmentResponseMergeBehavior (..) -- * GoogleCloudDialogflowCxV3ImportFlowRequest , GoogleCloudDialogflowCxV3ImportFlowRequest , googleCloudDialogflowCxV3ImportFlowRequest , gcdcvifrFlowContent , gcdcvifrFlowURI , gcdcvifrImportOption -- * GoogleCloudDialogflowCxV3QueryParametersPayload , GoogleCloudDialogflowCxV3QueryParametersPayload , googleCloudDialogflowCxV3QueryParametersPayload , gcdcvqppcAddtional -- * GoogleCloudDialogflowCxV3beta1PageInfoFormInfo , GoogleCloudDialogflowCxV3beta1PageInfoFormInfo , googleCloudDialogflowCxV3beta1PageInfoFormInfo , gParameterInfo -- * GoogleCloudDialogflowV2beta1IntentMessageRbmText , GoogleCloudDialogflowV2beta1IntentMessageRbmText , googleCloudDialogflowV2beta1IntentMessageRbmText , gcdvimrtText , gcdvimrtRbmSuggestion -- * GoogleCloudDialogflowV2beta1IntentMessageTelephonySynthesizeSpeech , GoogleCloudDialogflowV2beta1IntentMessageTelephonySynthesizeSpeech , googleCloudDialogflowV2beta1IntentMessageTelephonySynthesizeSpeech , gcdvimtssText , gcdvimtssSsml -- * GoogleCloudDialogflowCxV3IntentTrainingPhrasePart , GoogleCloudDialogflowCxV3IntentTrainingPhrasePart , googleCloudDialogflowCxV3IntentTrainingPhrasePart , gcdcvitppcParameterId , gcdcvitppcText -- * GoogleCloudDialogflowCxV3ListWebhooksResponse , GoogleCloudDialogflowCxV3ListWebhooksResponse , googleCloudDialogflowCxV3ListWebhooksResponse , gcdcvlwrNextPageToken , gcdcvlwrWebhooks -- * GoogleCloudDialogflowCxV3beta1Fulfillment , GoogleCloudDialogflowCxV3beta1Fulfillment , googleCloudDialogflowCxV3beta1Fulfillment , gooTag , gooConditionalCases , gooReturnPartialResponses , gooMessages , gooWebhook , gooSetParameterActions -- * GoogleCloudDialogflowCxV3RunContinuousTestResponse , GoogleCloudDialogflowCxV3RunContinuousTestResponse , googleCloudDialogflowCxV3RunContinuousTestResponse , gContinuousTestResult -- * GoogleCloudDialogflowCxV3beta1SessionInfoParameters , GoogleCloudDialogflowCxV3beta1SessionInfoParameters , googleCloudDialogflowCxV3beta1SessionInfoParameters , gcdcvsipsAddtional -- * GoogleCloudDialogflowV2beta1IntentMessageListSelectItem , GoogleCloudDialogflowV2beta1IntentMessageListSelectItem , googleCloudDialogflowV2beta1IntentMessageListSelectItem , gcdvimlsicImage , gcdvimlsicTitle , gcdvimlsicDescription , gcdvimlsicInfo -- * GoogleCloudDialogflowV2IntentMessageSuggestion , GoogleCloudDialogflowV2IntentMessageSuggestion , googleCloudDialogflowV2IntentMessageSuggestion , gcdvimscTitle -- * GoogleCloudDialogflowV2IntentMessageTableCardCell , GoogleCloudDialogflowV2IntentMessageTableCardCell , googleCloudDialogflowV2IntentMessageTableCardCell , gcdvimtccText -- * GoogleCloudDialogflowCxV3beta1ResponseMessagePlayAudio , GoogleCloudDialogflowCxV3beta1ResponseMessagePlayAudio , googleCloudDialogflowCxV3beta1ResponseMessagePlayAudio , gcdcvrmpaAudioURI , gcdcvrmpaAllowPlaybackInterruption -- * GoogleCloudDialogflowV2beta1EntityTypeEntity , GoogleCloudDialogflowV2beta1EntityTypeEntity , googleCloudDialogflowV2beta1EntityTypeEntity , gcdveteValue , gcdveteSynonyms -- * GoogleCloudDialogflowV2EntityType , GoogleCloudDialogflowV2EntityType , googleCloudDialogflowV2EntityType , gcdvetEntities , gcdvetKind , gcdvetName , gcdvetAutoExpansionMode , gcdvetDisplayName , gcdvetEnableFuzzyExtraction -- * GoogleCloudDialogflowV2beta1IntentMessagePlatform , GoogleCloudDialogflowV2beta1IntentMessagePlatform (..) -- * GoogleCloudDialogflowCxV3VersionVariantsVariant , GoogleCloudDialogflowCxV3VersionVariantsVariant , googleCloudDialogflowCxV3VersionVariantsVariant , gcdcvvvvIsControlGroup , gcdcvvvvTrafficAllocation , gcdcvvvvVersion -- * GoogleCloudDialogflowV2EntityTypeKind , GoogleCloudDialogflowV2EntityTypeKind (..) -- * GoogleCloudDialogflowV2IntentMessageBasicCardButtonOpenURIAction , GoogleCloudDialogflowV2IntentMessageBasicCardButtonOpenURIAction , googleCloudDialogflowV2IntentMessageBasicCardButtonOpenURIAction , gcdvimbcbouriaURI -- * GoogleCloudDialogflowCxV3beta1ImportDocumentsResponse , GoogleCloudDialogflowCxV3beta1ImportDocumentsResponse , googleCloudDialogflowCxV3beta1ImportDocumentsResponse , gWarnings -- * GoogleCloudDialogflowCxV3TransitionRouteGroupCoverageCoverage , GoogleCloudDialogflowCxV3TransitionRouteGroupCoverageCoverage , googleCloudDialogflowCxV3TransitionRouteGroupCoverageCoverage , gcdcvtrgccTransitions , gcdcvtrgccCoverageScore , gcdcvtrgccRouteGroup -- * GoogleCloudDialogflowCxV3ImportDocumentsOperationMetadata , GoogleCloudDialogflowCxV3ImportDocumentsOperationMetadata , googleCloudDialogflowCxV3ImportDocumentsOperationMetadata , gcdcvidomGenericMetadata -- * GoogleCloudDialogflowCxV3beta1TestCase , GoogleCloudDialogflowCxV3beta1TestCase , googleCloudDialogflowCxV3beta1TestCase , gcdcvtcCreationTime , gcdcvtcLastTestResult , gcdcvtcTestConfig , gcdcvtcName , gcdcvtcDisplayName , gcdcvtcNotes , gcdcvtcTags , gcdcvtcTestCaseConversationTurns -- * GoogleCloudDialogflowV2IntentMessageCard , GoogleCloudDialogflowV2IntentMessageCard , googleCloudDialogflowV2IntentMessageCard , gcdvimccButtons , gcdvimccImageURI , gcdvimccSubtitle , gcdvimccTitle -- * GoogleCloudDialogflowCxV3beta1FulfillmentConditionalCasesCaseCaseContent , GoogleCloudDialogflowCxV3beta1FulfillmentConditionalCasesCaseCaseContent , googleCloudDialogflowCxV3beta1FulfillmentConditionalCasesCaseCaseContent , gcdcvfcccccAdditionalCases , gcdcvfcccccMessage -- * GoogleCloudDialogflowCxV3BatchRunTestCasesMetadata , GoogleCloudDialogflowCxV3BatchRunTestCasesMetadata , googleCloudDialogflowCxV3BatchRunTestCasesMetadata , gooErrors -- * GoogleCloudDialogflowCxV3IntentTrainingPhrase , GoogleCloudDialogflowCxV3IntentTrainingPhrase , googleCloudDialogflowCxV3IntentTrainingPhrase , gcdcvitpParts , gcdcvitpRepeatCount , gcdcvitpId -- * GoogleCloudDialogflowV2OriginalDetectIntentRequest , GoogleCloudDialogflowV2OriginalDetectIntentRequest , googleCloudDialogflowV2OriginalDetectIntentRequest , gcdvodircPayload , gcdvodircVersion , gcdvodircSource -- * GoogleCloudDialogflowV2beta1IntentWebhookState , GoogleCloudDialogflowV2beta1IntentWebhookState (..) -- * GoogleCloudDialogflowV2beta1IntentMessageImage , GoogleCloudDialogflowV2beta1IntentMessageImage , googleCloudDialogflowV2beta1IntentMessageImage , gcdvimiAccessibilityText , gcdvimiImageURI -- * GoogleCloudDialogflowCxV3TransitionCoverage , GoogleCloudDialogflowCxV3TransitionCoverage , googleCloudDialogflowCxV3TransitionCoverage , gcdcvtcTransitions , gcdcvtcCoverageScore -- * GoogleCloudDialogflowCxV3TransitionRouteGroup , GoogleCloudDialogflowCxV3TransitionRouteGroup , googleCloudDialogflowCxV3TransitionRouteGroup , gcdcvtrgTransitionRoutes , gcdcvtrgName , gcdcvtrgDisplayName -- * GoogleCloudDialogflowV2beta1SessionEntityType , GoogleCloudDialogflowV2beta1SessionEntityType , googleCloudDialogflowV2beta1SessionEntityType , gcdvSetEntityOverrideMode , gcdvSetEntities , gcdvSetName -- * GoogleCloudDialogflowV2ExportAgentResponse , GoogleCloudDialogflowV2ExportAgentResponse , googleCloudDialogflowV2ExportAgentResponse , gcdvearAgentURI , gcdvearAgentContent -- * GoogleCloudDialogflowV2WebhookResponsePayload , GoogleCloudDialogflowV2WebhookResponsePayload , googleCloudDialogflowV2WebhookResponsePayload , gcdvwrpcAddtional -- * GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedActionRbmSuggestedActionOpenURI , GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedActionRbmSuggestedActionOpenURI , googleCloudDialogflowV2beta1IntentMessageRbmSuggestedActionRbmSuggestedActionOpenURI , gcdvimrsarsaouURI -- * GoogleCloudDialogflowV2beta1IntentMessageLinkOutSuggestion , GoogleCloudDialogflowV2beta1IntentMessageLinkOutSuggestion , googleCloudDialogflowV2beta1IntentMessageLinkOutSuggestion , gooURI , gooDestinationName -- * GoogleCloudDialogflowCxV3SentimentAnalysisResult , GoogleCloudDialogflowCxV3SentimentAnalysisResult , googleCloudDialogflowCxV3SentimentAnalysisResult , gcdcvsarScore , gcdcvsarMagnitude -- * GoogleCloudDialogflowCxV3beta1ImportTestCasesResponse , GoogleCloudDialogflowCxV3beta1ImportTestCasesResponse , googleCloudDialogflowCxV3beta1ImportTestCasesResponse , gcdcvitcrNames -- * GoogleCloudDialogflowCxV3ImportFlowResponse , GoogleCloudDialogflowCxV3ImportFlowResponse , googleCloudDialogflowCxV3ImportFlowResponse , gFlow -- * GoogleCloudDialogflowCxV3TestCaseResultTestResult , GoogleCloudDialogflowCxV3TestCaseResultTestResult (..) -- * GoogleCloudDialogflowCxV3FormParameterFillBehavior , GoogleCloudDialogflowCxV3FormParameterFillBehavior , googleCloudDialogflowCxV3FormParameterFillBehavior , gcdcvfpfbRepromptEventHandlers , gcdcvfpfbInitialPromptFulfillment -- * GoogleCloudDialogflowCxV3Intent , GoogleCloudDialogflowCxV3Intent , googleCloudDialogflowCxV3Intent , gcdcvicPriority , gcdcvicName , gcdcvicParameters , gcdcvicDisplayName , gcdcvicLabels , gcdcvicTrainingPhrases , gcdcvicDescription , gcdcvicIsFallback -- * GoogleCloudDialogflowV2BatchUpdateEntityTypesResponse , GoogleCloudDialogflowV2BatchUpdateEntityTypesResponse , googleCloudDialogflowV2BatchUpdateEntityTypesResponse , gEntityTypes -- * GoogleCloudDialogflowCxV3SecuritySettingsRedactionScope , GoogleCloudDialogflowCxV3SecuritySettingsRedactionScope (..) -- * GoogleCloudDialogflowCxV3TestConfig , GoogleCloudDialogflowCxV3TestConfig , googleCloudDialogflowCxV3TestConfig , gooFlow , gooTrackingParameters -- * GoogleCloudDialogflowV2beta1ArticleAnswerMetadata , GoogleCloudDialogflowV2beta1ArticleAnswerMetadata , googleCloudDialogflowV2beta1ArticleAnswerMetadata , gcdvaamAddtional -- * GoogleCloudDialogflowCxV3ExportTestCasesRequest , GoogleCloudDialogflowCxV3ExportTestCasesRequest , googleCloudDialogflowCxV3ExportTestCasesRequest , gDataFormat , gFilter , gGcsURI -- * GoogleCloudDialogflowV2QueryResultWebhookPayload , GoogleCloudDialogflowV2QueryResultWebhookPayload , googleCloudDialogflowV2QueryResultWebhookPayload , gcdvqrwpAddtional -- * GoogleCloudDialogflowCxV3beta1FormParameter , GoogleCloudDialogflowCxV3beta1FormParameter , googleCloudDialogflowCxV3beta1FormParameter , gcdcvfpRedact , gcdcvfpEntityType , gcdcvfpFillBehavior , gcdcvfpRequired , gcdcvfpDisplayName , gcdcvfpDefaultValue , gcdcvfpIsList -- * GoogleCloudDialogflowCxV3GenericKnowledgeOperationMetadataState , GoogleCloudDialogflowCxV3GenericKnowledgeOperationMetadataState (..) -- * GoogleCloudDialogflowCxV3EventHandler , GoogleCloudDialogflowCxV3EventHandler , googleCloudDialogflowCxV3EventHandler , gcdcvehcEvent , gcdcvehcTriggerFulfillment , gcdcvehcName , gcdcvehcTargetPage , gcdcvehcTargetFlow -- * GoogleCloudDialogflowV2beta1IntentParameter , GoogleCloudDialogflowV2beta1IntentParameter , googleCloudDialogflowV2beta1IntentParameter , gcdvipValue , gcdvipName , gcdvipPrompts , gcdvipMandatory , gcdvipDisplayName , gcdvipDefaultValue , gcdvipIsList , gcdvipEntityTypeDisplayName -- * GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard , GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard , googleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard , gcdvimbccItems , gcdvimbccImageDisplayOptions -- * GoogleCloudDialogflowV2beta1IntentMessageTableCard , GoogleCloudDialogflowV2beta1IntentMessageTableCard , googleCloudDialogflowV2beta1IntentMessageTableCard , gcdvimtccImage , gcdvimtccButtons , gcdvimtccRows , gcdvimtccSubtitle , gcdvimtccColumnProperties , gcdvimtccTitle -- * GoogleCloudDialogflowCxV3beta1FulfillmentSetParameterAction , GoogleCloudDialogflowCxV3beta1FulfillmentSetParameterAction , googleCloudDialogflowCxV3beta1FulfillmentSetParameterAction , gcdcvfspaValue , gcdcvfspaParameter -- * GoogleCloudDialogflowV3alpha1ImportDocumentsResponse , GoogleCloudDialogflowV3alpha1ImportDocumentsResponse , googleCloudDialogflowV3alpha1ImportDocumentsResponse , gooWarnings -- * GoogleCloudDialogflowCxV3ExperimentResultMetric , GoogleCloudDialogflowCxV3ExperimentResultMetric , googleCloudDialogflowCxV3ExperimentResultMetric , gcdcvermConfidenceInterval , gcdcvermCount , gcdcvermRatio , gcdcvermType , gcdcvermCountType -- * GoogleCloudDialogflowV2EntityTypeAutoExpansionMode , GoogleCloudDialogflowV2EntityTypeAutoExpansionMode (..) -- * GoogleCloudDialogflowCxV3VoiceSelectionParamsSsmlGender , GoogleCloudDialogflowCxV3VoiceSelectionParamsSsmlGender (..) -- * GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedReply , GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedReply , googleCloudDialogflowV2beta1IntentMessageRbmSuggestedReply , gcdvimrsrText , gcdvimrsrPostbackData -- * GoogleCloudDialogflowCxV3beta1ConversationTurnVirtualAgentOutput , GoogleCloudDialogflowCxV3beta1ConversationTurnVirtualAgentOutput , googleCloudDialogflowCxV3beta1ConversationTurnVirtualAgentOutput , gooStatus , gooCurrentPage , gooSessionParameters , gooDifferences , gooTextResponses , gooTriggeredIntent , gooDiagnosticInfo -- * GoogleCloudDialogflowV2beta1HumanAgentAssistantEvent , GoogleCloudDialogflowV2beta1HumanAgentAssistantEvent , googleCloudDialogflowV2beta1HumanAgentAssistantEvent , gooConversation , gooParticipant , gooSuggestionResults -- * GoogleLongrunningListOperationsResponse , GoogleLongrunningListOperationsResponse , googleLongrunningListOperationsResponse , gllorNextPageToken , gllorOperations -- * GoogleCloudDialogflowCxV3beta1FormParameterFillBehavior , GoogleCloudDialogflowCxV3beta1FormParameterFillBehavior , googleCloudDialogflowCxV3beta1FormParameterFillBehavior , gRepromptEventHandlers , gInitialPromptFulfillment -- * GoogleCloudDialogflowV2SuggestionResult , GoogleCloudDialogflowV2SuggestionResult , googleCloudDialogflowV2SuggestionResult , gError , gSuggestFaqAnswersResponse , gSuggestArticlesResponse -- * GoogleCloudDialogflowV2IntentParameter , GoogleCloudDialogflowV2IntentParameter , googleCloudDialogflowV2IntentParameter , gcdvipcValue , gcdvipcName , gcdvipcPrompts , gcdvipcMandatory , gcdvipcDisplayName , gcdvipcDefaultValue , gcdvipcIsList , gcdvipcEntityTypeDisplayName -- * GoogleCloudDialogflowV2beta1QueryResultWebhookPayload , GoogleCloudDialogflowV2beta1QueryResultWebhookPayload , googleCloudDialogflowV2beta1QueryResultWebhookPayload , gcdvqrwpcAddtional -- * GoogleCloudDialogflowV2beta1IntentTrainingPhrasePart , GoogleCloudDialogflowV2beta1IntentTrainingPhrasePart , googleCloudDialogflowV2beta1IntentTrainingPhrasePart , gcdvitppcText , gcdvitppcUserDefined , gcdvitppcEntityType , gcdvitppcAlias -- * GoogleCloudDialogflowV2beta1EntityTypeAutoExpansionMode , GoogleCloudDialogflowV2beta1EntityTypeAutoExpansionMode (..) -- * GoogleCloudDialogflowCxV3ExportTestCasesRequestDataFormat , GoogleCloudDialogflowCxV3ExportTestCasesRequestDataFormat (..) -- * GoogleCloudDialogflowV2IntentMessageBrowseCarouselCard , GoogleCloudDialogflowV2IntentMessageBrowseCarouselCard , googleCloudDialogflowV2IntentMessageBrowseCarouselCard , gItems , gImageDisplayOptions -- * GoogleCloudDialogflowCxV3beta1QueryInput , GoogleCloudDialogflowCxV3beta1QueryInput , googleCloudDialogflowCxV3beta1QueryInput , gcdcvqicEvent , gcdcvqicLanguageCode , gcdcvqicText , gcdcvqicIntent , gcdcvqicDtmf , gcdcvqicAudio -- * GoogleCloudDialogflowV2beta1IntentMessageTelephonyTransferCall , GoogleCloudDialogflowV2beta1IntentMessageTelephonyTransferCall , googleCloudDialogflowV2beta1IntentMessageTelephonyTransferCall , gcdvimttcPhoneNumber -- * GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestion , GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestion , googleCloudDialogflowV2beta1IntentMessageRbmSuggestion , gcdvimrsReply , gcdvimrsAction -- * GoogleCloudDialogflowCxV3ExportFlowRequest , GoogleCloudDialogflowCxV3ExportFlowRequest , googleCloudDialogflowCxV3ExportFlowRequest , gooIncludeReferencedFlows , gooFlowURI -- * GoogleCloudDialogflowV2beta1IntentMessageMediaContentMediaType , GoogleCloudDialogflowV2beta1IntentMessageMediaContentMediaType (..) -- * GoogleCloudDialogflowCxV3beta1ResponseMessageOutputAudioText , GoogleCloudDialogflowCxV3beta1ResponseMessageOutputAudioText , googleCloudDialogflowCxV3beta1ResponseMessageOutputAudioText , gcdcvrmoatcText , gcdcvrmoatcSsml , gcdcvrmoatcAllowPlaybackInterruption -- * GoogleCloudDialogflowV2beta1ExportAgentResponse , GoogleCloudDialogflowV2beta1ExportAgentResponse , googleCloudDialogflowV2beta1ExportAgentResponse , gcdvearcAgentURI , gcdvearcAgentContent -- * GoogleCloudDialogflowV2ArticleAnswerMetadata , GoogleCloudDialogflowV2ArticleAnswerMetadata , googleCloudDialogflowV2ArticleAnswerMetadata , gcdvaamcAddtional -- * GoogleCloudDialogflowV3alpha1ImportDocumentsOperationMetadata , GoogleCloudDialogflowV3alpha1ImportDocumentsOperationMetadata , googleCloudDialogflowV3alpha1ImportDocumentsOperationMetadata , gcdvidomGenericMetadata -- * GoogleCloudDialogflowCxV3FulfillmentSetParameterAction , GoogleCloudDialogflowCxV3FulfillmentSetParameterAction , googleCloudDialogflowCxV3FulfillmentSetParameterAction , gValue , gParameter -- * GoogleCloudDialogflowCxV3QueryParametersWebhookHeaders , GoogleCloudDialogflowCxV3QueryParametersWebhookHeaders , googleCloudDialogflowCxV3QueryParametersWebhookHeaders , gcdcvqpwhAddtional -- * GoogleCloudDialogflowCxV3ImportTestCasesResponse , GoogleCloudDialogflowCxV3ImportTestCasesResponse , googleCloudDialogflowCxV3ImportTestCasesResponse , gNames -- * GoogleCloudDialogflowV2OriginalDetectIntentRequestPayload , GoogleCloudDialogflowV2OriginalDetectIntentRequestPayload , googleCloudDialogflowV2OriginalDetectIntentRequestPayload , gcdvodirpcAddtional -- * GoogleCloudDialogflowV2SessionEntityType , GoogleCloudDialogflowV2SessionEntityType , googleCloudDialogflowV2SessionEntityType , gcdvSetcEntityOverrideMode , gcdvSetcEntities , gcdvSetcName -- * GoogleCloudDialogflowV2IntentDefaultResponsePlatformsItem , GoogleCloudDialogflowV2IntentDefaultResponsePlatformsItem (..) -- * GoogleCloudDialogflowCxV3FormParameter , GoogleCloudDialogflowCxV3FormParameter , googleCloudDialogflowCxV3FormParameter , gooRedact , gooEntityType , gooFillBehavior , gooRequired , gooDisplayName , gooDefaultValue , gooIsList -- * GoogleCloudDialogflowCxV3VoiceSelectionParams , GoogleCloudDialogflowCxV3VoiceSelectionParams , googleCloudDialogflowCxV3VoiceSelectionParams , gcdcvvspSsmlGender , gcdcvvspName -- * GoogleCloudDialogflowCxV3NluSettings , GoogleCloudDialogflowCxV3NluSettings , googleCloudDialogflowCxV3NluSettings , gcdcvnsModelTrainingMode , gcdcvnsModelType , gcdcvnsClassificationThreshold -- * GoogleCloudDialogflowV2beta1EntityTypeKind , GoogleCloudDialogflowV2beta1EntityTypeKind (..) -- * GoogleCloudDialogflowCxV3ResponseMessagePlayAudio , GoogleCloudDialogflowCxV3ResponseMessagePlayAudio , googleCloudDialogflowCxV3ResponseMessagePlayAudio , gooAudioURI , gooAllowPlaybackInterruption -- * GoogleCloudDialogflowV2ArticleAnswer , GoogleCloudDialogflowV2ArticleAnswer , googleCloudDialogflowV2ArticleAnswer , gcdvaacURI , gcdvaacAnswerRecord , gcdvaacConfidence , gcdvaacMetadata , gcdvaacTitle , gcdvaacSnippets -- * GoogleCloudDialogflowCxV3QueryResultDiagnosticInfo , GoogleCloudDialogflowCxV3QueryResultDiagnosticInfo , googleCloudDialogflowCxV3QueryResultDiagnosticInfo , gcdcvqrdiAddtional -- * GoogleCloudDialogflowCxV3IntentCoverage , GoogleCloudDialogflowCxV3IntentCoverage , googleCloudDialogflowCxV3IntentCoverage , gcdcvicIntents , gcdcvicCoverageScore -- * GoogleCloudDialogflowV2beta1IntentMessageTableCardCell , GoogleCloudDialogflowV2beta1IntentMessageTableCardCell , googleCloudDialogflowV2beta1IntentMessageTableCardCell , gcdvimtcccText -- * GoogleCloudDialogflowCxV3IntentInput , GoogleCloudDialogflowCxV3IntentInput , googleCloudDialogflowCxV3IntentInput , gIntent -- * GoogleCloudDialogflowV2IntentMessageColumnProperties , GoogleCloudDialogflowV2IntentMessageColumnProperties , googleCloudDialogflowV2IntentMessageColumnProperties , gHeader , gHorizontalAlignment -- * GoogleCloudDialogflowCxV3PageInfoFormInfoParameterInfo , GoogleCloudDialogflowCxV3PageInfoFormInfoParameterInfo , googleCloudDialogflowCxV3PageInfoFormInfoParameterInfo , gcdcvpifipicJustCollected , gcdcvpifipicState , gcdcvpifipicValue , gcdcvpifipicRequired , gcdcvpifipicDisplayName -- * GoogleCloudDialogflowCxV3RunTestCaseRequest , GoogleCloudDialogflowCxV3RunTestCaseRequest , googleCloudDialogflowCxV3RunTestCaseRequest , gcdcvrtcrEnvironment -- * GoogleCloudDialogflowCxV3Flow , GoogleCloudDialogflowCxV3Flow , googleCloudDialogflowCxV3Flow , gcdcvfEventHandlers , gcdcvfNluSettings , gcdcvfTransitionRoutes , gcdcvfName , gcdcvfTransitionRouteGroups , gcdcvfDisplayName , gcdcvfDescription -- * GoogleCloudDialogflowV2SuggestArticlesResponse , GoogleCloudDialogflowV2SuggestArticlesResponse , googleCloudDialogflowV2SuggestArticlesResponse , gooContextSize , gooArticleAnswers , gooLatestMessage -- * GoogleCloudDialogflowV2EntityTypeEntity , GoogleCloudDialogflowV2EntityTypeEntity , googleCloudDialogflowV2EntityTypeEntity , gooValue , gooSynonyms -- * GoogleCloudDialogflowV2IntentWebhookState , GoogleCloudDialogflowV2IntentWebhookState (..) -- * GoogleCloudDialogflowV2beta1QueryResult , GoogleCloudDialogflowV2beta1QueryResult , googleCloudDialogflowV2beta1QueryResult , gcdvqrcLanguageCode , gcdvqrcAllRequiredParamsPresent , gcdvqrcIntentDetectionConfidence , gcdvqrcFulfillmentMessages , gcdvqrcKnowledgeAnswers , gcdvqrcSpeechRecognitionConfidence , gcdvqrcCancelsSlotFilling , gcdvqrcAction , gcdvqrcIntent , gcdvqrcSentimentAnalysisResult , gcdvqrcQueryText , gcdvqrcFulfillmentText , gcdvqrcParameters , gcdvqrcWebhookPayload , gcdvqrcOutputContexts , gcdvqrcWebhookSource , gcdvqrcDiagnosticInfo -- * GoogleCloudDialogflowV2IntentMessageImage , GoogleCloudDialogflowV2IntentMessageImage , googleCloudDialogflowV2IntentMessageImage , gAccessibilityText , gImageURI -- * GoogleCloudDialogflowV2WebhookResponse , GoogleCloudDialogflowV2WebhookResponse , googleCloudDialogflowV2WebhookResponse , gcdvwrcFulfillmentMessages , gcdvwrcPayload , gcdvwrcFulfillmentText , gcdvwrcSource , gcdvwrcOutputContexts , gcdvwrcFollowupEventInput , gcdvwrcSessionEntityTypes -- * GoogleCloudDialogflowCxV3ListSecuritySettingsResponse , GoogleCloudDialogflowCxV3ListSecuritySettingsResponse , googleCloudDialogflowCxV3ListSecuritySettingsResponse , gcdcvlssrNextPageToken , gcdcvlssrSecuritySettings -- * GoogleCloudDialogflowCxV3TestCase , GoogleCloudDialogflowCxV3TestCase , googleCloudDialogflowCxV3TestCase , gcdcvtccCreationTime , gcdcvtccLastTestResult , gcdcvtccTestConfig , gcdcvtccName , gcdcvtccDisplayName , gcdcvtccNotes , gcdcvtccTags , gcdcvtccTestCaseConversationTurns -- * GoogleCloudDialogflowCxV3beta1ImportDocumentsOperationMetadata , GoogleCloudDialogflowCxV3beta1ImportDocumentsOperationMetadata , googleCloudDialogflowCxV3beta1ImportDocumentsOperationMetadata , gooGenericMetadata -- * ProjectsLocationsAgentsIntentsListIntentView , ProjectsLocationsAgentsIntentsListIntentView (..) -- * GoogleCloudDialogflowV2beta1Message , GoogleCloudDialogflowV2beta1Message , googleCloudDialogflowV2beta1Message , gcdvmcLanguageCode , gcdvmcParticipantRole , gcdvmcContent , gcdvmcMessageAnnotation , gcdvmcName , gcdvmcParticipant , gcdvmcSentimentAnalysis , gcdvmcSendTime , gcdvmcCreateTime -- * GoogleCloudDialogflowCxV3FulfillmentConditionalCasesCaseCaseContent , GoogleCloudDialogflowCxV3FulfillmentConditionalCasesCaseCaseContent , googleCloudDialogflowCxV3FulfillmentConditionalCasesCaseCaseContent , gAdditionalCases , gMessage -- * GoogleCloudDialogflowCxV3DetectIntentRequest , GoogleCloudDialogflowCxV3DetectIntentRequest , googleCloudDialogflowCxV3DetectIntentRequest , gQueryInput , gOutputAudioConfig , gQueryParams -- * GoogleCloudDialogflowV2beta1IntentMessageRbmStandaloneCard , GoogleCloudDialogflowV2beta1IntentMessageRbmStandaloneCard , googleCloudDialogflowV2beta1IntentMessageRbmStandaloneCard , gcdvimrscThumbnailImageAlignment , gcdvimrscCardOrientation , gcdvimrscCardContent -- * GoogleCloudDialogflowCxV3beta1IntentTrainingPhrase , GoogleCloudDialogflowCxV3beta1IntentTrainingPhrase , googleCloudDialogflowCxV3beta1IntentTrainingPhrase , gooParts , gooRepeatCount , gooId -- * GoogleCloudDialogflowCxV3beta1ImportTestCasesMetadata , GoogleCloudDialogflowCxV3beta1ImportTestCasesMetadata , googleCloudDialogflowCxV3beta1ImportTestCasesMetadata , gcdcvitcmcErrors -- * GoogleCloudDialogflowCxV3TestCaseError , GoogleCloudDialogflowCxV3TestCaseError , googleCloudDialogflowCxV3TestCaseError , gStatus , gTestCase -- * GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenURLActionURLTypeHint , GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenURLActionURLTypeHint (..) -- * GoogleCloudDialogflowV2beta1EntityType , GoogleCloudDialogflowV2beta1EntityType , googleCloudDialogflowV2beta1EntityType , gcdvetcEntities , gcdvetcKind , gcdvetcName , gcdvetcAutoExpansionMode , gcdvetcDisplayName , gcdvetcEnableFuzzyExtraction -- * GoogleCloudDialogflowCxV3BatchRunTestCasesRequest , GoogleCloudDialogflowCxV3BatchRunTestCasesRequest , googleCloudDialogflowCxV3BatchRunTestCasesRequest , gcdcvbrtcrEnvironment , gcdcvbrtcrTestCases -- * GoogleCloudDialogflowCxV3ExperimentResultVersionMetrics , GoogleCloudDialogflowCxV3ExperimentResultVersionMetrics , googleCloudDialogflowCxV3ExperimentResultVersionMetrics , gcdcvervmMetrics , gcdcvervmSessionCount , gcdcvervmVersion -- * GoogleCloudDialogflowCxV3beta1ResponseMessageLiveAgentHandoffMetadata , GoogleCloudDialogflowCxV3beta1ResponseMessageLiveAgentHandoffMetadata , googleCloudDialogflowCxV3beta1ResponseMessageLiveAgentHandoffMetadata , gcdcvrmlahmcAddtional -- * GoogleCloudDialogflowCxV3WebhookServiceDirectoryConfig , GoogleCloudDialogflowCxV3WebhookServiceDirectoryConfig , googleCloudDialogflowCxV3WebhookServiceDirectoryConfig , gcdcvwsdcGenericWebService , gcdcvwsdcService -- * GoogleCloudDialogflowCxV3beta1DeleteDocumentOperationMetadata , GoogleCloudDialogflowCxV3beta1DeleteDocumentOperationMetadata , googleCloudDialogflowCxV3beta1DeleteDocumentOperationMetadata , gcdcvddomcGenericMetadata -- * GoogleLongrunningOperation , GoogleLongrunningOperation , googleLongrunningOperation , gloDone , gloError , gloResponse , gloName , gloMetadata -- * GoogleCloudDialogflowCxV3beta1ExportTestCasesResponse , GoogleCloudDialogflowCxV3beta1ExportTestCasesResponse , googleCloudDialogflowCxV3beta1ExportTestCasesResponse , gooContent , gooGcsURI -- * GoogleCloudDialogflowCxV3ResponseMessageEndInteraction , GoogleCloudDialogflowCxV3ResponseMessageEndInteraction , googleCloudDialogflowCxV3ResponseMessageEndInteraction -- * GoogleCloudDialogflowCxV3beta1RunTestCaseMetadata , GoogleCloudDialogflowCxV3beta1RunTestCaseMetadata , googleCloudDialogflowCxV3beta1RunTestCaseMetadata -- * GoogleCloudDialogflowCxV3ValidateFlowRequest , GoogleCloudDialogflowCxV3ValidateFlowRequest , googleCloudDialogflowCxV3ValidateFlowRequest , gcdcvvfrLanguageCode -- * GoogleCloudDialogflowCxV3FulfillIntentRequest , GoogleCloudDialogflowCxV3FulfillIntentRequest , googleCloudDialogflowCxV3FulfillIntentRequest , gooOutputAudioConfig , gooMatch , gooMatchIntentRequest -- * GoogleCloudDialogflowV2IntentMessage , GoogleCloudDialogflowV2IntentMessage , googleCloudDialogflowV2IntentMessage , gcdvimcCard , gcdvimcImage , gcdvimcPlatform , gcdvimcBrowseCarouselCard , gcdvimcTableCard , gcdvimcLinkOutSuggestion , gcdvimcText , gcdvimcCarouselSelect , gcdvimcSimpleResponses , gcdvimcPayload , gcdvimcSuggestions , gcdvimcListSelect , gcdvimcMediaContent , gcdvimcBasicCard , gcdvimcQuickReplies -- * GoogleCloudDialogflowCxV3VersionState , GoogleCloudDialogflowCxV3VersionState (..) -- * GoogleCloudDialogflowV2IntentMessageCarouselSelect , GoogleCloudDialogflowV2IntentMessageCarouselSelect , googleCloudDialogflowV2IntentMessageCarouselSelect , gcdvimcscItems -- * GoogleCloudDialogflowV2Sentiment , GoogleCloudDialogflowV2Sentiment , googleCloudDialogflowV2Sentiment , gooScore , gooMagnitude -- * GoogleCloudDialogflowCxV3beta1Form , GoogleCloudDialogflowCxV3beta1Form , googleCloudDialogflowCxV3beta1Form , gooParameters -- * GoogleCloudDialogflowCxV3beta1UpdateDocumentOperationMetadata , GoogleCloudDialogflowCxV3beta1UpdateDocumentOperationMetadata , googleCloudDialogflowCxV3beta1UpdateDocumentOperationMetadata , gcdcvudomcGenericMetadata -- * GoogleCloudDialogflowCxV3beta1TransitionRoute , GoogleCloudDialogflowCxV3beta1TransitionRoute , googleCloudDialogflowCxV3beta1TransitionRoute , gcdcvtrcTriggerFulfillment , gcdcvtrcIntent , gcdcvtrcName , gcdcvtrcTargetPage , gcdcvtrcCondition , gcdcvtrcTargetFlow -- * GoogleCloudDialogflowCxV3LoadVersionRequest , GoogleCloudDialogflowCxV3LoadVersionRequest , googleCloudDialogflowCxV3LoadVersionRequest , gcdcvlvrAllowOverrideAgentResources -- * ProjectsLocationsAgentsTestCasesCalculateCoverageType , ProjectsLocationsAgentsTestCasesCalculateCoverageType (..) -- * GoogleCloudDialogflowCxV3WebhookResponseFulfillmentResponseMergeBehavior , GoogleCloudDialogflowCxV3WebhookResponseFulfillmentResponseMergeBehavior (..) -- * GoogleCloudDialogflowCxV3DtmfInput , GoogleCloudDialogflowCxV3DtmfInput , googleCloudDialogflowCxV3DtmfInput , gDigits , gFinishDigit -- * GoogleCloudDialogflowCxV3beta1WebhookResponsePayload , GoogleCloudDialogflowCxV3beta1WebhookResponsePayload , googleCloudDialogflowCxV3beta1WebhookResponsePayload , ggAddtional -- * GoogleCloudDialogflowV2beta1IntentMessageSelectItemInfo , GoogleCloudDialogflowV2beta1IntentMessageSelectItemInfo , googleCloudDialogflowV2beta1IntentMessageSelectItemInfo , gKey , gSynonyms -- * GoogleCloudDialogflowV2beta1Intent , GoogleCloudDialogflowV2beta1Intent , googleCloudDialogflowV2beta1Intent , gcdvicDefaultResponsePlatforms , gcdvicWebhookState , gcdvicMlEnabled , gcdvicPriority , gcdvicLiveAgentHandoff , gcdvicAction , gcdvicRootFollowupIntentName , gcdvicName , gcdvicEvents , gcdvicParameters , gcdvicDisplayName , gcdvicInputContextNames , gcdvicEndInteraction , gcdvicMessages , gcdvicParentFollowupIntentName , gcdvicOutputContexts , gcdvicTrainingPhrases , gcdvicFollowupIntentInfo , gcdvicIsFallback , gcdvicMlDisabled , gcdvicResetContexts -- * GoogleCloudDialogflowCxV3beta1ReLoadDocumentOperationMetadata , GoogleCloudDialogflowCxV3beta1ReLoadDocumentOperationMetadata , googleCloudDialogflowCxV3beta1ReLoadDocumentOperationMetadata , gcdcvrldomcGenericMetadata -- * GoogleCloudDialogflowV2Context , GoogleCloudDialogflowV2Context , googleCloudDialogflowV2Context , gcdvccLifespanCount , gcdvccName , gcdvccParameters -- * GoogleCloudDialogflowV2IntentMessageBasicCardButton , GoogleCloudDialogflowV2IntentMessageBasicCardButton , googleCloudDialogflowV2IntentMessageBasicCardButton , gcdvimbcbcOpenURIAction , gcdvimbcbcTitle -- * GoogleCloudDialogflowCxV3beta1TestError , GoogleCloudDialogflowCxV3beta1TestError , googleCloudDialogflowCxV3beta1TestError , gcdcvtecStatus , gcdcvtecTestCase , gcdcvtecTestTime ) where import Network.Google.DialogFlow.Types.Product import Network.Google.DialogFlow.Types.Sum import Network.Google.Prelude -- | Default request referring to version 'v3' of the Dialogflow API. This contains the host and root path used as a starting point for constructing service requests. dialogFlowService :: ServiceConfig dialogFlowService = defaultService (ServiceId "dialogflow:v3") "dialogflow.googleapis.com" -- | View, manage and query your Dialogflow agents dialogFlowScope :: Proxy '["https://www.googleapis.com/auth/dialogflow"] dialogFlowScope = Proxy -- | See, edit, configure, and delete your Google Cloud Platform data cloudPlatformScope :: Proxy '["https://www.googleapis.com/auth/cloud-platform"] cloudPlatformScope = Proxy
brendanhay/gogol
gogol-dialogflow/gen/Network/Google/DialogFlow/Types.hs
mpl-2.0
114,358
0
7
17,264
7,383
5,116
2,267
2,176
1
{-# LANGUAGE MultiParamTypeClasses #-} module Math.Topology.KnotTh.Invariants.KnotPolynomials ( SkeinRelation(..) , reduceSkein , skeinRelationPostMinimization , skeinRelationMidMinimization , skeinRelationPreMinimization ) where import Math.Topology.KnotTh.Algebra.PlanarAlgebra.Reduction import Math.Topology.KnotTh.Tangle class (Functor f, TransposeAction (f p), PlanarAlgebra (f p)) => SkeinRelation f p where crossingSkein :: DiagramCrossing -> f p reduceSkein :: (SkeinRelation f p) => TangleDiagram -> f p reduceSkein = reducePlanarAlgebra . fmap crossingSkein skeinRelationPostMinimization :: (Ord (f p), MirrorAction (f p), SkeinRelation f p) => (TangleDiagram -> f p) -> TangleDiagram -> f p skeinRelationPostMinimization invariant tangle = minimum $ do p <- allOrientationsOf $ invariant tangle [p, transposeIt p] skeinRelationMidMinimization :: (Ord (f p), MirrorAction (f p), SkeinRelation f p) => (TangleDiagram -> f p) -> TangleDiagram -> f p skeinRelationMidMinimization invariant tangle = minimum $ do p <- map invariant [tangle, transposeCrossings tangle] allOrientationsOf p skeinRelationPreMinimization :: (Ord (f p), SkeinRelation f p) => (TangleDiagram -> f p) -> TangleDiagram -> f p skeinRelationPreMinimization invariant tangle = minimum $ do inv <- [id, transposeCrossings] t <- allOrientationsOf tangle return $ invariant $ inv t
mishun/tangles
src/Math/Topology/KnotTh/Invariants/KnotPolynomials.hs
lgpl-3.0
1,425
0
11
239
441
229
212
-1
-1
{-# LANGUAGE TypeSynonymInstances , FlexibleInstances , DeriveGeneric , DeriveDataTypeable #-} module OskarBinReader ( TaskData(..) , SortType(..) , tdVisibilitiesSize , tdUVWSize , finalizeTaskData , mkSortedClone , finalizeSortedClone , readOskarData , writeTaskData , readTaskData , readTaskDataHeader ) where import OskarBinReaderFFI import Foreign import Foreign.C import Foreign.Storable.Complex () import Text.Printf import System.IO import System.FilePath import Control.Applicative ( (<$>) ) import GHC.Generics (Generic) import Data.Binary import BinaryInstances () import Data.Typeable import Utils data TaskData = TaskData { tdBaselines :: !Int , tdTimes :: !Int , tdChannels :: !Int , tdPoints :: !Int , tdMaxx :: !CDouble , tdWstep :: !CDouble , tdComplexity :: !Int , tdVisibilies :: !(Ptr CxDouble) , tdUVWs :: !(Ptr CDouble) , tdMap :: !(Ptr BlWMap) } deriving (Generic, Typeable) instance Binary TaskData tdVisibilitiesSize :: TaskData -> Int tdVisibilitiesSize td = tdPoints td * 8 * sizeOf (undefined :: CDouble) tdUVWSize :: TaskData -> Int tdUVWSize td = tdPoints td * 3 * sizeOf (undefined :: CDouble) finalizeTaskData :: TaskData -> IO () finalizeTaskData td = do free $ tdMap td free $ tdUVWs td free $ tdVisibilies td data SortType = NoSort | PlainSort | NormSort -- FIXME: Add type layer to distingush between cloned and original data. -- Another option is to attach finalizer to the data itself, but -- that would require bothering with Binary instance. mkSortedClone :: SortType -> TaskData -> IO TaskData mkSortedClone st td = do newMap <- mallocArray n copyArray newMap (tdMap td) n sort st newMap (fromIntegral n) return td {tdMap = newMap} where n = tdBaselines td sort NoSort = \_ _ -> return () sort PlainSort = sort_on_w sort NormSort = sort_on_abs_w finalizeSortedClone :: TaskData -> IO () finalizeSortedClone td = free $ tdMap td readOskarData :: String -> IO TaskData readOskarData fname = withCString fname doRead where fi = fromIntegral throwErr = throwIf_ (/= 0) (\n -> printf "While trying to read binary file %s : %d" fname $ fi n) doRead namep = alloca $ \vptr -> do throwErr $ mkFromFile vptr namep nbls <- numBaselines vptr ntms <- numTimes vptr nchs <- numChannels vptr -- it is in fact a product of previous three npts <- numPoints vptr let n = fi npts nb = fi nbls visptr <- alignedMallocArray (n * 4) 32 uvwptr <- mallocArray (n * 3) mapptr <- mallocArray nb alloca $ \mptr -> allocaArray nb $ \mmptr -> do throwErr $ readAndReshuffle vptr visptr uvwptr mptr mmptr mapptr freeBinHandler vptr wstp <- wstep mptr mxx <- maxx mptr pcount <- fromIntegral <$> count_points mapptr (fromIntegral nb) return $ TaskData nb (fi ntms) (fi nchs) n mxx wstp pcount visptr uvwptr mapptr -- Our Binary instance is unrelated to deep serializing. -- Here is deep from/to disk marchalling. writeTaskData :: String -> TaskData -> IO () writeTaskData namespace (TaskData nb nt nc np mxx wstp _ visptr uvwptr mapptr) = allocaArray 4 $ \ip -> allocaArray 2 $ \cdp -> do let pokei = poke . advancePtr ip pokec = poke . advancePtr cdp pokei 0 nb pokei 1 nt pokei 2 nc pokei 3 np pokec 0 mxx pokec 1 wstp let writeb handle = do let hput = hPutBuf handle hput ip (4 * sizeOf (undefined :: Int)) hput cdp (2 * cdb_siz) hput visptr (np * 8 * cdb_siz) hput uvwptr (np * 3 * cdb_siz) hput mapptr (nb * sizeOf (undefined :: BlWMap)) withBinaryFile (namespace </> "taskdata.dat") WriteMode writeb where cdb_siz = sizeOf (undefined :: CDouble) readTaskDataHeader :: String -> IO TaskData readTaskDataHeader = readTaskDataGen True readTaskData :: String -> IO TaskData readTaskData = readTaskDataGen False readTaskDataGen :: Bool -> String -> IO TaskData readTaskDataGen headerOnly namespace = allocaArray 4 $ \ip -> allocaArray 2 $ \cdp -> withBinaryFile (namespace </> "taskdata.dat") ReadMode $ \handle -> do let hget p siz = throwIf_ (/= siz) (\n -> printf "While reading taskdata from %s got %d instead of %d" namespace n siz) (hGetBuf handle p siz) hget ip (4 * sizeOf (undefined :: Int)) hget cdp (2 * cdb_siz) let peeki = peek . advancePtr ip peekc = peek . advancePtr cdp nb <- peeki 0 nt <- peeki 1 nc <- peeki 2 np <- peeki 3 mxx <- peekc 0 wstp <- peekc 1 let header = TaskData nb nt nc np mxx wstp 0 nullPtr nullPtr nullPtr if headerOnly then return header else do visptr <- alignedMallocArray (np * 4) 32 uvwptr <- mallocArray (np * 3) mapptr <- mallocArray nb hget visptr (tdVisibilitiesSize header) hget uvwptr (tdUVWSize header) hget mapptr (nb * sizeOf (undefined :: BlWMap)) pcount <- fromIntegral <$> count_points mapptr (fromIntegral nb) return header { tdComplexity = pcount , tdVisibilies = visptr , tdUVWs = uvwptr , tdMap = mapptr } where cdb_siz = sizeOf (undefined :: CDouble)
SKA-ScienceDataProcessor/RC
MS3/Sketches/Oskar_New_Reader/OskarBinReader.hs
apache-2.0
5,555
0
21
1,626
1,686
835
851
169
3
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QStyleOptionProgressBarV2.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:35 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Gui.QStyleOptionProgressBarV2 ( QStyleOptionProgressBarV2StyleOptionType , QStyleOptionProgressBarV2StyleOptionVersion ) where import Foreign.C.Types import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CQStyleOptionProgressBarV2StyleOptionType a = CQStyleOptionProgressBarV2StyleOptionType a type QStyleOptionProgressBarV2StyleOptionType = QEnum(CQStyleOptionProgressBarV2StyleOptionType Int) ieQStyleOptionProgressBarV2StyleOptionType :: Int -> QStyleOptionProgressBarV2StyleOptionType ieQStyleOptionProgressBarV2StyleOptionType x = QEnum (CQStyleOptionProgressBarV2StyleOptionType x) instance QEnumC (CQStyleOptionProgressBarV2StyleOptionType Int) where qEnum_toInt (QEnum (CQStyleOptionProgressBarV2StyleOptionType x)) = x qEnum_fromInt x = QEnum (CQStyleOptionProgressBarV2StyleOptionType x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> QStyleOptionProgressBarV2StyleOptionType -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () instance QeType QStyleOptionProgressBarV2StyleOptionType where eType = ieQStyleOptionProgressBarV2StyleOptionType $ 6 data CQStyleOptionProgressBarV2StyleOptionVersion a = CQStyleOptionProgressBarV2StyleOptionVersion a type QStyleOptionProgressBarV2StyleOptionVersion = QEnum(CQStyleOptionProgressBarV2StyleOptionVersion Int) ieQStyleOptionProgressBarV2StyleOptionVersion :: Int -> QStyleOptionProgressBarV2StyleOptionVersion ieQStyleOptionProgressBarV2StyleOptionVersion x = QEnum (CQStyleOptionProgressBarV2StyleOptionVersion x) instance QEnumC (CQStyleOptionProgressBarV2StyleOptionVersion Int) where qEnum_toInt (QEnum (CQStyleOptionProgressBarV2StyleOptionVersion x)) = x qEnum_fromInt x = QEnum (CQStyleOptionProgressBarV2StyleOptionVersion x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> QStyleOptionProgressBarV2StyleOptionVersion -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () instance QeVersion QStyleOptionProgressBarV2StyleOptionVersion where eVersion = ieQStyleOptionProgressBarV2StyleOptionVersion $ 2
keera-studios/hsQt
Qtc/Enums/Gui/QStyleOptionProgressBarV2.hs
bsd-2-clause
4,860
0
18
921
1,080
532
548
90
1
module Shapes (surface,nudge,baseCircle, baseRect, Point(..), Shape(..)) where surface :: Shape -> Float surface (Circle _ r) = pi * r ^ 2 surface (Rectangle (Point x1 y1) (Point x2 y2)) = abs (x2 - x1) * abs (y2 - y1) nudge :: Shape -> Float -> Float -> Shape nudge (Circle (Point x y) r) a b = Circle (Point (x+a) (y+b)) r nudge (Rectangle (Point x1 y1) (Point x2 y2)) a b = Rectangle (Point (x1+a) (y1+b)) (Point (x2+a) (y2+b)) baseCircle :: Float -> Shape baseCircle = Circle (Point 0 0) baseRect :: Float -> Float -> Shape baseRect width height = Rectangle (Point 0 0) (Point width height) data Point = Point Float Float deriving (Show) data Shape = Circle Point Float | Rectangle Point Point deriving (Show)
Hidowga/Projetos
Shapes.hs
bsd-3-clause
719
0
9
135
390
207
183
13
1
{-# LANGUAGE PackageImports, ScopedTypeVariables, BangPatterns #-} -- | -- Copyright : (c) 2011 Simon Meier -- License : BSD3-style (see LICENSE) -- -- Maintainer : Simon Meier <[email protected]> -- Stability : experimental -- Portability : tested on GHC only -- -- Benchmark all 'Builder' functions. module Main (main) where import Prelude hiding (words) import Criterion.Main import Data.Foldable (foldMap) import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import Data.ByteString.Builder import Data.ByteString.Builder.ASCII import Data.ByteString.Builder.Prim ( FixedPrim, BoundedPrim, (>$<) ) import qualified Data.ByteString.Builder.Prim as P import qualified Data.ByteString.Builder.Prim.Internal as PI import Foreign ------------------------------------------------------------------------------ -- Benchmark support ------------------------------------------------------------------------------ countToZero :: Int -> Maybe (Int, Int) countToZero 0 = Nothing countToZero n = Just (n, n - 1) ------------------------------------------------------------------------------ -- Benchmark ------------------------------------------------------------------------------ -- input data (NOINLINE to ensure memoization) ---------------------------------------------- -- | Few-enough repetitions to avoid making GC too expensive. nRepl :: Int nRepl = 10000 {-# NOINLINE intData #-} intData :: [Int] intData = [1..nRepl] -- Half of the integers inside the range of an Int and half of them outside. {-# NOINLINE integerData #-} integerData :: [Integer] integerData = map (\x -> fromIntegral x + fromIntegral (maxBound - nRepl `div` 2)) intData {-# NOINLINE floatData #-} floatData :: [Float] floatData = map (\x -> (3.14159 * fromIntegral x) ^ (3 :: Int)) intData {-# NOINLINE doubleData #-} doubleData :: [Double] doubleData = map (\x -> (3.14159 * fromIntegral x) ^ (3 :: Int)) intData {-# NOINLINE byteStringData #-} byteStringData :: S.ByteString byteStringData = S.pack $ map fromIntegral intData {-# NOINLINE lazyByteStringData #-} lazyByteStringData :: L.ByteString lazyByteStringData = case S.splitAt (nRepl `div` 2) byteStringData of (bs1, bs2) -> L.fromChunks [bs1, bs2] -- benchmark wrappers --------------------- {-# INLINE benchB #-} benchB :: String -> a -> (a -> Builder) -> Benchmark benchB name x b = bench (name ++" (" ++ show nRepl ++ ")") $ whnf (L.length . toLazyByteString . b) x {-# INLINE benchBInts #-} benchBInts :: String -> ([Int] -> Builder) -> Benchmark benchBInts name = benchB name intData -- | Benchmark a 'FixedPrim'. Full inlining to enable specialization. {-# INLINE benchFE #-} benchFE :: String -> FixedPrim Int -> Benchmark benchFE name = benchBE name . P.liftFixedToBounded -- | Benchmark a 'BoundedPrim'. Full inlining to enable specialization. {-# INLINE benchBE #-} benchBE :: String -> BoundedPrim Int -> Benchmark benchBE name e = bench (name ++" (" ++ show nRepl ++ ")") $ benchIntEncodingB nRepl e -- We use this construction of just looping through @n,n-1,..,1@ to ensure that -- we measure the speed of the encoding and not the speed of generating the -- values to be encoded. {-# INLINE benchIntEncodingB #-} benchIntEncodingB :: Int -- ^ Maximal 'Int' to write -> BoundedPrim Int -- ^ 'BoundedPrim' to execute -> IO () -- ^ 'IO' action to benchmark benchIntEncodingB n0 w | n0 <= 0 = return () | otherwise = do fpbuf <- mallocForeignPtrBytes (n0 * PI.sizeBound w) withForeignPtr fpbuf (loop n0) >> return () where loop !n !op | n <= 0 = return op | otherwise = PI.runB w n op >>= loop (n - 1) -- benchmarks ------------- sanityCheckInfo :: [String] sanityCheckInfo = [ "Sanity checks:" , " lengths of input data: " ++ show [ length intData, length floatData, length doubleData, length integerData , S.length byteStringData, fromIntegral (L.length lazyByteStringData) ] ] main :: IO () main = do mapM_ putStrLn sanityCheckInfo putStrLn "" Criterion.Main.defaultMain [ bgroup "Data.ByteString.Builder" [ bgroup "Encoding wrappers" [ benchBInts "foldMap word8" $ foldMap (word8 . fromIntegral) , benchBInts "primMapListFixed word8" $ P.primMapListFixed (fromIntegral >$< P.word8) , benchB "primUnfoldrFixed word8" nRepl $ P.primUnfoldrFixed (fromIntegral >$< P.word8) countToZero , benchB "primMapByteStringFixed word8" byteStringData $ P.primMapByteStringFixed P.word8 , benchB "primMapLazyByteStringFixed word8" lazyByteStringData $ P.primMapLazyByteStringFixed P.word8 ] , bgroup "Non-bounded encodings" [ benchB "foldMap floatDec" floatData $ foldMap floatDec , benchB "foldMap doubleDec" doubleData $ foldMap doubleDec , benchB "foldMap integerDec" integerData $ foldMap integerDec , benchB "byteStringHex" byteStringData $ byteStringHex , benchB "lazyByteStringHex" lazyByteStringData $ lazyByteStringHex ] ] , bgroup "Data.ByteString.Builder.Prim" [ benchFE "char7" $ toEnum >$< P.char7 , benchFE "char8" $ toEnum >$< P.char8 , benchBE "charUtf8" $ toEnum >$< P.charUtf8 -- binary encoding , benchFE "int8" $ fromIntegral >$< P.int8 , benchFE "word8" $ fromIntegral >$< P.word8 -- big-endian , benchFE "int16BE" $ fromIntegral >$< P.int16BE , benchFE "int32BE" $ fromIntegral >$< P.int32BE , benchFE "int64BE" $ fromIntegral >$< P.int64BE , benchFE "word16BE" $ fromIntegral >$< P.word16BE , benchFE "word32BE" $ fromIntegral >$< P.word32BE , benchFE "word64BE" $ fromIntegral >$< P.word64BE , benchFE "floatBE" $ fromIntegral >$< P.floatBE , benchFE "doubleBE" $ fromIntegral >$< P.doubleBE -- little-endian , benchFE "int16LE" $ fromIntegral >$< P.int16LE , benchFE "int32LE" $ fromIntegral >$< P.int32LE , benchFE "int64LE" $ fromIntegral >$< P.int64LE , benchFE "word16LE" $ fromIntegral >$< P.word16LE , benchFE "word32LE" $ fromIntegral >$< P.word32LE , benchFE "word64LE" $ fromIntegral >$< P.word64LE , benchFE "floatLE" $ fromIntegral >$< P.floatLE , benchFE "doubleLE" $ fromIntegral >$< P.doubleLE -- host-dependent , benchFE "int16Host" $ fromIntegral >$< P.int16Host , benchFE "int32Host" $ fromIntegral >$< P.int32Host , benchFE "int64Host" $ fromIntegral >$< P.int64Host , benchFE "intHost" $ fromIntegral >$< P.intHost , benchFE "word16Host" $ fromIntegral >$< P.word16Host , benchFE "word32Host" $ fromIntegral >$< P.word32Host , benchFE "word64Host" $ fromIntegral >$< P.word64Host , benchFE "wordHost" $ fromIntegral >$< P.wordHost , benchFE "floatHost" $ fromIntegral >$< P.floatHost , benchFE "doubleHost" $ fromIntegral >$< P.doubleHost ] , bgroup "Data.ByteString.Builder.Prim.ASCII" [ -- decimal number benchBE "int8Dec" $ fromIntegral >$< P.int8Dec , benchBE "int16Dec" $ fromIntegral >$< P.int16Dec , benchBE "int32Dec" $ fromIntegral >$< P.int32Dec , benchBE "int64Dec" $ fromIntegral >$< P.int64Dec , benchBE "intDec" $ fromIntegral >$< P.intDec , benchBE "word8Dec" $ fromIntegral >$< P.word8Dec , benchBE "word16Dec" $ fromIntegral >$< P.word16Dec , benchBE "word32Dec" $ fromIntegral >$< P.word32Dec , benchBE "word64Dec" $ fromIntegral >$< P.word64Dec , benchBE "wordDec" $ fromIntegral >$< P.wordDec -- hexadecimal number , benchBE "word8Hex" $ fromIntegral >$< P.word8Hex , benchBE "word16Hex" $ fromIntegral >$< P.word16Hex , benchBE "word32Hex" $ fromIntegral >$< P.word32Hex , benchBE "word64Hex" $ fromIntegral >$< P.word64Hex , benchBE "wordHex" $ fromIntegral >$< P.wordHex -- fixed-width hexadecimal numbers , benchFE "int8HexFixed" $ fromIntegral >$< P.int8HexFixed , benchFE "int16HexFixed" $ fromIntegral >$< P.int16HexFixed , benchFE "int32HexFixed" $ fromIntegral >$< P.int32HexFixed , benchFE "int64HexFixed" $ fromIntegral >$< P.int64HexFixed , benchFE "word8HexFixed" $ fromIntegral >$< P.word8HexFixed , benchFE "word16HexFixed" $ fromIntegral >$< P.word16HexFixed , benchFE "word32HexFixed" $ fromIntegral >$< P.word32HexFixed , benchFE "word64HexFixed" $ fromIntegral >$< P.word64HexFixed , benchFE "floatHexFixed" $ fromIntegral >$< P.floatHexFixed , benchFE "doubleHexFixed" $ fromIntegral >$< P.doubleHexFixed ] ]
markflorisson/hpack
testrepo/bytestring-0.10.2.0/bench/BenchAll.hs
bsd-3-clause
9,063
0
17
2,189
2,039
1,073
966
153
1
{-#LANGUAGE LambdaCase #-} {-#LANGUAGE OverloadedStrings #-} module Twilio.Types.AddressRequirement where import Control.Monad import Data.Aeson data AddressRequirement = None | Any | Local | Foreign deriving (Bounded, Enum, Eq, Ord) instance Read AddressRequirement where readsPrec _ = \case "none" -> return (None, "none") "any" -> return (None, "any") "local" -> return (None, "local") "foreign" -> return (None, "foregin") _ -> mzero instance Show AddressRequirement where show None = "none" show Any = "any" show Local = "local" show Foreign = "foreign" instance FromJSON AddressRequirement where parseJSON (String "none") = return None parseJSON (String "any") = return Any parseJSON (String "local") = return Local parseJSON (String "foreign") = return Foreign parseJSON _ = mzero
seagreen/twilio-haskell
src/Twilio/Types/AddressRequirement.hs
bsd-3-clause
879
0
10
202
262
137
125
29
0
import Test.Tasty import qualified TestPlanning as TP import TestDP as TDP tests :: TestTree tests = testGroup "Tests" [TP.unitTests] main :: IO () main = do defaultMain tests print TDP.calcVI
DbIHbKA/hmdp
test/Spec.hs
bsd-3-clause
204
0
8
41
66
36
30
9
1
----------------------------------------------------------------------------- -- | -- Module : NLP.WordNet -- Copyright : (c) Hal Daume III 2003-2004 -- License : BSD-style -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (H98 + implicit parameters) -- -- This is the top level module to the Haskell WordNet interface. -- -- This module is maintained at: -- <http://www.isi.edu/~hdaume/HWordNet/>. -- -- This is the only module in the WordNet package you need to import. -- The others provide utility functions and primitives that this -- module is based on. -- -- More information about WordNet is available at: -- <http://http://www.cogsci.princeton.edu/~wn/>. ----------------------------------------------------------------------------- module NLP.WordNet ( -- * The basic type system module NLP.WordNet.Types, -- * Top level execution functions runWordNet, runWordNetQuiet, runWordNetWithOptions, -- * Functions to manually initialize the WordNet system; these are not -- needed if you use one of the "runWordNet" functions above. initializeWordNet, initializeWordNetWithOptions, closeWordNet, runs, -- * The basic database access functions. getOverview, searchByOverview, search, lookupKey, -- * The agglomeration functions relatedBy, closure, closureOn, -- * Computing lowest-common ancestor functions; the implementation -- of these can be tuned by providing a different "Bag" implementation. -- use "emptyQueue" for breadth-first-search (recommended) or "emptyStack" -- for depth-first-search, or write your own. meet, meetPaths, meetSearchPaths, Bag(..), emptyQueue, emptyStack, ) where import Prelude import Data.Tree import qualified Data.Set as Set import System.IO.Unsafe import NLP.WordNet.Common import NLP.WordNet.Util import NLP.WordNet.Types import qualified NLP.WordNet.PrimTypes as T import qualified NLP.WordNet.Prims as P -- | Takes a WordNet command, initializes the environment -- and returns the results in the 'IO' monad. WordNet -- warnings are printed to stderr. runWordNet :: WN a -> IO a runWordNet = runWordNetWithOptions Nothing Nothing -- | Takes a WordNet command, initializes the environment -- and returns the results in the 'IO' monad. WordNet -- warnings are ignored. runWordNetQuiet :: WN a -> IO a runWordNetQuiet = runWordNetWithOptions Nothing (Just (\_ _ -> return ())) -- | Takes a FilePath to the directory holding WordNet and -- a function to do with warnings and a WordNet command, initializes -- the environment and returns the results in the 'IO' monad. runWordNetWithOptions :: Maybe FilePath -> -- word net data directory Maybe (String -> SomeException -> IO ()) -> -- warning function (by default, warnings go to stderr) WN a -> -- what to run IO a runWordNetWithOptions dd warn wn = do wne <- P.initializeWordNetWithOptions dd warn let a = let ?wne = wne in wn -- P.closeWordNet wne return a -- | Gives you a 'WordNetEnv' which can be passed to 'runs' or used -- as the implicit parameter to the other WordNet functions. initializeWordNet :: IO WordNetEnv initializeWordNet = P.initializeWordNet -- | Takes a FilePath to the directory holding WordNet and -- a function to do with warnings, initializes -- the environment and returns a 'WordNetEnv' as in 'initializeWordNet'. initializeWordNetWithOptions :: Maybe FilePath -> Maybe (String -> SomeException -> IO ()) -> IO WordNetEnv initializeWordNetWithOptions = P.initializeWordNetWithOptions -- | Closes all the handles associated with the 'WordNetEnv'. Since -- the functions provided in the "NLP.WordNet.WordNet" module -- are /lazy/, you shouldn't do this until you're really done. -- Or perhaps not at all (GC will eventually kick in). closeWordNet :: WordNetEnv -> IO () closeWordNet = P.closeWordNet -- | This simply takes a 'WordNetEnv' and provides it as the -- implicit parameter to the WordNet command. runs :: WordNetEnv -> WN a -> a runs wne x = let ?wne = wne in x -- | This takes a word and returns an 'Overview' of all its senses -- for all parts of speech. getOverview :: WN (Word -> Overview) getOverview word = unsafePerformIO $ do idxN <- unsafeInterleaveIO $ getOverview' Noun idxV <- unsafeInterleaveIO $ getOverview' Verb idxA <- unsafeInterleaveIO $ getOverview' Adj idxR <- unsafeInterleaveIO $ getOverview' Adv return (T.Overview idxN idxV idxA idxR) where getOverview' pos = do strM <- P.getIndexString ?wne word pos case strM of Nothing -> return Nothing Just _ -> unsafeInterleaveIO $ P.indexLookup ?wne word pos -- | This takes an 'Overview' (see 'getOverview'), a 'POS' and a 'SenseType' and returns -- a list of search results. If 'SenseType' is 'AllSenses', there will be one -- 'SearchResult' in the results for each valid sense. If 'SenseType' is -- a single sense number, there will be at most one element in the result list. searchByOverview :: WN (Overview -> POS -> SenseType -> [SearchResult]) searchByOverview overview pos sense = unsafePerformIO $ case (case pos of { Noun -> T.nounIndex ; Verb -> T.verbIndex ; Adj -> T.adjIndex ; Adv -> T.advIndex }) overview of Nothing -> return [] Just idx -> do let numSenses = T.indexSenseCount idx skL <- mapMaybe id `liftM` unsafeInterleaveIO ( mapM (\sense' -> do skey <- P.indexToSenseKey ?wne idx sense' return (liftM ((,) sense') skey) ) (sensesOf numSenses sense) ) r <- unsafeInterleaveIO $ mapM (\ (snum, skey) -> unsafeInterleaveIO (P.getSynsetForSense ?wne skey) >>= \v -> case v of Nothing -> return Nothing Just ss -> return $ Just (T.SearchResult (Just skey) (Just overview) (Just idx) (Just (SenseNumber snum)) ss) ) skL return (mapMaybe id r) -- | This takes a 'Word', a 'POS' and a 'SenseType' and returns -- the equivalent of first running 'getOverview' and then 'searchByOverview'. search :: WN (Word -> POS -> SenseType -> [SearchResult]) search word = searchByOverview (getOverview word) -- | This takes a 'Key' (see 'srToKey' and 'srFormKeys') and looks it -- up in the databse. lookupKey :: WN (Key -> SearchResult) lookupKey (T.Key (o,p)) = unsafePerformIO $ do ss <- unsafeInterleaveIO $ P.readSynset ?wne p o "" return $ T.SearchResult Nothing Nothing Nothing Nothing ss -- | This takes a 'Form' and a 'SearchResult' and returns all -- 'SearchResult' related to the given one by the given 'Form'. -- -- For example: -- -- > relatedBy Antonym (head (search "happy" Adj 1)) -- > [<unhappy>] -- > -- > relatedBy Hypernym (head (search "dog" Noun 1)) -- > [<canine canid>] relatedBy :: WN (Form -> SearchResult -> [SearchResult]) relatedBy form sr = map lookupKey $ srFormKeys sr form -- | This is a utility function to build lazy trees from a function and a root. closure :: (a -> [a]) -> a -> Tree a closure f x = Node x (map (closure f) $ f x) -- | This enables 'Form'-based trees to be built. -- -- For example: -- -- > take 5 $ flatten $ closureOn Antonym (head (search "happy" Adj AllSenses))) -- > [<happy>,<unhappy>,<happy>,<unhappy>,<happy>] -- -- > closureOn Hypernym (head (search "dog" Noun 1))) -- > - <dog domestic_dog Canis_familiaris> --- <canine canid> --- <carnivore>\\ -- > --- <placental placental_mammal eutherian eutherian_mammal> --- <mammal>\\ -- > --- <vertebrate craniate> --- <chordate> --- <animal animate_being beast\\ -- > brute creature fauna> --- <organism being> --- <living_thing animate_thing>\\ -- > --- <object physical_object> --- <entity> closureOn :: WN (Form -> SearchResult -> Tree SearchResult) closureOn form = closure (relatedBy form) -- | A simple bag class for our 'meet' implementation. class Bag b a where emptyBag :: b a addToBag :: b a -> a -> b a addListToBag :: b a -> [a] -> b a isEmptyBag :: b a -> Bool splitBag :: b a -> (a, b a) addListToBag = foldr (flip addToBag) instance Bag [] a where emptyBag = [] addToBag = flip (:) isEmptyBag = null splitBag (x:xs) = (x, xs) splitBag [] = undefined -- | A very slow queue based on lists. newtype Queue a = Queue [a] deriving (Show) instance Bag Queue a where emptyBag = Queue [] addToBag (Queue l) a = Queue (l++[a]) isEmptyBag (Queue l) = null l splitBag (Queue (x:xs)) = (x, Queue xs) splitBag (Queue []) = undefined addListToBag (Queue l) l' = Queue (l ++ l') -- | An empty stack. emptyStack :: [a] emptyStack = [] -- | An empty queue. emptyQueue :: Queue a emptyQueue = Queue [] -- | This function takes an empty bag (in particular, this is to specify -- what type of search to perform), and the results of two search. -- It returns (maybe) the lowest point at which the two terms -- meet in the WordNet hierarchy. -- -- For example: -- -- > meet emptyQueue (head $ search "cat" Noun 1) (head $ search "dog" Noun 1) -- > Just <carnivore> -- -- > meet emptyQueue (head $ search "run" Verb 1) (head $ search "walk" Verb 1) -- > Just <travel go move locomote> meet :: Bag b (Tree SearchResult) => WN (b (Tree SearchResult) -> SearchResult -> SearchResult -> Maybe SearchResult) meet emptyBg sr1 sr2 = srch Set.empty Set.empty (addToBag emptyBg t1) (addToBag emptyBg t2) where t1 = closureOn Hypernym sr1 t2 = closureOn Hypernym sr2 srch v1 v2 bag1 bag2 | isEmptyBag bag1 && isEmptyBag bag2 = Nothing | isEmptyBag bag1 = srch v2 v1 bag2 bag1 | otherwise = let (Node sr chl, bag1') = splitBag bag1 in if v2 `containsResult` sr then Just sr else srch v2 (addResult v1 sr) bag2 (addListToBag bag1' chl) -- flip the order :) containsResult v sr = srWords sr AllSenses `Set.member` v addResult v sr = Set.insert (srWords sr AllSenses) v -- | This function takes an empty bag (see 'meet'), and the results of two searches. -- It returns (maybe) the lowest point at which the two terms -- meet in the WordNet hierarchy, as well as the paths leading from each -- term to this common term. -- -- For example: -- -- > meetPaths emptyQueue (head $ search "cat" Noun 1) (head $ search "dog" Noun 1) -- > Just ([<cat true_cat>,<feline felid>],<carnivore>,[<canine canid>,<dog domestic_dog Canis_familiaris>]) -- -- > meetPaths emptyQueue (head $ search "run" Verb 1) (head $ search "walk" Verb 1) -- > Just ([<run>,<travel_rapidly speed hurry zip>],<travel go move locomote>,[<walk>]) -- -- This is marginally less efficient than just using 'meet', since it uses -- linear-time lookup for the visited sets, whereas 'meet' uses log-time -- lookup. meetPaths :: Bag b (Tree SearchResult) => WN ( b (Tree SearchResult) -> -- bag implementation SearchResult -> -- word 1 SearchResult -> -- word 2 Maybe ([SearchResult], SearchResult, [SearchResult])) -- word 1 -> common, -- common -- common -> word 2 meetPaths emptyBg sr1 sr2 = meetSearchPaths emptyBg t1 t2 where t1 = closureOn Hypernym sr1 t2 = closureOn Hypernym sr2 meetSearchPaths :: Bag b (Tree SearchResult) => b (Tree SearchResult) -> Tree SearchResult -> Tree SearchResult -> Maybe ([SearchResult], SearchResult, [SearchResult]) meetSearchPaths emptyBg t1 t2 = let srch b v1 v2 bag1 bag2 | isEmptyBag bag1 && isEmptyBag bag2 = Nothing | isEmptyBag bag1 = srch (not b) v2 v1 bag2 bag1 | otherwise = let (Node sr chl, bag1') = splitBag bag1 sl = srWords sr AllSenses in if v2 `containsResult` sl then Just $ if b then (reverse v1, sr, drop 1 $ dropWhile ((/=sl) . flip srWords AllSenses) v2) else (reverse $ drop 1 $ dropWhile ((/=sl) . flip srWords AllSenses) v2, sr, v1) else srch (not b) v2 (addResult v1 sr) bag2 (addListToBag bag1' chl) -- flip the order :) in srch True [] [] (addToBag emptyBg t1) (addToBag emptyBg t2) where containsResult v sl = sl `elem` map (`srWords` AllSenses) v addResult v sr = sr:v
pikajude/WordNet-ghc74
NLP/WordNet.hs
bsd-3-clause
13,042
0
28
3,501
2,500
1,332
1,168
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 TcSplice: Template Haskell splices -} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE MultiWayIf #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module TcSplice( -- These functions are defined in stage1 and stage2 -- The raise civilised errors in stage1 tcSpliceExpr, tcTypedBracket, tcUntypedBracket, -- runQuasiQuoteExpr, runQuasiQuotePat, -- runQuasiQuoteDecl, runQuasiQuoteType, runAnnotation, #ifdef GHCI -- These ones are defined only in stage2, and are -- called only in stage2 (ie GHCI is on) runMetaE, runMetaP, runMetaT, runMetaD, runQuasi, tcTopSpliceExpr, lookupThName_maybe, defaultRunMeta, runMeta', finishTH #endif ) where #include "HsVersions.h" import HsSyn import Annotations import Name import TcRnMonad import TcType import Outputable import TcExpr import SrcLoc import THNames import TcUnify import TcEnv import Control.Monad #ifdef GHCI import GHCi.Message import GHCi.RemoteTypes import GHCi import HscMain -- These imports are the reason that TcSplice -- is very high up the module hierarchy import RnSplice( traceSplice, SpliceInfo(..) ) import RdrName import HscTypes import Convert import RnExpr import RnEnv import RnTypes import TcHsSyn import TcSimplify import Type import Kind import NameSet import TcMType import TcHsType import TcIface import TyCoRep import FamInst import FamInstEnv import InstEnv import Inst import NameEnv import PrelNames import TysWiredIn import OccName import Hooks import Var import Module import LoadIface import Class import TyCon import CoAxiom import PatSyn import ConLike import DataCon import TcEvidence( TcEvBinds(..) ) import Id import IdInfo import DsExpr import DsMonad import GHC.Serialized import ErrUtils import Util import Unique import VarSet ( isEmptyVarSet, filterVarSet, mkVarSet, elemVarSet ) import Data.List ( find ) import Data.Maybe import FastString import BasicTypes hiding( SuccessFlag(..) ) import Maybes( MaybeErr(..) ) import DynFlags import Panic import Lexeme import qualified Language.Haskell.TH as TH -- THSyntax gives access to internal functions and data types import qualified Language.Haskell.TH.Syntax as TH -- Because GHC.Desugar might not be in the base library of the bootstrapping compiler import GHC.Desugar ( AnnotationWrapper(..) ) import qualified Data.IntSet as IntSet import Control.Exception import Data.Binary import Data.Binary.Get import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as LB import Data.Dynamic ( fromDynamic, toDyn ) import qualified Data.Map as Map import Data.Typeable ( typeOf, Typeable, TypeRep, typeRep ) import Data.Data (Data) import Data.Proxy ( Proxy (..) ) import GHC.Exts ( unsafeCoerce# ) #endif {- ************************************************************************ * * \subsection{Main interface + stubs for the non-GHCI case * * ************************************************************************ -} tcTypedBracket :: HsBracket Name -> ExpRhoType -> TcM (HsExpr TcId) tcUntypedBracket :: HsBracket Name -> [PendingRnSplice] -> ExpRhoType -> TcM (HsExpr TcId) tcSpliceExpr :: HsSplice Name -> ExpRhoType -> TcM (HsExpr TcId) -- None of these functions add constraints to the LIE -- runQuasiQuoteExpr :: HsQuasiQuote RdrName -> RnM (LHsExpr RdrName) -- runQuasiQuotePat :: HsQuasiQuote RdrName -> RnM (LPat RdrName) -- runQuasiQuoteType :: HsQuasiQuote RdrName -> RnM (LHsType RdrName) -- runQuasiQuoteDecl :: HsQuasiQuote RdrName -> RnM [LHsDecl RdrName] runAnnotation :: CoreAnnTarget -> LHsExpr Name -> TcM Annotation {- ************************************************************************ * * \subsection{Quoting an expression} * * ************************************************************************ -} -- See Note [How brackets and nested splices are handled] -- tcTypedBracket :: HsBracket Name -> TcRhoType -> TcM (HsExpr TcId) tcTypedBracket brack@(TExpBr expr) res_ty = addErrCtxt (quotationCtxtDoc brack) $ do { cur_stage <- getStage ; ps_ref <- newMutVar [] ; lie_var <- getConstraintVar -- Any constraints arising from nested splices -- should get thrown into the constraint set -- from outside the bracket -- Typecheck expr to make sure it is valid, -- Throw away the typechecked expression but return its type. -- We'll typecheck it again when we splice it in somewhere ; (_tc_expr, expr_ty) <- setStage (Brack cur_stage (TcPending ps_ref lie_var)) $ tcInferRhoNC expr -- NC for no context; tcBracket does that ; meta_ty <- tcTExpTy expr_ty ; ps' <- readMutVar ps_ref ; texpco <- tcLookupId unsafeTExpCoerceName ; tcWrapResultO (Shouldn'tHappenOrigin "TExpBr") (unLoc (mkHsApp (nlHsTyApp texpco [expr_ty]) (noLoc (HsTcBracketOut brack ps')))) meta_ty res_ty } tcTypedBracket other_brack _ = pprPanic "tcTypedBracket" (ppr other_brack) -- tcUntypedBracket :: HsBracket Name -> [PendingRnSplice] -> ExpRhoType -> TcM (HsExpr TcId) tcUntypedBracket brack ps res_ty = do { traceTc "tc_bracket untyped" (ppr brack $$ ppr ps) ; ps' <- mapM tcPendingSplice ps ; meta_ty <- tcBrackTy brack ; traceTc "tc_bracket done untyped" (ppr meta_ty) ; tcWrapResultO (Shouldn'tHappenOrigin "untyped bracket") (HsTcBracketOut brack ps') meta_ty res_ty } --------------- tcBrackTy :: HsBracket Name -> TcM TcType tcBrackTy (VarBr _ _) = tcMetaTy nameTyConName -- Result type is Var (not Q-monadic) tcBrackTy (ExpBr _) = tcMetaTy expQTyConName -- Result type is ExpQ (= Q Exp) tcBrackTy (TypBr _) = tcMetaTy typeQTyConName -- Result type is Type (= Q Typ) tcBrackTy (DecBrG _) = tcMetaTy decsQTyConName -- Result type is Q [Dec] tcBrackTy (PatBr _) = tcMetaTy patQTyConName -- Result type is PatQ (= Q Pat) tcBrackTy (DecBrL _) = panic "tcBrackTy: Unexpected DecBrL" tcBrackTy (TExpBr _) = panic "tcUntypedBracket: Unexpected TExpBr" --------------- tcPendingSplice :: PendingRnSplice -> TcM PendingTcSplice tcPendingSplice (PendingRnSplice flavour splice_name expr) = do { res_ty <- tcMetaTy meta_ty_name ; expr' <- tcMonoExpr expr (mkCheckExpType res_ty) ; return (PendingTcSplice splice_name expr') } where meta_ty_name = case flavour of UntypedExpSplice -> expQTyConName UntypedPatSplice -> patQTyConName UntypedTypeSplice -> typeQTyConName UntypedDeclSplice -> decsQTyConName --------------- -- Takes a tau and returns the type Q (TExp tau) tcTExpTy :: TcType -> TcM TcType tcTExpTy exp_ty = do { unless (isTauTy exp_ty) $ addErr (err_msg exp_ty) ; q <- tcLookupTyCon qTyConName ; texp <- tcLookupTyCon tExpTyConName ; return (mkTyConApp q [mkTyConApp texp [exp_ty]]) } where err_msg ty = vcat [ text "Illegal polytype:" <+> ppr ty , text "The type of a Typed Template Haskell expression must" <+> text "not have any quantification." ] quotationCtxtDoc :: HsBracket Name -> SDoc quotationCtxtDoc br_body = hang (text "In the Template Haskell quotation") 2 (ppr br_body) #ifndef GHCI tcSpliceExpr e _ = failTH e "Template Haskell splice" -- runQuasiQuoteExpr q = failTH q "quasiquote" -- runQuasiQuotePat q = failTH q "pattern quasiquote" -- runQuasiQuoteType q = failTH q "type quasiquote" -- runQuasiQuoteDecl q = failTH q "declaration quasiquote" runAnnotation _ q = failTH q "annotation" #else -- The whole of the rest of the file is the else-branch (ie stage2 only) {- Note [How top-level splices are handled] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Top-level splices (those not inside a [| .. |] quotation bracket) are handled very straightforwardly: 1. tcTopSpliceExpr: typecheck the body e of the splice $(e) 2. runMetaT: desugar, compile, run it, and convert result back to HsSyn RdrName (of the appropriate flavour, eg HsType RdrName, HsExpr RdrName etc) 3. treat the result as if that's what you saw in the first place e.g for HsType, rename and kind-check for HsExpr, rename and type-check (The last step is different for decls, because they can *only* be top-level: we return the result of step 2.) Note [How brackets and nested splices are handled] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Nested splices (those inside a [| .. |] quotation bracket), are treated quite differently. Remember, there are two forms of bracket typed [|| e ||] and untyped [| e |] The life cycle of a typed bracket: * Starts as HsBracket * When renaming: * Set the ThStage to (Brack s RnPendingTyped) * Rename the body * Result is still a HsBracket * When typechecking: * Set the ThStage to (Brack s (TcPending ps_var lie_var)) * Typecheck the body, and throw away the elaborated result * Nested splices (which must be typed) are typechecked, and the results accumulated in ps_var; their constraints accumulate in lie_var * Result is a HsTcBracketOut rn_brack pending_splices where rn_brack is the incoming renamed bracket The life cycle of a un-typed bracket: * Starts as HsBracket * When renaming: * Set the ThStage to (Brack s (RnPendingUntyped ps_var)) * Rename the body * Nested splices (which must be untyped) are renamed, and the results accumulated in ps_var * Result is still (HsRnBracketOut rn_body pending_splices) * When typechecking a HsRnBracketOut * Typecheck the pending_splices individually * Ignore the body of the bracket; just check that the context expects a bracket of that type (e.g. a [p| pat |] bracket should be in a context needing a (Q Pat) * Result is a HsTcBracketOut rn_brack pending_splices where rn_brack is the incoming renamed bracket In both cases, desugaring happens like this: * HsTcBracketOut is desugared by DsMeta.dsBracket. It a) Extends the ds_meta environment with the PendingSplices attached to the bracket b) Converts the quoted (HsExpr Name) to a CoreExpr that, when run, will produce a suitable TH expression/type/decl. This is why we leave the *renamed* expression attached to the bracket: the quoted expression should not be decorated with all the goop added by the type checker * Each splice carries a unique Name, called a "splice point", thus ${n}(e). The name is initialised to an (Unqual "splice") when the splice is created; the renamer gives it a unique. * When DsMeta (used to desugar the body of the bracket) comes across a splice, it looks up the splice's Name, n, in the ds_meta envt, to find an (HsExpr Id) that should be substituted for the splice; it just desugars it to get a CoreExpr (DsMeta.repSplice). Example: Source: f = [| Just $(g 3) |] The [| |] part is a HsBracket Typechecked: f = [| Just ${s7}(g 3) |]{s7 = g Int 3} The [| |] part is a HsBracketOut, containing *renamed* (not typechecked) expression The "s7" is the "splice point"; the (g Int 3) part is a typechecked expression Desugared: f = do { s7 <- g Int 3 ; return (ConE "Data.Maybe.Just" s7) } Note [Template Haskell state diagram] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here are the ThStages, s, their corresponding level numbers (the result of (thLevel s)), and their state transitions. The top level of the program is stage Comp: Start here | V ----------- $ ------------ $ | Comp | ---------> | Splice | -----| | 1 | | 0 | <----| ----------- ------------ ^ | ^ | $ | | [||] $ | | [||] | v | v -------------- ---------------- | Brack Comp | | Brack Splice | | 2 | | 1 | -------------- ---------------- * Normal top-level declarations start in state Comp (which has level 1). Annotations start in state Splice, since they are treated very like a splice (only without a '$') * Code compiled in state Splice (and only such code) will be *run at compile time*, with the result replacing the splice * The original paper used level -1 instead of 0, etc. * The original paper did not allow a splice within a splice, but there is no reason not to. This is the $ transition in the top right. Note [Template Haskell levels] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Imported things are impLevel (= 0) * However things at level 0 are not *necessarily* imported. eg $( \b -> ... ) here b is bound at level 0 * In GHCi, variables bound by a previous command are treated as impLevel, because we have bytecode for them. * Variables are bound at the "current level" * The current level starts off at outerLevel (= 1) * The level is decremented by splicing $(..) incremented by brackets [| |] incremented by name-quoting 'f When a variable is used, we compare bind: binding level, and use: current level at usage site Generally bind > use Always error (bound later than used) [| \x -> $(f x) |] bind = use Always OK (bound same stage as used) [| \x -> $(f [| x |]) |] bind < use Inside brackets, it depends Inside splice, OK Inside neither, OK For (bind < use) inside brackets, there are three cases: - Imported things OK f = [| map |] - Top-level things OK g = [| f |] - Non-top-level Only if there is a liftable instance h = \(x:Int) -> [| x |] To track top-level-ness we use the ThBindEnv in TcLclEnv For example: f = ... g1 = $(map ...) is OK g2 = $(f ...) is not OK; because we havn't compiled f yet -} {- ************************************************************************ * * \subsection{Splicing an expression} * * ************************************************************************ -} tcSpliceExpr splice@(HsTypedSplice name expr) res_ty = addErrCtxt (spliceCtxtDoc splice) $ setSrcSpan (getLoc expr) $ do { stage <- getStage ; case stage of Splice {} -> tcTopSplice expr res_ty Comp -> tcTopSplice expr res_ty Brack pop_stage pend -> tcNestedSplice pop_stage pend name expr res_ty } tcSpliceExpr splice _ = pprPanic "tcSpliceExpr" (ppr splice) tcNestedSplice :: ThStage -> PendingStuff -> Name -> LHsExpr Name -> ExpRhoType -> TcM (HsExpr Id) -- See Note [How brackets and nested splices are handled] -- A splice inside brackets tcNestedSplice pop_stage (TcPending ps_var lie_var) splice_name expr res_ty = do { res_ty <- expTypeToType res_ty ; meta_exp_ty <- tcTExpTy res_ty ; expr' <- setStage pop_stage $ setConstraintVar lie_var $ tcMonoExpr expr (mkCheckExpType meta_exp_ty) ; untypeq <- tcLookupId unTypeQName ; let expr'' = mkHsApp (nlHsTyApp untypeq [res_ty]) expr' ; ps <- readMutVar ps_var ; writeMutVar ps_var (PendingTcSplice splice_name expr'' : ps) -- The returned expression is ignored; it's in the pending splices ; return (panic "tcSpliceExpr") } tcNestedSplice _ _ splice_name _ _ = pprPanic "tcNestedSplice: rename stage found" (ppr splice_name) tcTopSplice :: LHsExpr Name -> ExpRhoType -> TcM (HsExpr Id) tcTopSplice expr res_ty = do { -- Typecheck the expression, -- making sure it has type Q (T res_ty) res_ty <- expTypeToType res_ty ; meta_exp_ty <- tcTExpTy res_ty ; zonked_q_expr <- tcTopSpliceExpr Typed $ tcMonoExpr expr (mkCheckExpType meta_exp_ty) -- Run the expression ; expr2 <- runMetaE zonked_q_expr ; traceSplice (SpliceInfo { spliceDescription = "expression" , spliceIsDecl = False , spliceSource = Just expr , spliceGenerated = ppr expr2 }) -- Rename and typecheck the spliced-in expression, -- making sure it has type res_ty -- These steps should never fail; this is a *typed* splice ; addErrCtxt (spliceResultDoc expr) $ do { (exp3, _fvs) <- rnLExpr expr2 ; exp4 <- tcMonoExpr exp3 (mkCheckExpType res_ty) ; return (unLoc exp4) } } {- ************************************************************************ * * \subsection{Error messages} * * ************************************************************************ -} spliceCtxtDoc :: HsSplice Name -> SDoc spliceCtxtDoc splice = hang (text "In the Template Haskell splice") 2 (pprSplice splice) spliceResultDoc :: LHsExpr Name -> SDoc spliceResultDoc expr = sep [ text "In the result of the splice:" , nest 2 (char '$' <> pprParendLExpr expr) , text "To see what the splice expanded to, use -ddump-splices"] ------------------- tcTopSpliceExpr :: SpliceType -> TcM (LHsExpr Id) -> TcM (LHsExpr Id) -- Note [How top-level splices are handled] -- Type check an expression that is the body of a top-level splice -- (the caller will compile and run it) -- Note that set the level to Splice, regardless of the original level, -- before typechecking the expression. For example: -- f x = $( ...$(g 3) ... ) -- The recursive call to tcPolyExpr will simply expand the -- inner escape before dealing with the outer one tcTopSpliceExpr isTypedSplice tc_action = checkNoErrs $ -- checkNoErrs: must not try to run the thing -- if the type checker fails! unsetGOptM Opt_DeferTypeErrors $ -- Don't defer type errors. Not only are we -- going to run this code, but we do an unsafe -- coerce, so we get a seg-fault if, say we -- splice a type into a place where an expression -- is expected (Trac #7276) setStage (Splice isTypedSplice) $ do { -- Typecheck the expression (expr', wanted) <- captureConstraints tc_action ; const_binds <- simplifyTop wanted -- Zonk it and tie the knot of dictionary bindings ; zonkTopLExpr (mkHsDictLet (EvBinds const_binds) expr') } {- ************************************************************************ * * Annotations * * ************************************************************************ -} runAnnotation target expr = do -- Find the classes we want instances for in order to call toAnnotationWrapper loc <- getSrcSpanM data_class <- tcLookupClass dataClassName to_annotation_wrapper_id <- tcLookupId toAnnotationWrapperName -- Check the instances we require live in another module (we want to execute it..) -- and check identifiers live in other modules using TH stage checks. tcSimplifyStagedExpr -- also resolves the LIE constraints to detect e.g. instance ambiguity zonked_wrapped_expr' <- tcTopSpliceExpr Untyped $ do { (expr', expr_ty) <- tcInferRhoNC expr -- We manually wrap the typechecked expression in a call to toAnnotationWrapper -- By instantiating the call >here< it gets registered in the -- LIE consulted by tcTopSpliceExpr -- and hence ensures the appropriate dictionary is bound by const_binds ; wrapper <- instCall AnnOrigin [expr_ty] [mkClassPred data_class [expr_ty]] ; let specialised_to_annotation_wrapper_expr = L loc (HsWrap wrapper (HsVar (L loc to_annotation_wrapper_id))) ; return (L loc (HsApp specialised_to_annotation_wrapper_expr expr')) } -- Run the appropriately wrapped expression to get the value of -- the annotation and its dictionaries. The return value is of -- type AnnotationWrapper by construction, so this conversion is -- safe serialized <- runMetaAW zonked_wrapped_expr' return Annotation { ann_target = target, ann_value = serialized } convertAnnotationWrapper :: ForeignHValue -> TcM (Either MsgDoc Serialized) convertAnnotationWrapper fhv = do dflags <- getDynFlags if gopt Opt_ExternalInterpreter dflags then do Right <$> runTH THAnnWrapper fhv else do annotation_wrapper <- liftIO $ wormhole dflags fhv return $ Right $ case unsafeCoerce# annotation_wrapper of AnnotationWrapper value | let serialized = toSerialized serializeWithData value -> -- Got the value and dictionaries: build the serialized value and -- call it a day. We ensure that we seq the entire serialized value -- in order that any errors in the user-written code for the -- annotation are exposed at this point. This is also why we are -- doing all this stuff inside the context of runMeta: it has the -- facilities to deal with user error in a meta-level expression seqSerialized serialized `seq` serialized -- | Force the contents of the Serialized value so weknow it doesn't contain any bottoms seqSerialized :: Serialized -> () seqSerialized (Serialized the_type bytes) = the_type `seq` bytes `seqList` () {- ************************************************************************ * * \subsection{Running an expression} * * ************************************************************************ -} runQuasi :: TH.Q a -> TcM a runQuasi act = TH.runQ act runQResult :: (a -> String) -> (SrcSpan -> a -> b) -> (ForeignHValue -> TcM a) -> SrcSpan -> ForeignHValue {- TH.Q a -} -> TcM b runQResult show_th f runQ expr_span hval = do { th_result <- runQ hval ; traceTc "Got TH result:" (text (show_th th_result)) ; return (f expr_span th_result) } ----------------- runMeta :: (MetaHook TcM -> LHsExpr Id -> TcM hs_syn) -> LHsExpr Id -> TcM hs_syn runMeta unwrap e = do { h <- getHooked runMetaHook defaultRunMeta ; unwrap h e } defaultRunMeta :: MetaHook TcM defaultRunMeta (MetaE r) = fmap r . runMeta' True ppr (runQResult TH.pprint convertToHsExpr runTHExp) defaultRunMeta (MetaP r) = fmap r . runMeta' True ppr (runQResult TH.pprint convertToPat runTHPat) defaultRunMeta (MetaT r) = fmap r . runMeta' True ppr (runQResult TH.pprint convertToHsType runTHType) defaultRunMeta (MetaD r) = fmap r . runMeta' True ppr (runQResult TH.pprint convertToHsDecls runTHDec) defaultRunMeta (MetaAW r) = fmap r . runMeta' False (const empty) (const convertAnnotationWrapper) -- We turn off showing the code in meta-level exceptions because doing so exposes -- the toAnnotationWrapper function that we slap around the users code ---------------- runMetaAW :: LHsExpr Id -- Of type AnnotationWrapper -> TcM Serialized runMetaAW = runMeta metaRequestAW runMetaE :: LHsExpr Id -- Of type (Q Exp) -> TcM (LHsExpr RdrName) runMetaE = runMeta metaRequestE runMetaP :: LHsExpr Id -- Of type (Q Pat) -> TcM (LPat RdrName) runMetaP = runMeta metaRequestP runMetaT :: LHsExpr Id -- Of type (Q Type) -> TcM (LHsType RdrName) runMetaT = runMeta metaRequestT runMetaD :: LHsExpr Id -- Of type Q [Dec] -> TcM [LHsDecl RdrName] runMetaD = runMeta metaRequestD --------------- runMeta' :: Bool -- Whether code should be printed in the exception message -> (hs_syn -> SDoc) -- how to print the code -> (SrcSpan -> ForeignHValue -> TcM (Either MsgDoc hs_syn)) -- How to run x -> LHsExpr Id -- Of type x; typically x = Q TH.Exp, or something like that -> TcM hs_syn -- Of type t runMeta' show_code ppr_hs run_and_convert expr = do { traceTc "About to run" (ppr expr) ; recordThSpliceUse -- seems to be the best place to do this, -- we catch all kinds of splices and annotations. -- Check that we've had no errors of any sort so far. -- For example, if we found an error in an earlier defn f, but -- recovered giving it type f :: forall a.a, it'd be very dodgy -- to carry ont. Mind you, the staging restrictions mean we won't -- actually run f, but it still seems wrong. And, more concretely, -- see Trac #5358 for an example that fell over when trying to -- reify a function with a "?" kind in it. (These don't occur -- in type-correct programs. ; failIfErrsM -- Desugar ; ds_expr <- initDsTc (dsLExpr expr) -- Compile and link it; might fail if linking fails ; hsc_env <- getTopEnv ; src_span <- getSrcSpanM ; traceTc "About to run (desugared)" (ppr ds_expr) ; either_hval <- tryM $ liftIO $ HscMain.hscCompileCoreExpr hsc_env src_span ds_expr ; case either_hval of { Left exn -> fail_with_exn "compile and link" exn ; Right hval -> do { -- Coerce it to Q t, and run it -- Running might fail if it throws an exception of any kind (hence tryAllM) -- including, say, a pattern-match exception in the code we are running -- -- We also do the TH -> HS syntax conversion inside the same -- exception-cacthing thing so that if there are any lurking -- exceptions in the data structure returned by hval, we'll -- encounter them inside the try -- -- See Note [Exceptions in TH] let expr_span = getLoc expr ; either_tval <- tryAllM $ setSrcSpan expr_span $ -- Set the span so that qLocation can -- see where this splice is do { mb_result <- run_and_convert expr_span hval ; case mb_result of Left err -> failWithTc err Right result -> do { traceTc "Got HsSyn result:" (ppr_hs result) ; return $! result } } ; case either_tval of Right v -> return v Left se -> case fromException se of Just IOEnvFailure -> failM -- Error already in Tc monad _ -> fail_with_exn "run" se -- Exception }}} where -- see Note [Concealed TH exceptions] fail_with_exn :: Exception e => String -> e -> TcM a fail_with_exn phase exn = do exn_msg <- liftIO $ Panic.safeShowException exn let msg = vcat [text "Exception when trying to" <+> text phase <+> text "compile-time code:", nest 2 (text exn_msg), if show_code then text "Code:" <+> ppr expr else empty] failWithTc msg {- Note [Exceptions in TH] ~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have something like this $( f 4 ) where f :: Int -> Q [Dec] f n | n>3 = fail "Too many declarations" | otherwise = ... The 'fail' is a user-generated failure, and should be displayed as a perfectly ordinary compiler error message, not a panic or anything like that. Here's how it's processed: * 'fail' is the monad fail. The monad instance for Q in TH.Syntax effectively transforms (fail s) to qReport True s >> fail where 'qReport' comes from the Quasi class and fail from its monad superclass. * The TcM monad is an instance of Quasi (see TcSplice), and it implements (qReport True s) by using addErr to add an error message to the bag of errors. The 'fail' in TcM raises an IOEnvFailure exception * 'qReport' forces the message to ensure any exception hidden in unevaluated thunk doesn't get into the bag of errors. Otherwise the following splice will triger panic (Trac #8987): $(fail undefined) See also Note [Concealed TH exceptions] * So, when running a splice, we catch all exceptions; then for - an IOEnvFailure exception, we assume the error is already in the error-bag (above) - other errors, we add an error to the bag and then fail Note [Concealed TH exceptions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When displaying the error message contained in an exception originated from TH code, we need to make sure that the error message itself does not contain an exception. For example, when executing the following splice: $( error ("foo " ++ error "bar") ) the message for the outer exception is a thunk which will throw the inner exception when evaluated. For this reason, we display the message of a TH exception using the 'safeShowException' function, which recursively catches any exception thrown when showing an error message. To call runQ in the Tc monad, we need to make TcM an instance of Quasi: -} instance TH.Quasi TcM where qNewName s = do { u <- newUnique ; let i = getKey u ; return (TH.mkNameU s i) } -- 'msg' is forced to ensure exceptions don't escape, -- see Note [Exceptions in TH] qReport True msg = seqList msg $ addErr (text msg) qReport False msg = seqList msg $ addWarn NoReason (text msg) qLocation = do { m <- getModule ; l <- getSrcSpanM ; r <- case l of UnhelpfulSpan _ -> pprPanic "qLocation: Unhelpful location" (ppr l) RealSrcSpan s -> return s ; return (TH.Loc { TH.loc_filename = unpackFS (srcSpanFile r) , TH.loc_module = moduleNameString (moduleName m) , TH.loc_package = unitIdString (moduleUnitId m) , TH.loc_start = (srcSpanStartLine r, srcSpanStartCol r) , TH.loc_end = (srcSpanEndLine r, srcSpanEndCol r) }) } qLookupName = lookupName qReify = reify qReifyFixity nm = lookupThName nm >>= reifyFixity qReifyInstances = reifyInstances qReifyRoles = reifyRoles qReifyAnnotations = reifyAnnotations qReifyModule = reifyModule qReifyConStrictness nm = do { nm' <- lookupThName nm ; dc <- tcLookupDataCon nm' ; let bangs = dataConImplBangs dc ; return (map reifyDecidedStrictness bangs) } -- For qRecover, discard error messages if -- the recovery action is chosen. Otherwise -- we'll only fail higher up. c.f. tryTcLIE_ qRecover recover main = do { (msgs, mb_res) <- tryTcErrs main ; case mb_res of Just val -> do { addMessages msgs -- There might be warnings ; return val } Nothing -> recover -- Discard all msgs } qRunIO io = liftIO io qAddDependentFile fp = do ref <- fmap tcg_dependent_files getGblEnv dep_files <- readTcRef ref writeTcRef ref (fp:dep_files) qAddTopDecls thds = do l <- getSrcSpanM let either_hval = convertToHsDecls l thds ds <- case either_hval of Left exn -> pprPanic "qAddTopDecls: can't convert top-level declarations" exn Right ds -> return ds mapM_ (checkTopDecl . unLoc) ds th_topdecls_var <- fmap tcg_th_topdecls getGblEnv updTcRef th_topdecls_var (\topds -> ds ++ topds) where checkTopDecl :: HsDecl RdrName -> TcM () checkTopDecl (ValD binds) = mapM_ bindName (collectHsBindBinders binds) checkTopDecl (SigD _) = return () checkTopDecl (AnnD _) = return () checkTopDecl (ForD (ForeignImport { fd_name = L _ name })) = bindName name checkTopDecl _ = addErr $ text "Only function, value, annotation, and foreign import declarations may be added with addTopDecl" bindName :: RdrName -> TcM () bindName (Exact n) = do { th_topnames_var <- fmap tcg_th_topnames getGblEnv ; updTcRef th_topnames_var (\ns -> extendNameSet ns n) } bindName name = addErr $ hang (text "The binder" <+> quotes (ppr name) <+> ptext (sLit "is not a NameU.")) 2 (text "Probable cause: you used mkName instead of newName to generate a binding.") qAddModFinalizer fin = do th_modfinalizers_var <- fmap tcg_th_modfinalizers getGblEnv updTcRef th_modfinalizers_var (\fins -> fin:fins) qGetQ :: forall a. Typeable a => TcM (Maybe a) qGetQ = do th_state_var <- fmap tcg_th_state getGblEnv th_state <- readTcRef th_state_var -- See #10596 for why we use a scoped type variable here. return (Map.lookup (typeRep (Proxy :: Proxy a)) th_state >>= fromDynamic) qPutQ x = do th_state_var <- fmap tcg_th_state getGblEnv updTcRef th_state_var (\m -> Map.insert (typeOf x) (toDyn x) m) qIsExtEnabled = xoptM qExtsEnabled = do dflags <- hsc_dflags <$> getTopEnv return $ map toEnum $ IntSet.elems $ extensionFlags dflags -- | Run all module finalizers finishTH :: TcM () finishTH = do hsc_env <- env_top <$> getEnv dflags <- getDynFlags if not (gopt Opt_ExternalInterpreter dflags) then do tcg <- getGblEnv let th_modfinalizers_var = tcg_th_modfinalizers tcg modfinalizers <- readTcRef th_modfinalizers_var writeTcRef th_modfinalizers_var [] mapM_ runQuasi modfinalizers else withIServ hsc_env $ \i -> do tcg <- getGblEnv th_state <- readTcRef (tcg_th_remote_state tcg) case th_state of Nothing -> return () -- TH was not started, nothing to do Just fhv -> do liftIO $ withForeignRef fhv $ \rhv -> writeIServ i (putMessage (FinishTH rhv)) () <- runRemoteTH i [] writeTcRef (tcg_th_remote_state tcg) Nothing runTHExp :: ForeignHValue -> TcM TH.Exp runTHExp = runTH THExp runTHPat :: ForeignHValue -> TcM TH.Pat runTHPat = runTH THPat runTHType :: ForeignHValue -> TcM TH.Type runTHType = runTH THType runTHDec :: ForeignHValue -> TcM [TH.Dec] runTHDec = runTH THDec runTH :: Binary a => THResultType -> ForeignHValue -> TcM a runTH ty fhv = do hsc_env <- env_top <$> getEnv dflags <- getDynFlags if not (gopt Opt_ExternalInterpreter dflags) then do -- just run it in the local TcM hv <- liftIO $ wormhole dflags fhv r <- runQuasi (unsafeCoerce# hv :: TH.Q a) return r else -- run it on the server withIServ hsc_env $ \i -> do rstate <- getTHState i loc <- TH.qLocation liftIO $ withForeignRef rstate $ \state_hv -> withForeignRef fhv $ \q_hv -> writeIServ i (putMessage (RunTH state_hv q_hv ty (Just loc))) bs <- runRemoteTH i [] return $! runGet get (LB.fromStrict bs) -- | communicate with a remotely-running TH computation until it -- finishes and returns a result. runRemoteTH :: Binary a => IServ -> [Messages] -- saved from nested calls to qRecover -> TcM a runRemoteTH iserv recovers = do Msg msg <- liftIO $ readIServ iserv getMessage case msg of QDone -> liftIO $ readIServ iserv get QException str -> liftIO $ throwIO (ErrorCall str) QFail str -> fail str StartRecover -> do -- Note [TH recover with -fexternal-interpreter] v <- getErrsVar msgs <- readTcRef v writeTcRef v emptyMessages runRemoteTH iserv (msgs : recovers) EndRecover caught_error -> do v <- getErrsVar let (prev_msgs, rest) = case recovers of [] -> panic "EndRecover" a : b -> (a,b) if caught_error then writeTcRef v prev_msgs else updTcRef v (unionMessages prev_msgs) runRemoteTH iserv rest _other -> do r <- handleTHMessage msg liftIO $ writeIServ iserv (put r) runRemoteTH iserv recovers {- Note [TH recover with -fexternal-interpreter] Recover is slightly tricky to implement. The meaning of "recover a b" is - Do a - If it finished successfully, then keep the messages it generated - If it failed, discard any messages it generated, and do b The messages are managed by GHC in the TcM monad, whereas the exception-handling is done in the ghc-iserv process, so we have to coordinate between the two. On the server: - emit a StartRecover message - run "a" inside a catch - if it finishes, emit EndRecover False - if it fails, emit EndRecover True, then run "b" Back in GHC, when we receive: StartRecover save the current messages and start with an empty set. EndRecover caught_error Restore the previous messages, and merge in the new messages if caught_error is false. -} getTHState :: IServ -> TcM (ForeignRef (IORef QState)) getTHState i = do tcg <- getGblEnv th_state <- readTcRef (tcg_th_remote_state tcg) case th_state of Just rhv -> return rhv Nothing -> do hsc_env <- env_top <$> getEnv fhv <- liftIO $ mkFinalizedHValue hsc_env =<< iservCall i StartTH writeTcRef (tcg_th_remote_state tcg) (Just fhv) return fhv wrapTHResult :: TcM a -> TcM (THResult a) wrapTHResult tcm = do e <- tryM tcm -- only catch 'fail', treat everything else as catastrophic case e of Left e -> return (THException (show e)) Right a -> return (THComplete a) handleTHMessage :: Message a -> TcM a handleTHMessage msg = case msg of NewName a -> wrapTHResult $ TH.qNewName a Report b str -> wrapTHResult $ TH.qReport b str LookupName b str -> wrapTHResult $ TH.qLookupName b str Reify n -> wrapTHResult $ TH.qReify n ReifyFixity n -> wrapTHResult $ TH.qReifyFixity n ReifyInstances n ts -> wrapTHResult $ TH.qReifyInstances n ts ReifyRoles n -> wrapTHResult $ TH.qReifyRoles n ReifyAnnotations lookup tyrep -> wrapTHResult $ (map B.pack <$> getAnnotationsByTypeRep lookup tyrep) ReifyModule m -> wrapTHResult $ TH.qReifyModule m AddDependentFile f -> wrapTHResult $ TH.qAddDependentFile f AddTopDecls decs -> wrapTHResult $ TH.qAddTopDecls decs IsExtEnabled ext -> wrapTHResult $ TH.qIsExtEnabled ext ExtsEnabled -> wrapTHResult $ TH.qExtsEnabled _ -> panic ("handleTHMessage: unexpected message " ++ show msg) getAnnotationsByTypeRep :: TH.AnnLookup -> TypeRep -> TcM [[Word8]] getAnnotationsByTypeRep th_name tyrep = do { name <- lookupThAnnLookup th_name ; topEnv <- getTopEnv ; epsHptAnns <- liftIO $ prepareAnnotations topEnv Nothing ; tcg <- getGblEnv ; let selectedEpsHptAnns = findAnnsByTypeRep epsHptAnns name tyrep ; let selectedTcgAnns = findAnnsByTypeRep (tcg_ann_env tcg) name tyrep ; return (selectedEpsHptAnns ++ selectedTcgAnns) } {- ************************************************************************ * * Instance Testing * * ************************************************************************ -} reifyInstances :: TH.Name -> [TH.Type] -> TcM [TH.Dec] reifyInstances th_nm th_tys = addErrCtxt (text "In the argument of reifyInstances:" <+> ppr_th th_nm <+> sep (map ppr_th th_tys)) $ do { loc <- getSrcSpanM ; rdr_ty <- cvt loc (mkThAppTs (TH.ConT th_nm) th_tys) -- #9262 says to bring vars into scope, like in HsForAllTy case -- of rnHsTyKi ; free_vars <- extractHsTyRdrTyVars rdr_ty ; let tv_rdrs = freeKiTyVarsAllVars free_vars -- Rename to HsType Name ; ((tv_names, rn_ty), _fvs) <- bindLRdrNames tv_rdrs $ \ tv_names -> do { (rn_ty, fvs) <- rnLHsType doc rdr_ty ; return ((tv_names, rn_ty), fvs) } ; (_tvs, ty) <- solveEqualities $ tcImplicitTKBndrsType tv_names $ fst <$> tcLHsType rn_ty ; ty <- zonkTcTypeToType emptyZonkEnv ty -- Substitute out the meta type variables -- In particular, the type might have kind -- variables inside it (Trac #7477) ; traceTc "reifyInstances" (ppr ty $$ ppr (typeKind ty)) ; case splitTyConApp_maybe ty of -- This expands any type synonyms Just (tc, tys) -- See Trac #7910 | Just cls <- tyConClass_maybe tc -> do { inst_envs <- tcGetInstEnvs ; let (matches, unifies, _) = lookupInstEnv False inst_envs cls tys ; traceTc "reifyInstances1" (ppr matches) ; reifyClassInstances cls (map fst matches ++ unifies) } | isOpenFamilyTyCon tc -> do { inst_envs <- tcGetFamInstEnvs ; let matches = lookupFamInstEnv inst_envs tc tys ; traceTc "reifyInstances2" (ppr matches) ; reifyFamilyInstances tc (map fim_instance matches) } _ -> bale_out (hang (text "reifyInstances:" <+> quotes (ppr ty)) 2 (text "is not a class constraint or type family application")) } where doc = ClassInstanceCtx bale_out msg = failWithTc msg cvt :: SrcSpan -> TH.Type -> TcM (LHsType RdrName) cvt loc th_ty = case convertToHsType loc th_ty of Left msg -> failWithTc msg Right ty -> return ty {- ************************************************************************ * * Reification * * ************************************************************************ -} lookupName :: Bool -- True <=> type namespace -- False <=> value namespace -> String -> TcM (Maybe TH.Name) lookupName is_type_name s = do { lcl_env <- getLocalRdrEnv ; case lookupLocalRdrEnv lcl_env rdr_name of Just n -> return (Just (reifyName n)) Nothing -> do { mb_nm <- lookupGlobalOccRn_maybe rdr_name ; return (fmap reifyName mb_nm) } } where th_name = TH.mkName s -- Parses M.x into a base of 'x' and a module of 'M' occ_fs :: FastString occ_fs = mkFastString (TH.nameBase th_name) occ :: OccName occ | is_type_name = if isLexCon occ_fs then mkTcOccFS occ_fs else mkTyVarOccFS occ_fs | otherwise = if isLexCon occ_fs then mkDataOccFS occ_fs else mkVarOccFS occ_fs rdr_name = case TH.nameModule th_name of Nothing -> mkRdrUnqual occ Just mod -> mkRdrQual (mkModuleName mod) occ getThing :: TH.Name -> TcM TcTyThing getThing th_name = do { name <- lookupThName th_name ; traceIf (text "reify" <+> text (show th_name) <+> brackets (ppr_ns th_name) <+> ppr name) ; tcLookupTh name } -- ToDo: this tcLookup could fail, which would give a -- rather unhelpful error message where ppr_ns (TH.Name _ (TH.NameG TH.DataName _pkg _mod)) = text "data" ppr_ns (TH.Name _ (TH.NameG TH.TcClsName _pkg _mod)) = text "tc" ppr_ns (TH.Name _ (TH.NameG TH.VarName _pkg _mod)) = text "var" ppr_ns _ = panic "reify/ppr_ns" reify :: TH.Name -> TcM TH.Info reify th_name = do { traceTc "reify 1" (text (TH.showName th_name)) ; thing <- getThing th_name ; traceTc "reify 2" (ppr thing) ; reifyThing thing } lookupThName :: TH.Name -> TcM Name lookupThName th_name = do mb_name <- lookupThName_maybe th_name case mb_name of Nothing -> failWithTc (notInScope th_name) Just name -> return name lookupThName_maybe :: TH.Name -> TcM (Maybe Name) lookupThName_maybe th_name = do { names <- mapMaybeM lookup (thRdrNameGuesses th_name) -- Pick the first that works -- E.g. reify (mkName "A") will pick the class A in preference to the data constructor A ; return (listToMaybe names) } where lookup rdr_name = do { -- Repeat much of lookupOccRn, becase we want -- to report errors in a TH-relevant way ; rdr_env <- getLocalRdrEnv ; case lookupLocalRdrEnv rdr_env rdr_name of Just name -> return (Just name) Nothing -> lookupGlobalOccRn_maybe rdr_name } tcLookupTh :: Name -> TcM TcTyThing -- This is a specialised version of TcEnv.tcLookup; specialised mainly in that -- it gives a reify-related error message on failure, whereas in the normal -- tcLookup, failure is a bug. tcLookupTh name = do { (gbl_env, lcl_env) <- getEnvs ; case lookupNameEnv (tcl_env lcl_env) name of { Just thing -> return thing; Nothing -> case lookupNameEnv (tcg_type_env gbl_env) name of { Just thing -> return (AGlobal thing); Nothing -> if nameIsLocalOrFrom (tcg_mod gbl_env) name then -- It's defined in this module failWithTc (notInEnv name) else do { mb_thing <- tcLookupImported_maybe name ; case mb_thing of Succeeded thing -> return (AGlobal thing) Failed msg -> failWithTc msg }}}} notInScope :: TH.Name -> SDoc notInScope th_name = quotes (text (TH.pprint th_name)) <+> text "is not in scope at a reify" -- Ugh! Rather an indirect way to display the name notInEnv :: Name -> SDoc notInEnv name = quotes (ppr name) <+> text "is not in the type environment at a reify" ------------------------------ reifyRoles :: TH.Name -> TcM [TH.Role] reifyRoles th_name = do { thing <- getThing th_name ; case thing of AGlobal (ATyCon tc) -> return (map reify_role (tyConRoles tc)) _ -> failWithTc (text "No roles associated with" <+> (ppr thing)) } where reify_role Nominal = TH.NominalR reify_role Representational = TH.RepresentationalR reify_role Phantom = TH.PhantomR ------------------------------ reifyThing :: TcTyThing -> TcM TH.Info -- The only reason this is monadic is for error reporting, -- which in turn is mainly for the case when TH can't express -- some random GHC extension reifyThing (AGlobal (AnId id)) = do { ty <- reifyType (idType id) ; let v = reifyName id ; case idDetails id of ClassOpId cls -> return (TH.ClassOpI v ty (reifyName cls)) RecSelId{sel_tycon=RecSelData tc} -> return (TH.VarI (reifySelector id tc) ty Nothing) _ -> return (TH.VarI v ty Nothing) } reifyThing (AGlobal (ATyCon tc)) = reifyTyCon tc reifyThing (AGlobal (AConLike (RealDataCon dc))) = do { let name = dataConName dc ; ty <- reifyType (idType (dataConWrapId dc)) ; return (TH.DataConI (reifyName name) ty (reifyName (dataConOrigTyCon dc))) } reifyThing (AGlobal (AConLike (PatSynCon ps))) = do { let name = reifyName ps ; ty <- reifyPatSynType (patSynSig ps) ; return (TH.PatSynI name ty) } reifyThing (ATcId {tct_id = id}) = do { ty1 <- zonkTcType (idType id) -- Make use of all the info we have, even -- though it may be incomplete ; ty2 <- reifyType ty1 ; return (TH.VarI (reifyName id) ty2 Nothing) } reifyThing (ATyVar tv tv1) = do { ty1 <- zonkTcTyVar tv1 ; ty2 <- reifyType ty1 ; return (TH.TyVarI (reifyName tv) ty2) } reifyThing thing = pprPanic "reifyThing" (pprTcTyThingCategory thing) ------------------------------------------- reifyAxBranch :: TyCon -> CoAxBranch -> TcM TH.TySynEqn reifyAxBranch fam_tc (CoAxBranch { cab_lhs = args, cab_rhs = rhs }) -- remove kind patterns (#8884) = do { args' <- mapM reifyType (filterOutInvisibleTypes fam_tc args) ; rhs' <- reifyType rhs ; return (TH.TySynEqn args' rhs') } reifyTyCon :: TyCon -> TcM TH.Info reifyTyCon tc | Just cls <- tyConClass_maybe tc = reifyClass cls | isFunTyCon tc = return (TH.PrimTyConI (reifyName tc) 2 False) | isPrimTyCon tc = return (TH.PrimTyConI (reifyName tc) (tyConArity tc) (isUnliftedTyCon tc)) | isTypeFamilyTyCon tc = do { let tvs = tyConTyVars tc res_kind = tyConResKind tc resVar = famTcResVar tc ; kind' <- reifyKind res_kind ; let (resultSig, injectivity) = case resVar of Nothing -> (TH.KindSig kind', Nothing) Just name -> let thName = reifyName name injAnnot = familyTyConInjectivityInfo tc sig = TH.TyVarSig (TH.KindedTV thName kind') inj = case injAnnot of NotInjective -> Nothing Injective ms -> Just (TH.InjectivityAnn thName injRHS) where injRHS = map (reifyName . tyVarName) (filterByList ms tvs) in (sig, inj) ; tvs' <- reifyTyVars tvs (Just tc) ; let tfHead = TH.TypeFamilyHead (reifyName tc) tvs' resultSig injectivity ; if isOpenTypeFamilyTyCon tc then do { fam_envs <- tcGetFamInstEnvs ; instances <- reifyFamilyInstances tc (familyInstances fam_envs tc) ; return (TH.FamilyI (TH.OpenTypeFamilyD tfHead) instances) } else do { eqns <- case isClosedSynFamilyTyConWithAxiom_maybe tc of Just ax -> mapM (reifyAxBranch tc) $ fromBranches $ coAxiomBranches ax Nothing -> return [] ; return (TH.FamilyI (TH.ClosedTypeFamilyD tfHead eqns) []) } } | isDataFamilyTyCon tc = do { let tvs = tyConTyVars tc res_kind = tyConResKind tc ; kind' <- fmap Just (reifyKind res_kind) ; tvs' <- reifyTyVars tvs (Just tc) ; fam_envs <- tcGetFamInstEnvs ; instances <- reifyFamilyInstances tc (familyInstances fam_envs tc) ; return (TH.FamilyI (TH.DataFamilyD (reifyName tc) tvs' kind') instances) } | Just (tvs, rhs) <- synTyConDefn_maybe tc -- Vanilla type synonym = do { rhs' <- reifyType rhs ; tvs' <- reifyTyVars tvs (Just tc) ; return (TH.TyConI (TH.TySynD (reifyName tc) tvs' rhs')) } | otherwise = do { cxt <- reifyCxt (tyConStupidTheta tc) ; let tvs = tyConTyVars tc dataCons = tyConDataCons tc -- see Note [Reifying GADT data constructors] isGadt = any (not . null . dataConEqSpec) dataCons ; cons <- mapM (reifyDataCon isGadt (mkTyVarTys tvs)) dataCons ; r_tvs <- reifyTyVars tvs (Just tc) ; let name = reifyName tc deriv = [] -- Don't know about deriving decl | isNewTyCon tc = TH.NewtypeD cxt name r_tvs Nothing (head cons) deriv | otherwise = TH.DataD cxt name r_tvs Nothing cons deriv ; return (TH.TyConI decl) } reifyDataCon :: Bool -> [Type] -> DataCon -> TcM TH.Con -- For GADTs etc, see Note [Reifying GADT data constructors] reifyDataCon isGadtDataCon tys dc = do { let -- used for H98 data constructors (ex_tvs, theta, arg_tys) = dataConInstSig dc tys -- used for GADTs data constructors (g_univ_tvs, g_ex_tvs, g_eq_spec, g_theta, g_arg_tys, g_res_ty) = dataConFullSig dc (srcUnpks, srcStricts) = mapAndUnzip reifySourceBang (dataConSrcBangs dc) dcdBangs = zipWith TH.Bang srcUnpks srcStricts fields = dataConFieldLabels dc name = reifyName dc -- Universal tvs present in eq_spec need to be filtered out, as -- they will not appear anywhere in the type. eq_spec_tvs = mkVarSet (map eqSpecTyVar g_eq_spec) g_unsbst_univ_tvs = filterOut (`elemVarSet` eq_spec_tvs) g_univ_tvs ; r_arg_tys <- reifyTypes (if isGadtDataCon then g_arg_tys else arg_tys) ; main_con <- if | not (null fields) && not isGadtDataCon -> return $ TH.RecC name (zip3 (map reifyFieldLabel fields) dcdBangs r_arg_tys) | not (null fields) -> do { res_ty <- reifyType g_res_ty ; return $ TH.RecGadtC [name] (zip3 (map (reifyName . flSelector) fields) dcdBangs r_arg_tys) res_ty } -- We need to check not isGadtDataCon here because GADT -- constructors can be declared infix. -- See Note [Infix GADT constructors] in TcTyClsDecls. | dataConIsInfix dc && not isGadtDataCon -> ASSERT( length arg_tys == 2 ) do { let [r_a1, r_a2] = r_arg_tys [s1, s2] = dcdBangs ; return $ TH.InfixC (s1,r_a1) name (s2,r_a2) } | isGadtDataCon -> do { res_ty <- reifyType g_res_ty ; return $ TH.GadtC [name] (dcdBangs `zip` r_arg_tys) res_ty } | otherwise -> return $ TH.NormalC name (dcdBangs `zip` r_arg_tys) ; let (ex_tvs', theta') | isGadtDataCon = ( g_unsbst_univ_tvs ++ g_ex_tvs , g_theta ) | otherwise = ( ex_tvs, theta ) ret_con | null ex_tvs' && null theta' = return main_con | otherwise = do { cxt <- reifyCxt theta' ; ex_tvs'' <- reifyTyVars ex_tvs' Nothing ; return (TH.ForallC ex_tvs'' cxt main_con) } ; ASSERT( length arg_tys == length dcdBangs ) ret_con } -- Note [Reifying GADT data constructors] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- At this point in the compilation pipeline we have no way of telling whether a -- data type was declared as a H98 data type or as a GADT. We have to rely on -- heuristics here. We look at dcEqSpec field of all data constructors in a -- data type declaration. If at least one data constructor has non-empty -- dcEqSpec this means that the data type must have been declared as a GADT. -- Consider these declarations: -- -- data T a where -- MkT :: forall a. (a ~ Int) => T a -- -- data T a where -- MkT :: T Int -- -- First declaration will be reified as a GADT. Second declaration will be -- reified as a normal H98 data type declaration. ------------------------------ reifyClass :: Class -> TcM TH.Info reifyClass cls = do { cxt <- reifyCxt theta ; inst_envs <- tcGetInstEnvs ; insts <- reifyClassInstances cls (InstEnv.classInstances inst_envs cls) ; assocTys <- concatMapM reifyAT ats ; ops <- concatMapM reify_op op_stuff ; tvs' <- reifyTyVars tvs (Just $ classTyCon cls) ; let dec = TH.ClassD cxt (reifyName cls) tvs' fds' (assocTys ++ ops) ; return (TH.ClassI dec insts) } where (tvs, fds, theta, _, ats, op_stuff) = classExtraBigSig cls fds' = map reifyFunDep fds reify_op (op, def_meth) = do { ty <- reifyType (idType op) ; let nm' = reifyName op ; case def_meth of Just (_, GenericDM gdm_ty) -> do { gdm_ty' <- reifyType gdm_ty ; return [TH.SigD nm' ty, TH.DefaultSigD nm' gdm_ty'] } _ -> return [TH.SigD nm' ty] } reifyAT :: ClassATItem -> TcM [TH.Dec] reifyAT (ATI tycon def) = do tycon' <- reifyTyCon tycon case tycon' of TH.FamilyI dec _ -> do let (tyName, tyArgs) = tfNames dec (dec :) <$> maybe (return []) (fmap (:[]) . reifyDefImpl tyName tyArgs . fst) def _ -> pprPanic "reifyAT" (text (show tycon')) reifyDefImpl :: TH.Name -> [TH.Name] -> Type -> TcM TH.Dec reifyDefImpl n args ty = TH.TySynInstD n . TH.TySynEqn (map TH.VarT args) <$> reifyType ty tfNames :: TH.Dec -> (TH.Name, [TH.Name]) tfNames (TH.OpenTypeFamilyD (TH.TypeFamilyHead n args _ _)) = (n, map bndrName args) tfNames d = pprPanic "tfNames" (text (show d)) bndrName :: TH.TyVarBndr -> TH.Name bndrName (TH.PlainTV n) = n bndrName (TH.KindedTV n _) = n ------------------------------ -- | Annotate (with TH.SigT) a type if the first parameter is True -- and if the type contains a free variable. -- This is used to annotate type patterns for poly-kinded tyvars in -- reifying class and type instances. See #8953 and th/T8953. annotThType :: Bool -- True <=> annotate -> TyCoRep.Type -> TH.Type -> TcM TH.Type -- tiny optimization: if the type is annotated, don't annotate again. annotThType _ _ th_ty@(TH.SigT {}) = return th_ty annotThType True ty th_ty | not $ isEmptyVarSet $ filterVarSet isTyVar $ tyCoVarsOfType ty = do { let ki = typeKind ty ; th_ki <- reifyKind ki ; return (TH.SigT th_ty th_ki) } annotThType _ _ th_ty = return th_ty -- | For every type variable in the input, -- report whether or not the tv is poly-kinded. This is used to eventually -- feed into 'annotThType'. mkIsPolyTvs :: [TyVar] -> [Bool] mkIsPolyTvs = map is_poly_tv where is_poly_tv tv = not $ isEmptyVarSet $ filterVarSet isTyVar $ tyCoVarsOfType $ tyVarKind tv ------------------------------ reifyClassInstances :: Class -> [ClsInst] -> TcM [TH.Dec] reifyClassInstances cls insts = mapM (reifyClassInstance (mkIsPolyTvs tvs)) insts where tvs = filterOutInvisibleTyVars (classTyCon cls) (classTyVars cls) reifyClassInstance :: [Bool] -- True <=> the corresponding tv is poly-kinded -- includes only *visible* tvs -> ClsInst -> TcM TH.Dec reifyClassInstance is_poly_tvs i = do { cxt <- reifyCxt theta ; let vis_types = filterOutInvisibleTypes cls_tc types ; thtypes <- reifyTypes vis_types ; annot_thtypes <- zipWith3M annotThType is_poly_tvs vis_types thtypes ; let head_ty = mkThAppTs (TH.ConT (reifyName cls)) annot_thtypes ; return $ (TH.InstanceD over cxt head_ty []) } where (_tvs, theta, cls, types) = tcSplitDFunTy (idType dfun) cls_tc = classTyCon cls dfun = instanceDFunId i over = case overlapMode (is_flag i) of NoOverlap _ -> Nothing Overlappable _ -> Just TH.Overlappable Overlapping _ -> Just TH.Overlapping Overlaps _ -> Just TH.Overlaps Incoherent _ -> Just TH.Incoherent ------------------------------ reifyFamilyInstances :: TyCon -> [FamInst] -> TcM [TH.Dec] reifyFamilyInstances fam_tc fam_insts = mapM (reifyFamilyInstance (mkIsPolyTvs fam_tvs)) fam_insts where fam_tvs = filterOutInvisibleTyVars fam_tc (tyConTyVars fam_tc) reifyFamilyInstance :: [Bool] -- True <=> the corresponding tv is poly-kinded -- includes only *visible* tvs -> FamInst -> TcM TH.Dec reifyFamilyInstance is_poly_tvs inst@(FamInst { fi_flavor = flavor , fi_fam = fam , fi_tys = lhs , fi_rhs = rhs }) = case flavor of SynFamilyInst -> -- remove kind patterns (#8884) do { let lhs_types_only = filterOutInvisibleTypes fam_tc lhs ; th_lhs <- reifyTypes lhs_types_only ; annot_th_lhs <- zipWith3M annotThType is_poly_tvs lhs_types_only th_lhs ; th_rhs <- reifyType rhs ; return (TH.TySynInstD (reifyName fam) (TH.TySynEqn annot_th_lhs th_rhs)) } DataFamilyInst rep_tc -> do { let tvs = tyConTyVars rep_tc fam' = reifyName fam -- eta-expand lhs types, because sometimes data/newtype -- instances are eta-reduced; See Trac #9692 -- See Note [Eta reduction for data family axioms] -- in TcInstDcls (_rep_tc, rep_tc_args) = splitTyConApp rhs etad_tyvars = dropList rep_tc_args tvs eta_expanded_lhs = lhs `chkAppend` mkTyVarTys etad_tyvars dataCons = tyConDataCons rep_tc -- see Note [Reifying GADT data constructors] isGadt = any (not . null . dataConEqSpec) dataCons ; cons <- mapM (reifyDataCon isGadt (mkTyVarTys tvs)) dataCons ; let types_only = filterOutInvisibleTypes fam_tc eta_expanded_lhs ; th_tys <- reifyTypes types_only ; annot_th_tys <- zipWith3M annotThType is_poly_tvs types_only th_tys ; return $ if isNewTyCon rep_tc then TH.NewtypeInstD [] fam' annot_th_tys Nothing (head cons) [] else TH.DataInstD [] fam' annot_th_tys Nothing cons [] } where fam_tc = famInstTyCon inst ------------------------------ reifyType :: TyCoRep.Type -> TcM TH.Type -- Monadic only because of failure reifyType ty@(ForAllTy (Named _ _) _) = reify_for_all ty reifyType (LitTy t) = do { r <- reifyTyLit t; return (TH.LitT r) } reifyType (TyVarTy tv) = return (TH.VarT (reifyName tv)) reifyType (TyConApp tc tys) = reify_tc_app tc tys -- Do not expand type synonyms here reifyType (AppTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) } reifyType ty@(ForAllTy (Anon t1) t2) | isPredTy t1 = reify_for_all ty -- Types like ((?x::Int) => Char -> Char) | otherwise = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) } reifyType ty@(CastTy {}) = noTH (sLit "kind casts") (ppr ty) reifyType ty@(CoercionTy {})= noTH (sLit "coercions in types") (ppr ty) reify_for_all :: TyCoRep.Type -> TcM TH.Type reify_for_all ty = do { cxt' <- reifyCxt cxt; ; tau' <- reifyType tau ; tvs' <- reifyTyVars tvs Nothing ; return (TH.ForallT tvs' cxt' tau') } where (tvs, cxt, tau) = tcSplitSigmaTy ty reifyTyLit :: TyCoRep.TyLit -> TcM TH.TyLit reifyTyLit (NumTyLit n) = return (TH.NumTyLit n) reifyTyLit (StrTyLit s) = return (TH.StrTyLit (unpackFS s)) reifyTypes :: [Type] -> TcM [TH.Type] reifyTypes = mapM reifyType reifyPatSynType :: ([TyVar], ThetaType, [TyVar], ThetaType, [Type], Type) -> TcM TH.Type -- reifies a pattern synonym's type and returns its *complete* type -- signature; see NOTE [Pattern synonym signatures and Template -- Haskell] reifyPatSynType (univTyVars, req, exTyVars, prov, argTys, resTy) = do { univTyVars' <- reifyTyVars univTyVars Nothing ; req' <- reifyCxt req ; exTyVars' <- reifyTyVars exTyVars Nothing ; prov' <- reifyCxt prov ; tau' <- reifyType (mkFunTys argTys resTy) ; return $ TH.ForallT univTyVars' req' $ TH.ForallT exTyVars' prov' tau' } reifyKind :: Kind -> TcM TH.Kind reifyKind ki = do { let (kis, ki') = splitFunTys ki ; ki'_rep <- reifyNonArrowKind ki' ; kis_rep <- mapM reifyKind kis ; return (foldr (TH.AppT . TH.AppT TH.ArrowT) ki'_rep kis_rep) } where reifyNonArrowKind k | isLiftedTypeKind k = return TH.StarT | isConstraintKind k = return TH.ConstraintT reifyNonArrowKind (TyVarTy v) = return (TH.VarT (reifyName v)) reifyNonArrowKind (ForAllTy _ k) = reifyKind k reifyNonArrowKind (TyConApp kc kis) = reify_kc_app kc kis reifyNonArrowKind (AppTy k1 k2) = do { k1' <- reifyKind k1 ; k2' <- reifyKind k2 ; return (TH.AppT k1' k2') } reifyNonArrowKind k = noTH (sLit "this kind") (ppr k) reify_kc_app :: TyCon -> [TyCoRep.Kind] -> TcM TH.Kind reify_kc_app kc kis = fmap (mkThAppTs r_kc) (mapM reifyKind vis_kis) where r_kc | isTupleTyCon kc = TH.TupleT (tyConArity kc) | kc `hasKey` listTyConKey = TH.ListT | otherwise = TH.ConT (reifyName kc) vis_kis = filterOutInvisibleTypes kc kis reifyCxt :: [PredType] -> TcM [TH.Pred] reifyCxt = mapM reifyPred reifyFunDep :: ([TyVar], [TyVar]) -> TH.FunDep reifyFunDep (xs, ys) = TH.FunDep (map reifyName xs) (map reifyName ys) reifyTyVars :: [TyVar] -> Maybe TyCon -- the tycon if the tycovars are from a tycon. -- Used to detect which tvs are implicit. -> TcM [TH.TyVarBndr] reifyTyVars tvs m_tc = mapM reify_tv tvs' where tvs' = case m_tc of Just tc -> filterOutInvisibleTyVars tc tvs Nothing -> tvs -- even if the kind is *, we need to include a kind annotation, -- in case a poly-kind would be inferred without the annotation. -- See #8953 or test th/T8953 reify_tv tv = TH.KindedTV name <$> reifyKind kind where kind = tyVarKind tv name = reifyName tv {- Note [Kind annotations on TyConApps] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A poly-kinded tycon sometimes needs a kind annotation to be unambiguous. For example: type family F a :: k type instance F Int = (Proxy :: * -> *) type instance F Bool = (Proxy :: (* -> *) -> *) It's hard to figure out where these annotations should appear, so we do this: Suppose the tycon is applied to n arguments. We strip off the first n arguments of the tycon's kind. If there are any variables left in the result kind, we put on a kind annotation. But we must be slightly careful: it's possible that the tycon's kind will have fewer than n arguments, in the case that the concrete application instantiates a result kind variable with an arrow kind. So, if we run out of arguments, we conservatively put on a kind annotation anyway. This should be a rare case, indeed. Here is an example: data T1 :: k1 -> k2 -> * data T2 :: k1 -> k2 -> * type family G (a :: k) :: k type instance G T1 = T2 type instance F Char = (G T1 Bool :: (* -> *) -> *) -- F from above Here G's kind is (forall k. k -> k), and the desugared RHS of that last instance of F is (G (* -> (* -> *) -> *) (T1 * (* -> *)) Bool). According to the algorithm above, there are 3 arguments to G so we should peel off 3 arguments in G's kind. But G's kind has only two arguments. This is the rare special case, and we conservatively choose to put the annotation in. See #8953 and test th/T8953. -} reify_tc_app :: TyCon -> [Type.Type] -> TcM TH.Type reify_tc_app tc tys = do { tys' <- reifyTypes (filterOutInvisibleTypes tc tys) ; maybe_sig_t (mkThAppTs r_tc tys') } where arity = tyConArity tc tc_binders = tyConBinders tc tc_res_kind = tyConResKind tc r_tc | isTupleTyCon tc = if isPromotedDataCon tc then TH.PromotedTupleT arity else TH.TupleT arity | tc `hasKey` listTyConKey = TH.ListT | tc `hasKey` nilDataConKey = TH.PromotedNilT | tc `hasKey` consDataConKey = TH.PromotedConsT | tc `hasKey` heqTyConKey = TH.EqualityT | tc `hasKey` eqPrimTyConKey = TH.EqualityT | tc `hasKey` eqReprPrimTyConKey = TH.ConT (reifyName coercibleTyCon) | otherwise = TH.ConT (reifyName tc) -- See Note [Kind annotations on TyConApps] maybe_sig_t th_type | needs_kind_sig = do { let full_kind = typeKind (mkTyConApp tc tys) ; th_full_kind <- reifyKind full_kind ; return (TH.SigT th_type th_full_kind) } | otherwise = return th_type needs_kind_sig | GT <- compareLength tys tc_binders , tcIsTyVarTy tc_res_kind = True | otherwise = not $ isEmptyVarSet $ filterVarSet isTyVar $ tyCoVarsOfType $ mkForAllTys (dropList tys tc_binders) tc_res_kind reifyPred :: TyCoRep.PredType -> TcM TH.Pred reifyPred ty -- We could reify the invisible paramter as a class but it seems -- nicer to support them properly... | isIPPred ty = noTH (sLit "implicit parameters") (ppr ty) | otherwise = reifyType ty ------------------------------ reifyName :: NamedThing n => n -> TH.Name reifyName thing | isExternalName name = mk_varg pkg_str mod_str occ_str | otherwise = TH.mkNameU occ_str (getKey (getUnique name)) -- Many of the things we reify have local bindings, and -- NameL's aren't supposed to appear in binding positions, so -- we use NameU. When/if we start to reify nested things, that -- have free variables, we may need to generate NameL's for them. where name = getName thing mod = ASSERT( isExternalName name ) nameModule name pkg_str = unitIdString (moduleUnitId mod) mod_str = moduleNameString (moduleName mod) occ_str = occNameString occ occ = nameOccName name mk_varg | OccName.isDataOcc occ = TH.mkNameG_d | OccName.isVarOcc occ = TH.mkNameG_v | OccName.isTcOcc occ = TH.mkNameG_tc | otherwise = pprPanic "reifyName" (ppr name) -- See Note [Reifying field labels] reifyFieldLabel :: FieldLabel -> TH.Name reifyFieldLabel fl | flIsOverloaded fl = TH.Name (TH.mkOccName occ_str) (TH.NameQ (TH.mkModName mod_str)) | otherwise = TH.mkNameG_v pkg_str mod_str occ_str where name = flSelector fl mod = ASSERT( isExternalName name ) nameModule name pkg_str = unitIdString (moduleUnitId mod) mod_str = moduleNameString (moduleName mod) occ_str = unpackFS (flLabel fl) reifySelector :: Id -> TyCon -> TH.Name reifySelector id tc = case find ((idName id ==) . flSelector) (tyConFieldLabels tc) of Just fl -> reifyFieldLabel fl Nothing -> pprPanic "reifySelector: missing field" (ppr id $$ ppr tc) ------------------------------ reifyFixity :: Name -> TcM (Maybe TH.Fixity) reifyFixity name = do { (found, fix) <- lookupFixityRn_help name ; return (if found then Just (conv_fix fix) else Nothing) } where conv_fix (BasicTypes.Fixity _ i d) = TH.Fixity i (conv_dir d) conv_dir BasicTypes.InfixR = TH.InfixR conv_dir BasicTypes.InfixL = TH.InfixL conv_dir BasicTypes.InfixN = TH.InfixN reifyUnpackedness :: DataCon.SrcUnpackedness -> TH.SourceUnpackedness reifyUnpackedness NoSrcUnpack = TH.NoSourceUnpackedness reifyUnpackedness SrcNoUnpack = TH.SourceNoUnpack reifyUnpackedness SrcUnpack = TH.SourceUnpack reifyStrictness :: DataCon.SrcStrictness -> TH.SourceStrictness reifyStrictness NoSrcStrict = TH.NoSourceStrictness reifyStrictness SrcStrict = TH.SourceStrict reifyStrictness SrcLazy = TH.SourceLazy reifySourceBang :: DataCon.HsSrcBang -> (TH.SourceUnpackedness, TH.SourceStrictness) reifySourceBang (HsSrcBang _ u s) = (reifyUnpackedness u, reifyStrictness s) reifyDecidedStrictness :: DataCon.HsImplBang -> TH.DecidedStrictness reifyDecidedStrictness HsLazy = TH.DecidedLazy reifyDecidedStrictness HsStrict = TH.DecidedStrict reifyDecidedStrictness HsUnpack{} = TH.DecidedUnpack ------------------------------ lookupThAnnLookup :: TH.AnnLookup -> TcM CoreAnnTarget lookupThAnnLookup (TH.AnnLookupName th_nm) = fmap NamedTarget (lookupThName th_nm) lookupThAnnLookup (TH.AnnLookupModule (TH.Module pn mn)) = return $ ModuleTarget $ mkModule (stringToUnitId $ TH.pkgString pn) (mkModuleName $ TH.modString mn) reifyAnnotations :: Data a => TH.AnnLookup -> TcM [a] reifyAnnotations th_name = do { name <- lookupThAnnLookup th_name ; topEnv <- getTopEnv ; epsHptAnns <- liftIO $ prepareAnnotations topEnv Nothing ; tcg <- getGblEnv ; let selectedEpsHptAnns = findAnns deserializeWithData epsHptAnns name ; let selectedTcgAnns = findAnns deserializeWithData (tcg_ann_env tcg) name ; return (selectedEpsHptAnns ++ selectedTcgAnns) } ------------------------------ modToTHMod :: Module -> TH.Module modToTHMod m = TH.Module (TH.PkgName $ unitIdString $ moduleUnitId m) (TH.ModName $ moduleNameString $ moduleName m) reifyModule :: TH.Module -> TcM TH.ModuleInfo reifyModule (TH.Module (TH.PkgName pkgString) (TH.ModName mString)) = do this_mod <- getModule let reifMod = mkModule (stringToUnitId pkgString) (mkModuleName mString) if (reifMod == this_mod) then reifyThisModule else reifyFromIface reifMod where reifyThisModule = do usages <- fmap (map modToTHMod . moduleEnvKeys . imp_mods) getImports return $ TH.ModuleInfo usages reifyFromIface reifMod = do iface <- loadInterfaceForModule (text "reifying module from TH for" <+> ppr reifMod) reifMod let usages = [modToTHMod m | usage <- mi_usages iface, Just m <- [usageToModule (moduleUnitId reifMod) usage] ] return $ TH.ModuleInfo usages usageToModule :: UnitId -> Usage -> Maybe Module usageToModule _ (UsageFile {}) = Nothing usageToModule this_pkg (UsageHomeModule { usg_mod_name = mn }) = Just $ mkModule this_pkg mn usageToModule _ (UsagePackageModule { usg_mod = m }) = Just m ------------------------------ mkThAppTs :: TH.Type -> [TH.Type] -> TH.Type mkThAppTs fun_ty arg_tys = foldl TH.AppT fun_ty arg_tys noTH :: LitString -> SDoc -> TcM a noTH s d = failWithTc (hsep [text "Can't represent" <+> ptext s <+> text "in Template Haskell:", nest 2 d]) ppr_th :: TH.Ppr a => a -> SDoc ppr_th x = text (TH.pprint x) {- Note [Reifying field labels] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When reifying a datatype declared with DuplicateRecordFields enabled, we want the reified names of the fields to be labels rather than selector functions. That is, we want (reify ''T) and (reify 'foo) to produce data T = MkT { foo :: Int } foo :: T -> Int rather than data T = MkT { $sel:foo:MkT :: Int } $sel:foo:MkT :: T -> Int because otherwise TH code that uses the field names as strings will silently do the wrong thing. Thus we use the field label (e.g. foo) as the OccName, rather than the selector (e.g. $sel:foo:MkT). Since the Orig name M.foo isn't in the environment, NameG can't be used to represent such fields. Instead, reifyFieldLabel uses NameQ. However, this means that extracting the field name from the output of reify, and trying to reify it again, may fail with an ambiguity error if there are multiple such fields defined in the module (see the test case overloadedrecflds/should_fail/T11103.hs). The "proper" fix requires changes to the TH AST to make it able to represent duplicate record fields. -} #endif /* GHCI */
vikraman/ghc
compiler/typecheck/TcSplice.hs
bsd-3-clause
77,999
0
16
23,592
1,395
789
606
85
4
module HLint.Default where import Control.Arrow import Control.Exception import Control.Monad import Control.Monad.Trans.State import qualified Data.Foldable import Data.Foldable(asum, sequenceA_, traverse_, for_) import Data.Traversable(traverse, for) import Control.Applicative import Data.Function import Data.Int import Data.Char import Data.List as Data.List import Data.List as X import Data.Maybe import Data.Monoid import System.IO import Control.Concurrent.Chan import System.Mem.Weak import Control.Exception.Base import System.Exit import Data.Either import Numeric import IO as System.IO import List as Data.List import Maybe as Data.Maybe import Monad as Control.Monad import Char as Data.Char -- I/O error = putStrLn (show x) ==> print x error = mapM_ putChar ==> putStr error = hGetChar stdin ==> getChar error = hGetLine stdin ==> getLine error = hGetContents stdin ==> getContents error = hPutChar stdout ==> putChar error = hPutStr stdout ==> putStr error = hPutStrLn stdout ==> putStrLn error = hPrint stdout ==> print error = hWaitForInput a 0 ==> hReady a error = hPutStrLn a (show b) ==> hPrint a b error = hIsEOF stdin ==> isEOF -- EXIT error = exitWith ExitSuccess ==> exitSuccess -- ORD error = not (a == b) ==> a /= b where note = "incorrect if either value is NaN" error = not (a /= b) ==> a == b where note = "incorrect if either value is NaN" error = not (a > b) ==> a <= b where note = "incorrect if either value is NaN" error = not (a >= b) ==> a < b where note = "incorrect if either value is NaN" error = not (a < b) ==> a >= b where note = "incorrect if either value is NaN" error = not (a <= b) ==> a > b where note = "incorrect if either value is NaN" error = compare x y /= GT ==> x <= y error = compare x y == LT ==> x < y error = compare x y /= LT ==> x >= y error = compare x y == GT ==> x > y --warning = x == a || x == b || x == c ==> x `elem` [a,b,c] where note = ValidInstance "Eq" x --warning = x /= a && x /= b && x /= c ==> x `notElem` [a,b,c] where note = ValidInstance "Eq" x --error = compare (f x) (f y) ==> Data.Ord.comparing f x y -- not that great --error = on compare f ==> Data.Ord.comparing f -- not that great error = head (sort x) ==> minimum x error = last (sort x) ==> maximum x error = head (sortBy f x) ==> minimumBy f x where _ = isCompare f error = last (sortBy f x) ==> maximumBy f x where _ = isCompare f error "Avoid reverse" = reverse (sort x) ==> sortBy (flip compare) x error "Avoid reverse" = reverse (sortBy f x) ==> sortBy (flip f) x where _ = isCompare f warn = flip (g `on` h) ==> flip g `on` h warn = (f `on` g) `on` h ==> f `on` (g . h) -- READ/SHOW error = showsPrec 0 x "" ==> show x error = readsPrec 0 ==> reads error = showsPrec 0 ==> shows warn = showIntAtBase 16 intToDigit ==> showHex warn = showIntAtBase 8 intToDigit ==> showOct -- LIST error = concat (map f x) ==> concatMap f x warn = concat [a, b] ==> a ++ b warn "Use map once" = map f (map g x) ==> map (f . g) x warn = x !! 0 ==> head x error = take n (repeat x) ==> replicate n x where _ = noQuickCheck -- takes too long error = map f (replicate n x) ==> replicate n (f x) where _ = noQuickCheck -- takes too long error = map f (repeat x) ==> repeat (f x) where _ = noQuickCheck -- takes forever error = cycle [x] ==> repeat x where _ = noQuickCheck -- takes forever error = head (reverse x) ==> last x error = head (drop n x) ==> x !! n where _ = isNat n error = reverse (tail (reverse x)) ==> init x where note = IncreasesLaziness error "Avoid reverse" = reverse (reverse x) ==> x where note = IncreasesLaziness -- error = take (length x - 1) x ==> init x -- not true for x == [] error = isPrefixOf (reverse x) (reverse y) ==> isSuffixOf x y error = foldr (++) [] ==> concat error = foldl (++) [] ==> concat where note = IncreasesLaziness error = foldl f (head x) (tail x) ==> foldl1 f x error = foldr f (last x) (init x) ==> foldr1 f x error = span (not . p) ==> break p error = break (not . p) ==> span p error = (takeWhile p x, dropWhile p x) ==> span p x error = fst (span p x) ==> takeWhile p x error = snd (span p x) ==> dropWhile p x error = fst (break p x) ==> takeWhile (not . p) x error = snd (break p x) ==> dropWhile (not . p) x error = concatMap (++ "\n") ==> unlines error = map id ==> id error = or (map p x) ==> any p x error = and (map p x) ==> all p x error = zipWith (,) ==> zip error = zipWith3 (,,) ==> zip3 warn = length x == 0 ==> null x where note = IncreasesLaziness warn = x == [] ==> null x warn "Use null" = length x /= 0 ==> not (null x) where note = IncreasesLaziness warn "Use :" = (\x -> [x]) ==> (:[]) error = map (uncurry f) (zip x y) ==> zipWith f x y warn = map f (zip x y) ==> zipWith (curry f) x y where _ = isVar f error = not (elem x y) ==> notElem x y warn = foldr f z (map g x) ==> foldr (f . g) z x error = x ++ concatMap (' ':) y ==> unwords (x:y) error = intercalate " " ==> unwords warn = concat (intersperse x y) ==> intercalate x y where _ = notEq x " " warn = concat (intersperse " " x) ==> unwords x error "Use any" = null (filter f x) ==> not (any f x) error "Use any" = filter f x == [] ==> not (any f x) error = filter f x /= [] ==> any f x error = any id ==> or error = all id ==> and error = any ((==) a) ==> elem a where note = ValidInstance "Eq" a error = any (== a) ==> elem a error = any (a ==) ==> elem a where note = ValidInstance "Eq" a error = all ((/=) a) ==> notElem a where note = ValidInstance "Eq" a error = all (/= a) ==> notElem a where note = ValidInstance "Eq" a error = all (a /=) ==> notElem a where note = ValidInstance "Eq" a error = elem True ==> or error = notElem False ==> and error = findIndex ((==) a) ==> elemIndex a error = findIndex (a ==) ==> elemIndex a error = findIndex (== a) ==> elemIndex a error = findIndices ((==) a) ==> elemIndices a error = findIndices (a ==) ==> elemIndices a error = findIndices (== a) ==> elemIndices a error = lookup b (zip l [0..]) ==> elemIndex b l warn "Length always non-negative" = length x >= 0 ==> True warn "Use null" = length x > 0 ==> not (null x) where note = IncreasesLaziness warn "Use null" = length x >= 1 ==> not (null x) where note = IncreasesLaziness error "Take on a non-positive" = take i x ==> [] where _ = isNegZero i error "Drop on a non-positive" = drop i x ==> x where _ = isNegZero i error = last (scanl f z x) ==> foldl f z x error = head (scanr f z x) ==> foldr f z x error = iterate id ==> repeat where _ = noQuickCheck -- takes forever error = zipWith f (repeat x) ==> map (f x) error = zipWith f x (repeat y) ==> map (\x -> f x y) x -- BY error = deleteBy (==) ==> delete error = groupBy (==) ==> group error = insertBy compare ==> insert error = intersectBy (==) ==> intersect error = maximumBy compare ==> maximum error = minimumBy compare ==> minimum error = nubBy (==) ==> nub error = sortBy compare ==> sort error = unionBy (==) ==> union -- FOLDS error = foldr (>>) (return ()) ==> sequence_ where _ = noQuickCheck error = foldr (&&) True ==> and error = foldl (&&) True ==> and where note = IncreasesLaziness error = foldr1 (&&) ==> and where note = RemovesError "on []" error = foldl1 (&&) ==> and where note = RemovesError "on []" error = foldr (||) False ==> or error = foldl (||) False ==> or where note = IncreasesLaziness error = foldr1 (||) ==> or where note = RemovesError "on []" error = foldl1 (||) ==> or where note = RemovesError "on []" error = foldl (+) 0 ==> sum error = foldr (+) 0 ==> sum error = foldl1 (+) ==> sum where note = RemovesError "on []" error = foldr1 (+) ==> sum where note = RemovesError "on []" error = foldl (*) 1 ==> product error = foldr (*) 1 ==> product error = foldl1 (*) ==> product where note = RemovesError "on []" error = foldr1 (*) ==> product where note = RemovesError "on []" error = foldl1 max ==> maximum error = foldr1 max ==> maximum error = foldl1 min ==> minimum error = foldr1 min ==> minimum error = foldr mplus mzero ==> msum where _ = noQuickCheck -- FUNCTION error = (\x -> x) ==> id error = (\x y -> x) ==> const error = (\(x,y) -> y) ==> snd error = (\(x,y) -> x) ==> fst warn "Use curry" = (\x y -> f (x,y)) ==> curry f warn "Use uncurry" = (\(x,y) -> f x y) ==> uncurry f where note = IncreasesLaziness error "Redundant $" = (($) . f) ==> f error "Redundant $" = (f $) ==> f warn = (\x -> y) ==> const y where _ = isAtom y error "Redundant flip" = flip f x y ==> f y x where _ = isApp original warn = (\a b -> g (f a) (f b)) ==> g `Data.Function.on` f error "Evaluate" = id x ==> x error "Redundant id" = id . x ==> x error "Redundant id" = x . id ==> x -- CHAR error = a >= 'a' && a <= 'z' ==> isAsciiLower a error = a >= 'A' && a <= 'Z' ==> isAsciiUpper a error = a >= '0' && a <= '9' ==> isDigit a error = a >= '0' && a <= '7' ==> isOctDigit a error = isLower a || isUpper a ==> isAlpha a error = isUpper a || isLower a ==> isAlpha a -- BOOL error "Redundant ==" = x == True ==> x warn "Redundant ==" = x == False ==> not x error "Redundant ==" = True == a ==> a warn "Redundant ==" = False == a ==> not a error "Redundant /=" = a /= True ==> not a warn "Redundant /=" = a /= False ==> a error "Redundant /=" = True /= a ==> not a warn "Redundant /=" = False /= a ==> a error "Redundant if" = (if a then x else x) ==> x where note = IncreasesLaziness error "Redundant if" = (if a then True else False) ==> a error "Redundant if" = (if a then False else True) ==> not a error "Redundant if" = (if a then t else (if b then t else f)) ==> if a || b then t else f error "Redundant if" = (if a then (if b then t else f) else f) ==> if a && b then t else f error "Redundant if" = (if x then True else y) ==> x || y where _ = notEq y False error "Redundant if" = (if x then y else False) ==> x && y where _ = notEq y True warn "Use if" = case a of {True -> t; False -> f} ==> if a then t else f warn "Use if" = case a of {False -> f; True -> t} ==> if a then t else f warn "Use if" = case a of {True -> t; _ -> f} ==> if a then t else f warn "Use if" = case a of {False -> f; _ -> t} ==> if a then t else f warn "Redundant if" = (if c then (True, x) else (False, x)) ==> (c, x) where note = IncreasesLaziness warn "Redundant if" = (if c then (False, x) else (True, x)) ==> (not c, x) where note = IncreasesLaziness warn = or [x, y] ==> x || y warn = or [x, y, z] ==> x || y || z warn = and [x, y] ==> x && y warn = and [x, y, z] ==> x && y && z error "Redundant if" = (if x then False else y) ==> not x && y where _ = notEq y True error "Redundant if" = (if x then y else True) ==> not x || y where _ = notEq y False error "Redundant not" = not (not x) ==> x -- error "Too strict if" = (if c then f x else f y) ==> f (if c then x else y) where note = IncreasesLaziness -- also breaks types, see #87 -- ARROW error = id *** g ==> second g error = f *** id ==> first f error = zip (map f x) (map g x) ==> map (f Control.Arrow.&&& g) x warn = (\(x,y) -> (f x, g y)) ==> f Control.Arrow.*** g warn = (\x -> (f x, g x)) ==> f Control.Arrow.&&& g warn = (\(x,y) -> (f x,y)) ==> Control.Arrow.first f warn = (\(x,y) -> (x,f y)) ==> Control.Arrow.second f warn = (f (fst x), g (snd x)) ==> (f Control.Arrow.*** g) x warn "Redundant pair" = (fst x, snd x) ==> x where note = DecreasesLaziness -- FUNCTOR error "Functor law" = fmap f (fmap g x) ==> fmap (f . g) x where _ = noQuickCheck error "Functor law" = fmap id ==> id where _ = noQuickCheck warn = fmap f $ x ==> f Control.Applicative.<$> x where _ = (isApp x || isAtom x) && noQuickCheck -- MONAD error "Monad law, left identity" = return a >>= f ==> f a where _ = noQuickCheck error "Monad law, right identity" = m >>= return ==> m where _ = noQuickCheck warn = m >>= return . f ==> Control.Monad.liftM f m where _ = noQuickCheck -- cannot be fmap, because is in Functor not Monad error = (if x then y else return ()) ==> Control.Monad.when x $ _noParen_ y where _ = not (isAtom y) && noQuickCheck error = (if x then y else return ()) ==> Control.Monad.when x y where _ = isAtom y && noQuickCheck error = (if x then return () else y) ==> Control.Monad.unless x $ _noParen_ y where _ = not (isAtom y) && noQuickCheck error = (if x then return () else y) ==> Control.Monad.unless x y where _ = isAtom y && noQuickCheck error = sequence (map f x) ==> mapM f x where _ = noQuickCheck error = sequence_ (map f x) ==> mapM_ f x where _ = noQuickCheck warn = flip mapM ==> Control.Monad.forM where _ = noQuickCheck warn = flip mapM_ ==> Control.Monad.forM_ where _ = noQuickCheck warn = flip forM ==> mapM where _ = noQuickCheck warn = flip forM_ ==> mapM_ where _ = noQuickCheck error = when (not x) ==> unless x where _ = noQuickCheck error = x >>= id ==> Control.Monad.join x where _ = noQuickCheck error = liftM f (liftM g x) ==> liftM (f . g) x where _ = noQuickCheck error = fmap f (fmap g x) ==> fmap (f . g) x where _ = noQuickCheck warn = a >> return () ==> Control.Monad.void a where _ = (isAtom a || isApp a) && noQuickCheck error = fmap (const ()) ==> Control.Monad.void where _ = noQuickCheck error = flip (>=>) ==> (<=<) where _ = noQuickCheck error = flip (<=<) ==> (>=>) where _ = noQuickCheck error = flip (>>=) ==> (=<<) where _ = noQuickCheck error = flip (=<<) ==> (>>=) where _ = noQuickCheck warn = (\x -> f x >>= g) ==> f Control.Monad.>=> g where _ = noQuickCheck warn = (\x -> f =<< g x) ==> f Control.Monad.<=< g where _ = noQuickCheck error = a >> forever a ==> forever a where _ = noQuickCheck warn = liftM2 id ==> ap where _ = noQuickCheck error = mapM (uncurry f) (zip l m) ==> zipWithM f l m where _ = noQuickCheck -- STATE MONAD error = fst (runState x y) ==> evalState x y where _ = noQuickCheck error = snd (runState x y) ==> execState x y where _ = noQuickCheck -- MONAD LIST error = liftM unzip (mapM f x) ==> Control.Monad.mapAndUnzipM f x where _ = noQuickCheck error = sequence (zipWith f x y) ==> Control.Monad.zipWithM f x y where _ = noQuickCheck error = sequence_ (zipWith f x y) ==> Control.Monad.zipWithM_ f x y where _ = noQuickCheck error = sequence (replicate n x) ==> Control.Monad.replicateM n x where _ = noQuickCheck error = sequence_ (replicate n x) ==> Control.Monad.replicateM_ n x where _ = noQuickCheck error = mapM f (replicate n x) ==> Control.Monad.replicateM n (f x) where _ = noQuickCheck error = mapM_ f (replicate n x) ==> Control.Monad.replicateM_ n (f x) where _ = noQuickCheck error = mapM f (map g x) ==> mapM (f . g) x where _ = noQuickCheck error = mapM_ f (map g x) ==> mapM_ (f . g) x where _ = noQuickCheck error = mapM id ==> sequence where _ = noQuickCheck error = mapM_ id ==> sequence_ where _ = noQuickCheck -- APPLICATIVE / TRAVERSABLE error = flip traverse ==> for where _ = noQuickCheck error = flip for ==> traverse where _ = noQuickCheck error = flip traverse_ ==> for_ where _ = noQuickCheck error = flip for_ ==> traverse_ where _ = noQuickCheck error = foldr (*>) (pure ()) ==> sequenceA_ where _ = noQuickCheck error = foldr (<|>) empty ==> asum where _ = noQuickCheck error = liftA2 (flip ($)) ==> (<**>) where _ = noQuickCheck error = Just <$> a <|> pure Nothing ==> optional a where _ = noQuickCheck -- LIST COMP warn "Use list comprehension" = (if b then [x] else []) ==> [x | b] warn "Redundant list comprehension" = [x | x <- y] ==> y where _ = isVar x -- SEQ error "Redundant seq" = x `seq` x ==> x error "Redundant $!" = id $! x ==> x error "Redundant seq" = x `seq` y ==> y where _ = isWHNF x error "Redundant $!" = f $! x ==> f x where _ = isWHNF x error "Redundant evaluate" = evaluate x ==> return x where _ = isWHNF x -- MAYBE error = maybe x id ==> Data.Maybe.fromMaybe x error = maybe False (const True) ==> Data.Maybe.isJust error = maybe True (const False) ==> Data.Maybe.isNothing error = not (isNothing x) ==> isJust x error = not (isJust x) ==> isNothing x error = maybe [] (:[]) ==> maybeToList error = catMaybes (map f x) ==> mapMaybe f x warn = (case x of Nothing -> y; Just a -> a) ==> fromMaybe y x error = (if isNothing x then y else f (fromJust x)) ==> maybe y f x error = (if isJust x then f (fromJust x) else y) ==> maybe y f x error = maybe Nothing (Just . f) ==> fmap f warn = map fromJust . filter isJust ==> Data.Maybe.catMaybes error = x == Nothing ==> isNothing x error = Nothing == x ==> isNothing x error = x /= Nothing ==> Data.Maybe.isJust x error = Nothing /= x ==> Data.Maybe.isJust x error = concatMap (maybeToList . f) ==> Data.Maybe.mapMaybe f error = concatMap maybeToList ==> catMaybes error = maybe n Just x ==> Control.Monad.mplus x n warn = (case x of Just a -> a; Nothing -> y) ==> fromMaybe y x error = (if isNothing x then y else fromJust x) ==> fromMaybe y x error = (if isJust x then fromJust x else y) ==> fromMaybe y x error = isJust x && (fromJust x == y) ==> x == Just y error = mapMaybe f (map g x) ==> mapMaybe (f . g) x error = fromMaybe a (fmap f x) ==> maybe a f x error = mapMaybe id ==> catMaybes warn = [x | Just x <- a] ==> Data.Maybe.catMaybes a warn = (case m of Nothing -> Nothing; Just x -> x) ==> Control.Monad.join m warn = maybe Nothing id ==> join warn "Too strict maybe" = maybe (f x) (f . g) ==> f . maybe x g where note = IncreasesLaziness -- EITHER error = [a | Left a <- a] ==> lefts a error = [a | Right a <- a] ==> rights a error = either Left (Right . f) ==> fmap f -- INFIX warn "Use infix" = elem x y ==> x `elem` y where _ = not (isInfixApp original) && not (isParen result) warn "Use infix" = notElem x y ==> x `notElem` y where _ = not (isInfixApp original) && not (isParen result) warn "Use infix" = isInfixOf x y ==> x `isInfixOf` y where _ = not (isInfixApp original) && not (isParen result) warn "Use infix" = isSuffixOf x y ==> x `isSuffixOf` y where _ = not (isInfixApp original) && not (isParen result) warn "Use infix" = isPrefixOf x y ==> x `isPrefixOf` y where _ = not (isInfixApp original) && not (isParen result) warn "Use infix" = union x y ==> x `union` y where _ = not (isInfixApp original) && not (isParen result) warn "Use infix" = intersect x y ==> x `intersect` y where _ = not (isInfixApp original) && not (isParen result) -- MATHS error "Redundant fromIntegral" = fromIntegral x ==> x where _ = isLitInt x error "Redundant fromInteger" = fromInteger x ==> x where _ = isLitInt x warn = x + negate y ==> x - y warn = 0 - x ==> negate x error "Redundant negate" = negate (negate x) ==> x warn = log y / log x ==> logBase x y warn = sin x / cos x ==> tan x warn = n `rem` 2 == 0 ==> even n warn = n `rem` 2 /= 0 ==> odd n warn = not (even x) ==> odd x warn = not (odd x) ==> even x warn = x ** 0.5 ==> sqrt x warn "Use 1" = x ^ 0 ==> 1 warn = round (x - 0.5) ==> floor x -- CONCURRENT warn = mapM_ (writeChan a) ==> writeList2Chan a -- EXCEPTION warn = flip Control.Exception.catch ==> handle warn = flip handle ==> Control.Exception.catch warn = flip (catchJust p) ==> handleJust p warn = flip (handleJust p) ==> catchJust p warn = Control.Exception.bracket b (const a) (const t) ==> Control.Exception.bracket_ b a t warn = Control.Exception.bracket (openFile x y) hClose ==> withFile x y warn = Control.Exception.bracket (openBinaryFile x y) hClose ==> withBinaryFile x y warn = throw (ErrorCall a) ==> error a error = toException NonTermination ==> nonTermination error = toException NestedAtomically ==> nestedAtomically -- WEAK POINTERS error = mkWeak a a b ==> mkWeakPtr a b error = mkWeak a (a, b) c ==> mkWeakPair a b c -- FOLDABLE error "Use Foldable.forM_" = (case m of Nothing -> return (); Just x -> f x) ==> Data.Foldable.forM_ m f where _ = noQuickCheck error "Use Foldable.forM_" = when (isJust m) (f (fromJust m)) ==> Data.Foldable.forM_ m f where _ = noQuickCheck -- EVALUATE -- TODO: These should be moved in to HSE\Evaluate.hs and applied -- through a special evaluate hint mechanism error "Evaluate" = True && x ==> x error "Evaluate" = False && x ==> False error "Evaluate" = True || x ==> True error "Evaluate" = False || x ==> x error "Evaluate" = not True ==> False error "Evaluate" = not False ==> True error "Evaluate" = Nothing >>= k ==> Nothing error "Evaluate" = either f g (Left x) ==> f x error "Evaluate" = either f g (Right y) ==> g y error "Evaluate" = fst (x,y) ==> x error "Evaluate" = snd (x,y) ==> y error "Evaluate" = f (fst p) (snd p) ==> uncurry f p error "Evaluate" = init [x] ==> [] error "Evaluate" = null [] ==> True error "Evaluate" = length [] ==> 0 error "Evaluate" = foldl f z [] ==> z error "Evaluate" = foldr f z [] ==> z error "Evaluate" = foldr1 f [x] ==> x error "Evaluate" = scanr f z [] ==> [z] error "Evaluate" = scanr1 f [] ==> [] error "Evaluate" = scanr1 f [x] ==> [x] error "Evaluate" = take n [] ==> [] where note = IncreasesLaziness error "Evaluate" = drop n [] ==> [] where note = IncreasesLaziness error "Evaluate" = takeWhile p [] ==> [] error "Evaluate" = dropWhile p [] ==> [] error "Evaluate" = span p [] ==> ([],[]) error "Evaluate" = lines "" ==> [] error "Evaluate" = unwords [] ==> "" error "Evaluate" = x - 0 ==> x error "Evaluate" = x * 1 ==> x error "Evaluate" = x / 1 ==> x error "Evaluate" = concat [a] ==> a error "Evaluate" = concat [] ==> [] error "Evaluate" = zip [] [] ==> [] error "Evaluate" = const x y ==> x -- COMPLEX {- -- these would be a good idea, but we have not yet proven them and they seem to have side conditions error "Use isPrefixOf" = take (length t) s == t ==> t `Data.List.isPrefixOf` s error "Use isPrefixOf" = (take i s == t) ==> _eval_ ((i >= length t) && (t `Data.List.isPrefixOf` s)) where _ = (isList t || isLit t) && isPos i -} {- -- clever hint, but not actually a good idea warn = (do a <- f; g a) ==> f >>= g where _ = (isAtom f || isApp f) -} test = hints named test are to allow people to put test code within hint files testPrefix = and any prefix also works {- <TEST> yes = concat . map f -- concatMap f yes = foo . bar . concat . map f . baz . bar -- concatMap f . baz . bar yes = map f (map g x) -- map (f . g) x yes = concat.map (\x->if x==e then l' else [x]) -- concatMap (\x->if x==e then l' else [x]) yes = f x where f x = concat . map head -- concatMap head yes = concat . map f . g -- concatMap f . g yes = concat $ map f x -- concatMap f x yes = "test" ++ concatMap (' ':) ["of","this"] -- unwords ("test":["of","this"]) yes = if f a then True else b -- f a || b yes = not (a == b) -- a /= b yes = not (a /= b) -- a == b yes = if a then 1 else if b then 1 else 2 -- if a || b then 1 else 2 no = if a then 1 else if b then 3 else 2 yes = a >>= return . bob -- Control.Monad.liftM bob a yes = (x !! 0) + (x !! 2) -- head x yes = if b < 42 then [a] else [] -- [a | b < 42] no = take n (foo xs) == "hello" yes = head (reverse xs) -- last xs yes = reverse xs `isPrefixOf` reverse ys -- isSuffixOf xs ys no = putStrLn $ show (length xs) ++ "Test" yes = ftable ++ map (\ (c, x) -> (toUpper c, urlEncode x)) ftable -- toUpper Control.Arrow.*** urlEncode yes = map (\(a,b) -> a) xs -- fst yes = map (\(a,_) -> a) xs -- fst yes = readFile $ args !! 0 -- head args yes = if Debug `elem` opts then ["--debug"] else [] -- ["--debug" | Debug `elem` opts] yes = if nullPS s then return False else if headPS s /= '\n' then return False else alter_input tailPS >> return True \ -- if nullPS s || (headPS s /= '\n') then return False else alter_input tailPS >> return True yes = if foo then do stuff; moreStuff; lastOfTheStuff else return () \ -- Control.Monad.when foo $ do stuff ; moreStuff ; lastOfTheStuff yes = if foo then stuff else return () -- Control.Monad.when foo stuff yes = foo $ \(a, b) -> (a, y + b) -- Control.Arrow.second ((+) y) no = foo $ \(a, b) -> (a, a + b) yes = map (uncurry (+)) $ zip [1 .. 5] [6 .. 10] -- zipWith (+) [1 .. 5] [6 .. 10] no = do iter <- textBufferGetTextIter tb ; textBufferSelectRange tb iter iter no = flip f x $ \y -> y*y+y no = \x -> f x (g x) no = foo (\ v -> f v . g) yes = concat . intersperse " " -- unwords yes = Prelude.concat $ intersperse " " xs -- unwords xs yes = concat $ Data.List.intersperse " " xs -- unwords xs yes = if a then True else False -- a yes = if x then true else False -- x && true yes = elem x y -- x `elem` y yes = foo (elem x y) -- x `elem` y no = x `elem` y no = elem 1 [] : [] test a = foo (\x -> True) -- const True h a = flip f x (y z) -- f (y z) x h a = flip f x $ y z yes x = case x of {True -> a ; False -> b} -- if x then a else b yes x = case x of {False -> a ; _ -> b} -- if x then b else a no = const . ok . toResponse $ "saved" yes = case x z of Nothing -> y z; Just pattern -> pattern -- fromMaybe (y z) (x z) yes = if p then s else return () -- Control.Monad.when p s error = a $$$$ b $$$$ c ==> a . b $$$$$ c yes = when (not . null $ asdf) -- unless (null asdf) yes = id 1 -- 1 yes = case concat (map f x) of [] -> [] -- concatMap f x yes = [v | v <- xs] -- xs no = [Left x | Left x <- xs] when p s = if p then s else return () no = x ^^ 18.5 instance Arrow (->) where first f = f *** id yes = fromInteger 12 -- 12 import Prelude hiding (catch); no = catch import Control.Exception as E; no = E.catch main = do f; putStrLn $ show x -- print x main = map (writer,) $ map arcObj $ filter (rdfPredEq (Res dctreferences)) ts -- map ((writer,) . arcObj) (filter (rdfPredEq (Res dctreferences)) ts) h x y = return $! (x, y) -- return (x, y) h x y = return $! x getInt = do { x <- readIO "0"; return $! (x :: Int) } foo = evaluate [12] -- return [12] test = \ a -> f a >>= \ b -> return (a, b) fooer input = catMaybes . map Just $ input -- mapMaybe Just yes = mapMaybe id -- catMaybes main = print $ map (\_->5) [2,3,5] -- const 5 main = head $ drop n x main = head $ drop (-3) x -- x main = head $ drop 2 x -- x !! 2 main = drop 0 x -- x main = take 0 x -- [] main = take (-5) x -- [] main = take (-y) x main = take 4 x main = let (first, rest) = (takeWhile p l, dropWhile p l) in rest -- span p l main = map $ \ d -> ([| $d |], [| $d |]) pairs (x:xs) = map (\y -> (x,y)) xs ++ pairs xs {-# ANN foo "HLint: ignore" #-};foo = map f (map g x) -- @Ignore ??? yes = fmap lines $ abc 123 -- lines Control.Applicative.<$> abc 123 no = fmap lines $ abc $ def 123 test = foo . not . not -- id test = map (not . not) xs -- id used = not . not . any (`notElem` special) . fst . derives -- any (`notElem` special) . fst . derives test = foo . id . map -- map test = food id xs yes = baz baz >> return () -- Control.Monad.void (baz baz) no = foo >>= bar >>= something >>= elsee >> return () no = f (#) x data Pair = P {a :: !Int}; foo = return $! P{a=undefined} data Pair = P {a :: !Int}; foo = return $! P undefined foo = return $! Just undefined -- return (Just undefined) foo = return $! (a,b) -- return (a,b) foo = return $! 1 foo = return $! "test" bar = [x| (x,_) <- pts] return' x = x `seq` return x foo = last (sortBy (compare `on` fst) xs) -- maximumBy (compare `on` fst) xs g = \ f -> parseFile f >>= (\ cu -> return (f, cu)) foo = bar $ \(x,y) -> x x y foo = (\x -> f x >>= g) -- f Control.Monad.>=> g foo = (\f -> h f >>= g) -- h Control.Monad.>=> g foo = (\f -> h f >>= f) foo = bar $ \x -> [x,y] foo = bar $ \x -> [z,y] -- const [z,y] f condition tChar tBool = if condition then _monoField tChar else _monoField tBool import Prelude \ yes = flip mapM -- Control.Monad.forM import Control.Monad \ yes = flip mapM -- forM import Control.Monad(forM) \ yes = flip mapM -- forM import Control.Monad(forM_) \ yes = flip mapM -- Control.Monad.forM import qualified Control.Monad \ yes = flip mapM -- Control.Monad.forM import qualified Control.Monad as CM \ yes = flip mapM -- CM.forM import qualified Control.Monad as CM(forM,filterM) \ yes = flip mapM -- CM.forM import Control.Monad as CM(forM,filterM) \ yes = flip mapM -- forM import Control.Monad hiding (forM) \ yes = flip mapM -- Control.Monad.forM import Control.Monad hiding (filterM) \ yes = flip mapM -- forM import qualified Data.Text.Lazy as DTL \ main = DTL.concat $ map (`DTL.snoc` '-') [DTL.pack "one", DTL.pack "two", DTL.pack "three"] import Text.Blaze.Html5.Attributes as A \ main = A.id (stringValue id') </TEST> -}
fpco/hlint
data/Default.hs
bsd-3-clause
28,019
0
11
6,180
9,725
5,005
4,720
-1
-1
module Main where import Ciphers (inCaesar, unCaesar, inVig, unVig) import Test.QuickCheck genCaesar :: Gen (Int, String) genCaesar = do k <- arbitrary t <- arbitrary return (k, t) genVig :: Gen (String, String) genVig = do k <- arbitrary t <- arbitrary return (k, t) prop_Caesar :: Property prop_Caesar = forAll genCaesar (\(k, t) -> unCaesar k (inCaesar k t) == t) prop_Vig :: Property prop_Vig = forAll genVig (\(k, t) -> unVig k (inVig k t) == t) main :: IO () main = do putStrLn "\n unCaesar returns the same string\ \\nwhich was encoded by inCaesar." quickCheck prop_Caesar putStrLn "\n unVig returns the same string\ \\nwhich was encoded by inVig." quickCheck prop_Vig
dmvianna/ciphers
tests/tests.hs
bsd-3-clause
734
0
11
172
247
129
118
27
1
----------------------------------------------------------------------------- -- | -- Module : Distribution.TestSuite -- Copyright : Thomas Tuegel 2010 -- License : BSD3 -- -- Maintainer : [email protected] -- Portability : portable -- -- This module defines the detailed test suite interface which makes it -- possible to expose individual tests to Cabal or other test agents. module Distribution.TestSuite ( TestInstance(..) , OptionDescr(..) , OptionType(..) , Test(..) , Options , Progress(..) , Result(..) , testGroup ) where import Prelude () import Distribution.Compat.Prelude data TestInstance = TestInstance { run :: IO Progress -- ^ Perform the test. , name :: String -- ^ A name for the test, unique within a -- test suite. , tags :: [String] -- ^ Users can select groups of tests by -- their tags. , options :: [OptionDescr] -- ^ Descriptions of the options recognized -- by this test. , setOption :: String -> String -> Either String TestInstance -- ^ Try to set the named option to the given value. Returns an error -- message if the option is not supported or the value could not be -- correctly parsed; otherwise, a 'TestInstance' with the option set to -- the given value is returned. } data OptionDescr = OptionDescr { optionName :: String , optionDescription :: String -- ^ A human-readable description of the -- option to guide the user setting it. , optionType :: OptionType , optionDefault :: Maybe String } deriving (Eq, Read, Show) data OptionType = OptionFile { optionFileMustExist :: Bool , optionFileIsDir :: Bool , optionFileExtensions :: [String] } | OptionString { optionStringMultiline :: Bool } | OptionNumber { optionNumberIsInt :: Bool , optionNumberBounds :: (Maybe String, Maybe String) } | OptionBool | OptionEnum [String] | OptionSet [String] | OptionRngSeed deriving (Eq, Read, Show) data Test = Test TestInstance | Group { groupName :: String , concurrently :: Bool -- ^ If true, then children of this group may be run in parallel. -- Note that this setting is not inherited by children. In -- particular, consider a group F with "concurrently = False" that -- has some children, including a group T with "concurrently = -- True". The children of group T may be run concurrently with each -- other, as long as none are run at the same time as any of the -- direct children of group F. , groupTests :: [Test] } | ExtraOptions [OptionDescr] Test type Options = [(String, String)] data Progress = Finished Result | Progress String (IO Progress) data Result = Pass | Fail String | Error String deriving (Eq, Read, Show) -- | Create a named group of tests, which are assumed to be safe to run in -- parallel. testGroup :: String -> [Test] -> Test testGroup n ts = Group { groupName = n, concurrently = True, groupTests = ts }
sopvop/cabal
Cabal/Distribution/TestSuite.hs
bsd-3-clause
3,418
0
11
1,116
480
306
174
54
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Mafia.Options.Applicative ( module X , RunType (..) , SafeCommand (..) , eitherTextReader , pOption , command' , dispatch , cli , safeCommand , versionFlag , dryRunFlag , orDie , orDieWithCode ) where import Control.Monad.Trans.Either (EitherT, runEitherT) import qualified Data.Attoparsec.Text as A import Data.String (String) import qualified Data.Text as T import Options.Applicative as X import Options.Applicative.Types as X import Mafia.P import System.Exit (exitSuccess, ExitCode(..), exitWith) import System.IO (IO, putStrLn, print, hPutStrLn, stderr) data RunType = DryRun | RealRun deriving (Eq, Show) data SafeCommand a = VersionCommand | DependencyCommand | RunCommand RunType a deriving (Eq, Show) -- | Turn a parser into a ReadM eitherTextReader :: (e -> Text) -> (Text -> Either e a) -> ReadM a eitherTextReader render f = eitherReader $ first (T.unpack . render) . f . T.pack -- | Turn apn attoparsec parser into a ReadM pOption :: A.Parser a -> ReadM a pOption p = eitherReader (A.parseOnly p . T.pack) -- | A 'command' combinator that adds helper and description in a -- slightly cleaner way. command' :: String -> String -> Parser a -> Mod CommandFields a command' label description parser = command label (info (parser <**> helper) (progDesc description)) -- | Dispatch multi-mode programs with appropriate helper to make the -- default behaviour a bit better. dispatch :: Parser a -> IO a dispatch p = customExecParser (prefs showHelpOnEmpty) (info (p <**> helper) idm) -- | Simple interface over 'dispatch' and 'safeCommand' -- -- @ name -> version -> dependencyInfo -> parser -> action @ -- -- Example usage: -- -- > cli "my-cli" buildInfoVersion cabalVersion dependencyInfo myThingParser $ \c -> -- > case c of -- > DoThingA -> ... -- > DoThingB -> ... cli :: Show a => [Char] -> [Char] -> [Char] -> [[Char]] -> Parser a -> (a -> IO b) -> IO b cli name v cv deps commandParser act = do dispatch (safeCommand commandParser) >>= \a -> case a of VersionCommand -> do putStrLn (name <> ": " <> v) putStrLn ("built with cabal version: " <> cv) >> exitSuccess DependencyCommand -> mapM putStrLn deps >> exitSuccess RunCommand DryRun c -> print c >> exitSuccess RunCommand RealRun c -> act c -- | Turn a Parser for a command of type a into a safe command -- with a dry-run mode and a version flag safeCommand :: Parser a -> Parser (SafeCommand a) safeCommand commandParser = VersionCommand <$ versionFlag <|> DependencyCommand <$ dependencyFlag <|> RunCommand <$> dryRunFlag <*> commandParser versionFlag :: Parser () versionFlag = flag' () $ short 'v' <> long "version" <> help "Version information" dependencyFlag :: Parser () dependencyFlag = flag' () $ long "dependencies" <> hidden dryRunFlag :: Parser RunType dryRunFlag = flag RealRun DryRun $ long "dry-run" <> hidden -- | orDieWithCode with an exit code of 1 in case of an error -- orDie :: (e -> Text) -> EitherT e IO a -> IO a orDie = orDieWithCode 1 -- | An idiom for failing hard on EitherT errors. -- -- *This really dies*. There is no other way to say it. -- -- The reason it lives with command line parser tooling, is that is -- the only valid place to actually exit like this. Be appropriately -- wary. -- orDieWithCode :: Int -> (e -> Text) -> EitherT e IO a -> IO a orDieWithCode code render e = runEitherT e >>= either (\err -> (hPutStrLn stderr . T.unpack . render) err >> exitWith (ExitFailure code)) pure
ambiata/mafia
src/Mafia/Options/Applicative.hs
bsd-3-clause
3,767
0
17
883
953
516
437
86
4
----------------------------------------------------------------------------- -- | -- Copyright : (C) 2015 Dimitri Sabadie -- License : BSD3 -- -- Maintainer : Dimitri Sabadie <[email protected]> -- Stability : experimental -- Portability : portable ---------------------------------------------------------------------------- module Quaazar.Render.Projection ( -- * Projection Projection(..) , projectionMatrix , projectionZFar ) where import Linear -- |Projection type. -- -- @Perspective fovy ratio znear zfar@ creates a perspective projection. data Projection = Perspective Float Float Float Float deriving (Eq,Show) -- |Turn a `Projection` into a projection 4x4 matrix. projectionMatrix :: Projection -> M44 Float projectionMatrix (Perspective fovy ratio znear zfar) = perspectiveMatrix fovy ratio znear zfar -- |Perspective matrix. perspectiveMatrix :: Float -> Float -> Float -> Float -> M44 Float perspectiveMatrix = perspective projectionZFar :: Projection -> Float projectionZFar (Perspective _ _ _ zfar) = zfar
phaazon/quaazar
src/Quaazar/Render/Projection.hs
bsd-3-clause
1,094
0
9
191
165
96
69
19
1
{-# LANGUAGE OverloadedStrings #-} module Set2.Challenge09Spec ( spec ) where import Test.Hspec import Test.QuickCheck import Control.Exception (evaluate) import Challenges.Set2 as S2 main :: IO () main = hspec spec key = "YELLOW SUBMARINE" solution = "YELLOW SUBMARINE\x04\x04\x04\x04" spec :: Spec spec = do describe "Challenge 9" $ do it "pads the key" $ do S2.challenge9 20 key `shouldBe` solution
eelcoh/cryptochallenge
test/Set2/Challenge09Spec.hs
bsd-3-clause
434
0
15
91
113
62
51
18
1
{-# LANGUAGE CPP, GADTs, RankNTypes #-} ----------------------------------------------------------------------------- -- -- Cmm utilities. -- -- (c) The University of Glasgow 2004-2006 -- ----------------------------------------------------------------------------- module CmmUtils( -- CmmType primRepCmmType, slotCmmType, slotForeignHint, cmmArgType, typeCmmType, typeForeignHint, -- CmmLit zeroCLit, mkIntCLit, mkWordCLit, packHalfWordsCLit, mkByteStringCLit, mkDataLits, mkRODataLits, mkStgWordCLit, -- CmmExpr mkIntExpr, zeroExpr, mkLblExpr, cmmRegOff, cmmOffset, cmmLabelOff, cmmOffsetLit, cmmOffsetExpr, cmmRegOffB, cmmOffsetB, cmmLabelOffB, cmmOffsetLitB, cmmOffsetExprB, cmmRegOffW, cmmOffsetW, cmmLabelOffW, cmmOffsetLitW, cmmOffsetExprW, cmmIndex, cmmIndexExpr, cmmLoadIndex, cmmLoadIndexW, cmmNegate, cmmULtWord, cmmUGeWord, cmmUGtWord, cmmUShrWord, cmmSLtWord, cmmNeWord, cmmEqWord, cmmOrWord, cmmAndWord, cmmSubWord, cmmAddWord, cmmMulWord, cmmQuotWord, cmmToWord, isTrivialCmmExpr, hasNoGlobalRegs, -- Statics blankWord, -- Tagging cmmTagMask, cmmPointerMask, cmmUntag, cmmIsTagged, cmmConstrTag1, -- Overlap and usage regsOverlap, regUsedIn, -- Liveness and bitmaps mkLiveness, -- * Operations that probably don't belong here modifyGraph, ofBlockMap, toBlockMap, insertBlock, ofBlockList, toBlockList, bodyToBlockList, toBlockListEntryFirst, toBlockListEntryFirstFalseFallthrough, foldGraphBlocks, mapGraphNodes, postorderDfs, mapGraphNodes1, analFwd, analBwd, analRewFwd, analRewBwd, dataflowPassFwd, dataflowPassBwd, dataflowAnalFwd, dataflowAnalBwd, dataflowAnalFwdBlocks, -- * Ticks blockTicks ) where #include "HsVersions.h" import TyCon ( PrimRep(..), PrimElemRep(..) ) import RepType ( UnaryType, SlotTy (..), typePrimRep ) import SMRep import Cmm import BlockId import CLabel import Outputable import Unique import UniqSupply import DynFlags import Util import CodeGen.Platform import Data.Word import Data.Maybe import Data.Bits import Hoopl --------------------------------------------------- -- -- CmmTypes -- --------------------------------------------------- primRepCmmType :: DynFlags -> PrimRep -> CmmType primRepCmmType _ VoidRep = panic "primRepCmmType:VoidRep" primRepCmmType dflags PtrRep = gcWord dflags primRepCmmType dflags IntRep = bWord dflags primRepCmmType dflags WordRep = bWord dflags primRepCmmType _ Int64Rep = b64 primRepCmmType _ Word64Rep = b64 primRepCmmType dflags AddrRep = bWord dflags primRepCmmType _ FloatRep = f32 primRepCmmType _ DoubleRep = f64 primRepCmmType _ (VecRep len rep) = vec len (primElemRepCmmType rep) slotCmmType :: DynFlags -> SlotTy -> CmmType slotCmmType dflags PtrSlot = gcWord dflags slotCmmType dflags WordSlot = bWord dflags slotCmmType _ Word64Slot = b64 slotCmmType _ FloatSlot = f32 slotCmmType _ DoubleSlot = f64 primElemRepCmmType :: PrimElemRep -> CmmType primElemRepCmmType Int8ElemRep = b8 primElemRepCmmType Int16ElemRep = b16 primElemRepCmmType Int32ElemRep = b32 primElemRepCmmType Int64ElemRep = b64 primElemRepCmmType Word8ElemRep = b8 primElemRepCmmType Word16ElemRep = b16 primElemRepCmmType Word32ElemRep = b32 primElemRepCmmType Word64ElemRep = b64 primElemRepCmmType FloatElemRep = f32 primElemRepCmmType DoubleElemRep = f64 typeCmmType :: DynFlags -> UnaryType -> CmmType typeCmmType dflags ty = primRepCmmType dflags (typePrimRep ty) cmmArgType :: DynFlags -> CmmArg -> CmmType cmmArgType dflags (CmmExprArg e) = cmmExprType dflags e cmmArgType dflags (CmmRubbishArg ty) = typeCmmType dflags ty primRepForeignHint :: PrimRep -> ForeignHint primRepForeignHint VoidRep = panic "primRepForeignHint:VoidRep" primRepForeignHint PtrRep = AddrHint primRepForeignHint IntRep = SignedHint primRepForeignHint WordRep = NoHint primRepForeignHint Int64Rep = SignedHint primRepForeignHint Word64Rep = NoHint primRepForeignHint AddrRep = AddrHint -- NB! AddrHint, but NonPtrArg primRepForeignHint FloatRep = NoHint primRepForeignHint DoubleRep = NoHint primRepForeignHint (VecRep {}) = NoHint slotForeignHint :: SlotTy -> ForeignHint slotForeignHint PtrSlot = AddrHint slotForeignHint WordSlot = NoHint slotForeignHint Word64Slot = NoHint slotForeignHint FloatSlot = NoHint slotForeignHint DoubleSlot = NoHint typeForeignHint :: UnaryType -> ForeignHint typeForeignHint = primRepForeignHint . typePrimRep --------------------------------------------------- -- -- CmmLit -- --------------------------------------------------- -- XXX: should really be Integer, since Int doesn't necessarily cover -- the full range of target Ints. mkIntCLit :: DynFlags -> Int -> CmmLit mkIntCLit dflags i = CmmInt (toInteger i) (wordWidth dflags) mkIntExpr :: DynFlags -> Int -> CmmExpr mkIntExpr dflags i = CmmLit $! mkIntCLit dflags i zeroCLit :: DynFlags -> CmmLit zeroCLit dflags = CmmInt 0 (wordWidth dflags) zeroExpr :: DynFlags -> CmmExpr zeroExpr dflags = CmmLit (zeroCLit dflags) mkWordCLit :: DynFlags -> Integer -> CmmLit mkWordCLit dflags wd = CmmInt wd (wordWidth dflags) mkByteStringCLit :: Unique -> [Word8] -> (CmmLit, GenCmmDecl CmmStatics info stmt) -- We have to make a top-level decl for the string, -- and return a literal pointing to it mkByteStringCLit uniq bytes = (CmmLabel lbl, CmmData sec $ Statics lbl [CmmString bytes]) where lbl = mkStringLitLabel uniq sec = Section ReadOnlyData lbl mkDataLits :: Section -> CLabel -> [CmmLit] -> GenCmmDecl CmmStatics info stmt -- Build a data-segment data block mkDataLits section lbl lits = CmmData section (Statics lbl $ map CmmStaticLit lits) mkRODataLits :: CLabel -> [CmmLit] -> GenCmmDecl CmmStatics info stmt -- Build a read-only data block mkRODataLits lbl lits = mkDataLits section lbl lits where section | any needsRelocation lits = Section RelocatableReadOnlyData lbl | otherwise = Section ReadOnlyData lbl needsRelocation (CmmLabel _) = True needsRelocation (CmmLabelOff _ _) = True needsRelocation _ = False mkStgWordCLit :: DynFlags -> StgWord -> CmmLit mkStgWordCLit dflags wd = CmmInt (fromStgWord wd) (wordWidth dflags) packHalfWordsCLit :: DynFlags -> StgHalfWord -> StgHalfWord -> CmmLit -- Make a single word literal in which the lower_half_word is -- at the lower address, and the upper_half_word is at the -- higher address -- ToDo: consider using half-word lits instead -- but be careful: that's vulnerable when reversed packHalfWordsCLit dflags lower_half_word upper_half_word = if wORDS_BIGENDIAN dflags then mkWordCLit dflags ((l `shiftL` hALF_WORD_SIZE_IN_BITS dflags) .|. u) else mkWordCLit dflags (l .|. (u `shiftL` hALF_WORD_SIZE_IN_BITS dflags)) where l = fromStgHalfWord lower_half_word u = fromStgHalfWord upper_half_word --------------------------------------------------- -- -- CmmExpr -- --------------------------------------------------- mkLblExpr :: CLabel -> CmmExpr mkLblExpr lbl = CmmLit (CmmLabel lbl) cmmOffsetExpr :: DynFlags -> CmmExpr -> CmmExpr -> CmmExpr -- assumes base and offset have the same CmmType cmmOffsetExpr dflags e (CmmLit (CmmInt n _)) = cmmOffset dflags e (fromInteger n) cmmOffsetExpr dflags e byte_off = CmmMachOp (MO_Add (cmmExprWidth dflags e)) [e, byte_off] cmmOffset :: DynFlags -> CmmExpr -> Int -> CmmExpr cmmOffset _ e 0 = e cmmOffset _ (CmmReg reg) byte_off = cmmRegOff reg byte_off cmmOffset _ (CmmRegOff reg m) byte_off = cmmRegOff reg (m+byte_off) cmmOffset _ (CmmLit lit) byte_off = CmmLit (cmmOffsetLit lit byte_off) cmmOffset _ (CmmStackSlot area off) byte_off = CmmStackSlot area (off - byte_off) -- note stack area offsets increase towards lower addresses cmmOffset _ (CmmMachOp (MO_Add rep) [expr, CmmLit (CmmInt byte_off1 _rep)]) byte_off2 = CmmMachOp (MO_Add rep) [expr, CmmLit (CmmInt (byte_off1 + toInteger byte_off2) rep)] cmmOffset dflags expr byte_off = CmmMachOp (MO_Add width) [expr, CmmLit (CmmInt (toInteger byte_off) width)] where width = cmmExprWidth dflags expr -- Smart constructor for CmmRegOff. Same caveats as cmmOffset above. cmmRegOff :: CmmReg -> Int -> CmmExpr cmmRegOff reg 0 = CmmReg reg cmmRegOff reg byte_off = CmmRegOff reg byte_off cmmOffsetLit :: CmmLit -> Int -> CmmLit cmmOffsetLit (CmmLabel l) byte_off = cmmLabelOff l byte_off cmmOffsetLit (CmmLabelOff l m) byte_off = cmmLabelOff l (m+byte_off) cmmOffsetLit (CmmLabelDiffOff l1 l2 m) byte_off = CmmLabelDiffOff l1 l2 (m+byte_off) cmmOffsetLit (CmmInt m rep) byte_off = CmmInt (m + fromIntegral byte_off) rep cmmOffsetLit _ byte_off = pprPanic "cmmOffsetLit" (ppr byte_off) cmmLabelOff :: CLabel -> Int -> CmmLit -- Smart constructor for CmmLabelOff cmmLabelOff lbl 0 = CmmLabel lbl cmmLabelOff lbl byte_off = CmmLabelOff lbl byte_off -- | Useful for creating an index into an array, with a statically known offset. -- The type is the element type; used for making the multiplier cmmIndex :: DynFlags -> Width -- Width w -> CmmExpr -- Address of vector of items of width w -> Int -- Which element of the vector (0 based) -> CmmExpr -- Address of i'th element cmmIndex dflags width base idx = cmmOffset dflags base (idx * widthInBytes width) -- | Useful for creating an index into an array, with an unknown offset. cmmIndexExpr :: DynFlags -> Width -- Width w -> CmmExpr -- Address of vector of items of width w -> CmmExpr -- Which element of the vector (0 based) -> CmmExpr -- Address of i'th element cmmIndexExpr dflags width base (CmmLit (CmmInt n _)) = cmmIndex dflags width base (fromInteger n) cmmIndexExpr dflags width base idx = cmmOffsetExpr dflags base byte_off where idx_w = cmmExprWidth dflags idx byte_off = CmmMachOp (MO_Shl idx_w) [idx, mkIntExpr dflags (widthInLog width)] cmmLoadIndex :: DynFlags -> CmmType -> CmmExpr -> Int -> CmmExpr cmmLoadIndex dflags ty expr ix = CmmLoad (cmmIndex dflags (typeWidth ty) expr ix) ty -- The "B" variants take byte offsets cmmRegOffB :: CmmReg -> ByteOff -> CmmExpr cmmRegOffB = cmmRegOff cmmOffsetB :: DynFlags -> CmmExpr -> ByteOff -> CmmExpr cmmOffsetB = cmmOffset cmmOffsetExprB :: DynFlags -> CmmExpr -> CmmExpr -> CmmExpr cmmOffsetExprB = cmmOffsetExpr cmmLabelOffB :: CLabel -> ByteOff -> CmmLit cmmLabelOffB = cmmLabelOff cmmOffsetLitB :: CmmLit -> ByteOff -> CmmLit cmmOffsetLitB = cmmOffsetLit ----------------------- -- The "W" variants take word offsets cmmOffsetExprW :: DynFlags -> CmmExpr -> CmmExpr -> CmmExpr -- The second arg is a *word* offset; need to change it to bytes cmmOffsetExprW dflags e (CmmLit (CmmInt n _)) = cmmOffsetW dflags e (fromInteger n) cmmOffsetExprW dflags e wd_off = cmmIndexExpr dflags (wordWidth dflags) e wd_off cmmOffsetW :: DynFlags -> CmmExpr -> WordOff -> CmmExpr cmmOffsetW dflags e n = cmmOffsetB dflags e (wordsToBytes dflags n) cmmRegOffW :: DynFlags -> CmmReg -> WordOff -> CmmExpr cmmRegOffW dflags reg wd_off = cmmRegOffB reg (wordsToBytes dflags wd_off) cmmOffsetLitW :: DynFlags -> CmmLit -> WordOff -> CmmLit cmmOffsetLitW dflags lit wd_off = cmmOffsetLitB lit (wordsToBytes dflags wd_off) cmmLabelOffW :: DynFlags -> CLabel -> WordOff -> CmmLit cmmLabelOffW dflags lbl wd_off = cmmLabelOffB lbl (wordsToBytes dflags wd_off) cmmLoadIndexW :: DynFlags -> CmmExpr -> Int -> CmmType -> CmmExpr cmmLoadIndexW dflags base off ty = CmmLoad (cmmOffsetW dflags base off) ty ----------------------- cmmULtWord, cmmUGeWord, cmmUGtWord, cmmUShrWord, cmmSLtWord, cmmNeWord, cmmEqWord, cmmOrWord, cmmAndWord, cmmSubWord, cmmAddWord, cmmMulWord, cmmQuotWord :: DynFlags -> CmmExpr -> CmmExpr -> CmmExpr cmmOrWord dflags e1 e2 = CmmMachOp (mo_wordOr dflags) [e1, e2] cmmAndWord dflags e1 e2 = CmmMachOp (mo_wordAnd dflags) [e1, e2] cmmNeWord dflags e1 e2 = CmmMachOp (mo_wordNe dflags) [e1, e2] cmmEqWord dflags e1 e2 = CmmMachOp (mo_wordEq dflags) [e1, e2] cmmULtWord dflags e1 e2 = CmmMachOp (mo_wordULt dflags) [e1, e2] cmmUGeWord dflags e1 e2 = CmmMachOp (mo_wordUGe dflags) [e1, e2] cmmUGtWord dflags e1 e2 = CmmMachOp (mo_wordUGt dflags) [e1, e2] --cmmShlWord dflags e1 e2 = CmmMachOp (mo_wordShl dflags) [e1, e2] cmmSLtWord dflags e1 e2 = CmmMachOp (mo_wordSLt dflags) [e1, e2] cmmUShrWord dflags e1 e2 = CmmMachOp (mo_wordUShr dflags) [e1, e2] cmmAddWord dflags e1 e2 = CmmMachOp (mo_wordAdd dflags) [e1, e2] cmmSubWord dflags e1 e2 = CmmMachOp (mo_wordSub dflags) [e1, e2] cmmMulWord dflags e1 e2 = CmmMachOp (mo_wordMul dflags) [e1, e2] cmmQuotWord dflags e1 e2 = CmmMachOp (mo_wordUQuot dflags) [e1, e2] cmmNegate :: DynFlags -> CmmExpr -> CmmExpr cmmNegate _ (CmmLit (CmmInt n rep)) = CmmLit (CmmInt (-n) rep) cmmNegate dflags e = CmmMachOp (MO_S_Neg (cmmExprWidth dflags e)) [e] blankWord :: DynFlags -> CmmStatic blankWord dflags = CmmUninitialised (wORD_SIZE dflags) cmmToWord :: DynFlags -> CmmExpr -> CmmExpr cmmToWord dflags e | w == word = e | otherwise = CmmMachOp (MO_UU_Conv w word) [e] where w = cmmExprWidth dflags e word = wordWidth dflags --------------------------------------------------- -- -- CmmExpr predicates -- --------------------------------------------------- isTrivialCmmExpr :: CmmExpr -> Bool isTrivialCmmExpr (CmmLoad _ _) = False isTrivialCmmExpr (CmmMachOp _ _) = False isTrivialCmmExpr (CmmLit _) = True isTrivialCmmExpr (CmmReg _) = True isTrivialCmmExpr (CmmRegOff _ _) = True isTrivialCmmExpr (CmmStackSlot _ _) = panic "isTrivialCmmExpr CmmStackSlot" hasNoGlobalRegs :: CmmExpr -> Bool hasNoGlobalRegs (CmmLoad e _) = hasNoGlobalRegs e hasNoGlobalRegs (CmmMachOp _ es) = all hasNoGlobalRegs es hasNoGlobalRegs (CmmLit _) = True hasNoGlobalRegs (CmmReg (CmmLocal _)) = True hasNoGlobalRegs (CmmRegOff (CmmLocal _) _) = True hasNoGlobalRegs _ = False --------------------------------------------------- -- -- Tagging -- --------------------------------------------------- -- Tag bits mask --cmmTagBits = CmmLit (mkIntCLit tAG_BITS) cmmTagMask, cmmPointerMask :: DynFlags -> CmmExpr cmmTagMask dflags = mkIntExpr dflags (tAG_MASK dflags) cmmPointerMask dflags = mkIntExpr dflags (complement (tAG_MASK dflags)) -- Used to untag a possibly tagged pointer -- A static label need not be untagged cmmUntag :: DynFlags -> CmmExpr -> CmmExpr cmmUntag _ e@(CmmLit (CmmLabel _)) = e -- Default case cmmUntag dflags e = cmmAndWord dflags e (cmmPointerMask dflags) -- Test if a closure pointer is untagged cmmIsTagged :: DynFlags -> CmmExpr -> CmmExpr cmmIsTagged dflags e = cmmNeWord dflags (cmmAndWord dflags e (cmmTagMask dflags)) (zeroExpr dflags) cmmConstrTag1 :: DynFlags -> CmmExpr -> CmmExpr -- Get constructor tag, but one based. cmmConstrTag1 dflags e = cmmAndWord dflags e (cmmTagMask dflags) ----------------------------------------------------------------------------- -- Overlap and usage -- | Returns True if the two STG registers overlap on the specified -- platform, in the sense that writing to one will clobber the -- other. This includes the case that the two registers are the same -- STG register. See Note [Overlapping global registers] for details. regsOverlap :: DynFlags -> CmmReg -> CmmReg -> Bool regsOverlap dflags (CmmGlobal g) (CmmGlobal g') | Just real <- globalRegMaybe (targetPlatform dflags) g, Just real' <- globalRegMaybe (targetPlatform dflags) g', real == real' = True regsOverlap _ reg reg' = reg == reg' -- | Returns True if the STG register is used by the expression, in -- the sense that a store to the register might affect the value of -- the expression. -- -- We must check for overlapping registers and not just equal -- registers here, otherwise CmmSink may incorrectly reorder -- assignments that conflict due to overlap. See Trac #10521 and Note -- [Overlapping global registers]. regUsedIn :: DynFlags -> CmmReg -> CmmExpr -> Bool regUsedIn dflags = regUsedIn_ where _ `regUsedIn_` CmmLit _ = False reg `regUsedIn_` CmmLoad e _ = reg `regUsedIn_` e reg `regUsedIn_` CmmReg reg' = regsOverlap dflags reg reg' reg `regUsedIn_` CmmRegOff reg' _ = regsOverlap dflags reg reg' reg `regUsedIn_` CmmMachOp _ es = any (reg `regUsedIn_`) es _ `regUsedIn_` CmmStackSlot _ _ = False -------------------------------------------- -- -- mkLiveness -- --------------------------------------------- mkLiveness :: DynFlags -> [Maybe LocalReg] -> Liveness mkLiveness _ [] = [] mkLiveness dflags (reg:regs) = take sizeW bits ++ mkLiveness dflags regs where sizeW = case reg of Nothing -> 1 Just r -> (widthInBytes (typeWidth (localRegType r)) + wORD_SIZE dflags - 1) `quot` wORD_SIZE dflags -- number of words, rounded up bits = repeat $ is_non_ptr reg -- True <=> Non Ptr is_non_ptr Nothing = True is_non_ptr (Just reg) = not $ isGcPtrType (localRegType reg) -- ============================================== - -- ============================================== - -- ============================================== - --------------------------------------------------- -- -- Manipulating CmmGraphs -- --------------------------------------------------- modifyGraph :: (Graph n C C -> Graph n' C C) -> GenCmmGraph n -> GenCmmGraph n' modifyGraph f g = CmmGraph {g_entry=g_entry g, g_graph=f (g_graph g)} toBlockMap :: CmmGraph -> BlockEnv CmmBlock toBlockMap (CmmGraph {g_graph=GMany NothingO body NothingO}) = body ofBlockMap :: BlockId -> BlockEnv CmmBlock -> CmmGraph ofBlockMap entry bodyMap = CmmGraph {g_entry=entry, g_graph=GMany NothingO bodyMap NothingO} insertBlock :: CmmBlock -> BlockEnv CmmBlock -> BlockEnv CmmBlock insertBlock block map = ASSERT(isNothing $ mapLookup id map) mapInsert id block map where id = entryLabel block toBlockList :: CmmGraph -> [CmmBlock] toBlockList g = mapElems $ toBlockMap g -- | like 'toBlockList', but the entry block always comes first toBlockListEntryFirst :: CmmGraph -> [CmmBlock] toBlockListEntryFirst g | mapNull m = [] | otherwise = entry_block : others where m = toBlockMap g entry_id = g_entry g Just entry_block = mapLookup entry_id m others = filter ((/= entry_id) . entryLabel) (mapElems m) -- | Like 'toBlockListEntryFirst', but we strive to ensure that we order blocks -- so that the false case of a conditional jumps to the next block in the output -- list of blocks. This matches the way OldCmm blocks were output since in -- OldCmm the false case was a fallthrough, whereas in Cmm conditional branches -- have both true and false successors. Block ordering can make a big difference -- in performance in the LLVM backend. Note that we rely crucially on the order -- of successors returned for CmmCondBranch by the NonLocal instance for CmmNode -- defind in cmm/CmmNode.hs. -GBM toBlockListEntryFirstFalseFallthrough :: CmmGraph -> [CmmBlock] toBlockListEntryFirstFalseFallthrough g | mapNull m = [] | otherwise = dfs setEmpty [entry_block] where m = toBlockMap g entry_id = g_entry g Just entry_block = mapLookup entry_id m dfs :: LabelSet -> [CmmBlock] -> [CmmBlock] dfs _ [] = [] dfs visited (block:bs) | id `setMember` visited = dfs visited bs | otherwise = block : dfs (setInsert id visited) bs' where id = entryLabel block bs' = foldr add_id bs (successors block) add_id id bs = case mapLookup id m of Just b -> b : bs Nothing -> bs ofBlockList :: BlockId -> [CmmBlock] -> CmmGraph ofBlockList entry blocks = CmmGraph { g_entry = entry , g_graph = GMany NothingO body NothingO } where body = foldr addBlock emptyBody blocks bodyToBlockList :: Body CmmNode -> [CmmBlock] bodyToBlockList body = mapElems body mapGraphNodes :: ( CmmNode C O -> CmmNode C O , CmmNode O O -> CmmNode O O , CmmNode O C -> CmmNode O C) -> CmmGraph -> CmmGraph mapGraphNodes funs@(mf,_,_) g = ofBlockMap (entryLabel $ mf $ CmmEntry (g_entry g) GlobalScope) $ mapMap (mapBlock3' funs) $ toBlockMap g mapGraphNodes1 :: (forall e x. CmmNode e x -> CmmNode e x) -> CmmGraph -> CmmGraph mapGraphNodes1 f = modifyGraph (mapGraph f) foldGraphBlocks :: (CmmBlock -> a -> a) -> a -> CmmGraph -> a foldGraphBlocks k z g = mapFold k z $ toBlockMap g postorderDfs :: CmmGraph -> [CmmBlock] postorderDfs g = {-# SCC "postorderDfs" #-} postorder_dfs_from (toBlockMap g) (g_entry g) ------------------------------------------------- -- Running dataflow analysis and/or rewrites -- Constructing forward and backward analysis-only pass analFwd :: DataflowLattice f -> FwdTransfer n f -> FwdPass UniqSM n f analBwd :: DataflowLattice f -> BwdTransfer n f -> BwdPass UniqSM n f analFwd lat xfer = analRewFwd lat xfer noFwdRewrite analBwd lat xfer = analRewBwd lat xfer noBwdRewrite -- Constructing forward and backward analysis + rewrite pass analRewFwd :: DataflowLattice f -> FwdTransfer n f -> FwdRewrite UniqSM n f -> FwdPass UniqSM n f analRewBwd :: DataflowLattice f -> BwdTransfer n f -> BwdRewrite UniqSM n f -> BwdPass UniqSM n f analRewFwd lat xfer rew = FwdPass {fp_lattice = lat, fp_transfer = xfer, fp_rewrite = rew} analRewBwd lat xfer rew = BwdPass {bp_lattice = lat, bp_transfer = xfer, bp_rewrite = rew} -- Running forward and backward dataflow analysis + optional rewrite dataflowPassFwd :: NonLocal n => GenCmmGraph n -> [(BlockId, f)] -> FwdPass UniqSM n f -> UniqSM (GenCmmGraph n, BlockEnv f) dataflowPassFwd (CmmGraph {g_entry=entry, g_graph=graph}) facts fwd = do (graph, facts, NothingO) <- analyzeAndRewriteFwd fwd (JustC [entry]) graph (mkFactBase (fp_lattice fwd) facts) return (CmmGraph {g_entry=entry, g_graph=graph}, facts) dataflowAnalFwd :: NonLocal n => GenCmmGraph n -> [(BlockId, f)] -> FwdPass UniqSM n f -> BlockEnv f dataflowAnalFwd (CmmGraph {g_entry=entry, g_graph=graph}) facts fwd = analyzeFwd fwd (JustC [entry]) graph (mkFactBase (fp_lattice fwd) facts) dataflowAnalFwdBlocks :: NonLocal n => GenCmmGraph n -> [(BlockId, f)] -> FwdPass UniqSM n f -> UniqSM (BlockEnv f) dataflowAnalFwdBlocks (CmmGraph {g_entry=entry, g_graph=graph}) facts fwd = do -- (graph, facts, NothingO) <- analyzeAndRewriteFwd fwd (JustC [entry]) graph (mkFactBase (fp_lattice fwd) facts) -- return facts return (analyzeFwdBlocks fwd (JustC [entry]) graph (mkFactBase (fp_lattice fwd) facts)) dataflowAnalBwd :: NonLocal n => GenCmmGraph n -> [(BlockId, f)] -> BwdPass UniqSM n f -> BlockEnv f dataflowAnalBwd (CmmGraph {g_entry=entry, g_graph=graph}) facts bwd = analyzeBwd bwd (JustC [entry]) graph (mkFactBase (bp_lattice bwd) facts) dataflowPassBwd :: NonLocal n => GenCmmGraph n -> [(BlockId, f)] -> BwdPass UniqSM n f -> UniqSM (GenCmmGraph n, BlockEnv f) dataflowPassBwd (CmmGraph {g_entry=entry, g_graph=graph}) facts bwd = do (graph, facts, NothingO) <- analyzeAndRewriteBwd bwd (JustC [entry]) graph (mkFactBase (bp_lattice bwd) facts) return (CmmGraph {g_entry=entry, g_graph=graph}, facts) ------------------------------------------------- -- Tick utilities -- | Extract all tick annotations from the given block blockTicks :: Block CmmNode C C -> [CmmTickish] blockTicks b = reverse $ foldBlockNodesF goStmt b [] where goStmt :: CmmNode e x -> [CmmTickish] -> [CmmTickish] goStmt (CmmTick t) ts = t:ts goStmt _other ts = ts
sgillespie/ghc
compiler/cmm/CmmUtils.hs
bsd-3-clause
24,570
0
18
5,206
6,304
3,314
2,990
399
6
{- TGA.hs; Mun Hon Cheong ([email protected]) 2005 This module was based on lesson 24 from neon helium productions http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=24 The TGA format is a used bitmap image file format. They are quite easy to load compared to other formats and have good support in image editors. All that has to be done is read the header to determine the dimensions and pixel format. Then the bytes have to be swapped and can be used by OPenGL. If you see a texture that is upside down, just open it in your editor and flip it vertically. Somtimes the TGA file is stored with its pixels upside down. -} module TGA where import Data.Word ( Word8 ) import Control.Exception ( bracket ) import System.IO ( Handle, IOMode(ReadMode), openBinaryFile, hGetBuf, hClose ) import Foreign.Marshal.Array (peekArray, pokeArray) import Foreign.Marshal.Alloc (free, mallocBytes) import Foreign.Ptr (plusPtr, Ptr()) -- import Graphics.UI.GLUT -- (Size, PixelData, UnsignedByte, PixelFormat, RGBA, RGB) import Graphics.Rendering.OpenGL withBinaryFile' :: FilePath -> (Handle -> IO a) -> IO a withBinaryFile' filePath = bracket (openBinaryFile filePath ReadMode) hClose -- reads a *.tga file readTga :: FilePath -> IO (Maybe (Size, PixelData Word8)) readTga filePath = withBinaryFile' filePath $ \handle -> do buf <- mallocBytes 6 :: IO(Ptr Word8) --the first 12 bytes of the header aren't used hGetBuf handle buf 6 hGetBuf handle buf 6 hGetBuf handle buf 6 header <- peekArray 6 buf let w1 = (fromIntegral (header!!1))*256 :: Int let width = w1 + (fromIntegral (header!!0)) let h1 = (fromIntegral (header!!3))*256 :: Int let height = h1 + (fromIntegral (header!!2)) let bitspp = (fromIntegral (header!!4)) let numBytes = (bitspp `div` 8) * width * height --allocate memory for the image image <- mallocBytes numBytes hGetBuf handle image numBytes --define whether the pixels are in RGB or RGBA format. pixelFormat <- getFormat (fromIntegral bitspp) free buf --convert the pixels which are in BGR/BGRA to RGB/RGBA swapBytes' image (bitspp `div` 8) (width * height) print ("loaded "++filePath) return $ Just (Size (fromIntegral width) (fromIntegral height), PixelData pixelFormat UnsignedByte image) -- converts the image from bgr/bgra to rgb/rgba -- perhaps the opengl bgra extension could be -- used to avoid this swapBytes' :: Ptr Word8 -> Int -> Int -> IO() swapBytes' image bytespp size = case bytespp of 3 -> do mapM_ (swapByteRGB.(plusPtr image).(bytespp*)) [0..(size-1)] _ -> do mapM_ (swapByteRGBA.(plusPtr image).(bytespp*)) [0..(size-1)] -- 4 -- converts from bgr to rgb swapByteRGB :: Ptr Word8 -> IO() swapByteRGB ptr = do [b,g,r] <- peekArray 3 ptr pokeArray ptr [r,g,b] -- converts from bgra to rgba swapByteRGBA :: Ptr Word8 -> IO() swapByteRGBA ptr = do [b,g,r,a] <- peekArray 4 ptr pokeArray ptr [r,g,b,a] -- returns the pixel format given the bits per pixel getFormat :: Int -> IO(PixelFormat) getFormat bpp = do case bpp of 32 -> return RGBA _ -> return RGB -- 24
gbluma/opengl1
src/TGA.hs
bsd-3-clause
3,258
4
16
732
865
451
414
50
2
{-# OPTIONS_GHC -Wall -fno-warn-orphans #-} module Language.JavaScript.Pretty ( -- | This module just defines and exports 'Pretty' and 'PrettyPrec' instances Pretty(..) ) where -- System libraries import Text.PrettyPrint.Leijen import Text.PrettyPrint.Leijen.PrettyPrec import Prelude hiding (GT, LT, (<$>)) -- friends import Language.JavaScript.AST import Language.JavaScript.NonEmptyList -- FIXME: This will be a little tricky to get right. -- If the string contains double quotes you need to escape. -- If the string contains single quotes you need to escape. instance Pretty JSString where pretty s = char '"' <> text (unString s) <> char '"' -- enclosed in double quotes instance Pretty Name where pretty = text . unName sepWith :: Pretty a => Doc -> [a] -> Doc sepWith s = encloseSep empty empty s . map pretty endWith :: Pretty a => Doc -> [a] -> Doc endWith s xs = sepWith s xs <> s sepWith' :: Pretty a => Doc -> NonEmptyList a -> Doc sepWith' s = encloseSep empty empty s . map pretty . toList prettyBlock :: Pretty a => [a] -> Doc prettyBlock stmts = lbrace <$> indent 2 (endWith (semi <$> empty) stmts) <$> rbrace ------------------------------------------------------------------------ -- -- Associativity -- data Associativity = LeftToRight | RightToLeft deriving Eq prettyInfixOpApp :: (PrettyPrec a, PrettyPrec b) => Int -> OpInfo -> a -> b -> Doc prettyInfixOpApp prec (OpInfo opPrec assoc nm) a b = docParen (prec > opPrec) $ bump LeftToRight a <+> text nm <+> bump RightToLeft b where bump assoc' d = prettyPrec opPrec' d where opPrec' = if assoc == assoc' then opPrec else opPrec + 1 docParen :: Bool -> Doc -> Doc docParen True = parens docParen False = id data OpInfo = OpInfo Int -- precedence Associativity -- associativity String -- name -- -- Lower precedence means the operator binds more tightly -- infixOpInfo :: InfixOperator -> OpInfo infixOpInfo op = case op of Mul -> go 6 "*" Div -> go 6 "/" Mod -> go 6 "%" Add -> go 5 "+" Sub -> go 5 "-" GTE -> go 4 ">=" LTE -> go 4 "<=" GT -> go 4 ">" LT -> go 4 "<" Eq -> go 3 "===" NotEq -> go 3 "!==" Or -> go 1 "||" And -> go 2 "&&" where go i s = OpInfo i LeftToRight s ----------------------------------------------------------------------- instance Pretty Number where pretty (Number n) = pretty n -- FIXME: Make sure this always produce valid Javascript numbers. instance PrettyPrec Number -- default instance Pretty VarStmt where pretty (VarStmt varDecls) = text "var" <+> sepWith' (comma <+> empty) varDecls <> semi instance PrettyPrec VarStmt -- default instance Pretty VarDecl where pretty (VarDecl nm Nothing) = pretty nm pretty (VarDecl nm (Just exp')) = pretty nm <+> text "=" <+> pretty exp' instance PrettyPrec VarDecl -- default instance Pretty Stmt where pretty stmt = case stmt of (StmtExpr es) -> pretty es <> semi (StmtDisruptive ds) -> pretty ds (StmtTry ts) -> pretty ts (StmtIf is) -> pretty is (StmtSwitch mbLbl ss) -> pp mbLbl ss (StmtWhile mbLbl ws) -> pp mbLbl ws (StmtFor mbLbl fs) -> pp mbLbl fs (StmtDo mbLbl ds) -> pp mbLbl ds where pp :: Pretty a => Maybe Name -> a -> Doc pp (Just label) doc = pretty label <> colon <+> pretty doc pp Nothing doc = pretty doc instance PrettyPrec Stmt-- default instance Pretty DisruptiveStmt where pretty stmt = case stmt of DSBreak bs -> pretty bs DSReturn rs -> pretty rs DSThrow ts -> pretty ts instance PrettyPrec DisruptiveStmt -- default instance Pretty IfStmt where pretty (IfStmt cond thenStmts blockOrIf) = text "if" <+> parens (pretty cond) <+> prettyBlock thenStmts <+> ppRest where ppRest = case blockOrIf of Nothing -> empty Just (Left elseStmts) -> text "else" <+> prettyBlock elseStmts Just (Right ifStmt) -> pretty ifStmt instance PrettyPrec IfStmt -- default instance Pretty SwitchStmt where pretty (SwitchStmtSingleCase cond caseClause) = text "switch" <+> parens (pretty cond) <+> lbrace <$> pretty caseClause <$> rbrace pretty (SwitchStmt cond cds stmts) = text "switch" <+> parens (pretty cond) <+> lbrace <$> indent 2 (vcat (toList . fmap pretty $ cds) <$> (text "default:" <$> indent 2 (endWith semi stmts))) <$> rbrace instance PrettyPrec SwitchStmt -- default instance Pretty CaseAndDisruptive where pretty (CaseAndDisruptive caseClause disruptive) = pretty caseClause <$> pretty disruptive instance PrettyPrec CaseAndDisruptive -- default instance Pretty CaseClause where pretty (CaseClause exp' stmts) = text "case" <+> pretty exp' <> colon <+> endWith semi stmts instance PrettyPrec CaseClause -- default instance Pretty ForStmt where pretty (ForStmtCStyle init_ cond incr stmts) = text "for" <+> parens (pretty init_ <> semi <+> pretty cond <> semi <+> pretty incr) <+> prettyBlock stmts pretty (ForStmtInStyle nm exp' stmts) = text "for" <+> parens (pretty nm <+> text "in" <+> pretty exp') <+> prettyBlock stmts instance PrettyPrec ForStmt -- default instance Pretty DoStmt where pretty (DoStmt stmts cond) = text "do" <+> prettyBlock stmts <+> text "while" <+> parens (pretty cond) <> semi instance PrettyPrec DoStmt -- default instance Pretty WhileStmt where pretty (WhileStmt cond stmts) = text "while" <+> parens (pretty cond) <+> prettyBlock stmts instance PrettyPrec WhileStmt -- default instance Pretty TryStmt where pretty (TryStmt tryStmts varName catchStmts) = text "try" <+> prettyBlock tryStmts <+> parens (pretty varName) <+> prettyBlock catchStmts instance PrettyPrec TryStmt -- default instance Pretty ThrowStmt where pretty (ThrowStmt exp_) = text "throw" <+> pretty exp_ <> semi instance PrettyPrec ThrowStmt -- default instance Pretty ReturnStmt where pretty (ReturnStmt mbExp) = case mbExp of Nothing -> text "return;" Just exp_ -> text "return" <+> pretty exp_ <> semi instance PrettyPrec ReturnStmt -- default instance Pretty BreakStmt where pretty (BreakStmt mbExp) = case mbExp of Nothing -> text "break;" Just exp_ -> text "break" <+> pretty exp_ <> semi instance PrettyPrec BreakStmt -- default instance Pretty ExprStmt where pretty (ESApply lvalues rvalue) = sepWith' (space <> text "=" <> space) lvalues <+> pretty rvalue pretty (ESDelete exp_ refine) = text "delete" <+> pretty exp_ <> pretty refine instance PrettyPrec ExprStmt -- default instance Pretty LValue where pretty (LValue nm invsAndRefines) = pretty nm <> (hcat . map ppIR $ invsAndRefines) where ppIR (invs, refine) = (hcat . map pretty $ invs) <> pretty refine instance PrettyPrec LValue -- default instance Pretty RValue where pretty rvalue = case rvalue of RVAssign e -> text "=" <+> pretty e RVAddAssign e -> text "+=" <+> pretty e RVSubAssign e -> text "-=" <+> pretty e RVInvoke invs -> hcat . toList . fmap pretty $ invs instance PrettyPrec RValue -- default instance Pretty Expr where pretty = prettyPrec 0 instance PrettyPrec Expr where prettyPrec i exp_ = case exp_ of ExprLit literal -> pretty literal ExprName nm -> pretty nm ExprPrefix prefixOp e -> pretty prefixOp <> pretty e ExprInfix infixOp e e' -> prettyInfixOpApp i (infixOpInfo infixOp) e e' ExprTernary cond thn els -> pretty cond <+> char '?' <+> pretty thn <+> colon <+> pretty els ExprInvocation e i' -> pretty e <> pretty i' ExprRefinement e r -> pretty e <> pretty r ExprNew e i' -> text "new" <+> pretty e <> pretty i' ExprDelete e r -> text "new" <+> pretty e <> pretty r instance Pretty PrefixOperator where pretty op = case op of TypeOf -> text "typeof" <+> empty ToNumber -> char '+' Negate -> char '-' Not -> char '!' instance PrettyPrec PrefixOperator --default instance Pretty InfixOperator where pretty = prettyPrec 0 instance PrettyPrec InfixOperator where prettyPrec = error "we never print an operator by itself" instance Pretty Invocation where pretty (Invocation es) = lparen <> sepWith (comma <+> empty) es <> rparen instance PrettyPrec Invocation -- default instance Pretty Refinement where pretty (Property nm) = char '.' <> pretty nm pretty (Subscript e) = char '[' <> pretty e <> char ']' instance PrettyPrec Refinement -- default instance Pretty Lit where pretty lit = case lit of LitNumber n -> pretty n LitBool b -> if b then text "true" else text "false" LitString s -> pretty s LitObject o -> pretty o LitArray a -> pretty a LitFn f -> pretty f instance PrettyPrec Lit -- default instance Pretty ObjectLit where pretty (ObjectLit fields) = lbrace <> sepWith (comma <$> empty) fields <> rbrace instance PrettyPrec ObjectLit -- default instance Pretty ObjectField where pretty (ObjectField eitherNameString e) = ppEitherNameString <> colon <+> pretty e where ppEitherNameString = case eitherNameString of Left nm -> pretty nm Right s -> pretty s instance PrettyPrec ObjectField -- default instance Pretty ArrayLit where pretty (ArrayLit es) = lbracket <> sepWith (comma <+> empty) es <> rbracket instance PrettyPrec ArrayLit -- default instance Pretty FnLit where pretty (FnLit mbName params body) = text "function" `join` (parens . hcat . map pretty $ params) <+> pretty body where join = case mbName of Just nm -> (\a b -> a <+> pretty nm <> b) Nothing -> (<>) instance PrettyPrec FnLit -- default instance Pretty FnBody where pretty (FnBody varStmts stmts) = lbrace <$> indent 2 (sepWith (semi <$> empty) (map pretty varStmts ++ map pretty stmts)) <$> rbrace instance PrettyPrec FnBody -- default instance Pretty Program where pretty (Program varStmts stmts) = vcat (map pretty varStmts ++ map pretty stmts) ------------------------ {- test1 = add (n 1) (add (n 2) (add (add (n 3) (n 4)) (n 5))) test2 = add (n 1) (mul (n 2) (n 3)) test2' = ((n 1) `add` (n 2)) `mul` (n 3) test3 :: ExprStmt test3 = case jsName "x" of Right nm -> case jsName "y" of Right nm' -> ESApply ((LValue nm' []) <:> singleton (LValue nm [])) (RVAssign test2') test4 :: Stmt test4 = StmtExpr test3 -- test4a = Stmt test5 :: Program test5 = Program [] [test4, test4] test6 :: FnLit test6 = FnLit Nothing [] (FnBody [] [test4]) add e e' = ExprInfix Add e e' mul e e' = ExprInfix Mul e e' n x = ExprLit (LitNumber (Number x)) -}
sseefried/js-good-parts
src/Language/JavaScript/Pretty.hs
bsd-3-clause
10,904
0
15
2,693
3,324
1,607
1,717
223
13
{-# OPTIONS_GHC -fno-warn-name-shadowing #-} module PFDS.Sec2.Ex5 where data Tree a = E | T (Tree a) a (Tree a) deriving (Show) -- practice 2.5a complete :: Ord a => a -> Int -> Tree a complete _ 0 = E complete x d = T t x t where t = complete x (d-1) -- practice 2.5b balanced :: Ord a => a -> Int -> Tree a balanced _ 0 = E balanced x 1 = T E x E balanced x m = T (balanced x m'') x (balanced x m') where m' = (m - 1) `div` 2 m'' = m - 1 - m'
matonix/pfds
src/PFDS/Sec2/Ex5.hs
bsd-3-clause
464
0
9
127
231
121
110
12
1
{-# LANGUAGE OverloadedStrings #-} module State.Setup.Threads ( startUserRefreshThread , startTypingUsersRefreshThread , updateUserStatuses , startSubprocessLoggerThread , startTimezoneMonitorThread , maybeStartSpellChecker , startAsyncWorkerThread , startSyntaxMapLoaderThread , module State.Setup.Threads.Logging ) where import Prelude () import Prelude.MH import Brick.BChan import Control.Concurrent ( threadDelay, forkIO, MVar, putMVar, tryTakeMVar ) import qualified Control.Concurrent.STM as STM import Control.Concurrent.STM.Delay import Control.Exception ( SomeException, try, finally, fromException ) import qualified Data.Foldable as F import Data.List ( isInfixOf ) import qualified Data.Map as M import qualified Data.Text as T import Data.Time ( getCurrentTime, addUTCTime ) import Lens.Micro.Platform ( (.=), (%=), (%~), mapped ) import Skylighting.Loader ( loadSyntaxesFromDir ) import System.Directory ( getTemporaryDirectory ) import System.Exit ( ExitCode(ExitSuccess) ) import System.IO ( hPutStrLn, hFlush ) import System.IO.Temp ( openTempFile ) import Text.Aspell ( Aspell, AspellOption(..), startAspell ) import Network.Mattermost.Endpoints import Network.Mattermost.Types import Constants import State.Editing ( requestSpellCheck ) import State.Setup.Threads.Logging import TimeUtils ( lookupLocalTimeZone ) import Types updateUserStatuses :: STM.TVar (Seq UserId) -> MVar () -> Session -> IO (MH ()) updateUserStatuses usersVar lock session = do lockResult <- tryTakeMVar lock users <- STM.atomically $ STM.readTVar usersVar case lockResult of Just () | not (F.null users) -> do statuses <- mmGetUserStatusByIds users session `finally` putMVar lock () return $ do forM_ statuses $ \s -> setUserStatus (statusUserId s) (statusStatus s) Just () -> putMVar lock () >> return (return ()) _ -> return $ return () startUserRefreshThread :: STM.TVar (Seq UserId) -> MVar () -> Session -> RequestChan -> IO () startUserRefreshThread usersVar lock session requestChan = void $ forkIO $ forever refresh where seconds = (* (1000 * 1000)) userRefreshInterval = 30 refresh = do STM.atomically $ STM.writeTChan requestChan $ do rs <- try $ updateUserStatuses usersVar lock session case rs of Left (_ :: SomeException) -> return (return ()) Right upd -> return upd threadDelay (seconds userRefreshInterval) -- This thread refreshes the map of typing users every second, forever, -- to expire users who have stopped typing. Expiry time is 3 seconds. startTypingUsersRefreshThread :: RequestChan -> IO () startTypingUsersRefreshThread requestChan = void $ forkIO $ forever refresh where seconds = (* (1000 * 1000)) refreshIntervalMicros = ceiling $ seconds $ userTypingExpiryInterval / 2 refresh = do STM.atomically $ STM.writeTChan requestChan $ return $ do now <- liftIO getCurrentTime let expiry = addUTCTime (- userTypingExpiryInterval) now let expireUsers c = c & ccInfo.cdTypingUsers %~ expireTypingUsers expiry csChannels . mapped %= expireUsers threadDelay refreshIntervalMicros startSubprocessLoggerThread :: STM.TChan ProgramOutput -> RequestChan -> IO () startSubprocessLoggerThread logChan requestChan = do let logMonitor mPair = do ProgramOutput progName args out stdoutOkay err ec <- STM.atomically $ STM.readTChan logChan -- If either stdout or stderr is non-empty or there was an exit -- failure, log it and notify the user. let emptyOutput s = null s || s == "\n" case ec == ExitSuccess && (emptyOutput out || stdoutOkay) && emptyOutput err of -- the "good" case, no output and exit sucess True -> logMonitor mPair False -> do (logPath, logHandle) <- case mPair of Just p -> return p Nothing -> do tmp <- getTemporaryDirectory openTempFile tmp "matterhorn-subprocess.log" hPutStrLn logHandle $ unlines [ "Program: " <> progName , "Arguments: " <> show args , "Exit code: " <> show ec , "Stdout:" , out , "Stderr:" , err ] hFlush logHandle STM.atomically $ STM.writeTChan requestChan $ do return $ mhError $ ProgramExecutionFailed (T.pack progName) (T.pack logPath) logMonitor (Just (logPath, logHandle)) void $ forkIO $ logMonitor Nothing startTimezoneMonitorThread :: TimeZoneSeries -> RequestChan -> IO () startTimezoneMonitorThread tz requestChan = do -- Start the timezone monitor thread let timezoneMonitorSleepInterval = minutes 5 minutes = (* (seconds 60)) seconds = (* (1000 * 1000)) timezoneMonitor prevTz = do threadDelay timezoneMonitorSleepInterval newTz <- lookupLocalTimeZone when (newTz /= prevTz) $ STM.atomically $ STM.writeTChan requestChan $ do return $ timeZone .= newTz timezoneMonitor newTz void $ forkIO (timezoneMonitor tz) maybeStartSpellChecker :: Config -> BChan MHEvent -> IO (Maybe (Aspell, IO ())) maybeStartSpellChecker config eventQueue = do case configEnableAspell config of False -> return Nothing True -> do let aspellOpts = catMaybes [ UseDictionary <$> (configAspellDictionary config) ] spellCheckerTimeout = 500 * 1000 -- 500k us = 500ms asResult <- either (const Nothing) Just <$> startAspell aspellOpts case asResult of Nothing -> return Nothing Just as -> do resetSCChan <- startSpellCheckerThread eventQueue spellCheckerTimeout let resetSCTimer = STM.atomically $ STM.writeTChan resetSCChan () return $ Just (as, resetSCTimer) -- Start the background spell checker delay thread. -- -- The purpose of this thread is to postpone the spell checker query -- while the user is actively typing and only wait until they have -- stopped typing before bothering with a query. This is to avoid spell -- checker queries when the editor contents are changing rapidly. -- Avoiding such queries reduces system load and redraw frequency. -- -- We do this by starting a thread whose job is to wait for the event -- loop to tell it to schedule a spell check. Spell checks are scheduled -- by writing to the channel returned by this function. The scheduler -- thread reads from that channel and then works with another worker -- thread as follows: -- -- A wakeup of the main spell checker thread causes it to determine -- whether the worker thread is already waiting on a timer. When that -- timer goes off, a spell check will be requested. If there is already -- an active timer that has not yet expired, the timer's expiration is -- extended. This is the case where typing is occurring and we want to -- continue postponing the spell check. If there is not an active timer -- or the active timer has expired, we create a new timer and send it to -- the worker thread for waiting. -- -- The worker thread works by reading a timer from its queue, waiting -- until the timer expires, and then injecting an event into the main -- event loop to request a spell check. startSpellCheckerThread :: BChan MHEvent -- ^ The main event loop's event channel. -> Int -- ^ The number of microseconds to wait before -- requesting a spell check. -> IO (STM.TChan ()) startSpellCheckerThread eventChan spellCheckTimeout = do delayWakeupChan <- STM.atomically STM.newTChan delayWorkerChan <- STM.atomically STM.newTChan delVar <- STM.atomically $ STM.newTVar Nothing -- The delay worker actually waits on the delay to expire and then -- requests a spell check. void $ forkIO $ forever $ do STM.atomically $ waitDelay =<< STM.readTChan delayWorkerChan writeBChan eventChan (RespEvent requestSpellCheck) -- The delay manager waits for requests to start a delay timer and -- signals the worker to begin waiting. void $ forkIO $ forever $ do () <- STM.atomically $ STM.readTChan delayWakeupChan oldDel <- STM.atomically $ STM.readTVar delVar mNewDel <- case oldDel of Nothing -> Just <$> newDelay spellCheckTimeout Just del -> do -- It's possible that between this check for expiration and -- the updateDelay below, the timer will expire -- at which -- point this will mean that we won't extend the timer as -- originally desired. But that's alright, because future -- keystroke will trigger another timer anyway. expired <- tryWaitDelayIO del case expired of True -> Just <$> newDelay spellCheckTimeout False -> do updateDelay del spellCheckTimeout return Nothing case mNewDel of Nothing -> return () Just newDel -> STM.atomically $ do STM.writeTVar delVar $ Just newDel STM.writeTChan delayWorkerChan newDel return delayWakeupChan startSyntaxMapLoaderThread :: Config -> BChan MHEvent -> IO () startSyntaxMapLoaderThread config eventChan = void $ forkIO $ do -- Iterate over the configured syntax directories, loading syntax -- maps. Ensure that entries loaded in earlier directories in the -- sequence take precedence over entries loaded later. mMaps <- forM (configSyntaxDirs config) $ \dir -> do result <- try $ loadSyntaxesFromDir dir case result of Left (_::SomeException) -> return Nothing Right (Left _) -> return Nothing Right (Right m) -> return $ Just m let maps = catMaybes mMaps finalMap = foldl M.union mempty maps writeBChan eventChan $ RespEvent $ do csResources.crSyntaxMap .= finalMap ------------------------------------------------------------------- -- Async worker thread startAsyncWorkerThread :: Config -> STM.TChan (IO (MH ())) -> BChan MHEvent -> IO () startAsyncWorkerThread c r e = void $ forkIO $ asyncWorker c r e asyncWorker :: Config -> STM.TChan (IO (MH ())) -> BChan MHEvent -> IO () asyncWorker c r e = forever $ doAsyncWork c r e doAsyncWork :: Config -> STM.TChan (IO (MH ())) -> BChan MHEvent -> IO () doAsyncWork config requestChan eventChan = do startWork <- case configShowBackground config of Disabled -> return $ return () Active -> do chk <- STM.atomically $ STM.tryPeekTChan requestChan case chk of Nothing -> do writeBChan eventChan BGIdle return $ writeBChan eventChan $ BGBusy Nothing _ -> return $ return () ActiveCount -> do chk <- STM.atomically $ do chanCopy <- STM.cloneTChan requestChan let cntMsgs = do m <- STM.tryReadTChan chanCopy case m of Nothing -> return 0 Just _ -> (1 +) <$> cntMsgs cntMsgs case chk of 0 -> do writeBChan eventChan BGIdle return (writeBChan eventChan $ BGBusy (Just 1)) _ -> do writeBChan eventChan $ BGBusy (Just chk) return $ return () req <- STM.atomically $ STM.readTChan requestChan startWork res <- try req case res of Left e -> do when (not $ shouldIgnore e) $ do let err = case fromException e of Nothing -> AsyncErrEvent e Just mmErr -> ServerError mmErr writeBChan eventChan $ IEvent $ DisplayError err Right upd -> writeBChan eventChan (RespEvent upd) -- Filter for exceptions that we don't want to report to the user, -- probably because they are not actionable and/or contain no useful -- information. -- -- E.g. -- https://github.com/matterhorn-chat/matterhorn/issues/391 shouldIgnore :: SomeException -> Bool shouldIgnore e = let eStr = show e in or [ "getAddrInfo" `isInfixOf` eStr , "Network.Socket.recvBuf: timeout" `isInfixOf` eStr , "resource vanished" `isInfixOf` eStr ]
aisamanra/matterhorn
src/State/Setup/Threads.hs
bsd-3-clause
13,030
0
26
3,941
2,849
1,415
1,434
-1
-1
{-# LANGUAGE ExistentialQuantification, MultiParamTypeClasses, FlexibleInstances, StandaloneDeriving #-} ----------------------------------------------------------------------------------------- -- | -- Module : FRP.Yampa.Point2 -- Copyright : (c) Antony Courtney and Henrik Nilsson, Yale University, 2003 -- License : BSD-style (see the LICENSE file in the distribution) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : non-portable (GHC extensions) -- -- 2D point abstraction (R^2). -- ----------------------------------------------------------------------------------------- module FRP.Yampa.Point2 ( -- module AFRPVectorSpace, -- module AFRPAffineSpace, -- module AFRPVector2, Point2(..), -- Non-abstract, instance of AffineSpace point2X, -- :: RealFloat a => Point2 a -> a point2Y -- :: RealFloat a => Point2 a -> a ) where import FRP.Yampa.VectorSpace () import FRP.Yampa.AffineSpace import FRP.Yampa.Vector2 import FRP.Yampa.Forceable ------------------------------------------------------------------------------ -- 2D point, constructors and selectors. ------------------------------------------------------------------------------ data Point2 a = RealFloat a => Point2 !a !a deriving instance Eq a => Eq (Point2 a) deriving instance Show a => Show (Point2 a) point2X :: RealFloat a => Point2 a -> a point2X (Point2 x _) = x point2Y :: RealFloat a => Point2 a -> a point2Y (Point2 _ y) = y ------------------------------------------------------------------------------ -- Affine space instance ------------------------------------------------------------------------------ instance RealFloat a => AffineSpace (Point2 a) (Vector2 a) a where origin = Point2 0 0 (Point2 x y) .+^ v = Point2 (x + vector2X v) (y + vector2Y v) (Point2 x y) .-^ v = Point2 (x - vector2X v) (y - vector2Y v) (Point2 x1 y1) .-. (Point2 x2 y2) = vector2 (x1 - x2) (y1 - y2) ------------------------------------------------------------------------------ -- Forceable instance ------------------------------------------------------------------------------ instance RealFloat a => Forceable (Point2 a) where force = id
meimisaki/Yampa
src/FRP/Yampa/Point2.hs
bsd-3-clause
2,222
0
9
345
412
224
188
27
1
----------------------------------------------------------------------------- -- | -- Module : Data.SBV.BitVectors.Splittable -- Copyright : (c) Levent Erkok -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- -- Implementation of bit-vector concatanetation and splits ----------------------------------------------------------------------------- {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE BangPatterns #-} module Data.SBV.BitVectors.Splittable (Splittable(..), FromBits(..), checkAndConvert) where import Data.Bits (Bits(..)) import Data.Word (Word8, Word16, Word32, Word64) import Data.SBV.BitVectors.Operations import Data.SBV.BitVectors.Data import Data.SBV.BitVectors.Model infixr 5 # -- | Splitting an @a@ into two @b@'s and joining back. -- Intuitively, @a@ is a larger bit-size word than @b@, typically double. -- The 'extend' operation captures embedding of a @b@ value into an @a@ -- without changing its semantic value. -- -- Minimal complete definition: All, no defaults. class Splittable a b | b -> a where split :: a -> (b, b) (#) :: b -> b -> a extend :: b -> a genSplit :: (Integral a, Num b) => Int -> a -> (b, b) genSplit ss x = (fromIntegral ((ix `shiftR` ss) .&. mask), fromIntegral (ix .&. mask)) where ix = toInteger x mask = 2 ^ ss - 1 genJoin :: (Integral b, Num a) => Int -> b -> b -> a genJoin ss x y = fromIntegral ((ix `shiftL` ss) .|. iy) where ix = toInteger x iy = toInteger y -- concrete instances instance Splittable Word64 Word32 where split = genSplit 32 (#) = genJoin 32 extend b = 0 # b instance Splittable Word32 Word16 where split = genSplit 16 (#) = genJoin 16 extend b = 0 # b instance Splittable Word16 Word8 where split = genSplit 8 (#) = genJoin 8 extend b = 0 # b -- symbolic instances instance Splittable SWord64 SWord32 where split (SBV x) = (SBV (svExtract 63 32 x), SBV (svExtract 31 0 x)) SBV a # SBV b = SBV (svJoin a b) extend b = 0 # b instance Splittable SWord32 SWord16 where split (SBV x) = (SBV (svExtract 31 16 x), SBV (svExtract 15 0 x)) SBV a # SBV b = SBV (svJoin a b) extend b = 0 # b instance Splittable SWord16 SWord8 where split (SBV x) = (SBV (svExtract 15 8 x), SBV (svExtract 7 0 x)) SBV a # SBV b = SBV (svJoin a b) extend b = 0 # b -- | Unblasting a value from symbolic-bits. The bits can be given little-endian -- or big-endian. For a signed number in little-endian, we assume the very last bit -- is the sign digit. This is a bit awkward, but it is more consistent with the "reverse" view of -- little-big-endian representations -- -- Minimal complete definition: 'fromBitsLE' class FromBits a where fromBitsLE, fromBitsBE :: [SBool] -> a fromBitsBE = fromBitsLE . reverse -- | Construct a symbolic word from its bits given in little-endian fromBinLE :: (Num a, Bits a, SymWord a) => [SBool] -> SBV a fromBinLE = go 0 0 where go !acc _ [] = acc go !acc !i (x:xs) = go (ite x (setBit acc i) acc) (i+1) xs -- | Perform a sanity check that we should receive precisely the same -- number of bits as required by the resulting type. The input is little-endian checkAndConvert :: (Num a, Bits a, SymWord a) => Int -> [SBool] -> SBV a checkAndConvert sz xs | sz /= l = error $ "SBV.fromBits.SWord" ++ ssz ++ ": Expected " ++ ssz ++ " elements, got: " ++ show l | True = fromBinLE xs where l = length xs ssz = show sz instance FromBits SBool where fromBitsLE [x] = x fromBitsLE xs = error $ "SBV.fromBits.SBool: Expected 1 element, got: " ++ show (length xs) instance FromBits SWord8 where fromBitsLE = checkAndConvert 8 instance FromBits SInt8 where fromBitsLE = checkAndConvert 8 instance FromBits SWord16 where fromBitsLE = checkAndConvert 16 instance FromBits SInt16 where fromBitsLE = checkAndConvert 16 instance FromBits SWord32 where fromBitsLE = checkAndConvert 32 instance FromBits SInt32 where fromBitsLE = checkAndConvert 32 instance FromBits SWord64 where fromBitsLE = checkAndConvert 64 instance FromBits SInt64 where fromBitsLE = checkAndConvert 64
Copilot-Language/sbv-for-copilot
Data/SBV/BitVectors/Splittable.hs
bsd-3-clause
4,256
0
11
867
1,202
641
561
74
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE FlexibleContexts #-} module Yesod.Core.Internal.Run where import Yesod.Core.Internal.Response import Data.ByteString.Builder (toLazyByteString) import qualified Data.ByteString.Lazy as BL import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Logger (LogLevel (LevelError), LogSource, liftLoc) import Control.Monad.Trans.Resource (runResourceT, withInternalState, runInternalState, InternalState) import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import qualified Data.IORef as I import qualified Data.Map as Map import Data.Maybe (isJust, fromMaybe) import Data.Monoid (appEndo) import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8, decodeUtf8With) import Data.Text.Encoding.Error (lenientDecode) import Language.Haskell.TH.Syntax (Loc, qLocation) import qualified Network.HTTP.Types as H import Network.Wai import Network.Wai.Internal import System.Log.FastLogger (LogStr, toLogStr) import Yesod.Core.Content import Yesod.Core.Class.Yesod import Yesod.Core.Types import Yesod.Core.Internal.Request (parseWaiRequest, tooLargeResponse) import Yesod.Core.Internal.Util (getCurrentMaxExpiresRFC1123) import Yesod.Routes.Class (Route, renderRoute) import Control.DeepSeq (($!!), NFData) import UnliftIO.Exception -- | Convert a synchronous exception into an ErrorResponse toErrorHandler :: SomeException -> IO ErrorResponse toErrorHandler e0 = handleAny errFromShow $ case fromException e0 of Just (HCError x) -> evaluate $!! x _ -> errFromShow e0 -- | Generate an @ErrorResponse@ based on the shown version of the exception errFromShow :: SomeException -> IO ErrorResponse errFromShow x = do text <- evaluate (T.pack $ show x) `catchAny` \_ -> return (T.pack "Yesod.Core.Internal.Run.errFromShow: show of an exception threw an exception") return $ InternalError text -- | Do a basic run of a handler, getting some contents and the final -- @GHState@. The @GHState@ unfortunately may contain some impure -- exceptions, but all other synchronous exceptions will be caught and -- represented by the @HandlerContents@. basicRunHandler :: ToTypedContent c => RunHandlerEnv site site -> HandlerFor site c -> YesodRequest -> InternalState -> IO (GHState, HandlerContents) basicRunHandler rhe handler yreq resState = do -- Create a mutable ref to hold the state. We use mutable refs so -- that the updates will survive runtime exceptions. istate <- I.newIORef defState -- Run the handler itself, capturing any runtime exceptions and -- converting them into a @HandlerContents@ contents' <- catchAny (do res <- unHandlerFor handler (hd istate) tc <- evaluate (toTypedContent res) -- Success! Wrap it up in an @HCContent@ return (HCContent defaultStatus tc)) (\e -> case fromException e of Just e' -> return e' Nothing -> HCError <$> toErrorHandler e) -- Get the raw state and return state <- I.readIORef istate return (state, contents') where defState = GHState { ghsSession = reqSession yreq , ghsRBC = Nothing , ghsIdent = 1 , ghsCache = mempty , ghsCacheBy = mempty , ghsHeaders = mempty } hd istate = HandlerData { handlerRequest = yreq , handlerEnv = rhe , handlerState = istate , handlerResource = resState } -- | Convert an @ErrorResponse@ into a @YesodResponse@ handleError :: RunHandlerEnv sub site -> YesodRequest -> InternalState -> Map.Map Text S8.ByteString -> [Header] -> ErrorResponse -> IO YesodResponse handleError rhe yreq resState finalSession headers e0 = do -- Find any evil hidden impure exceptions e <- (evaluate $!! e0) `catchAny` errFromShow -- Generate a response, leveraging the updated session and -- response headers flip runInternalState resState $ do yar <- rheOnError rhe e yreq { reqSession = finalSession } case yar of YRPlain status' hs ct c sess -> let hs' = headers ++ hs status | status' == defaultStatus = getStatus e | otherwise = status' in return $ YRPlain status hs' ct c sess YRWai _ -> return yar YRWaiApp _ -> return yar -- | Convert a @HandlerContents@ into a @YesodResponse@ handleContents :: (ErrorResponse -> IO YesodResponse) -> Map.Map Text S8.ByteString -> [Header] -> HandlerContents -> IO YesodResponse handleContents handleError' finalSession headers contents = case contents of HCContent status (TypedContent ct c) -> do -- Check for impure exceptions hiding in the contents ec' <- evaluateContent c case ec' of Left e -> handleError' e Right c' -> return $ YRPlain status headers ct c' finalSession HCError e -> handleError' e HCRedirect status loc -> do let disable_caching x = Header "Cache-Control" "no-cache, must-revalidate" : Header "Expires" "Thu, 01 Jan 1970 05:05:05 GMT" : x hs = (if status /= H.movedPermanently301 then disable_caching else id) $ Header "Location" (encodeUtf8 loc) : headers return $ YRPlain status hs typePlain emptyContent finalSession HCSendFile ct fp p -> return $ YRPlain H.status200 headers ct (ContentFile fp p) finalSession HCCreated loc -> return $ YRPlain H.status201 (Header "Location" (encodeUtf8 loc) : headers) typePlain emptyContent finalSession HCWai r -> return $ YRWai r HCWaiApp a -> return $ YRWaiApp a -- | Evaluate the given value. If an exception is thrown, use it to -- replace the provided contents and then return @mempty@ in place of the -- evaluated value. evalFallback :: (Monoid w, NFData w) => HandlerContents -> w -> IO (w, HandlerContents) evalFallback contents val = catchAny (fmap (, contents) (evaluate $!! val)) (fmap ((mempty, ) . HCError) . toErrorHandler) -- | Function used internally by Yesod in the process of converting a -- 'HandlerT' into an 'Application'. Should not be needed by users. runHandler :: ToTypedContent c => RunHandlerEnv site site -> HandlerFor site c -> YesodApp runHandler rhe@RunHandlerEnv {..} handler yreq = withInternalState $ \resState -> do -- Get the raw state and original contents (state, contents0) <- basicRunHandler rhe handler yreq resState -- Evaluate the unfortunately-lazy session and headers, -- propagating exceptions into the contents (finalSession, contents1) <- evalFallback contents0 (ghsSession state) (headers, contents2) <- evalFallback contents1 (appEndo (ghsHeaders state) []) contents3 <- (evaluate contents2) `catchAny` (fmap HCError . toErrorHandler) -- Convert the HandlerContents into the final YesodResponse handleContents (handleError rhe yreq resState finalSession headers) finalSession headers contents3 safeEh :: (Loc -> LogSource -> LogLevel -> LogStr -> IO ()) -> ErrorResponse -> YesodApp safeEh log' er req = do liftIO $ log' $(qLocation >>= liftLoc) "yesod-core" LevelError $ toLogStr $ "Error handler errored out: " ++ show er return $ YRPlain H.status500 [] typePlain (toContent ("Internal Server Error" :: S.ByteString)) (reqSession req) -- | Run a 'HandlerT' completely outside of Yesod. This -- function comes with many caveats and you shouldn't use it -- unless you fully understand what it's doing and how it works. -- -- As of now, there's only one reason to use this function at -- all: in order to run unit tests of functions inside 'HandlerT' -- but that aren't easily testable with a full HTTP request. -- Even so, it's better to use @wai-test@ or @yesod-test@ instead -- of using this function. -- -- This function will create a fake HTTP request (both @wai@'s -- 'Request' and @yesod@'s 'Request') and feed it to the -- @HandlerT@. The only useful information the @HandlerT@ may -- get from the request is the session map, which you must supply -- as argument to @runFakeHandler@. All other fields contain -- fake information, which means that they can be accessed but -- won't have any useful information. The response of the -- @HandlerT@ is completely ignored, including changes to the -- session, cookies or headers. We only return you the -- @HandlerT@'s return value. runFakeHandler :: (Yesod site, MonadIO m) => SessionMap -> (site -> Logger) -> site -> HandlerFor site a -> m (Either ErrorResponse a) runFakeHandler fakeSessionMap logger site handler = liftIO $ do ret <- I.newIORef (Left $ InternalError "runFakeHandler: no result") maxExpires <- getCurrentMaxExpiresRFC1123 let handler' = liftIO . I.writeIORef ret . Right =<< handler let yapp = runHandler RunHandlerEnv { rheRender = yesodRender site $ resolveApproot site fakeWaiRequest , rheRoute = Nothing , rheRouteToMaster = id , rheChild = site , rheSite = site , rheUpload = fileUpload site , rheLog = messageLoggerSource site $ logger site , rheOnError = errHandler , rheMaxExpires = maxExpires } handler' errHandler err req = do liftIO $ I.writeIORef ret (Left err) return $ YRPlain H.status500 [] typePlain (toContent ("runFakeHandler: errHandler" :: S8.ByteString)) (reqSession req) fakeWaiRequest = Request { requestMethod = "POST" , httpVersion = H.http11 , rawPathInfo = "/runFakeHandler/pathInfo" , rawQueryString = "" , requestHeaderHost = Nothing , requestHeaders = [] , isSecure = False , remoteHost = error "runFakeHandler-remoteHost" , pathInfo = ["runFakeHandler", "pathInfo"] , queryString = [] , requestBody = return mempty , vault = mempty , requestBodyLength = KnownLength 0 , requestHeaderRange = Nothing , requestHeaderReferer = Nothing , requestHeaderUserAgent = Nothing } fakeRequest = YesodRequest { reqGetParams = [] , reqCookies = [] , reqWaiRequest = fakeWaiRequest , reqLangs = [] , reqToken = Just "NaN" -- not a nonce =) , reqAccept = [] , reqSession = fakeSessionMap } _ <- runResourceT $ yapp fakeRequest I.readIORef ret yesodRunner :: (ToTypedContent res, Yesod site) => HandlerFor site res -> YesodRunnerEnv site -> Maybe (Route site) -> Application yesodRunner handler' YesodRunnerEnv {..} route req sendResponse | Just maxLen <- mmaxLen, KnownLength len <- requestBodyLength req, maxLen < len = sendResponse (tooLargeResponse maxLen len) | otherwise = do let dontSaveSession _ = return [] (session, saveSession) <- liftIO $ maybe (return (Map.empty, dontSaveSession)) (`sbLoadSession` req) yreSessionBackend maxExpires <- yreGetMaxExpires let mkYesodReq = parseWaiRequest req session (isJust yreSessionBackend) mmaxLen let yreq = case mkYesodReq of Left yreq' -> yreq' Right needGen -> needGen yreGen let ra = resolveApproot yreSite req let log' = messageLoggerSource yreSite yreLogger -- We set up two environments: the first one has a "safe" error handler -- which will never throw an exception. The second one uses the -- user-provided errorHandler function. If that errorHandler function -- errors out, it will use the safeEh below to recover. rheSafe = RunHandlerEnv { rheRender = yesodRender yreSite ra , rheRoute = route , rheRouteToMaster = id , rheChild = yreSite , rheSite = yreSite , rheUpload = fileUpload yreSite , rheLog = log' , rheOnError = safeEh log' , rheMaxExpires = maxExpires } rhe = rheSafe { rheOnError = runHandler rheSafe . errorHandler } yesodWithInternalState yreSite route $ \is -> do yreq' <- yreq yar <- runInternalState (runHandler rhe handler yreq') is yarToResponse yar saveSession yreq' req is sendResponse where mmaxLen = maximumContentLength yreSite route handler = yesodMiddleware handler' yesodRender :: Yesod y => y -> ResolvedApproot -> Route y -> [(Text, Text)] -- ^ url query string -> Text yesodRender y ar url params = decodeUtf8With lenientDecode $ BL.toStrict $ toLazyByteString $ fromMaybe (joinPath y ar ps $ params ++ params') (urlParamRenderOverride y url params) where (ps, params') = renderRoute url resolveApproot :: Yesod master => master -> Request -> ResolvedApproot resolveApproot master req = case approot of ApprootRelative -> "" ApprootStatic t -> t ApprootMaster f -> f master ApprootRequest f -> f master req
s9gf4ult/yesod
yesod-core/Yesod/Core/Internal/Run.hs
mit
14,837
0
20
4,813
2,957
1,570
1,387
286
9
import System.Directory import System.FilePath import Text.XML.Light import System.IO import System.IO.Temp (withTempDirectory) import System.Process import Text.TeXMath import System.Exit import Control.Applicative import Control.Monad import GHC.IO.Encoding (setLocaleEncoding) import qualified Data.Text as T import qualified Data.Text.IO as T import Data.List (intercalate) import Data.List.Split (splitWhen) import System.Environment (getArgs) -- strict version of readFile readFile' :: FilePath -> IO String readFile' f = T.unpack <$> T.readFile f data Status = Pass FilePath FilePath | Fail FilePath FilePath | Error FilePath FilePath deriving (Eq, Show) type Ext = String readers :: [(Ext, String -> Either String [Exp])] readers = [ (".tex", readTeX) , (".mml", readMathML) , (".omml", readOMML) ] writers :: [(Ext, [Exp] -> String)] writers = [ (".mml", ppTopElement . writeMathML DisplayBlock) , (".tex", writeTeX) , (".omml", ppTopElement . writeOMML DisplayBlock) ] -- when called with --round-trip, JUST do round trip tests. -- otherwise omit them. main :: IO () main = do args <- getArgs let roundTrip = "--round-trip" `elem` args let regen = "--regenerate-tests" `elem` args setLocaleEncoding utf8 setCurrentDirectory "tests" statuses <- if roundTrip then do texs <- runRoundTrip "tex" writeTeX readTeX ommls <- runRoundTrip "omml" (ppTopElement . writeOMML DisplayBlock) readOMML mathmls <- runRoundTrip "mmml" (ppTopElement . writeMathML DisplayBlock) readMathML return $ texs ++ ommls ++ mathmls else (++) <$> (concat <$> mapM (uncurry (runReader regen)) readers) <*> (concat <$> mapM (uncurry (runWriter regen)) writers) let passes = length $ filter isPass statuses let failures = length statuses - passes putStrLn $ show passes ++ " tests passed, " ++ show failures ++ " failed." if all isPass statuses then exitWith ExitSuccess else exitWith $ ExitFailure failures printPass :: FilePath -> FilePath -> IO () printPass _inp _out = return () -- putStrLn $ "PASSED: " ++ inp ++ " ==> " ++ out -- Second parameter is Left format (for round-trip) or Right output file. printFail :: FilePath -> Either String FilePath -> String -> IO () printFail inp out actual = withTempDirectory "." ((either (const inp) id out) ++ ".") $ \tmpDir -> do -- break native files at commas for easier diffing let breakAtCommas = case out of Left _ -> intercalate ",\n" . splitWhen (==',') Right f | takeExtension f == ".native" -> intercalate ",\n" . splitWhen (==',') _ -> id putStrLn $ "FAILED: " ++ inp ++ " ==> " ++ either (\x -> "round trip via " ++ x) id out readFile' (either (const inp) id out) >>= writeFile (tmpDir </> "expected") . ensureFinalNewline . breakAtCommas writeFile (tmpDir </> "actual") $ ensureFinalNewline $ breakAtCommas actual hFlush stdout _ <- runProcess "diff" ["-u", tmpDir </> "expected", tmpDir </> "actual"] Nothing Nothing Nothing Nothing Nothing >>= waitForProcess putStrLn "" printError :: FilePath -> FilePath -> String -> IO () printError inp out msg = putStrLn $ "ERROR: " ++ inp ++ " ==> " ++ out ++ "\n" ++ msg ensureFinalNewline :: String -> String ensureFinalNewline "" = "" ensureFinalNewline xs = if last xs == '\n' then xs else xs ++ "\n" isPass :: Status -> Bool isPass (Pass _ _) = True isPass _ = False runReader :: Bool -> String -> (String -> Either String [Exp]) -> IO [Status] runReader regen ext f = do input <- filter (\x -> takeExtension x == ext) <$> getDirectoryContents "./src" let input' = map ("src" </>) input mapM (\inp -> runReaderTest regen (\x -> show <$> f x) inp (rename inp)) input' where rename x = replaceExtension (replaceDirectory x ("./readers" </> (tail ext))) "native" runWriter :: Bool -> String -> ([Exp] -> String) -> IO [Status] runWriter regen ext f = do mmls <- map ("./readers/mml/"++) <$> getDirectoryContents "./readers/mml" texs <- map ("./readers/tex/"++) <$> getDirectoryContents "./readers/tex" let sources = mmls ++ texs let inputs = [x | x <- sources, takeExtension x == ".native"] mapM (\inp -> runWriterTest regen f inp ("./writers/" ++ takeBaseName inp ++ ext)) inputs runRoundTrip :: String -> ([Exp] -> String) -> (String -> Either String [Exp]) -> IO [Status] runRoundTrip fmt writer reader = do inps <- filter (\x -> takeExtension x == ".native") <$> map (("./readers/" ++ fmt ++ "/") ++) <$> getDirectoryContents ("./readers/" ++ fmt) mapM (runRoundTripTest fmt writer reader) inps runWriterTest :: Bool -> ([Exp] -> String) -> FilePath -> FilePath -> IO Status runWriterTest regen f input output = do rawnative <- readFile' input native <- case reads rawnative of ((x,_):_) -> return x [] -> error $ "Could not read " ++ input let result = ensureFinalNewline $ f native when regen $ writeFile output result out_t <- ensureFinalNewline <$> readFile' output if result == out_t then printPass input output >> return (Pass input output) else printFail input (Right output) result >> return (Fail input output) runReaderTest :: Bool -> (String -> Either String String) -> FilePath -> FilePath -> IO Status runReaderTest regen fn input output = do inp_t <- readFile' input let result = ensureFinalNewline <$> fn inp_t when regen $ writeFile output (either (const "") id result) out_t <- ensureFinalNewline <$> readFile' output case result of Left msg -> printError input output msg >> return (Error input output) Right r | r == out_t -> printPass input output >> return (Pass input output) | otherwise -> printFail input (Right output) r >> return (Fail input output) runRoundTripTest :: String -> ([Exp] -> String) -> (String -> Either String [Exp]) -> FilePath -> IO Status runRoundTripTest fmt writer reader input = do rawnative <- readFile' input native <- case reads rawnative of ((x,_):_) -> return x [] -> error $ "Could not read " ++ input let rendered = ensureFinalNewline $ writer native case reader rendered of Left msg -> printError input input msg >> return (Error input input) Right r | r == native -> printPass input input >> return (Pass input input) | otherwise -> printFail input (Left fmt) (show r) >> return (Fail input input)
beni55/texmath
tests/test-texmath.hs
gpl-2.0
7,192
1
19
2,123
2,315
1,155
1,160
158
3
module Llvm.AsmHirConversion (module Llvm.AsmHirConversion.AsmToHir ,module Llvm.AsmHirConversion.HirToAsm ,module Llvm.AsmHirConversion.LabelMapM ) where import Llvm.AsmHirConversion.AsmToHir import Llvm.AsmHirConversion.HirToAsm import Llvm.AsmHirConversion.LabelMapM (IdLabelMap(..),a2h,invertMap)
mlite/hLLVM
src/Llvm/AsmHirConversion.hs
bsd-3-clause
329
0
6
45
62
42
20
7
0
{-# LANGUAGE FlexibleContexts #-} -- | Type checking for FKL expressions module Database.DSH.FKL.Typing ( inferFKLTy ) where import Control.Monad.Except import Control.Monad.Reader import Data.List import qualified Data.List.NonEmpty as N import Text.Printf import Database.DSH.FKL.Lang import Database.DSH.Common.Lang import Database.DSH.Common.Type import Database.DSH.Common.Pretty import Database.DSH.Common.Nat -------------------------------------------------------------------------------- -- Typing infrastructure type TyEnv = [(Ident, Type)] expTyErr :: FExpr -> String -> Typing a expTyErr a msg = throwError $ printf "FKL type inference failed in expression\n>>>\n%s\n<<<\n\n%s" (pp a) msg opTyErr :: String -> [Type] -> Typing a opTyErr msg tys = throwError $ printf "FKL type error: %s {%s}" msg tyMsg where tyMsg = concat $ intersperse "," $ fmap pp tys bindTy :: Ident -> Type -> TyEnv -> TyEnv bindTy x ty tyEnv = (x,ty) : tyEnv lookupTy :: Ident -> Typing Type lookupTy x = do tyEnv <- ask case lookup x tyEnv of Just ty -> pure ty Nothing -> throwError $ printf "FKL type error: %s not in type env %s" x (pp tyEnv) type Typing = ReaderT TyEnv (Either String) -------------------------------------------------------------------------------- -- Monad type predicates elemTy :: Type -> Typing Type elemTy (ListT ty) = pure ty elemTy ty = throwError $ printf "FKL type error: %s not a list type" (pp ty) listTy :: Type -> Typing () listTy (ListT _) = pure () listTy ty = throwError $ printf "FKL type error: %s not a list type" (pp ty) numTy :: Type -> Typing () numTy (ScalarT IntT) = pure () numTy (ScalarT DoubleT) = pure () numTy (ScalarT DecimalT) = pure () numTy ty = throwError $ printf "FKL type error: %s not a numeric type" (pp ty) boolTy :: Type -> Typing () boolTy (ScalarT BoolT) = pure () boolTy ty = throwError $ printf "FKL type error: %s not boolean" (pp ty) fractTy :: Type -> Typing () fractTy (ScalarT DoubleT) = pure () fractTy (ScalarT DecimalT) = pure () fractTy ty = throwError $ printf "FKL type error: %s not a fractional type" (pp ty) scalarTy :: Type -> Typing ScalarType scalarTy (ScalarT sty) = pure sty scalarTy ty = throwError $ printf "FKL type error: %s not a scalar type" (pp ty) -------------------------------------------------------------------------------- -- Type inference aggTy :: Type -> AggrFun -> Typing Type aggTy ty a = case a of Length _ -> pure $ ScalarT IntT Sum -> numTy ty >> pure ty Avg -> fractTy ty >> pure ty And -> boolTy ty >> pure ty Or -> boolTy ty >> pure ty Maximum -> void (scalarTy ty) >> pure ty Minimum -> void (scalarTy ty) >> pure ty -- | Typing of unary builtins tyPrim1 :: Prim1 -> Type -> Typing Type tyPrim1 Singleton ty = pure $ ListT ty tyPrim1 Only ty = catchError (elemTy ty) (const $ opTyErr "only" [ty]) tyPrim1 Concat ty = case ty of ListT (ListT eTy) -> pure $ ListT eTy _ -> opTyErr "concat" [ty] tyPrim1 Reverse ty = catchError (listTy ty) (const $ opTyErr "reverse" [ty]) >> pure ty tyPrim1 Nub ty = catchError (listTy ty) (const $ opTyErr "nub" [ty]) >> pure ty tyPrim1 Number ty = flip catchError (const $ opTyErr "number" [ty]) $ do eTy <- elemTy ty pure $ ListT $ TupleT [eTy, ScalarT IntT] tyPrim1 Sort ty = do case ty of ListT (TupleT [ty1, _]) -> pure $ ListT ty1 _ -> opTyErr "sort" [ty] tyPrim1 Group ty = do case ty of ListT (TupleT [ty1, ty2]) -> pure $ ListT (TupleT [ty2, ListT ty1]) _ -> opTyErr "group" [ty] tyPrim1 (GroupAgg as) ty = case ty of ListT (TupleT [ty1, ty2]) -> do aTys <- runReaderT (mapM aggrTy $ N.toList $ getNE as) (Just ty1) pure $ ListT (TupleT $ [ty2, ListT ty1] ++ aTys) _ -> opTyErr "groupagg" [ty] tyPrim1 (TupElem i) ty = case ty of TupleT tys -> maybe (opTyErr (printf "_.%d" (tupleIndex i)) [ty]) pure (safeIndex i tys) _ -> opTyErr (printf "_.%d" (tupleIndex i)) [ty] tyPrim1 (Agg a) ty = flip catchError (const $ opTyErr (pp a) [ty]) $ do eTy <- elemTy ty aggTy eTy a tyPrim1 Restrict ty = case ty of ListT (TupleT [ty1, ScalarT BoolT]) -> pure $ ListT ty1 _ -> opTyErr "restrict" [ty] -- | Typing of binary builtins tyPrim2 :: Prim2 -> Type -> Type -> Typing Type tyPrim2 Append ty1 ty2 = if isList ty1 && isList ty2 && ty1 == ty2 then pure ty1 else opTyErr "append" [ty1, ty2] tyPrim2 Zip ty1 ty2 = flip catchError (const $ opTyErr "zip" [ty1,ty2]) $ do ety1 <- elemTy ty1 ety2 <- elemTy ty2 pure $ ListT $ TupleT [ety1, ety2] tyPrim2 CartProduct ty1 ty2 = flip catchError (const $ opTyErr "cartproduct" [ty1,ty2]) $ do ety1 <- elemTy ty1 ety2 <- elemTy ty2 pure $ ListT $ TupleT [ety1, ety2] tyPrim2 (ThetaJoin p) ty1 ty2 = flip catchError (const $ opTyErr "thetajoin" [ty1,ty2]) $ do ety1 <- elemTy ty1 ety2 <- elemTy ty2 checkPredTy ety1 ety2 p pure $ ListT $ TupleT [ety1, ety2] tyPrim2 (NestJoin p) ty1 ty2 = flip catchError (const $ opTyErr "nestjoin" [ty1, ty2]) $ do ety1 <- elemTy ty1 ety2 <- elemTy ty2 checkPredTy ety1 ety2 p pure $ ListT $ TupleT [ety1, ListT (TupleT [ety1, ety2])] tyPrim2 (SemiJoin p) ty1 ty2 = flip catchError (const $ opTyErr "semijoin" [ty1, ty2]) $ do ety1 <- elemTy ty1 ety2 <- elemTy ty2 checkPredTy ety1 ety2 p pure $ ListT ety1 tyPrim2 (AntiJoin p) ty1 ty2 = flip catchError (const $ opTyErr "antijoin" [ty1, ty2]) $ do ety1 <- elemTy ty1 ety2 <- elemTy ty2 checkPredTy ety1 ety2 p pure $ ListT ety1 tyPrim2 (GroupJoin p as) ty1 ty2 = flip catchError (const $ opTyErr "groupjoin" [ty1, ty2]) $ do ety1 <- elemTy ty1 ety2 <- elemTy ty2 checkPredTy ety1 ety2 p let tupTy = TupleT [ety1, ety2] aTys <- runReaderT (mapM aggrTy $ N.toList $ getNE as) (Just tupTy) case aTys of [aTy] -> pure $ ListT $ TupleT [ety1, aTy] _ -> pure $ ListT $ TupleT $ ety1 : aTys tyPrim2 Dist ty1 ty2 = flip catchError (const $ opTyErr "dist" [ty1, ty2]) $ do if isList ty2 then pure $ ListT ty1 else throwError "FKL.Typing.dist: not a list" tyPrim3 :: Prim3 -> Type -> Type -> Type -> Typing Type tyPrim3 Combine ty1 ty2 ty3 = flip catchError (const $ opTyErr "combine" [ty1, ty2, ty3]) $ do eTy1 <- elemTy ty1 eTy2 <- elemTy ty2 eTy3 <- elemTy ty3 if eTy1 == ScalarT BoolT && eTy2 == eTy3 then pure $ ListT eTy2 else throwError "FKL.Typing.combine: type error" tyPrim3Lift :: Lifted -> Prim3 -> Type -> Type -> Type -> Typing Type tyPrim3Lift Lifted p ty1 ty2 ty3 = do eTy1 <- elemTy ty1 eTy2 <- elemTy ty2 eTy3 <- elemTy ty3 ListT <$> tyPrim3 p eTy1 eTy2 eTy3 tyPrim3Lift NotLifted p ty1 ty2 ty3 = tyPrim3 p ty1 ty2 ty3 tyPrim2Lift :: Lifted -> Prim2 -> Type -> Type -> Typing Type tyPrim2Lift Lifted p ty1 ty2 = do eTy1 <- elemTy ty1 eTy2 <- elemTy ty2 ListT <$> tyPrim2 p eTy1 eTy2 tyPrim2Lift NotLifted p ty1 ty2 = tyPrim2 p ty1 ty2 tyPrim1Lift :: Lifted -> Prim1 -> Type -> Typing Type tyPrim1Lift Lifted p ty = do eTy <- elemTy ty ListT <$> tyPrim1 p eTy tyPrim1Lift NotLifted p ty = tyPrim1 p ty tyMkTuple :: Type -> Lifted -> [FExpr] -> Typing Type tyMkTuple _ NotLifted es = TupleT <$> mapM inferTy es tyMkTuple tyAnn Lifted es = flip catchError (expTyErr $ MkTuple tyAnn Lifted es) $ do eTys <- mapM (\e -> inferTy e >>= elemTy) es pure $ ListT $ TupleT eTys tyBinOpLift :: Lifted -> ScalarBinOp -> Type -> Type -> Typing Type tyBinOpLift NotLifted o ty1 ty2 = case (ty1, ty2) of (ScalarT sTy1, ScalarT sTy2) -> ScalarT <$> inferBinOpScalar sTy1 sTy2 o _ -> opTyErr (pp o) [ty1, ty2] tyBinOpLift Lifted o ty1 ty2 = do eTy1 <- elemTy ty1 eTy2 <- elemTy ty2 case (eTy1, eTy2) of (ScalarT sTy1, ScalarT sTy2) -> ListT <$> ScalarT <$> inferBinOpScalar sTy1 sTy2 o _ -> opTyErr (pp o) [ty1, ty2] tyUnOpLift :: Lifted -> ScalarUnOp -> Type -> Typing Type tyUnOpLift NotLifted o ty = case ty of ScalarT sTy -> ScalarT <$> inferUnOpScalar sTy o _ -> opTyErr (pp o) [ty] tyUnOpLift Lifted o ty = do eTy <- elemTy ty case eTy of ScalarT sTy -> ListT <$> ScalarT <$> inferUnOpScalar sTy o _ -> opTyErr (pp o) [ty] unwrapListType :: Nat -> Type -> Typing Type unwrapListType Zero t = pure t unwrapListType (Succ n') (ListT xt) = unwrapListType n' xt unwrapListType _ _ = throwError "NKL.Typing.forget" wrapListType :: Nat -> Type -> Type wrapListType Zero t = t wrapListType (Succ n') t = wrapListType n' (ListT t) tyShapeExt :: ShapeExt -> Typing Type tyShapeExt s@(Rep ty _ e) = catchError (void (inferTy e) >> pure ty) (expTyErr $ Ext s) tyShapeExt s@(Forget n _ e) = catchError (inferTy e >>= unwrapListType n) (expTyErr $ Ext s) tyShapeExt s@(Imprint n _ e1 e2) = flip catchError (expTyErr $ Ext s) $ do ty1 <- inferTy e1 ty2 <- inferTy e2 void $ unwrapListType n ty1 pure $ wrapListType n ty2 -- | Typing of FKL expressions inferTy :: FExpr -> Typing Type inferTy (Table _ _ schema) = pure $ ListT $ TupleT $ N.toList $ fmap (ScalarT . snd) $ tableCols schema inferTy a@(PApp1 _ p l e) = catchError (inferTy e >>= tyPrim1Lift l p) (expTyErr a) inferTy a@(PApp2 _ p l e1 e2) = do ty1 <- inferTy e1 ty2 <- inferTy e2 catchError (tyPrim2Lift l p ty1 ty2) (expTyErr a) inferTy a@(PApp3 _ p l e1 e2 e3) = do ty1 <- inferTy e1 ty2 <- inferTy e2 ty3 <- inferTy e3 catchError (tyPrim3Lift l p ty1 ty2 ty3) (expTyErr a) inferTy a@(BinOp _ o l e1 e2) = do ty1 <- inferTy e1 ty2 <- inferTy e2 catchError (tyBinOpLift l o ty1 ty2) (expTyErr a) inferTy a@(UnOp _ o l e) = do ty <- inferTy e catchError (tyUnOpLift l o ty) (expTyErr a) inferTy (Const ty _) = pure ty inferTy (Var _ x) = lookupTy x inferTy (MkTuple ty l es) = tyMkTuple ty l es inferTy (Let _ x e1 e2) = do ty1 <- inferTy e1 local (bindTy x ty1) $ inferTy e2 inferTy (Ext e) = tyShapeExt e -- | Infer the type of a FKL expression inferFKLTy :: FExpr -> Either String Type inferFKLTy e = runReaderT (inferTy e) []
ulricha/dsh
src/Database/DSH/FKL/Typing.hs
bsd-3-clause
10,923
0
16
3,149
4,249
2,063
2,186
240
7
module Lang.Hask ( module Lang.Hask.CPS , module Lang.Hask.Semantics ) where import Lang.Hask.CPS hiding (atom) import Lang.Hask.Semantics
davdar/maam
src/Lang/Hask.hs
bsd-3-clause
146
0
5
23
40
27
13
5
0
{-# LANGUAGE CPP, DeriveDataTypeable, DeriveFunctor, TemplateHaskell, FlexibleContexts, MultiParamTypeClasses, FlexibleInstances #-} module Language.Java.Paragon.Syntax ( module Language.Java.Paragon.Syntax, module Language.Java.Paragon.Annotated ) where import Data.Data import Language.Java.Paragon.Annotated import Language.Java.Paragon.Interaction import Language.Java.Paragon.SourcePos import qualified Data.ByteString.Char8 as B syntaxModule :: String syntaxModule = libraryBase ++ ".Syntax" ----------------------------------------------------------------------- -- Packages -- | A compilation unit is the top level syntactic goal symbol of a Java program -- This usually corresponds to a single .java source file that may start with -- a package declaration, followed by a (possibly empty) list of imports and -- a (usually non-empty) list of type declaration, where a type is a class -- or interface. -- Note that the paragon compiler currently only accepts a single type per -- compilation unit and does not yet suport enums, although files containing -- enums can be parsed data CompilationUnit a = CompilationUnit a (Maybe (PackageDecl a)) [ImportDecl a] [TypeDecl a] #ifdef __GLASGOW_HASKELL__ deriving (Eq,Ord,Show,Typeable,Data,Functor) #else deriving (Eq,Ord,Show) #endif -- | A package declaration appears within a compilation unit to indicate the package to which the compilation unit belongs. data PackageDecl a = PackageDecl a (Name a) #ifdef __GLASGOW_HASKELL__ deriving (Eq,Ord,Show,Typeable,Data,Functor) #else deriving (Eq,Ord,Show) #endif -- | An import declaration allows a static member or a named type to be referred -- to by a single unqualified identifier. -- The first argument signals whether the declaration only imports static -- members. -- The last argument signals whether the declaration brings all names in the -- named type or package, or only brings a single name into scope. data ImportDecl a = SingleTypeImport a (Name a) -- ^Import a single type (class/interface/enum) | TypeImportOnDemand a (Name a) -- ^Bring all types of package into scope, e.g. import java.lang.util.* | SingleStaticImport a (Name a) (Ident a) -- ^Single static import, e.g. import static java.lang.Math.PI | StaticImportOnDemand a (Name a) -- ^Static import of all members, e.g. import static java.lang.Math.* deriving (Eq,Ord,Show,Typeable,Data,Functor) ----------------------------------------------------------------------- -- Declarations -- | A type declaration declares a class type or an interface type. data TypeDecl a = ClassTypeDecl a (ClassDecl a) | InterfaceTypeDecl a (InterfaceDecl a) deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A class declaration specifies a new named reference type. -- Note that the compiler does not actually deal with enums yet! data ClassDecl a = ClassDecl a [Modifier a] (Ident a) [TypeParam a] (Maybe (ClassType a)) [ClassType a] (ClassBody a) -- ^Fields: Class modifiers, class identifier, type params, super class, -- if any, list of implemented interfaces, class body | EnumDecl a [Modifier a] (Ident a) [ClassType a] (EnumBody a) deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A class body may contain declarations of members of the class, that is, -- fields, classes, interfaces and methods. -- A class body may also contain instance initializers, static -- initializers, and declarations of constructors for the class. data ClassBody a = ClassBody a [Decl a] deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | The body of an enum type may contain enum constants. data EnumBody a = EnumBody a [EnumConstant a] [Decl a] deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | An enum constant defines an instance of the enum type. data EnumConstant a = EnumConstant a (Ident a) [Argument a] (Maybe (ClassBody a)) deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | An interface declaration introduces a new reference type whose members -- are classes, interfaces, constants and abstract methods. This type has -- no implementation, but otherwise unrelated classes can implement it by -- providing implementations for its abstract methods. data InterfaceDecl a = InterfaceDecl a [Modifier a] (Ident a) [TypeParam a] [ClassType a] (InterfaceBody a) deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | The body of an interface may declare members of the interface. data InterfaceBody a = InterfaceBody a [MemberDecl a] deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A declaration is either a member declaration, or a declaration of an -- initializer, which may be static. data Decl a = MemberDecl a (MemberDecl a) | InitDecl a Bool (Block a) deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A class or interface member can be an inner class or interface, a field or -- constant, or a method or constructor. An interface may only have as members -- constants (not fields), abstract methods, and no constructors. data MemberDecl a -- | The variables of a class type are introduced by field declarations. = FieldDecl a [Modifier a] (Type a) [VarDecl a] -- | A method declares executable code that can be invoked, passing a fixed number of values as arguments. | MethodDecl a [Modifier a] [TypeParam a] (ReturnType a) (Ident a) [FormalParam a] [ExceptionSpec a] (MethodBody a) -- | A constructor is used in the creation of an object that is an instance of a class. | ConstructorDecl a [Modifier a] [TypeParam a] (Ident a) [FormalParam a] [ExceptionSpec a] (ConstructorBody a) -- | A member class is a class whose declaration is directly enclosed in another class or interface declaration. | MemberClassDecl a (ClassDecl a) -- | A member interface is an interface whose declaration is directly enclosed in another class or interface declaration. | MemberInterfaceDecl a (InterfaceDecl a) -- Paragon -- | A lock declaration is a special kind of field declaration. | LockDecl a [Modifier a] (Ident a) [RefType a] (Maybe (LockProperties a)) {- -- | A policy declaration - should be a field decl really. | PolicyDecl a [Modifier a] Ident Policy -} {- -- | An actor declaration is a special kind of field declaration. | ActorDecl [Modifier] Ident (Maybe VarInit) -} deriving (Eq,Ord,Show,Typeable,Data,Functor) -- int x; => VarDecl (VarId "x") Nothing -- int x = 1; => VarDecl (VarId "x") (Just ...) -- | A declaration of a variable, which may be explicitly initialized. data VarDecl a = VarDecl a (VarDeclId a) (Maybe (VarInit a)) deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | The name of a variable in a declaration, which may be an array. data VarDeclId a = VarId a (Ident a) | VarDeclArray a (VarDeclId a) -- ^ Multi-dimensional arrays are represented by nested applications of 'VarDeclArray' (Deprecated) deriving (Eq,Ord,Show,Typeable,Data,Functor) getVarDeclId :: VarDeclId a -> Ident a getVarDeclId (VarId _ ident) = ident getVarDeclId (VarDeclArray _ varDeclId) = getVarDeclId varDeclId -- | Explicit initializer for a variable declaration. data VarInit a = InitExp a (Exp a) | InitArray a (ArrayInit a) deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A formal parameter in method declaration. The last parameter -- for a given declaration may be marked as variable arity, -- indicated by the boolean argument. data FormalParam a = FormalParam a [Modifier a] (Type a) Bool (VarDeclId a) deriving (Eq,Ord,Show,Typeable,Data,Functor) getFormalParamId :: FormalParam a -> Ident a getFormalParamId (FormalParam _ _ _ _ varDeclId) = getVarDeclId varDeclId -- | A method body is either a block of code that implements the method or simply a -- semicolon, indicating the lack of an implementation (modelled by 'Nothing'). data MethodBody a = MethodBody a (Maybe (Block a)) deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | The first statement of a constructor body may be an explicit invocation of -- another constructor of the same class or of the direct superclass. data ConstructorBody a = ConstructorBody a (Maybe (ExplConstrInv a)) [BlockStmt a] deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | An explicit constructor invocation invokes another constructor of the -- same class, or a constructor of the direct superclass, which may -- be qualified to explicitly specify the newly created object's immediately -- enclosing instance. data ExplConstrInv a = ThisInvoke a [NonWildTypeArgument a] [Argument a] | SuperInvoke a [NonWildTypeArgument a] [Argument a] | PrimarySuperInvoke a (Exp a) [NonWildTypeArgument a] [Argument a] deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A modifier specifying properties of a given declaration. In general only -- a few of these modifiers are allowed for each declaration type, for instance -- a member type declaration may only specify one of public, private or protected. data Modifier a = Public a | Private a | Protected a | Abstract a | Final a | Static a | StrictFP a | Transient a | Volatile a | Native a | Typemethod a | Reflexive a | Transitive a | Symmetric a | Readonly a | Notnull a | Reads a (Policy a) | Writes a (Policy a) | Opens a [Lock a] | Closes a [Lock a] | Expects a [Lock a] deriving (Eq,Ord,Show,Typeable,Data,Functor) isMethodStatic :: [Modifier a] -> Bool isMethodStatic ms = Static () `elem` removeAnnotationMany ms ----------------------------------------------------------------------- -- Statements -- | A block is a sequence of statements, local class declarations -- and local variable declaration statements within braces. data Block a = Block a [BlockStmt a] deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A block statement is either a normal statement, a local -- class declaration or a local variable declaration. data BlockStmt a = BlockStmt a (Stmt a) | LocalClass a (ClassDecl a) | LocalVars a [Modifier a] (Type a) [VarDecl a] -- Paragon | LocalLock a [Modifier a] (Ident a) [RefType a] (Maybe (LockProperties a)) {- | LocalPolicy [Modifier] Ident Policy | LocalActor [Modifier] Ident (Maybe VarInit) -} deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A Java statement. data Stmt a -- | A statement can be a nested block. = StmtBlock a (Block a) -- | The @if-then@ statement allows conditional execution of a statement. | IfThen a (Exp a) (Stmt a) -- | The @if-then-else@ statement allows conditional choice of two statements, executing one or the other but not both. | IfThenElse a (Exp a) (Stmt a) (Stmt a) -- | The @while@ statement executes an expression and a statement repeatedly until the value of the expression is false. | While a (Exp a) (Stmt a) -- | The basic @for@ statement executes some initialization code, then executes an expression, a statement, and some -- update code repeatedly until the value of the expression is false. | BasicFor a (Maybe (ForInit a)) (Maybe (Exp a)) (Maybe [Exp a]) (Stmt a) -- | The enhanced @for@ statement iterates over an array or a value of a class that implements the @iterator@ interface. | EnhancedFor a [Modifier a] (Type a) (Ident a) (Exp a) (Stmt a) -- | An empty statement does nothing. | Empty a -- | Certain kinds of expressions may be used as statements by following them with semicolons: -- assignments, pre- or post-inc- or decrementation, method invocation or class instance -- creation expressions. | ExpStmt a (Exp a) -- | An assertion is a statement containing a boolean expression, where an error is reported if the expression -- evaluates to false. | Assert a (Exp a) (Maybe (Exp a)) -- | The switch statement transfers control to one of several statements depending on the value of an expression. | Switch a (Exp a) [SwitchBlock a] -- | The @do@ statement executes a statement and an expression repeatedly until the value of the expression is false. | Do a (Stmt a) (Exp a) -- | A @break@ statement transfers control out of an enclosing statement. | Break a (Maybe (Ident a)) -- | A @continue@ statement may occur only in a while, do, or for statement. Control passes to the loop-continuation -- point of that statement. | Continue a (Maybe (Ident a)) -- A @return@ statement returns control to the invoker of a method or constructor. | Return a (Maybe (Exp a)) -- | A @synchronized@ statement acquires a mutual-exclusion lock on behalf of the executing thread, executes a block, -- then releases the lock. While the executing thread owns the lock, no other thread may acquire the lock. | Synchronized a (Exp a) (Block a) -- | A @throw@ statement causes an exception to be thrown. | Throw a (Exp a) -- | A try statement executes a block. If a value is thrown and the try statement has one or more catch clauses that -- can catch it, then control will be transferred to the first such catch clause. If the try statement has a finally -- clause, then another block of code is executed, no matter whether the try block completes normally or abruptly, -- and no matter whether a catch clause is first given control. | Try a (Block a) [Catch a] (Maybe {- finally -} (Block a)) -- | Statements may have label prefixes. | Labeled a (Ident a) (Stmt a) -- Paragon -- | Locks can be opened or closed. | Open a (Lock a) | Close a (Lock a) | OpenBlock a (Lock a) (Block a) | CloseBlock a (Lock a) (Block a) {- -- A @when@ statement is a variant of @if@ that only tests whether locks are open. | WhenThen Lock Stmt | WhenThenElse Lock Stmt Stmt -} deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | If a value is thrown and the try statement has one or more catch clauses that can catch it, then control will be -- transferred to the first such catch clause. data Catch a = Catch a (FormalParam a) (Block a) deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A block of code labelled with a @case@ or @default@ within a @switch@ statement. data SwitchBlock a = SwitchBlock a (SwitchLabel a) [BlockStmt a] deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A label within a @switch@ statement. data SwitchLabel a -- | The expression contained in the @case@ must be a 'Lit' or an @enum@ constant. = SwitchCase a (Exp a) | Default a deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | Initialization code for a basic @for@ statement. data ForInit a = ForLocalVars a [Modifier a] (Type a) [VarDecl a] | ForInitExps a [Exp a] deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | An exception type has to be a class type or a type variable. type ExceptionType a = RefType a -- restricted to ClassType or TypeVariable data ExceptionSpec a = ExceptionSpec a [Modifier a] (ExceptionType a) deriving (Eq,Ord,Show,Typeable,Data,Functor) ----------------------------------------------------------------------- -- Expressions -- | Arguments to methods and constructors are expressions. type Argument a = (Exp a) -- | A Java expression. data Exp a -- | A literal denotes a fixed, unchanging value. = Lit a (Literal a) -- | A class literal, which is an expression consisting of the name of a class, interface, array, -- or primitive type, or the pseudo-type void (modelled by 'Nothing'), followed by a `.' and the token class. | ClassLit a (Maybe (Type a)) -- | The keyword @this@ denotes a value that is a reference to the object for which the instance method -- was invoked, or to the object being constructed. | This a -- | Any lexically enclosing instance can be referred to by explicitly qualifying the keyword this. | ThisClass a (Name a) -- | A parenthesized expression is a primary expression whose type is the type of the contained expression -- and whose value at run time is the value of the contained expression. If the contained expression -- denotes a variable then the parenthesized expression also denotes that variable. | Paren a (Exp a) -- | A class instance creation expression is used to create new objects that are instances of classes. -- | The first argument is a list of non-wildcard type arguments to a generic constructor. -- What follows is the type to be instantiated, the list of arguments passed to the constructor, and -- optionally a class body that makes the constructor result in an object of an /anonymous/ class. | InstanceCreation a [TypeArgument a] (ClassType a) [Argument a] (Maybe (ClassBody a)) -- | A qualified class instance creation expression enables the creation of instances of inner member classes -- and their anonymous subclasses. | QualInstanceCreation a (Exp a) [TypeArgument a] (Ident a) [Argument a] (Maybe (ClassBody a)) -- | An array instance creation expression is used to create new arrays. The last argument denotes the number -- of dimensions that have no explicit length given. These dimensions must be given last. | ArrayCreate a (Type a) [(Exp a, Maybe (Policy a))] [Maybe (Policy a)] -- | An array instance creation expression may come with an explicit initializer. Such expressions may not -- be given explicit lengths for any of its dimensions. | ArrayCreateInit a (Type a) [Maybe (Policy a)] (ArrayInit a) -- | A field access expression. | FieldAccess a (FieldAccess a) -- | A method invocation expression. | MethodInv a (MethodInvocation a) -- | An array access expression refers to a variable that is a component of an array. | ArrayAccess a (ArrayIndex a) -- | An expression name, e.g. a variable. | ExpName a (Name a) -- | Post-incrementation expression, i.e. an expression followed by @++@. | PostIncrement a (Exp a) -- | Post-decrementation expression, i.e. an expression followed by @--@. | PostDecrement a (Exp a) -- | Pre-incrementation expression, i.e. an expression preceded by @++@. | PreIncrement a (Exp a) -- | Pre-decrementation expression, i.e. an expression preceded by @--@. | PreDecrement a (Exp a) -- | Unary plus, the promotion of the value of the expression to a primitive numeric type. | PrePlus a (Exp a) -- | Unary minus, the promotion of the negation of the value of the expression to a primitive numeric type. | PreMinus a (Exp a) -- | Unary bitwise complementation: note that, in all cases, @~x@ equals @(-x)-1@. | PreBitCompl a (Exp a) -- | Logical complementation of boolean values. | PreNot a (Exp a) -- | A cast expression converts, at run time, a value of one numeric type to a similar value of another -- numeric type; or confirms, at compile time, that the type of an expression is boolean; or checks, -- at run time, that a reference value refers to an object whose class is compatible with a specified -- reference type. | Cast a (Type a) (Exp a) -- | The application of a binary operator to two operand expressions. | BinOp a (Exp a) (Op a) (Exp a) -- | Testing whether the result of an expression is an instance of some reference type. | InstanceOf a (Exp a) (RefType a) -- | The conditional operator @? :@ uses the boolean value of one expression to decide which of two other -- expressions should be evaluated. | Cond a (Exp a) (Exp a) (Exp a) -- | Assignment of the result of an expression to a variable. | Assign a (Lhs a) (AssignOp a) (Exp a) -- Paragon | PolicyExp a (PolicyExp a) -- | PolicyOf (Ident a) | LockExp a (Lock a) -- Quasi-quotation | AntiQExp a String deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A literal denotes a fixed, unchanging value. data Literal a = Int a Integer | Word a Integer | Float a Double | Double a Double | Boolean a Bool | Char a Char | String a String | Null a deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A binary infix operator. data Op a = Mult a | Div a | Rem a | Add a | Sub a | LShift a | RShift a | RRShift a | LThan a | GThan a | LThanE a | GThanE a | Equal a | NotEq a | And a | Or a | Xor a | CAnd a | COr a deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | An assignment operator. data AssignOp a = EqualA a | MultA a | DivA a | RemA a | AddA a | SubA a | LShiftA a | RShiftA a | RRShiftA a | AndA a | XorA a | OrA a deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | The left-hand side of an assignment expression. This operand may be a named variable, such as a local -- variable or a field of the current object or class, or it may be a computed variable, as can result from -- a field access or an array access. data Lhs a = NameLhs a (Name a) -- ^ Assign to a variable | FieldLhs a (FieldAccess a) -- ^ Assign through a field access | ArrayLhs a (ArrayIndex a) -- ^ Assign to an array deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | Array access data ArrayIndex a = ArrayIndex a (Exp a) (Exp a) -- ^ Index into an array deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A field access expression may access a field of an object or array, a reference to which is the value -- of either an expression or the special keyword super. data FieldAccess a = PrimaryFieldAccess a (Exp a) (Ident a) -- ^ Accessing a field of an object or array computed from an expression. | SuperFieldAccess a (Ident a) -- ^ Accessing a field of the superclass. | ClassFieldAccess a (Name a) (Ident a) -- ^ Accessing a (static) field of a named class. deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A method invocation expression is used to invoke a class or instance method. data MethodInvocation a -- | Invoking a specific named method. = MethodCallOrLockQuery a (Name a) [Argument a] -- | Invoking a method of a class computed from a primary expression, giving arguments for any generic type parameters. | PrimaryMethodCall a (Exp a) [NonWildTypeArgument a] (Ident a) [Argument a] -- | Invoking a method of the super class, giving arguments for any generic type parameters. | SuperMethodCall a [NonWildTypeArgument a] (Ident a) [Argument a] -- | Invoking a method of the superclass of a named class, giving arguments for any generic type parameters. | ClassMethodCall a (Name a) [NonWildTypeArgument a] (Ident a) [Argument a] -- | Invoking a method of a named type, giving arguments for any generic type parameters. | TypeMethodCall a (Name a) [NonWildTypeArgument a] (Ident a) [Argument a] deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | An array initializer may be specified in a declaration, or as part of an array creation expression, creating an -- array and providing some initial values data ArrayInit a = ArrayInit a [VarInit a] deriving (Eq,Ord,Show,Typeable,Data,Functor) ----------------------------------------------------------------------- -- Types data ReturnType a = VoidType a | LockType a | Type a (Type a) deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | There are two kinds of types in the Java programming language: primitive types and reference types. data Type a = PrimType a (PrimType a) | RefType a (RefType a) | AntiQType a String deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | There are three kinds of reference types: class types, interface types, and array types. -- Reference types may be parameterized with type arguments. -- Type variables are introduced by generic type parameters. data RefType a = ClassRefType a (ClassType a) | TypeVariable a (Ident a) | ArrayType a (Type a) [Maybe (Policy a)] -- ^ The second argument to ArrayType is the base type, and should not be an array type deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A class or interface type consists of a type declaration specifier, -- optionally followed by type arguments (in which case it is a parameterized type). data ClassType a = ClassType a (Name a) [TypeArgument a] deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | Type arguments may be either reference types or wildcards. data TypeArgument a = Wildcard a (Maybe (WildcardBound a)) | ActualArg a (NonWildTypeArgument a) deriving (Eq,Ord,Show,Typeable,Data,Functor) data NonWildTypeArgument a = ActualName a (Name a) -- Can mean a type or an exp | ActualType a (RefType a) | ActualExp a (Exp a) -- Constrained to argExp | ActualLockState a [Lock a] deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | Wildcards may be given explicit bounds, either upper (@extends@) or lower (@super@) bounds. data WildcardBound a = ExtendsBound a (RefType a) | SuperBound a (RefType a) deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A primitive type is predefined by the Java programming language and named by its reserved keyword. data PrimType a = BooleanT a | ByteT a | ShortT a | IntT a | LongT a | CharT a | FloatT a | DoubleT a -- Paragon | ActorT a | PolicyT a deriving (Eq,Ord,Show,Typeable,Data,Functor) aOfPrimType :: PrimType a -> a aOfPrimType (BooleanT x) = x aOfPrimType (ByteT x) = x aOfPrimType (ShortT x) = x aOfPrimType (IntT x) = x aOfPrimType (LongT x) = x aOfPrimType (CharT x) = x aOfPrimType (FloatT x) = x aOfPrimType (DoubleT x) = x aOfPrimType (ActorT x) = x aOfPrimType (PolicyT x) = x -- | A class is generic if it declares one or more type variables. These type variables are known -- as the type parameters of the class. -- Paragon adds three new forms - actor, policy and lockstate parameters. data TypeParam a = TypeParam a (Ident a) [RefType a] -- Paragon | ActorParam a (RefType a) (Ident a) | PolicyParam a (Ident a) | LockStateParam a (Ident a) deriving (Eq,Ord,Show,Typeable,Data,Functor) ----------------------------------------------------------------------- -- Paragon type Policy a = Exp a -- | A policy is a conjunction (set) of clauses, represented as a list. --data PolicyLit = PolicyLit [Clause Actor] data PolicyExp a = PolicyLit a [Clause a] | PolicyOf a (Ident a) | PolicyThis a | PolicyTypeVar a (Ident a) deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A lock property is a potentially recursive policy with an atom head. data LockProperties a = LockProperties a [LClause a] deriving (Eq,Ord,Show,Typeable,Data,Functor) -- HERE -- | A clause of the form Sigma => a, where a is an actor and Sigma a set of -- locks/atomic predicates that must be open/true. data Clause a = Clause a [ClauseVarDecl a] (ClauseHead a) [Atom a] deriving (Eq,Ord,Show,Typeable,Data,Functor) data ClauseVarDecl a = ClauseVarDecl a (RefType a) (Ident a) deriving (Eq,Ord,Show,Typeable,Data,Functor) data ClauseHead a = ClauseDeclHead a (ClauseVarDecl a) | ClauseVarHead a (Actor a) deriving (Eq,Ord,Show,Typeable,Data,Functor) data LClause a = LClause a [ClauseVarDecl a] (Atom a) [Atom a] | ConstraintClause a [ClauseVarDecl a] [Atom a] deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | An actor variable, either forall-quantified within the current clause, or -- free and thus concrete w.r.t. the policy under scrutiny. data Actor a = Actor a (ActorName a) -- ^ Free actor variables | Var a (Ident a) -- ^ Quantified actor variables deriving (Eq,Ord,Show,Typeable,Data,Functor) data ActorName a = ActorName a (Name a) -- ^ A free actor variable | ActorTypeVar a (RefType a) (Ident a) -- ^ A free actor type parameter deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | A lock is an atomic n-ary predicate. data Atom a = Atom a (Name a) [Actor a] deriving (Eq,Ord,Show,Typeable,Data,Functor) data Lock a = Lock a (Name a) [ActorName a] | LockVar a (Ident a) deriving (Eq,Ord,Show,Typeable,Data,Functor) ----------------------------------------------------------------------- -- Useful accessors importDeclName :: ImportDecl a -> Name a importDeclName (SingleTypeImport _ n) = n importDeclName (TypeImportOnDemand _ n) = n importDeclName (SingleStaticImport _ n _) = n importDeclName (StaticImportOnDemand _ n) = n ----------------------------------------------------------------------- -- Names and identifiers -- | A single identifier. data Ident a = Ident a B.ByteString | AntiQIdent a String deriving (Eq,Ord,Show,Typeable,Data,Functor) -- | Extract actual identifier string from Ident wrapper type unIdent :: Ident a -> B.ByteString unIdent (Ident _ bs) = bs unIdent (AntiQIdent _ str) = panic (syntaxModule ++ ".unIdent") $ "AntiQIdent " ++ str -- | A name, i.e. a period-separated list of identifiers. data Name a = Name a NameType (Maybe (Name a)) (Ident a) | AntiQName a String -- Show removed to get more readable debug output deriving (Eq,Ord,Typeable,Data,Functor) -- Prints name as a simple string to be easier to read. -- To get printout of the whole recursive name structure, comment this out and put -- Show in the deriving clause. instance Show (Name a) where show (Name _ _ nextBase (Ident _ iBase)) = show (showInner nextBase ++ B.unpack iBase) where showInner Nothing = "" showInner (Just (Name _ _ next (Ident _ i))) = showInner next ++ B.unpack i ++ "." data NameType = EName -- ^Expression name | MName -- ^Method name | TName -- ^Type (class, interface, enum [not implemented]) name | PName -- ^Package name | LName -- ^Lock name | POrTName -- ^Either package or Type name | MOrLName -- ^Method or lock name | EOrLName -- ^Expression or lock name | AmbName -- ^Ambiguous name deriving (Eq,Ord,Show,Typeable,Data) nameType :: Name a -> NameType nameType (Name _ nt _ _) = nt nameType _ = panic (syntaxModule ++ ".nameType") $ "AntiQName" setNameType :: NameType -> Name a -> Name a setNameType nt (Name a _ mPre i) = Name a nt mPre i setNameType _ n = n mkSimpleName :: NameType -> Ident a -> Name a mkSimpleName nt i = Name (ann i) nt Nothing i mkUniformName :: (a -> a -> a) -- Merge annotations -> NameType -> [Ident a] -> Name a mkUniformName f nt ids = mkName' (reverse ids) where mkName' [] = panic (syntaxModule ++ ".mkUniformName") $ "Empty list of idents" mkName' [i] = Name (ann i) nt Nothing i mkName' (i:is) = let pre = mkName' is a = f (ann pre) (ann i) in Name a nt (Just pre) i mkUniformName_ :: NameType -> [Ident a] -> Name a mkUniformName_ = mkUniformName const mkName :: (a -> a -> a) -- Merge annotations -> NameType -> NameType -> [Ident a] -> Name a mkName f nt ntPre ids = mkName' (reverse ids) where mkName' [] = panic (syntaxModule ++ ".mkName") $ "Empty list of idents" mkName' [i] = Name (ann i) nt Nothing i mkName' (i:is) = let pre = mkUniformName f ntPre (reverse is) a = f (ann pre) (ann i) in Name a nt (Just pre) i mkName_ :: NameType -> NameType -> [Ident a] -> Name a mkName_ = mkName const flattenName :: Name a -> [Ident a] flattenName n = reverse $ flName n where flName (Name _ _ mPre i) = i : maybe [] flName mPre flName (AntiQName{}) = panic (syntaxModule ++ ".flattenName") $ "Cannot flatten name anti-quote" mkIdent :: a -> String -> Ident a mkIdent a = Ident a . B.pack mkIdent_ :: String -> Ident SourcePos mkIdent_ = mkIdent defaultPos ----------------------------------------------------------------------- -- Annotations $(deriveAnnMany [''CompilationUnit, ''PackageDecl, ''ImportDecl, ''TypeDecl, ''ClassDecl, ''ClassBody, ''EnumBody, ''EnumConstant, ''InterfaceDecl, ''InterfaceBody, ''Decl, ''MemberDecl, ''VarDecl, ''VarDeclId, ''VarInit, ''ArrayInit, ''FormalParam, ''MethodBody, ''ConstructorBody, ''ExplConstrInv, ''Modifier, ''Block, ''BlockStmt, ''Stmt, ''Catch, ''SwitchBlock, ''SwitchLabel, ''ForInit, ''ExceptionSpec, ''Exp, ''Literal, ''Op, ''AssignOp, ''Lhs, ''ArrayIndex, ''FieldAccess, ''MethodInvocation, ''Type, ''PrimType, ''RefType, ''ClassType, ''ReturnType, ''TypeArgument, ''NonWildTypeArgument, ''WildcardBound, ''TypeParam, ''PolicyExp, ''LockProperties, ''Clause, ''LClause, ''ClauseVarDecl, ''ClauseHead, ''Actor, ''ActorName, ''Atom, ''Lock, ''Ident, ''Name])
bvdelft/parac2
src/Language/Java/Paragon/Syntax.hs
bsd-3-clause
33,833
0
14
8,084
7,310
3,996
3,314
406
3
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ConstraintKinds #-} -- | Cache information about previous builds module Stack.Build.Cache ( tryGetBuildCache , tryGetConfigCache , tryGetCabalMod , getInstalledExes , buildCacheTimes , tryGetFlagCache , deleteCaches , markExeInstalled , markExeNotInstalled , writeFlagCache , writeBuildCache , writeConfigCache , writeCabalMod , setTestSuccess , unsetTestSuccess , checkTestSuccess , setTestBuilt , unsetTestBuilt , checkTestBuilt , setBenchBuilt , unsetBenchBuilt , checkBenchBuilt , writePrecompiledCache , readPrecompiledCache ) where import Control.Exception.Enclosed (handleIO) import Control.Monad.Catch (MonadThrow) import Control.Monad.IO.Class import Control.Monad.Logger (MonadLogger) import Control.Monad.Reader import qualified Crypto.Hash.SHA256 as SHA256 import qualified Data.Binary as Binary (encode) import Data.Binary.VersionTagged import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString.Base16 as B16 import Data.Map (Map) import Data.Maybe (fromMaybe, mapMaybe) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import GHC.Generics (Generic) import Path import Path.IO import Stack.Types.Build import Stack.Constants import Stack.Types -- | Directory containing files to mark an executable as installed exeInstalledDir :: (MonadReader env m, HasEnvConfig env, MonadThrow m) => InstallLocation -> m (Path Abs Dir) exeInstalledDir Snap = (</> $(mkRelDir "installed-packages")) `liftM` installationRootDeps exeInstalledDir Local = (</> $(mkRelDir "installed-packages")) `liftM` installationRootLocal -- | Get all of the installed executables getInstalledExes :: (MonadReader env m, HasEnvConfig env, MonadIO m, MonadThrow m) => InstallLocation -> m [PackageIdentifier] getInstalledExes loc = do dir <- exeInstalledDir loc (_, files) <- liftIO $ handleIO (const $ return ([], [])) $ listDirectory dir return $ mapMaybe (parsePackageIdentifierFromString . toFilePath . filename) files -- | Mark the given executable as installed markExeInstalled :: (MonadReader env m, HasEnvConfig env, MonadIO m, MonadThrow m) => InstallLocation -> PackageIdentifier -> m () markExeInstalled loc ident = do dir <- exeInstalledDir loc createTree dir ident' <- parseRelFile $ packageIdentifierString ident let fp = toFilePath $ dir </> ident' -- TODO consideration for the future: list all of the executables -- installed, and invalidate this file in getInstalledExes if they no -- longer exist liftIO $ writeFile fp "Installed" -- | Mark the given executable as not installed markExeNotInstalled :: (MonadReader env m, HasEnvConfig env, MonadIO m, MonadThrow m) => InstallLocation -> PackageIdentifier -> m () markExeNotInstalled loc ident = do dir <- exeInstalledDir loc ident' <- parseRelFile $ packageIdentifierString ident removeFileIfExists (dir </> ident') -- | Stored on disk to know whether the flags have changed or any -- files have changed. data BuildCache = BuildCache { buildCacheTimes :: !(Map FilePath FileCacheInfo) -- ^ Modification times of files. } deriving (Generic) instance Binary BuildCache instance HasStructuralInfo BuildCache instance HasSemanticVersion BuildCache instance NFData BuildCache -- | Try to read the dirtiness cache for the given package directory. tryGetBuildCache :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m, HasEnvConfig env) => Path Abs Dir -> m (Maybe (Map FilePath FileCacheInfo)) tryGetBuildCache = liftM (fmap buildCacheTimes) . tryGetCache buildCacheFile -- | Try to read the dirtiness cache for the given package directory. tryGetConfigCache :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m, HasEnvConfig env) => Path Abs Dir -> m (Maybe ConfigCache) tryGetConfigCache = tryGetCache configCacheFile -- | Try to read the mod time of the cabal file from the last build tryGetCabalMod :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m, HasEnvConfig env) => Path Abs Dir -> m (Maybe ModTime) tryGetCabalMod = tryGetCache configCabalMod -- | Try to load a cache. tryGetCache :: (MonadIO m, BinarySchema a) => (Path Abs Dir -> m (Path Abs File)) -> Path Abs Dir -> m (Maybe a) tryGetCache get' dir = get' dir >>= decodeFileOrFailDeep . toFilePath -- | Write the dirtiness cache for this package's files. writeBuildCache :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m, HasEnvConfig env) => Path Abs Dir -> Map FilePath FileCacheInfo -> m () writeBuildCache dir times = writeCache dir buildCacheFile (BuildCache { buildCacheTimes = times }) -- | Write the dirtiness cache for this package's configuration. writeConfigCache :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m, HasEnvConfig env) => Path Abs Dir -> ConfigCache -> m () writeConfigCache dir = writeCache dir configCacheFile -- | See 'tryGetCabalMod' writeCabalMod :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m, HasEnvConfig env) => Path Abs Dir -> ModTime -> m () writeCabalMod dir = writeCache dir configCabalMod -- | Delete the caches for the project. deleteCaches :: (MonadIO m, MonadReader env m, HasConfig env, MonadLogger m, MonadThrow m, HasEnvConfig env) => Path Abs Dir -> m () deleteCaches dir = do {- FIXME confirm that this is acceptable to remove bfp <- buildCacheFile dir removeFileIfExists bfp -} cfp <- configCacheFile dir removeFileIfExists cfp -- | Write to a cache. writeCache :: (BinarySchema a, MonadIO m) => Path Abs Dir -> (Path Abs Dir -> m (Path Abs File)) -> a -> m () writeCache dir get' content = do fp <- get' dir taggedEncodeFile (toFilePath fp) content flagCacheFile :: (MonadIO m, MonadThrow m, MonadReader env m, HasEnvConfig env) => Installed -> m (Path Abs File) flagCacheFile installed = do rel <- parseRelFile $ case installed of Library _ gid -> ghcPkgIdString gid Executable ident -> packageIdentifierString ident dir <- flagCacheLocal return $ dir </> rel -- | Loads the flag cache for the given installed extra-deps tryGetFlagCache :: (MonadIO m, MonadThrow m, MonadReader env m, HasEnvConfig env) => Installed -> m (Maybe ConfigCache) tryGetFlagCache gid = flagCacheFile gid >>= decodeFileOrFailDeep . toFilePath writeFlagCache :: (MonadIO m, MonadReader env m, HasEnvConfig env, MonadThrow m) => Installed -> ConfigCache -> m () writeFlagCache gid cache = do file <- flagCacheFile gid liftIO $ do createTree (parent file) taggedEncodeFile (toFilePath file) cache -- | Mark a test suite as having succeeded setTestSuccess :: (MonadIO m, MonadLogger m, MonadThrow m, MonadReader env m, HasConfig env, HasEnvConfig env) => Path Abs Dir -> m () setTestSuccess dir = writeCache dir testSuccessFile True -- | Mark a test suite as not having succeeded unsetTestSuccess :: (MonadIO m, MonadLogger m, MonadThrow m, MonadReader env m, HasConfig env, HasEnvConfig env) => Path Abs Dir -> m () unsetTestSuccess dir = writeCache dir testSuccessFile False -- | Check if the test suite already passed checkTestSuccess :: (MonadIO m, MonadLogger m, MonadThrow m, MonadReader env m, HasConfig env, HasEnvConfig env) => Path Abs Dir -> m Bool checkTestSuccess dir = liftM (fromMaybe False) (tryGetCache testSuccessFile dir) -- | Mark a test suite as having built setTestBuilt :: (MonadIO m, MonadLogger m, MonadThrow m, MonadReader env m, HasConfig env, HasEnvConfig env) => Path Abs Dir -> m () setTestBuilt dir = writeCache dir testBuiltFile True -- | Mark a test suite as not having built unsetTestBuilt :: (MonadIO m, MonadLogger m, MonadThrow m, MonadReader env m, HasConfig env, HasEnvConfig env) => Path Abs Dir -> m () unsetTestBuilt dir = writeCache dir testBuiltFile False -- | Check if the test suite already built checkTestBuilt :: (MonadIO m, MonadLogger m, MonadThrow m, MonadReader env m, HasConfig env, HasEnvConfig env) => Path Abs Dir -> m Bool checkTestBuilt dir = liftM (fromMaybe False) (tryGetCache testBuiltFile dir) -- | Mark a bench suite as having built setBenchBuilt :: (MonadIO m, MonadLogger m, MonadThrow m, MonadReader env m, HasConfig env, HasEnvConfig env) => Path Abs Dir -> m () setBenchBuilt dir = writeCache dir benchBuiltFile True -- | Mark a bench suite as not having built unsetBenchBuilt :: (MonadIO m, MonadLogger m, MonadThrow m, MonadReader env m, HasConfig env, HasEnvConfig env) => Path Abs Dir -> m () unsetBenchBuilt dir = writeCache dir benchBuiltFile False -- | Check if the bench suite already built checkBenchBuilt :: (MonadIO m, MonadLogger m, MonadThrow m, MonadReader env m, HasConfig env, HasEnvConfig env) => Path Abs Dir -> m Bool checkBenchBuilt dir = liftM (fromMaybe False) (tryGetCache benchBuiltFile dir) -------------------------------------- -- Precompiled Cache -- -- Idea is simple: cache information about packages built in other snapshots, -- and then for identical matches (same flags, config options, dependencies) -- just copy over the executables and reregister the libraries. -------------------------------------- -- | The file containing information on the given package/configuration -- combination. The filename contains a hash of the non-directory configure -- options for quick lookup if there's a match. precompiledCacheFile :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => PackageIdentifier -> ConfigureOpts -> m (Path Abs File) precompiledCacheFile pkgident copts = do ec <- asks getEnvConfig compiler <- parseRelDir $ compilerVersionString $ envConfigCompilerVersion ec cabal <- parseRelDir $ versionString $ envConfigCabalVersion ec pkg <- parseRelDir $ packageIdentifierString pkgident -- We only pay attention to non-directory options. We don't want to avoid a -- cache hit just because it was installed in a different directory. copts' <- parseRelFile $ S8.unpack $ B16.encode $ SHA256.hashlazy $ Binary.encode $ coNoDirs copts return $ getStackRoot ec </> $(mkRelDir "precompiled") </> compiler </> cabal </> pkg </> copts' -- | Write out information about a newly built package writePrecompiledCache :: (MonadThrow m, MonadReader env m, HasEnvConfig env, MonadIO m) => BaseConfigOpts -> PackageIdentifier -> ConfigureOpts -> Maybe GhcPkgId -- ^ library -> Set Text -- ^ executables -> m () writePrecompiledCache baseConfigOpts pkgident copts mghcPkgId exes = do file <- precompiledCacheFile pkgident copts createTree $ parent file mlibpath <- case mghcPkgId of Nothing -> return Nothing Just ipid -> liftM Just $ do ipid' <- parseRelFile $ ghcPkgIdString ipid ++ ".conf" return $ toFilePath $ bcoSnapDB baseConfigOpts </> ipid' exes' <- forM (Set.toList exes) $ \exe -> do name <- parseRelFile $ T.unpack exe return $ toFilePath $ bcoSnapInstallRoot baseConfigOpts </> bindirSuffix </> name liftIO $ taggedEncodeFile (toFilePath file) PrecompiledCache { pcLibrary = mlibpath , pcExes = exes' } -- | Check the cache for a precompiled package matching the given -- configuration. readPrecompiledCache :: (MonadThrow m, MonadReader env m, HasEnvConfig env, MonadIO m) => PackageIdentifier -- ^ target package -> ConfigureOpts -> m (Maybe PrecompiledCache) readPrecompiledCache pkgident copts = do file <- precompiledCacheFile pkgident copts decodeFileOrFailDeep $ toFilePath file
rrnewton/stack
src/Stack/Build/Cache.hs
bsd-3-clause
13,267
0
17
3,604
3,107
1,589
1,518
268
2
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types] -- in module PlaceHolder {-# LANGUAGE ConstraintKinds #-} -- | Abstract Haskell syntax for expressions. module HsExpr where #include "HsVersions.h" -- friends: import HsDecls import HsPat import HsLit import PlaceHolder ( PostTc,PostRn,DataId ) import HsTypes import HsBinds -- others: import TcEvidence import CoreSyn import Var import RdrName import Name import BasicTypes import DataCon import SrcLoc import Util import StaticFlags( opt_PprStyle_Debug ) import Outputable import FastString import Type -- libraries: import Data.Data hiding (Fixity) {- ************************************************************************ * * \subsection{Expressions proper} * * ************************************************************************ -} -- * Expressions proper type LHsExpr id = Located (HsExpr id) -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when -- in a list -- For details on above see note [Api annotations] in ApiAnnotation ------------------------- -- | PostTcExpr is an evidence expression attached to the syntax tree by the -- type checker (c.f. postTcType). type PostTcExpr = HsExpr Id -- | We use a PostTcTable where there are a bunch of pieces of evidence, more -- than is convenient to keep individually. type PostTcTable = [(Name, PostTcExpr)] noPostTcExpr :: PostTcExpr noPostTcExpr = HsLit (HsString "" (fsLit "noPostTcExpr")) noPostTcTable :: PostTcTable noPostTcTable = [] ------------------------- -- | SyntaxExpr is like 'PostTcExpr', but it's filled in a little earlier, -- by the renamer. It's used for rebindable syntax. -- -- E.g. @(>>=)@ is filled in before the renamer by the appropriate 'Name' for -- @(>>=)@, and then instantiated by the type checker with its type args -- etc type SyntaxExpr id = HsExpr id noSyntaxExpr :: SyntaxExpr id -- Before renaming, and sometimes after, -- (if the syntax slot makes no sense) noSyntaxExpr = HsLit (HsString "" (fsLit "noSyntaxExpr")) type CmdSyntaxTable id = [(Name, SyntaxExpr id)] -- See Note [CmdSyntaxTable] {- Note [CmdSyntaxtable] ~~~~~~~~~~~~~~~~~~~~~ Used only for arrow-syntax stuff (HsCmdTop), the CmdSyntaxTable keeps track of the methods needed for a Cmd. * Before the renamer, this list is an empty list * After the renamer, it takes the form @[(std_name, HsVar actual_name)]@ For example, for the 'arr' method * normal case: (GHC.Control.Arrow.arr, HsVar GHC.Control.Arrow.arr) * with rebindable syntax: (GHC.Control.Arrow.arr, arr_22) where @arr_22@ is whatever 'arr' is in scope * After the type checker, it takes the form [(std_name, <expression>)] where <expression> is the evidence for the method. This evidence is instantiated with the class, but is still polymorphic in everything else. For example, in the case of 'arr', the evidence has type forall b c. (b->c) -> a b c where 'a' is the ambient type of the arrow. This polymorphism is important because the desugarer uses the same evidence at multiple different types. This is Less Cool than what we normally do for rebindable syntax, which is to make fully-instantiated piece of evidence at every use site. The Cmd way is Less Cool because * The renamer has to predict which methods are needed. See the tedious RnExpr.methodNamesCmd. * The desugarer has to know the polymorphic type of the instantiated method. This is checked by Inst.tcSyntaxName, but is less flexible than the rest of rebindable syntax, where the type is less pre-ordained. (And this flexibility is useful; for example we can typecheck do-notation with (>>=) :: m1 a -> (a -> m2 b) -> m2 b.) -} -- | A Haskell expression. data HsExpr id = HsVar id -- ^ Variable | HsIPVar HsIPName -- ^ Implicit parameter | HsOverLit (HsOverLit id) -- ^ Overloaded literals | HsLit HsLit -- ^ Simple (non-overloaded) literals | HsLam (MatchGroup id (LHsExpr id)) -- ^ Lambda abstraction. Currently always a single match -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam', -- 'ApiAnnotation.AnnRarrow', -- For details on above see note [Api annotations] in ApiAnnotation | HsLamCase (PostTc id Type) (MatchGroup id (LHsExpr id)) -- ^ Lambda-case -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam', -- 'ApiAnnotation.AnnCase','ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsApp (LHsExpr id) (LHsExpr id) -- ^ Application -- | Operator applications: -- NB Bracketed ops such as (+) come out as Vars. -- NB We need an expr for the operator in an OpApp/Section since -- the typechecker may need to apply the operator to a few types. | OpApp (LHsExpr id) -- left operand (LHsExpr id) -- operator (PostRn id Fixity) -- Renamer adds fixity; bottom until then (LHsExpr id) -- right operand -- | Negation operator. Contains the negated expression and the name -- of 'negate' -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnMinus' -- For details on above see note [Api annotations] in ApiAnnotation | NegApp (LHsExpr id) (SyntaxExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsPar (LHsExpr id) -- ^ Parenthesised expr; see Note [Parens in HsSyn] | SectionL (LHsExpr id) -- operand; see Note [Sections in HsSyn] (LHsExpr id) -- operator | SectionR (LHsExpr id) -- operator; see Note [Sections in HsSyn] (LHsExpr id) -- operand -- | Used for explicit tuples and sections thereof -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | ExplicitTuple [LHsTupArg id] Boxity -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase', -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCase (LHsExpr id) (MatchGroup id (LHsExpr id)) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf', -- 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnElse', -- For details on above see note [Api annotations] in ApiAnnotation | HsIf (Maybe (SyntaxExpr id)) -- cond function -- Nothing => use the built-in 'if' -- See Note [Rebindable if] (LHsExpr id) -- predicate (LHsExpr id) -- then part (LHsExpr id) -- else part -- | Multi-way if -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf' -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose', -- For details on above see note [Api annotations] in ApiAnnotation | HsMultiIf (PostTc id Type) [LGRHS id (LHsExpr id)] -- | let(rec) -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet', -- 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn' -- For details on above see note [Api annotations] in ApiAnnotation | HsLet (HsLocalBinds id) (LHsExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo', -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsDo (HsStmtContext Name) -- The parameterisation is unimportant -- because in this context we never use -- the PatGuard or ParStmt variant [ExprLStmt id] -- "do":one or more stmts (PostTc id Type) -- Type of the whole expression -- | Syntactic list: [a,b,c,...] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@, -- 'ApiAnnotation.AnnClose' @']'@ -- For details on above see note [Api annotations] in ApiAnnotation | ExplicitList (PostTc id Type) -- Gives type of components of list (Maybe (SyntaxExpr id)) -- For OverloadedLists, the fromListN witness [LHsExpr id] -- | Syntactic parallel array: [:e1, ..., en:] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@, -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnComma', -- 'ApiAnnotation.AnnVbar' -- 'ApiAnnotation.AnnClose' @':]'@ -- For details on above see note [Api annotations] in ApiAnnotation | ExplicitPArr (PostTc id Type) -- type of elements of the parallel array [LHsExpr id] -- | Record construction -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | RecordCon (Located id) -- The constructor. After type checking -- it's the dataConWrapId of the constructor PostTcExpr -- Data con Id applied to type args (HsRecordBinds id) -- | Record update -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | RecordUpd (LHsExpr id) (HsRecordBinds id) -- (HsMatchGroup Id) -- Filled in by the type checker to be -- -- a match that does the job [DataCon] -- Filled in by the type checker to the -- _non-empty_ list of DataCons that have -- all the upd'd fields [PostTc id Type] -- Argument types of *input* record type [PostTc id Type] -- and *output* record type -- For a type family, the arg types are of the *instance* tycon, -- not the family tycon -- | Expression with an explicit type signature. @e :: type@ -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon' -- For details on above see note [Api annotations] in ApiAnnotation | ExprWithTySig (LHsExpr id) (LHsType id) (PostRn id [Name]) -- After renaming, the list of Names -- contains the named and unnamed -- wildcards brought in scope by the -- signature | ExprWithTySigOut -- TRANSLATION (LHsExpr id) (LHsType Name) -- Retain the signature for -- round-tripping purposes -- | Arithmetic sequence -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@, -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot', -- 'ApiAnnotation.AnnClose' @']'@ -- For details on above see note [Api annotations] in ApiAnnotation | ArithSeq PostTcExpr (Maybe (SyntaxExpr id)) -- For OverloadedLists, the fromList witness (ArithSeqInfo id) -- | Arithmetic sequence for parallel array -- -- > [:e1..e2:] or [:e1, e2..e3:] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@, -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot', -- 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnClose' @':]'@ -- For details on above see note [Api annotations] in ApiAnnotation | PArrSeq PostTcExpr (ArithSeqInfo id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# SCC'@, -- 'ApiAnnotation.AnnVal' or 'ApiAnnotation.AnnValStr', -- 'ApiAnnotation.AnnClose' @'\#-}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsSCC SourceText -- Note [Pragma source text] in BasicTypes FastString -- "set cost centre" SCC pragma (LHsExpr id) -- expr whose cost is to be measured -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# CORE'@, -- 'ApiAnnotation.AnnVal', 'ApiAnnotation.AnnClose' @'\#-}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCoreAnn SourceText -- Note [Pragma source text] in BasicTypes FastString -- hdaume: core annotation (LHsExpr id) ----------------------------------------------------------- -- MetaHaskell Extensions -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsBracket (HsBracket id) -- See Note [Pending Splices] | HsRnBracketOut (HsBracket Name) -- Output of the renamer is the *original* renamed -- expression, plus [PendingRnSplice] -- _renamed_ splices to be type checked | HsTcBracketOut (HsBracket Name) -- Output of the type checker is the *original* -- renamed expression, plus [PendingTcSplice] -- _typechecked_ splices to be -- pasted back in by the desugarer -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsSpliceE (HsSplice id) ----------------------------------------------------------- -- Arrow notation extension -- | @proc@ notation for Arrows -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnProc', -- 'ApiAnnotation.AnnRarrow' -- For details on above see note [Api annotations] in ApiAnnotation | HsProc (LPat id) -- arrow abstraction, proc (LHsCmdTop id) -- body of the abstraction -- always has an empty stack --------------------------------------- -- static pointers extension -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnStatic', -- For details on above see note [Api annotations] in ApiAnnotation | HsStatic (LHsExpr id) --------------------------------------- -- The following are commands, not expressions proper -- They are only used in the parsing stage and are removed -- immediately in parser.RdrHsSyn.checkCommand -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail', -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail', -- 'ApiAnnotation.AnnRarrowtail' -- For details on above see note [Api annotations] in ApiAnnotation | HsArrApp -- Arrow tail, or arrow application (f -< arg) (LHsExpr id) -- arrow expression, f (LHsExpr id) -- input expression, arg (PostTc id Type) -- type of the arrow expressions f, -- of the form a t t', where arg :: t HsArrAppType -- higher-order (-<<) or first-order (-<) Bool -- True => right-to-left (f -< arg) -- False => left-to-right (arg >- f) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@, -- 'ApiAnnotation.AnnClose' @'|)'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsArrForm -- Command formation, (| e cmd1 .. cmdn |) (LHsExpr id) -- the operator -- after type-checking, a type abstraction to be -- applied to the type of the local environment tuple (Maybe Fixity) -- fixity (filled in by the renamer), for forms that -- were converted from OpApp's by the renamer [LHsCmdTop id] -- argument commands --------------------------------------- -- Haskell program coverage (Hpc) Support | HsTick (Tickish id) (LHsExpr id) -- sub-expression | HsBinTick Int -- module-local tick number for True Int -- module-local tick number for False (LHsExpr id) -- sub-expression -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnOpen' @'{-\# GENERATED'@, -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnColon','ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnMinus', -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnColon', -- 'ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnClose' @'\#-}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsTickPragma -- A pragma introduced tick SourceText -- Note [Pragma source text] in BasicTypes (FastString,(Int,Int),(Int,Int)) -- external span for this tick (LHsExpr id) --------------------------------------- -- These constructors only appear temporarily in the parser. -- The renamer translates them into the Right Thing. | EWildPat -- wildcard -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt' -- For details on above see note [Api annotations] in ApiAnnotation | EAsPat (Located id) -- as pattern (LHsExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow' -- For details on above see note [Api annotations] in ApiAnnotation | EViewPat (LHsExpr id) -- view pattern (LHsExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde' -- For details on above see note [Api annotations] in ApiAnnotation | ELazyPat (LHsExpr id) -- ~ pattern | HsType (LHsType id) -- Explicit type argument; e.g f {| Int |} x y --------------------------------------- -- Finally, HsWrap appears only in typechecker output | HsWrap HsWrapper -- TRANSLATION (HsExpr id) | HsUnboundVar RdrName deriving (Typeable) deriving instance (DataId id) => Data (HsExpr id) -- | HsTupArg is used for tuple sections -- (,a,) is represented by ExplicitTuple [Missing ty1, Present a, Missing ty3] -- Which in turn stands for (\x:ty1 \y:ty2. (x,a,y)) type LHsTupArg id = Located (HsTupArg id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' -- For details on above see note [Api annotations] in ApiAnnotation data HsTupArg id = Present (LHsExpr id) -- ^ The argument | Missing (PostTc id Type) -- ^ The argument is missing, but this is its type deriving (Typeable) deriving instance (DataId id) => Data (HsTupArg id) tupArgPresent :: LHsTupArg id -> Bool tupArgPresent (L _ (Present {})) = True tupArgPresent (L _ (Missing {})) = False {- Note [Parens in HsSyn] ~~~~~~~~~~~~~~~~~~~~~~ HsPar (and ParPat in patterns, HsParTy in types) is used as follows * Generally HsPar is optional; the pretty printer adds parens where necessary. Eg (HsApp f (HsApp g x)) is fine, and prints 'f (g x)' * HsPars are pretty printed as '( .. )' regardless of whether or not they are strictly necssary * HsPars are respected when rearranging operator fixities. So a * (b + c) means what it says (where the parens are an HsPar) Note [Sections in HsSyn] ~~~~~~~~~~~~~~~~~~~~~~~~ Sections should always appear wrapped in an HsPar, thus HsPar (SectionR ...) The parser parses sections in a wider variety of situations (See Note [Parsing sections]), but the renamer checks for those parens. This invariant makes pretty-printing easier; we don't need a special case for adding the parens round sections. Note [Rebindable if] ~~~~~~~~~~~~~~~~~~~~ The rebindable syntax for 'if' is a bit special, because when rebindable syntax is *off* we do not want to treat (if c then t else e) as if it was an application (ifThenElse c t e). Why not? Because we allow an 'if' to return *unboxed* results, thus if blah then 3# else 4# whereas that would not be possible using a all to a polymorphic function (because you can't call a polymorphic function at an unboxed type). So we use Nothing to mean "use the old built-in typing rule". -} instance OutputableBndr id => Outputable (HsExpr id) where ppr expr = pprExpr expr ----------------------- -- pprExpr, pprLExpr, pprBinds call pprDeeper; -- the underscore versions do not pprLExpr :: OutputableBndr id => LHsExpr id -> SDoc pprLExpr (L _ e) = pprExpr e pprExpr :: OutputableBndr id => HsExpr id -> SDoc pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e | otherwise = pprDeeper (ppr_expr e) isQuietHsExpr :: HsExpr id -> Bool -- Parentheses do display something, but it gives little info and -- if we go deeper when we go inside them then we get ugly things -- like (...) isQuietHsExpr (HsPar _) = True -- applications don't display anything themselves isQuietHsExpr (HsApp _ _) = True isQuietHsExpr (OpApp _ _ _ _) = True isQuietHsExpr _ = False pprBinds :: (OutputableBndr idL, OutputableBndr idR) => HsLocalBindsLR idL idR -> SDoc pprBinds b = pprDeeper (ppr b) ----------------------- ppr_lexpr :: OutputableBndr id => LHsExpr id -> SDoc ppr_lexpr e = ppr_expr (unLoc e) ppr_expr :: forall id. OutputableBndr id => HsExpr id -> SDoc ppr_expr (HsVar v) = pprPrefixOcc v ppr_expr (HsIPVar v) = ppr v ppr_expr (HsLit lit) = ppr lit ppr_expr (HsOverLit lit) = ppr lit ppr_expr (HsPar e) = parens (ppr_lexpr e) ppr_expr (HsCoreAnn _ s e) = vcat [ptext (sLit "HsCoreAnn") <+> ftext s, ppr_lexpr e] ppr_expr (HsApp e1 e2) = let (fun, args) = collect_args e1 [e2] in hang (ppr_lexpr fun) 2 (sep (map pprParendExpr args)) where collect_args (L _ (HsApp fun arg)) args = collect_args fun (arg:args) collect_args fun args = (fun, args) ppr_expr (OpApp e1 op _ e2) = case unLoc op of HsVar v -> pp_infixly v _ -> pp_prefixly where pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens pp_e2 = pprDebugParendExpr e2 -- to make precedence clear pp_prefixly = hang (ppr op) 2 (sep [pp_e1, pp_e2]) pp_infixly v = sep [pp_e1, sep [pprInfixOcc v, nest 2 pp_e2]] ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e ppr_expr (SectionL expr op) = case unLoc op of HsVar v -> pp_infixly v _ -> pp_prefixly where pp_expr = pprDebugParendExpr expr pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op]) 4 (hsep [pp_expr, ptext (sLit "x_ )")]) pp_infixly v = (sep [pp_expr, pprInfixOcc v]) ppr_expr (SectionR op expr) = case unLoc op of HsVar v -> pp_infixly v _ -> pp_prefixly where pp_expr = pprDebugParendExpr expr pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext (sLit "x_")]) 4 (pp_expr <> rparen) pp_infixly v = sep [pprInfixOcc v, pp_expr] ppr_expr (ExplicitTuple exprs boxity) = tupleParens (boxityTupleSort boxity) (fcat (ppr_tup_args $ map unLoc exprs)) where ppr_tup_args [] = [] ppr_tup_args (Present e : es) = (ppr_lexpr e <> punc es) : ppr_tup_args es ppr_tup_args (Missing _ : es) = punc es : ppr_tup_args es punc (Present {} : _) = comma <> space punc (Missing {} : _) = comma punc [] = empty --avoid using PatternSignatures for stage1 code portability ppr_expr (HsLam matches) = pprMatches (LambdaExpr :: HsMatchContext id) matches ppr_expr (HsLamCase _ matches) = sep [ sep [ptext (sLit "\\case {")], nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches <+> char '}') ] ppr_expr (HsCase expr matches) = sep [ sep [ptext (sLit "case"), nest 4 (ppr expr), ptext (sLit "of {")], nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches <+> char '}') ] ppr_expr (HsIf _ e1 e2 e3) = sep [hsep [ptext (sLit "if"), nest 2 (ppr e1), ptext (sLit "then")], nest 4 (ppr e2), ptext (sLit "else"), nest 4 (ppr e3)] ppr_expr (HsMultiIf _ alts) = sep $ ptext (sLit "if") : map ppr_alt alts where ppr_alt (L _ (GRHS guards expr)) = sep [ char '|' <+> interpp'SP guards , ptext (sLit "->") <+> pprDeeper (ppr expr) ] -- special case: let ... in let ... ppr_expr (HsLet binds expr@(L _ (HsLet _ _))) = sep [hang (ptext (sLit "let")) 2 (hsep [pprBinds binds, ptext (sLit "in")]), ppr_lexpr expr] ppr_expr (HsLet binds expr) = sep [hang (ptext (sLit "let")) 2 (pprBinds binds), hang (ptext (sLit "in")) 2 (ppr expr)] ppr_expr (HsDo do_or_list_comp stmts _) = pprDo do_or_list_comp stmts ppr_expr (ExplicitList _ _ exprs) = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs))) ppr_expr (ExplicitPArr _ exprs) = paBrackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs))) ppr_expr (RecordCon con_id _ rbinds) = hang (ppr con_id) 2 (ppr rbinds) ppr_expr (RecordUpd aexp rbinds _ _ _) = hang (pprLExpr aexp) 2 (ppr rbinds) ppr_expr (ExprWithTySig expr sig _) = hang (nest 2 (ppr_lexpr expr) <+> dcolon) 4 (ppr sig) ppr_expr (ExprWithTySigOut expr sig) = hang (nest 2 (ppr_lexpr expr) <+> dcolon) 4 (ppr sig) ppr_expr (ArithSeq _ _ info) = brackets (ppr info) ppr_expr (PArrSeq _ info) = paBrackets (ppr info) ppr_expr EWildPat = char '_' ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e ppr_expr (EViewPat p e) = ppr p <+> ptext (sLit "->") <+> ppr e ppr_expr (HsSCC _ lbl expr) = sep [ ptext (sLit "{-# SCC") <+> doubleQuotes (ftext lbl) <+> ptext (sLit "#-}"), pprParendExpr expr ] ppr_expr (HsWrap co_fn e) = pprHsWrapper (pprExpr e) co_fn ppr_expr (HsType id) = ppr id ppr_expr (HsSpliceE s) = pprSplice s ppr_expr (HsBracket b) = pprHsBracket b ppr_expr (HsRnBracketOut e []) = ppr e ppr_expr (HsRnBracketOut e ps) = ppr e $$ ptext (sLit "pending(rn)") <+> ppr ps ppr_expr (HsTcBracketOut e []) = ppr e ppr_expr (HsTcBracketOut e ps) = ppr e $$ ptext (sLit "pending(tc)") <+> ppr ps ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _))) = hsep [ptext (sLit "proc"), ppr pat, ptext (sLit "->"), ppr cmd] ppr_expr (HsStatic e) = hsep [ptext (sLit "static"), pprParendExpr e] ppr_expr (HsTick tickish exp) = pprTicks (ppr exp) $ ppr tickish <+> ppr_lexpr exp ppr_expr (HsBinTick tickIdTrue tickIdFalse exp) = pprTicks (ppr exp) $ hcat [ptext (sLit "bintick<"), ppr tickIdTrue, ptext (sLit ","), ppr tickIdFalse, ptext (sLit ">("), ppr exp,ptext (sLit ")")] ppr_expr (HsTickPragma _ externalSrcLoc exp) = pprTicks (ppr exp) $ hcat [ptext (sLit "tickpragma<"), ppr externalSrcLoc, ptext (sLit ">("), ppr exp, ptext (sLit ")")] ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True) = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg] ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False) = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow] ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True) = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg] ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False) = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow] ppr_expr (HsArrForm (L _ (HsVar v)) (Just _) [arg1, arg2]) = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]] ppr_expr (HsArrForm op _ args) = hang (ptext (sLit "(|") <+> ppr_lexpr op) 4 (sep (map (pprCmdArg.unLoc) args) <+> ptext (sLit "|)")) ppr_expr (HsUnboundVar nm) = ppr nm {- HsSyn records exactly where the user put parens, with HsPar. So generally speaking we print without adding any parens. However, some code is internally generated, and in some places parens are absolutely required; so for these places we use pprParendExpr (but don't print double parens of course). For operator applications we don't add parens, because the operator fixities should do the job, except in debug mode (-dppr-debug) so we can see the structure of the parse tree. -} pprDebugParendExpr :: OutputableBndr id => LHsExpr id -> SDoc pprDebugParendExpr expr = getPprStyle (\sty -> if debugStyle sty then pprParendExpr expr else pprLExpr expr) pprParendExpr :: OutputableBndr id => LHsExpr id -> SDoc pprParendExpr expr | hsExprNeedsParens (unLoc expr) = parens (pprLExpr expr) | otherwise = pprLExpr expr -- Using pprLExpr makes sure that we go 'deeper' -- I think that is usually (always?) right hsExprNeedsParens :: HsExpr id -> Bool -- True of expressions for which '(e)' and 'e' -- mean the same thing hsExprNeedsParens (ArithSeq {}) = False hsExprNeedsParens (PArrSeq {}) = False hsExprNeedsParens (HsLit {}) = False hsExprNeedsParens (HsOverLit {}) = False hsExprNeedsParens (HsVar {}) = False hsExprNeedsParens (HsUnboundVar {}) = False hsExprNeedsParens (HsIPVar {}) = False hsExprNeedsParens (ExplicitTuple {}) = False hsExprNeedsParens (ExplicitList {}) = False hsExprNeedsParens (ExplicitPArr {}) = False hsExprNeedsParens (RecordCon {}) = False hsExprNeedsParens (RecordUpd {}) = False hsExprNeedsParens (HsPar {}) = False hsExprNeedsParens (HsBracket {}) = False hsExprNeedsParens (HsRnBracketOut {}) = False hsExprNeedsParens (HsTcBracketOut {}) = False hsExprNeedsParens (HsDo sc _ _) | isListCompExpr sc = False hsExprNeedsParens _ = True isAtomicHsExpr :: HsExpr id -> Bool -- True of a single token isAtomicHsExpr (HsVar {}) = True isAtomicHsExpr (HsLit {}) = True isAtomicHsExpr (HsOverLit {}) = True isAtomicHsExpr (HsIPVar {}) = True isAtomicHsExpr (HsUnboundVar {}) = True isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e) isAtomicHsExpr _ = False {- ************************************************************************ * * \subsection{Commands (in arrow abstractions)} * * ************************************************************************ We re-use HsExpr to represent these. -} type LHsCmd id = Located (HsCmd id) data HsCmd id -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail', -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail', -- 'ApiAnnotation.AnnRarrowtail' -- For details on above see note [Api annotations] in ApiAnnotation = HsCmdArrApp -- Arrow tail, or arrow application (f -< arg) (LHsExpr id) -- arrow expression, f (LHsExpr id) -- input expression, arg (PostTc id Type) -- type of the arrow expressions f, -- of the form a t t', where arg :: t HsArrAppType -- higher-order (-<<) or first-order (-<) Bool -- True => right-to-left (f -< arg) -- False => left-to-right (arg >- f) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@, -- 'ApiAnnotation.AnnClose' @'|)'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdArrForm -- Command formation, (| e cmd1 .. cmdn |) (LHsExpr id) -- the operator -- after type-checking, a type abstraction to be -- applied to the type of the local environment tuple (Maybe Fixity) -- fixity (filled in by the renamer), for forms that -- were converted from OpApp's by the renamer [LHsCmdTop id] -- argument commands | HsCmdApp (LHsCmd id) (LHsExpr id) | HsCmdLam (MatchGroup id (LHsCmd id)) -- kappa -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam', -- 'ApiAnnotation.AnnRarrow', -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdPar (LHsCmd id) -- parenthesised command -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdCase (LHsExpr id) (MatchGroup id (LHsCmd id)) -- bodies are HsCmd's -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase', -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdIf (Maybe (SyntaxExpr id)) -- cond function (LHsExpr id) -- predicate (LHsCmd id) -- then part (LHsCmd id) -- else part -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf', -- 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnElse', -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdLet (HsLocalBinds id) -- let(rec) (LHsCmd id) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet', -- 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn' -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdDo [CmdLStmt id] (PostTc id Type) -- Type of the whole expression -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo', -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdCast TcCoercion -- A simpler version of HsWrap in HsExpr (HsCmd id) -- If cmd :: arg1 --> res -- co :: arg1 ~ arg2 -- Then (HsCmdCast co cmd) :: arg2 --> res deriving (Typeable) deriving instance (DataId id) => Data (HsCmd id) data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp deriving (Data, Typeable) {- | Top-level command, introducing a new arrow. This may occur inside a proc (where the stack is empty) or as an argument of a command-forming operator. -} type LHsCmdTop id = Located (HsCmdTop id) data HsCmdTop id = HsCmdTop (LHsCmd id) (PostTc id Type) -- Nested tuple of inputs on the command's stack (PostTc id Type) -- return type of the command (CmdSyntaxTable id) -- See Note [CmdSyntaxTable] deriving (Typeable) deriving instance (DataId id) => Data (HsCmdTop id) instance OutputableBndr id => Outputable (HsCmd id) where ppr cmd = pprCmd cmd ----------------------- -- pprCmd and pprLCmd call pprDeeper; -- the underscore versions do not pprLCmd :: OutputableBndr id => LHsCmd id -> SDoc pprLCmd (L _ c) = pprCmd c pprCmd :: OutputableBndr id => HsCmd id -> SDoc pprCmd c | isQuietHsCmd c = ppr_cmd c | otherwise = pprDeeper (ppr_cmd c) isQuietHsCmd :: HsCmd id -> Bool -- Parentheses do display something, but it gives little info and -- if we go deeper when we go inside them then we get ugly things -- like (...) isQuietHsCmd (HsCmdPar _) = True -- applications don't display anything themselves isQuietHsCmd (HsCmdApp _ _) = True isQuietHsCmd _ = False ----------------------- ppr_lcmd :: OutputableBndr id => LHsCmd id -> SDoc ppr_lcmd c = ppr_cmd (unLoc c) ppr_cmd :: forall id. OutputableBndr id => HsCmd id -> SDoc ppr_cmd (HsCmdPar c) = parens (ppr_lcmd c) ppr_cmd (HsCmdApp c e) = let (fun, args) = collect_args c [e] in hang (ppr_lcmd fun) 2 (sep (map pprParendExpr args)) where collect_args (L _ (HsCmdApp fun arg)) args = collect_args fun (arg:args) collect_args fun args = (fun, args) --avoid using PatternSignatures for stage1 code portability ppr_cmd (HsCmdLam matches) = pprMatches (LambdaExpr :: HsMatchContext id) matches ppr_cmd (HsCmdCase expr matches) = sep [ sep [ptext (sLit "case"), nest 4 (ppr expr), ptext (sLit "of {")], nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches <+> char '}') ] ppr_cmd (HsCmdIf _ e ct ce) = sep [hsep [ptext (sLit "if"), nest 2 (ppr e), ptext (sLit "then")], nest 4 (ppr ct), ptext (sLit "else"), nest 4 (ppr ce)] -- special case: let ... in let ... ppr_cmd (HsCmdLet binds cmd@(L _ (HsCmdLet _ _))) = sep [hang (ptext (sLit "let")) 2 (hsep [pprBinds binds, ptext (sLit "in")]), ppr_lcmd cmd] ppr_cmd (HsCmdLet binds cmd) = sep [hang (ptext (sLit "let")) 2 (pprBinds binds), hang (ptext (sLit "in")) 2 (ppr cmd)] ppr_cmd (HsCmdDo stmts _) = pprDo ArrowExpr stmts ppr_cmd (HsCmdCast co cmd) = sep [ ppr_cmd cmd , ptext (sLit "|>") <+> ppr co ] ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp True) = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg] ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp False) = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow] ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp True) = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg] ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp False) = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow] ppr_cmd (HsCmdArrForm (L _ (HsVar v)) (Just _) [arg1, arg2]) = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]] ppr_cmd (HsCmdArrForm op _ args) = hang (ptext (sLit "(|") <> ppr_lexpr op) 4 (sep (map (pprCmdArg.unLoc) args) <> ptext (sLit "|)")) pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc pprCmdArg (HsCmdTop cmd@(L _ (HsCmdArrForm _ Nothing [])) _ _ _) = ppr_lcmd cmd pprCmdArg (HsCmdTop cmd _ _ _) = parens (ppr_lcmd cmd) instance OutputableBndr id => Outputable (HsCmdTop id) where ppr = pprCmdArg {- ************************************************************************ * * \subsection{Record binds} * * ************************************************************************ -} type HsRecordBinds id = HsRecFields id (LHsExpr id) {- ************************************************************************ * * \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes} * * ************************************************************************ @Match@es are sets of pattern bindings and right hand sides for functions, patterns or case branches. For example, if a function @g@ is defined as: \begin{verbatim} g (x,y) = y g ((x:ys),y) = y+1, \end{verbatim} then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@. It is always the case that each element of an @[Match]@ list has the same number of @pats@s inside it. This corresponds to saying that a function defined by pattern matching must have the same number of patterns in each equation. -} data MatchGroup id body = MG { mg_alts :: [LMatch id body] -- The alternatives , mg_arg_tys :: [PostTc id Type] -- Types of the arguments, t1..tn , mg_res_ty :: PostTc id Type -- Type of the result, tr , mg_origin :: Origin } -- The type is the type of the entire group -- t1 -> ... -> tn -> tr -- where there are n patterns deriving (Typeable) deriving instance (Data body,DataId id) => Data (MatchGroup id body) type LMatch id body = Located (Match id body) -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when in a -- list -- For details on above see note [Api annotations] in ApiAnnotation data Match id body = Match { m_fun_id_infix :: (Maybe (Located id,Bool)), -- fun_id and fun_infix for functions with multiple equations -- only present for a RdrName. See note [fun_id in Match] m_pats :: [LPat id], -- The patterns m_type :: (Maybe (LHsType id)), -- A type signature for the result of the match -- Nothing after typechecking m_grhss :: (GRHSs id body) } deriving (Typeable) deriving instance (Data body,DataId id) => Data (Match id body) {- Note [fun_id in Match] ~~~~~~~~~~~~~~~~~~~~~~ The parser initially creates a FunBind with a single Match in it for every function definition it sees. These are then grouped together by getMonoBind into a single FunBind, where all the Matches are combined. In the process, all the original FunBind fun_id's bar one are discarded, including the locations. This causes a problem for source to source conversions via API Annotations, so the original fun_ids and infix flags are preserved in the Match, when it originates from a FunBind. Example infix function definition requiring individual API Annotations (&&& ) [] [] = [] xs &&& [] = xs ( &&& ) [] ys = ys -} isEmptyMatchGroup :: MatchGroup id body -> Bool isEmptyMatchGroup (MG { mg_alts = ms }) = null ms matchGroupArity :: MatchGroup id body -> Arity -- Precondition: MatchGroup is non-empty -- This is called before type checking, when mg_arg_tys is not set matchGroupArity (MG { mg_alts = alts }) | (alt1:_) <- alts = length (hsLMatchPats alt1) | otherwise = panic "matchGroupArity" hsLMatchPats :: LMatch id body -> [LPat id] hsLMatchPats (L _ (Match _ pats _ _)) = pats -- | GRHSs are used both for pattern bindings and for Matches -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere', -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose' -- 'ApiAnnotation.AnnRarrow','ApiAnnotation.AnnSemi' -- For details on above see note [Api annotations] in ApiAnnotation data GRHSs id body = GRHSs { grhssGRHSs :: [LGRHS id body], -- ^ Guarded RHSs grhssLocalBinds :: (HsLocalBinds id) -- ^ The where clause } deriving (Typeable) deriving instance (Data body,DataId id) => Data (GRHSs id body) type LGRHS id body = Located (GRHS id body) -- | Guarded Right Hand Side. data GRHS id body = GRHS [GuardLStmt id] -- Guards body -- Right hand side deriving (Typeable) deriving instance (Data body,DataId id) => Data (GRHS id body) -- We know the list must have at least one @Match@ in it. pprMatches :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => HsMatchContext idL -> MatchGroup idR body -> SDoc pprMatches ctxt (MG { mg_alts = matches }) = vcat (map (pprMatch ctxt) (map unLoc matches)) -- Don't print the type; it's only a place-holder before typechecking -- Exported to HsBinds, which can't see the defn of HsMatchContext pprFunBind :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => idL -> Bool -> MatchGroup idR body -> SDoc pprFunBind fun inf matches = pprMatches (FunRhs fun inf) matches -- Exported to HsBinds, which can't see the defn of HsMatchContext pprPatBind :: forall bndr id body. (OutputableBndr bndr, OutputableBndr id, Outputable body) => LPat bndr -> GRHSs id body -> SDoc pprPatBind pat (grhss) = sep [ppr pat, nest 2 (pprGRHSs (PatBindRhs :: HsMatchContext id) grhss)] pprMatch :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => HsMatchContext idL -> Match idR body -> SDoc pprMatch ctxt (Match _ pats maybe_ty grhss) = sep [ sep (herald : map (nest 2 . pprParendLPat) other_pats) , nest 2 ppr_maybe_ty , nest 2 (pprGRHSs ctxt grhss) ] where (herald, other_pats) = case ctxt of FunRhs fun is_infix | not is_infix -> (pprPrefixOcc fun, pats) -- f x y z = e -- Not pprBndr; the AbsBinds will -- have printed the signature | null pats2 -> (pp_infix, []) -- x &&& y = e | otherwise -> (parens pp_infix, pats2) -- (x &&& y) z = e where pp_infix = pprParendLPat pat1 <+> pprInfixOcc fun <+> pprParendLPat pat2 LambdaExpr -> (char '\\', pats) _ -> ASSERT( null pats1 ) (ppr pat1, []) -- No parens around the single pat (pat1:pats1) = pats (pat2:pats2) = pats1 ppr_maybe_ty = case maybe_ty of Just ty -> dcolon <+> ppr ty Nothing -> empty pprGRHSs :: (OutputableBndr idR, Outputable body) => HsMatchContext idL -> GRHSs idR body -> SDoc pprGRHSs ctxt (GRHSs grhss binds) = vcat (map (pprGRHS ctxt . unLoc) grhss) $$ ppUnless (isEmptyLocalBinds binds) (text "where" $$ nest 4 (pprBinds binds)) pprGRHS :: (OutputableBndr idR, Outputable body) => HsMatchContext idL -> GRHS idR body -> SDoc pprGRHS ctxt (GRHS [] body) = pp_rhs ctxt body pprGRHS ctxt (GRHS guards body) = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt body] pp_rhs :: Outputable body => HsMatchContext idL -> body -> SDoc pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs) {- ************************************************************************ * * \subsection{Do stmts and list comprehensions} * * ************************************************************************ -} type LStmt id body = Located (StmtLR id id body) type LStmtLR idL idR body = Located (StmtLR idL idR body) type Stmt id body = StmtLR id id body type CmdLStmt id = LStmt id (LHsCmd id) type CmdStmt id = Stmt id (LHsCmd id) type ExprLStmt id = LStmt id (LHsExpr id) type ExprStmt id = Stmt id (LHsExpr id) type GuardLStmt id = LStmt id (LHsExpr id) type GuardStmt id = Stmt id (LHsExpr id) type GhciLStmt id = LStmt id (LHsExpr id) type GhciStmt id = Stmt id (LHsExpr id) -- The SyntaxExprs in here are used *only* for do-notation and monad -- comprehensions, which have rebindable syntax. Otherwise they are unused. -- | API Annotations when in qualifier lists or guards -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnThen', -- 'ApiAnnotation.AnnBy','ApiAnnotation.AnnBy', -- 'ApiAnnotation.AnnGroup','ApiAnnotation.AnnUsing' -- For details on above see note [Api annotations] in ApiAnnotation data StmtLR idL idR body -- body should always be (LHs**** idR) = LastStmt -- Always the last Stmt in ListComp, MonadComp, PArrComp, -- and (after the renamer) DoExpr, MDoExpr -- Not used for GhciStmtCtxt, PatGuard, which scope over other stuff body (SyntaxExpr idR) -- The return operator, used only for MonadComp -- For ListComp, PArrComp, we use the baked-in 'return' -- For DoExpr, MDoExpr, we don't appply a 'return' at all -- See Note [Monad Comprehensions] -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLarrow' -- For details on above see note [Api annotations] in ApiAnnotation | BindStmt (LPat idL) body (SyntaxExpr idR) -- The (>>=) operator; see Note [The type of bind] (SyntaxExpr idR) -- The fail operator -- The fail operator is noSyntaxExpr -- if the pattern match can't fail | BodyStmt body -- See Note [BodyStmt] (SyntaxExpr idR) -- The (>>) operator (SyntaxExpr idR) -- The `guard` operator; used only in MonadComp -- See notes [Monad Comprehensions] (PostTc idR Type) -- Element type of the RHS (used for arrows) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet' -- 'ApiAnnotation.AnnOpen' @'{'@,'ApiAnnotation.AnnClose' @'}'@, -- For details on above see note [Api annotations] in ApiAnnotation | LetStmt (HsLocalBindsLR idL idR) -- ParStmts only occur in a list/monad comprehension | ParStmt [ParStmtBlock idL idR] (SyntaxExpr idR) -- Polymorphic `mzip` for monad comprehensions (SyntaxExpr idR) -- The `>>=` operator -- See notes [Monad Comprehensions] -- After renaming, the ids are the binders -- bound by the stmts and used after themp | TransStmt { trS_form :: TransForm, trS_stmts :: [ExprLStmt idL], -- Stmts to the *left* of the 'group' -- which generates the tuples to be grouped trS_bndrs :: [(idR, idR)], -- See Note [TransStmt binder map] trS_using :: LHsExpr idR, trS_by :: Maybe (LHsExpr idR), -- "by e" (optional) -- Invariant: if trS_form = GroupBy, then grp_by = Just e trS_ret :: SyntaxExpr idR, -- The monomorphic 'return' function for -- the inner monad comprehensions trS_bind :: SyntaxExpr idR, -- The '(>>=)' operator trS_fmap :: SyntaxExpr idR -- The polymorphic 'fmap' function for desugaring -- Only for 'group' forms } -- See Note [Monad Comprehensions] -- Recursive statement (see Note [How RecStmt works] below) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRec' -- For details on above see note [Api annotations] in ApiAnnotation | RecStmt { recS_stmts :: [LStmtLR idL idR body] -- The next two fields are only valid after renaming , recS_later_ids :: [idR] -- The ids are a subset of the variables bound by the -- stmts that are used in stmts that follow the RecStmt , recS_rec_ids :: [idR] -- Ditto, but these variables are the "recursive" ones, -- that are used before they are bound in the stmts of -- the RecStmt. -- An Id can be in both groups -- Both sets of Ids are (now) treated monomorphically -- See Note [How RecStmt works] for why they are separate -- Rebindable syntax , recS_bind_fn :: SyntaxExpr idR -- The bind function , recS_ret_fn :: SyntaxExpr idR -- The return function , recS_mfix_fn :: SyntaxExpr idR -- The mfix function -- These fields are only valid after typechecking , recS_later_rets :: [PostTcExpr] -- (only used in the arrow version) , recS_rec_rets :: [PostTcExpr] -- These expressions correspond 1-to-1 -- with recS_later_ids and recS_rec_ids, -- and are the expressions that should be -- returned by the recursion. -- They may not quite be the Ids themselves, -- because the Id may be *polymorphic*, but -- the returned thing has to be *monomorphic*, -- so they may be type applications , recS_ret_ty :: PostTc idR Type -- The type of -- do { stmts; return (a,b,c) } -- With rebindable syntax the type might not -- be quite as simple as (m (tya, tyb, tyc)). } deriving (Typeable) deriving instance (Data body, DataId idL, DataId idR) => Data (StmtLR idL idR body) data TransForm -- The 'f' below is the 'using' function, 'e' is the by function = ThenForm -- then f or then f by e (depending on trS_by) | GroupForm -- then group using f or then group by e using f (depending on trS_by) deriving (Data, Typeable) data ParStmtBlock idL idR = ParStmtBlock [ExprLStmt idL] [idR] -- The variables to be returned (SyntaxExpr idR) -- The return operator deriving( Typeable ) deriving instance (DataId idL, DataId idR) => Data (ParStmtBlock idL idR) {- Note [The type of bind in Stmts] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Some Stmts, notably BindStmt, keep the (>>=) bind operator. We do NOT assume that it has type (>>=) :: m a -> (a -> m b) -> m b In some cases (see Trac #303, #1537) it might have a more exotic type, such as (>>=) :: m i j a -> (a -> m j k b) -> m i k b So we must be careful not to make assumptions about the type. In particular, the monad may not be uniform throughout. Note [TransStmt binder map] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The [(idR,idR)] in a TransStmt behaves as follows: * Before renaming: [] * After renaming: [ (x27,x27), ..., (z35,z35) ] These are the variables bound by the stmts to the left of the 'group' and used either in the 'by' clause, or in the stmts following the 'group' Each item is a pair of identical variables. * After typechecking: [ (x27:Int, x27:[Int]), ..., (z35:Bool, z35:[Bool]) ] Each pair has the same unique, but different *types*. Note [BodyStmt] ~~~~~~~~~~~~~~~ BodyStmts are a bit tricky, because what they mean depends on the context. Consider the following contexts: A do expression of type (m res_ty) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E any_ty: do { ....; E; ... } E :: m any_ty Translation: E >> ... A list comprehensions of type [elt_ty] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E Bool: [ .. | .... E ] [ .. | ..., E, ... ] [ .. | .... | ..., E | ... ] E :: Bool Translation: if E then fail else ... A guard list, guarding a RHS of type rhs_ty ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E BooParStmtBlockl: f x | ..., E, ... = ...rhs... E :: Bool Translation: if E then fail else ... A monad comprehension of type (m res_ty) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E Bool: [ .. | .... E ] E :: Bool Translation: guard E >> ... Array comprehensions are handled like list comprehensions. Note [How RecStmt works] ~~~~~~~~~~~~~~~~~~~~~~~~ Example: HsDo [ BindStmt x ex , RecStmt { recS_rec_ids = [a, c] , recS_stmts = [ BindStmt b (return (a,c)) , LetStmt a = ...b... , BindStmt c ec ] , recS_later_ids = [a, b] , return (a b) ] Here, the RecStmt binds a,b,c; but - Only a,b are used in the stmts *following* the RecStmt, - Only a,c are used in the stmts *inside* the RecStmt *before* their bindings Why do we need *both* rec_ids and later_ids? For monads they could be combined into a single set of variables, but not for arrows. That follows from the types of the respective feedback operators: mfix :: MonadFix m => (a -> m a) -> m a loop :: ArrowLoop a => a (b,d) (c,d) -> a b c * For mfix, the 'a' covers the union of the later_ids and the rec_ids * For 'loop', 'c' is the later_ids and 'd' is the rec_ids Note [Typing a RecStmt] ~~~~~~~~~~~~~~~~~~~~~~~ A (RecStmt stmts) types as if you had written (v1,..,vn, _, ..., _) <- mfix (\~(_, ..., _, r1, ..., rm) -> do { stmts ; return (v1,..vn, r1, ..., rm) }) where v1..vn are the later_ids r1..rm are the rec_ids Note [Monad Comprehensions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Monad comprehensions require separate functions like 'return' and '>>=' for desugaring. These functions are stored in the statements used in monad comprehensions. For example, the 'return' of the 'LastStmt' expression is used to lift the body of the monad comprehension: [ body | stmts ] => stmts >>= \bndrs -> return body In transform and grouping statements ('then ..' and 'then group ..') the 'return' function is required for nested monad comprehensions, for example: [ body | stmts, then f, rest ] => f [ env | stmts ] >>= \bndrs -> [ body | rest ] BodyStmts require the 'Control.Monad.guard' function for boolean expressions: [ body | exp, stmts ] => guard exp >> [ body | stmts ] Parallel statements require the 'Control.Monad.Zip.mzip' function: [ body | stmts1 | stmts2 | .. ] => mzip stmts1 (mzip stmts2 (..)) >>= \(bndrs1, (bndrs2, ..)) -> return body In any other context than 'MonadComp', the fields for most of these 'SyntaxExpr's stay bottom. -} instance (OutputableBndr idL) => Outputable (ParStmtBlock idL idR) where ppr (ParStmtBlock stmts _ _) = interpp'SP stmts instance (OutputableBndr idL, OutputableBndr idR, Outputable body) => Outputable (StmtLR idL idR body) where ppr stmt = pprStmt stmt pprStmt :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => (StmtLR idL idR body) -> SDoc pprStmt (LastStmt expr _) = ifPprDebug (ptext (sLit "[last]")) <+> ppr expr pprStmt (BindStmt pat expr _ _) = hsep [ppr pat, larrow, ppr expr] pprStmt (LetStmt binds) = hsep [ptext (sLit "let"), pprBinds binds] pprStmt (BodyStmt expr _ _ _) = ppr expr pprStmt (ParStmt stmtss _ _) = sep (punctuate (ptext (sLit " | ")) (map ppr stmtss)) pprStmt (TransStmt { trS_stmts = stmts, trS_by = by, trS_using = using, trS_form = form }) = sep $ punctuate comma (map ppr stmts ++ [pprTransStmt by using form]) pprStmt (RecStmt { recS_stmts = segment, recS_rec_ids = rec_ids , recS_later_ids = later_ids }) = ptext (sLit "rec") <+> vcat [ ppr_do_stmts segment , ifPprDebug (vcat [ ptext (sLit "rec_ids=") <> ppr rec_ids , ptext (sLit "later_ids=") <> ppr later_ids])] pprTransformStmt :: OutputableBndr id => [id] -> LHsExpr id -> Maybe (LHsExpr id) -> SDoc pprTransformStmt bndrs using by = sep [ ptext (sLit "then") <+> ifPprDebug (braces (ppr bndrs)) , nest 2 (ppr using) , nest 2 (pprBy by)] pprTransStmt :: Outputable body => Maybe body -> body -> TransForm -> SDoc pprTransStmt by using ThenForm = sep [ ptext (sLit "then"), nest 2 (ppr using), nest 2 (pprBy by)] pprTransStmt by using GroupForm = sep [ ptext (sLit "then group"), nest 2 (pprBy by), nest 2 (ptext (sLit "using") <+> ppr using)] pprBy :: Outputable body => Maybe body -> SDoc pprBy Nothing = empty pprBy (Just e) = ptext (sLit "by") <+> ppr e pprDo :: (OutputableBndr id, Outputable body) => HsStmtContext any -> [LStmt id body] -> SDoc pprDo DoExpr stmts = ptext (sLit "do") <+> ppr_do_stmts stmts pprDo GhciStmtCtxt stmts = ptext (sLit "do") <+> ppr_do_stmts stmts pprDo ArrowExpr stmts = ptext (sLit "do") <+> ppr_do_stmts stmts pprDo MDoExpr stmts = ptext (sLit "mdo") <+> ppr_do_stmts stmts pprDo ListComp stmts = brackets $ pprComp stmts pprDo PArrComp stmts = paBrackets $ pprComp stmts pprDo MonadComp stmts = brackets $ pprComp stmts pprDo _ _ = panic "pprDo" -- PatGuard, ParStmtCxt ppr_do_stmts :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => [LStmtLR idL idR body] -> SDoc -- Print a bunch of do stmts, with explicit braces and semicolons, -- so that we are not vulnerable to layout bugs ppr_do_stmts stmts = lbrace <+> pprDeeperList vcat (punctuate semi (map ppr stmts)) <+> rbrace pprComp :: (OutputableBndr id, Outputable body) => [LStmt id body] -> SDoc pprComp quals -- Prints: body | qual1, ..., qualn | not (null quals) , L _ (LastStmt body _) <- last quals = hang (ppr body <+> char '|') 2 (pprQuals (dropTail 1 quals)) | otherwise = pprPanic "pprComp" (pprQuals quals) pprQuals :: (OutputableBndr id, Outputable body) => [LStmt id body] -> SDoc -- Show list comprehension qualifiers separated by commas pprQuals quals = interpp'SP quals {- ************************************************************************ * * Template Haskell quotation brackets * * ************************************************************************ -} data HsSplice id = HsTypedSplice -- $z or $(f 4) id -- A unique name to identify this splice point (LHsExpr id) -- See Note [Pending Splices] | HsUntypedSplice -- $z or $(f 4) id -- A unique name to identify this splice point (LHsExpr id) -- See Note [Pending Splices] | HsQuasiQuote -- See Note [Quasi-quote overview] in TcSplice id -- Splice point id -- Quoter SrcSpan -- The span of the enclosed string FastString -- The enclosed string deriving (Typeable ) deriving instance (DataId id) => Data (HsSplice id) isTypedSplice :: HsSplice id -> Bool isTypedSplice (HsTypedSplice {}) = True isTypedSplice _ = False -- Quasi-quotes are untyped splices -- See Note [Pending Splices] type SplicePointName = Name data PendingRnSplice = PendingRnSplice UntypedSpliceFlavour SplicePointName (LHsExpr Name) deriving (Data, Typeable) data UntypedSpliceFlavour = UntypedExpSplice | UntypedPatSplice | UntypedTypeSplice | UntypedDeclSplice deriving( Data, Typeable ) data PendingTcSplice = PendingTcSplice SplicePointName (LHsExpr Id) deriving( Data, Typeable ) {- Note [Pending Splices] ~~~~~~~~~~~~~~~~~~~~~~ When we rename an untyped bracket, we name and lift out all the nested splices, so that when the typechecker hits the bracket, it can typecheck those nested splices without having to walk over the untyped bracket code. So for example [| f $(g x) |] looks like HsBracket (HsApp (HsVar "f") (HsSpliceE _ (g x))) which the renamer rewrites to HsRnBracketOut (HsApp (HsVar f) (HsSpliceE sn (g x))) [PendingRnSplice UntypedExpSplice sn (g x)] * The 'sn' is the Name of the splice point, the SplicePointName * The PendingRnExpSplice gives the splice that splice-point name maps to; and the typechecker can now conveniently find these sub-expressions * The other copy of the splice, in the second argument of HsSpliceE in the renamed first arg of HsRnBracketOut is used only for pretty printing There are four varieties of pending splices generated by the renamer, distinguished by their UntypedSpliceFlavour * Pending expression splices (UntypedExpSplice), e.g., [|$(f x) + 2|] UntypedExpSplice is also used for * quasi-quotes, where the pending expression expands to $(quoter "...blah...") (see RnSplice.makePending, HsQuasiQuote case) * cross-stage lifting, where the pending expression expands to $(lift x) (see RnSplice.checkCrossStageLifting) * Pending pattern splices (UntypedPatSplice), e.g., [| \$(f x) -> x |] * Pending type splices (UntypedTypeSplice), e.g., [| f :: $(g x) |] * Pending declaration (UntypedDeclSplice), e.g., [| let $(f x) in ... |] There is a fifth variety of pending splice, which is generated by the type checker: * Pending *typed* expression splices, (PendingTcSplice), e.g., [||1 + $$(f 2)||] It would be possible to eliminate HsRnBracketOut and use HsBracketOut for the output of the renamer. However, when pretty printing the output of the renamer, e.g., in a type error message, we *do not* want to print out the pending splices. In contrast, when pretty printing the output of the type checker, we *do* want to print the pending splices. So splitting them up seems to make sense, although I hate to add another constructor to HsExpr. -} instance OutputableBndr id => Outputable (HsSplice id) where ppr s = pprSplice s pprPendingSplice :: OutputableBndr id => SplicePointName -> LHsExpr id -> SDoc pprPendingSplice n e = angleBrackets (ppr n <> comma <+> ppr e) pprSplice :: OutputableBndr id => HsSplice id -> SDoc pprSplice (HsTypedSplice n e) = ppr_splice (ptext (sLit "$$")) n e pprSplice (HsUntypedSplice n e) = ppr_splice (ptext (sLit "$")) n e pprSplice (HsQuasiQuote n q _ s) = ppr_quasi n q s ppr_quasi :: OutputableBndr id => id -> id -> FastString -> SDoc ppr_quasi n quoter quote = ifPprDebug (brackets (ppr n)) <> char '[' <> ppr quoter <> ptext (sLit "|") <> ppr quote <> ptext (sLit "|]") ppr_splice :: OutputableBndr id => SDoc -> id -> LHsExpr id -> SDoc ppr_splice herald n e = herald <> ifPprDebug (brackets (ppr n)) <> eDoc where -- We use pprLExpr to match pprParendExpr: -- Using pprLExpr makes sure that we go 'deeper' -- I think that is usually (always?) right pp_as_was = pprLExpr e eDoc = case unLoc e of HsPar _ -> pp_as_was HsVar _ -> pp_as_was _ -> parens pp_as_was data HsBracket id = ExpBr (LHsExpr id) -- [| expr |] | PatBr (LPat id) -- [p| pat |] | DecBrL [LHsDecl id] -- [d| decls |]; result of parser | DecBrG (HsGroup id) -- [d| decls |]; result of renamer | TypBr (LHsType id) -- [t| type |] | VarBr Bool id -- True: 'x, False: ''T -- (The Bool flag is used only in pprHsBracket) | TExpBr (LHsExpr id) -- [|| expr ||] deriving (Typeable) deriving instance (DataId id) => Data (HsBracket id) isTypedBracket :: HsBracket id -> Bool isTypedBracket (TExpBr {}) = True isTypedBracket _ = False instance OutputableBndr id => Outputable (HsBracket id) where ppr = pprHsBracket pprHsBracket :: OutputableBndr id => HsBracket id -> SDoc pprHsBracket (ExpBr e) = thBrackets empty (ppr e) pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p) pprHsBracket (DecBrG gp) = thBrackets (char 'd') (ppr gp) pprHsBracket (DecBrL ds) = thBrackets (char 'd') (vcat (map ppr ds)) pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t) pprHsBracket (VarBr True n) = char '\'' <> ppr n pprHsBracket (VarBr False n) = ptext (sLit "''") <> ppr n pprHsBracket (TExpBr e) = thTyBrackets (ppr e) thBrackets :: SDoc -> SDoc -> SDoc thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+> pp_body <+> ptext (sLit "|]") thTyBrackets :: SDoc -> SDoc thTyBrackets pp_body = ptext (sLit "[||") <+> pp_body <+> ptext (sLit "||]") instance Outputable PendingRnSplice where ppr (PendingRnSplice _ n e) = pprPendingSplice n e instance Outputable PendingTcSplice where ppr (PendingTcSplice n e) = pprPendingSplice n e {- ************************************************************************ * * \subsection{Enumerations and list comprehensions} * * ************************************************************************ -} data ArithSeqInfo id = From (LHsExpr id) | FromThen (LHsExpr id) (LHsExpr id) | FromTo (LHsExpr id) (LHsExpr id) | FromThenTo (LHsExpr id) (LHsExpr id) (LHsExpr id) deriving (Typeable) deriving instance (DataId id) => Data (ArithSeqInfo id) instance OutputableBndr id => Outputable (ArithSeqInfo id) where ppr (From e1) = hcat [ppr e1, pp_dotdot] ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot] ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3] ppr (FromThenTo e1 e2 e3) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3] pp_dotdot :: SDoc pp_dotdot = ptext (sLit " .. ") {- ************************************************************************ * * \subsection{HsMatchCtxt} * * ************************************************************************ -} data HsMatchContext id -- Context of a Match = FunRhs id Bool -- Function binding for f; True <=> written infix | LambdaExpr -- Patterns of a lambda | CaseAlt -- Patterns and guards on a case alternative | IfAlt -- Guards of a multi-way if alternative | ProcExpr -- Patterns of a proc | PatBindRhs -- A pattern binding eg [y] <- e = e | RecUpd -- Record update [used only in DsExpr to -- tell matchWrapper what sort of -- runtime error message to generate] | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt, list comprehension, -- pattern guard, etc | ThPatSplice -- A Template Haskell pattern splice | ThPatQuote -- A Template Haskell pattern quotation [p| (a,b) |] | PatSyn -- A pattern synonym declaration deriving (Data, Typeable) data HsStmtContext id = ListComp | MonadComp | PArrComp -- Parallel array comprehension | DoExpr -- do { ... } | MDoExpr -- mdo { ... } ie recursive do-expression | ArrowExpr -- do-notation in an arrow-command context | GhciStmtCtxt -- A command-line Stmt in GHCi pat <- rhs | PatGuard (HsMatchContext id) -- Pattern guard for specified thing | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt | TransStmtCtxt (HsStmtContext id) -- A branch of a transform stmt deriving (Data, Typeable) isListCompExpr :: HsStmtContext id -> Bool -- Uses syntax [ e | quals ] isListCompExpr ListComp = True isListCompExpr PArrComp = True isListCompExpr MonadComp = True isListCompExpr (ParStmtCtxt c) = isListCompExpr c isListCompExpr (TransStmtCtxt c) = isListCompExpr c isListCompExpr _ = False isMonadCompExpr :: HsStmtContext id -> Bool isMonadCompExpr MonadComp = True isMonadCompExpr (ParStmtCtxt ctxt) = isMonadCompExpr ctxt isMonadCompExpr (TransStmtCtxt ctxt) = isMonadCompExpr ctxt isMonadCompExpr _ = False matchSeparator :: HsMatchContext id -> SDoc matchSeparator (FunRhs {}) = ptext (sLit "=") matchSeparator CaseAlt = ptext (sLit "->") matchSeparator IfAlt = ptext (sLit "->") matchSeparator LambdaExpr = ptext (sLit "->") matchSeparator ProcExpr = ptext (sLit "->") matchSeparator PatBindRhs = ptext (sLit "=") matchSeparator (StmtCtxt _) = ptext (sLit "<-") matchSeparator RecUpd = panic "unused" matchSeparator ThPatSplice = panic "unused" matchSeparator ThPatQuote = panic "unused" matchSeparator PatSyn = panic "unused" pprMatchContext :: Outputable id => HsMatchContext id -> SDoc pprMatchContext ctxt | want_an ctxt = ptext (sLit "an") <+> pprMatchContextNoun ctxt | otherwise = ptext (sLit "a") <+> pprMatchContextNoun ctxt where want_an (FunRhs {}) = True -- Use "an" in front want_an ProcExpr = True want_an _ = False pprMatchContextNoun :: Outputable id => HsMatchContext id -> SDoc pprMatchContextNoun (FunRhs fun _) = ptext (sLit "equation for") <+> quotes (ppr fun) pprMatchContextNoun CaseAlt = ptext (sLit "case alternative") pprMatchContextNoun IfAlt = ptext (sLit "multi-way if alternative") pprMatchContextNoun RecUpd = ptext (sLit "record-update construct") pprMatchContextNoun ThPatSplice = ptext (sLit "Template Haskell pattern splice") pprMatchContextNoun ThPatQuote = ptext (sLit "Template Haskell pattern quotation") pprMatchContextNoun PatBindRhs = ptext (sLit "pattern binding") pprMatchContextNoun LambdaExpr = ptext (sLit "lambda abstraction") pprMatchContextNoun ProcExpr = ptext (sLit "arrow abstraction") pprMatchContextNoun (StmtCtxt ctxt) = ptext (sLit "pattern binding in") $$ pprStmtContext ctxt pprMatchContextNoun PatSyn = ptext (sLit "pattern synonym declaration") ----------------- pprAStmtContext, pprStmtContext :: Outputable id => HsStmtContext id -> SDoc pprAStmtContext ctxt = article <+> pprStmtContext ctxt where pp_an = ptext (sLit "an") pp_a = ptext (sLit "a") article = case ctxt of MDoExpr -> pp_an PArrComp -> pp_an GhciStmtCtxt -> pp_an _ -> pp_a ----------------- pprStmtContext GhciStmtCtxt = ptext (sLit "interactive GHCi command") pprStmtContext DoExpr = ptext (sLit "'do' block") pprStmtContext MDoExpr = ptext (sLit "'mdo' block") pprStmtContext ArrowExpr = ptext (sLit "'do' block in an arrow command") pprStmtContext ListComp = ptext (sLit "list comprehension") pprStmtContext MonadComp = ptext (sLit "monad comprehension") pprStmtContext PArrComp = ptext (sLit "array comprehension") pprStmtContext (PatGuard ctxt) = ptext (sLit "pattern guard for") $$ pprMatchContext ctxt -- Drop the inner contexts when reporting errors, else we get -- Unexpected transform statement -- in a transformed branch of -- transformed branch of -- transformed branch of monad comprehension pprStmtContext (ParStmtCtxt c) | opt_PprStyle_Debug = sep [ptext (sLit "parallel branch of"), pprAStmtContext c] | otherwise = pprStmtContext c pprStmtContext (TransStmtCtxt c) | opt_PprStyle_Debug = sep [ptext (sLit "transformed branch of"), pprAStmtContext c] | otherwise = pprStmtContext c -- Used to generate the string for a *runtime* error message matchContextErrString :: Outputable id => HsMatchContext id -> SDoc matchContextErrString (FunRhs fun _) = ptext (sLit "function") <+> ppr fun matchContextErrString CaseAlt = ptext (sLit "case") matchContextErrString IfAlt = ptext (sLit "multi-way if") matchContextErrString PatBindRhs = ptext (sLit "pattern binding") matchContextErrString RecUpd = ptext (sLit "record update") matchContextErrString LambdaExpr = ptext (sLit "lambda") matchContextErrString ProcExpr = ptext (sLit "proc") matchContextErrString ThPatSplice = panic "matchContextErrString" -- Not used at runtime matchContextErrString ThPatQuote = panic "matchContextErrString" -- Not used at runtime matchContextErrString PatSyn = panic "matchContextErrString" -- Not used at runtime matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c) matchContextErrString (StmtCtxt (TransStmtCtxt c)) = matchContextErrString (StmtCtxt c) matchContextErrString (StmtCtxt (PatGuard _)) = ptext (sLit "pattern guard") matchContextErrString (StmtCtxt GhciStmtCtxt) = ptext (sLit "interactive GHCi command") matchContextErrString (StmtCtxt DoExpr) = ptext (sLit "'do' block") matchContextErrString (StmtCtxt ArrowExpr) = ptext (sLit "'do' block") matchContextErrString (StmtCtxt MDoExpr) = ptext (sLit "'mdo' block") matchContextErrString (StmtCtxt ListComp) = ptext (sLit "list comprehension") matchContextErrString (StmtCtxt MonadComp) = ptext (sLit "monad comprehension") matchContextErrString (StmtCtxt PArrComp) = ptext (sLit "array comprehension") pprMatchInCtxt :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => HsMatchContext idL -> Match idR body -> SDoc pprMatchInCtxt ctxt match = hang (ptext (sLit "In") <+> pprMatchContext ctxt <> colon) 4 (pprMatch ctxt match) pprStmtInCtxt :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => HsStmtContext idL -> StmtLR idL idR body -> SDoc pprStmtInCtxt ctxt (LastStmt e _) | isListCompExpr ctxt -- For [ e | .. ], do not mutter about "stmts" = hang (ptext (sLit "In the expression:")) 2 (ppr e) pprStmtInCtxt ctxt stmt = hang (ptext (sLit "In a stmt of") <+> pprAStmtContext ctxt <> colon) 2 (ppr_stmt stmt) where -- For Group and Transform Stmts, don't print the nested stmts! ppr_stmt (TransStmt { trS_by = by, trS_using = using , trS_form = form }) = pprTransStmt by using form ppr_stmt stmt = pprStmt stmt
fmthoma/ghc
compiler/hsSyn/HsExpr.hs
bsd-3-clause
78,894
0
15
22,191
13,855
7,262
6,593
886
9
module Turbinado.Environment.Params( getParam, getParam_u, populateParamsAndFiles ) where import Control.Monad import qualified Data.ByteString.Lazy.Char8 as BS import Data.ByteString.Lazy.Char8 (ByteString) import qualified Data.Map as M import Data.Int (Int64) import Data.List import Data.Maybe import Network.HTTP import Network.HTTP.Headers import Network.URI import Turbinado.Environment.Header import Turbinado.Environment.Logger import Turbinado.Environment.Request import Turbinado.Environment.Types import Turbinado.Utility.Data import Codec.MIME.Parse import Codec.MIME.Type -- | Attempt to get a Parameter from the Request query string -- or POST body. getParam :: (HasEnvironment m) => String -> m (Maybe String) getParam p = do (Params ps) <- populateParamsAndFiles -- lazy population return $ M.lookup p ps -- | An unsafe version of getParam. Errors if the key does not exist. getParam_u :: (HasEnvironment m) => String -> m String getParam_u p = do r <- getParam p maybe (error $ "getParam_u : key does not exist - \"" ++ p ++ "\"") return r populateParamsAndFiles :: (HasEnvironment m) => m Params populateParamsAndFiles = do e <- getEnvironment case (getParams e) of Just ps' -> return ps' Nothing -> do ct <- getHeader HdrContentType let rm = rqMethod (fromJust' "Params : getParamsFromBody" $ Turbinado.Environment.Types.getRequest e) rb = rqBody (fromJust' "Params : getParamsFromBody" $ Turbinado.Environment.Types.getRequest e) qsPs <- setParamsFromQueryString -- always process the query string case rm of POST -> case ct of Just "application/x-www-form-urlencoded" -> setParamsFromBody rb qsPs _ -> setParamsFromForm rb qsPs _ -> return qsPs -- Functions used by getParam. Not exported. setParamsFromQueryString :: (HasEnvironment m) => m Params setParamsFromQueryString = do e <- getEnvironment let qs = dropWhile (=='?') $ uriQuery $ rqURI (fromJust' "Params : getParamFromQueryString" $ Turbinado.Environment.Types.getRequest e) ps = Params $ M.fromList $ qsDecode qs setEnvironment $ e {getParams = Just ps} return ps setParamsFromBody :: (HasEnvironment m) => String -> Params -> m Params setParamsFromBody s (Params qsps) = do e <- getEnvironment let ps = Params $ M.union (M.fromList $ qsDecode s) qsps setEnvironment $ e {getParams = Just ps} return ps setParamsFromForm :: (HasEnvironment m) => String -> Params -> m Params setParamsFromForm s qsps = multipartDecode s qsps -- LIFTED FROM THE CGI PACKAGE -- | Gets the name-value pairs from urlencoded data. qsDecode :: String -> [(String,String)] qsDecode "" = [] qsDecode s = (urlDecode n, urlDecode (drop 1 v)) : qsDecode (drop 1 rs) where (nv,rs) = break (=='&') s (n,v) = break (=='=') nv multipartDecode :: (HasEnvironment m) => String -> Params -> m Params multipartDecode s qsps = do hd <- getHeader_u HdrContentType errorM $ "hd: " ++ hd let ms = parseMIMEBody [("content-type", hd)] s (fs, ps) = extractParamsAndFiles ms (Params qsps') = qsps ps' = Params $ M.union ps qsps' errorM $ "qsps: " ++ show qsps' errorM $ "ps: " ++ show ps errorM $ "ps': " ++ show (M.union ps qsps') e <- getEnvironment setEnvironment $ e { getFiles = Just $ Files fs, getParams = Just ps'} return ps' {- First draft: If there is a disposition we could have a file, and we look at the content, if there is one single content we add it into the Files Map. If there are more than one Files we run the function for each file. -} extractParamsAndFiles :: MIMEValue -> (M.Map String MIMEValue, M.Map String String) extractParamsAndFiles mi = worker (M.empty, M.empty) mi where worker :: (M.Map String MIMEValue, M.Map String String) -> MIMEValue -> (M.Map String MIMEValue, M.Map String String) worker (fs,ps) mv = if (isSingle mv) then case (getFileAndName $ dispParams $ fromJust' "MIMEValue has no Dispositions" $ mime_val_disp mv) of (True, nm) -> (M.insert nm mv fs,ps) (False, nm) -> (fs, M.insert nm (_getContent mv) ps) else foldl worker (fs, ps) (_getContents mv) _getContent mv = case (mime_val_content mv) of Single c -> c _ -> error "Turbinado.Environment.Params.getContent: called with a Multi Content" _getContents mv = case (mime_val_content mv) of Multi c -> c _ -> error "Turbinado.Environment.Params.getContents: called with a Single Content" isSingle :: MIMEValue -> Bool isSingle mv = case (mime_val_content mv) of Single _ -> True _ -> False getFileAndName :: [DispParam] -> (Bool, String) getFileAndName ds = worker (False, "no-name-found") ds where worker (b, n) [] = (b, n) worker (_, n) ((Filename _):ds') = worker (True, n) ds' worker (b, _) ((Name n'):ds') = worker (b, n') ds'
alsonkemp/turbinado-website
Turbinado/Environment/Params.hs
bsd-3-clause
6,058
0
19
2,185
1,538
799
739
96
4
module Stack.Options.ConfigParser where import Data.Char import Data.Either.Combinators import Data.Monoid.Extra import qualified Data.Set as Set import Options.Applicative import Options.Applicative.Builder.Extra import Path import Stack.Constants import Stack.Options.BuildMonoidParser import Stack.Options.DockerParser import Stack.Options.GhcBuildParser import Stack.Options.GhcVariantParser import Stack.Options.NixParser import Stack.Options.Utils import Stack.Types.Config import qualified System.FilePath as FilePath -- | Command-line arguments parser for configuration. configOptsParser :: FilePath -> GlobalOptsContext -> Parser ConfigMonoid configOptsParser currentDir hide0 = (\stackRoot workDir buildOpts dockerOpts nixOpts systemGHC installGHC arch ghcVariant ghcBuild jobs includes libs overrideGccPath skipGHCCheck skipMsys localBin modifyCodePage allowDifferentUser dumpLogs -> mempty { configMonoidStackRoot = stackRoot , configMonoidWorkDir = workDir , configMonoidBuildOpts = buildOpts , configMonoidDockerOpts = dockerOpts , configMonoidNixOpts = nixOpts , configMonoidSystemGHC = systemGHC , configMonoidInstallGHC = installGHC , configMonoidSkipGHCCheck = skipGHCCheck , configMonoidArch = arch , configMonoidGHCVariant = ghcVariant , configMonoidGHCBuild = ghcBuild , configMonoidJobs = jobs , configMonoidExtraIncludeDirs = includes , configMonoidExtraLibDirs = libs , configMonoidOverrideGccPath = overrideGccPath , configMonoidSkipMsys = skipMsys , configMonoidLocalBinPath = localBin , configMonoidModifyCodePage = modifyCodePage , configMonoidAllowDifferentUser = allowDifferentUser , configMonoidDumpLogs = dumpLogs }) <$> optionalFirst (absDirOption ( long stackRootOptionName <> metavar (map toUpper stackRootOptionName) <> help ("Absolute path to the global stack root directory " ++ "(Overrides any STACK_ROOT environment variable)") <> hide )) <*> optionalFirst (option (eitherReader (mapLeft showWorkDirError . parseRelDir)) ( long "work-dir" <> metavar "WORK-DIR" <> completer (pathCompleterWith (defaultPathCompleterOpts { pcoAbsolute = False, pcoFileFilter = const False })) <> help ("Relative path of work directory " ++ "(Overrides any STACK_WORK environment variable, default is '.stack-work')") <> hide )) <*> buildOptsMonoidParser hide0 <*> dockerOptsParser True <*> nixOptsParser True <*> firstBoolFlags "system-ghc" "using the system installed GHC (on the PATH) if available and a matching version. Disabled by default." hide <*> firstBoolFlags "install-ghc" "downloading and installing GHC if necessary (can be done manually with stack setup)" hide <*> optionalFirst (strOption ( long "arch" <> metavar "ARCH" <> help "System architecture, e.g. i386, x86_64" <> hide )) <*> optionalFirst (ghcVariantParser (hide0 /= OuterGlobalOpts)) <*> optionalFirst (ghcBuildParser (hide0 /= OuterGlobalOpts)) <*> optionalFirst (option auto ( long "jobs" <> short 'j' <> metavar "JOBS" <> help "Number of concurrent jobs to run" <> hide )) <*> fmap Set.fromList (many ((currentDir FilePath.</>) <$> strOption ( long "extra-include-dirs" <> metavar "DIR" <> completer dirCompleter <> help "Extra directories to check for C header files" <> hide ))) <*> fmap Set.fromList (many ((currentDir FilePath.</>) <$> strOption ( long "extra-lib-dirs" <> metavar "DIR" <> completer dirCompleter <> help "Extra directories to check for libraries" <> hide ))) <*> optionalFirst (absFileOption ( long "with-gcc" <> metavar "PATH-TO-GCC" <> help "Use gcc found at PATH-TO-GCC" <> hide )) <*> firstBoolFlags "skip-ghc-check" "skipping the GHC version and architecture check" hide <*> firstBoolFlags "skip-msys" "skipping the local MSYS installation (Windows only)" hide <*> optionalFirst (strOption ( long "local-bin-path" <> metavar "DIR" <> completer dirCompleter <> help "Install binaries to DIR" <> hide )) <*> firstBoolFlags "modify-code-page" "setting the codepage to support UTF-8 (Windows only)" hide <*> firstBoolFlags "allow-different-user" ("permission for users other than the owner of the stack root " ++ "directory to use a stack installation (POSIX only)") hide <*> fmap toDumpLogs (firstBoolFlags "dump-logs" "dump the build output logs for local packages to the console" hide) where hide = hideMods (hide0 /= OuterGlobalOpts) toDumpLogs (First (Just True)) = First (Just DumpAllLogs) toDumpLogs (First (Just False)) = First (Just DumpNoLogs) toDumpLogs (First Nothing) = First Nothing showWorkDirError err = show err ++ "\nNote that --work-dir must be a relative child directory, because work-dirs outside of the package are not supported by Cabal." ++ "\nSee https://github.com/commercialhaskell/stack/issues/2954"
mrkkrp/stack
src/Stack/Options/ConfigParser.hs
bsd-3-clause
5,961
0
37
1,886
1,000
524
476
129
3
foo = let x = 5 in let zig x = zag x zag y = zig x in zag fco = let fst (x:xs) = x in fst 5 fbo = \ x -> y fbo = let head (x:xs) = x head (x:xs) = xs in head fao = let id x = x in (id, id) fzo = let fst (x, y) = x fst [] = 0 in fst fco =let fst1 (x, y) = 1 fst2 [] = 0 in (fst1, fst2) fbo = let fst (x:xs) = x fst [] = 0 in fst fbo = let zig = 1:zag zag = 2:zig in zig fbo = let (a, b) = ([], []) ones = 1:ones in ones fco = let (a, b) = (5, "foo") in (b, a) fbo = let (a, b) = (5, "foo") in a fao = let y = 5 in \ x -> [x, x, (\ x -> x)]
themattchan/tandoori
input/input-1.hs
bsd-3-clause
739
13
11
361
474
228
246
33
2
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE GADTSyntax #-} module T17379b where import Language.Haskell.TH $(let typ = mkName "T" in pure [ DataD [] typ [] Nothing [RecGadtC [] [] (ConT typ)] [] ])
sdiehl/ghc
testsuite/tests/th/T17379b.hs
bsd-3-clause
203
0
15
36
78
40
38
5
0
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you 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 KindSignatures #-} module Thrift.Serializable ( ThriftSerializable(..) , Serialized(..) , serialize , deserialize ) where import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as BS import Thrift.Protocol import Thrift.Transport (Transport) import Thrift.Transport.Empty newtype Serialized (p :: * -> *) = Serialized { getBS :: ByteString } class ThriftSerializable a where encode :: (Protocol p, Transport t) => p t -> a -> BS.ByteString decode :: (Protocol p, Transport t) => p t -> BS.ByteString -> a serialize :: (ThriftSerializable a, Protocol p) => a -> Serialized p serialize = s . BS.toStrict . encode prot where (s, prot) = (Serialized, mkProtocol EmptyTransport) :: Protocol p => (ByteString -> Serialized p, p EmptyTransport) deserialize :: (ThriftSerializable a, Protocol p) => Serialized p -> a deserialize = decode prot . BS.fromStrict . get where (get, prot) = (getBS, mkProtocol EmptyTransport) :: Protocol p => (Serialized p -> ByteString, p EmptyTransport)
getyourguide/fbthrift
thrift/lib/hs/Thrift/Serializable.hs
apache-2.0
1,857
0
10
325
374
216
158
23
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="sk-SK"> <title>AMF Support</title> <maps> <homeID>amf</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/amf/src/main/javahelp/help_sk_SK/helpset_sk_SK.hs
apache-2.0
956
82
52
156
390
206
184
-1
-1
{-+ Reusable functions for translation from the (non-recursive) base structure to Stratego. -} module BaseStruct2Stratego where import StrategoAST import BaseSyntax hiding (EntSpec(..)) -- non-recursive base syntax structure import PrettyPrint(pp) transP trId trP p = case mapPI trId trP p of HsPId n -> Pvar (getHSName n) -- constructor vs variable ?? HsPLit (HsInt _ i) -> Pconst i HsPInfixApp x op y -> Pcondata (getHSName op) [x,y] -- con vs var ?? HsPApp n ps -> Pcondata n ps HsPTuple ps -> Ptuple ps HsPIrrPat p -> Ptilde p HsPParen p -> p _ -> error ("no "++pp p++" patterns yet") transD trId trE trP trDs trT trC trTp d = case mapDI trId trE trP trDs trT trC trTp d of HsPatBind loc p b ds -> Val p (transRhs b) ds HsFunBind loc matches -> Fun (name matches) (map g matches) where name (HsMatch loc nm ps rhs ds: ms) = nm g (HsMatch loc nm ps rhs ds) = (ps,transRhs rhs,ds) other -> error ("illegal dec "++pp d) --transRhs :: HsRhs E -> B transRhs (HsBody e) = Normal e transRhs (HsGuard triples) = Guarded(map f triples) where f (loc,guard,body) = (guard,body) --transAlt :: HsAlt E P [D] -> (P,B,[D]) transAlt (HsAlt loc pat rhs ds) = (pat,transRhs rhs,ds) transE trId trE trP trDs trT trC e = case mapEI trId trE trP trDs trT trC e of HsId n -> Var (getHSName n) -- constructor vs variable ?? HsApp x y -> App x y HsLit (HsInt _ i) -> Const i HsInfixApp x op z -> App (App (Var (getHSName op)) x) z -- con vs var ?? HsNegApp _ x -> App (Var "negate") x HsLambda ps e -> Abs ps e HsLet ds e -> Let ds e HsIf x y z -> Cond x y z HsCase e alts -> Case e (map transAlt alts) HsTuple xs -> TupleExp xs HsList xs -> foldr cons nil xs where cons x xs = ConApp ":" [(x,Lazy),(xs,Lazy)] nil = ConApp "[]" [] HsParen x -> x HsLeftSection x op -> Abs[Pvar "zzz"] (App (App (Var (getHSName op)) x) (Var "zzz")) HsRightSection op y -> Abs[Pvar "zzz"] (App (App (Var (getHSName op)) (Var "zzz")) y) other -> error ("no translation yet for: "++pp e) --showId (HsVar x) = show x --showId (HsCon x) = show x showId x = pp x
forste/haReFork
tools/Phugs/BaseStruct2Stratego.hs
bsd-3-clause
2,386
1
16
763
935
459
476
47
15
{-# LANGUAGE MagicHash #-} module T7287 where import GHC.Prim {-# RULES "int2Word#/word2Int#" forall x. int2Word# (word2Int# x) = x #-} {- We get a legitimate T7287.hs:7:3: warning: Rule int2Word#/word2Int# may never fire because rule "word2Int#" for ‘word2Int#’ might fire first Probable fix: add phase [n] or [~n] to the competing rule because rule "word2Int#" is the constant folding rule that converts a sufficiently-narrow Word# literal to an Int#. There is a similar one for int2Word#, so the whole lot is confluent. -}
sdiehl/ghc
testsuite/tests/simplCore/should_compile/T7287.hs
bsd-3-clause
566
0
4
118
12
9
3
5
0
{- ------------------------------------------------------------------------ (c) The GHC Team, 1992-2012 DeriveConstants is a program that extracts information from the C declarations in the header files (primarily struct field offsets) and generates various files, such as a header file that can be #included into non-C source containing this information. We want to get information about code generated by the C compiler, such as the sizes of types, and offsets of struct fields. We need this because the layout of certain runtime objects is defined in C headers (e.g. includes/rts/storage/Closures.h), but we need access to the layout of these structures from a Haskell program (GHC). One way to do this is to compile and run a C program that includes the header files and prints out the sizes and offsets. However, when we are cross-compiling, we can't run a C program compiled for the target platform. So, this program works as follows: we generate a C program that when compiled to an object file, has the information we need encoded as symbol sizes. This means that we can extract the information without needing to run the program, by inspecting the object file using 'nm'. ------------------------------------------------------------------------ -} import Control.Monad (when, unless) import Data.Bits (shiftL) import Data.Char (toLower) import Data.List (stripPrefix) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (catMaybes) import Numeric (readHex) import System.Environment (getArgs) import System.Exit (ExitCode(ExitSuccess), exitFailure) import System.FilePath ((</>)) import System.IO (stderr, hPutStrLn) import System.Info (os) import System.Process (showCommandForUser, readProcess, rawSystem) main :: IO () main = do opts <- parseArgs let getOption descr opt = case opt opts of Just x -> return x Nothing -> die ("No " ++ descr ++ " given") mode <- getOption "mode" o_mode fn <- getOption "output filename" o_outputFilename case mode of Gen_Haskell_Type -> writeHaskellType fn haskellWanteds Gen_Haskell_Wrappers -> writeHaskellWrappers fn haskellWanteds Gen_Haskell_Exports -> writeHaskellExports fn haskellWanteds Gen_Computed cm -> do tmpdir <- getOption "tmpdir" o_tmpdir gccProg <- getOption "gcc program" o_gccProg nmProg <- getOption "nm program" o_nmProg let verbose = o_verbose opts gccFlags = o_gccFlags opts rs <- getWanted verbose tmpdir gccProg gccFlags nmProg let haskellRs = [ what | (wh, what) <- rs , wh `elem` [Haskell, Both] ] cRs = [ what | (wh, what) <- rs , wh `elem` [C, Both] ] case cm of ComputeHaskell -> writeHaskellValue fn haskellRs ComputeHeader -> writeHeader fn cRs where haskellWanteds = [ what | (wh, what) <- wanteds, wh `elem` [Haskell, Both] ] data Options = Options { o_verbose :: Bool, o_mode :: Maybe Mode, o_tmpdir :: Maybe FilePath, o_outputFilename :: Maybe FilePath, o_gccProg :: Maybe FilePath, o_gccFlags :: [String], o_nmProg :: Maybe FilePath } parseArgs :: IO Options parseArgs = do args <- getArgs opts <- f emptyOptions args return (opts {o_gccFlags = reverse (o_gccFlags opts)}) where emptyOptions = Options { o_verbose = False, o_mode = Nothing, o_tmpdir = Nothing, o_outputFilename = Nothing, o_gccProg = Nothing, o_gccFlags = [], o_nmProg = Nothing } f opts [] = return opts f opts ("-v" : args') = f (opts {o_verbose = True}) args' f opts ("--gen-haskell-type" : args') = f (opts {o_mode = Just Gen_Haskell_Type}) args' f opts ("--gen-haskell-value" : args') = f (opts {o_mode = Just (Gen_Computed ComputeHaskell)}) args' f opts ("--gen-haskell-wrappers" : args') = f (opts {o_mode = Just Gen_Haskell_Wrappers}) args' f opts ("--gen-haskell-exports" : args') = f (opts {o_mode = Just Gen_Haskell_Exports}) args' f opts ("--gen-header" : args') = f (opts {o_mode = Just (Gen_Computed ComputeHeader)}) args' f opts ("--tmpdir" : dir : args') = f (opts {o_tmpdir = Just dir}) args' f opts ("-o" : fn : args') = f (opts {o_outputFilename = Just fn}) args' f opts ("--gcc-program" : prog : args') = f (opts {o_gccProg = Just prog}) args' f opts ("--gcc-flag" : flag : args') = f (opts {o_gccFlags = flag : o_gccFlags opts}) args' f opts ("--nm-program" : prog : args') = f (opts {o_nmProg = Just prog}) args' f _ (flag : _) = die ("Unrecognised flag: " ++ show flag) data Mode = Gen_Haskell_Type | Gen_Haskell_Wrappers | Gen_Haskell_Exports | Gen_Computed ComputeMode data ComputeMode = ComputeHaskell | ComputeHeader type Wanteds = [(Where, What Fst)] type Results = [(Where, What Snd)] type Name = String newtype CExpr = CExpr String newtype CPPExpr = CPPExpr String data What f = GetFieldType Name (f CExpr Integer) | GetClosureSize Name (f CExpr Integer) | GetWord Name (f CExpr Integer) | GetInt Name (f CExpr Integer) | GetNatural Name (f CExpr Integer) | GetBool Name (f CPPExpr Bool) | StructFieldMacro Name | ClosureFieldMacro Name | ClosurePayloadMacro Name | FieldTypeGcptrMacro Name data Fst a b = Fst a data Snd a b = Snd b data Where = C | Haskell | Both deriving Eq constantInt :: Where -> Name -> String -> Wanteds constantInt w name expr = [(w, GetInt name (Fst (CExpr expr)))] constantWord :: Where -> Name -> String -> Wanteds constantWord w name expr = [(w, GetWord name (Fst (CExpr expr)))] constantNatural :: Where -> Name -> String -> Wanteds constantNatural w name expr = [(w, GetNatural name (Fst (CExpr expr)))] constantBool :: Where -> Name -> String -> Wanteds constantBool w name expr = [(w, GetBool name (Fst (CPPExpr expr)))] fieldOffset :: Where -> String -> String -> Wanteds fieldOffset w theType theField = fieldOffset_ w nameBase theType theField where nameBase = theType ++ "_" ++ theField fieldOffset_ :: Where -> Name -> String -> String -> Wanteds fieldOffset_ w nameBase theType theField = [(w, GetWord name (Fst (CExpr expr)))] where name = "OFFSET_" ++ nameBase expr = "offsetof(" ++ theType ++ ", " ++ theField ++ ")" -- FieldType is for defining REP_x to be b32 etc -- These are both the C-- types used in a load -- e.g. b32[addr] -- and the names of the CmmTypes in the compiler -- b32 :: CmmType fieldType' :: Where -> String -> String -> Wanteds fieldType' w theType theField = fieldType_' w nameBase theType theField where nameBase = theType ++ "_" ++ theField fieldType_' :: Where -> Name -> String -> String -> Wanteds fieldType_' w nameBase theType theField = [(w, GetFieldType name (Fst (CExpr expr)))] where name = "REP_" ++ nameBase expr = "FIELD_SIZE(" ++ theType ++ ", " ++ theField ++ ")" structField :: Where -> String -> String -> Wanteds structField = structFieldHelper C structFieldH :: Where -> String -> String -> Wanteds structFieldH w = structFieldHelper w w structField_ :: Where -> Name -> String -> String -> Wanteds structField_ w nameBase theType theField = fieldOffset_ w nameBase theType theField ++ fieldType_' C nameBase theType theField ++ structFieldMacro nameBase structFieldMacro :: Name -> Wanteds structFieldMacro nameBase = [(C, StructFieldMacro nameBase)] -- Outputs the byte offset and MachRep for a field structFieldHelper :: Where -> Where -> String -> String -> Wanteds structFieldHelper wFT w theType theField = fieldOffset w theType theField ++ fieldType' wFT theType theField ++ structFieldMacro nameBase where nameBase = theType ++ "_" ++ theField closureFieldMacro :: Name -> Wanteds closureFieldMacro nameBase = [(C, ClosureFieldMacro nameBase)] closurePayload :: Where -> String -> String -> Wanteds closurePayload w theType theField = closureFieldOffset_ w nameBase theType theField ++ closurePayloadMacro nameBase where nameBase = theType ++ "_" ++ theField closurePayloadMacro :: Name -> Wanteds closurePayloadMacro nameBase = [(C, ClosurePayloadMacro nameBase)] -- Byte offset and MachRep for a closure field, minus the header closureField_ :: Where -> Name -> String -> String -> Wanteds closureField_ w nameBase theType theField = closureFieldOffset_ w nameBase theType theField ++ fieldType_' C nameBase theType theField ++ closureFieldMacro nameBase closureField :: Where -> String -> String -> Wanteds closureField w theType theField = closureField_ w nameBase theType theField where nameBase = theType ++ "_" ++ theField closureFieldOffset_ :: Where -> Name -> String -> String -> Wanteds closureFieldOffset_ w nameBase theType theField = defOffset w nameBase (CExpr ("offsetof(" ++ theType ++ ", " ++ theField ++ ") - TYPE_SIZE(StgHeader)")) -- Size of a closure type, minus the header, named SIZEOF_<type>_NoHdr -- Also, we #define SIZEOF_<type> to be the size of the whole closure for .cmm. closureSize :: Where -> String -> Wanteds closureSize w theType = defSize w (theType ++ "_NoHdr") (CExpr expr) ++ defClosureSize C theType (CExpr expr) where expr = "TYPE_SIZE(" ++ theType ++ ") - TYPE_SIZE(StgHeader)" -- Byte offset and MachRep for a closure field, minus the header closureFieldGcptr :: Where -> String -> String -> Wanteds closureFieldGcptr w theType theField = closureFieldOffset_ w nameBase theType theField ++ fieldTypeGcptr nameBase ++ closureFieldMacro nameBase where nameBase = theType ++ "_" ++ theField fieldTypeGcptr :: Name -> Wanteds fieldTypeGcptr nameBase = [(C, FieldTypeGcptrMacro nameBase)] closureFieldOffset :: Where -> String -> String -> Wanteds closureFieldOffset w theType theField = defOffset w nameBase (CExpr expr) where nameBase = theType ++ "_" ++ theField expr = "offsetof(" ++ theType ++ ", " ++ theField ++ ") - TYPE_SIZE(StgHeader)" thunkSize :: Where -> String -> Wanteds thunkSize w theType = defSize w (theType ++ "_NoThunkHdr") (CExpr expr) ++ closureSize w theType where expr = "TYPE_SIZE(" ++ theType ++ ") - TYPE_SIZE(StgThunkHeader)" defIntOffset :: Where -> Name -> String -> Wanteds defIntOffset w nameBase cExpr = [(w, GetInt ("OFFSET_" ++ nameBase) (Fst (CExpr cExpr)))] defOffset :: Where -> Name -> CExpr -> Wanteds defOffset w nameBase cExpr = [(w, GetWord ("OFFSET_" ++ nameBase) (Fst cExpr))] structSize :: Where -> String -> Wanteds structSize w theType = defSize w theType (CExpr ("TYPE_SIZE(" ++ theType ++ ")")) defSize :: Where -> Name -> CExpr -> Wanteds defSize w nameBase cExpr = [(w, GetWord ("SIZEOF_" ++ nameBase) (Fst cExpr))] defClosureSize :: Where -> Name -> CExpr -> Wanteds defClosureSize w nameBase cExpr = [(w, GetClosureSize ("SIZEOF_" ++ nameBase) (Fst cExpr))] haskellise :: Name -> Name haskellise (c : cs) = toLower c : cs haskellise "" = "" wanteds :: Wanteds wanteds = concat [-- Closure header sizes. constantWord Both "STD_HDR_SIZE" -- grrr.. PROFILING is on so we need to -- subtract sizeofW(StgProfHeader) "sizeofW(StgHeader) - sizeofW(StgProfHeader)" ,constantWord Both "PROF_HDR_SIZE" "sizeofW(StgProfHeader)" -- Size of a storage manager block (in bytes). ,constantWord Both "BLOCK_SIZE" "BLOCK_SIZE" ,constantWord C "MBLOCK_SIZE" "MBLOCK_SIZE" -- blocks that fit in an MBlock, leaving space for the block -- descriptors ,constantWord Both "BLOCKS_PER_MBLOCK" "BLOCKS_PER_MBLOCK" -- could be derived, but better to save doing the calculation twice ,fieldOffset Both "StgRegTable" "rR1" ,fieldOffset Both "StgRegTable" "rR2" ,fieldOffset Both "StgRegTable" "rR3" ,fieldOffset Both "StgRegTable" "rR4" ,fieldOffset Both "StgRegTable" "rR5" ,fieldOffset Both "StgRegTable" "rR6" ,fieldOffset Both "StgRegTable" "rR7" ,fieldOffset Both "StgRegTable" "rR8" ,fieldOffset Both "StgRegTable" "rR9" ,fieldOffset Both "StgRegTable" "rR10" ,fieldOffset Both "StgRegTable" "rF1" ,fieldOffset Both "StgRegTable" "rF2" ,fieldOffset Both "StgRegTable" "rF3" ,fieldOffset Both "StgRegTable" "rF4" ,fieldOffset Both "StgRegTable" "rF5" ,fieldOffset Both "StgRegTable" "rF6" ,fieldOffset Both "StgRegTable" "rD1" ,fieldOffset Both "StgRegTable" "rD2" ,fieldOffset Both "StgRegTable" "rD3" ,fieldOffset Both "StgRegTable" "rD4" ,fieldOffset Both "StgRegTable" "rD5" ,fieldOffset Both "StgRegTable" "rD6" ,fieldOffset Both "StgRegTable" "rXMM1" ,fieldOffset Both "StgRegTable" "rXMM2" ,fieldOffset Both "StgRegTable" "rXMM3" ,fieldOffset Both "StgRegTable" "rXMM4" ,fieldOffset Both "StgRegTable" "rXMM5" ,fieldOffset Both "StgRegTable" "rXMM6" ,fieldOffset Both "StgRegTable" "rYMM1" ,fieldOffset Both "StgRegTable" "rYMM2" ,fieldOffset Both "StgRegTable" "rYMM3" ,fieldOffset Both "StgRegTable" "rYMM4" ,fieldOffset Both "StgRegTable" "rYMM5" ,fieldOffset Both "StgRegTable" "rYMM6" ,fieldOffset Both "StgRegTable" "rZMM1" ,fieldOffset Both "StgRegTable" "rZMM2" ,fieldOffset Both "StgRegTable" "rZMM3" ,fieldOffset Both "StgRegTable" "rZMM4" ,fieldOffset Both "StgRegTable" "rZMM5" ,fieldOffset Both "StgRegTable" "rZMM6" ,fieldOffset Both "StgRegTable" "rL1" ,fieldOffset Both "StgRegTable" "rSp" ,fieldOffset Both "StgRegTable" "rSpLim" ,fieldOffset Both "StgRegTable" "rHp" ,fieldOffset Both "StgRegTable" "rHpLim" ,fieldOffset Both "StgRegTable" "rCCCS" ,fieldOffset Both "StgRegTable" "rCurrentTSO" ,fieldOffset Both "StgRegTable" "rCurrentNursery" ,fieldOffset Both "StgRegTable" "rHpAlloc" ,structField C "StgRegTable" "rRet" ,structField C "StgRegTable" "rNursery" ,defIntOffset Both "stgEagerBlackholeInfo" "FUN_OFFSET(stgEagerBlackholeInfo)" ,defIntOffset Both "stgGCEnter1" "FUN_OFFSET(stgGCEnter1)" ,defIntOffset Both "stgGCFun" "FUN_OFFSET(stgGCFun)" ,fieldOffset Both "Capability" "r" ,fieldOffset C "Capability" "lock" ,structField C "Capability" "no" ,structField C "Capability" "mut_lists" ,structField C "Capability" "context_switch" ,structField C "Capability" "interrupt" ,structField C "Capability" "sparks" ,structField C "Capability" "total_allocated" ,structField C "Capability" "weak_ptr_list_hd" ,structField C "Capability" "weak_ptr_list_tl" ,structField Both "bdescr" "start" ,structField Both "bdescr" "free" ,structField Both "bdescr" "blocks" ,structField C "bdescr" "gen_no" ,structField C "bdescr" "link" ,structSize C "generation" ,structField C "generation" "n_new_large_words" ,structField C "generation" "weak_ptr_list" ,structSize Both "CostCentreStack" ,structField C "CostCentreStack" "ccsID" ,structFieldH Both "CostCentreStack" "mem_alloc" ,structFieldH Both "CostCentreStack" "scc_count" ,structField C "CostCentreStack" "prevStack" ,structField C "CostCentre" "ccID" ,structField C "CostCentre" "link" ,structField C "StgHeader" "info" ,structField_ Both "StgHeader_ccs" "StgHeader" "prof.ccs" ,structField_ Both "StgHeader_ldvw" "StgHeader" "prof.hp.ldvw" ,structSize Both "StgSMPThunkHeader" ,closurePayload C "StgClosure" "payload" ,structFieldH Both "StgEntCounter" "allocs" ,structFieldH Both "StgEntCounter" "allocd" ,structField Both "StgEntCounter" "registeredp" ,structField Both "StgEntCounter" "link" ,structField Both "StgEntCounter" "entry_count" ,closureSize Both "StgUpdateFrame" ,closureSize C "StgCatchFrame" ,closureSize C "StgStopFrame" ,closureSize Both "StgMutArrPtrs" ,closureField Both "StgMutArrPtrs" "ptrs" ,closureField Both "StgMutArrPtrs" "size" ,closureSize Both "StgSmallMutArrPtrs" ,closureField Both "StgSmallMutArrPtrs" "ptrs" ,closureSize Both "StgArrWords" ,closureField Both "StgArrWords" "bytes" ,closurePayload C "StgArrWords" "payload" ,closureField C "StgTSO" "_link" ,closureField C "StgTSO" "global_link" ,closureField C "StgTSO" "what_next" ,closureField C "StgTSO" "why_blocked" ,closureField C "StgTSO" "block_info" ,closureField C "StgTSO" "blocked_exceptions" ,closureField C "StgTSO" "id" ,closureField C "StgTSO" "cap" ,closureField C "StgTSO" "saved_errno" ,closureField C "StgTSO" "trec" ,closureField C "StgTSO" "flags" ,closureField C "StgTSO" "dirty" ,closureField C "StgTSO" "bq" ,closureField Both "StgTSO" "alloc_limit" ,closureField_ Both "StgTSO_cccs" "StgTSO" "prof.cccs" ,closureField Both "StgTSO" "stackobj" ,closureField Both "StgStack" "sp" ,closureFieldOffset Both "StgStack" "stack" ,closureField C "StgStack" "stack_size" ,closureField C "StgStack" "dirty" ,structSize C "StgTSOProfInfo" ,closureField Both "StgUpdateFrame" "updatee" ,closureField C "StgCatchFrame" "handler" ,closureField C "StgCatchFrame" "exceptions_blocked" ,closureSize C "StgPAP" ,closureField C "StgPAP" "n_args" ,closureFieldGcptr C "StgPAP" "fun" ,closureField C "StgPAP" "arity" ,closurePayload C "StgPAP" "payload" ,thunkSize C "StgAP" ,closureField C "StgAP" "n_args" ,closureFieldGcptr C "StgAP" "fun" ,closurePayload C "StgAP" "payload" ,thunkSize C "StgAP_STACK" ,closureField C "StgAP_STACK" "size" ,closureFieldGcptr C "StgAP_STACK" "fun" ,closurePayload C "StgAP_STACK" "payload" ,thunkSize C "StgSelector" ,closureFieldGcptr C "StgInd" "indirectee" ,closureSize C "StgMutVar" ,closureField C "StgMutVar" "var" ,closureSize C "StgAtomicallyFrame" ,closureField C "StgAtomicallyFrame" "code" ,closureField C "StgAtomicallyFrame" "next_invariant_to_check" ,closureField C "StgAtomicallyFrame" "result" ,closureField C "StgInvariantCheckQueue" "invariant" ,closureField C "StgInvariantCheckQueue" "my_execution" ,closureField C "StgInvariantCheckQueue" "next_queue_entry" ,closureField C "StgAtomicInvariant" "code" ,closureField C "StgTRecHeader" "enclosing_trec" ,closureSize C "StgCatchSTMFrame" ,closureField C "StgCatchSTMFrame" "handler" ,closureField C "StgCatchSTMFrame" "code" ,closureSize C "StgCatchRetryFrame" ,closureField C "StgCatchRetryFrame" "running_alt_code" ,closureField C "StgCatchRetryFrame" "first_code" ,closureField C "StgCatchRetryFrame" "alt_code" ,closureField C "StgTVarWatchQueue" "closure" ,closureField C "StgTVarWatchQueue" "next_queue_entry" ,closureField C "StgTVarWatchQueue" "prev_queue_entry" ,closureSize C "StgTVar" ,closureField C "StgTVar" "current_value" ,closureField C "StgTVar" "first_watch_queue_entry" ,closureField C "StgTVar" "num_updates" ,closureSize C "StgWeak" ,closureField C "StgWeak" "link" ,closureField C "StgWeak" "key" ,closureField C "StgWeak" "value" ,closureField C "StgWeak" "finalizer" ,closureField C "StgWeak" "cfinalizers" ,closureSize C "StgCFinalizerList" ,closureField C "StgCFinalizerList" "link" ,closureField C "StgCFinalizerList" "fptr" ,closureField C "StgCFinalizerList" "ptr" ,closureField C "StgCFinalizerList" "eptr" ,closureField C "StgCFinalizerList" "flag" ,closureSize C "StgMVar" ,closureField C "StgMVar" "head" ,closureField C "StgMVar" "tail" ,closureField C "StgMVar" "value" ,closureSize C "StgMVarTSOQueue" ,closureField C "StgMVarTSOQueue" "link" ,closureField C "StgMVarTSOQueue" "tso" ,closureSize C "StgBCO" ,closureField C "StgBCO" "instrs" ,closureField C "StgBCO" "literals" ,closureField C "StgBCO" "ptrs" ,closureField C "StgBCO" "arity" ,closureField C "StgBCO" "size" ,closurePayload C "StgBCO" "bitmap" ,closureSize C "StgStableName" ,closureField C "StgStableName" "sn" ,closureSize C "StgBlockingQueue" ,closureField C "StgBlockingQueue" "bh" ,closureField C "StgBlockingQueue" "owner" ,closureField C "StgBlockingQueue" "queue" ,closureField C "StgBlockingQueue" "link" ,closureSize C "MessageBlackHole" ,closureField C "MessageBlackHole" "link" ,closureField C "MessageBlackHole" "tso" ,closureField C "MessageBlackHole" "bh" ,structField_ C "RtsFlags_ProfFlags_showCCSOnException" "RTS_FLAGS" "ProfFlags.showCCSOnException" ,structField_ C "RtsFlags_DebugFlags_apply" "RTS_FLAGS" "DebugFlags.apply" ,structField_ C "RtsFlags_DebugFlags_sanity" "RTS_FLAGS" "DebugFlags.sanity" ,structField_ C "RtsFlags_DebugFlags_weak" "RTS_FLAGS" "DebugFlags.weak" ,structField_ C "RtsFlags_GcFlags_initialStkSize" "RTS_FLAGS" "GcFlags.initialStkSize" ,structField_ C "RtsFlags_MiscFlags_tickInterval" "RTS_FLAGS" "MiscFlags.tickInterval" ,structSize C "StgFunInfoExtraFwd" ,structField C "StgFunInfoExtraFwd" "slow_apply" ,structField C "StgFunInfoExtraFwd" "fun_type" ,structFieldH Both "StgFunInfoExtraFwd" "arity" ,structField_ C "StgFunInfoExtraFwd_bitmap" "StgFunInfoExtraFwd" "b.bitmap" ,structSize Both "StgFunInfoExtraRev" ,structField C "StgFunInfoExtraRev" "slow_apply_offset" ,structField C "StgFunInfoExtraRev" "fun_type" ,structFieldH Both "StgFunInfoExtraRev" "arity" ,structField_ C "StgFunInfoExtraRev_bitmap" "StgFunInfoExtraRev" "b.bitmap" ,structField C "StgLargeBitmap" "size" ,fieldOffset C "StgLargeBitmap" "bitmap" ,structSize C "snEntry" ,structField C "snEntry" "sn_obj" ,structField C "snEntry" "addr" ,structSize C "spEntry" ,structField C "spEntry" "addr" -- Note that this conditional part only affects the C headers. -- That's important, as it means we get the same PlatformConstants -- type on all platforms. ,if os == "mingw32" then concat [structSize C "StgAsyncIOResult" ,structField C "StgAsyncIOResult" "reqID" ,structField C "StgAsyncIOResult" "len" ,structField C "StgAsyncIOResult" "errCode"] else [] -- pre-compiled thunk types ,constantWord Haskell "MAX_SPEC_SELECTEE_SIZE" "MAX_SPEC_SELECTEE_SIZE" ,constantWord Haskell "MAX_SPEC_AP_SIZE" "MAX_SPEC_AP_SIZE" -- closure sizes: these do NOT include the header (see below for -- header sizes) ,constantWord Haskell "MIN_PAYLOAD_SIZE" "MIN_PAYLOAD_SIZE" ,constantInt Haskell "MIN_INTLIKE" "MIN_INTLIKE" ,constantWord Haskell "MAX_INTLIKE" "MAX_INTLIKE" ,constantWord Haskell "MIN_CHARLIKE" "MIN_CHARLIKE" ,constantWord Haskell "MAX_CHARLIKE" "MAX_CHARLIKE" ,constantWord Haskell "MUT_ARR_PTRS_CARD_BITS" "MUT_ARR_PTRS_CARD_BITS" -- A section of code-generator-related MAGIC CONSTANTS. ,constantWord Haskell "MAX_Vanilla_REG" "MAX_VANILLA_REG" ,constantWord Haskell "MAX_Float_REG" "MAX_FLOAT_REG" ,constantWord Haskell "MAX_Double_REG" "MAX_DOUBLE_REG" ,constantWord Haskell "MAX_Long_REG" "MAX_LONG_REG" ,constantWord Haskell "MAX_XMM_REG" "MAX_XMM_REG" ,constantWord Haskell "MAX_Real_Vanilla_REG" "MAX_REAL_VANILLA_REG" ,constantWord Haskell "MAX_Real_Float_REG" "MAX_REAL_FLOAT_REG" ,constantWord Haskell "MAX_Real_Double_REG" "MAX_REAL_DOUBLE_REG" ,constantWord Haskell "MAX_Real_XMM_REG" "MAX_REAL_XMM_REG" ,constantWord Haskell "MAX_Real_Long_REG" "MAX_REAL_LONG_REG" -- This tells the native code generator the size of the spill -- area is has available. ,constantWord Haskell "RESERVED_C_STACK_BYTES" "RESERVED_C_STACK_BYTES" -- The amount of (Haskell) stack to leave free for saving -- registers when returning to the scheduler. ,constantWord Haskell "RESERVED_STACK_WORDS" "RESERVED_STACK_WORDS" -- Continuations that need more than this amount of stack -- should do their own stack check (see bug #1466). ,constantWord Haskell "AP_STACK_SPLIM" "AP_STACK_SPLIM" -- Size of a word, in bytes ,constantWord Haskell "WORD_SIZE" "SIZEOF_HSWORD" -- Size of a double in StgWords. ,constantWord Haskell "DOUBLE_SIZE" "SIZEOF_DOUBLE" -- Size of a C int, in bytes. May be smaller than wORD_SIZE. ,constantWord Haskell "CINT_SIZE" "SIZEOF_INT" ,constantWord Haskell "CLONG_SIZE" "SIZEOF_LONG" ,constantWord Haskell "CLONG_LONG_SIZE" "SIZEOF_LONG_LONG" -- Number of bits to shift a bitfield left by in an info table. ,constantWord Haskell "BITMAP_BITS_SHIFT" "BITMAP_BITS_SHIFT" -- Amount of pointer bits used for semi-tagging constructor closures ,constantWord Haskell "TAG_BITS" "TAG_BITS" ,constantBool Haskell "WORDS_BIGENDIAN" "defined(WORDS_BIGENDIAN)" ,constantBool Haskell "DYNAMIC_BY_DEFAULT" "defined(DYNAMIC_BY_DEFAULT)" ,constantWord Haskell "LDV_SHIFT" "LDV_SHIFT" ,constantNatural Haskell "ILDV_CREATE_MASK" "LDV_CREATE_MASK" ,constantNatural Haskell "ILDV_STATE_CREATE" "LDV_STATE_CREATE" ,constantNatural Haskell "ILDV_STATE_USE" "LDV_STATE_USE" ] getWanted :: Bool -> FilePath -> FilePath -> [String] -> FilePath -> IO Results getWanted verbose tmpdir gccProgram gccFlags nmProgram = do let cStuff = unlines (headers ++ concatMap (doWanted . snd) wanteds) cFile = tmpdir </> "tmp.c" oFile = tmpdir </> "tmp.o" writeFile cFile cStuff execute verbose gccProgram (gccFlags ++ ["-c", cFile, "-o", oFile]) xs <- case os of "openbsd" -> readProcess "/usr/bin/objdump" ["--syms", oFile] "" _ -> readProcess nmProgram ["-P", oFile] "" let ls = lines xs ms = map parseNmLine ls m = Map.fromList $ catMaybes ms rs <- mapM (lookupResult m) wanteds return rs where headers = ["#define IN_STG_CODE 0", "", "/*", " * We need offsets of profiled things...", " * better be careful that this doesn't", " * affect the offsets of anything else.", " */", "", "#define PROFILING", "#define THREADED_RTS", "", "#include \"PosixSource.h\"", "#include \"Rts.h\"", "#include \"Stable.h\"", "#include \"Capability.h\"", "", "#include <inttypes.h>", "#include <stddef.h>", "#include <stdio.h>", "#include <string.h>", "", "#define FIELD_SIZE(s_type, field) ((size_t)sizeof(((s_type*)0)->field))", "#define TYPE_SIZE(type) (sizeof(type))", "#define FUN_OFFSET(sym) (offsetof(Capability,f.sym) - offsetof(Capability,r))", "", "#pragma GCC poison sizeof" ] prefix = "derivedConstant" mkFullName name = prefix ++ name -- We add 1 to the value, as some platforms will make a symbol -- of size 1 when for -- char foo[0]; -- We then subtract 1 again when parsing. doWanted (GetFieldType name (Fst (CExpr cExpr))) = ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"] doWanted (GetClosureSize name (Fst (CExpr cExpr))) = ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"] doWanted (GetWord name (Fst (CExpr cExpr))) = ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"] doWanted (GetInt name (Fst (CExpr cExpr))) = ["char " ++ mkFullName name ++ "Mag[1 + ((intptr_t)(" ++ cExpr ++ ") >= 0 ? (" ++ cExpr ++ ") : -(" ++ cExpr ++ "))];", "char " ++ mkFullName name ++ "Sig[(intptr_t)(" ++ cExpr ++ ") >= 0 ? 3 : 1];"] doWanted (GetNatural name (Fst (CExpr cExpr))) = -- These casts fix "right shift count >= width of type" -- warnings let cExpr' = "(uint64_t)(size_t)(" ++ cExpr ++ ")" in ["char " ++ mkFullName name ++ "0[1 + ((" ++ cExpr' ++ ") & 0xFFFF)];", "char " ++ mkFullName name ++ "1[1 + (((" ++ cExpr' ++ ") >> 16) & 0xFFFF)];", "char " ++ mkFullName name ++ "2[1 + (((" ++ cExpr' ++ ") >> 32) & 0xFFFF)];", "char " ++ mkFullName name ++ "3[1 + (((" ++ cExpr' ++ ") >> 48) & 0xFFFF)];"] doWanted (GetBool name (Fst (CPPExpr cppExpr))) = ["#if " ++ cppExpr, "char " ++ mkFullName name ++ "[1];", "#else", "char " ++ mkFullName name ++ "[2];", "#endif"] doWanted (StructFieldMacro {}) = [] doWanted (ClosureFieldMacro {}) = [] doWanted (ClosurePayloadMacro {}) = [] doWanted (FieldTypeGcptrMacro {}) = [] -- parseNmLine parses "nm -P" output that looks like -- "derivedConstantMAX_Vanilla_REG C 0000000b 0000000b" (GNU nm) -- "_derivedConstantMAX_Vanilla_REG C b 0" (Mac OS X) -- "_derivedConstantMAX_Vanilla_REG C 000000b" (MinGW) -- "derivedConstantMAX_Vanilla_REG D 1 b" (Solaris) -- and returns ("MAX_Vanilla_REG", 11) parseNmLine line = case words line of ('_' : n) : "C" : s : _ -> mkP n s n : "C" : s : _ -> mkP n s [n, "D", _, s] -> mkP n s [s, "O", "*COM*", _, n] -> mkP n s _ -> Nothing where mkP r s = case (stripPrefix prefix r, readHex s) of (Just name, [(size, "")]) -> Just (name, size) _ -> Nothing -- If an Int value is larger than 2^28 or smaller -- than -2^28, then fail. -- This test is a bit conservative, but if any -- constants are roughly maxBound or minBound then -- we probably need them to be Integer rather than -- Int so that -- cross-compiling between 32bit and -- 64bit platforms works. lookupSmall :: Map String Integer -> Name -> IO Integer lookupSmall m name = case Map.lookup name m of Just v | v > 2^(28 :: Int) || v < -(2^(28 :: Int)) -> die ("Value too large for GetWord: " ++ show v) | otherwise -> return v Nothing -> die ("Can't find " ++ show name) lookupResult :: Map String Integer -> (Where, What Fst) -> IO (Where, What Snd) lookupResult m (w, GetWord name _) = do v <- lookupSmall m name return (w, GetWord name (Snd (v - 1))) lookupResult m (w, GetInt name _) = do mag <- lookupSmall m (name ++ "Mag") sig <- lookupSmall m (name ++ "Sig") return (w, GetWord name (Snd ((mag - 1) * (sig - 2)))) lookupResult m (w, GetNatural name _) = do v0 <- lookupSmall m (name ++ "0") v1 <- lookupSmall m (name ++ "1") v2 <- lookupSmall m (name ++ "2") v3 <- lookupSmall m (name ++ "3") let v = (v0 - 1) + shiftL (v1 - 1) 16 + shiftL (v2 - 1) 32 + shiftL (v3 - 1) 48 return (w, GetWord name (Snd v)) lookupResult m (w, GetBool name _) = do v <- lookupSmall m name case v of 1 -> return (w, GetBool name (Snd True)) 2 -> return (w, GetBool name (Snd False)) _ -> die ("Bad boolean: " ++ show v) lookupResult m (w, GetFieldType name _) = do v <- lookupSmall m name return (w, GetFieldType name (Snd (v - 1))) lookupResult m (w, GetClosureSize name _) = do v <- lookupSmall m name return (w, GetClosureSize name (Snd (v - 1))) lookupResult _ (w, StructFieldMacro name) = return (w, StructFieldMacro name) lookupResult _ (w, ClosureFieldMacro name) = return (w, ClosureFieldMacro name) lookupResult _ (w, ClosurePayloadMacro name) = return (w, ClosurePayloadMacro name) lookupResult _ (w, FieldTypeGcptrMacro name) = return (w, FieldTypeGcptrMacro name) writeHaskellType :: FilePath -> [What Fst] -> IO () writeHaskellType fn ws = writeFile fn xs where xs = unlines (headers ++ body ++ footers) headers = ["data PlatformConstants = PlatformConstants {" -- Now a kludge that allows the real entries to -- all start with a comma, which makes life a -- little easier ," pc_platformConstants :: ()"] footers = [" } deriving Read"] body = concatMap doWhat ws doWhat (GetClosureSize name _) = [" , pc_" ++ name ++ " :: Int"] doWhat (GetFieldType name _) = [" , pc_" ++ name ++ " :: Int"] doWhat (GetWord name _) = [" , pc_" ++ name ++ " :: Int"] doWhat (GetInt name _) = [" , pc_" ++ name ++ " :: Int"] doWhat (GetNatural name _) = [" , pc_" ++ name ++ " :: Integer"] doWhat (GetBool name _) = [" , pc_" ++ name ++ " :: Bool"] doWhat (StructFieldMacro {}) = [] doWhat (ClosureFieldMacro {}) = [] doWhat (ClosurePayloadMacro {}) = [] doWhat (FieldTypeGcptrMacro {}) = [] writeHaskellValue :: FilePath -> [What Snd] -> IO () writeHaskellValue fn rs = writeFile fn xs where xs = unlines (headers ++ body ++ footers) headers = ["PlatformConstants {" ," pc_platformConstants = ()"] footers = [" }"] body = concatMap doWhat rs doWhat (GetClosureSize name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v] doWhat (GetFieldType name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v] doWhat (GetWord name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v] doWhat (GetInt name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v] doWhat (GetNatural name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v] doWhat (GetBool name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v] doWhat (StructFieldMacro {}) = [] doWhat (ClosureFieldMacro {}) = [] doWhat (ClosurePayloadMacro {}) = [] doWhat (FieldTypeGcptrMacro {}) = [] writeHaskellWrappers :: FilePath -> [What Fst] -> IO () writeHaskellWrappers fn ws = writeFile fn xs where xs = unlines body body = concatMap doWhat ws doWhat (GetFieldType {}) = [] doWhat (GetClosureSize {}) = [] doWhat (GetWord name _) = [haskellise name ++ " :: DynFlags -> Int", haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"] doWhat (GetInt name _) = [haskellise name ++ " :: DynFlags -> Int", haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"] doWhat (GetNatural name _) = [haskellise name ++ " :: DynFlags -> Integer", haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"] doWhat (GetBool name _) = [haskellise name ++ " :: DynFlags -> Bool", haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"] doWhat (StructFieldMacro {}) = [] doWhat (ClosureFieldMacro {}) = [] doWhat (ClosurePayloadMacro {}) = [] doWhat (FieldTypeGcptrMacro {}) = [] writeHaskellExports :: FilePath -> [What Fst] -> IO () writeHaskellExports fn ws = writeFile fn xs where xs = unlines body body = concatMap doWhat ws doWhat (GetFieldType {}) = [] doWhat (GetClosureSize {}) = [] doWhat (GetWord name _) = [" " ++ haskellise name ++ ","] doWhat (GetInt name _) = [" " ++ haskellise name ++ ","] doWhat (GetNatural name _) = [" " ++ haskellise name ++ ","] doWhat (GetBool name _) = [" " ++ haskellise name ++ ","] doWhat (StructFieldMacro {}) = [] doWhat (ClosureFieldMacro {}) = [] doWhat (ClosurePayloadMacro {}) = [] doWhat (FieldTypeGcptrMacro {}) = [] writeHeader :: FilePath -> [What Snd] -> IO () writeHeader fn rs = writeFile fn xs where xs = unlines (headers ++ body) headers = ["/* This file is created automatically. Do not edit by hand.*/", ""] body = concatMap doWhat rs doWhat (GetFieldType name (Snd v)) = ["#define " ++ name ++ " b" ++ show (v * 8)] doWhat (GetClosureSize name (Snd v)) = ["#define " ++ name ++ " (SIZEOF_StgHeader+" ++ show v ++ ")"] doWhat (GetWord name (Snd v)) = ["#define " ++ name ++ " " ++ show v] doWhat (GetInt name (Snd v)) = ["#define " ++ name ++ " " ++ show v] doWhat (GetNatural name (Snd v)) = ["#define " ++ name ++ " " ++ show v] doWhat (GetBool name (Snd v)) = ["#define " ++ name ++ " " ++ show (fromEnum v)] doWhat (StructFieldMacro nameBase) = ["#define " ++ nameBase ++ "(__ptr__) REP_" ++ nameBase ++ "[__ptr__+OFFSET_" ++ nameBase ++ "]"] doWhat (ClosureFieldMacro nameBase) = ["#define " ++ nameBase ++ "(__ptr__) REP_" ++ nameBase ++ "[__ptr__+SIZEOF_StgHeader+OFFSET_" ++ nameBase ++ "]"] doWhat (ClosurePayloadMacro nameBase) = ["#define " ++ nameBase ++ "(__ptr__,__ix__) W_[__ptr__+SIZEOF_StgHeader+OFFSET_" ++ nameBase ++ " + WDS(__ix__)]"] doWhat (FieldTypeGcptrMacro nameBase) = ["#define REP_" ++ nameBase ++ " gcptr"] die :: String -> IO a die err = do hPutStrLn stderr err exitFailure execute :: Bool -> FilePath -> [String] -> IO () execute verbose prog args = do when verbose $ putStrLn $ showCommandForUser prog args ec <- rawSystem prog args unless (ec == ExitSuccess) $ die ("Executing " ++ show prog ++ " failed")
forked-upstream-packages-for-ghcjs/ghc
utils/deriveConstants/DeriveConstants.hs
bsd-3-clause
42,401
200
19
13,623
9,636
4,998
4,638
707
28
module Data.Maybe.Utils(unsafeUnjust, maybeToMPlus) where import Control.Monad (MonadPlus(..)) unsafeUnjust :: String -> Maybe a -> a unsafeUnjust msg Nothing = error ("unsafeUnjust: " ++ msg) unsafeUnjust _ (Just x) = x maybeToMPlus :: MonadPlus m => Maybe a -> m a maybeToMPlus Nothing = mzero maybeToMPlus (Just x) = return x
da-x/lamdu
bottlelib/Data/Maybe/Utils.hs
gpl-3.0
332
0
7
53
128
67
61
8
1
{-# OPTIONS_GHC -XScopedTypeVariables #-} -- We don't actually want scoped type variables, but this flag makes the -- forall be recognised by the parser module ShouldCompile where newtype Swizzle = MkSwizzle (forall a. Ord a => [a] -> [a])
urbanslug/ghc
testsuite/tests/typecheck/should_fail/tcfail184.hs
bsd-3-clause
243
0
10
42
40
25
15
-1
-1
-- | Axis aligned rectangles in two-dimensional space. -- {-# LANGUAGE ForeignFunctionInterface, RecordWildCards #-} {-# LANGUAGE MultiParamTypeClasses, DeriveFunctor #-} {-# LANGUAGE FlexibleInstances, ViewPatterns #-} {-# LANGUAGE NoImplicitPrelude, DeriveDataTypeable #-} module Caramia.Extras.Rectangle ( -- * Construction ltrb , ltwh -- * Types , ARectangle() , Rectangle , IRectangle , FRectangle , DRectangle , ACover() , PointCovering(..) , RectangleCovering(..) , NextAfter(..) , NextAfterDir(..) , Halvable(..) -- * Transformations , normalize , maximize , subtract , overlapping -- * Lenses , left , top , right , bottom , width , height , lt , rb -- * Tests , overlaps , isNormal , isInside' -- * Views , viewArea -- * Orderings , byArea , ByArea(..) -- * Rectangle covers , addToCover , addManyToCover ) where import Caramia.Prelude hiding ( left, right, subtract ) import Control.Lens import Foreign.C.Types foreign import ccall unsafe "nextafter" c_nextafter :: CDouble -> CDouble -> CDouble foreign import ccall unsafe "nextafterf" c_nextafterf :: CFloat -> CFloat -> CFloat data NextAfterDir = Positive | Negative deriving ( Eq, Ord, Show, Read, Typeable ) -- | Class of values that have a concept of successor. -- -- If @x@ is input, for integral types, `nextAfter` should return @ x+1 @. For -- floating point values, it should return the smallest value that is greater -- than @x@. Instances are provided for common numerical types. class NextAfter a where nextAfter :: NextAfterDir -> a -> a instance NextAfter CDouble where nextAfter Positive x = c_nextafter x (1/0) nextAfter Negative x = c_nextafter x (-(1/0)) instance NextAfter CFloat where nextAfter Positive x = c_nextafterf x (1/0) nextAfter Negative x = c_nextafterf x (-(1/0)) instance NextAfter Float where nextAfter dir x = unwrap $ nextAfter dir (CFloat x) where unwrap (CFloat x) = x instance NextAfter Double where nextAfter dir x = unwrap $ nextAfter dir (CDouble x) where unwrap (CDouble x) = x instance NextAfter Integer where nextAfter Positive x = x+1 nextAfter Negative x = x-1 instance NextAfter Int where nextAfter = intNextAfter instance NextAfter Word8 where nextAfter = intNextAfter instance NextAfter Word16 where nextAfter = intNextAfter instance NextAfter Word32 where nextAfter = intNextAfter instance NextAfter Word64 where nextAfter = intNextAfter instance NextAfter Int8 where nextAfter = intNextAfter instance NextAfter Int16 where nextAfter = intNextAfter instance NextAfter Int32 where nextAfter = intNextAfter instance NextAfter Int64 where nextAfter = intNextAfter instance NextAfter CInt where nextAfter = intNextAfter instance NextAfter CUInt where nextAfter = intNextAfter instance NextAfter CLong where nextAfter = intNextAfter instance NextAfter CULong where nextAfter = intNextAfter instance NextAfter CShort where nextAfter = intNextAfter instance NextAfter CUShort where nextAfter = intNextAfter instance NextAfter CUChar where nextAfter = intNextAfter instance NextAfter CChar where nextAfter = intNextAfter instance NextAfter CSize where nextAfter = intNextAfter instance Halvable Int where halfCut = intHalfCut instance Halvable Word8 where halfCut = intHalfCut instance Halvable Word16 where halfCut = intHalfCut instance Halvable Word32 where halfCut = intHalfCut instance Halvable Word64 where halfCut = intHalfCut instance Halvable Int8 where halfCut = intHalfCut instance Halvable Int16 where halfCut = intHalfCut instance Halvable Int32 where halfCut = intHalfCut instance Halvable Int64 where halfCut = intHalfCut instance Halvable CInt where halfCut = intHalfCut instance Halvable CUInt where halfCut = intHalfCut instance Halvable CLong where halfCut = intHalfCut instance Halvable CULong where halfCut = intHalfCut instance Halvable CShort where halfCut = intHalfCut instance Halvable CUShort where halfCut = intHalfCut instance Halvable CUChar where halfCut = intHalfCut instance Halvable CChar where halfCut = intHalfCut instance Halvable CSize where halfCut = intHalfCut intHalfCut :: Integral a => a -> (a, a) intHalfCut x = let h = x `div` 2 in ( h, h+1 ) intNextAfter :: (Eq a, Bounded a, Num a) => NextAfterDir -> a -> a intNextAfter Positive x | x == maxBound = error "intNextAfter: integral maximum reached." | otherwise = x+1 intNextAfter Negative x | x == minBound = error "intNextAfter: integral minimum reached." | otherwise = x-1 class NextAfter a => Halvable a where halfCut :: a -> (a, a) instance Halvable CDouble where halfCut (CDouble d) = halfCut d & over both CDouble {-# INLINE halfCut #-} instance Halvable CFloat where halfCut (CFloat f) = halfCut f & over both CFloat {-# INLINE halfCut #-} instance Halvable Double where halfCut d = let h = d/2 in ( h, nextAfter Positive h ) {-# INLINE halfCut #-} instance Halvable Float where halfCut f = let h = f/2 in ( h, nextAfter Positive h ) {-# INLINE halfCut #-} -- | Type of an axis aligned rectangle in two-dimensional space. data ARectangle a = ARectangle { _left :: !a , _top :: !a , _right :: !a , _bottom :: !a } deriving ( Eq , Ord , Show , Read , Typeable , Functor ) -- | Creates a rectangle by specifying left, top, right and bottom. -- -- @ ltrb = left-top-right-bottom @. All values are inclusive, that is, a -- a @ ltrb 5 5 5 5 @ is has area of 1 and has a width and height of 1. ltrb :: a -> a -> a -> a -> ARectangle a ltrb = ARectangle -- | Creates a rectangle by specifying left, top, width and height. -- -- @ ltwh = left-top-width-height @. Left and top are inclusive. Width and -- height specify the size of the rectangle. ltwh :: Num a => a -> a -> a -> a -> ARectangle a ltwh left top width height = ARectangle { _left = left , _top = top , _right = left + width - 1 , _bottom = top + height - 1 } -- | `Int` rectangle. type Rectangle = ARectangle Int -- | `Integer` rectangle. type IRectangle = ARectangle Integer -- | `Float` rectangle. type FRectangle = ARectangle Float -- | `Double rectangle. type DRectangle = ARectangle Double -- | Lens to left and top of rectangle. lt :: Lens' (ARectangle a) (a, a) lt = lens (\old -> (_left old, _top old)) (\old (new_left, new_top) -> old { _left = new_left , _top = new_top }) -- | Lens to right and bottom of rectangle. rb :: Lens' (ARectangle a) (a, a) rb = lens (\old -> (_right old, _bottom old)) (\old (new_right, new_bottom) -> old { _right = new_right , _bottom = new_bottom }) left :: Lens' (ARectangle a) a left = lens _left (\old new -> old { _left = new }) {-# INLINE left #-} right :: Lens' (ARectangle a) a right = lens _right (\old new -> old { _right = new }) {-# INLINE right #-} top :: Lens' (ARectangle a) a top = lens _top (\old new -> old { _top = new }) {-# INLINE top #-} bottom :: Lens' (ARectangle a) a bottom = lens _bottom (\old new -> old { _bottom = new }) {-# INLINE bottom #-} width :: Num a => Lens' (ARectangle a) a width = lens (\x -> _right x - _left x + 1) (\old new -> old { _right = _left old + new - 1 }) {-# INLINE width #-} height :: Num a => Lens' (ARectangle a) a height = lens (\x -> _bottom x - _top x + 1) (\old new -> old { _bottom = _top old + new - 1 }) {-# INLINE height #-} -- | Returns the area of a rectangle. viewArea :: (Num a) => ARectangle a -> a viewArea rect = (rect^.width) * (rect^.height) {-# INLINE viewArea #-} -- | Normalizes a rectangle. -- -- In this context, normalizing means checking that the right side of the -- rectangle is actually on the right of the left side and bottom side is -- actually at the bottom. This makes sure `viewArea` returns a positive value -- and that `right` is guaranteed to be equal or greater than `left` and -- `bottom` is equal or greater than `top`. normalize :: Ord a => ARectangle a -> ARectangle a normalize rect = rect & (if _right rect < _left rect then (right .~ _left rect) . (left .~ _right rect) else id) . (if _bottom rect < _top rect then (bottom .~ _top rect) . (top .~ _bottom rect) else id) {-# INLINE normalize #-} -- | Returns `True` if a rectangle is in \"normal\", form, that is, if -- invoking `normalize` on it would just return the same rectangle. isNormal :: Ord a => ARectangle a -> Bool isNormal (ARectangle {..}) = _right >= _left && _bottom >= _top {-# INLINE isNormal #-} -- | A function suitable for functions such as `sortBy`. It will order -- rectangles by their area. -- -- If areas are equivalent, then the position of the rectangle is considered in -- an unspecified way. -- -- Also see `ByArea` data type. byArea :: (Num a, Ord a) => ARectangle a -> ARectangle a -> Ordering byArea rect1 rect2 = case compare (viewArea rect1) (viewArea rect2) of EQ -> rect1 `compare` rect2 LT -> LT GT -> GT {-# INLINE byArea #-} -- | A newtype wrapper for `ARectangle` that replaces the `Ord` instance with -- an implementation equivalent to `byArea`. newtype ByArea a = ByArea { unwrapByArea :: ARectangle a } deriving ( Eq, Show, Read, Typeable, Functor ) instance (Num a, Ord a, Eq a) => Ord (ByArea a) where ByArea x `compare` ByArea y = x `byArea` y -- | Returns `True` if two given rectangles overlap. -- -- This function normalizes the rectangles before doing the test. overlaps :: Ord a => ARectangle a -> ARectangle a -> Bool overlaps (normalize -> rect1) (normalize -> rect2) = not $ (_right rect1 < _left rect2) || (_left rect1 > _right rect2) || (_bottom rect1 < _top rect2) || (_top rect1 > _bottom rect2) {-# INLINE overlaps #-} -- | Returns the overlapping area of two rectangles, or `Nothing` if the -- rectangles do not overlap. -- -- This function normalizes the rectangles before doing the operation. overlapping :: Ord a => ARectangle a -> ARectangle a -> Maybe (ARectangle a) overlapping (normalize -> rect1) (normalize -> rect2) = if _right result < _left result || _bottom result < _top result then Nothing else Just result where result = ARectangle { _left = max (_left rect1) (_left rect2) , _right = min (_right rect1) (_right rect2) , _top = max (_top rect1) (_top rect2) , _bottom = min (_bottom rect1) (_bottom rect2) } {-# INLINE overlapping #-} -- | This function \"subtracts\" overlapping area from a rectangle. -- -- Here's an example. -- -- @ -- Given two rectangles A and B (with the overlapping area marked with -- dashes): -- -- AAAAAAAAAAAA -- AAAAAAAAAAAA -- AAAAAAAAAAAA -- AAAAAAA-----BBBBBBBB -- AAAAAAA-----BBBBBBBB -- BBBBBBBBBBBBB -- BBBBBBBBBBBBB -- -- Results in two rectangles C and D. -- -- AAAAAAAAAAAA -- AAAAAAAAAAAA -- AAAAAAAAAAAA -- AAAAAAA-----CCCCCCCC -- AAAAAAA-----CCCCCCCC -- DDDDDCCCCCCCC -- DDDDDCCCCCCCC -- @ -- -- At maximum, there can be 4 returned rectangles which happens when the -- subtracted area is completely covered by the source rectangle. subtract :: (Ord a, NextAfter a) => ARectangle a -- ^ Subtract from this rectangle. -> ARectangle a -> [ARectangle a] -- ^ Either 0, 1, 2, 3 or 4 rectangles -- , depending on how the given rectangles -- overlap. subtract (normalize -> rect1) (normalize -> rect2) | not $ overlaps rect1 rect2 = [rect1] | fullCover rect1 rect2 = [] | otherwise = let rrect8 = ARectangle { _left = max (_left rect2) (_left rect1) , _right = min (_right rect2) (_right rect1) , _top = _top rect1 , _bottom = nextAfter Negative $ _top rect2 } rrect2 = ARectangle { _left = max (_left rect2) (_left rect1) , _right = min (_right rect2) (_right rect1) , _top = nextAfter Positive $ _bottom rect2 , _bottom = _bottom rect1 } rrect4 = ARectangle { _left = _left rect1 , _right = nextAfter Negative $ _left rect2 , _top = _top rect1 , _bottom = _bottom rect1 } rrect6 = ARectangle { _left = nextAfter Positive $ _right rect2 , _right = _right rect1 , _top = _top rect1 , _bottom = _bottom rect1 } in filter isNormal [rrect2, rrect4, rrect6, rrect8] {-# INLINABLE subtract #-} -- | Class of things that can cover axis-aligned rectangles in two-dimensional -- space. -- -- Minimal implementation: `fullCover`. class RectangleCovering cov a where -- | Returns `True` if the given rectangle is completely inside the given -- covering. fullCover :: ARectangle a -> cov -> Bool instance Ord a => RectangleCovering (ARectangle a) a where fullCover rect1 rect2 = rect1^.left >= rect2^.left && rect1^.right <= rect2^.right && rect1^.top >= rect2^.top && rect1^.bottom <= rect2^.bottom instance (Ord a, NextAfter a) => RectangleCovering (ACover a) a where fullCover rect (_coverings -> covers) = folder [rect] covers where folder [] _ = True folder _ [] = False folder rects (cover:rest) = folder (concatMap (flip subtract cover) rects) rest -- | Class of things that can cover points in two-dimensional space. -- -- Minimal implementation: `isInside`. class PointCovering cov val where -- | Tests if a point is inside a rectangle. -- -- This function normalizes the rectangle before doing the test. -- -- The first argument is where the point is on the X axis (left-right) and the -- second is on the Y (top-bottom) axis. isInside :: val -> val -> cov -> Bool -- | Same as `isInside` but uncurried to take a tuple. isInside' :: PointCovering cov a => (a, a) -> cov -> Bool isInside' (x, y) = isInside x y instance Ord a => PointCovering (ARectangle a) a where isInside x y (normalize -> ARectangle{..}) = x >= _left && x <= _right && y >= _top && y <= _bottom {-# INLINE isInside #-} instance Ord a => PointCovering (ACover a) a where isInside x y (_coverings -> covers) = any (isInside x y) covers -- | Given two rectangles, returns a rectangle that encompasses both -- rectangles. -- -- This normalizes both rectangles before doing its operation. maximize :: Ord a => ARectangle a -> ARectangle a -> ARectangle a maximize (normalize -> rect1) (normalize -> rect2) = ARectangle { _left = min (_left rect1) (_left rect2) , _top = min (_top rect1) (_top rect2) , _right = max (_right rect1) (_right rect2) , _bottom = max (_bottom rect1) (_bottom rect2) } -- | Type of rectangle covers. -- -- It can be thought as a set of rectangles that together cover an area. -- -- Be careful of time complexity. Adding a rectangle is O(N) complexity and -- checking is a point is covered by the cover is also O(N). -- -- Use `mempty` to create an empty cover. newtype ACover a = ACover { _coverings :: [ARectangle a] } deriving ( Eq, Ord, Show, Read, Typeable, Functor ) -- | `mempty` for `ACover` covers nothing and appending two covers together -- results in a cover that now covers both areas. instance Monoid (ACover a) where mempty = ACover { _coverings = [] } (_coverings -> cover1) `mappend` (_coverings -> cover2) = ACover { _coverings = cover1 `mappend` cover2 } -- | This instance follows the same appending rule as the `Monoid` instance. instance Semigroup (ACover a) where cover1 <> cover2 = cover1 `mappend` cover2 coverings :: Lens (ACover a) (ACover b) [ARectangle a] [ARectangle b] coverings = lens _coverings (\old new -> old { _coverings = new }) {-# INLINE coverings #-} -- | Adds another rectangle to the cover. -- -- This is O(N) to the number of rectangles already added to the cover. -- -- This does not increase the size of the cover if the given rectangle would be -- fully covered already by the existing rectangles. addToCover :: (NextAfter a, Ord a) => ARectangle a -> ACover a -> ACover a addToCover rect cover | fullCover rect cover = cover | otherwise = cover & coverings %~ (rect:) -- | Adds many rectangles to a cover. -- -- Uses `addManyToCover` so time complexity is O(N*M) where M is the number of -- rectangles to add and N is the number of rectangles already in the cover. addManyToCover :: (NextAfter a, Ord a) => [ARectangle a] -> ACover a -> ACover a addManyToCover [] cover = cover addManyToCover xs cover = foldl' (flip addToCover) cover xs
Noeda/caramia-extras
lib/Caramia/Extras/Rectangle.hs
mit
17,243
0
20
4,427
4,277
2,318
1,959
-1
-1
main = putStrLn $ show solve solve :: Int solve = head [a*b*c | c <- [1..1000], b <- [1..(c-1)], a <- [1..(b-1)], a^2 + b^2 == c^2, a+b+c == 1000]
pshendry/project-euler-solutions
0009/solution.hs
mit
149
1
12
33
139
69
70
3
1
module VizTree where import Treedot data VizTree = VizNode String [VizTree] instance Tree (VizTree) where subtrees (VizNode x xs) = xs instance LabeledTree (VizTree) where label (VizNode x xs) = x class Viz a where toVizTree :: a -> VizTree -- handling a list is implemented under Viz class instead of the instance with a list param toVizList :: [a] -> VizTree toVizList [] = VizNode "[]" [] toVizList (x:xs) = VizNode ":" [toVizTree x, toVizTree xs] instance Viz Integer where toVizTree n = VizNode (show n) [] instance Viz Char where toVizTree n = VizNode (show n) [] -- when it sees Char of param, this is going to use this overriden definition to handle special case toVizList s = VizNode ("\\\""++s++"\\\"") [] instance Viz a => Viz [a] where -- otherwise it is going to use the class method toVizTree = toVizList -- toVizTree [] = VizNode "[]" [] -- toVizTree (x:xs) = VizNode ":" [toVizTree x, toVizTree xs] instance Viz Bool where toVizTree n = VizNode (show n) [] instance Viz Int where toVizTree n = VizNode (show n) [] instance Viz a => Viz (Maybe a) where toVizTree Nothing = VizNode "Nothing" [] toVizTree (Just a) = toVizTree a instance (Viz a, Viz b) => Viz (a,b) where toVizTree (a,b) = VizNode ((label (toVizTree a)) ++ "," ++ (label (toVizTree b))) [] instance (Viz a, Viz b, Viz c) => Viz (a,b,c) where toVizTree (a,b,c) = VizNode ((label (toVizTree a)) ++ "," ++ (label (toVizTree b)) ++ "," ++ (label (toVizTree c))) [] viz :: Viz a => a -> IO () viz = writeFile "tree.dot" . toDot . toVizTree
craynafinal/cs557_functional_languages
project/haskell-rest-api/src/VizTree.hs
mit
1,549
0
15
308
616
317
299
32
1
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, TupleSections, GADTs, FlexibleContexts #-} {-# LANGUAGE ViewPatterns #-} module Day22 where import AdventPrelude import Control.Arrow (returnA) import qualified Data.Sequence as S import Data.Ratio ((%)) import Data.Text.Format import Data.Set (size) input :: IO Text input = readFile "data/day22.txt" -- input = pure "/dev/grid/node-x0-y0 10T 8T 2T 80%\n\ -- \/dev/grid/node-x0-y1 11T 6T 5T 54%\n\ -- \/dev/grid/node-x0-y2 32T 28T 4T 87%\n\ -- \/dev/grid/node-x1-y0 9T 7T 2T 77%\n\ -- \/dev/grid/node-x1-y1 8T 0T 8T 0%\n\ -- \/dev/grid/node-x1-y2 11T 7T 4T 63%\n\ -- \/dev/grid/node-x2-y0 10T 6T 4T 60%\n\ -- \/dev/grid/node-x2-y1 9T 8T 1T 88%\n\ -- \/dev/grid/node-x2-y2 9T 6T 3T 66%" data Node = Node { nX :: Int , nY :: Int , nUsed :: Int , nAvail :: Int } deriving (Show, Eq) parser = Node <$> ("/dev/grid/node-x" *> decimal) <*> ("-y" *> decimal) <* (skipSpace *> decimal <* "T") <*> (skipSpace *> decimal <* "T") <*> (skipSpace *> decimal <* "T") <* (skipSpace *> decimal <* "%") isViable :: Node -> Node -> Bool isViable n1 n2 = nUsed n1 > 0 && n1 /= n2 && nUsed n1 <= nAvail n2 enumViable :: [Node] -> [(Node,Node)] enumViable ns = do a <- ns b <- ns guard (isViable a b) pure (a,b) result1 = runEitherT $ do i <- EitherT (parseOnly (parser `sepBy1` endOfLine) <$> input) pure (length $ enumViable i) type Grid = (Seq (Seq Int), Seq (Seq Int)) type Coord = (Int, Int) mkGrid :: [Node] -> Grid mkGrid ns = let maxX = maximumEx (fmap nX ns) maxY = maximumEx (fmap nY ns) col = S.replicate (maxY + 1) 0 gridZero = S.replicate (maxX + 1) col in -- traceShow (maxX, maxY, col, gridZero) $ foldl' setCell (gridZero, gridZero) ns where setCell (u, s) n = (u & ix (nX n) . ix (nY n) .~ nUsed n, s & ix (nX n) . ix (nY n) .~ nUsed n + nAvail n) tr :: Seq (Seq a) -> Seq (Seq a) tr ss@(viewl -> (viewl -> _ :< _) :< _) = let hs = concatMap (S.take 1) ss rs = map (S.drop 1) ss in hs S.<| tr rs tr _ = S.empty showGrid :: Grid -> LText showGrid (go, gt) = let l = fromIntegral . S.length $ headEx go s = "\n" <> replicate (l * 5 + (l - 1) * 3) '-' <> "\n" in intercalate s $ map showRow (S.zip (tr go) (tr gt)) where showRow (ro, rt) = intercalate " | " $ map showCell (zip ro rt) showCell (o, t) = format "{}/{}" (left 2 ' ' (tshow o), left 2 ' ' (tshow t)) showGrid' :: (Coord, Coord, Grid) -> LText showGrid' ((x, y), _, (go, gt)) = unlines $ S.mapWithIndex showRow (S.zip (tr go) (tr gt)) where showRow y' (ro, rt) = unwords $ S.mapWithIndex (showCell y') (zip ro rt) showCell _ _ (0, t) = "_" showCell y' x' (o, t) | x == x' && y == y' = "G" | o > 100 = "#" | otherwise = "." showResult :: [(Coord, Coord, Grid)] -> LText showResult rs = intercalate "\n\n" (map showGrid' rs) used x y = _1 . ix x . ix y total x y = _2 . ix x . ix y result2 :: IO (Either String Int) result2 = runEitherT $ do i <- EitherT (parseOnly (parser `sepBy1` endOfLine) <$> input) let tgtX = maximumEx (fmap nX $ filter ((== 0) . nY) i) Just (zx, zy) = (nX &&& nY) <$> (find ((== 0) . nUsed) i) g = mkGrid i r = stepSearch (step g) heur isDone id ((tgtX, 0), (zx, zy)) pure (length r - 1) where isDone ((x, y), _) = x == 0 && y == 0 heur ((x, y), (zx, zy)) = x + y + abs (x - zx) + abs (y - zy) step g (xy@(x, y), zxy@(zx, zy)) = do let mx = S.length (g ^. _1) my = S.length (g ^. _1 . ix 0) isValid x2 y2 = let Just u = g ^? used x2 y2 in 0 <= x2 && x2 < mx && 0 <= y2 && y2 < my && u < 100 zxy'@(zx', zy') <- [(zx + 1, zy), (zx - 1, zy), (zx, zy + 1), (zx, zy - 1)] guard (isValid zx' zy') let xy' = if xy == zxy' then zxy else xy pure (xy', zxy')
farrellm/advent-2016
src/Day22.hs
mit
4,162
0
22
1,321
1,810
955
855
-1
-1
-- | Types for a variety of puzzle elements. module Data.Elements where import Data.GridShape type Clue a = Maybe a data MasyuPearl = MWhite | MBlack deriving (Eq, Show) type MasyuClue = Clue MasyuPearl type IntClue = Clue Int -- | A Compass clue, specifiying optional numbers in the -- four cardinal directions. data CompassC = CC (Maybe Int) (Maybe Int) (Maybe Int) (Maybe Int) deriving (Show) type CompassClue = Clue CompassC data SlovakClue = SlovakClue !Int !Int -- | A cell that is optionally bisected by a diagonal -- (up-right or down-right). data Tightfit a = TightSingle a | TightUR a a | TightDR a a instance Show a => Show (Tightfit a) where show c = "(" ++ show' c ++ ")" where show' (TightSingle x) = show x show' (TightUR x y) = show x ++ "/" ++ show y show' (TightDR x y) = show x ++ "\\" ++ show y -- | A marked word in a letter grid, by its start and end -- coordinates. data MarkedWord = MW {mwstart :: Coord, mwend :: Coord} -- | A loop of edges. type Loop a = [Edge a] -- | A loop consisting of straight segments of arbitrary -- angles between vertices. type VertexLoop = [N] -- | A thermometer, as a list of coordinates from bulb to end. -- There should be at least two entries, entries should be distinct, -- and successive entries should be neighbours (diagonal neighbours -- are fine). type Thermometer = [C] -- | A forward or backward diagonal as occurring in the solution -- of a slalom puzzle. data SlalomDiag = SlalomForward | SlalomBackward deriving (Show) data KropkiDot = KNone | KBlack | KWhite deriving (Show, Eq, Ord) newtype TapaClue = TapaClue [Int] deriving (Show) -- | Diagonal marking for Prime Place: forward diag?, backward diag? newtype PrimeDiag = PrimeDiag (Bool, Bool) data Black = Black deriving (Eq) data Fish = Fish deriving (Eq) data Star = Star deriving (Eq) data Crossing = Crossing deriving (Eq) type BahnhofClue = Either Int Crossing data DigitRange = DigitRange !Int !Int deriving (Show, Eq) digitList :: DigitRange -> [Int] digitList (DigitRange a b) = [a .. b] data MEnd = MEnd data Fraction = FComp String String String -- a b/c | FFrac String String -- a/b | FInt String -- a data PlainNode = PlainNode type Myopia = [Dir'] data Relation = RGreater | RLess | REqual | RUndetermined deriving (Show, Eq) type GreaterClue = [Relation] data GalaxyCentre = GalaxyCentre data PlacedTent = Tent Dir' data Tree = Tree data Pentomino = Pentomino Char deriving (Show, Eq)
robx/puzzle-draw
src/Data/Elements.hs
mit
2,524
0
10
539
672
382
290
64
1
module Main ( main ) where -- doctest import qualified Test.DocTest as DocTest main :: IO () main = DocTest.doctest [ "-isrc" , "src/Fibonacci.hs" ]
mauriciofierrom/cis194-homework
homework06/test/examples/Main.hs
mit
172
0
6
48
44
27
17
8
1