code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# language CPP #-}
-- | = Name
--
-- VK_EXT_pipeline_creation_cache_control - device extension
--
-- == VK_EXT_pipeline_creation_cache_control
--
-- [__Name String__]
-- @VK_EXT_pipeline_creation_cache_control@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 298
--
-- [__Revision__]
-- 3
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.0
--
-- [__Deprecation state__]
--
-- - /Promoted/ to
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.3-promotions Vulkan 1.3>
--
-- [__Contact__]
--
-- - Gregory Grebe
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_pipeline_creation_cache_control] @grgrebe_amd%0A<<Here describe the issue or question you have about the VK_EXT_pipeline_creation_cache_control extension>> >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2020-03-23
--
-- [__Interactions and External Dependencies__]
--
-- - Promoted to Vulkan 1.3 Core
--
-- [__IP Status__]
-- No known IP claims.
--
-- [__Contributors__]
--
-- - Gregory Grebe, AMD
--
-- - Tobias Hector, AMD
--
-- - Matthaeus Chajdas, AMD
--
-- - Mitch Singer, AMD
--
-- - Spencer Fricke, Samsung Electronics
--
-- - Stuart Smith, Imagination Technologies
--
-- - Jeff Bolz, NVIDIA Corporation
--
-- - Daniel Koch, NVIDIA Corporation
--
-- - Dan Ginsburg, Valve Corporation
--
-- - Jeff Leger, QUALCOMM
--
-- - Michal Pietrasiuk, Intel
--
-- - Jan-Harald Fredriksen, Arm Limited
--
-- == Description
--
-- This extension adds flags to @Vk*PipelineCreateInfo@ and
-- 'Vulkan.Core10.PipelineCache.PipelineCacheCreateInfo' structures with
-- the aim of improving the predictability of pipeline creation cost. The
-- goal is to provide information about potentially expensive hazards
-- within the client driver during pipeline creation to the application
-- before carrying them out rather than after.
--
-- == Background
--
-- Pipeline creation is a costly operation, and the explicit nature of the
-- Vulkan design means that cost is not hidden from the developer.
-- Applications are also expected to schedule, prioritize, and load balance
-- all calls for pipeline creation. It is strongly advised that
-- applications create pipelines sufficiently ahead of their usage. Failure
-- to do so will result in an unresponsive application, intermittent
-- stuttering, or other poor user experiences. Proper usage of pipeline
-- caches and\/or derivative pipelines help mitigate this but is not
-- assured to eliminate disruption in all cases. In the event that an
-- ahead-of-time creation is not possible, considerations should be taken
-- to ensure that the current execution context is suitable for the
-- workload of pipeline creation including possible shader compilation.
--
-- Applications making API calls to create a pipeline must be prepared for
-- any of the following to occur:
--
-- - OS\/kernel calls to be made by the ICD
--
-- - Internal memory allocation not tracked by the @pAllocator@ passed to
-- @vkCreate*Pipelines@
--
-- - Internal thread synchronization or yielding of the current thread’s
-- core
--
-- - Extremely long (multi-millisecond+), blocking, compilation times
--
-- - Arbitrary call stacks depths and stack memory usage
--
-- The job or task based game engines that are being developed to take
-- advantage of explicit graphics APIs like Vulkan may behave exceptionally
-- poorly if any of the above scenarios occur. However, most game engines
-- are already built to “stream” in assets dynamically as the user plays
-- the game. By adding control by way of
-- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PipelineCreateFlags', we can
-- require an ICD to report back a failure in critical execution paths
-- rather than forcing an unexpected wait.
--
-- Applications can prevent unexpected compilation by setting
-- 'PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT_EXT' on
-- @Vk*PipelineCreateInfo@::@flags@. When set, an ICD must not attempt
-- pipeline or shader compilation to create the pipeline object. The ICD
-- will return the result 'PIPELINE_COMPILE_REQUIRED_EXT'. An ICD may still
-- return a valid 'Vulkan.Core10.Handles.Pipeline' object by either
-- re-using existing pre-compiled objects such as those from a pipeline
-- cache, or derivative pipelines.
--
-- By default @vkCreate*Pipelines@ calls must attempt to create all
-- pipelines before returning. Setting
-- 'PIPELINE_CREATE_EARLY_RETURN_ON_FAILURE_BIT_EXT' on
-- @Vk*PipelineCreateInfo@::@flags@ can be used as an escape hatch for
-- batched pipeline creates.
--
-- Hidden locks also add to the unpredictability of the cost of pipeline
-- creation. The most common case of locks inside the @vkCreate*Pipelines@
-- is internal synchronization of the 'Vulkan.Core10.Handles.PipelineCache'
-- object. 'PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT_EXT' can be
-- set when calling 'Vulkan.Core10.PipelineCache.createPipelineCache' to
-- state the cache is
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#fundamentals-threadingbehavior externally synchronized>.
--
-- The hope is that armed with this information application and engine
-- developers can leverage existing asset streaming systems to recover from
-- \"just-in-time\" pipeline creation stalls.
--
-- == New Structures
--
-- - Extending
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2',
-- 'Vulkan.Core10.Device.DeviceCreateInfo':
--
-- - 'PhysicalDevicePipelineCreationCacheControlFeaturesEXT'
--
-- == New Enums
--
-- - 'Vulkan.Core10.Enums.PipelineCacheCreateFlagBits.PipelineCacheCreateFlagBits'
--
-- == New Enum Constants
--
-- - 'EXT_PIPELINE_CREATION_CACHE_CONTROL_EXTENSION_NAME'
--
-- - 'EXT_PIPELINE_CREATION_CACHE_CONTROL_SPEC_VERSION'
--
-- - Extending
-- 'Vulkan.Core10.Enums.PipelineCacheCreateFlagBits.PipelineCacheCreateFlagBits':
--
-- - 'PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT_EXT'
--
-- - Extending
-- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PipelineCreateFlagBits':
--
-- - 'PIPELINE_CREATE_EARLY_RETURN_ON_FAILURE_BIT_EXT'
--
-- - 'PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT_EXT'
--
-- - Extending 'Vulkan.Core10.Enums.Result.Result':
--
-- - 'ERROR_PIPELINE_COMPILE_REQUIRED_EXT'
--
-- - 'PIPELINE_COMPILE_REQUIRED_EXT'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_CREATION_CACHE_CONTROL_FEATURES_EXT'
--
-- == Promotion to Vulkan 1.3
--
-- Functionality in this extension is included in core Vulkan 1.3, with the
-- EXT suffix omitted. The original type, enum and command names are still
-- available as aliases of the core functionality.
--
-- == Version History
--
-- - Revision 1, 2019-11-01 (Gregory Grebe)
--
-- - Initial revision
--
-- - Revision 2, 2020-02-24 (Gregory Grebe)
--
-- - Initial public revision
--
-- - Revision 3, 2020-03-23 (Tobias Hector)
--
-- - Changed 'PIPELINE_COMPILE_REQUIRED_EXT' to a success code,
-- adding an alias for the original
-- 'ERROR_PIPELINE_COMPILE_REQUIRED_EXT'. Also updated the xml to
-- include these codes as return values.
--
-- == See Also
--
-- 'PhysicalDevicePipelineCreationCacheControlFeaturesEXT',
-- 'Vulkan.Core10.Enums.PipelineCacheCreateFlagBits.PipelineCacheCreateFlagBits'
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_pipeline_creation_cache_control Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_EXT_pipeline_creation_cache_control ( pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_CREATION_CACHE_CONTROL_FEATURES_EXT
, pattern PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT_EXT
, pattern PIPELINE_CREATE_EARLY_RETURN_ON_FAILURE_BIT_EXT
, pattern PIPELINE_COMPILE_REQUIRED_EXT
, pattern ERROR_PIPELINE_COMPILE_REQUIRED_EXT
, pattern PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT_EXT
, PhysicalDevicePipelineCreationCacheControlFeaturesEXT
, EXT_PIPELINE_CREATION_CACHE_CONTROL_SPEC_VERSION
, pattern EXT_PIPELINE_CREATION_CACHE_CONTROL_SPEC_VERSION
, EXT_PIPELINE_CREATION_CACHE_CONTROL_EXTENSION_NAME
, pattern EXT_PIPELINE_CREATION_CACHE_CONTROL_EXTENSION_NAME
) where
import Data.String (IsString)
import Vulkan.Core13.Promoted_From_VK_EXT_pipeline_creation_cache_control (PhysicalDevicePipelineCreationCacheControlFeatures)
import Vulkan.Core10.Enums.PipelineCacheCreateFlagBits (PipelineCacheCreateFlags)
import Vulkan.Core10.Enums.PipelineCacheCreateFlagBits (PipelineCacheCreateFlagBits(PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT))
import Vulkan.Core10.Enums.Result (Result(PIPELINE_COMPILE_REQUIRED))
import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlags)
import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlagBits(PIPELINE_CREATE_EARLY_RETURN_ON_FAILURE_BIT))
import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlags)
import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlagBits(PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_CREATION_CACHE_CONTROL_FEATURES))
-- No documentation found for TopLevel "VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_CREATION_CACHE_CONTROL_FEATURES_EXT"
pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_CREATION_CACHE_CONTROL_FEATURES_EXT = STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_CREATION_CACHE_CONTROL_FEATURES
-- No documentation found for TopLevel "VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT_EXT"
pattern PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT_EXT = PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT
-- No documentation found for TopLevel "VK_PIPELINE_CREATE_EARLY_RETURN_ON_FAILURE_BIT_EXT"
pattern PIPELINE_CREATE_EARLY_RETURN_ON_FAILURE_BIT_EXT = PIPELINE_CREATE_EARLY_RETURN_ON_FAILURE_BIT
-- No documentation found for TopLevel "VK_PIPELINE_COMPILE_REQUIRED_EXT"
pattern PIPELINE_COMPILE_REQUIRED_EXT = PIPELINE_COMPILE_REQUIRED
-- No documentation found for TopLevel "VK_ERROR_PIPELINE_COMPILE_REQUIRED_EXT"
pattern ERROR_PIPELINE_COMPILE_REQUIRED_EXT = PIPELINE_COMPILE_REQUIRED
-- No documentation found for TopLevel "VK_PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT_EXT"
pattern PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT_EXT = PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT
-- No documentation found for TopLevel "VkPhysicalDevicePipelineCreationCacheControlFeaturesEXT"
type PhysicalDevicePipelineCreationCacheControlFeaturesEXT = PhysicalDevicePipelineCreationCacheControlFeatures
type EXT_PIPELINE_CREATION_CACHE_CONTROL_SPEC_VERSION = 3
-- No documentation found for TopLevel "VK_EXT_PIPELINE_CREATION_CACHE_CONTROL_SPEC_VERSION"
pattern EXT_PIPELINE_CREATION_CACHE_CONTROL_SPEC_VERSION :: forall a . Integral a => a
pattern EXT_PIPELINE_CREATION_CACHE_CONTROL_SPEC_VERSION = 3
type EXT_PIPELINE_CREATION_CACHE_CONTROL_EXTENSION_NAME = "VK_EXT_pipeline_creation_cache_control"
-- No documentation found for TopLevel "VK_EXT_PIPELINE_CREATION_CACHE_CONTROL_EXTENSION_NAME"
pattern EXT_PIPELINE_CREATION_CACHE_CONTROL_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern EXT_PIPELINE_CREATION_CACHE_CONTROL_EXTENSION_NAME = "VK_EXT_pipeline_creation_cache_control"
| expipiplus1/vulkan | src/Vulkan/Extensions/VK_EXT_pipeline_creation_cache_control.hs | bsd-3-clause | 12,465 | 0 | 8 | 2,202 | 553 | 427 | 126 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Auth
import Common
import Control.Applicative
import Control.Lens
import Control.Monad.IO.Class
import Control.Monad.State
import Data.Aeson
import Data.Aeson.Types
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as L8
import qualified Data.ByteString.Lazy.UTF8 as LU
import qualified Data.ByteString.UTF8 as BU
import Data.Conduit
import qualified Data.Conduit.List as CL
import qualified Data.Foldable as F
import qualified Data.HashMap.Strict as HS
import qualified Data.List as DL
import qualified Data.Text as T
import qualified Data.Tree as TR
import Network.HTTP.Conduit
import System.IO
import Text.Printf (printf)
import qualified Types
import Types
import qualified User as U
import qualified Thread as Th
add3 x y z = x + y + z
x = Just 1
y = Just 2
z = Just 3
t = add3 <$> x <*> y <*> z
vs = [1..10]
summed :: [Int]
summed = getZipList $ add3 <$> ZipList vs <*> ZipList vs <*> ZipList vs
aboutIO :: String -> IO Account
aboutIO user = do
req <- parseUrl $ printf "http://www.reddit.com/user/%s/about.json" user
resp <- withManager $ httpLbs req
let body = responseBody resp
let jVal = eitherDecode body
return $ eitherToException $ jVal >>= (\x -> parseEither (x .:) "data")
main :: IO ()
main = do
about <- aboutIO "urdnot_rekt"
print "Got `about` `urdnot_rekt` successfully"
handle <- openFile "secrets.txt" ReadMode
[user, pass] <- sequence [hGetLine handle, hGetLine handle]
print $ user ++ " " ++ pass
state <- login user pass
evalStateT thing state
thing :: Reddit ()
thing = do
me <- aboutMe
liftIO $ print "Got `aboutMe` successfully. (Means auth is good)"
comments <- U.comments "Suppiluliuma_I" New DefaultAge $$ CL.take 1
submitted <- U.submitted "Suppiluliuma_I" New DefaultAge $$ CL.take 1
liked <- U.liked "Suppiluliuma_I" $$ CL.take 1
let sample = head $ head liked
thread <- Th.thread sample
fullThread <- Th.fillThread sample thread
liftIO $ do
putStrLn "\n"
print $ head $ head comments
putStrLn "\n"
print $ head $ head submitted
putStrLn "\n"
print $ sample
putStrLn "\n"
putStrLn $ Th.drawThread thread
putStrLn $ (show $ countForest thread) ++ " comments total."
--putStrLn "\n"
--print $ (\x -> x ^. ups - x ^. downs) <$> fst (Th.thing thread)
putStrLn "\n"
putStrLn $ Th.drawThread fullThread
putStrLn $ (show $ countForest fullThread) ++ " comments total."
getRight x = case x of
Left _ -> error "Left in getRight"
Right x -> x
countForest :: TR.Forest (Either a b) -> Int
countForest f = sum $ (F.foldr (\elem acc -> case elem of
Left _ -> acc
Right _ -> acc + 1) 0 ) <$> f | MarkJr94/sleuth | Main.hs | bsd-3-clause | 3,151 | 0 | 14 | 930 | 909 | 470 | 439 | 83 | 2 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[TcType]{Types used in the typechecker}
This module provides the Type interface for front-end parts of the
compiler. These parts
* treat "source types" as opaque:
newtypes, and predicates are meaningful.
* look through usage types
The "tc" prefix is for "TypeChecker", because the type checker
is the principal client.
-}
{-# LANGUAGE CPP, MultiWayIf #-}
module TcType (
--------------------------------
-- Types
TcType, TcSigmaType, TcRhoType, TcTauType, TcPredType, TcThetaType,
TcTyVar, TcTyVarSet, TcDTyVarSet, TcTyCoVarSet, TcDTyCoVarSet,
TcKind, TcCoVar, TcTyCoVar, TcTyBinder, TcTyCon,
ExpType(..), ExpSigmaType, ExpRhoType, mkCheckExpType,
SyntaxOpType(..), synKnownType, mkSynFunTys,
-- TcLevel
TcLevel(..), topTcLevel, pushTcLevel, isTopTcLevel,
strictlyDeeperThan, sameDepthAs, fmvTcLevel,
--------------------------------
-- MetaDetails
UserTypeCtxt(..), pprUserTypeCtxt, pprSigCtxt, isSigMaybe,
TcTyVarDetails(..), pprTcTyVarDetails, vanillaSkolemTv, superSkolemTv,
MetaDetails(Flexi, Indirect), MetaInfo(..), TauTvFlavour(..),
isImmutableTyVar, isSkolemTyVar, isMetaTyVar, isMetaTyVarTy, isTyVarTy,
isSigTyVar, isOverlappableTyVar, isTyConableTyVar,
isFskTyVar, isFmvTyVar, isFlattenTyVar,
isAmbiguousTyVar, metaTvRef, metaTyVarInfo,
isFlexi, isIndirect, isRuntimeUnkSkol,
metaTyVarTcLevel, setMetaTyVarTcLevel, metaTyVarTcLevel_maybe,
isTouchableMetaTyVar, isTouchableOrFmv,
isFloatedTouchableMetaTyVar,
canUnifyWithPolyType,
--------------------------------
-- Builders
mkPhiTy, mkInvSigmaTy, mkSpecSigmaTy, mkSigmaTy,
mkNakedTyConApp, mkNakedAppTys, mkNakedAppTy,
mkNakedCastTy,
--------------------------------
-- Splitters
-- These are important because they do not look through newtypes
getTyVar,
tcSplitForAllTy_maybe,
tcSplitForAllTys, tcSplitPiTys, tcSplitNamedPiTys,
tcSplitPhiTy, tcSplitPredFunTy_maybe,
tcSplitFunTy_maybe, tcSplitFunTys, tcFunArgTy, tcFunResultTy, tcSplitFunTysN,
tcSplitTyConApp, tcSplitTyConApp_maybe, tcRepSplitTyConApp_maybe,
tcTyConAppTyCon, tcTyConAppArgs,
tcSplitAppTy_maybe, tcSplitAppTy, tcSplitAppTys, tcRepSplitAppTy_maybe,
tcGetTyVar_maybe, tcGetTyVar, nextRole,
tcSplitSigmaTy, tcDeepSplitSigmaTy_maybe,
---------------------------------
-- Predicates.
-- Again, newtypes are opaque
eqType, eqTypes, cmpType, cmpTypes, eqTypeX,
pickyEqType, tcEqType, tcEqKind, tcEqTypeNoKindCheck, tcEqTypeVis,
isSigmaTy, isRhoTy, isRhoExpTy, isOverloadedTy,
isFloatingTy, isDoubleTy, isFloatTy, isIntTy, isWordTy, isStringTy,
isIntegerTy, isBoolTy, isUnitTy, isCharTy,
isTauTy, isTauTyCon, tcIsTyVarTy, tcIsForAllTy,
isPredTy, isTyVarClassPred, isTyVarExposed, isTyVarUnderDatatype,
checkValidClsArgs, hasTyVarHead,
isRigidEqPred, isRigidTy,
---------------------------------
-- Misc type manipulators
deNoteType, occurCheckExpand, OccCheckResult(..),
orphNamesOfType, orphNamesOfCo,
orphNamesOfTypes, orphNamesOfCoCon,
getDFunTyKey,
evVarPred_maybe, evVarPred,
---------------------------------
-- Predicate types
mkMinimalBySCs, transSuperClasses,
pickQuantifiablePreds,
immSuperClasses,
isImprovementPred,
-- * Finding type instances
tcTyFamInsts,
-- * Finding "exact" (non-dead) type variables
exactTyCoVarsOfType, exactTyCoVarsOfTypes,
-- * Extracting bound variables
allBoundVariables, allBoundVariabless,
---------------------------------
-- Foreign import and export
isFFIArgumentTy, -- :: DynFlags -> Safety -> Type -> Bool
isFFIImportResultTy, -- :: DynFlags -> Type -> Bool
isFFIExportResultTy, -- :: Type -> Bool
isFFIExternalTy, -- :: Type -> Bool
isFFIDynTy, -- :: Type -> Type -> Bool
isFFIPrimArgumentTy, -- :: DynFlags -> Type -> Bool
isFFIPrimResultTy, -- :: DynFlags -> Type -> Bool
isFFILabelTy, -- :: Type -> Bool
isFFITy, -- :: Type -> Bool
isFunPtrTy, -- :: Type -> Bool
tcSplitIOType_maybe, -- :: Type -> Maybe Type
--------------------------------
-- Rexported from Kind
Kind, typeKind,
liftedTypeKind,
constraintKind,
isLiftedTypeKind, isUnliftedTypeKind, classifiesTypeWithValues,
--------------------------------
-- Rexported from Type
Type, PredType, ThetaType, TyBinder, VisibilityFlag(..),
mkForAllTy, mkForAllTys, mkInvForAllTys, mkSpecForAllTys, mkNamedForAllTy,
mkFunTy, mkFunTys,
mkTyConApp, mkAppTy, mkAppTys,
mkTyConTy, mkTyVarTy,
mkTyVarTys,
mkNamedBinder,
isClassPred, isEqPred, isNomEqPred, isIPPred,
mkClassPred,
isDictLikeTy,
tcSplitDFunTy, tcSplitDFunHead, tcSplitMethodTy,
isRuntimeRepVar, isRuntimeRepPolymorphic,
isVisibleBinder, isInvisibleBinder,
-- Type substitutions
TCvSubst(..), -- Representation visible to a few friends
TvSubstEnv, emptyTCvSubst,
zipTvSubst,
mkTvSubstPrs, notElemTCvSubst, unionTCvSubst,
getTvSubstEnv, setTvSubstEnv, getTCvInScope, extendTCvInScope,
extendTCvInScopeList, extendTCvInScopeSet, extendTvSubstAndInScope,
Type.lookupTyVar, Type.extendTCvSubst, Type.substTyVarBndr,
Type.extendTvSubst,
isInScope, mkTCvSubst, mkTvSubst, zipTyEnv, zipCoEnv,
Type.substTy, substTys, substTyWith, substTyWithCoVars,
substTyAddInScope,
substTyUnchecked, substTysUnchecked, substThetaUnchecked,
substTyWithBindersUnchecked, substTyWithUnchecked,
substCoUnchecked, substCoWithUnchecked,
substTheta,
isUnliftedType, -- Source types are always lifted
isUnboxedTupleType, -- Ditto
isPrimitiveType,
coreView,
tyCoVarsOfType, tyCoVarsOfTypes, closeOverKinds,
tyCoVarsOfTelescope,
tyCoVarsOfTypeAcc, tyCoVarsOfTypesAcc,
tyCoVarsOfTypeDSet, tyCoVarsOfTypesDSet, closeOverKindsDSet,
tyCoVarsOfTypeList, tyCoVarsOfTypesList,
--------------------------------
-- Transforming Types to TcTypes
toTcType, -- :: Type -> TcType
toTcTypeBag, -- :: Bag EvVar -> Bag EvVar
pprKind, pprParendKind, pprSigmaType,
pprType, pprParendType, pprTypeApp, pprTyThingCategory,
pprTheta, pprThetaArrowTy, pprClassPred,
TypeSize, sizeType, sizeTypes, toposortTyVars
) where
#include "HsVersions.h"
-- friends:
import Kind
import TyCoRep
import Class
import Var
import ForeignCall
import VarSet
import Coercion
import Type
import TyCon
-- others:
import DynFlags
import CoreFVs
import Name -- hiding (varName)
-- We use this to make dictionaries for type literals.
-- Perhaps there's a better way to do this?
import NameSet
import VarEnv
import PrelNames
import TysWiredIn
import BasicTypes
import Util
import Bag
import Maybes
import Pair
import Outputable
import FastString
import ErrUtils( Validity(..), MsgDoc, isValid )
import FV
import qualified GHC.LanguageExtensions as LangExt
import Data.IORef
import Control.Monad (liftM, ap)
import Data.Functor.Identity
{-
************************************************************************
* *
\subsection{Types}
* *
************************************************************************
The type checker divides the generic Type world into the
following more structured beasts:
sigma ::= forall tyvars. phi
-- A sigma type is a qualified type
--
-- Note that even if 'tyvars' is empty, theta
-- may not be: e.g. (?x::Int) => Int
-- Note that 'sigma' is in prenex form:
-- all the foralls are at the front.
-- A 'phi' type has no foralls to the right of
-- an arrow
phi :: theta => rho
rho ::= sigma -> rho
| tau
-- A 'tau' type has no quantification anywhere
-- Note that the args of a type constructor must be taus
tau ::= tyvar
| tycon tau_1 .. tau_n
| tau_1 tau_2
| tau_1 -> tau_2
-- In all cases, a (saturated) type synonym application is legal,
-- provided it expands to the required form.
-}
type TcTyVar = TyVar -- Used only during type inference
type TcCoVar = CoVar -- Used only during type inference
type TcType = Type -- A TcType can have mutable type variables
type TcTyCoVar = Var -- Either a TcTyVar or a CoVar
-- Invariant on ForAllTy in TcTypes:
-- forall a. T
-- a cannot occur inside a MutTyVar in T; that is,
-- T is "flattened" before quantifying over a
type TcTyBinder = TyBinder
type TcTyCon = TyCon -- these can be the TcTyCon constructor
-- These types do not have boxy type variables in them
type TcPredType = PredType
type TcThetaType = ThetaType
type TcSigmaType = TcType
type TcRhoType = TcType -- Note [TcRhoType]
type TcTauType = TcType
type TcKind = Kind
type TcTyVarSet = TyVarSet
type TcTyCoVarSet = TyCoVarSet
type TcDTyVarSet = DTyVarSet
type TcDTyCoVarSet = DTyCoVarSet
-- | An expected type to check against during type-checking.
-- See Note [ExpType] in TcMType, where you'll also find manipulators.
data ExpType = Check TcType
| Infer Unique -- for debugging only
TcLevel -- See Note [TcLevel of ExpType] in TcMType
Kind
(IORef (Maybe TcType))
type ExpSigmaType = ExpType
type ExpRhoType = ExpType
instance Outputable ExpType where
ppr (Check ty) = ppr ty
ppr (Infer u lvl ki _)
= parens (text "Infer" <> braces (ppr u <> comma <> ppr lvl)
<+> dcolon <+> ppr ki)
-- | Make an 'ExpType' suitable for checking.
mkCheckExpType :: TcType -> ExpType
mkCheckExpType = Check
-- | What to expect for an argument to a rebindable-syntax operator.
-- Quite like 'Type', but allows for holes to be filled in by tcSyntaxOp.
-- The callback called from tcSyntaxOp gets a list of types; the meaning
-- of these types is determined by a left-to-right depth-first traversal
-- of the 'SyntaxOpType' tree. So if you pass in
--
-- > SynAny `SynFun` (SynList `SynFun` SynType Int) `SynFun` SynAny
--
-- you'll get three types back: one for the first 'SynAny', the /element/
-- type of the list, and one for the last 'SynAny'. You don't get anything
-- for the 'SynType', because you've said positively that it should be an
-- Int, and so it shall be.
--
-- This is defined here to avoid defining it in TcExpr.hs-boot.
data SyntaxOpType
= SynAny -- ^ Any type
| SynRho -- ^ A rho type, deeply skolemised or instantiated as appropriate
| SynList -- ^ A list type. You get back the element type of the list
| SynFun SyntaxOpType SyntaxOpType
-- ^ A function.
| SynType ExpType -- ^ A known type.
infixr 0 `SynFun`
-- | Like 'SynType' but accepts a regular TcType
synKnownType :: TcType -> SyntaxOpType
synKnownType = SynType . mkCheckExpType
-- | Like 'mkFunTys' but for 'SyntaxOpType'
mkSynFunTys :: [SyntaxOpType] -> ExpType -> SyntaxOpType
mkSynFunTys arg_tys res_ty = foldr SynFun (SynType res_ty) arg_tys
{-
Note [TcRhoType]
~~~~~~~~~~~~~~~~
A TcRhoType has no foralls or contexts at the top, or to the right of an arrow
YES (forall a. a->a) -> Int
NO forall a. a -> Int
NO Eq a => a -> a
NO Int -> forall a. a -> Int
************************************************************************
* *
\subsection{TyVarDetails}
* *
************************************************************************
TyVarDetails gives extra info about type variables, used during type
checking. It's attached to mutable type variables only.
It's knot-tied back to Var.hs. There is no reason in principle
why Var.hs shouldn't actually have the definition, but it "belongs" here.
Note [Signature skolems]
~~~~~~~~~~~~~~~~~~~~~~~~
Consider this
f :: forall a. [a] -> Int
f (x::b : xs) = 3
Here 'b' is a lexically scoped type variable, but it turns out to be
the same as the skolem 'a'. So we have a special kind of skolem
constant, SigTv, which can unify with other SigTvs. They are used
*only* for pattern type signatures.
Similarly consider
data T (a:k1) = MkT (S a)
data S (b:k2) = MkS (T b)
When doing kind inference on {S,T} we don't want *skolems* for k1,k2,
because they end up unifying; we want those SigTvs again.
Note [TyVars and TcTyVars during type checking]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Var type has constructors TyVar and TcTyVar. They are used
as follows:
* TcTyVar: used /only/ during type checking. Should never appear
afterwards. May contain a mutable field, in the MetaTv case.
* TyVar: is never seen by the constraint solver, except locally
inside a type like (forall a. [a] ->[a]), where 'a' is a TyVar.
We instantiate these with TcTyVars before exposing the type
to the constraint solver.
I have swithered about the latter invariant, excluding TyVars from the
constraint solver. It's not strictly essential, and indeed
(historically but still there) Var.tcTyVarDetails returns
vanillaSkolemTv for a TyVar.
But ultimately I want to seeparate Type from TcType, and in that case
we would need to enforce the separation.
-}
-- A TyVarDetails is inside a TyVar
-- See Note [TyVars and TcTyVars]
data TcTyVarDetails
= SkolemTv -- A skolem
Bool -- True <=> this skolem type variable can be overlapped
-- when looking up instances
-- See Note [Binding when looking up instances] in InstEnv
| FlatSkol -- A flatten-skolem. It stands for the TcType, and zonking
TcType -- will replace it by that type.
-- See Note [The flattening story] in TcFlatten
| RuntimeUnk -- Stands for an as-yet-unknown type in the GHCi
-- interactive context
| MetaTv { mtv_info :: MetaInfo
, mtv_ref :: IORef MetaDetails
, mtv_tclvl :: TcLevel } -- See Note [TcLevel and untouchable type variables]
vanillaSkolemTv, superSkolemTv :: TcTyVarDetails
-- See Note [Binding when looking up instances] in InstEnv
vanillaSkolemTv = SkolemTv False -- Might be instantiated
superSkolemTv = SkolemTv True -- Treat this as a completely distinct type
-----------------------------
data MetaDetails
= Flexi -- Flexi type variables unify to become Indirects
| Indirect TcType
instance Outputable MetaDetails where
ppr Flexi = text "Flexi"
ppr (Indirect ty) = text "Indirect" <+> ppr ty
data TauTvFlavour
= VanillaTau
| WildcardTau -- ^ A tyvar that originates from a type wildcard.
data MetaInfo
= TauTv -- This MetaTv is an ordinary unification variable
-- A TauTv is always filled in with a tau-type, which
-- never contains any ForAlls.
| SigTv -- A variant of TauTv, except that it should not be
-- unified with a type, only with a type variable
-- SigTvs are only distinguished to improve error messages
-- see Note [Signature skolems]
-- The MetaDetails, if filled in, will
-- always be another SigTv or a SkolemTv
| FlatMetaTv -- A flatten meta-tyvar
-- It is a meta-tyvar, but it is always untouchable, with level 0
-- See Note [The flattening story] in TcFlatten
-------------------------------------
-- UserTypeCtxt describes the origin of the polymorphic type
-- in the places where we need to an expression has that type
data UserTypeCtxt
= FunSigCtxt -- Function type signature, when checking the type
-- Also used for types in SPECIALISE pragmas
Name -- Name of the function
Bool -- True <=> report redundant constraints
-- This is usually True, but False for
-- * Record selectors (not important here)
-- * Class and instance methods. Here
-- the code may legitimately be more
-- polymorphic than the signature
-- generated from the class
-- declaration
| InfSigCtxt Name -- Inferred type for function
| ExprSigCtxt -- Expression type signature
| TypeAppCtxt -- Visible type application
| ConArgCtxt Name -- Data constructor argument
| TySynCtxt Name -- RHS of a type synonym decl
| PatSynCtxt Name -- Type sig for a pattern synonym
-- eg pattern C :: Int -> T
| PatSigCtxt -- Type sig in pattern
-- eg f (x::t) = ...
-- or (x::t, y) = e
| RuleSigCtxt Name -- LHS of a RULE forall
-- RULE "foo" forall (x :: a -> a). f (Just x) = ...
| ResSigCtxt -- Result type sig
-- f x :: t = ....
| ForSigCtxt Name -- Foreign import or export signature
| DefaultDeclCtxt -- Types in a default declaration
| InstDeclCtxt -- An instance declaration
| SpecInstCtxt -- SPECIALISE instance pragma
| ThBrackCtxt -- Template Haskell type brackets [t| ... |]
| GenSigCtxt -- Higher-rank or impredicative situations
-- e.g. (f e) where f has a higher-rank type
-- We might want to elaborate this
| GhciCtxt -- GHCi command :kind <type>
| ClassSCCtxt Name -- Superclasses of a class
| SigmaCtxt -- Theta part of a normal for-all type
-- f :: <S> => a -> a
| DataTyCtxt Name -- Theta part of a data decl
-- data <S> => T a = MkT a
{-
-- Notes re TySynCtxt
-- We allow type synonyms that aren't types; e.g. type List = []
--
-- If the RHS mentions tyvars that aren't in scope, we'll
-- quantify over them:
-- e.g. type T = a->a
-- will become type T = forall a. a->a
--
-- With gla-exts that's right, but for H98 we should complain.
-}
{- *********************************************************************
* *
Untoucable type variables
* *
********************************************************************* -}
newtype TcLevel = TcLevel Int deriving( Eq, Ord )
-- See Note [TcLevel and untouchable type variables] for what this Int is
-- See also Note [TcLevel assignment]
{-
Note [TcLevel and untouchable type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Each unification variable (MetaTv)
and each Implication
has a level number (of type TcLevel)
* INVARIANTS. In a tree of Implications,
(ImplicInv) The level number of an Implication is
STRICTLY GREATER THAN that of its parent
(MetaTvInv) The level number of a unification variable is
LESS THAN OR EQUAL TO that of its parent
implication
* A unification variable is *touchable* if its level number
is EQUAL TO that of its immediate parent implication.
* INVARIANT
(GivenInv) The free variables of the ic_given of an
implication are all untouchable; ie their level
numbers are LESS THAN the ic_tclvl of the implication
Note [Skolem escape prevention]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We only unify touchable unification variables. Because of
(MetaTvInv), there can be no occurrences of the variable further out,
so the unification can't cause the skolems to escape. Example:
data T = forall a. MkT a (a->Int)
f x (MkT v f) = length [v,x]
We decide (x::alpha), and generate an implication like
[1]forall a. (a ~ alpha[0])
But we must not unify alpha:=a, because the skolem would escape.
For the cases where we DO want to unify, we rely on floating the
equality. Example (with same T)
g x (MkT v f) = x && True
We decide (x::alpha), and generate an implication like
[1]forall a. (Bool ~ alpha[0])
We do NOT unify directly, bur rather float out (if the constraint
does not mention 'a') to get
(Bool ~ alpha[0]) /\ [1]forall a.()
and NOW we can unify alpha.
The same idea of only unifying touchables solves another problem.
Suppose we had
(F Int ~ uf[0]) /\ [1](forall a. C a => F Int ~ beta[1])
In this example, beta is touchable inside the implication. The
first solveSimpleWanteds step leaves 'uf' un-unified. Then we move inside
the implication where a new constraint
uf ~ beta
emerges. If we (wrongly) spontaneously solved it to get uf := beta,
the whole implication disappears but when we pop out again we are left with
(F Int ~ uf) which will be unified by our final zonking stage and
uf will get unified *once more* to (F Int).
Note [TcLevel assignment]
~~~~~~~~~~~~~~~~~~~~~~~~~
We arrange the TcLevels like this
1 Top level
2 Flatten-meta-vars of level 3
3 First-level implication constraints
4 Flatten-meta-vars of level 5
5 Second-level implication constraints
...etc...
The even-numbered levels are for the flatten-meta-variables assigned
at the next level in. Eg for a second-level implication conststraint
(level 5), the flatten meta-vars are level 4, which makes them untouchable.
The flatten meta-vars could equally well all have level 0, or just NotALevel
since they do not live across implications.
-}
fmvTcLevel :: TcLevel -> TcLevel
-- See Note [TcLevel assignment]
fmvTcLevel (TcLevel n) = TcLevel (n-1)
topTcLevel :: TcLevel
-- See Note [TcLevel assignment]
topTcLevel = TcLevel 1 -- 1 = outermost level
isTopTcLevel :: TcLevel -> Bool
isTopTcLevel (TcLevel 1) = True
isTopTcLevel _ = False
pushTcLevel :: TcLevel -> TcLevel
-- See Note [TcLevel assignment]
pushTcLevel (TcLevel us) = TcLevel (us + 2)
strictlyDeeperThan :: TcLevel -> TcLevel -> Bool
strictlyDeeperThan (TcLevel tv_tclvl) (TcLevel ctxt_tclvl)
= tv_tclvl > ctxt_tclvl
sameDepthAs :: TcLevel -> TcLevel -> Bool
sameDepthAs (TcLevel ctxt_tclvl) (TcLevel tv_tclvl)
= ctxt_tclvl == tv_tclvl -- NB: invariant ctxt_tclvl >= tv_tclvl
-- So <= would be equivalent
checkTcLevelInvariant :: TcLevel -> TcLevel -> Bool
-- Checks (MetaTvInv) from Note [TcLevel and untouchable type variables]
checkTcLevelInvariant (TcLevel ctxt_tclvl) (TcLevel tv_tclvl)
= ctxt_tclvl >= tv_tclvl
instance Outputable TcLevel where
ppr (TcLevel us) = ppr us
{-
************************************************************************
* *
Pretty-printing
* *
************************************************************************
-}
pprTcTyVarDetails :: TcTyVarDetails -> SDoc
-- For debugging
pprTcTyVarDetails (SkolemTv True) = text "ssk"
pprTcTyVarDetails (SkolemTv False) = text "sk"
pprTcTyVarDetails (RuntimeUnk {}) = text "rt"
pprTcTyVarDetails (FlatSkol {}) = text "fsk"
pprTcTyVarDetails (MetaTv { mtv_info = info, mtv_tclvl = tclvl })
= pp_info <> colon <> ppr tclvl
where
pp_info = case info of
TauTv -> text "tau"
SigTv -> text "sig"
FlatMetaTv -> text "fuv"
pprUserTypeCtxt :: UserTypeCtxt -> SDoc
pprUserTypeCtxt (FunSigCtxt n _) = text "the type signature for" <+> quotes (ppr n)
pprUserTypeCtxt (InfSigCtxt n) = text "the inferred type for" <+> quotes (ppr n)
pprUserTypeCtxt (RuleSigCtxt n) = text "a RULE for" <+> quotes (ppr n)
pprUserTypeCtxt ExprSigCtxt = text "an expression type signature"
pprUserTypeCtxt TypeAppCtxt = text "a type argument"
pprUserTypeCtxt (ConArgCtxt c) = text "the type of the constructor" <+> quotes (ppr c)
pprUserTypeCtxt (TySynCtxt c) = text "the RHS of the type synonym" <+> quotes (ppr c)
pprUserTypeCtxt (PatSynCtxt c) = text "the type signature for pattern synonym" <+> quotes (ppr c)
pprUserTypeCtxt ThBrackCtxt = text "a Template Haskell quotation [t|...|]"
pprUserTypeCtxt PatSigCtxt = text "a pattern type signature"
pprUserTypeCtxt ResSigCtxt = text "a result type signature"
pprUserTypeCtxt (ForSigCtxt n) = text "the foreign declaration for" <+> quotes (ppr n)
pprUserTypeCtxt DefaultDeclCtxt = text "a type in a `default' declaration"
pprUserTypeCtxt InstDeclCtxt = text "an instance declaration"
pprUserTypeCtxt SpecInstCtxt = text "a SPECIALISE instance pragma"
pprUserTypeCtxt GenSigCtxt = text "a type expected by the context"
pprUserTypeCtxt GhciCtxt = text "a type in a GHCi command"
pprUserTypeCtxt (ClassSCCtxt c) = text "the super-classes of class" <+> quotes (ppr c)
pprUserTypeCtxt SigmaCtxt = text "the context of a polymorphic type"
pprUserTypeCtxt (DataTyCtxt tc) = text "the context of the data type declaration for" <+> quotes (ppr tc)
pprSigCtxt :: UserTypeCtxt -> SDoc -> SDoc -> SDoc
-- (pprSigCtxt ctxt <extra> <type>)
-- prints In <extra> the type signature for 'f':
-- f :: <type>
-- The <extra> is either empty or "the ambiguity check for"
pprSigCtxt ctxt extra pp_ty
| Just n <- isSigMaybe ctxt
= vcat [ text "In" <+> extra <+> ptext (sLit "the type signature:")
, nest 2 (pprPrefixOcc n <+> dcolon <+> pp_ty) ]
| otherwise
= hang (text "In" <+> extra <+> pprUserTypeCtxt ctxt <> colon)
2 pp_ty
where
isSigMaybe :: UserTypeCtxt -> Maybe Name
isSigMaybe (FunSigCtxt n _) = Just n
isSigMaybe (ConArgCtxt n) = Just n
isSigMaybe (ForSigCtxt n) = Just n
isSigMaybe (PatSynCtxt n) = Just n
isSigMaybe _ = Nothing
{-
************************************************************************
* *
Finding type family instances
* *
************************************************************************
-}
-- | Finds outermost type-family applications occuring in a type,
-- after expanding synonyms. In the list (F, tys) that is returned
-- we guarantee that tys matches F's arity. For example, given
-- type family F a :: * -> * (arity 1)
-- calling tcTyFamInsts on (Maybe (F Int Bool) will return
-- (F, [Int]), not (F, [Int,Bool])
--
-- This is important for its use in deciding termination of type
-- instances (see Trac #11581). E.g.
-- type instance G [Int] = ...(F Int <big type>)...
-- we don't need to take <big type> into account when asking if
-- the calls on the RHS are smaller than the LHS
tcTyFamInsts :: Type -> [(TyCon, [Type])]
tcTyFamInsts ty
| Just exp_ty <- coreView ty = tcTyFamInsts exp_ty
tcTyFamInsts (TyVarTy _) = []
tcTyFamInsts (TyConApp tc tys)
| isTypeFamilyTyCon tc = [(tc, take (tyConArity tc) tys)]
| otherwise = concat (map tcTyFamInsts tys)
tcTyFamInsts (LitTy {}) = []
tcTyFamInsts (ForAllTy bndr ty) = tcTyFamInsts (binderType bndr)
++ tcTyFamInsts ty
tcTyFamInsts (AppTy ty1 ty2) = tcTyFamInsts ty1 ++ tcTyFamInsts ty2
tcTyFamInsts (CastTy ty _) = tcTyFamInsts ty
tcTyFamInsts (CoercionTy _) = [] -- don't count tyfams in coercions,
-- as they never get normalized, anyway
{-
************************************************************************
* *
The "exact" free variables of a type
* *
************************************************************************
Note [Silly type synonym]
~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
type T a = Int
What are the free tyvars of (T x)? Empty, of course!
Here's the example that Ralf Laemmel showed me:
foo :: (forall a. C u a -> C u a) -> u
mappend :: Monoid u => u -> u -> u
bar :: Monoid u => u
bar = foo (\t -> t `mappend` t)
We have to generalise at the arg to f, and we don't
want to capture the constraint (Monad (C u a)) because
it appears to mention a. Pretty silly, but it was useful to him.
exactTyCoVarsOfType is used by the type checker to figure out exactly
which type variables are mentioned in a type. It's also used in the
smart-app checking code --- see TcExpr.tcIdApp
On the other hand, consider a *top-level* definition
f = (\x -> x) :: T a -> T a
If we don't abstract over 'a' it'll get fixed to GHC.Prim.Any, and then
if we have an application like (f "x") we get a confusing error message
involving Any. So the conclusion is this: when generalising
- at top level use tyCoVarsOfType
- in nested bindings use exactTyCoVarsOfType
See Trac #1813 for example.
-}
exactTyCoVarsOfType :: Type -> TyCoVarSet
-- Find the free type variables (of any kind)
-- but *expand* type synonyms. See Note [Silly type synonym] above.
exactTyCoVarsOfType ty
= go ty
where
go ty | Just ty' <- coreView ty = go ty' -- This is the key line
go (TyVarTy tv) = unitVarSet tv `unionVarSet` go (tyVarKind tv)
go (TyConApp _ tys) = exactTyCoVarsOfTypes tys
go (LitTy {}) = emptyVarSet
go (AppTy fun arg) = go fun `unionVarSet` go arg
go (ForAllTy bndr ty) = delBinderVar (go ty) bndr `unionVarSet` go (binderType bndr)
go (CastTy ty co) = go ty `unionVarSet` goCo co
go (CoercionTy co) = goCo co
goCo (Refl _ ty) = go ty
goCo (TyConAppCo _ _ args)= goCos args
goCo (AppCo co arg) = goCo co `unionVarSet` goCo arg
goCo (ForAllCo tv k_co co)
= goCo co `delVarSet` tv `unionVarSet` goCo k_co
goCo (CoVarCo v) = unitVarSet v `unionVarSet` go (varType v)
goCo (AxiomInstCo _ _ args) = goCos args
goCo (UnivCo p _ t1 t2) = goProv p `unionVarSet` go t1 `unionVarSet` go t2
goCo (SymCo co) = goCo co
goCo (TransCo co1 co2) = goCo co1 `unionVarSet` goCo co2
goCo (NthCo _ co) = goCo co
goCo (LRCo _ co) = goCo co
goCo (InstCo co arg) = goCo co `unionVarSet` goCo arg
goCo (CoherenceCo c1 c2) = goCo c1 `unionVarSet` goCo c2
goCo (KindCo co) = goCo co
goCo (SubCo co) = goCo co
goCo (AxiomRuleCo _ c) = goCos c
goCos cos = foldr (unionVarSet . goCo) emptyVarSet cos
goProv UnsafeCoerceProv = emptyVarSet
goProv (PhantomProv kco) = goCo kco
goProv (ProofIrrelProv kco) = goCo kco
goProv (PluginProv _) = emptyVarSet
goProv (HoleProv _) = emptyVarSet
exactTyCoVarsOfTypes :: [Type] -> TyVarSet
exactTyCoVarsOfTypes tys = mapUnionVarSet exactTyCoVarsOfType tys
{-
************************************************************************
* *
Bound variables in a type
* *
************************************************************************
-}
-- | Find all variables bound anywhere in a type.
-- See also Note [Scope-check inferred kinds] in TcHsType
allBoundVariables :: Type -> TyVarSet
allBoundVariables ty = runFVSet $ go ty
where
go :: Type -> FV
go (TyVarTy tv) = go (tyVarKind tv)
go (TyConApp _ tys) = mapUnionFV go tys
go (AppTy t1 t2) = go t1 `unionFV` go t2
go (ForAllTy (Anon t1) t2) = go t1 `unionFV` go t2
go (ForAllTy (Named tv _) t2) = oneVar tv `unionFV`
go (tyVarKind tv) `unionFV` go t2
go (LitTy {}) = noVars
go (CastTy ty _) = go ty
go (CoercionTy {}) = noVars
-- any types mentioned in a coercion should also be mentioned in
-- a type.
allBoundVariabless :: [Type] -> TyVarSet
allBoundVariabless = mapUnionVarSet allBoundVariables
{-
************************************************************************
* *
Predicates
* *
************************************************************************
-}
isTouchableOrFmv :: TcLevel -> TcTyVar -> Bool
isTouchableOrFmv ctxt_tclvl tv
= ASSERT2( isTcTyVar tv, ppr tv )
case tcTyVarDetails tv of
MetaTv { mtv_tclvl = tv_tclvl, mtv_info = info }
-> ASSERT2( checkTcLevelInvariant ctxt_tclvl tv_tclvl,
ppr tv $$ ppr tv_tclvl $$ ppr ctxt_tclvl )
case info of
FlatMetaTv -> True
_ -> tv_tclvl `sameDepthAs` ctxt_tclvl
_ -> False
isTouchableMetaTyVar :: TcLevel -> TcTyVar -> Bool
isTouchableMetaTyVar ctxt_tclvl tv
| isTyVar tv
= ASSERT2( isTcTyVar tv, ppr tv )
case tcTyVarDetails tv of
MetaTv { mtv_tclvl = tv_tclvl }
-> ASSERT2( checkTcLevelInvariant ctxt_tclvl tv_tclvl,
ppr tv $$ ppr tv_tclvl $$ ppr ctxt_tclvl )
tv_tclvl `sameDepthAs` ctxt_tclvl
_ -> False
| otherwise = False
isFloatedTouchableMetaTyVar :: TcLevel -> TcTyVar -> Bool
isFloatedTouchableMetaTyVar ctxt_tclvl tv
| isTyVar tv
= ASSERT2( isTcTyVar tv, ppr tv )
case tcTyVarDetails tv of
MetaTv { mtv_tclvl = tv_tclvl } -> tv_tclvl `strictlyDeeperThan` ctxt_tclvl
_ -> False
| otherwise = False
isImmutableTyVar :: TyVar -> Bool
isImmutableTyVar tv
| isTcTyVar tv = isSkolemTyVar tv
| otherwise = True
isTyConableTyVar, isSkolemTyVar, isOverlappableTyVar,
isMetaTyVar, isAmbiguousTyVar,
isFmvTyVar, isFskTyVar, isFlattenTyVar :: TcTyVar -> Bool
isTyConableTyVar tv
-- True of a meta-type variable that can be filled in
-- with a type constructor application; in particular,
-- not a SigTv
| isTyVar tv
= ASSERT2( isTcTyVar tv, ppr tv )
case tcTyVarDetails tv of
MetaTv { mtv_info = SigTv } -> False
_ -> True
| otherwise = True
isFmvTyVar tv
= ASSERT2( isTcTyVar tv, ppr tv )
case tcTyVarDetails tv of
MetaTv { mtv_info = FlatMetaTv } -> True
_ -> False
-- | True of both given and wanted flatten-skolems (fak and usk)
isFlattenTyVar tv
= ASSERT2( isTcTyVar tv, ppr tv )
case tcTyVarDetails tv of
FlatSkol {} -> True
MetaTv { mtv_info = FlatMetaTv } -> True
_ -> False
-- | True of FlatSkol skolems only
isFskTyVar tv
= ASSERT2( isTcTyVar tv, ppr tv )
case tcTyVarDetails tv of
FlatSkol {} -> True
_ -> False
isSkolemTyVar tv
= ASSERT2( isTcTyVar tv, ppr tv )
case tcTyVarDetails tv of
MetaTv {} -> False
_other -> True
isOverlappableTyVar tv
| isTyVar tv
= ASSERT2( isTcTyVar tv, ppr tv )
case tcTyVarDetails tv of
SkolemTv overlappable -> overlappable
_ -> False
| otherwise = False
isMetaTyVar tv
| isTyVar tv
= ASSERT2( isTcTyVar tv, ppr tv )
case tcTyVarDetails tv of
MetaTv {} -> True
_ -> False
| otherwise = False
-- isAmbiguousTyVar is used only when reporting type errors
-- It picks out variables that are unbound, namely meta
-- type variables and the RuntimUnk variables created by
-- RtClosureInspect.zonkRTTIType. These are "ambiguous" in
-- the sense that they stand for an as-yet-unknown type
isAmbiguousTyVar tv
| isTyVar tv
= case tcTyVarDetails tv of
MetaTv {} -> True
RuntimeUnk {} -> True
_ -> False
| otherwise = False
isMetaTyVarTy :: TcType -> Bool
isMetaTyVarTy (TyVarTy tv) = isMetaTyVar tv
isMetaTyVarTy _ = False
metaTyVarInfo :: TcTyVar -> MetaInfo
metaTyVarInfo tv
= case tcTyVarDetails tv of
MetaTv { mtv_info = info } -> info
_ -> pprPanic "metaTyVarInfo" (ppr tv)
metaTyVarTcLevel :: TcTyVar -> TcLevel
metaTyVarTcLevel tv
= case tcTyVarDetails tv of
MetaTv { mtv_tclvl = tclvl } -> tclvl
_ -> pprPanic "metaTyVarTcLevel" (ppr tv)
metaTyVarTcLevel_maybe :: TcTyVar -> Maybe TcLevel
metaTyVarTcLevel_maybe tv
= case tcTyVarDetails tv of
MetaTv { mtv_tclvl = tclvl } -> Just tclvl
_ -> Nothing
setMetaTyVarTcLevel :: TcTyVar -> TcLevel -> TcTyVar
setMetaTyVarTcLevel tv tclvl
= case tcTyVarDetails tv of
details@(MetaTv {}) -> setTcTyVarDetails tv (details { mtv_tclvl = tclvl })
_ -> pprPanic "metaTyVarTcLevel" (ppr tv)
isSigTyVar :: Var -> Bool
isSigTyVar tv
= case tcTyVarDetails tv of
MetaTv { mtv_info = SigTv } -> True
_ -> False
metaTvRef :: TyVar -> IORef MetaDetails
metaTvRef tv
= case tcTyVarDetails tv of
MetaTv { mtv_ref = ref } -> ref
_ -> pprPanic "metaTvRef" (ppr tv)
isFlexi, isIndirect :: MetaDetails -> Bool
isFlexi Flexi = True
isFlexi _ = False
isIndirect (Indirect _) = True
isIndirect _ = False
isRuntimeUnkSkol :: TyVar -> Bool
-- Called only in TcErrors; see Note [Runtime skolems] there
isRuntimeUnkSkol x
| isTcTyVar x, RuntimeUnk <- tcTyVarDetails x = True
| otherwise = False
{-
************************************************************************
* *
\subsection{Tau, sigma and rho}
* *
************************************************************************
-}
mkSigmaTy :: [TyBinder] -> [PredType] -> Type -> Type
mkSigmaTy bndrs theta tau = mkForAllTys bndrs (mkPhiTy theta tau)
mkInvSigmaTy :: [TyVar] -> [PredType] -> Type -> Type
mkInvSigmaTy tyvars
= mkSigmaTy (map (mkNamedBinder Invisible) tyvars)
-- | Make a sigma ty where all type variables are "specified". That is,
-- they can be used with visible type application
mkSpecSigmaTy :: [TyVar] -> [PredType] -> Type -> Type
mkSpecSigmaTy tyvars
= mkSigmaTy (map (mkNamedBinder Specified) tyvars)
mkPhiTy :: [PredType] -> Type -> Type
mkPhiTy = mkFunTys
-- @isTauTy@ tests if a type is "simple"..
isTauTy :: Type -> Bool
isTauTy ty | Just ty' <- coreView ty = isTauTy ty'
isTauTy (TyVarTy _) = True
isTauTy (LitTy {}) = True
isTauTy (TyConApp tc tys) = all isTauTy tys && isTauTyCon tc
isTauTy (AppTy a b) = isTauTy a && isTauTy b
isTauTy (ForAllTy (Anon a) b) = isTauTy a && isTauTy b
isTauTy (ForAllTy {}) = False
isTauTy (CastTy _ _) = False
isTauTy (CoercionTy _) = False
isTauTyCon :: TyCon -> Bool
-- Returns False for type synonyms whose expansion is a polytype
isTauTyCon tc
| Just (_, rhs) <- synTyConDefn_maybe tc = isTauTy rhs
| otherwise = True
---------------
getDFunTyKey :: Type -> OccName -- Get some string from a type, to be used to
-- construct a dictionary function name
getDFunTyKey ty | Just ty' <- coreView ty = getDFunTyKey ty'
getDFunTyKey (TyVarTy tv) = getOccName tv
getDFunTyKey (TyConApp tc _) = getOccName tc
getDFunTyKey (LitTy x) = getDFunTyLitKey x
getDFunTyKey (AppTy fun _) = getDFunTyKey fun
getDFunTyKey (ForAllTy (Anon _) _) = getOccName funTyCon
getDFunTyKey (ForAllTy (Named {}) t) = getDFunTyKey t
getDFunTyKey (CastTy ty _) = getDFunTyKey ty
getDFunTyKey t@(CoercionTy _) = pprPanic "getDFunTyKey" (ppr t)
getDFunTyLitKey :: TyLit -> OccName
getDFunTyLitKey (NumTyLit n) = mkOccName Name.varName (show n)
getDFunTyLitKey (StrTyLit n) = mkOccName Name.varName (show n) -- hm
---------------
mkNakedTyConApp :: TyCon -> [Type] -> Type
-- Builds a TyConApp
-- * without being strict in TyCon,
-- * without satisfying the invariants of TyConApp
-- A subsequent zonking will establish the invariants
-- See Note [Type-checking inside the knot] in TcHsType
mkNakedTyConApp tc tys = TyConApp tc tys
mkNakedAppTys :: Type -> [Type] -> Type
-- See Note [Type-checking inside the knot] in TcHsType
mkNakedAppTys ty1 [] = ty1
mkNakedAppTys (TyConApp tc tys1) tys2 = mkNakedTyConApp tc (tys1 ++ tys2)
mkNakedAppTys ty1 tys2 = foldl AppTy ty1 tys2
mkNakedAppTy :: Type -> Type -> Type
-- See Note [Type-checking inside the knot] in TcHsType
mkNakedAppTy ty1 ty2 = mkNakedAppTys ty1 [ty2]
mkNakedCastTy :: Type -> Coercion -> Type
mkNakedCastTy = CastTy
{-
************************************************************************
* *
\subsection{Expanding and splitting}
* *
************************************************************************
These tcSplit functions are like their non-Tc analogues, but
*) they do not look through newtypes
However, they are non-monadic and do not follow through mutable type
variables. It's up to you to make sure this doesn't matter.
-}
-- | Splits a forall type into a list of 'TyBinder's and the inner type.
-- Always succeeds, even if it returns an empty list.
tcSplitPiTys :: Type -> ([TyBinder], Type)
tcSplitPiTys = splitPiTys
tcSplitForAllTy_maybe :: Type -> Maybe (TyBinder, Type)
tcSplitForAllTy_maybe ty | Just ty' <- coreView ty = tcSplitForAllTy_maybe ty'
tcSplitForAllTy_maybe (ForAllTy tv ty) = Just (tv, ty)
tcSplitForAllTy_maybe _ = Nothing
-- | Like 'tcSplitPiTys', but splits off only named binders, returning
-- just the tycovars.
tcSplitForAllTys :: Type -> ([TyVar], Type)
tcSplitForAllTys = splitForAllTys
-- | Like 'tcSplitForAllTys', but splits off only named binders.
tcSplitNamedPiTys :: Type -> ([TyBinder], Type)
tcSplitNamedPiTys = splitNamedPiTys
-- | Is this a ForAllTy with a named binder?
tcIsForAllTy :: Type -> Bool
tcIsForAllTy ty | Just ty' <- coreView ty = tcIsForAllTy ty'
tcIsForAllTy (ForAllTy (Named {}) _) = True
tcIsForAllTy _ = False
tcSplitPredFunTy_maybe :: Type -> Maybe (PredType, Type)
-- Split off the first predicate argument from a type
tcSplitPredFunTy_maybe ty
| Just ty' <- coreView ty = tcSplitPredFunTy_maybe ty'
tcSplitPredFunTy_maybe (ForAllTy (Anon arg) res)
| isPredTy arg = Just (arg, res)
tcSplitPredFunTy_maybe _
= Nothing
tcSplitPhiTy :: Type -> (ThetaType, Type)
tcSplitPhiTy ty
= split ty []
where
split ty ts
= case tcSplitPredFunTy_maybe ty of
Just (pred, ty) -> split ty (pred:ts)
Nothing -> (reverse ts, ty)
-- | Split a sigma type into its parts.
tcSplitSigmaTy :: Type -> ([TyVar], ThetaType, Type)
tcSplitSigmaTy ty = case tcSplitForAllTys ty of
(tvs, rho) -> case tcSplitPhiTy rho of
(theta, tau) -> (tvs, theta, tau)
-----------------------
tcDeepSplitSigmaTy_maybe
:: TcSigmaType -> Maybe ([TcType], [TyVar], ThetaType, TcSigmaType)
-- Looks for a *non-trivial* quantified type, under zero or more function arrows
-- By "non-trivial" we mean either tyvars or constraints are non-empty
tcDeepSplitSigmaTy_maybe ty
| Just (arg_ty, res_ty) <- tcSplitFunTy_maybe ty
, Just (arg_tys, tvs, theta, rho) <- tcDeepSplitSigmaTy_maybe res_ty
= Just (arg_ty:arg_tys, tvs, theta, rho)
| (tvs, theta, rho) <- tcSplitSigmaTy ty
, not (null tvs && null theta)
= Just ([], tvs, theta, rho)
| otherwise = Nothing
-----------------------
tcTyConAppTyCon :: Type -> TyCon
tcTyConAppTyCon ty = case tcSplitTyConApp_maybe ty of
Just (tc, _) -> tc
Nothing -> pprPanic "tcTyConAppTyCon" (pprType ty)
tcTyConAppArgs :: Type -> [Type]
tcTyConAppArgs ty = case tcSplitTyConApp_maybe ty of
Just (_, args) -> args
Nothing -> pprPanic "tcTyConAppArgs" (pprType ty)
tcSplitTyConApp :: Type -> (TyCon, [Type])
tcSplitTyConApp ty = case tcSplitTyConApp_maybe ty of
Just stuff -> stuff
Nothing -> pprPanic "tcSplitTyConApp" (pprType ty)
tcSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
tcSplitTyConApp_maybe ty | Just ty' <- coreView ty = tcSplitTyConApp_maybe ty'
tcSplitTyConApp_maybe ty = tcRepSplitTyConApp_maybe ty
tcRepSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
tcRepSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
tcRepSplitTyConApp_maybe (ForAllTy (Anon arg) res) = Just (funTyCon, [arg,res])
tcRepSplitTyConApp_maybe _ = Nothing
-----------------------
tcSplitFunTys :: Type -> ([Type], Type)
tcSplitFunTys ty = case tcSplitFunTy_maybe ty of
Nothing -> ([], ty)
Just (arg,res) -> (arg:args, res')
where
(args,res') = tcSplitFunTys res
tcSplitFunTy_maybe :: Type -> Maybe (Type, Type)
tcSplitFunTy_maybe ty | Just ty' <- coreView ty = tcSplitFunTy_maybe ty'
tcSplitFunTy_maybe (ForAllTy (Anon arg) res)
| not (isPredTy arg) = Just (arg, res)
tcSplitFunTy_maybe _ = Nothing
-- Note the typeKind guard
-- Consider (?x::Int) => Bool
-- We don't want to treat this as a function type!
-- A concrete example is test tc230:
-- f :: () -> (?p :: ()) => () -> ()
--
-- g = f () ()
tcSplitFunTysN
:: TcRhoType
-> Arity -- N: Number of desired args
-> ([TcSigmaType], -- Arg types (N or fewer)
TcSigmaType) -- The rest of the type
tcSplitFunTysN ty n_args
| n_args == 0
= ([], ty)
| Just (arg,res) <- tcSplitFunTy_maybe ty
= case tcSplitFunTysN res (n_args - 1) of
(args, res) -> (arg:args, res)
| otherwise
= ([], ty)
tcSplitFunTy :: Type -> (Type, Type)
tcSplitFunTy ty = expectJust "tcSplitFunTy" (tcSplitFunTy_maybe ty)
tcFunArgTy :: Type -> Type
tcFunArgTy ty = fst (tcSplitFunTy ty)
tcFunResultTy :: Type -> Type
tcFunResultTy ty = snd (tcSplitFunTy ty)
-----------------------
tcSplitAppTy_maybe :: Type -> Maybe (Type, Type)
tcSplitAppTy_maybe ty | Just ty' <- coreView ty = tcSplitAppTy_maybe ty'
tcSplitAppTy_maybe ty = tcRepSplitAppTy_maybe ty
tcSplitAppTy :: Type -> (Type, Type)
tcSplitAppTy ty = case tcSplitAppTy_maybe ty of
Just stuff -> stuff
Nothing -> pprPanic "tcSplitAppTy" (pprType ty)
tcSplitAppTys :: Type -> (Type, [Type])
tcSplitAppTys ty
= go ty []
where
go ty args = case tcSplitAppTy_maybe ty of
Just (ty', arg) -> go ty' (arg:args)
Nothing -> (ty,args)
-----------------------
tcGetTyVar_maybe :: Type -> Maybe TyVar
tcGetTyVar_maybe ty | Just ty' <- coreView ty = tcGetTyVar_maybe ty'
tcGetTyVar_maybe (TyVarTy tv) = Just tv
tcGetTyVar_maybe _ = Nothing
tcGetTyVar :: String -> Type -> TyVar
tcGetTyVar msg ty = expectJust msg (tcGetTyVar_maybe ty)
tcIsTyVarTy :: Type -> Bool
tcIsTyVarTy ty | Just ty' <- coreView ty = tcIsTyVarTy ty'
tcIsTyVarTy (CastTy ty _) = tcIsTyVarTy ty -- look through casts, as
-- this is only used for
-- e.g., FlexibleContexts
tcIsTyVarTy (TyVarTy _) = True
tcIsTyVarTy _ = False
-----------------------
tcSplitDFunTy :: Type -> ([TyVar], [Type], Class, [Type])
-- Split the type of a dictionary function
-- We don't use tcSplitSigmaTy, because a DFun may (with NDP)
-- have non-Pred arguments, such as
-- df :: forall m. (forall b. Eq b => Eq (m b)) -> C m
--
-- Also NB splitFunTys, not tcSplitFunTys;
-- the latter specifically stops at PredTy arguments,
-- and we don't want to do that here
tcSplitDFunTy ty
= case tcSplitForAllTys ty of { (tvs, rho) ->
case splitFunTys rho of { (theta, tau) ->
case tcSplitDFunHead tau of { (clas, tys) ->
(tvs, theta, clas, tys) }}}
tcSplitDFunHead :: Type -> (Class, [Type])
tcSplitDFunHead = getClassPredTys
tcSplitMethodTy :: Type -> ([TyVar], PredType, Type)
-- A class method (selector) always has a type like
-- forall as. C as => blah
-- So if the class looks like
-- class C a where
-- op :: forall b. (Eq a, Ix b) => a -> b
-- the class method type looks like
-- op :: forall a. C a => forall b. (Eq a, Ix b) => a -> b
--
-- tcSplitMethodTy just peels off the outer forall and
-- that first predicate
tcSplitMethodTy ty
| (sel_tyvars,sel_rho) <- tcSplitForAllTys ty
, Just (first_pred, local_meth_ty) <- tcSplitPredFunTy_maybe sel_rho
= (sel_tyvars, first_pred, local_meth_ty)
| otherwise
= pprPanic "tcSplitMethodTy" (ppr ty)
-----------------------
tcEqKind :: TcKind -> TcKind -> Bool
tcEqKind = tcEqType
tcEqType :: TcType -> TcType -> Bool
-- tcEqType is a proper implements the same Note [Non-trivial definitional
-- equality] (in TyCoRep) as `eqType`, but Type.eqType believes (* ==
-- Constraint), and that is NOT what we want in the type checker!
tcEqType ty1 ty2
= isNothing (tc_eq_type coreView ki1 ki2) &&
isNothing (tc_eq_type coreView ty1 ty2)
where
ki1 = typeKind ty1
ki2 = typeKind ty2
-- | Just like 'tcEqType', but will return True for types of different kinds
-- as long as their non-coercion structure is identical.
tcEqTypeNoKindCheck :: TcType -> TcType -> Bool
tcEqTypeNoKindCheck ty1 ty2
= isNothing $ tc_eq_type coreView ty1 ty2
-- | Like 'tcEqType', but returns information about whether the difference
-- is visible in the case of a mismatch. A return of Nothing means the types
-- are 'tcEqType'.
tcEqTypeVis :: TcType -> TcType -> Maybe VisibilityFlag
tcEqTypeVis ty1 ty2
= tc_eq_type coreView ty1 ty2 <!> tc_eq_type coreView ki1 ki2
where
ki1 = typeKind ty1
ki2 = typeKind ty2
(<!>) :: Maybe VisibilityFlag -> Maybe VisibilityFlag -> Maybe VisibilityFlag
Nothing <!> x = x
Just Visible <!> _ = Just Visible
Just _inv <!> Just Visible = Just Visible
Just inv <!> _ = Just inv
infixr 3 <!>
-- | Real worker for 'tcEqType'. No kind check!
tc_eq_type :: (TcType -> Maybe TcType) -- ^ @coreView@, if you want unwrapping
-> Type -> Type -> Maybe VisibilityFlag
tc_eq_type view_fun orig_ty1 orig_ty2 = go Visible orig_env orig_ty1 orig_ty2
where
go vis env t1 t2 | Just t1' <- view_fun t1 = go vis env t1' t2
go vis env t1 t2 | Just t2' <- view_fun t2 = go vis env t1 t2'
go vis env (TyVarTy tv1) (TyVarTy tv2)
= check vis $ rnOccL env tv1 == rnOccR env tv2
go vis _ (LitTy lit1) (LitTy lit2)
= check vis $ lit1 == lit2
go vis env (ForAllTy (Named tv1 vis1) ty1)
(ForAllTy (Named tv2 vis2) ty2)
= go vis1 env (tyVarKind tv1) (tyVarKind tv2)
<!> go vis (rnBndr2 env tv1 tv2) ty1 ty2
<!> check vis (vis1 == vis2)
go vis env (ForAllTy (Anon arg1) res1) (ForAllTy (Anon arg2) res2)
= go vis env arg1 arg2 <!> go vis env res1 res2
-- See Note [Equality on AppTys] in Type
go vis env (AppTy s1 t1) ty2
| Just (s2, t2) <- tcRepSplitAppTy_maybe ty2
= go vis env s1 s2 <!> go vis env t1 t2
go vis env ty1 (AppTy s2 t2)
| Just (s1, t1) <- tcRepSplitAppTy_maybe ty1
= go vis env s1 s2 <!> go vis env t1 t2
go vis env (TyConApp tc1 ts1) (TyConApp tc2 ts2)
= check vis (tc1 == tc2) <!> gos (tc_vis tc1) env ts1 ts2
go vis env (CastTy t1 _) t2 = go vis env t1 t2
go vis env t1 (CastTy t2 _) = go vis env t1 t2
go _ _ (CoercionTy {}) (CoercionTy {}) = Nothing
go vis _ _ _ = Just vis
gos _ _ [] [] = Nothing
gos (v:vs) env (t1:ts1) (t2:ts2) = go v env t1 t2 <!> gos vs env ts1 ts2
gos (v:_) _ _ _ = Just v
gos _ _ _ _ = panic "tc_eq_type"
tc_vis :: TyCon -> [VisibilityFlag]
tc_vis tc = viss ++ repeat Visible
-- the repeat Visible is necessary because tycons can legitimately
-- be oversaturated
where
bndrs = tyConBinders tc
viss = map binderVisibility bndrs
check :: VisibilityFlag -> Bool -> Maybe VisibilityFlag
check _ True = Nothing
check vis False = Just vis
orig_env = mkRnEnv2 $ mkInScopeSet $ tyCoVarsOfTypes [orig_ty1, orig_ty2]
-- | Like 'pickyEqTypeVis', but returns a Bool for convenience
pickyEqType :: TcType -> TcType -> Bool
-- Check when two types _look_ the same, _including_ synonyms.
-- So (pickyEqType String [Char]) returns False
-- This ignores kinds and coercions, because this is used only for printing.
pickyEqType ty1 ty2
= isNothing $
tc_eq_type (const Nothing) ty1 ty2
{-
Note [Occurs check expansion]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(occurCheckExpand tv xi) expands synonyms in xi just enough to get rid
of occurrences of tv outside type function arguments, if that is
possible; otherwise, it returns Nothing.
For example, suppose we have
type F a b = [a]
Then
occurCheckExpand b (F Int b) = Just [Int]
but
occurCheckExpand a (F a Int) = Nothing
We don't promise to do the absolute minimum amount of expanding
necessary, but we try not to do expansions we don't need to. We
prefer doing inner expansions first. For example,
type F a b = (a, Int, a, [a])
type G b = Char
We have
occurCheckExpand b (F (G b)) = F Char
even though we could also expand F to get rid of b.
See also Note [occurCheckExpand] in TcCanonical
-}
data OccCheckResult a
= OC_OK a
| OC_Forall
| OC_NonTyVar
| OC_Occurs
instance Functor OccCheckResult where
fmap = liftM
instance Applicative OccCheckResult where
pure = OC_OK
(<*>) = ap
instance Monad OccCheckResult where
OC_OK x >>= k = k x
OC_Forall >>= _ = OC_Forall
OC_NonTyVar >>= _ = OC_NonTyVar
OC_Occurs >>= _ = OC_Occurs
occurCheckExpand :: DynFlags -> TcTyVar -> Type -> OccCheckResult Type
-- See Note [Occurs check expansion]
-- Check whether
-- a) the given variable occurs in the given type.
-- b) there is a forall in the type (unless we have -XImpredicativeTypes)
-- c) if it's a SigTv, ty should be a tyvar
--
-- We may have needed to do some type synonym unfolding in order to
-- get rid of the variable (or forall), so we also return the unfolded
-- version of the type, which is guaranteed to be syntactically free
-- of the given type variable. If the type is already syntactically
-- free of the variable, then the same type is returned.
occurCheckExpand dflags tv ty
| MetaTv { mtv_info = SigTv } <- details
= go_sig_tv ty
| fast_check ty = return ty
| otherwise = go emptyVarEnv ty
where
details = tcTyVarDetails tv
impredicative = canUnifyWithPolyType dflags details
-- Check 'ty' is a tyvar, or can be expanded into one
go_sig_tv ty@(TyVarTy tv')
| fast_check (tyVarKind tv') = return ty
| otherwise = do { k' <- go emptyVarEnv (tyVarKind tv')
; return (mkTyVarTy (setTyVarKind tv' k')) }
go_sig_tv ty | Just ty' <- coreView ty = go_sig_tv ty'
go_sig_tv _ = OC_NonTyVar
-- True => fine
fast_check (LitTy {}) = True
fast_check (TyVarTy tv') = tv /= tv' && fast_check (tyVarKind tv')
fast_check (TyConApp tc tys) = all fast_check tys && (isTauTyCon tc || impredicative)
fast_check (ForAllTy (Anon a) r) = fast_check a && fast_check r
fast_check (AppTy fun arg) = fast_check fun && fast_check arg
fast_check (ForAllTy (Named tv' _) ty)
= impredicative
&& fast_check (tyVarKind tv')
&& (tv == tv' || fast_check ty)
fast_check (CastTy ty co) = fast_check ty && fast_check_co co
fast_check (CoercionTy co) = fast_check_co co
-- we really are only doing an occurs check here; no bother about
-- impredicativity in coercions, as they're inferred
fast_check_co co = not (tv `elemVarSet` tyCoVarsOfCo co)
go :: VarEnv TyVar -- carries mappings necessary because of kind expansion
-> Type -> OccCheckResult Type
go env (TyVarTy tv')
| tv == tv' = OC_Occurs
| Just tv'' <- lookupVarEnv env tv' = return (mkTyVarTy tv'')
| otherwise = do { k' <- go env (tyVarKind tv')
; return (mkTyVarTy $
setTyVarKind tv' k') }
go _ ty@(LitTy {}) = return ty
go env (AppTy ty1 ty2) = do { ty1' <- go env ty1
; ty2' <- go env ty2
; return (mkAppTy ty1' ty2') }
go env (ForAllTy (Anon ty1) ty2)
= do { ty1' <- go env ty1
; ty2' <- go env ty2
; return (mkFunTy ty1' ty2') }
go env ty@(ForAllTy (Named tv' vis) body_ty)
| not impredicative = OC_Forall
| tv == tv' = return ty
| otherwise = do { ki' <- go env ki
; let tv'' = setTyVarKind tv' ki'
env' = extendVarEnv env tv' tv''
; body' <- go env' body_ty
; return (ForAllTy (Named tv'' vis) body') }
where ki = tyVarKind tv'
-- For a type constructor application, first try expanding away the
-- offending variable from the arguments. If that doesn't work, next
-- see if the type constructor is a type synonym, and if so, expand
-- it and try again.
go env ty@(TyConApp tc tys)
= case do { tys <- mapM (go env) tys
; return (mkTyConApp tc tys) } of
OC_OK ty
| impredicative || isTauTyCon tc
-> return ty -- First try to eliminate the tyvar from the args
| otherwise
-> OC_Forall -- A type synonym with a forall on the RHS
bad | Just ty' <- coreView ty -> go env ty'
| otherwise -> bad
-- Failing that, try to expand a synonym
go env (CastTy ty co) = do { ty' <- go env ty
; co' <- go_co env co
; return (mkCastTy ty' co') }
go env (CoercionTy co) = do { co' <- go_co env co
; return (mkCoercionTy co') }
go_co env (Refl r ty) = do { ty' <- go env ty
; return (mkReflCo r ty') }
-- Note: Coercions do not contain type synonyms
go_co env (TyConAppCo r tc args) = do { args' <- mapM (go_co env) args
; return (mkTyConAppCo r tc args') }
go_co env (AppCo co arg) = do { co' <- go_co env co
; arg' <- go_co env arg
; return (mkAppCo co' arg') }
go_co env co@(ForAllCo tv' kind_co body_co)
| not impredicative = OC_Forall
| tv == tv' = return co
| otherwise = do { kind_co' <- go_co env kind_co
; let tv'' = setTyVarKind tv' $
pFst (coercionKind kind_co')
env' = extendVarEnv env tv' tv''
; body' <- go_co env' body_co
; return (ForAllCo tv'' kind_co' body') }
go_co env (CoVarCo c) = do { k' <- go env (varType c)
; return (mkCoVarCo (setVarType c k')) }
go_co env (AxiomInstCo ax ind args) = do { args' <- mapM (go_co env) args
; return (mkAxiomInstCo ax ind args') }
go_co env (UnivCo p r ty1 ty2) = do { p' <- go_prov env p
; ty1' <- go env ty1
; ty2' <- go env ty2
; return (mkUnivCo p' r ty1' ty2') }
go_co env (SymCo co) = do { co' <- go_co env co
; return (mkSymCo co') }
go_co env (TransCo co1 co2) = do { co1' <- go_co env co1
; co2' <- go_co env co2
; return (mkTransCo co1' co2') }
go_co env (NthCo n co) = do { co' <- go_co env co
; return (mkNthCo n co') }
go_co env (LRCo lr co) = do { co' <- go_co env co
; return (mkLRCo lr co') }
go_co env (InstCo co arg) = do { co' <- go_co env co
; arg' <- go_co env arg
; return (mkInstCo co' arg') }
go_co env (CoherenceCo co1 co2) = do { co1' <- go_co env co1
; co2' <- go_co env co2
; return (mkCoherenceCo co1' co2') }
go_co env (KindCo co) = do { co' <- go_co env co
; return (mkKindCo co') }
go_co env (SubCo co) = do { co' <- go_co env co
; return (mkSubCo co') }
go_co env (AxiomRuleCo ax cs) = do { cs' <- mapM (go_co env) cs
; return (mkAxiomRuleCo ax cs') }
go_prov _ UnsafeCoerceProv = return UnsafeCoerceProv
go_prov env (PhantomProv co) = PhantomProv <$> go_co env co
go_prov env (ProofIrrelProv co) = ProofIrrelProv <$> go_co env co
go_prov _ p@(PluginProv _) = return p
go_prov _ p@(HoleProv _) = return p
canUnifyWithPolyType :: DynFlags -> TcTyVarDetails -> Bool
canUnifyWithPolyType dflags details
= case details of
MetaTv { mtv_info = SigTv } -> False
MetaTv { mtv_info = TauTv } -> xopt LangExt.ImpredicativeTypes dflags
_other -> True
-- We can have non-meta tyvars in given constraints
{- Note [Expanding superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we expand superclasses, we use the following algorithm:
expand( so_far, pred ) returns the transitive superclasses of pred,
not including pred itself
1. If pred is not a class constraint, return empty set
Otherwise pred = C ts
2. If C is in so_far, return empty set (breaks loops)
3. Find the immediate superclasses constraints of (C ts)
4. For each such sc_pred, return (sc_pred : expand( so_far+C, D ss )
Notice that
* With normal Haskell-98 classes, the loop-detector will never bite,
so we'll get all the superclasses.
* Since there is only a finite number of distinct classes, expansion
must terminate.
* The loop breaking is a bit conservative. Notably, a tuple class
could contain many times without threatening termination:
(Eq a, (Ord a, Ix a))
And this is try of any class that we can statically guarantee
as non-recursive (in some sense). For now, we just make a special
case for tuples. Somthing better would be cool.
See also TcTyDecls.checkClassCycles.
************************************************************************
* *
\subsection{Predicate types}
* *
************************************************************************
Deconstructors and tests on predicate types
Note [Kind polymorphic type classes]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class C f where... -- C :: forall k. k -> Constraint
g :: forall (f::*). C f => f -> f
Here the (C f) in the signature is really (C * f), and we
don't want to complain that the * isn't a type variable!
-}
isTyVarClassPred :: PredType -> Bool
isTyVarClassPred ty = case getClassPredTys_maybe ty of
Just (_, tys) -> all isTyVarTy tys
_ -> False
-------------------------
checkValidClsArgs :: Bool -> Class -> [KindOrType] -> Bool
-- If the Bool is True (flexible contexts), return True (i.e. ok)
-- Otherwise, check that the type (not kind) args are all headed by a tyvar
-- E.g. (Eq a) accepted, (Eq (f a)) accepted, but (Eq Int) rejected
-- This function is here rather than in TcValidity because it is
-- called from TcSimplify, which itself is imported by TcValidity
checkValidClsArgs flexible_contexts cls kts
| flexible_contexts = True
| otherwise = all hasTyVarHead tys
where
tys = filterOutInvisibleTypes (classTyCon cls) kts
hasTyVarHead :: Type -> Bool
-- Returns true of (a t1 .. tn), where 'a' is a type variable
hasTyVarHead ty -- Haskell 98 allows predicates of form
| tcIsTyVarTy ty = True -- C (a ty1 .. tyn)
| otherwise -- where a is a type variable
= case tcSplitAppTy_maybe ty of
Just (ty, _) -> hasTyVarHead ty
Nothing -> False
evVarPred_maybe :: EvVar -> Maybe PredType
evVarPred_maybe v = if isPredTy ty then Just ty else Nothing
where ty = varType v
evVarPred :: EvVar -> PredType
evVarPred var
| debugIsOn
= case evVarPred_maybe var of
Just pred -> pred
Nothing -> pprPanic "tcEvVarPred" (ppr var <+> ppr (varType var))
| otherwise
= varType var
------------------
-- | When inferring types, should we quantify over a given predicate?
-- Generally true of classes; generally false of equality constraints.
-- Equality constraints that mention quantified type variables and
-- implicit variables complicate the story. See Notes
-- [Inheriting implicit parameters] and [Quantifying over equality constraints]
pickQuantifiablePreds
:: TyVarSet -- Quantifying over these
-> TcThetaType -- Proposed constraints to quantify
-> TcThetaType -- A subset that we can actually quantify
-- This function decides whether a particular constraint shoudl be
-- quantified over, given the type variables that are being quantified
pickQuantifiablePreds qtvs theta
= let flex_ctxt = True in -- Quantify over non-tyvar constraints, even without
-- -XFlexibleContexts: see Trac #10608, #10351
-- flex_ctxt <- xoptM Opt_FlexibleContexts
filter (pick_me flex_ctxt) theta
where
pick_me flex_ctxt pred
= case classifyPredType pred of
ClassPred cls tys
| isIPClass cls -> True -- See note [Inheriting implicit parameters]
| otherwise -> pick_cls_pred flex_ctxt cls tys
EqPred ReprEq ty1 ty2 -> pick_cls_pred flex_ctxt coercibleClass [ty1, ty2]
-- representational equality is like a class constraint
EqPred NomEq ty1 ty2 -> quant_fun ty1 || quant_fun ty2
IrredPred ty -> tyCoVarsOfType ty `intersectsVarSet` qtvs
pick_cls_pred flex_ctxt cls tys
= tyCoVarsOfTypes tys `intersectsVarSet` qtvs
&& (checkValidClsArgs flex_ctxt cls tys)
-- Only quantify over predicates that checkValidType
-- will pass! See Trac #10351.
-- See Note [Quantifying over equality constraints]
quant_fun ty
= case tcSplitTyConApp_maybe ty of
Just (tc, tys) | isTypeFamilyTyCon tc
-> tyCoVarsOfTypes tys `intersectsVarSet` qtvs
_ -> False
-- Superclasses
type PredWithSCs = (PredType, [PredType])
mkMinimalBySCs :: [PredType] -> [PredType]
-- Remove predicates that can be deduced from others by superclasses
-- Result is a subset of the input
mkMinimalBySCs ptys = go preds_with_scs []
where
preds_with_scs :: [PredWithSCs]
preds_with_scs = [ (pred, transSuperClasses pred)
| pred <- ptys ]
go :: [PredWithSCs] -- Work list
-> [PredWithSCs] -- Accumulating result
-> [PredType]
go [] min_preds = map fst min_preds
go (work_item@(p,_) : work_list) min_preds
| p `in_cloud` work_list || p `in_cloud` min_preds
= go work_list min_preds
| otherwise
= go work_list (work_item : min_preds)
in_cloud :: PredType -> [PredWithSCs] -> Bool
in_cloud p ps = or [ p `eqType` p' | (_, scs) <- ps, p' <- scs ]
transSuperClasses :: PredType -> [PredType]
-- (transSuperClasses p) returns (p's superclasses) not including p
-- Stop if you encounter the same class again
-- See Note [Expanding superclasses]
transSuperClasses p
= go emptyNameSet p
where
go :: NameSet -> PredType -> [PredType]
go rec_clss p
| ClassPred cls tys <- classifyPredType p
, let cls_nm = className cls
, not (cls_nm `elemNameSet` rec_clss)
, let rec_clss' | isCTupleClass cls = rec_clss
| otherwise = rec_clss `extendNameSet` cls_nm
= [ p' | sc <- immSuperClasses cls tys
, p' <- sc : go rec_clss' sc ]
| otherwise
= []
immSuperClasses :: Class -> [Type] -> [PredType]
immSuperClasses cls tys
= substTheta (zipTvSubst tyvars tys) sc_theta
where
(tyvars,sc_theta,_,_) = classBigSig cls
isImprovementPred :: PredType -> Bool
-- Either it's an equality, or has some functional dependency
isImprovementPred ty
= case classifyPredType ty of
EqPred NomEq t1 t2 -> not (t1 `tcEqType` t2)
EqPred ReprEq _ _ -> False
ClassPred cls _ -> classHasFds cls
IrredPred {} -> True -- Might have equalities after reduction?
{-
Note [Inheriting implicit parameters]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this:
f x = (x::Int) + ?y
where f is *not* a top-level binding.
From the RHS of f we'll get the constraint (?y::Int).
There are two types we might infer for f:
f :: Int -> Int
(so we get ?y from the context of f's definition), or
f :: (?y::Int) => Int -> Int
At first you might think the first was better, because then
?y behaves like a free variable of the definition, rather than
having to be passed at each call site. But of course, the WHOLE
IDEA is that ?y should be passed at each call site (that's what
dynamic binding means) so we'd better infer the second.
BOTTOM LINE: when *inferring types* you must quantify over implicit
parameters, *even if* they don't mention the bound type variables.
Reason: because implicit parameters, uniquely, have local instance
declarations. See pickQuantifiablePreds.
Note [Quantifying over equality constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Should we quantify over an equality constraint (s ~ t)? In general, we don't.
Doing so may simply postpone a type error from the function definition site to
its call site. (At worst, imagine (Int ~ Bool)).
However, consider this
forall a. (F [a] ~ Int) => blah
Should we quantify over the (F [a] ~ Int). Perhaps yes, because at the call
site we will know 'a', and perhaps we have instance F [Bool] = Int.
So we *do* quantify over a type-family equality where the arguments mention
the quantified variables.
************************************************************************
* *
\subsection{Predicates}
* *
************************************************************************
-}
isSigmaTy :: TcType -> Bool
-- isSigmaTy returns true of any qualified type. It doesn't
-- *necessarily* have any foralls. E.g
-- f :: (?x::Int) => Int -> Int
isSigmaTy ty | Just ty' <- coreView ty = isSigmaTy ty'
isSigmaTy (ForAllTy (Named {}) _) = True
isSigmaTy (ForAllTy (Anon a) _) = isPredTy a
isSigmaTy _ = False
isRhoTy :: TcType -> Bool -- True of TcRhoTypes; see Note [TcRhoType]
isRhoTy ty | Just ty' <- coreView ty = isRhoTy ty'
isRhoTy (ForAllTy (Named {}) _) = False
isRhoTy (ForAllTy (Anon a) r) = not (isPredTy a) && isRhoTy r
isRhoTy _ = True
-- | Like 'isRhoTy', but also says 'True' for 'Infer' types
isRhoExpTy :: ExpType -> Bool
isRhoExpTy (Check ty) = isRhoTy ty
isRhoExpTy (Infer {}) = True
isOverloadedTy :: Type -> Bool
-- Yes for a type of a function that might require evidence-passing
-- Used only by bindLocalMethods
isOverloadedTy ty | Just ty' <- coreView ty = isOverloadedTy ty'
isOverloadedTy (ForAllTy (Named {}) ty) = isOverloadedTy ty
isOverloadedTy (ForAllTy (Anon a) _) = isPredTy a
isOverloadedTy _ = False
isFloatTy, isDoubleTy, isIntegerTy, isIntTy, isWordTy, isBoolTy,
isUnitTy, isCharTy, isAnyTy :: Type -> Bool
isFloatTy = is_tc floatTyConKey
isDoubleTy = is_tc doubleTyConKey
isIntegerTy = is_tc integerTyConKey
isIntTy = is_tc intTyConKey
isWordTy = is_tc wordTyConKey
isBoolTy = is_tc boolTyConKey
isUnitTy = is_tc unitTyConKey
isCharTy = is_tc charTyConKey
isAnyTy = is_tc anyTyConKey
-- | Does a type represent a floating-point number?
isFloatingTy :: Type -> Bool
isFloatingTy ty = isFloatTy ty || isDoubleTy ty
-- | Is a type 'String'?
isStringTy :: Type -> Bool
isStringTy ty
= case tcSplitTyConApp_maybe ty of
Just (tc, [arg_ty]) -> tc == listTyCon && isCharTy arg_ty
_ -> False
is_tc :: Unique -> Type -> Bool
-- Newtypes are opaque to this
is_tc uniq ty = case tcSplitTyConApp_maybe ty of
Just (tc, _) -> uniq == getUnique tc
Nothing -> False
-- | Does the given tyvar appear in the given type outside of any
-- non-newtypes? Assume we're looking for @a@. Says "yes" for
-- @a@, @N a@, @b a@, @a b@, @b (N a)@. Says "no" for
-- @[a]@, @Maybe a@, @T a@, where @N@ is a newtype and @T@ is a datatype.
isTyVarExposed :: TcTyVar -> TcType -> Bool
isTyVarExposed tv (TyVarTy tv') = tv == tv'
isTyVarExposed tv (TyConApp tc tys)
| isNewTyCon tc = any (isTyVarExposed tv) tys
| otherwise = False
isTyVarExposed _ (LitTy {}) = False
isTyVarExposed tv (AppTy fun arg) = isTyVarExposed tv fun
|| isTyVarExposed tv arg
isTyVarExposed _ (ForAllTy {}) = False
isTyVarExposed tv (CastTy ty _) = isTyVarExposed tv ty
isTyVarExposed _ (CoercionTy {}) = False
-- | Does the given tyvar appear under a type generative w.r.t.
-- representational equality? See Note [Occurs check error] in
-- TcCanonical for the motivation for this function.
isTyVarUnderDatatype :: TcTyVar -> TcType -> Bool
isTyVarUnderDatatype tv = go False
where
go under_dt ty | Just ty' <- coreView ty = go under_dt ty'
go under_dt (TyVarTy tv') = under_dt && (tv == tv')
go under_dt (TyConApp tc tys) = let under_dt' = under_dt ||
isGenerativeTyCon tc
Representational
in any (go under_dt') tys
go _ (LitTy {}) = False
go _ (ForAllTy (Anon arg) res) = go True arg || go True res
go under_dt (AppTy fun arg) = go under_dt fun || go under_dt arg
go under_dt (ForAllTy (Named tv' _) inner_ty)
| tv' == tv = False
| otherwise = go under_dt inner_ty
go under_dt (CastTy ty _) = go under_dt ty
go _ (CoercionTy {}) = False
isRigidTy :: TcType -> Bool
isRigidTy ty
| Just (tc,_) <- tcSplitTyConApp_maybe ty = isGenerativeTyCon tc Nominal
| Just {} <- tcSplitAppTy_maybe ty = True
| isForAllTy ty = True
| otherwise = False
isRigidEqPred :: TcLevel -> PredTree -> Bool
-- ^ True of all Nominal equalities that are solidly insoluble
-- This means all equalities *except*
-- * Meta-tv non-SigTv on LHS
-- * Meta-tv SigTv on LHS, tyvar on right
isRigidEqPred tc_lvl (EqPred NomEq ty1 _)
| Just tv1 <- tcGetTyVar_maybe ty1
= ASSERT2( isTcTyVar tv1, ppr tv1 )
not (isMetaTyVar tv1) || isTouchableMetaTyVar tc_lvl tv1
| otherwise -- LHS is not a tyvar
= True
isRigidEqPred _ _ = False -- Not an equality
{-
************************************************************************
* *
\subsection{Transformation of Types to TcTypes}
* *
************************************************************************
-}
toTcType :: Type -> TcType
-- The constraint solver expects EvVars to have TcType, in which the
-- free type variables are TcTyVars. So we convert from Type to TcType here
-- A bit tiresome; but one day I expect the two types to be entirely separate
-- in which case we'll definitely need to do this
toTcType = runIdentity . to_tc_type emptyVarSet
toTcTypeBag :: Bag EvVar -> Bag EvVar -- All TyVars are transformed to TcTyVars
toTcTypeBag evvars = mapBag (\tv -> setTyVarKind tv (toTcType (tyVarKind tv))) evvars
to_tc_mapper :: TyCoMapper VarSet Identity
to_tc_mapper
= TyCoMapper { tcm_smart = False -- more efficient not to use smart ctors
, tcm_tyvar = tyvar
, tcm_covar = covar
, tcm_hole = hole
, tcm_tybinder = tybinder }
where
tyvar :: VarSet -> TyVar -> Identity Type
tyvar ftvs tv
| Just var <- lookupVarSet ftvs tv = return $ TyVarTy var
| isTcTyVar tv = TyVarTy <$> updateTyVarKindM (to_tc_type ftvs) tv
| otherwise
= do { kind' <- to_tc_type ftvs (tyVarKind tv)
; return $ TyVarTy $ mkTcTyVar (tyVarName tv) kind' vanillaSkolemTv }
covar :: VarSet -> CoVar -> Identity Coercion
covar ftvs cv
| Just var <- lookupVarSet ftvs cv = return $ CoVarCo var
| otherwise = CoVarCo <$> updateVarTypeM (to_tc_type ftvs) cv
hole :: VarSet -> CoercionHole -> Role -> Type -> Type
-> Identity Coercion
hole ftvs h r t1 t2 = mkHoleCo h r <$> to_tc_type ftvs t1
<*> to_tc_type ftvs t2
tybinder :: VarSet -> TyVar -> VisibilityFlag -> Identity (VarSet, TyVar)
tybinder ftvs tv _vis = do { kind' <- to_tc_type ftvs (tyVarKind tv)
; let tv' = mkTcTyVar (tyVarName tv) kind'
vanillaSkolemTv
; return (ftvs `extendVarSet` tv', tv') }
to_tc_type :: VarSet -> Type -> Identity TcType
to_tc_type = mapType to_tc_mapper
{-
************************************************************************
* *
\subsection{Misc}
* *
************************************************************************
Note [Visible type application]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC implements a generalisation of the algorithm described in the
"Visible Type Application" paper (available from
http://www.cis.upenn.edu/~sweirich/publications.html). A key part
of that algorithm is to distinguish user-specified variables from inferred
variables. For example, the following should typecheck:
f :: forall a b. a -> b -> b
f = const id
g = const id
x = f @Int @Bool 5 False
y = g 5 @Bool False
The idea is that we wish to allow visible type application when we are
instantiating a specified, fixed variable. In practice, specified, fixed
variables are either written in a type signature (or
annotation), OR are imported from another module. (We could do better here,
for example by doing SCC analysis on parts of a module and considering any
type from outside one's SCC to be fully specified, but this is very confusing to
users. The simple rule above is much more straightforward and predictable.)
So, both of f's quantified variables are specified and may be instantiated.
But g has no type signature, so only id's variable is specified (because id
is imported). We write the type of g as forall {a}. a -> forall b. b -> b.
Note that the a is in braces, meaning it cannot be instantiated with
visible type application.
Tracking specified vs. inferred variables is done conveniently by a field
in TyBinder.
-}
deNoteType :: Type -> Type
-- Remove all *outermost* type synonyms and other notes
deNoteType ty | Just ty' <- coreView ty = deNoteType ty'
deNoteType ty = ty
{-
Find the free tycons and classes of a type. This is used in the front
end of the compiler.
-}
{-
************************************************************************
* *
\subsection[TysWiredIn-ext-type]{External types}
* *
************************************************************************
The compiler's foreign function interface supports the passing of a
restricted set of types as arguments and results (the restricting factor
being the )
-}
tcSplitIOType_maybe :: Type -> Maybe (TyCon, Type)
-- (tcSplitIOType_maybe t) returns Just (IO,t',co)
-- if co : t ~ IO t'
-- returns Nothing otherwise
tcSplitIOType_maybe ty
= case tcSplitTyConApp_maybe ty of
Just (io_tycon, [io_res_ty])
| io_tycon `hasKey` ioTyConKey ->
Just (io_tycon, io_res_ty)
_ ->
Nothing
isFFITy :: Type -> Bool
-- True for any TyCon that can possibly be an arg or result of an FFI call
isFFITy ty = isValid (checkRepTyCon legalFFITyCon ty)
isFFIArgumentTy :: DynFlags -> Safety -> Type -> Validity
-- Checks for valid argument type for a 'foreign import'
isFFIArgumentTy dflags safety ty
= checkRepTyCon (legalOutgoingTyCon dflags safety) ty
isFFIExternalTy :: Type -> Validity
-- Types that are allowed as arguments of a 'foreign export'
isFFIExternalTy ty = checkRepTyCon legalFEArgTyCon ty
isFFIImportResultTy :: DynFlags -> Type -> Validity
isFFIImportResultTy dflags ty
= checkRepTyCon (legalFIResultTyCon dflags) ty
isFFIExportResultTy :: Type -> Validity
isFFIExportResultTy ty = checkRepTyCon legalFEResultTyCon ty
isFFIDynTy :: Type -> Type -> Validity
-- The type in a foreign import dynamic must be Ptr, FunPtr, or a newtype of
-- either, and the wrapped function type must be equal to the given type.
-- We assume that all types have been run through normaliseFfiType, so we don't
-- need to worry about expanding newtypes here.
isFFIDynTy expected ty
-- Note [Foreign import dynamic]
-- In the example below, expected would be 'CInt -> IO ()', while ty would
-- be 'FunPtr (CDouble -> IO ())'.
| Just (tc, [ty']) <- splitTyConApp_maybe ty
, tyConUnique tc `elem` [ptrTyConKey, funPtrTyConKey]
, eqType ty' expected
= IsValid
| otherwise
= NotValid (vcat [ text "Expected: Ptr/FunPtr" <+> pprParendType expected <> comma
, text " Actual:" <+> ppr ty ])
isFFILabelTy :: Type -> Validity
-- The type of a foreign label must be Ptr, FunPtr, or a newtype of either.
isFFILabelTy ty = checkRepTyCon ok ty
where
ok tc | tc `hasKey` funPtrTyConKey || tc `hasKey` ptrTyConKey
= IsValid
| otherwise
= NotValid (text "A foreign-imported address (via &foo) must have type (Ptr a) or (FunPtr a)")
isFFIPrimArgumentTy :: DynFlags -> Type -> Validity
-- Checks for valid argument type for a 'foreign import prim'
-- Currently they must all be simple unlifted types, or the well-known type
-- Any, which can be used to pass the address to a Haskell object on the heap to
-- the foreign function.
isFFIPrimArgumentTy dflags ty
| isAnyTy ty = IsValid
| otherwise = checkRepTyCon (legalFIPrimArgTyCon dflags) ty
isFFIPrimResultTy :: DynFlags -> Type -> Validity
-- Checks for valid result type for a 'foreign import prim'
-- Currently it must be an unlifted type, including unboxed tuples,
-- or the well-known type Any.
isFFIPrimResultTy dflags ty
| isAnyTy ty = IsValid
| otherwise = checkRepTyCon (legalFIPrimResultTyCon dflags) ty
isFunPtrTy :: Type -> Bool
isFunPtrTy ty
| Just (tc, [_]) <- splitTyConApp_maybe ty
= tc `hasKey` funPtrTyConKey
| otherwise
= False
-- normaliseFfiType gets run before checkRepTyCon, so we don't
-- need to worry about looking through newtypes or type functions
-- here; that's already been taken care of.
checkRepTyCon :: (TyCon -> Validity) -> Type -> Validity
checkRepTyCon check_tc ty
= case splitTyConApp_maybe ty of
Just (tc, tys)
| isNewTyCon tc -> NotValid (hang msg 2 (mk_nt_reason tc tys $$ nt_fix))
| otherwise -> case check_tc tc of
IsValid -> IsValid
NotValid extra -> NotValid (msg $$ extra)
Nothing -> NotValid (quotes (ppr ty) <+> text "is not a data type")
where
msg = quotes (ppr ty) <+> text "cannot be marshalled in a foreign call"
mk_nt_reason tc tys
| null tys = text "because its data constructor is not in scope"
| otherwise = text "because the data constructor for"
<+> quotes (ppr tc) <+> text "is not in scope"
nt_fix = text "Possible fix: import the data constructor to bring it into scope"
{-
Note [Foreign import dynamic]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A dynamic stub must be of the form 'FunPtr ft -> ft' where ft is any foreign
type. Similarly, a wrapper stub must be of the form 'ft -> IO (FunPtr ft)'.
We use isFFIDynTy to check whether a signature is well-formed. For example,
given a (illegal) declaration like:
foreign import ccall "dynamic"
foo :: FunPtr (CDouble -> IO ()) -> CInt -> IO ()
isFFIDynTy will compare the 'FunPtr' type 'CDouble -> IO ()' with the curried
result type 'CInt -> IO ()', and return False, as they are not equal.
----------------------------------------------
These chaps do the work; they are not exported
----------------------------------------------
-}
legalFEArgTyCon :: TyCon -> Validity
legalFEArgTyCon tc
-- It's illegal to make foreign exports that take unboxed
-- arguments. The RTS API currently can't invoke such things. --SDM 7/2000
= boxedMarshalableTyCon tc
legalFIResultTyCon :: DynFlags -> TyCon -> Validity
legalFIResultTyCon dflags tc
| tc == unitTyCon = IsValid
| otherwise = marshalableTyCon dflags tc
legalFEResultTyCon :: TyCon -> Validity
legalFEResultTyCon tc
| tc == unitTyCon = IsValid
| otherwise = boxedMarshalableTyCon tc
legalOutgoingTyCon :: DynFlags -> Safety -> TyCon -> Validity
-- Checks validity of types going from Haskell -> external world
legalOutgoingTyCon dflags _ tc
= marshalableTyCon dflags tc
legalFFITyCon :: TyCon -> Validity
-- True for any TyCon that can possibly be an arg or result of an FFI call
legalFFITyCon tc
| isUnliftedTyCon tc = IsValid
| tc == unitTyCon = IsValid
| otherwise = boxedMarshalableTyCon tc
marshalableTyCon :: DynFlags -> TyCon -> Validity
marshalableTyCon dflags tc
| isUnliftedTyCon tc
, not (isUnboxedTupleTyCon tc)
, case tyConPrimRep tc of -- Note [Marshalling VoidRep]
VoidRep -> False
_ -> True
= validIfUnliftedFFITypes dflags
| otherwise
= boxedMarshalableTyCon tc
boxedMarshalableTyCon :: TyCon -> Validity
boxedMarshalableTyCon tc
| getUnique tc `elem` [ intTyConKey, int8TyConKey, int16TyConKey
, int32TyConKey, int64TyConKey
, wordTyConKey, word8TyConKey, word16TyConKey
, word32TyConKey, word64TyConKey
, floatTyConKey, doubleTyConKey
, ptrTyConKey, funPtrTyConKey
, charTyConKey
, stablePtrTyConKey
, boolTyConKey
]
= IsValid
| otherwise = NotValid empty
legalFIPrimArgTyCon :: DynFlags -> TyCon -> Validity
-- Check args of 'foreign import prim', only allow simple unlifted types.
-- Strictly speaking it is unnecessary to ban unboxed tuples here since
-- currently they're of the wrong kind to use in function args anyway.
legalFIPrimArgTyCon dflags tc
| isUnliftedTyCon tc
, not (isUnboxedTupleTyCon tc)
= validIfUnliftedFFITypes dflags
| otherwise
= NotValid unlifted_only
legalFIPrimResultTyCon :: DynFlags -> TyCon -> Validity
-- Check result type of 'foreign import prim'. Allow simple unlifted
-- types and also unboxed tuple result types '... -> (# , , #)'
legalFIPrimResultTyCon dflags tc
| isUnliftedTyCon tc
, (isUnboxedTupleTyCon tc
|| case tyConPrimRep tc of -- Note [Marshalling VoidRep]
VoidRep -> False
_ -> True)
= validIfUnliftedFFITypes dflags
| otherwise
= NotValid unlifted_only
unlifted_only :: MsgDoc
unlifted_only = text "foreign import prim only accepts simple unlifted types"
validIfUnliftedFFITypes :: DynFlags -> Validity
validIfUnliftedFFITypes dflags
| xopt LangExt.UnliftedFFITypes dflags = IsValid
| otherwise = NotValid (text "To marshal unlifted types, use UnliftedFFITypes")
{-
Note [Marshalling VoidRep]
~~~~~~~~~~~~~~~~~~~~~~~~~~
We don't treat State# (whose PrimRep is VoidRep) as marshalable.
In turn that means you can't write
foreign import foo :: Int -> State# RealWorld
Reason: the back end falls over with panic "primRepHint:VoidRep";
and there is no compelling reason to permit it
-}
{-
************************************************************************
* *
The "Paterson size" of a type
* *
************************************************************************
-}
{-
Note [Paterson conditions on PredTypes]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We are considering whether *class* constraints terminate
(see Note [Paterson conditions]). Precisely, the Paterson conditions
would have us check that "the constraint has fewer constructors and variables
(taken together and counting repetitions) than the head.".
However, we can be a bit more refined by looking at which kind of constraint
this actually is. There are two main tricks:
1. It seems like it should be OK not to count the tuple type constructor
for a PredType like (Show a, Eq a) :: Constraint, since we don't
count the "implicit" tuple in the ThetaType itself.
In fact, the Paterson test just checks *each component* of the top level
ThetaType against the size bound, one at a time. By analogy, it should be
OK to return the size of the *largest* tuple component as the size of the
whole tuple.
2. Once we get into an implicit parameter or equality we
can't get back to a class constraint, so it's safe
to say "size 0". See Trac #4200.
NB: we don't want to detect PredTypes in sizeType (and then call
sizePred on them), or we might get an infinite loop if that PredType
is irreducible. See Trac #5581.
-}
type TypeSize = IntWithInf
sizeType :: Type -> TypeSize
-- Size of a type: the number of variables and constructors
-- Ignore kinds altogether
sizeType = go
where
go ty | Just exp_ty <- coreView ty = go exp_ty
go (TyVarTy {}) = 1
go (TyConApp tc tys)
| isTypeFamilyTyCon tc = infinity -- Type-family applications can
-- expand to any arbitrary size
| otherwise = sizeTypes (filterOutInvisibleTypes tc tys) + 1
go (LitTy {}) = 1
go (ForAllTy (Anon arg) res) = go arg + go res + 1
go (AppTy fun arg) = go fun + go arg
go (ForAllTy (Named tv vis) ty)
| Visible <- vis = go (tyVarKind tv) + go ty + 1
| otherwise = go ty + 1
go (CastTy ty _) = go ty
go (CoercionTy {}) = 0
sizeTypes :: [Type] -> TypeSize
sizeTypes tys = sum (map sizeType tys)
| oldmanmike/ghc | compiler/typecheck/TcType.hs | bsd-3-clause | 92,459 | 0 | 16 | 25,802 | 16,765 | 8,704 | 8,061 | -1 | -1 |
--------------------------------------------------------------------------------
-- |
-- Module : Geometry.Space
-- Copyright : (c) Artem M. Chirkin 2015
-- License : BSD3
--
-- Maintainer : Artem M. Chirkin <[email protected]>
-- Stability : Experimental
--
-- The module provides mathematical operations on vector types
--
--------------------------------------------------------------------------------
module Geometry.Space (module X) where
import Geometry.Space.Types as X
import Geometry.Space.Tensor as X
import Geometry.Space.Approximate as X
| achirkin/fgeom | src/Geometry/Space.hs | bsd-3-clause | 590 | 0 | 4 | 96 | 48 | 38 | 10 | 4 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module Cloud.AWS.EC2.Types.VPC
( Attachment(..)
, AttachmentState(..)
, CreateVpnGatewayType(..)
, CustomerGateway(..)
, CustomerGatewayState(..)
, DhcpConfiguration(..)
, DhcpOptions(..)
, DhcpValue(..)
, InternetGateway(..)
, InternetGatewayAttachment(..)
, InternetGatewayAttachmentState(..)
, Vpc(..)
, VpcState(..)
, VpnConnection(..)
, VpnConnectionOptionsRequest(..)
, VpnConnectionState(..)
, VpnGateway(..)
, VpnGatewayState(..)
, VpnStaticRoute(..)
, VpnStaticRouteSource(..)
, VpnStaticRouteState(..)
, VpnTunnelTelemetry(..)
) where
import Cloud.AWS.EC2.Types.Common (ResourceTag)
import Cloud.AWS.Lib.FromText (deriveFromText)
import Cloud.AWS.Lib.ToText (deriveToText)
import Data.IP (AddrRange, IPv4)
import Data.Text (Text)
import Data.Time (UTCTime)
data Attachment = Attachment
{ attachmentVpcId :: Text
, attachmentState :: AttachmentState
}
deriving (Show, Read, Eq)
data AttachmentState
= AttachmentStateAttaching
| AttachmentStateAttached
| AttachmentStateDetaching
| AttachmentStateDetached
deriving (Show, Read, Eq)
data CreateVpnGatewayType = CreateVpnGatewayTypeIpsec1
deriveToText "CreateVpnGatewayType" ["ipsec.1"]
data CustomerGateway = CustomerGateway
{ customerGatewayId :: Text
, customerGatewayState :: CustomerGatewayState
, customerGatewayType :: Text
, customerGatewayIpAddress :: IPv4
, customerGatewayBgpAsn :: Int
, customerGatewayTagSet :: [ResourceTag]
}
deriving (Show, Read, Eq)
data CustomerGatewayState
= CustomerGatewayStatePending
| CustomerGatewayStateAvailable
| CustomerGatewayStateDeleting
| CustomerGatewayStateDeleted
deriving (Show, Read, Eq)
data DhcpOptions = DhcpOptions
{ dhcpOptionsId :: Text
, dhcpOptionsDhcpConfigurationSet :: [DhcpConfiguration]
, dhcpOptionsTagSet :: [ResourceTag]
}
deriving (Show, Read, Eq)
data DhcpConfiguration = DhcpConfiguration
{ dhcpConfigurationKey :: Text
, dhcpConfigurationDhcpValueSet :: [DhcpValue]
}
deriving (Show, Read, Eq)
data DhcpValue = DhcpValue
{ dhcpValueValue :: Text
}
deriving (Show, Read, Eq)
data InternetGateway = InternetGateway
{ internetGatewayInternetGatewayId :: Text
, internetGatewayAttachmentSet :: [InternetGatewayAttachment]
, internetGatewayTagSet :: [ResourceTag]
}
deriving (Show, Read, Eq)
data InternetGatewayAttachment = InternetGatewayAttachment
{ internetGatewayAttachmentVpcId :: Text
, internetGatewayAttachmentState :: InternetGatewayAttachmentState
}
deriving (Show, Read, Eq)
data InternetGatewayAttachmentState
= InternetGatewayAttachmentStateAttaching
| InternetGatewayAttachmentStateAttached
| InternetGatewayAttachmentStateDetaching
| InternetGatewayAttachmentStateDetached
| InternetGatewayAttachmentStateAvailable
deriving (Show, Read, Eq)
data Vpc = Vpc
{ vpcId :: Text
, vpcState :: VpcState
, vpcCidrBlock :: AddrRange IPv4
, vpcDhcpOptionsId :: Text
, vpcTagSet :: [ResourceTag]
, vpcInstanceTenancy :: Text
, vpcIsDefault :: Maybe Text
}
deriving (Show, Read, Eq)
data VpcState
= VpcStatePending
| VpcStateAvailable
deriving (Show, Read, Eq)
data VpnConnection = VpnConnection
{ vpnConnectionId :: Text
, vpnConnectionState :: VpnConnectionState
, vpnConnectionCustomerGatewayConfiguration :: Maybe Text
, vpnConnectionType :: Maybe Text
, vpnConnectionCustomerGatewayId :: Text
, vpnConnectionVpnGatewayId :: Text
, vpnConnectionTagSet :: [ResourceTag]
, vpnConnectionVgwTelemetry :: [VpnTunnelTelemetry]
, vpnConnectionOptions :: Maybe VpnConnectionOptionsRequest
, vpnConnectionRoutes :: [VpnStaticRoute]
}
deriving (Show, Read, Eq)
data VpnConnectionOptionsRequest = VpnConnectionOptionsRequest
{ vpnConnectionOptionsRequestStaticRoutesOnly :: Bool
}
deriving (Show, Read, Eq)
data VpnConnectionState
= VpnConnectionStatePending
| VpnConnectionStateAvailable
| VpnConnectionStateDeleting
| VpnConnectionStateDeleted
deriving (Show, Read, Eq)
data VpnGateway = VpnGateway
{ vpnGatewayId :: Text
, vpnGatewayState :: VpnGatewayState
, vpnGatewayType :: Text
, vpnGatewayAvailabilityZone :: Maybe Text
, vpnGatewayAttachments :: [Attachment]
, vpnGatewayTagSet :: [ResourceTag]
}
deriving (Show, Read, Eq)
data VpnGatewayState
= VpnGatewayStatePending
| VpnGatewayStateAvailable
| VpnGatewayStateDeleting
| VpnGatewayStateDeleted
deriving (Show, Read, Eq)
data VpnStaticRoute = VpnStaticRoute
{ vpnStaticRouteDestinationCidrBlock :: Text
, vpnStaticRouteSource :: VpnStaticRouteSource
, vpnStaticRouteState :: VpnStaticRouteState
}
deriving (Show, Read, Eq)
data VpnStaticRouteSource = VpnStaticRouteSourceStatic
deriving (Show, Read, Eq)
data VpnStaticRouteState
= VpnStaticRouteStatePending
| VpnStaticRouteStateAvailable
| VpnStaticRouteStateDeleting
| VpnStaticRouteStateDeleted
deriving (Show, Read, Eq)
data VpnTunnelTelemetry = VpnTunnelTelemetry
{ vpnTunnelTelemetryOutsideIpAddress :: IPv4
, vpnTunnelTelemetryStatus :: VpnTunnelTelemetryStatus
, vpnTunnelTelemetryLastStatusChange :: UTCTime
, vpnTunnelTelemetryStatusMessage :: Maybe Text
, vpnTunnelTelemetryAcceptRouteCount :: Int
}
deriving (Show, Read, Eq)
data VpnTunnelTelemetryStatus
= VpnTunnelTelemetryStatusUp
| VpnTunnelTelemetryStatusDown
deriving (Show, Read, Eq)
deriveFromText "AttachmentState"
["attaching", "attached", "detaching", "detached"]
deriveFromText "CustomerGatewayState"
["pending", "available", "deleting", "deleted"]
deriveFromText "InternetGatewayAttachmentState"
["attaching", "attached", "detaching", "detached", "available"]
deriveFromText "VpcState" ["pending", "available"]
deriveFromText "VpnConnectionState"
["pending", "available", "deleting", "deleted"]
deriveFromText "VpnGatewayState"
["pending", "available", "deleting", "deleted"]
deriveFromText "VpnStaticRouteSource" ["static"]
deriveFromText "VpnStaticRouteState"
["pending", "available", "deleting", "deleted"]
deriveFromText "VpnTunnelTelemetryStatus" ["UP", "DOWN"]
| worksap-ate/aws-sdk | Cloud/AWS/EC2/Types/VPC.hs | bsd-3-clause | 6,366 | 0 | 9 | 1,127 | 1,352 | 814 | 538 | 171 | 0 |
module Language.DevSurf
( module Language.DevSurf.STL
, module Language.DevSurf.SVG
, module Language.DevSurf.Types
) where
import Language.DevSurf.STL
import Language.DevSurf.SVG
import Language.DevSurf.Types
| tomahawkins/devsurf | Language/DevSurf.hs | bsd-3-clause | 220 | 0 | 5 | 29 | 47 | 32 | 15 | 7 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : Text.Luthor.Handler
-- Copyright : (c) Edward Kmett 2010,
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- An 'Handler' describe actions that must be taken in order to accept the
-- current state and produce output.
-----------------------------------------------------------------------------
module Text.Luthor.Handler
( Handler(..)
, StateNum
) where
import Data.CharSet (CharSet)
import Text.Luthor.Bifunctor
type StateNum = Int
data Handler s -- ^ state label
c -- ^ code type
= Handler
{ handlerPriority :: Int -- ^ lower priorities resolve first
, handlerPre :: Maybe CharSet -- ^ left-hand context
, handlerPost :: Post s c -- ^ right-hand context
, handlerAction :: Maybe c -- ^ what to do
} deriving (Show)
instance Functor Handler where
fmap f (Handler pri pre post mc) =
Handler pri pre (first f post) (fmap f mc)
instance Bifunctor Handler where
bimap f g (Handler pri pre post mc) =
Handler pri pre (bimap f g post) (fmap g mc)
| ekmett/luthor | Text/Luthor/Handler.hs | bsd-3-clause | 1,243 | 0 | 9 | 313 | 226 | 132 | 94 | 20 | 0 |
{-# LANGUAGE DeriveDataTypeable
#-}
{-| The 'UUID' datatype.
-}
module Data.UUID
( UUID()
, asWord64s
, asWord32s
) where
import Data.Word
import Data.Char
import Data.Binary
import Data.Binary.Put
import Data.Binary.Get
import Data.Bits
import qualified Data.ByteString.Lazy
import Data.Digest.Murmur32
import Data.Digest.Murmur64
import Data.String
import Data.Typeable
import Foreign.C
import Foreign.ForeignPtr
import Foreign
import Control.Monad
import Control.Applicative
import Numeric
import Text.ParserCombinators.ReadPrec (lift)
import Text.ParserCombinators.ReadP
import Text.Read hiding (pfail)
import Data.List
import Text.Printf
{-| A type for Uniform Unique Identifiers. The 'Num' instance allows 'UUID's
to be specified with @0@, @1@, &c. -- testing for the null 'UUID' is
easier that way. The 'Storable' instance is compatible with most (all?)
systems' native representation of 'UUID's.
-}
data UUID = UUID
!Word8 !Word8 !Word8 !Word8 !Word8 !Word8 !Word8 !Word8
!Word8 !Word8 !Word8 !Word8 !Word8 !Word8 !Word8 !Word8
deriving (Eq, Ord, Typeable)
instance Show UUID where
show (UUID x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF)
= printf formatUUID x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF
where
formatUUID = intercalate "-" $ map b [ 2, 1, 1, 1, 3 ]
b = concat . (`replicate` "%02.2x%02.2x")
instance Read UUID where
readPrec = lift $ do
skipSpaces
[x0,x1,x2,x3] <- count 4 byte
char '-'
[x4,x5] <- count 2 byte
char '-'
[x6,x7] <- count 2 byte
char '-'
[x8,x9] <- count 2 byte
char '-'
[xA,xB,xC,xD,xE,xF] <- count 6 byte
return $ UUID x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF
where
byte = do
s <- sequence $ replicate 2 $ satisfy isHexDigit
case readHex s of
[(b, _)] -> return b
_ -> pfail
instance IsString UUID where
fromString = read
instance Storable UUID where
sizeOf _ = 16
alignment _ = 4
peek p = do
bytes <- peekArray 16 $ castPtr p
return $ fromList bytes
poke p uuid = pokeArray (castPtr p) $ listOfBytes uuid
instance Bounded UUID where
minBound = UUID 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
maxBound = UUID 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff
0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff
instance Binary UUID where
put = mapM_ putWord8 . listOfBytes
get = fromList <$> sequence (replicate 16 getWord8)
instance Hashable32 UUID where
hash32Add = hash32Add . asWord32s
instance Hashable64 UUID where
hash64Add = hash64Add . asWord64s
listOfBytes (UUID x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF)
= [ x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, xA, xB, xC, xD, xE, xF ]
fromList [ x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, xA, xB, xC, xD, xE, xF ]
= UUID x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF
fromList _ = minBound
asWord64s :: UUID -> (Word64, Word64)
asWord64s uuid = (decode front, decode back)
where
(front, back) = Data.ByteString.Lazy.splitAt 8 $ encode uuid
asWord32s :: UUID -> (Word32, Word32, Word32, Word32)
asWord32s uuid = (decode front', decode front'', decode back', decode back'')
where
(front, back) = Data.ByteString.Lazy.splitAt 8 $ encode uuid
(front', front'') = Data.ByteString.Lazy.splitAt 4 front
(back', back'') = Data.ByteString.Lazy.splitAt 4 back
| solidsnack/system-uuid | Data/UUID.hs | bsd-3-clause | 3,999 | 0 | 14 | 1,371 | 1,239 | 657 | 582 | 123 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module TestsXLSX
where
import Codec.Xlsx
import Codec.Xlsx.Formatted
import qualified Data.Text as T
import Data.Map (Map)
-- import qualified Data.Map as DM
import Data.Either.Extra (fromRight)
import WriteXLSX.DataframeToSheet
import qualified Data.ByteString.Lazy as L
-- import Data.ByteString.Lazy.Internal (packChars)
df = "{\"include\":[true,true,true,true,true,true],\"Petal.Width\":[0.22342,null,1.5,1.5,1.3,1.5],\"Species\":[\"setosa\",\"versicolor\",\"versicolor\",\"versicolor\",\"versicolor\",\"versicolor\"],\"Date\":[\"2017-01-14\",\"2017-01-15\",\"2017-01-16\",\"2017-01-17\",\"2017-01-18\",\"2017-01-19\"]}"
comments = "{\"include\":[\"HELLO\",null,null,null,null,null],\"Petal.Width\":[null,null,null,null,null,null],\"Species\":[null,null,null,null,null,null],\"Date\":[null,null,null,null,null,null]}"
-- ddf = packChars "{\"Strain\":[\"GBS-Ia\",\"GBS-Ia\",\"GBS-Ia\",\"GBS-Ia\",\"GBS-Ia\",\"GBS-Ia\",\"GBS-Ia\",\"GBS-Ia\"],\"Studie\":[\"V98_06\",\"V98_06\",\"V98_06\",\"V98_06\",\"V98_Sero\",\"V98_Sero\",\"V98_Sero\",\"V98_Sero\"],\"Versuchs-Nr.\":[\"GBS-Ia-V504\",\"GBS-Ia-V504\",\"GBS-Ia-V504\",\"GBS-Ia-V504\",\"GBS-Ia-V1072\",\"GBS-Ia-V1072\",\"GBS-Ia-V1073\",\"GBS-Ia-V1075\"],\"Platten ID\":[\"A7220001\",\"A7220002\",\"A7220003\",\"A7220004\",\"GBSIa1666\",\"GBSIa1667\",\"GBSIa1668\",\"GBSIa1669\"],\"valide / nicht valide\":[\"x\",\"x\",\"x\",\"x\",\"x\",\"n\",\"x\",\"x\"],\"Bemerkung \\\"wenn nicht\\\"\":[\"---\",\"---\",\"---\",\"---\",\"---\",\"c\",\"---\",\"---\"],\"High Kontrolle\":[\"GBS-Ia HK-V431\",\"GBS-Ia HK-V431\",\"GBS-Ia HK-V431\",\"GBS-Ia HK-V431\",\"GBS-Ia HK-V431\",\"GBS-Ia HK-V431\",\"GBS-Ia HK-V431\",\"GBS-Ia HK-V431\"],\"HK Auftau- nummer\":[\"---\",\"---\",\"---\",\"---\",22,22,22,22],\"HK upper level (µg/mL)\":[110.1,110.1,110.1,110.1,110.1,110.1,110.1,110.1]}"
x = dfToCellsWithComments df True comments (T.pack "John")
-- ws = dfToSheet df
cellmapExample = fst $ dfToCells df True
--coords = DM.keys cells
getXlsx :: FilePath -> IO Xlsx
getXlsx file = do
bs <- L.readFile file
return $ toXlsx bs
getWSheet :: FilePath -> IO Worksheet
getWSheet file = do
xlsx <- getXlsx file
return $ snd $ head (_xlSheets xlsx)
getStyleSheet :: FilePath -> IO StyleSheet
getStyleSheet file = do
xlsx <- getXlsx file
let ss = parseStyleSheet $ _xlStyles xlsx
return $ fromRight minimalStyleSheet ss
cellsexample :: IO CellMap
cellsexample = do
ws <- getWSheet "./tests_XLSXfiles/Book1Walter.xlsx"
return $ _wsCells ws
stylesheetexample :: IO StyleSheet
stylesheetexample = getStyleSheet "./tests_XLSXfiles/Book1Walter.xlsx"
formattedcellsexample :: IO (Map (Int, Int) FormattedCell)
formattedcellsexample = do
ws <- getWSheet "./tests_XLSXfiles/simpleExcel.xlsx"
stylesheet <- getStyleSheet "./tests_XLSXfiles/simpleExcel.xlsx"
return $ toFormattedCells (_wsCells ws) (_wsMerges ws) stylesheet
-- fcm <- formattedcellsexample
-- view formatNumberFormat $ view formattedFormat $ fcm DM.! (3,1)
-- StyleSheet only a subset of Styles ! (currently)
| stla/jsonxlsx | src/TestsXLSX.hs | bsd-3-clause | 3,070 | 0 | 11 | 275 | 385 | 198 | 187 | 37 | 1 |
module Queries where
import Model
import Control.Monad
import Control.Monad.Trans
import Database.Esqueleto
getTotalRevenue :: MonadIO m => SqlPersistT m [Maybe Double]
getTotalRevenue =
liftM (map unValue) $
select $
from $ \(s, i, c) ->
do where_ (s ^. SaleItem ==. i ^. ItemId &&. s ^. SaleCustomer ==. c ^. CustomerId)
return (sum_ $ castNum (s ^. SaleAmount) *. i ^. ItemRevenue)
| agrafix/revenue-sample-app | src/Queries.hs | bsd-3-clause | 451 | 0 | 17 | 128 | 154 | 81 | 73 | 12 | 1 |
{-| General purpose utilities
The names in this module clash heavily with the Haskell Prelude, so I
recommend the following import scheme:
> import Pipes
> import qualified Pipes.Prelude as P -- or use any other qualifier you prefer
Note that 'String'-based 'IO' is inefficient. The 'String'-based utilities
in this module exist only for simple demonstrations without incurring a
dependency on the @text@ package.
Also, 'stdinLn' and 'stdoutLn' remove and add newlines, respectively. This
behavior is intended to simplify examples. The corresponding @stdin@ and
@stdout@ utilities from @pipes-bytestring@ and @pipes-text@ preserve
newlines.
-}
{-# LANGUAGE RankNTypes, Trustworthy #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module Pipes.Prelude (
-- * Producers
-- $producers
stdinLn
, readLn
, fromHandle
, repeatM
, replicateM
-- * Consumers
-- $consumers
, stdoutLn
, print
, toHandle
, drain
-- * Pipes
-- $pipes
, map
, mapM
, sequence
, mapFoldable
, filter
, filterM
, take
, takeWhile
, drop
, dropWhile
, concat
, elemIndices
, findIndices
, scan
, scanM
, chain
, read
, show
, seq
-- * Folds
-- $folds
, fold
, fold'
, foldM
, foldM'
, all
, any
, and
, or
, elem
, notElem
, find
, findIndex
, head
, index
, last
, length
, maximum
, minimum
, null
, sum
, product
, toList
, toListM
-- * Zips
, zip
, zipWith
-- * Utilities
, tee
, generalize
) where
import Control.Exception (throwIO, try)
import Control.Monad (liftM, replicateM_, when, unless)
import Control.Monad.Trans.State.Strict (get, put)
import Data.Functor.Identity (Identity, runIdentity)
import Foreign.C.Error (Errno(Errno), ePIPE)
import Pipes
import Pipes.Core
import Pipes.Internal
import Pipes.Lift (evalStateP)
import qualified GHC.IO.Exception as G
import qualified System.IO as IO
import qualified Prelude
import Prelude hiding (
all
, and
, any
, concat
, drop
, dropWhile
, elem
, filter
, head
, last
, length
, map
, mapM
, maximum
, minimum
, notElem
, null
, or
, print
, product
, read
, readLn
, sequence
, show
, seq
, sum
, take
, takeWhile
, zip
, zipWith
)
{- $producers
Use 'for' loops to iterate over 'Producer's whenever you want to perform the
same action for every element:
> -- Echo all lines from standard input to standard output
> runEffect $ for P.stdinLn $ \str -> do
> lift $ putStrLn str
... or more concisely:
>>> runEffect $ for P.stdinLn (lift . putStrLn)
Test<Enter>
Test
ABC<Enter>
ABC
...
-}
{-| Read 'String's from 'IO.stdin' using 'getLine'
Terminates on end of input
-}
stdinLn :: MonadIO m => Producer' String m ()
stdinLn = fromHandle IO.stdin
{-# INLINABLE stdinLn #-}
-- | 'read' values from 'IO.stdin', ignoring failed parses
readLn :: (MonadIO m, Read a) => Producer' a m ()
readLn = stdinLn >-> read
{-# INLINABLE readLn #-}
{-| Read 'String's from a 'IO.Handle' using 'IO.hGetLine'
Terminates on end of input
-}
fromHandle :: MonadIO m => IO.Handle -> Producer' String m ()
fromHandle h = go
where
go = do
eof <- liftIO $ IO.hIsEOF h
unless eof $ do
str <- liftIO $ IO.hGetLine h
yield str
go
{-# INLINABLE fromHandle #-}
-- | Repeat a monadic action indefinitely, 'yield'ing each result
repeatM :: Monad m => m a -> Producer' a m r
repeatM m = lift m >~ cat
{-# INLINABLE repeatM #-}
{-# RULES
"repeatM m >-> p" forall m p . repeatM m >-> p = lift m >~ p
#-}
{-| Repeat a monadic action a fixed number of times, 'yield'ing each result
> replicateM 0 x = return ()
>
> replicateM (m + n) x = replicateM m x >> replicateM n x -- 0 <= {m,n}
-}
replicateM :: Monad m => Int -> m a -> Producer' a m ()
replicateM n m = lift m >~ take n
{-# INLINABLE replicateM #-}
{- $consumers
Feed a 'Consumer' the same value repeatedly using ('>~'):
>>> runEffect $ lift getLine >~ P.stdoutLn
Test<Enter>
Test
ABC<Enter>
ABC
...
-}
{-| Write 'String's to 'IO.stdout' using 'putStrLn'
Unlike 'toHandle', 'stdoutLn' gracefully terminates on a broken output pipe
-}
stdoutLn :: MonadIO m => Consumer' String m ()
stdoutLn = go
where
go = do
str <- await
x <- liftIO $ try (putStrLn str)
case x of
Left (G.IOError { G.ioe_type = G.ResourceVanished
, G.ioe_errno = Just ioe })
| Errno ioe == ePIPE
-> return ()
Left e -> liftIO (throwIO e)
Right () -> go
{-# INLINABLE stdoutLn #-}
-- | 'print' values to 'IO.stdout'
print :: (MonadIO m, Show a) => Consumer' a m r
print = for cat (\a -> liftIO (Prelude.print a))
{-# INLINABLE print #-}
{-# RULES
"p >-> print" forall p .
p >-> print = for p (\a -> liftIO (Prelude.print a))
#-}
-- | Write 'String's to a 'IO.Handle' using 'IO.hPutStrLn'
toHandle :: MonadIO m => IO.Handle -> Consumer' String m r
toHandle handle = for cat (\str -> liftIO (IO.hPutStrLn handle str))
{-# INLINABLE toHandle #-}
{-# RULES
"p >-> toHandle handle" forall p handle .
p >-> toHandle handle = for p (\str -> liftIO (IO.hPutStrLn handle str))
#-}
-- | 'discard' all incoming values
drain :: Monad m => Consumer' a m r
drain = for cat discard
{-# INLINABLE drain #-}
{-# RULES
"p >-> drain" forall p .
p >-> drain = for p discard
#-}
{- $pipes
Use ('>->') to connect 'Producer's, 'Pipe's, and 'Consumer's:
>>> runEffect $ P.stdinLn >-> P.takeWhile (/= "quit") >-> P.stdoutLn
Test<Enter>
Test
ABC<Enter>
ABC
quit<Enter>
>>>
-}
{-| Apply a function to all values flowing downstream
> map id = cat
>
> map (g . f) = map f >-> map g
-}
map :: Monad m => (a -> b) -> Pipe a b m r
map f = for cat (\a -> yield (f a))
{-# INLINABLE map #-}
{-# RULES
"p >-> map f" forall p f . p >-> map f = for p (\a -> yield (f a))
; "map f >-> p" forall p f . map f >-> p = (do
a <- await
return (f a) ) >~ p
#-}
{-| Apply a monadic function to all values flowing downstream
> mapM return = cat
>
> mapM (f >=> g) = mapM f >-> mapM g
-}
mapM :: Monad m => (a -> m b) -> Pipe a b m r
mapM f = for cat $ \a -> do
b <- lift (f a)
yield b
{-# INLINABLE mapM #-}
{-# RULES
"p >-> mapM f" forall p f . p >-> mapM f = for p (\a -> do
b <- lift (f a)
yield b )
; "mapM f >-> p" forall p f . mapM f >-> p = (do
a <- await
b <- lift (f a)
return b ) >~ p
#-}
-- | Convert a stream of actions to a stream of values
sequence :: Monad m => Pipe (m a) a m r
sequence = mapM id
{-# INLINABLE sequence #-}
{- | Apply a function to all values flowing downstream, and
forward each element of the result.
-}
mapFoldable :: (Monad m, Foldable t) => (a -> t b) -> Pipe a b m r
mapFoldable f = for cat (\a -> each (f a))
{-# INLINABLE mapFoldable #-}
{-# RULES
"p >-> mapFoldable f" forall p f .
p >-> mapFoldable f = for p (\a -> each (f a))
#-}
{-| @(filter predicate)@ only forwards values that satisfy the predicate.
> filter (pure True) = cat
>
> filter (liftA2 (&&) p1 p2) = filter p1 >-> filter p2
-}
filter :: Monad m => (a -> Bool) -> Pipe a a m r
filter predicate = for cat $ \a -> when (predicate a) (yield a)
{-# INLINABLE filter #-}
{-# RULES
"p >-> filter predicate" forall p predicate.
p >-> filter predicate = for p (\a -> when (predicate a) (yield a))
#-}
{-| @(filterM predicate)@ only forwards values that satisfy the monadic
predicate
> filterM (pure (pure True)) = cat
>
> filterM (liftA2 (liftA2 (&&)) p1 p2) = filterM p1 >-> filterM p2
-}
filterM :: Monad m => (a -> m Bool) -> Pipe a a m r
filterM predicate = for cat $ \a -> do
b <- lift (predicate a)
when b (yield a)
{-# INLINABLE filterM #-}
{-# RULES
"p >-> filterM predicate" forall p predicate .
p >-> filterM predicate = for p (\a -> do
b <- lift (predicate a)
when b (yield a) )
#-}
{-| @(take n)@ only allows @n@ values to pass through
> take 0 = return ()
>
> take (m + n) = take m >> take n
> take <infinity> = cat
>
> take (min m n) = take m >-> take n
-}
take :: Monad m => Int -> Pipe a a m ()
take n = replicateM_ n $ do
a <- await
yield a
{-# INLINABLE take #-}
{-| @(takeWhile p)@ allows values to pass downstream so long as they satisfy
the predicate @p@.
> takeWhile (pure True) = cat
>
> takeWhile (liftA2 (&&) p1 p2) = takeWhile p1 >-> takeWhile p2
-}
takeWhile :: Monad m => (a -> Bool) -> Pipe a a m ()
takeWhile predicate = go
where
go = do
a <- await
if (predicate a)
then do
yield a
go
else return ()
{-# INLINABLE takeWhile #-}
{-| @(drop n)@ discards @n@ values going downstream
> drop 0 = cat
>
> drop (m + n) = drop m >-> drop n
-}
drop :: Monad m => Int -> Pipe a a m r
drop n = do
replicateM_ n await
cat
{-# INLINABLE drop #-}
{-| @(dropWhile p)@ discards values going downstream until one violates the
predicate @p@.
> dropWhile (pure False) = cat
>
> dropWhile (liftA2 (||) p1 p2) = dropWhile p1 >-> dropWhile p2
-}
dropWhile :: Monad m => (a -> Bool) -> Pipe a a m r
dropWhile predicate = go
where
go = do
a <- await
if (predicate a)
then go
else do
yield a
cat
{-# INLINABLE dropWhile #-}
-- | Flatten all 'Foldable' elements flowing downstream
concat :: (Monad m, Foldable f) => Pipe (f a) a m r
concat = for cat each
{-# INLINABLE concat #-}
{-# RULES
"p >-> concat" forall p . p >-> concat = for p each
#-}
-- | Outputs the indices of all elements that match the given element
elemIndices :: (Monad m, Eq a) => a -> Pipe a Int m r
elemIndices a = findIndices (a ==)
{-# INLINABLE elemIndices #-}
-- | Outputs the indices of all elements that satisfied the predicate
findIndices :: Monad m => (a -> Bool) -> Pipe a Int m r
findIndices predicate = loop 0
where
loop n = do
a <- await
when (predicate a) (yield n)
loop $! n + 1
{-# INLINABLE findIndices #-}
{-| Strict left scan
> Control.Foldl.purely scan :: Monad m => Fold a b -> Pipe a b m r
-}
scan :: Monad m => (x -> a -> x) -> x -> (x -> b) -> Pipe a b m r
scan step begin done = loop begin
where
loop x = do
yield (done x)
a <- await
let x' = step x a
loop $! x'
{-# INLINABLE scan #-}
{-| Strict, monadic left scan
> Control.Foldl.impurely scan :: Monad m => FoldM a m b -> Pipe a b m r
-}
scanM :: Monad m => (x -> a -> m x) -> m x -> (x -> m b) -> Pipe a b m r
scanM step begin done = do
x <- lift begin
loop x
where
loop x = do
b <- lift (done x)
yield b
a <- await
x' <- lift (step x a)
loop $! x'
{-# INLINABLE scanM #-}
{-| Apply an action to all values flowing downstream
> chain (pure (return ())) = cat
>
> chain (liftA2 (>>) m1 m2) = chain m1 >-> chain m2
-}
chain :: Monad m => (a -> m ()) -> Pipe a a m r
chain f = for cat $ \a -> do
lift (f a)
yield a
{-# INLINABLE chain #-}
{-# RULES
"p >-> chain f" forall p f .
p >-> chain f = for p (\a -> do
lift (f a)
yield a )
; "chain f >-> p" forall p f .
chain f >-> p = (do
a <- await
lift (f a)
return a ) >~ p
#-}
-- | Parse 'Read'able values, only forwarding the value if the parse succeeds
read :: (Monad m, Read a) => Pipe String a m r
read = for cat $ \str -> case (reads str) of
[(a, "")] -> yield a
_ -> return ()
{-# INLINABLE read #-}
{-# RULES
"p >-> read" forall p .
p >-> read = for p (\str -> case (reads str) of
[(a, "")] -> yield a
_ -> return () )
#-}
-- | Convert 'Show'able values to 'String's
show :: (Monad m, Show a) => Pipe a String m r
show = map Prelude.show
{-# INLINABLE show #-}
-- | Evaluate all values flowing downstream to WHNF
seq :: (Monad m) => Pipe a a m r
seq = for cat $ \x -> yield $! x
{-# INLINABLE seq #-}
{- $folds
Use these to fold the output of a 'Producer'. Many of these folds will stop
drawing elements if they can compute their result early, like 'any':
>>> P.any null P.stdinLn
Test<Enter>
ABC<Enter>
<Enter>
True
>>>
-}
{-| Strict fold of the elements of a 'Producer'
> Control.Foldl.purely fold :: Monad m => Fold a b -> Producer a m () -> m b
-}
fold :: Monad m => (x -> a -> x) -> x -> (x -> b) -> Producer a m () -> m b
fold step begin done p0 = loop p0 begin
where
loop p x = case p of
Request v _ -> closed v
Respond a fu -> loop (fu ()) $! step x a
M m -> m >>= \p' -> loop p' x
Pure _ -> return (done x)
{-# INLINABLE fold #-}
{-| Strict fold of the elements of a 'Producer' that preserves the return value
> Control.Foldl.purely fold' :: Monad m => Fold a b -> Producer a m r -> m (b, r)
-}
fold' :: Monad m => (x -> a -> x) -> x -> (x -> b) -> Producer a m r -> m (b, r)
fold' step begin done p0 = loop p0 begin
where
loop p x = case p of
Request v _ -> closed v
Respond a fu -> loop (fu ()) $! step x a
M m -> m >>= \p' -> loop p' x
Pure r -> return (done x, r)
{-# INLINABLE fold' #-}
{-| Strict, monadic fold of the elements of a 'Producer'
> Control.Foldl.impurely foldM :: Monad m => FoldM a b -> Producer a m () -> m b
-}
foldM
:: Monad m
=> (x -> a -> m x) -> m x -> (x -> m b) -> Producer a m () -> m b
foldM step begin done p0 = do
x0 <- begin
loop p0 x0
where
loop p x = case p of
Request v _ -> closed v
Respond a fu -> do
x' <- step x a
loop (fu ()) $! x'
M m -> m >>= \p' -> loop p' x
Pure _ -> done x
{-# INLINABLE foldM #-}
{-| Strict, monadic fold of the elements of a 'Producer'
> Control.Foldl.impurely foldM' :: Monad m => FoldM a b -> Producer a m r -> m (b, r)
-}
foldM'
:: Monad m
=> (x -> a -> m x) -> m x -> (x -> m b) -> Producer a m r -> m (b, r)
foldM' step begin done p0 = do
x0 <- begin
loop p0 x0
where
loop p x = case p of
Request v _ -> closed v
Respond a fu -> do
x' <- step x a
loop (fu ()) $! x'
M m -> m >>= \p' -> loop p' x
Pure r -> do
b <- done x
return (b, r)
{-# INLINABLE foldM' #-}
{-| @(all predicate p)@ determines whether all the elements of @p@ satisfy the
predicate.
-}
all :: Monad m => (a -> Bool) -> Producer a m () -> m Bool
all predicate p = null $ p >-> filter (\a -> not (predicate a))
{-# INLINABLE all #-}
{-| @(any predicate p)@ determines whether any element of @p@ satisfies the
predicate.
-}
any :: Monad m => (a -> Bool) -> Producer a m () -> m Bool
any predicate p = liftM not $ null (p >-> filter predicate)
{-# INLINABLE any #-}
-- | Determines whether all elements are 'True'
and :: Monad m => Producer Bool m () -> m Bool
and = all id
{-# INLINABLE and #-}
-- | Determines whether any element is 'True'
or :: Monad m => Producer Bool m () -> m Bool
or = any id
{-# INLINABLE or #-}
{-| @(elem a p)@ returns 'True' if @p@ has an element equal to @a@, 'False'
otherwise
-}
elem :: (Monad m, Eq a) => a -> Producer a m () -> m Bool
elem a = any (a ==)
{-# INLINABLE elem #-}
{-| @(notElem a)@ returns 'False' if @p@ has an element equal to @a@, 'True'
otherwise
-}
notElem :: (Monad m, Eq a) => a -> Producer a m () -> m Bool
notElem a = all (a /=)
{-# INLINABLE notElem #-}
-- | Find the first element of a 'Producer' that satisfies the predicate
find :: Monad m => (a -> Bool) -> Producer a m () -> m (Maybe a)
find predicate p = head (p >-> filter predicate)
{-# INLINABLE find #-}
{-| Find the index of the first element of a 'Producer' that satisfies the
predicate
-}
findIndex :: Monad m => (a -> Bool) -> Producer a m () -> m (Maybe Int)
findIndex predicate p = head (p >-> findIndices predicate)
{-# INLINABLE findIndex #-}
-- | Retrieve the first element from a 'Producer'
head :: Monad m => Producer a m () -> m (Maybe a)
head p = do
x <- next p
return $ case x of
Left _ -> Nothing
Right (a, _) -> Just a
{-# INLINABLE head #-}
-- | Index into a 'Producer'
index :: Monad m => Int -> Producer a m () -> m (Maybe a)
index n p = head (p >-> drop n)
{-# INLINABLE index #-}
-- | Retrieve the last element from a 'Producer'
last :: Monad m => Producer a m () -> m (Maybe a)
last p0 = do
x <- next p0
case x of
Left _ -> return Nothing
Right (a, p') -> loop a p'
where
loop a p = do
x <- next p
case x of
Left _ -> return (Just a)
Right (a', p') -> loop a' p'
{-# INLINABLE last #-}
-- | Count the number of elements in a 'Producer'
length :: Monad m => Producer a m () -> m Int
length = fold (\n _ -> n + 1) 0 id
{-# INLINABLE length #-}
-- | Find the maximum element of a 'Producer'
maximum :: (Monad m, Ord a) => Producer a m () -> m (Maybe a)
maximum = fold step Nothing id
where
step x a = Just $ case x of
Nothing -> a
Just a' -> max a a'
{-# INLINABLE maximum #-}
-- | Find the minimum element of a 'Producer'
minimum :: (Monad m, Ord a) => Producer a m () -> m (Maybe a)
minimum = fold step Nothing id
where
step x a = Just $ case x of
Nothing -> a
Just a' -> min a a'
{-# INLINABLE minimum #-}
-- | Determine if a 'Producer' is empty
null :: Monad m => Producer a m () -> m Bool
null p = do
x <- next p
return $ case x of
Left _ -> True
Right _ -> False
{-# INLINABLE null #-}
-- | Compute the sum of the elements of a 'Producer'
sum :: (Monad m, Num a) => Producer a m () -> m a
sum = fold (+) 0 id
{-# INLINABLE sum #-}
-- | Compute the product of the elements of a 'Producer'
product :: (Monad m, Num a) => Producer a m () -> m a
product = fold (*) 1 id
{-# INLINABLE product #-}
-- | Convert a pure 'Producer' into a list
toList :: Producer a Identity () -> [a]
toList = loop
where
loop p = case p of
Request v _ -> closed v
Respond a fu -> a:loop (fu ())
M m -> loop (runIdentity m)
Pure _ -> []
{-# INLINABLE toList #-}
{-| Convert an effectful 'Producer' into a list
Note: 'toListM' is not an idiomatic use of @pipes@, but I provide it for
simple testing purposes. Idiomatic @pipes@ style consumes the elements
immediately as they are generated instead of loading all elements into
memory.
-}
toListM :: Monad m => Producer a m () -> m [a]
toListM = fold step begin done
where
step x a = x . (a:)
begin = id
done x = x []
{-# INLINABLE toListM #-}
-- | Zip two 'Producer's
zip :: Monad m
=> (Producer a m r)
-> (Producer b m r)
-> (Producer' (a, b) m r)
zip = zipWith (,)
{-# INLINABLE zip #-}
-- | Zip two 'Producer's using the provided combining function
zipWith :: Monad m
=> (a -> b -> c)
-> (Producer a m r)
-> (Producer b m r)
-> (Producer' c m r)
zipWith f = go
where
go p1 p2 = do
e1 <- lift $ next p1
case e1 of
Left r -> return r
Right (a, p1') -> do
e2 <- lift $ next p2
case e2 of
Left r -> return r
Right (b, p2') -> do
yield (f a b)
go p1' p2'
{-# INLINABLE zipWith #-}
{-| Transform a 'Consumer' to a 'Pipe' that reforwards all values further
downstream
-}
tee :: Monad m => Consumer a m r -> Pipe a a m r
tee p = evalStateP Nothing $ do
r <- up >\\ (hoist lift p //> dn)
ma <- lift get
case ma of
Nothing -> return ()
Just a -> yield a
return r
where
up () = do
ma <- lift get
case ma of
Nothing -> return ()
Just a -> yield a
a <- await
lift $ put (Just a)
return a
dn v = closed v
{-# INLINABLE tee #-}
{-| Transform a unidirectional 'Pipe' to a bidirectional 'Proxy'
> generalize (f >-> g) = generalize f >+> generalize g
>
> generalize cat = pull
-}
generalize :: Monad m => Pipe a b m r -> x -> Proxy x a x b m r
generalize p x0 = evalStateP x0 $ up >\\ hoist lift p //> dn
where
up () = do
x <- lift get
request x
dn a = do
x <- respond a
lift $ put x
{-# INLINABLE generalize #-}
| quchen/Haskell-Pipes-Library | src/Pipes/Prelude.hs | bsd-3-clause | 20,837 | 0 | 21 | 6,426 | 5,223 | 2,645 | 2,578 | -1 | -1 |
module Language.Xi.Base.Syntax where
-- | Syntactic representation of constants.
data Constant
= ConstBool Bool -- ^ Boolean.
| ConstInt Int -- ^ Integer.
| ConstChar Char -- ^ Character.
| ConstString String -- ^ String literal.
| ConstUnit -- ^ Unit (void).
-- | Operations over booleans.
data BoolOperation
= BoolAnd -- ^ Logical AND.
| BoolOr -- ^ Logical OR.
| BoolNot -- ^ Logical NOT.
-- | Operations over integers.
data IntOperation
= IntPlus -- ^ Integer addition.
| IntMinus -- ^ Integer subtraction.
| IntMult -- ^ Integer multiplication.
| IntDiv -- ^ Integer division.
| IntMod -- ^ Integer reminder.
-- | Operations over strings.
data StringOperation
= StringPlus -- ^ String concatenation.
-- | Comparison operations.
data ComparisonOperation
= CompLT -- ^ Less than.
| CompLE -- ^ Less than or equal.
| CompEQ -- ^ Equal.
| CompNE -- ^ Not equal.
| CompGE -- ^ Greater than or equal.
| CompGT -- ^ Greater than.
-- | Syntactic expression.
data Expression
= ExprBool BoolExpression -- ^ Boolean expression.
| ExprInt IntExpression -- ^ Integer expression.
| ExprChar CharExpression -- ^ Character expression.
| ExprString StringExpression -- ^ String expression.
| ExprUnit UnitExpression -- ^ Unit expression.
-- | Boolean expressions.
data BoolExpression
= BoolExprConst ConstBool -- ^ Boolean literal.
| BoolExprOp BoolOperation [BoolExpression] -- ^ Operation over booleans.
| BoolExprCompInt ComparisonOperation [IntExpression] -- ^ Integer comparison.
| BoolExprCompChar ComparisonOperation [CharExpression] -- ^ Character comparison.
| BoolExprCompString ComparisonOperation [StringExpression] -- ^ String comparison.
-- | Integer expressions.
data IntExpression
= IntExprConst ConstInt -- ^ Integer literal.
| IntExprOp IntOperation [IntExpression] -- ^ Operation over integers.
-- | Character expressions.
data CharExpression
= CharExprConst ConstChar
-- | String expressions.
data StringExpression
= StringExprConst ConstString -- ^ String literal.
| StringExprOp StringOperation [StringExpression] -- ^ Operation over strings.
-- | Unit (void) expressions.
data UnitExpression
= UnitExprConst ConstUnit -- ^ Unit literal.
| fizruk/xi-base | src/Language/Xi/Base/Syntax.hs | bsd-3-clause | 2,586 | 0 | 7 | 754 | 276 | 184 | 92 | 48 | 0 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
module Language.Haskell.Refact.Refactoring.DupDef(duplicateDef) where
import qualified Data.Generics as SYB
import qualified GHC.SYB.Utils as SYB
import qualified GHC
import qualified OccName as GHC
import qualified RdrName as GHC
import Control.Monad
import Data.List
import Data.Maybe
import qualified Language.Haskell.GhcMod as GM
import qualified Language.Haskell.GhcMod.Internal as GM
import Language.Haskell.GhcMod
import Language.Haskell.Refact.API
import Language.Haskell.GHC.ExactPrint.Types
import Language.Haskell.GHC.ExactPrint.Parsers
import Language.Haskell.GHC.ExactPrint.Transform
-- ---------------------------------------------------------------------
-- | This refactoring duplicates a definition (function binding or
-- simple pattern binding) at the same level with a new name provided by
-- the user. The new name should not cause name clash/capture.
duplicateDef :: RefactSettings -> Options -> FilePath -> String -> SimpPos -> IO [FilePath]
duplicateDef settings opts fileName newName (row,col) =
runRefacSession settings opts [Left fileName] (comp fileName newName (row,col))
comp :: FilePath -> String -> SimpPos
-> RefactGhc [ApplyRefacResult]
comp fileName newName (row, col) = do
if isVarId newName
then
do
getModuleGhc fileName
renamed <- getRefactRenamed
parsed <- getRefactParsed
targetModule <- getRefactTargetModule
let (Just (modName,_)) = getModuleName parsed
let maybePn = locToName (row, col) renamed
case maybePn of
Just pn ->
do
(refactoredMod@((_fp,ismod),(anns',renamed')),_) <- applyRefac (doDuplicating pn newName) (RSFile fileName)
case (ismod) of
RefacUnmodifed-> error "The selected identifier is not a function/simple pattern name, or is not defined in this module "
RefacModified -> return ()
if modIsExported modName renamed
then
do clients <- clientModsAndFiles targetModule
logm ("DupDef: clients=" ++ (showGhc clients)) -- ++AZ++ debug
refactoredClients <- mapM (refactorInClientMod (GHC.unLoc pn) modName
(findNewPName newName renamed')) clients
return $ refactoredMod:refactoredClients
else return [refactoredMod]
Nothing -> error "Invalid cursor position!"
else error $ "Invalid new function name:" ++ newName ++ "!"
doDuplicating :: GHC.Located GHC.Name -> String
-> RefactGhc ()
doDuplicating pn newName = do
inscopes <- getRefactInscopes
reallyDoDuplicating pn newName inscopes
reallyDoDuplicating :: GHC.Located GHC.Name -> String
-> InScopes
-> RefactGhc ()
reallyDoDuplicating pn newName inscopes = do
parsed <- getRefactParsed
parsed' <- SYB.everywhereMStaged SYB.Renamer (
SYB.mkM dupInModule
`SYB.extM` dupInMatch
`SYB.extM` dupInPat
`SYB.extM` dupInLet
`SYB.extM` dupInLetStmt
) parsed
putRefactParsed parsed' emptyAnns
return ()
where
--1. The definition to be duplicated is at top level.
-- dupInMod :: (GHC.HsGroup GHC.Name)-> RefactGhc (GHC.HsGroup GHC.Name)
-- dupInMod (grp :: (GHC.HsGroup GHC.Name))
-- | not $ emptyList (findFunOrPatBind pn (hsBinds grp)) = doDuplicating' inscopes grp pn
-- dupInMod grp = return grp
dupInModule :: GHC.ParsedSource -> RefactGhc GHC.ParsedSource
dupInModule p
= do
declsp <- liftT $ hsDecls p
nm <- getRefactNameMap
if not $ emptyList (findFunOrPatBind nm pn declsp)
then doDuplicating' p pn
else return p
--2. The definition to be duplicated is a local declaration in a match
dupInMatch (match::GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName))
= do
nm <- getRefactNameMap
-- declsp <- liftT $ hsDecls rhs
declsp <- liftT $ hsDecls match
if not $ emptyList (findFunOrPatBind nm pn declsp)
then doDuplicating' match pn
else return match
--3. The definition to be duplicated is a local declaration in a pattern binding
dupInPat (pat@(GHC.L _ (GHC.PatBind _p rhs _typ _fvs _)) :: GHC.LHsBind GHC.RdrName)
= doDuplicating' pat pn
-- | not $ emptyList (findFunOrPatBind pn (hsBinds rhs)) = doDuplicating' inscopes pat pn
-- dupInPat pat = return pat
--4: The defintion to be duplicated is a local decl in a Let expression
dupInLet (letExp@(GHC.L _ (GHC.HsLet ds _e)):: GHC.LHsExpr GHC.RdrName)
= doDuplicating' letExp pn
-- | not $ emptyList (findFunOrPatBind pn (hsBinds ds)) = doDuplicating' inscopes letExp pn
-- dupInLet letExp = return letExp
--5. The definition to be duplicated is a local decl in a case alternative.
-- Note: The local declarations in a case alternative are covered in #2 above.
--6.The definition to be duplicated is a local decl in a Let statement.
dupInLetStmt (letStmt@(GHC.LetStmt ds):: GHC.Stmt GHC.RdrName (GHC.LHsExpr GHC.RdrName))
= doDuplicating' letStmt pn
-- was |findFunOrPatBind pn ds /=[]=doDuplicating' inscps letStmt pn
-- |not $ emptyList (findFunOrPatBind pn (hsBinds ds)) = doDuplicating' inscopes letStmt pn
-- dupInLetStmt letStmt = return letStmt
-- findFunOrPatBind :: (SYB.Data t) => GHC.Located GHC.Name -> t -> [GHC.LHsBind GHC.Name]
findFunOrPatBind nm (GHC.L _ n) ds = filter (\d->isFunBindP d || isSimplePatDecl d) $ definingDeclsRdrNames nm [n] ds True False
doDuplicating' :: (HasDecls t) => t -> GHC.Located GHC.Name -> RefactGhc t
doDuplicating' t ln = do
declsp <- liftT $ hsDecls t
nm <- getRefactNameMap
if not $ emptyList (findFunOrPatBind nm pn declsp)
then doDuplicating' t pn
else return t
doDuplicating'' :: (HasDecls t) => t -> GHC.Located GHC.Name
-> RefactGhc t
doDuplicating'' parentr ln@(GHC.L _ n)
= do
declsp <- liftT $ hsDecls parentr
nm <- getRefactNameMap
let
-- declsr = hsBinds parentr
duplicatedDecls = definingDeclsRdrNames nm [n] declsp True False
-- (after,before) = break (definesP pn) (reverse declsp)
(f,d) <- hsFDNamesFromInside parentr
--f: names that might be shadowd by the new name,
--d: names that might clash with the new name
dv <- hsVisiblePNsRdr nm ln declsp --dv: names may shadow new name
let vars = nub (f `union` d `union` map showGhc dv)
newNameGhc <- mkNewGhcName Nothing newName
-- TODO: Where definition is of form tup@(h,t), test each element of it for clashes, or disallow
nameAlreadyInScope <- isInScopeAndUnqualifiedGhc newName Nothing
-- logm ("DupDef: nameAlreadyInScope =" ++ (show nameAlreadyInScope)) -- ++AZ++ debug
-- logm ("DupDef: ln =" ++ (show ln)) -- ++AZ++ debug
if elem newName vars || (nameAlreadyInScope && findEntity ln duplicatedDecls)
then error ("The new name'"++newName++"' will cause name clash/capture or ambiguity problem after "
++ "duplicating, please select another name!")
else do newBinding <- duplicateDecl declsp parentr n newNameGhc
-- let newDecls = replaceDecls declsr (declsr ++ newBinding)
-- let newDecls = replaceBinds declsr (declsr ++ newBinding)
-- return $ replaceBinds parentr newDecls
parentr' <- liftT $ replaceDecls parentr (declsp ++ newBinding)
return parentr'
-- | Find the the new definition name in GHC.Name format.
findNewPName :: (SYB.Data t) => String -> t -> GHC.Name
findNewPName name renamed = gfromJust "findNewPName" res
where
res = SYB.something (Nothing `SYB.mkQ` workerN `SYB.extQ` workerR) renamed
workerN (pname::GHC.Name)
| (GHC.occNameString $ GHC.getOccName pname) == name = Just pname
workerN _ = Nothing
workerR (pname::GHC.RdrName)
| (GHC.occNameString $ GHC.rdrNameOcc pname) == name = Just (error $ "need to call rdrNameToName")
workerR _ = Nothing
{-
-- | Find the the new definition name in GHC.Name format.
findNewPName :: String -> GHC.RenamedSource -> GHC.Name
findNewPName name renamed = gfromJust "findNewPName" res
where
res = SYB.somethingStaged SYB.Renamer Nothing
(Nothing `SYB.mkQ` worker) renamed
worker (pname::GHC.Name)
| (GHC.occNameString $ GHC.getOccName pname) == name = Just pname
worker _ = Nothing
-}
-- | Do refactoring in the client module. That is to hide the
-- identifer in the import declaration if it will cause any problem in
-- the client module.
refactorInClientMod :: GHC.Name -> GHC.ModuleName -> GHC.Name -> TargetModule
-> RefactGhc ApplyRefacResult
refactorInClientMod oldPN serverModName newPName targetModule
= do
logm ("refactorInClientMod: (serverModName,newPName)=" ++ (showGhc (serverModName,newPName))) -- ++AZ++ debug
-- void $ activateModule targetModule
getTargetGhc targetModule
-- let fileName = gfromJust "refactorInClientMod" $ GHC.ml_hs_file $ GHC.ms_location modSummary
let fileName = GM.mpPath targetModule
{-
-- modInfo@(t,ts) <- getModuleGhc fileName
getModuleGhc fileName
-}
renamed <- getRefactRenamed
parsed <- getRefactParsed
let modNames = willBeUnQualImportedBy serverModName renamed
logm ("refactorInClientMod: (modNames)=" ++ (showGhc (modNames))) -- ++AZ++ debug
-- if isJust modNames && needToBeHided (pNtoName newPName) exps parsed
mustHide <- needToBeHided newPName renamed parsed
logm ("refactorInClientMod: (mustHide)=" ++ (showGhc (mustHide))) -- ++AZ++ debug
if isJust modNames && mustHide
then do
-- refactoredMod <- applyRefac (doDuplicatingClient serverModName [newPName]) (Just modInfo) fileName
(refactoredMod,_) <- applyRefac (doDuplicatingClient serverModName [newPName]) (RSFile fileName)
return refactoredMod
else return ((fileName,RefacUnmodifed),(emptyAnns,parsed))
where
needToBeHided :: GHC.Name -> GHC.RenamedSource -> GHC.ParsedSource -> RefactGhc Bool
needToBeHided name exps parsed = do
let usedUnqual = usedWithoutQualR name parsed
logm ("refactorInClientMod: (usedUnqual)=" ++ (showGhc (usedUnqual))) -- ++AZ++ debug
return $ usedUnqual || causeNameClashInExports oldPN name serverModName exps
doDuplicatingClient :: GHC.ModuleName -> [GHC.Name]
-> RefactGhc ()
doDuplicatingClient serverModName newPNames = do
parsed <- getRefactParsed
parsed' <- addHiding serverModName parsed (map GHC.nameRdrName newPNames)
putRefactParsed parsed' emptyAnns
return ()
--Check here:
-- | get the module name or alias name by which the duplicated
-- definition will be imported automatically.
willBeUnQualImportedBy :: GHC.ModuleName -> GHC.RenamedSource -> Maybe [GHC.ModuleName]
willBeUnQualImportedBy modName (_,imps,_,_)
= let
ms = filter (\(GHC.L _ (GHC.ImportDecl _ (GHC.L _ modName1) _qualify _source _safe isQualified _isImplicit _as h))
-> modName == modName1
&& not isQualified
&& (isNothing h -- not hiding
||
(isJust h && ((fst (gfromJust "willBeUnQualImportedBy" h))==True))
))
imps
in if (emptyList ms) then Nothing
else Just $ nub $ map getModName ms
where getModName (GHC.L _ (GHC.ImportDecl _ _modName1 _qualify _source _safe _isQualified _isImplicit as _h))
= if isJust as then (fromJust as)
else modName
-- simpModName (SN m loc) = m
| mpickering/HaRe | src/Language/Haskell/Refact/Refactoring/DupDef.hs | bsd-3-clause | 12,860 | 3 | 24 | 3,823 | 2,434 | 1,252 | 1,182 | 171 | 5 |
step :: (Delta d, AAM aam) => d -> aam
-> StateSpace d aam -> StatSpace d aam
step d aam ss = eachInSet ss $ \ (c,e,s,t) ->
eachInSet (call d aam t c e s) $ \ (c',e',s') ->
setSingleton (c',e',s',tick aam c' t)
exec :: (Delta d, AAM aam) => d -> aam
-> Call -> StateSpace d aam
exec d aam c0 = iter (collect (step d aam)) $
setSingleton (c0, mapEmpty, mapEmpty, tzero aam)
| davdar/quals | writeup-old/sections/03AAMByExample/03AbstractSemantics/03Step.hs | bsd-3-clause | 396 | 0 | 11 | 102 | 226 | 118 | 108 | 9 | 1 |
{-# LANGUAGE RankNTypes, KindSignatures #-}
-- |
-- Module: Text.XML.Generic.ToXmlUtil
-- Copyright: 2013 Dmitry Olshansky
-- License: BSD3
--
-- Maintainer: [email protected]
--
-- Parameters and some utility functions for ToXml
module Text.XML.Generic.ToXmlUtil where
import Data.Conduit
import Data.Default(Default(..))
import Data.Maybe -- (catMaybes, fromMaybe, isNothing, maybeToList)
import Data.String(IsString(..))
import Data.XML.Types(Event(..), Name(..), Content(..))
import GHC.Generics
-- | Parameters of generic transformation
data TOX = TOX { toxTof :: TOF -- ^ functions to define name of attributes and elements
, toxTo :: TO -- ^ current state of transformation
}
instance Default TOX where
def = TOX def def
-- | Current state of transformation.
-- Generic transformation always started from Selector then Datatype then Sum is possible
-- then Constructor then optionally Products.
-- Values are filled accordingly.
data TO = TO { toSel :: Maybe String -- ^ name of selector
, toDT :: Maybe (String, String) -- ^ name of datatype and module
, toCons :: Maybe (String, (Fixity, Bool)) -- ^ constructor name, fixity and isRecord?
, toRoot :: Bool -- ^ True on the begining of transformation, then False
, toSum :: Bool -- ^ True if Sum type (valid when (isJust toCons))
, toSumFst :: Bool -- ^ Is current constructor first in Sum type
}
deriving Show
-- | functions to get attribute and element name
data TOF = TOF { tofElName :: TO -> Maybe Name -- ^ Define element name by current state in 'TO'
, tofAttrName :: TO -> Maybe Name -- ^ Define attribute name by current state in 'TO'
}
instance Default TO where
def = TO { toSel = def
, toDT = def
, toCons = def
, toRoot = False
, toSum = False
, toSumFst = False
}
instance Default TOF where
def = TOF { tofElName = getNameE
, tofAttrName = getNameA
}
where
getNameE t
-- in :+:
| p && f && isNothing mc && sEmpty = fmap (fromString . fst) md
| p && f && isNothing mc = fmap fromString ms
-- in Cons
| isJust mc && not p && sEmpty = fmap (fromString . fst) mc
| isJust mc && not p && not sEmpty = fmap fromString ms
| isJust mc && p = fmap (fromString . fst) mc
| otherwise = Nothing
where
(ms,md,mc,p,f) = (,,,,) <$> toSel <*> toDT <*> toCons <*> toSum <*> toSumFst $ t
sEmpty = ms `elem` [Nothing, Just ""]
getNameA t
| not sEmpty && isNothing md = fmap fromString ms
| otherwise = Nothing
where
(ms,md) = (,) <$> toSel <*> toDT $ t
sEmpty = ms `elem` [Nothing, Just ""]
-- | Name of element by 'TOX'
getElName :: TOX -> Maybe Name
getElName = tofElName . toxTof <*> toxTo
-- | Attribute name by 'TOX'
getAttrName :: TOX -> Maybe Name
getAttrName = tofAttrName . toxTof <*> toxTo
toxSum, toxNotRoot, toxDef :: TOX -> TOX
-- | Modifying 'TOX' for Sum type
toxSum tox
| toSum $ toxTo tox = tox { toxTo = (toxTo tox) { toSumFst = False } }
| otherwise = tox { toxTo = (toxTo tox) { toSum = True
, toSumFst = True } }
-- | Modifying 'TOX' for not root
toxNotRoot tox = tox { toxTo = (toxTo tox) { toRoot = False } }
-- | Initialize 'TOX'
toxDef tox = tox { toxTo = def }
-- | Modifying 'TOX' in selector
toxSel :: forall s (t :: * -> (* -> *) -> * -> *) (f :: * -> *) a.
Selector s =>
TOX -> t s f a -> TOX
toxSel tox sel = tox { toxTo = def { toSel = Just $ selName sel } }
-- | Modifying 'TOX' in constructor
toxCon :: forall c (t :: * -> (* -> *) -> * -> *) (f :: * -> *) a.
Constructor c =>
TOX -> t c f a -> TOX
toxCon tox con = tox { toxTo = (toxTo tox) { toCons = Just $ ((,)
<$> conName
<*> ((,)
<$> conFixity
<*> conIsRecord)) con } }
-- | Modifying 'TOX' in datatype
toxDT :: forall d (t :: * -> (* -> *) -> * -> *) (f :: * -> *) a.
Datatype d =>
TOX -> t d f a -> TOX
toxDT tox dt = tox { toxTo = (toxTo tox) { toDT = Just $ ((,) <$> datatypeName <*> moduleName) dt } }
-- | Internal function to yield elements
doTo :: Monad m
=> TOX -> (TOX -> t -> Maybe a) -> (TOX -> t -> [(Name, [Data.XML.Types.Content])]) -> t
-> ConduitM i Event m () -> ConduitM i Event m ()
doTo tox getAsAttr getAttrs x next
= maybe
(maybe
next
(\n -> do
yield $ EventBeginElement n $ getAttrs tox x
next
yield $ EventEndElement n
) $ getElName tox
)
(const $ return ())
$ getAsAttr tox x
| odr/xml-conduit-generic | Text/XML/Generic/ToXmlUtil.hs | bsd-3-clause | 5,559 | 0 | 16 | 2,242 | 1,419 | 789 | 630 | 86 | 1 |
module Part2.Problem44 where
import Data.List (find)
import Data.Maybe (mapMaybe)
import Part1.Problem3 (squareRoot)
--
-- Problem 44: Pentagon numbers
--
-- Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten
-- pentagonal numbers are:
--
-- 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
--
-- It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference,
-- 70 − 22 = 48, is not pentagonal.
--
-- Find the pair of pentagonal numbers, Pj and Pk, for which their sum and
-- difference are pentagonal and D = |Pk − Pj| is minimised; what is the value
-- of D?
problem44 :: [(Int, Int)]
problem44 = mapMaybe minPair (take 3000 pentagonals) where
minPair p1 = (\p2 -> (p1, p2)) <$> findMinPair p1
findMinPair p1 = find isPair domain where
domain = reverse $ takeWhile (< p1) pentagonals
isPair p2 = isPentagonal (p1 - p2) && isPentagonal (p1 + p2)
pentagonals :: [Int]
pentagonals = map pentagonal [1..]
pentagonal :: Int -> Int
pentagonal n = n * (3*n - 1) `div` 2
-- isPentagonal :: Int -> Bool
-- isPentagonal x = x `elem` takeWhile (<= x) pentagonals
isPentagonal :: Int -> Bool
isPentagonal x = x == pentagonal n || x == pentagonal (n + 1) where
n = squareRoot (x*2 `div` 3)
diffs :: [(Int, Int)]
diffs = filter (isPentagonal . snd)
$ [1..] `zip` tail (zipWith (-) pentagonals (0:pentagonals))
altProblem44 :: Maybe (Int, Int)
altProblem44 = find minPair diffs where
minPair (n, _) = let
p1 = pentagonal n
p2 = pentagonal (n + 1)
in isPentagonal $ p1 + p2
| c0deaddict/project-euler | src/Part2/Problem44.hs | bsd-3-clause | 1,583 | 0 | 13 | 359 | 445 | 250 | 195 | 26 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Scratch where
import Control.Distributed.Process
import Data.Binary
import Data.Typeable
import GHC.Generics (Generic)
import Control.Distributed.BriskStatic
import Control.Distributed.Process.Closure
import GHC.Base.Brisk
data PingMessage = Ping ProcessId | Pong ProcessId
deriving (Typeable, Generic)
instance Binary PingMessage
pingProcess :: ProcessId -> Process ()
pingProcess whom = do me <- getSelfPid
doSend <- liftIO $ getChar
if doSend == 'x' then
send whom (Ping me)
else
send whom (Ping me)
expect :: Process PingMessage
return ()
remotable ['pingProcess]
pongProcess :: Process ()
pongProcess = do msg <- expect
me <- getSelfPid
case msg of
Ping whom -> send whom $ Pong me
Pong x -> return ()
main :: NodeId -> Process ()
main n = do me <- getSelfPid
spawn n $ $(mkBriskClosure 'pingProcess) me
pongProcess
| abakst/brisk-prelude | tests/pos/Data01.hs | bsd-3-clause | 1,276 | 0 | 11 | 420 | 312 | 158 | 154 | 35 | 2 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Main where
import Test.Framework (defaultMain, testGroup, Test)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import qualified Data.Identifiers.Hashable as H
import qualified Data.Identifiers.ListLike as L
main :: IO ()
main = defaultMain tests
tests :: [Test]
tests = [ testGroup "QuickCheck Data.Identifiers.Hashable"
[ testProperty "hasId" H.prop_hasId
, testProperty "stableId" H.prop_stableId
, testProperty "keyRetrieval" H.prop_keyRetrieval
, testProperty "keyRetrievalUnsafe" H.prop_keyRetrievalUnsafe
, testProperty "idempotent" H.prop_idempotent
, testProperty "stableCombine" H.prop_stableCombine
, testProperty "propermigration" H.prop_properMigration
]
, testGroup "QuickCheck Data.Identifiers.ListLike"
[ testProperty "hasId" L.prop_hasId
, testProperty "stableId" L.prop_stableId
, testProperty "keyRetrieval" L.prop_keyRetrieval
, testProperty "keyRetrievalUnsafe" L.prop_keyRetrievalUnsafe
, testProperty "idempotent" L.prop_idempotent
, testProperty "stableCombine" L.prop_stableCombine
, testProperty "propermigration" L.prop_properMigration
]
]
| awagner83/identifiers | test/TestAll.hs | bsd-3-clause | 1,454 | 0 | 9 | 436 | 238 | 131 | 107 | 25 | 1 |
module S3Logd.Syslog (syslogLefts, consoleLefts,panic,syslog) where
import Data.Conduit
import Control.Applicative
import Control.Monad.IO.Class (liftIO)
import System.Log.Handler
import System.Log.Handler.Syslog
import System.Log
-- Nom on all the lefts:
splitLefts::(MonadResource m)=> IO st -> (st->IO ()) -> (st->b->IO ()) -> Conduit (Either b a) m a
splitLefts aloc deloc consume = conduitIO aloc deloc push none
where none _ = return []
push st = either (io st) wrap
io st b = do
liftIO $ consume st b
return $ IOProducing []
wrap a = return $ IOProducing [a]
-- Treat all the lefts as errors that need to be sent to syslog
syslogLefts::(MonadResource m)=>Conduit (Either String a) m a
syslogLefts = splitLefts logger close undefined
where logger = openlog "s3logd" [PID] DAEMON ERROR
log st str = handle st (ERROR,str) "error"
-- Just print all lefts to the console.
consoleLefts::(MonadResource m)=>Conduit (Either String a) m a
consoleLefts = splitLefts void none (const $ putStrLn)
where void = return ()
none _ = return ()
-- Log a string to syslog as an EMERGENCY
panic::String->IO ()
panic = logError EMERGENCY
syslog = logError ERROR
logError level str = do
logger <- openlog "s3logd" [PID] DAEMON ERROR
handle logger (level, str) "panic"
close logger | matthewSorensen/s3-tools | S3Logd/Syslog.hs | bsd-3-clause | 1,368 | 0 | 13 | 301 | 480 | 248 | 232 | 30 | 1 |
{-# LANGUAGE TypeFamilies #-}
-- | Simple implementation of slotting.
module Pos.Infra.Slotting.Impl.Simple
( SimpleSlottingStateVar
, mkSimpleSlottingStateVar
, SimpleSlottingMode
, MonadSimpleSlotting
, getCurrentSlotSimple
, getCurrentSlotSimple'
, getCurrentSlotBlockingSimple
, getCurrentSlotBlockingSimple'
, getCurrentSlotInaccurateSimple
, getCurrentSlotInaccurateSimple'
, currentTimeSlottingSimple
) where
import Universum
import Pos.Core.Conc (currentTime)
import Pos.Core.Slotting (MonadSlotsData, SlotCount, SlotId (..),
Timestamp (..), getCurrentNextEpochIndexM,
unflattenSlotId, waitCurrentEpochEqualsM)
import Pos.Infra.Slotting.Impl.Util (approxSlotUsingOutdated,
slotFromTimestamp)
import Pos.Util (HasLens (..))
----------------------------------------------------------------------------
-- Mode
----------------------------------------------------------------------------
type SimpleSlottingMode ctx m
= ( MonadSlotsData ctx m
, MonadIO m
)
type MonadSimpleSlotting ctx m
= ( MonadReader ctx m
, HasLens SimpleSlottingStateVar ctx SimpleSlottingStateVar
, SimpleSlottingMode ctx m
)
----------------------------------------------------------------------------
-- State
----------------------------------------------------------------------------
data SimpleSlottingState = SimpleSlottingState
{ _sssLastSlot :: !SlotId
}
type SimpleSlottingStateVar = TVar SimpleSlottingState
mkSimpleSlottingStateVar :: MonadIO m => SlotCount -> m SimpleSlottingStateVar
mkSimpleSlottingStateVar epochSlots =
atomically $ newTVar $ SimpleSlottingState $ unflattenSlotId epochSlots 0
----------------------------------------------------------------------------
-- Implementation
----------------------------------------------------------------------------
getCurrentSlotSimple'
:: SimpleSlottingMode ctx m
=> SlotCount
-> SimpleSlottingStateVar
-> m (Maybe SlotId)
getCurrentSlotSimple' epochSlots var =
currentTimeSlottingSimple
>>= slotFromTimestamp epochSlots
>>= traverse (updateLastSlot var)
getCurrentSlotSimple
:: MonadSimpleSlotting ctx m => SlotCount -> m (Maybe SlotId)
getCurrentSlotSimple epochSlots =
view (lensOf @SimpleSlottingStateVar) >>= getCurrentSlotSimple' epochSlots
getCurrentSlotBlockingSimple'
:: SimpleSlottingMode ctx m
=> SlotCount
-> SimpleSlottingStateVar
-> m SlotId
getCurrentSlotBlockingSimple' epochSlots var = do
(_, nextEpochIndex) <- getCurrentNextEpochIndexM
getCurrentSlotSimple' epochSlots var >>= \case
Just slot -> pure slot
Nothing -> do
waitCurrentEpochEqualsM nextEpochIndex
getCurrentSlotBlockingSimple' epochSlots var
getCurrentSlotBlockingSimple
:: MonadSimpleSlotting ctx m => SlotCount -> m SlotId
getCurrentSlotBlockingSimple epochSlots = view (lensOf @SimpleSlottingStateVar)
>>= getCurrentSlotBlockingSimple' epochSlots
getCurrentSlotInaccurateSimple'
:: SimpleSlottingMode ctx m
=> SlotCount
-> SimpleSlottingStateVar
-> m SlotId
getCurrentSlotInaccurateSimple' epochSlots var =
getCurrentSlotSimple' epochSlots var >>= \case
Just slot -> pure slot
Nothing -> do
lastSlot <- _sssLastSlot <$> readTVarIO var
max lastSlot <$> (currentTimeSlottingSimple >>=
approxSlotUsingOutdated epochSlots)
getCurrentSlotInaccurateSimple
:: MonadSimpleSlotting ctx m => SlotCount -> m SlotId
getCurrentSlotInaccurateSimple epochSlots =
view (lensOf @SimpleSlottingStateVar)
>>= getCurrentSlotInaccurateSimple' epochSlots
currentTimeSlottingSimple :: SimpleSlottingMode ctx m => m Timestamp
currentTimeSlottingSimple = Timestamp <$> currentTime
updateLastSlot :: MonadIO m => SimpleSlottingStateVar -> SlotId -> m SlotId
updateLastSlot var slot = atomically $ do
modifyTVar' var (SimpleSlottingState . max slot . _sssLastSlot)
_sssLastSlot <$> readTVar var
| input-output-hk/pos-haskell-prototype | infra/src/Pos/Infra/Slotting/Impl/Simple.hs | mit | 4,182 | 0 | 14 | 830 | 756 | 393 | 363 | -1 | -1 |
module Text.XkbCommon.ParseDefines
( readHeader, getKeysymDefs, genKeysyms, genKeycodes, genModnames ) where
import Language.Haskell.TH
import Language.Preprocessor.Cpphs
import System.Process
import Data.List
import Data.Maybe (isJust)
import Data.Text (pack, unpack, toLower)
import Control.Arrow
-- this function calls the c preprocessor to find out what the full path to a header file is.
readHeader :: String -> IO (String, String)
readHeader str = do
cpp_out <- readProcess "cpp" [] ("#include<" ++ str ++ ">")
-- parse output:
let headerfile = read $ head $ map ((!! 2) . words) (filter (isInfixOf str) $ lines cpp_out)
header <- readFile headerfile
return (headerfile, header)
getKeysymDefs :: IO [(String,Integer)]
getKeysymDefs = do
(headerFilename, keysyms_header) <- readHeader "xkbcommon/xkbcommon-keysyms.h"
(_, defs) <- macroPassReturningSymTab [] defaultBoolOptions [(newfile headerFilename, keysyms_header)]
let exclude_defs = ["XKB_KEY_VoidSymbol", "XKB_KEY_NoSymbol"]
let filtered_defs = filter (\ (name, _) -> isPrefixOf "XKB_KEY" name && notElem name exclude_defs) defs
let parsed_defs = map (drop 8 *** read) filtered_defs
return parsed_defs
genKeysyms :: IO [Dec]
genKeysyms = do
parsed_defs <- getKeysymDefs
return $ map (\ (name, val) -> ValD (VarP $ mkName ("keysym_" ++ name)) (NormalB (AppE (VarE $ mkName "toKeysym") (AppE (ConE $ mkName "CKeysym") $ LitE (IntegerL val)))) []) parsed_defs
genKeycodes :: IO [Dec]
genKeycodes = do
(headerFilename, keysyms_header) <- readHeader "linux/input.h"
preprocessed <- cppIfdef headerFilename [] [] defaultBoolOptions keysyms_header
(_, defs) <- macroPassReturningSymTab [] defaultBoolOptions preprocessed
let exclude_defs = []
let filtered_defs = filter (\ (name, val) -> isPrefixOf "KEY_" name && notElem name exclude_defs && isJust (maybeRead val :: Maybe Int)) defs
let parsed_defs = map (drop 4 *** read) filtered_defs
return $ map (\ (name, val) -> ValD (VarP $ mkName ("keycode_" ++ lowerCase name)) (NormalB (AppE (ConE $ mkName "CKeycode") $ LitE (IntegerL (8 + val)))) []) parsed_defs
genModnames :: IO [Dec]
-- genKeycodes = return []
genModnames = do
(headerFilename, keysyms_header) <- readHeader "xkbcommon/xkbcommon-names.h"
(_, defs) <- macroPassReturningSymTab [] defaultBoolOptions [(newfile headerFilename, keysyms_header)]
let exclude_defs = []
let mod_defs = filter (\ (name, val) -> isPrefixOf "XKB_MOD_" name && notElem name exclude_defs && isJust (maybeRead val :: Maybe String)) defs
let led_defs = filter (\ (name, val) -> isPrefixOf "XKB_LED_" name && notElem name exclude_defs && isJust (maybeRead val :: Maybe String)) defs
let parsed_mods = map ((\ name -> "modname_" ++ lowerCase (drop 13 name)) *** read) mod_defs
let parsed_leds = map ((\ name -> "ledname_" ++ lowerCase (drop 13 name)) *** read) led_defs
return $ map (\ (name, val) -> ValD (VarP $ mkName name) (NormalB (LitE (StringL val))) []) (parsed_mods ++ parsed_leds)
maybeRead :: Read a => String -> Maybe a
maybeRead s = case reads s of
[(x, "")] -> Just x
_ -> Nothing
lowerCase :: String -> String
lowerCase = unpack . toLower . pack
| tulcod/haskell-xkbcommon | Text/XkbCommon/ParseDefines.hs | mit | 3,198 | 0 | 21 | 544 | 1,200 | 615 | 585 | 52 | 2 |
module SugarScape.Core.Utils
( whenM
, ifThenElse
, ifThenElseM
, orM
, andM
, uncurry3
, uncurry4
, uncurry5
, uncurry6
, flipBoolAtIdx
, removeElemByIdx
, findFirstDiffIdx
, findMinWithIdx
, hammingDistances
) where
import Control.Monad
import Data.List
import Data.Maybe
import Data.List.Split
-------------------------------------------------------------------------------
-- MONADIC UTILITIES
-------------------------------------------------------------------------------
whenM :: Monad m
=> m Bool
-> m ()
-> m ()
whenM mp act = do
p <- mp
when p act
ifThenElse :: Monad m
=> Bool
-> m a
-> m a
-> m a
ifThenElse p trueAction falseAction
= if p then trueAction else falseAction
ifThenElseM :: Monad m
=> m Bool
-> m a
-> m a
-> m a
ifThenElseM test trueAction falseAction
= test >>= \t -> if t then trueAction else falseAction
orM :: Monad m
=> m Bool
-> m Bool
-> m Bool
orM = liftM2 (||)
andM :: Monad m
=> m Bool
-> m Bool
-> m Bool
andM = liftM2 (&&)
uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
uncurry3 f (a, b, c) = f a b c
uncurry4 :: (a -> b -> c -> d -> e) -> (a, b, c, d) -> e
uncurry4 f (a, b, c, d) = f a b c d
uncurry5 :: (a -> b -> c -> d -> e -> f) -> (a, b, c, d, e) -> f
uncurry5 f (a, b, c, d, e) = f a b c d e
uncurry6 :: (a -> b -> c -> d -> e -> f -> g) -> (a, b, c, d, e, f) -> g
uncurry6 fun (a, b, c, d, e, f) = fun a b c d e f
removeElemByIdx :: Int -> [a] -> [a]
removeElemByIdx idx xs = pre ++ tail re
where
(pre, re) = splitAt idx xs
findMinWithIdx :: (Ord a) => [a] -> (a, Int)
findMinWithIdx as = (minA, minAIdx)
where
minA = minimum as
minAIdx = fromJust $ elemIndex minA as
findFirstDiffIdx :: (Eq a) => [a] -> [a] -> Int
findFirstDiffIdx as bs = firstNotEqualIdx
where
notEquals = zipWith (/=) as bs
firstNotEqualIdx = fromJust $ elemIndex True notEquals
flipBoolAtIdx :: Int -> [Bool] -> [Bool]
flipBoolAtIdx idx bs = front ++ (flippedElem : backNoElem)
where
(front, back) = splitAt idx bs -- NOTE: back includes the element with the index
elemAtIdx = bs !! idx
flippedElem = not elemAtIdx
backNoElem = tail back
hammingDistances :: [Bool] -> [Bool] -> [Int]
hammingDistances i d = map (`hammingDistanceAux` d) isubs
where
dLen = length d
isubs = Data.List.Split.divvy dLen 1 i
-- NOTE: both must have the same length
hammingDistanceAux :: [Bool] -> [Bool] -> Int
hammingDistanceAux as bs = length $ filter (==False) equals
where
equals = zipWith (==) as bs
| thalerjonathan/phd | thesis/code/sugarscape/src/SugarScape/Core/Utils.hs | gpl-3.0 | 2,706 | 0 | 12 | 770 | 1,054 | 574 | 480 | 82 | 2 |
module HCharselect.Utils where
parseInt :: String -> Maybe Int
parseInt str = case reads str :: [(Int, String)] of
[(code,rest)] -> if rest == "" then Just code else Nothing
[] -> Nothing
| hpdeifel/hcharselect | HCharselect/Utils.hs | gpl-3.0 | 205 | 0 | 9 | 50 | 83 | 46 | 37 | 5 | 3 |
-- | Pick a random item from a list
{-# LANGUAGE OverloadedStrings #-}
module NumberSix.Handlers.Pick
( handler
) where
--------------------------------------------------------------------------------
import Control.Monad.Trans (liftIO)
import qualified Data.Text as T
--------------------------------------------------------------------------------
import NumberSix.Bang
import NumberSix.Irc
import NumberSix.Util
--------------------------------------------------------------------------------
handler :: UninitializedHandler
handler = makeBangHandler "Pick" ["!pick", "!who"] $
liftIO . randomElement . T.words
| itkovian/number-six | src/NumberSix/Handlers/Pick.hs | bsd-3-clause | 682 | 0 | 9 | 119 | 86 | 54 | 32 | 11 | 1 |
{-# LANGUAGE Haskell2010 #-}
{-# LINE 1 "Control/Concurrent/STM.hs" #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE Safe #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Concurrent.STM
-- Copyright : (c) The University of Glasgow 2004
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable (requires STM)
--
-- Software Transactional Memory: a modular composable concurrency
-- abstraction. See
--
-- * /Composable memory transactions/, by Tim Harris, Simon Marlow, Simon
-- Peyton Jones, and Maurice Herlihy, in /ACM Conference on Principles
-- and Practice of Parallel Programming/ 2005.
-- <http://research.microsoft.com/Users/simonpj/papers/stm/index.htm>
--
-----------------------------------------------------------------------------
module Control.Concurrent.STM (
module Control.Monad.STM,
module Control.Concurrent.STM.TVar,
module Control.Concurrent.STM.TMVar,
module Control.Concurrent.STM.TChan,
module Control.Concurrent.STM.TQueue,
module Control.Concurrent.STM.TBQueue,
module Control.Concurrent.STM.TArray
) where
import Control.Monad.STM
import Control.Concurrent.STM.TVar
import Control.Concurrent.STM.TMVar
import Control.Concurrent.STM.TChan
import Control.Concurrent.STM.TArray
import Control.Concurrent.STM.TQueue
import Control.Concurrent.STM.TBQueue
| phischu/fragnix | tests/packages/scotty/Control.Concurrent.STM.hs | bsd-3-clause | 1,570 | 0 | 5 | 277 | 135 | 104 | 31 | 19 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-|
Functions and combinators to expose functioanlity buiding
on happstack bit is not really specific to any one area
of Hackage.
-}
module Distribution.Server.Framework.HappstackUtils (
remainingPath,
remainingPathString,
mime,
consumeRequestBody,
uriEscape,
showContentType,
-- * Working with headers
alterResponseHeader,
removeResponseHeader,
-- * Response filters
enableGZip,
enableGZip',
enableRange
) where
import Happstack.Server.FileServe
import Happstack.Server.Internal.Compression (encodings)
import Happstack.Server.Monads
import Happstack.Server.Response
import Happstack.Server.Types
import Control.Monad
import Data.Char (toLower)
import Data.Int (Int64)
import System.FilePath.Posix (takeExtension, (</>))
import qualified Codec.Compression.GZip as GZip
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS.C8
import qualified Data.ByteString.Lazy as BS.Lazy
import qualified Data.Map as Map
import qualified Network.URI as URI
import qualified Text.Parsec as Parsec
import qualified Text.Parsec.ByteString as Parsec
-- |Passes a list of remaining path segments in the URL. Does not
-- include the query string. This call only fails if the passed in
-- handler fails.
remainingPath :: Monad m => ([String] -> ServerPartT m a) -> ServerPartT m a
remainingPath handle = do
rq <- askRq
localRq (\newRq -> newRq{rqPaths=[]}) $ handle (rqPaths rq)
-- | Gets the string without altering the request.
remainingPathString :: Monad m => ServerPartT m String
remainingPathString = do
strs <- liftM rqPaths askRq
return $ if null strs then "" else foldr1 (</>) . map uriEscape $ strs
-- This disappeared from happstack in 7.1.7
uriEscape :: String -> String
uriEscape = URI.escapeURIString URI.isAllowedInURI
-- |Returns a mime-type string based on the extension of the passed in
-- file.
mime :: FilePath -> String
mime x =
Map.findWithDefault thedefault (drop 1 (takeExtension x)) mimeTypes'
where
thedefault = "text/plain; charset=utf-8"
mimeTypes' = customMimeTypes `Map.union` mimeTypes
customMimeTypes = Map.fromList
[ ("xhtml", "application/xhtml+xml; charset=utf-8")
, ("html" , "text/html; charset=utf-8")
, ("cabal", "text/plain; charset=utf-8")
, ("hs", "text/plain; charset=utf-8")
, ("lhs", "text/plain; charset=utf-8")
, ("hsc", "text/plain; charset=utf-8")
, ("chs", "text/plain; charset=utf-8")
, ("c", " text/plain; charset=utf-8")
, ("h", " text/plain; charset=utf-8")
]
-- | Get the raw body of a PUT or POST request.
--
-- Note that for performance reasons, this consumes the data and it cannot be
-- called twice.
--
consumeRequestBody :: Happstack m => m BS.Lazy.ByteString
consumeRequestBody = do
mRq <- takeRequestBody =<< askRq
case mRq of
Nothing -> escape $ internalServerError $ toResponse
"consumeRequestBody cannot be called more than once."
Just (Body b) -> return b
-- The following functions are in happstack-server, but not exported. So we
-- copy them here.
-- | Produce the standard string representation of a content-type,
-- e.g. \"text\/html; charset=ISO-8859-1\".
showContentType :: ContentType -> String
showContentType (ContentType x y ps) = x ++ "/" ++ y ++ showParameters ps
-- | Helper for 'showContentType'.
showParameters :: [(String,String)] -> String
showParameters = concatMap f
where f (n,v) = "; " ++ n ++ "=\"" ++ concatMap esc v ++ "\""
esc '\\' = "\\\\"
esc '"' = "\\\""
esc c | c `elem` ['\\','"'] = '\\':[c]
| otherwise = [c]
{-------------------------------------------------------------------------------
Working with headers
-------------------------------------------------------------------------------}
-- | Alter a response header
--
-- If Happstack exported it's @HasHeaders@ type classes we could give a more
-- general implementation of this, but sadly it doesn't.
alterResponseHeader :: String
-> ([BS.ByteString] -> [BS.ByteString])
-> Response -> Response
alterResponseHeader nm f r = r { rsHeaders = aux (rsHeaders r) }
where
aux :: Headers -> Headers
aux = Map.alter f' $ BS.C8.pack (map toLower nm)
f' :: Maybe HeaderPair -> Maybe HeaderPair
f' (Just (HeaderPair nm' vals)) = f'' nm' $ f vals
f' Nothing = f'' (BS.C8.pack nm) $ f []
f'' :: BS.ByteString -> [BS.ByteString] -> Maybe HeaderPair
f'' _ [] = Nothing
f'' nm' vals = Just $ HeaderPair nm' vals
-- | Remove a response header
removeResponseHeader :: String -> Response -> Response
removeResponseHeader nm = alterResponseHeader nm (const [])
{-------------------------------------------------------------------------------
Response filters
-------------------------------------------------------------------------------}
-- | Enable GZip content compression if the client requests it
--
-- This differs from 'compressedResponseFilter' in a number of ways:
--
-- 1. We only allow GZip compression
-- 2. We make the GZip compression level configurable
-- 3. We remove the Content-Length and Content-MD5 headers from the response
-- 4. We change the ETag header and set the corresponding Vary header
enableGZip :: (FilterMonad Response m, WebMonad Response m, ServerMonad m)
=> GZip.CompressParams
-> (BS.ByteString -> BS.ByteString) -- ^ ETag modifier
-> m ()
enableGZip compressParams modifyETag = do
mHeader <- getHeaderM "Accept-Encoding"
case fmap (Parsec.parse encodings "" . BS.C8.unpack) mHeader of
Nothing -> return ()
Just (Left _) -> finishWith $ result 400 "Invalid Accept-Encodings"
Just (Right encs) -> do
if "gzip" `elem` map fst encs
then composeFilter gzipFilter
else return ()
where
gzipFilter :: Response -> Response
gzipFilter r@SendFile{} = r -- Leave files alone
gzipFilter r@Response{} =
chunked
. setHeader "Content-Encoding" "gzip"
. setHeader "Vary" "Accept-Encoding"
. removeResponseHeader "Content-Length"
. removeResponseHeader "Content-MD5"
. alterResponseHeader "ETag" (map modifyETag)
$ r { rsBody = GZip.compressWith compressParams $ rsBody r }
-- | Variation on 'enableGZip' with sensible defaults
--
-- We use the default compression parameters (with the exception of the c
-- compression level), and simply change any existing etag @"foo"@ to
-- @"foo-gzip"@.
enableGZip' :: (FilterMonad Response m, WebMonad Response m, ServerMonad m)
=> Int -- ^ Compression level
-> m ()
enableGZip' compressLevel =
enableGZip compressParams modifyETag
where
modifyETag etag = BS.init etag `BS.append` BS.C8.pack "-gzip\""
compressParams = GZip.defaultCompressParams {
GZip.compressLevel = GZip.compressionLevel compressLevel
}
-- | Enable range requests for this resource
--
-- IMPORTANT: If using both 'enableGZip' and 'enableRange', 'enableRange'
-- MUST be called first.
enableRange :: (FilterMonad Response m, WebMonad Response m, ServerMonad m)
=> m ()
enableRange = do
mRange <- getHeaderM "Range"
case fmap (Parsec.parse parseRange "Range header") mRange of
Nothing -> composeFilter indicateAcceptRanges
Just (Right r) -> composeFilter (rangeFilter r)
Just (Left _) -> finishWith $ result 400 "Invalid Range"
where
-- TODO: We don't check for ill-formed range requests (past the end of the
-- file, 'to' before 'fr', negative, etc.). Checking this here is a little
-- awkward; we'd have to parse the original Content-Length header to find
-- out the original length.
rangeFilter :: (Int64, Int64) -> Response -> Response
rangeFilter (fr, to) r =
setHeader "Content-Length" (show rangeLen)
. setHeaderBS (BS.C8.pack "Content-Range") (contentRange fr to fullLen)
. removeResponseHeader "Content-MD5"
$ r { rsBody = BS.Lazy.take rangeLen $ BS.Lazy.drop fr $ rsBody r
, rsCode = 206
}
where
rangeLen = to - fr + 1
fullLen = getHeader "Content-Length" r
contentRange :: Int64 -> Int64 -> Maybe BS.ByteString -> BS.ByteString
contentRange fr to mFullLen = BS.concat [
BS.C8.pack ("bytes " ++ show fr ++ "-" ++ show to ++ "/")
, case mFullLen of
Nothing -> BS.C8.pack "*"
Just fullLen -> fullLen
]
indicateAcceptRanges :: Response -> Response
indicateAcceptRanges = setHeader "Accept-Ranges" "bytes"
-- TODO: We might have to make this parser more flexible (allow for
-- whitespace, different capitalization, what have you).
parseRange :: Parsec.Parser (Int64, Int64)
parseRange = do
Parsec.string "bytes="
fr <- Parsec.many1 Parsec.digit
Parsec.char '-'
to <- Parsec.many1 Parsec.digit
return (read fr, read to)
| agrafix/hackage-server | Distribution/Server/Framework/HappstackUtils.hs | bsd-3-clause | 9,145 | 0 | 15 | 2,073 | 1,962 | 1,057 | 905 | 148 | 5 |
{-# LANGUAGE CPP, GADTs, RankNTypes #-}
-----------------------------------------------------------------------------
--
-- Cmm utilities.
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
module CmmUtils(
-- CmmType
primRepCmmType, primRepForeignHint,
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 Type ( UnaryType, 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)
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)
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
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
| oldmanmike/ghc | compiler/cmm/CmmUtils.hs | bsd-3-clause | 23,885 | 0 | 18 | 5,074 | 6,118 | 3,219 | 2,899 | 384 | 6 |
{-# LANGUAGE DataKinds, DeriveFunctor, FlexibleInstances, GADTs, KindSignatures, StandaloneDeriving #-}
module T8678 where
data {- kind -} Nat = Z | S Nat
-- GADT in parameter other than the last
data NonStandard :: Nat -> * -> * -> * where
Standard :: a -> NonStandard (S n) a b
Non :: NonStandard n a b -> b -> NonStandard (S n) a b
deriving instance (Show a, Show b) => Show (NonStandard n a b)
deriving instance Functor (NonStandard n a)
| urbanslug/ghc | testsuite/tests/deriving/should_compile/T8678.hs | bsd-3-clause | 453 | 0 | 10 | 93 | 142 | 76 | 66 | 8 | 0 |
{-# LANGUAGE UndecidableInstances, FlexibleInstances #-}
module ContextStack1 where
class Cls a where meth :: a
instance Cls [a] => Cls a
t :: ()
t = meth
| forked-upstream-packages-for-ghcjs/ghc | testsuite/tests/typecheck/should_fail/ContextStack1.hs | bsd-3-clause | 160 | 0 | 7 | 32 | 48 | 26 | 22 | -1 | -1 |
module Main where
import Text.BraVal
import Control.Monad.Trans.Writer
import Text.BraVal.Report
main = interact (report . parser . (lexer :: String -> [Symbol]))
| kindaro/BraVal | src/Main.hs | isc | 165 | 0 | 10 | 23 | 54 | 33 | 21 | 5 | 1 |
{-# LANGUAGE CPP #-}
module Application (rippleInvoiceForm, sendRippleInvoice, classicInvoiceForm, sendClassicInvoice) where
import Prelude ()
import BasicPrelude
import Control.Error (readMay)
import Data.Either.Combinators (leftToMaybe, rightToMaybe)
import Data.Base58Address (RippleAddress)
import qualified Ripple.Federation as Federation
import qualified Data.Text as T
import Network.Wai (Application, Request(..))
import Network.HTTP.Types (ok200, seeOther303)
import Network.Wai.Util (stringHeaders, textBuilder, redirect', responseToMailPart)
import Network.Mail.Mime (Address(..), Mail(..), renderSendMail)
import Network.Wai.Digestive (queryFormEnv, bodyFormEnv_)
import SimpleForm.Combined (label, Label(..), wdef, vdef, ShowRead(..), unShowRead, required)
import SimpleForm.Render (errors)
import SimpleForm.Render.XHTML5 (render)
import SimpleForm.Digestive.Combined (SimpleForm', input, input_, getSimpleForm, postSimpleForm)
import SimpleForm.Digestive.Validation (underRef)
import SimpleForm (textarea)
import Text.Digestive (validateM, Result(Success, Error))
import Text.Blaze (toMarkup)
import Network.URI (URI(..), isUnescapedInURIComponent, escapeURIString)
import Network.URI.Partial (relativeTo)
import Records
import MustacheTemplates
#include "PathHelpers.hs"
s :: (IsString s) => String -> s
s = fromString
Just [htmlCT] = stringHeaders [("Content-Type", "text/html; charset=utf-8")]
htmlEscape :: String -> String
htmlEscape = concatMap escChar
where
escChar '&' = "&"
escChar '"' = """
escChar '<' = "<"
escChar '>' = ">"
escChar c = [c]
lbl :: String -> Maybe Label
lbl = Just . Label . s
invoiceForm :: (Functor m, MonadIO m) => Bool -> SimpleForm' m Invoice
invoiceForm classic = do
from' <- input_ (s"from") (Just . from)
to' <- input_ (s"to") (Just . to)
ripple' <- uncurry (input (s"ripple") (Just . fmap show . ripple)) $
if classic then
((wdef . (>>= leftToMaybe), fmap Left vdef),
mempty {label = lbl"Your username"})
else
((wdef . (>>= rightToMaybe), fmap Right vdef),
mempty {label = lbl"Your Ripple address"})
amount' <- input_ (s"amount") (Just . amount)
currency' <- input_ (s"currency") (Just . currency)
message' <- input (s"message") (Just . message) (textarea,vdef)
(mempty {required = False})
return $ Invoice <$> from' <*> to' <*> (underRef (validateM maybeResolve) ripple') <*> amount' <*> currency' <*> message'
where
maybeResolve (Left user) = return $ Success (Left user)
maybeResolve (Right adr) = case readMay (T.unpack adr) of
Just r -> return (Success (Right r))
_ -> case (T.unpack adr, readMay (T.unpack adr)) of
(_, Just alias) -> do
v <- liftIO $ Federation.resolve alias
case v of
Left (Federation.Error _ msg) -> return $ Error $ toMarkup msg
Right (Federation.ResolvedAlias _ r Nothing) -> return $ Success (Right r)
Right (Federation.ResolvedAlias _ r _) ->
return $ Error $ toMarkup "Destination tags not supported yet"
('~':rippleName, _) -> maybeResolve (Right $ T.pack $ rippleName ++ "@ripple.com")
(rippleName, _) -> maybeResolve (Right $ T.pack $ rippleName ++ "@ripple.com")
showInvoiceForm :: Bool -> URI -> Application
showInvoiceForm classic root (Request {queryString = qs}) = do
(form,_) <- postSimpleForm hideErr (return $ queryFormEnv qs) (invoiceForm classic)
textBuilder ok200 [htmlCT] $ viewHome htmlEscape (Home form path classic)
where
path
| classic = sendClassicInvoicePath `relativeTo` root
| otherwise = sendRippleInvoicePath `relativeTo` root
hideErr opt = render (opt {errors = []})
rippleInvoiceForm :: URI -> Application
rippleInvoiceForm = showInvoiceForm False
classicInvoiceForm :: URI -> Application
classicInvoiceForm = showInvoiceForm True
sendInvoice :: Bool -> URI -> Application
sendInvoice classic root req = do
(form,minv) <- postSimpleForm render (bodyFormEnv_ req) (invoiceForm classic)
case minv of
Just invoice -> do
mailBody <- responseToMailPart True =<< textBuilder ok200 []
(template (escapeURIString isUnescapedInURIComponent) invoice)
liftIO $ renderSendMail Mail {
mailFrom = emailToAddress $ from invoice,
mailTo = [emailToAddress $ to invoice],
mailCc = [], mailBcc = [],
mailHeaders = [(s"Subject", formatSubject $ message invoice)],
mailParts = [[mailBody]]
}
redirect' seeOther303 [] home
Nothing ->
textBuilder ok200 [htmlCT] $ viewHome htmlEscape (Home form path classic)
where
template
| classic = viewClassicEmail
| otherwise = viewEmail
emailToAddress = Address Nothing . show
formatSubject msg
| T.null msg = s"Ripple Invoice"
| otherwise = s"Ripple Invoice \"" ++ T.take 30 msg ++ s"\""
path
| classic = sendClassicInvoicePath `relativeTo` root
| otherwise = sendRippleInvoicePath `relativeTo` root
home
| classic = classicInvoiceFormPath `relativeTo` root
| otherwise = rippleInvoiceFormPath `relativeTo` root
sendRippleInvoice :: URI -> Application
sendRippleInvoice = sendInvoice False
sendClassicInvoice :: URI -> Application
sendClassicInvoice = sendInvoice True
| singpolyma/RippleUnion-Invoices | Application.hs | isc | 5,123 | 32 | 21 | 852 | 1,794 | 959 | 835 | 111 | 8 |
{-# LANGUAGE NamedFieldPuns, ScopedTypeVariables, FlexibleContexts, FlexibleInstances, UndecidableInstances, GeneralizedNewtypeDeriving #-}
{-
Copyright (C) 2012-2013 Jimmy Liang, Kacper Bak <http://gsd.uwaterloo.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-}
module Language.Clafer.Intermediate.ResolverType (resolveTModule, intersects, (+++), fromUnionType, unionType) where
import Prelude hiding (exp)
import Language.ClaferT
import Language.Clafer.Common
import Language.Clafer.Intermediate.Analysis
import Language.Clafer.Intermediate.Intclafer hiding (uid)
import qualified Language.Clafer.Intermediate.Intclafer as I
import Control.Applicative
import Control.Monad.Error
import Control.Monad.List
import Control.Monad.Reader
import Data.Either
import Data.List
import Data.Maybe
type TypeDecls = [(String, IType)]
data TypeInfo = TypeInfo {iTypeDecls::TypeDecls, iInfo::Info, iCurThis::SClafer, iCurPath::Maybe IType}
newtype TypeAnalysis a = TypeAnalysis (ReaderT TypeInfo (Either ClaferSErr) a)
deriving (MonadError ClaferSErr, Monad, Functor, MonadReader TypeInfo)
typeOfUid :: MonadTypeAnalysis m => String -> m IType
typeOfUid uid = (fromMaybe (TClafer [uid]) . lookup uid) <$> typeDecls
class MonadAnalysis m => MonadTypeAnalysis m where
-- What "this" refers to
curThis :: m SClafer
localCurThis :: SClafer -> m a -> m a
-- The next path is a child of curPath (or Nothing)
curPath :: m (Maybe IType)
localCurPath :: IType -> m a -> m a
-- Extra declarations
typeDecls :: m TypeDecls
localDecls :: TypeDecls -> m a -> m a
instance MonadTypeAnalysis TypeAnalysis where
curThis = TypeAnalysis $ asks iCurThis
localCurThis newThis (TypeAnalysis d) =
TypeAnalysis $ local setCurThis d
where
setCurThis t = t{iCurThis = newThis}
curPath = TypeAnalysis $ asks iCurPath
localCurPath newPath (TypeAnalysis d) =
TypeAnalysis $ local setCurPath d
where
setCurPath t = t{iCurPath = Just newPath}
typeDecls = TypeAnalysis $ asks iTypeDecls
localDecls extra (TypeAnalysis d) =
TypeAnalysis $ local addTypeDecls d
where
addTypeDecls t@TypeInfo{iTypeDecls = c} = t{iTypeDecls = extra ++ c}
instance MonadTypeAnalysis m => MonadTypeAnalysis (ListT m) where
curThis = lift $ curThis
localCurThis = mapListT . localCurThis
curPath = lift $ curPath
localCurPath = mapListT . localCurPath
typeDecls = lift typeDecls
localDecls = mapListT . localDecls
instance MonadTypeAnalysis m => MonadTypeAnalysis (ErrorT ClaferSErr m) where
curThis = lift $ curThis
localCurThis = mapErrorT . localCurThis
curPath = lift $ curPath
localCurPath = mapErrorT . localCurPath
typeDecls = lift typeDecls
localDecls = mapErrorT . localDecls
instance MonadAnalysis TypeAnalysis where
clafers = asks (sclafers . iInfo)
withClafers cs r =
local setInfo r
where
setInfo t = t{iInfo = Info cs}
-- | Type inference and checking
runTypeAnalysis :: TypeAnalysis a -> IModule -> Either ClaferSErr a
runTypeAnalysis (TypeAnalysis tc) imodule = runReaderT tc $ TypeInfo [] (gatherInfo imodule) undefined Nothing
unionType :: IType -> [String]
unionType TString = ["string"]
unionType TReal = ["real"]
unionType TInteger = ["integer"]
unionType TBoolean = ["boolean"]
unionType (TClafer u) = u
(+++) :: IType -> IType -> IType
t1 +++ t2 = fromJust $ fromUnionType $ unionType t1 ++ unionType t2
fromUnionType :: [String] -> Maybe IType
fromUnionType u =
case sort $ nub $ u of
["string"] -> return TString
["real"] -> return TReal
["integer"] -> return TInteger
["int"] -> return TInteger
["boolean"] -> return TBoolean
[] -> Nothing
u' -> return $ TClafer u'
closure :: MonadAnalysis m => [String] -> m [String]
closure ut = concat <$> mapM hierarchy ut
intersection :: MonadAnalysis m => IType -> IType -> m (Maybe IType)
intersection t1 t2 =
do
h1 <- mapM hierarchy $ unionType t1
h2 <- mapM hierarchy $ unionType t2
let ut = catMaybes [contains (head u1) u2 `mplus` contains (head u2) u1 | u1 <- h1, u2 <- h2]
return $ fromUnionType ut
where
contains i is = if i `elem` is then Just i else Nothing
intersects :: MonadAnalysis m => IType -> IType -> m Bool
intersects t1 t2 = isJust <$> intersection t1 t2
numeric :: IType -> Bool
numeric TReal = True
numeric TInteger = True
numeric _ = False
coerce :: IType -> IType -> IType
coerce TReal TReal = TReal
coerce TReal TInteger = TReal
coerce TInteger TReal = TReal
coerce TInteger TInteger = TInteger
coerce x y = error $ "Not numeric: " ++ show x ++ ", " ++ show y
str :: IType -> String
str t =
case unionType t of
[t'] -> t'
ts -> "[" ++ intercalate "," ts ++ "]"
getIfThenElseType :: MonadAnalysis m => IType -> IType -> m (Maybe IType)
-- the function is similar to 'intersection', but takes into account more ancestors to be able to combine
-- clafers of different types, but with a common ancestor:
-- Inputs:
-- t1 is of type B
-- t2 is of type C
-- B : A
-- C : A
-- Outputs:
-- the resulting type is: A, and the type combination is valid
getIfThenElseType t1 t2 =
do
h1 <- mapM hierarchy $ unionType t1
h2 <- mapM hierarchy $ unionType t2
let ut = catMaybes [commonHierarchy u1 u2 | u1 <- h1, u2 <- h2]
return $ fromUnionType ut
where
commonHierarchy h1 h2 = filterClafer $ commonHierarchy' (reverse h1) (reverse h2) Nothing
commonHierarchy' (x:xs) (y:ys) accumulator =
if (x == y)
then
if (null xs || null ys)
then Just x
else commonHierarchy' xs ys $ Just x
else accumulator
commonHierarchy' _ _ _ = error "Function commonHierarchy' from ResolverType expects two non empty lists but was given at least one empty list!" -- Should never happen
filterClafer value =
if (value == Just "clafer") then Nothing else value
resolveTModule :: (IModule, GEnv) -> Either ClaferSErr IModule
resolveTModule (imodule, _) =
case runTypeAnalysis (analysis $ _mDecls imodule) imodule of
Right mDecls' -> return imodule{_mDecls = mDecls'}
Left err -> throwError err
where
analysis decls1 = mapM (resolveTElement $ rootUid) decls1
resolveTElement :: String -> IElement -> TypeAnalysis IElement
resolveTElement _ (IEClafer iclafer) =
do
elements' <- mapM (resolveTElement $ I._uid iclafer) (_elements iclafer)
return $ IEClafer $ iclafer{_elements = elements'}
resolveTElement parent' (IEConstraint _isHard _pexp) =
IEConstraint _isHard <$> (testBoolean =<< resolveTConstraint parent' _pexp)
where
testBoolean pexp' =
do
unless (typeOf pexp' == TBoolean) $
throwError $ SemanticErr (_inPos pexp') ("Cannot construct constraint on type '" ++ str (typeOf pexp') ++ "'")
return pexp'
resolveTElement parent' (IEGoal isMaximize' pexp') =
IEGoal isMaximize' <$> resolveTConstraint parent' pexp'
resolveTConstraint :: String -> PExp -> TypeAnalysis PExp
resolveTConstraint curThis' constraint =
do
curThis'' <- claferWithUid curThis'
head <$> (localCurThis curThis'' $ (resolveTPExp constraint :: TypeAnalysis [PExp]))
resolveTPExp :: PExp -> TypeAnalysis [PExp]
resolveTPExp p =
do
x <- resolveTPExp' p
case partitionEithers x of
(f:_, []) -> throwError f -- Case 1: Only fails. Complain about the first one.
([], []) -> error "No results but no errors." -- Case 2: No success and no error message. Bug.
(_, xs) -> return xs -- Case 3: At least one success.
resolveTPExp' :: PExp -> TypeAnalysis [Either ClaferSErr PExp]
resolveTPExp' p@PExp{_inPos, _exp = IClaferId{_sident = "ref"}} =
runListT $ runErrorT $ do
curPath' <- curPath
case curPath' of
Just curPath'' -> do
ut <- closure $ unionType curPath''
t <- runListT $ refOf =<< foreachM ut
case fromUnionType t of
Just t' -> return $ p `withType` t'
Nothing -> throwError $ SemanticErr _inPos ("Cannot ref from type '" ++ str curPath'' ++ "'")
Nothing -> throwError $ SemanticErr _inPos ("Cannot ref at the start of a path")
resolveTPExp' p@PExp{_inPos, _exp = IClaferId{_sident = "parent"}} =
runListT $ runErrorT $ do
curPath' <- curPath
case curPath' of
Just curPath'' -> do
parent' <- fromUnionType <$> runListT (parentOf =<< liftList (unionType curPath''))
when (isNothing parent') $
throwError $ SemanticErr _inPos "Cannot parent from root"
let result = p `withType` fromJust parent'
return result -- Case 1: Use the sident
<++>
addRef result -- Case 2: Dereference the sident 1..* times
Nothing -> throwError $ SemanticErr _inPos "Cannot parent at the start of a path"
resolveTPExp' p@PExp{_exp = IClaferId{_sident = "integer"}} = runListT $ runErrorT $ return $ p `withType` TInteger
resolveTPExp' p@PExp{_inPos, _exp = IClaferId{_sident}} =
runListT $ runErrorT $ do
curPath' <- curPath
sident' <- if _sident == "this" then uid <$> curThis else return _sident
when (isJust curPath') $ do
c <- mapM (isChild sident') $ unionType $ fromJust curPath'
unless (or c) $ throwError $ SemanticErr _inPos ("'" ++ sident' ++ "' is not a child of type '" ++ str (fromJust curPath') ++ "'")
result <- (p `withType`) <$> typeOfUid sident'
return result -- Case 1: Use the sident
<++>
addRef result -- Case 2: Dereference the sident 1..* times
resolveTPExp' p@PExp{_inPos, _exp} =
runListT $ runErrorT $ do
(iType', exp') <- ErrorT $ ListT $ resolveTExp _exp
return p{_iType = Just iType', _exp = exp'}
where
resolveTExp :: IExp -> TypeAnalysis [Either ClaferSErr (IType, IExp)]
resolveTExp e@(IInt _) = runListT $ runErrorT $ return (TInteger, e)
resolveTExp e@(IDouble _) = runListT $ runErrorT $ return (TReal, e)
resolveTExp e@(IStr _) = runListT $ runErrorT $ return (TString, e)
resolveTExp e@IFunExp {_op, _exps = [arg]} =
runListT $ runErrorT $ do
arg' <- lift $ ListT $ resolveTPExp arg
let t = typeOf arg'
let test c =
unless c $
throwError $ SemanticErr _inPos ("Function '" ++ _op ++ "' cannot be performed on " ++ _op ++ " '" ++ str t ++ "'")
let result
| _op == iNot = test (t == TBoolean) >> return TBoolean
| _op == iCSet = return TInteger
| _op == iSumSet = test (t == TInteger) >> return TInteger
| _op `elem` [iMin, iGMin, iGMax] = test (numeric t) >> return t
| otherwise = error $ "Unknown op '" ++ _op ++ "'"
result' <- result
return (result', e{_exps = [arg']})
resolveTExp e@IFunExp {_op = ".", _exps = [arg1, arg2]} =
do
runListT $ runErrorT $ do
arg1' <- lift $ ListT $ resolveTPExp arg1
localCurPath (typeOf arg1') $ do
arg2' <- liftError $ lift $ ListT $ resolveTPExp arg2
return (fromJust $ _iType arg2', e{_exps = [arg1', arg2']})
resolveTExp e@IFunExp {_op = "++", _exps = [arg1, arg2]} =
do
arg1s' <- resolveTPExp arg1
arg2s' <- resolveTPExp arg2
let union' a b = typeOf a +++ typeOf b
return $ [return (union' arg1' arg2', e{_exps = [arg1', arg2']}) | (arg1', arg2') <- sortBy (comparing $ length . unionType . uncurry union') $ liftM2 (,) arg1s' arg2s']
resolveTExp e@IFunExp {_op, _exps = [arg1, arg2]} =
runListT $ runErrorT $ do
arg1' <- lift $ ListT $ resolveTPExp arg1
arg2' <- lift $ ListT $ resolveTPExp arg2
let t1 = typeOf arg1'
let t2 = typeOf arg2'
let testIntersect e1 e2 =
do
it <- intersection e1 e2
case it of
Just it' -> return it'
Nothing -> throwError $ SemanticErr _inPos ("Function '" ++ _op ++ "' cannot be performed on '" ++ str t1 ++ "' " ++ _op ++ " '" ++ str t2 ++ "'")
let testNotSame e1 e2 =
when (e1 `sameAs` e2) $
throwError $ SemanticErr _inPos ("Function '" ++ _op ++ "' is redundant because the two subexpressions are always equivalent")
let test c =
unless c $
throwError $ SemanticErr _inPos ("Function '" ++ _op ++ "' cannot be performed on '" ++ str t1 ++ "' " ++ _op ++ " '" ++ str t2 ++ "'")
let result
| _op `elem` logBinOps = test (t1 == TBoolean && t2 == TBoolean) >> return TBoolean
| _op `elem` [iLt, iGt, iLte, iGte] = test (numeric t1 && numeric t2) >> return TBoolean
| _op `elem` [iEq, iNeq] = testNotSame arg1' arg2' >> testIntersect t1 t2 >> return TBoolean
| _op == iDifference = testNotSame arg1' arg2' >> testIntersect t1 t2 >> return t1
| _op == iIntersection = testNotSame arg1' arg2' >> testIntersect t1 t2
| _op `elem` [iDomain, iRange] = testIntersect t1 t2
| _op `elem` relSetBinOps = testIntersect t1 t2 >> return TBoolean
| _op `elem` [iSub, iMul, iDiv] = test (numeric t1 && numeric t2) >> return (coerce t1 t2)
| _op == iPlus =
(test (t1 == TString && t2 == TString) >> return TString) -- Case 1: String concatenation
`catchError`
const (test (numeric t1 && numeric t2) >> return (coerce t1 t2)) -- Case 2: Addition
| otherwise = error $ "Unknown op: " ++ show e
result' <- result
return (result', e{_exps = [arg1', arg2']})
resolveTExp e@(IFunExp "=>else" [arg1, arg2, arg3]) =
runListT $ runErrorT $ do
arg1' <- lift $ ListT $ resolveTPExp arg1
arg2' <- lift $ ListT $ resolveTPExp arg2
arg3' <- lift $ ListT $ resolveTPExp arg3
let t1 = typeOf arg1'
let t2 = typeOf arg2'
let t3 = typeOf arg3'
-- unless (False) $
-- throwError $ SemanticErr inPos ("The types are: '" ++ str t2 ++ "' and '" ++ str t3 ++ "'")
unless (t1 == TBoolean) $
throwError $ SemanticErr _inPos ("Function 'if/else' cannot be performed on 'if' " ++ str t1 ++ " 'then' " ++ str t2 ++ " 'else' " ++ str t3)
it <- getIfThenElseType t2 t3
t <- case it of
Just it' -> return it'
Nothing -> throwError $ SemanticErr _inPos ("Function '=>else' cannot be performed on if '" ++ str t1 ++ "' then '" ++ str t2 ++ "' else '" ++ str t3 ++ "'")
return (t, e{_exps = [arg1', arg2', arg3']})
resolveTExp e@IDeclPExp{_oDecls, _bpexp} =
runListT $ runErrorT $ do
oDecls' <- mapM resolveTDecl _oDecls
let extraDecls = [(decl, typeOf $ _body oDecl) | oDecl <- oDecls', decl <- _decls oDecl]
localDecls extraDecls $ do
bpexp' <- liftError $ lift $ ListT $ resolveTPExp _bpexp
return $ (TBoolean, e{_oDecls = oDecls', _bpexp = bpexp'})
where
resolveTDecl d@IDecl{_body} =
do
body' <- lift $ ListT $ resolveTPExp _body
return $ d{_body = body'}
resolveTExp e = error $ "Unknown iexp: " ++ show e
-- Adds "refs" at the end, effectively dereferencing Clafers when needed.
addRef :: PExp -> ErrorT ClaferSErr (ListT TypeAnalysis) PExp
addRef pexp =
do
localCurPath (typeOf pexp) $ do
deref <- (ErrorT $ ListT $ resolveTPExp' $ newPExp $ IClaferId "" "ref" False) `catchError` const (lift mzero)
let result = (newPExp $ IFunExp "." [pexp, deref]) `withType` typeOf deref
return result <++> addRef result
where
newPExp = PExp Nothing "" $ _inPos pexp
typeOf :: PExp -> IType
typeOf pexp = fromMaybe (error "No type") $ _iType pexp
withType :: PExp -> IType -> PExp
withType p t = p{_iType = Just t}
(<++>) :: (Error e, MonadPlus m) => ErrorT e m a -> ErrorT e m a -> ErrorT e m a
(ErrorT a) <++> (ErrorT b) = ErrorT $ a `mplus` b
liftError :: (MonadError e m, Error e) => ErrorT e m a -> ErrorT e m a
liftError e =
liftCatch catchError e throwError
where
liftCatch catchError' m h = ErrorT $ runErrorT m `catchError'` (runErrorT . h)
| juodaspaulius/clafer-old-customBNFC | src/Language/Clafer/Intermediate/ResolverType.hs | mit | 17,030 | 6 | 30 | 4,192 | 5,340 | 2,687 | 2,653 | 309 | 16 |
so = foldl (+) 0 (replicate 10000000 1)
-- foldl (+) 0 [1,2,3] =
-- foldl (+) (0 + 1) [2,3] =
-- foldl (+) (( 0 + 1) + 2) [3] =
-- foldl (+) ((( 0 + 1) + 2) + 3) [] =
-- (( 0 + 1) + 2) + 3 =
-- (1 + 2) + 3 =
-- 3 + 3 =
-- 6
-- foldl' (+) 0 [1,2,3] =
-- foldl' (+) 1 [2,3] =
-- foldl' (+) 3 [3] =
-- foldl' (+) 6 [] =
-- 6
| v0lkan/learning-haskell | session-archive/012-strict-folds.hs | mit | 336 | 0 | 7 | 110 | 36 | 25 | 11 | 1 | 1 |
module Text.Kindle.Clippings.Reader
( readClipping
, readClippings
) where
import Control.Applicative ((<$>), (<*>), (*>), (<*), (<|>), liftA2)
import Control.Monad (join)
import Data.Functor.Infix ((<$$>))
import Data.List (find)
import Data.Maybe (isJust, fromMaybe)
import Data.Time.LocalTime (LocalTime)
import Data.Time.Parse (strptime)
import Text.Kindle.Clippings.Types (Clipping(..),Interval(..),Document(..),Position(..),Content(..))
import Text.Parsec (many1, digit, string, oneOf, try, char, manyTill, anyToken, lookAhead, many, noneOf, between)
import Text.Parsec.String (Parser)
import Text.Parsec.Combinator.Extras (optional, but, tryString, stringCI)
data Tree = Leaf String | Node [Tree]
brackets :: Parser Tree
brackets = Node <$> between
(char '(') (char ')')
(many (brackets <|> (Leaf <$> many1 (noneOf "()"))))
instance Show Tree where
show (Leaf x) = x
show (Node xs) = "(" ++ concatMap show xs ++ ")"
node :: a -> ([Tree] -> a) -> (Tree -> a)
node _ fun (Node xs) = fun xs
node def _ _ = def
-- N.B.
-- The document parser (i.e. 'author' + 'title') is known to fail where
-- the author component includes unmatched parentheses, however this case
-- appears ambiguous in the grammar.
space :: Parser String
space = string " "
eol :: Parser String
eol = many1 $ oneOf "\n\r"
readTitle :: Parser String
readTitle = manyTill anyToken (lookAhead . try $ space *> (try brackets <|> (Leaf <$> space)) *> eol)
readAuthor :: Parser String
readAuthor = node (error "The impossible happened!") (concatMap show) <$> brackets
readContentType :: Parser String
readContentType = (tryString "- Your " <|> string "- ")
*> but " "
<* (tryString " on " <|> tryString " at " <|> many1 (char ' '))
parseSingletonInterval :: Parser Interval
parseSingletonInterval = Singleton . read <$> many1 digit
-- Early Kindle models sometimes described intervals of locations
-- with the prefix of the second part removed; e.g. ("1109", "12").
-- this padding will normalise this to (1109, 1112).
normaliseRegion :: String -> String -> (Int, Int)
normaliseRegion s0 s1 = (read s0, read $ take (length s0 - length s1) s0++s1)
parseProperInterval :: Parser Interval
parseProperInterval = (uncurry Proper <$$> normaliseRegion) <$> many1 digit <*> (char '-' *> many1 digit)
parseInterval :: Parser Interval
parseInterval = try parseProperInterval <|> parseSingletonInterval
readPage :: Parser Interval
readPage = stringCI "Page " *> parseInterval <* string " | "
readLocation :: Parser Interval
readLocation = (tryString "Loc. " <|> stringCI "Location ")
*> parseInterval
<* many1 (oneOf " |")
parseDate :: String -> LocalTime
parseDate raw = fromMaybe defaultLocalTime . join . find isJust . map (fst <$$> flip strptime raw) $
[ "%A, %d %B %y %X" -- Thursday, 01 January 70 12:00:00 AM
, "%A, %B %d, %Y %r" -- Thursday, January 01, 1970 12:00:00 AM
]
defaultLocalTime :: LocalTime
Just (defaultLocalTime, _) = strptime "" ""
readDate :: Parser LocalTime
readDate = string "Added on " *> (parseDate <$> but "\n\r")
eor :: Parser String
eor = string "=========="
readContent :: Parser String
readContent = manyTill anyToken (try $ many1 (oneOf "\n\r ") *> eor)
readClipping :: Parser (Maybe Clipping)
readClipping = clipping
<$> liftA2 Document readTitle (many1 space *> optional readAuthor) <* eol
<*> readContentType
<*> liftA2 Position (optional readPage) (optional readLocation)
<*> readDate <* eol
<*> readContent <* eol
clipping :: Document -> String -> Position -> LocalTime -> String -> Maybe Clipping
clipping d t p l c
| (==) t "Highlight" = Just . Clipping d p l $ Highlight c
| (==) t "Note" = Just . Clipping d p l $ Annotation c
| (==) t "Bookmark" = Just . Clipping d p l $ Bookmark
| otherwise = Nothing
readClippings :: Parser [Maybe Clipping]
readClippings = many1 readClipping
| fmap/clippings | src/Text/Kindle/Clippings/Reader.hs | mit | 3,943 | 0 | 16 | 757 | 1,283 | 685 | 598 | 78 | 1 |
import Data.Bool
mapBool :: (a -> b) -> (a -> b) -> (a -> Bool) -> [a] -> [b]
mapBool fFalse fTrue fCond xs =
map (\x -> bool (fFalse x) (fTrue x) (fCond x)) xs | candu/haskellbook | ch9/mapBool.hs | mit | 163 | 0 | 10 | 38 | 106 | 56 | 50 | 4 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Takeaway.Data.Acid.ID_v0 where
import Data.IntSet (IntSet)
import Data.SafeCopy
import Data.Typeable
type ID = Int
data IdManager = IdManager
{ allIds :: IntSet
}
deriving (Show, Typeable)
deriveSafeCopy 0 'base ''IdManager
| mcmaniac/takeaway | src/Takeaway/Data/Acid/ID_v0.hs | mit | 311 | 0 | 8 | 49 | 75 | 45 | 30 | 11 | 0 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGGlyphRefElement
(js_setGlyphRef, setGlyphRef, js_getGlyphRef, getGlyphRef,
js_setFormat, setFormat, js_getFormat, getFormat, js_setX, setX,
js_getX, getX, js_setY, setY, js_getY, getY, js_setDx, setDx,
js_getDx, getDx, js_setDy, setDy, js_getDy, getDy,
SVGGlyphRefElement, castToSVGGlyphRefElement,
gTypeSVGGlyphRefElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe "$1[\"glyphRef\"] = $2;"
js_setGlyphRef :: JSRef SVGGlyphRefElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGGlyphRefElement.glyphRef Mozilla SVGGlyphRefElement.glyphRef documentation>
setGlyphRef ::
(MonadIO m, ToJSString val) => SVGGlyphRefElement -> val -> m ()
setGlyphRef self val
= liftIO
(js_setGlyphRef (unSVGGlyphRefElement self) (toJSString val))
foreign import javascript unsafe "$1[\"glyphRef\"]" js_getGlyphRef
:: JSRef SVGGlyphRefElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGGlyphRefElement.glyphRef Mozilla SVGGlyphRefElement.glyphRef documentation>
getGlyphRef ::
(MonadIO m, FromJSString result) => SVGGlyphRefElement -> m result
getGlyphRef self
= liftIO
(fromJSString <$> (js_getGlyphRef (unSVGGlyphRefElement self)))
foreign import javascript unsafe "$1[\"format\"] = $2;"
js_setFormat :: JSRef SVGGlyphRefElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGGlyphRefElement.format Mozilla SVGGlyphRefElement.format documentation>
setFormat ::
(MonadIO m, ToJSString val) => SVGGlyphRefElement -> val -> m ()
setFormat self val
= liftIO
(js_setFormat (unSVGGlyphRefElement self) (toJSString val))
foreign import javascript unsafe "$1[\"format\"]" js_getFormat ::
JSRef SVGGlyphRefElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGGlyphRefElement.format Mozilla SVGGlyphRefElement.format documentation>
getFormat ::
(MonadIO m, FromJSString result) => SVGGlyphRefElement -> m result
getFormat self
= liftIO
(fromJSString <$> (js_getFormat (unSVGGlyphRefElement self)))
foreign import javascript unsafe "$1[\"x\"] = $2;" js_setX ::
JSRef SVGGlyphRefElement -> Float -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGGlyphRefElement.x Mozilla SVGGlyphRefElement.x documentation>
setX :: (MonadIO m) => SVGGlyphRefElement -> Float -> m ()
setX self val = liftIO (js_setX (unSVGGlyphRefElement self) val)
foreign import javascript unsafe "$1[\"x\"]" js_getX ::
JSRef SVGGlyphRefElement -> IO Float
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGGlyphRefElement.x Mozilla SVGGlyphRefElement.x documentation>
getX :: (MonadIO m) => SVGGlyphRefElement -> m Float
getX self = liftIO (js_getX (unSVGGlyphRefElement self))
foreign import javascript unsafe "$1[\"y\"] = $2;" js_setY ::
JSRef SVGGlyphRefElement -> Float -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGGlyphRefElement.y Mozilla SVGGlyphRefElement.y documentation>
setY :: (MonadIO m) => SVGGlyphRefElement -> Float -> m ()
setY self val = liftIO (js_setY (unSVGGlyphRefElement self) val)
foreign import javascript unsafe "$1[\"y\"]" js_getY ::
JSRef SVGGlyphRefElement -> IO Float
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGGlyphRefElement.y Mozilla SVGGlyphRefElement.y documentation>
getY :: (MonadIO m) => SVGGlyphRefElement -> m Float
getY self = liftIO (js_getY (unSVGGlyphRefElement self))
foreign import javascript unsafe "$1[\"dx\"] = $2;" js_setDx ::
JSRef SVGGlyphRefElement -> Float -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGGlyphRefElement.dx Mozilla SVGGlyphRefElement.dx documentation>
setDx :: (MonadIO m) => SVGGlyphRefElement -> Float -> m ()
setDx self val = liftIO (js_setDx (unSVGGlyphRefElement self) val)
foreign import javascript unsafe "$1[\"dx\"]" js_getDx ::
JSRef SVGGlyphRefElement -> IO Float
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGGlyphRefElement.dx Mozilla SVGGlyphRefElement.dx documentation>
getDx :: (MonadIO m) => SVGGlyphRefElement -> m Float
getDx self = liftIO (js_getDx (unSVGGlyphRefElement self))
foreign import javascript unsafe "$1[\"dy\"] = $2;" js_setDy ::
JSRef SVGGlyphRefElement -> Float -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGGlyphRefElement.dy Mozilla SVGGlyphRefElement.dy documentation>
setDy :: (MonadIO m) => SVGGlyphRefElement -> Float -> m ()
setDy self val = liftIO (js_setDy (unSVGGlyphRefElement self) val)
foreign import javascript unsafe "$1[\"dy\"]" js_getDy ::
JSRef SVGGlyphRefElement -> IO Float
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGGlyphRefElement.dy Mozilla SVGGlyphRefElement.dy documentation>
getDy :: (MonadIO m) => SVGGlyphRefElement -> m Float
getDy self = liftIO (js_getDy (unSVGGlyphRefElement self)) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/SVGGlyphRefElement.hs | mit | 5,830 | 84 | 11 | 848 | 1,329 | 731 | 598 | 82 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
module Control.Monad.Trans.Counter (CounterT(), runCounterT, Counter, runCounter, MonadCounter(..)) where
import Numeric.Natural
import Exception
import HsToCoq.Util.GHC.Exception ()
import Control.Monad.State.Strict
import Data.Functor.Identity
import Control.Applicative
import Control.Monad.Fail
import qualified Control.Monad.Reader.Class as R
import qualified Control.Monad.Writer.Class as W
import qualified Control.Monad.Error.Class as E
import qualified Control.Monad.Cont.Class as C
import qualified Control.Monad.Trans.Identity as I
import qualified Control.Monad.Trans.Reader as R
import qualified Control.Monad.Trans.Writer.Strict as WS
import qualified Control.Monad.Trans.Writer.Lazy as WL
import qualified Control.Monad.Trans.State.Lazy as SL
import qualified Control.Monad.Trans.RWS.Strict as RWSS
import qualified Control.Monad.Trans.RWS.Lazy as RWSL
import qualified Control.Monad.Trans.Maybe as M
import qualified Control.Monad.Trans.Except as E
import qualified Control.Monad.Trans.Cont as C
--------------------------------------------------------------------------------
-- Transformer
newtype CounterT m a = CounterT (StateT Natural m a)
deriving ( Functor, Applicative, Monad
, Alternative, MonadPlus
, MonadFail, MonadFix, MonadIO
, R.MonadReader r, W.MonadWriter w, E.MonadError e, C.MonadCont
, MonadTrans
, ExceptionMonad
)
instance MonadState s m => MonadState s (CounterT m) where
put = lift . put
get = lift get
state = lift . state
runCounterT :: Monad m => CounterT m a -> m a
runCounterT (CounterT m) = evalStateT m 0
--------------------------------------------------------------------------------
-- Monad
type Counter = CounterT Identity
runCounter :: Counter a -> a
runCounter = runIdentity . runCounterT
--------------------------------------------------------------------------------
-- Type Class
class Monad m => MonadCounter m where
fresh :: m Natural
instance Monad m => MonadCounter (CounterT m) where
fresh = CounterT . StateT $ \n -> pure (n, n + 1)
instance MonadCounter m => MonadCounter (I.IdentityT m) where fresh = lift fresh
instance MonadCounter m => MonadCounter (R.ReaderT r m) where fresh = lift fresh
instance (MonadCounter m, Monoid w) => MonadCounter (WS.WriterT w m) where fresh = lift fresh
instance (MonadCounter m, Monoid w) => MonadCounter (WL.WriterT w m) where fresh = lift fresh
instance MonadCounter m => MonadCounter (StateT s m) where fresh = lift fresh
instance MonadCounter m => MonadCounter (SL.StateT s m) where fresh = lift fresh
instance (MonadCounter m, Monoid w) => MonadCounter (RWSS.RWST r w s m) where fresh = lift fresh
instance (MonadCounter m, Monoid w) => MonadCounter (RWSL.RWST r w s m) where fresh = lift fresh
instance MonadCounter m => MonadCounter (M.MaybeT m) where fresh = lift fresh
instance MonadCounter m => MonadCounter (E.ExceptT e m) where fresh = lift fresh
instance MonadCounter m => MonadCounter (C.ContT r m) where fresh = lift fresh
| antalsz/hs-to-coq | src/lib/Control/Monad/Trans/Counter.hs | mit | 3,507 | 0 | 10 | 810 | 919 | 523 | 396 | 60 | 1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
module Bench.Network.Commons
( MsgId
, Ping (..)
, Pong (..)
, Payload (..)
, curTimeMcs
, logMeasure
, loadLogConfig
, Timestamp
, MeasureEvent (..)
, MeasureInfo (..)
, LogMessage (..)
, measureInfoParser
, logMessageParser
) where
import Control.Applicative ((<|>))
import Control.Lens ((&), (?~))
import Control.Monad (join)
import Control.Monad.Trans (MonadIO (..))
import Data.Binary (Binary)
import Data.Binary (Binary (..))
import qualified Data.ByteString.Lazy as BL
import Data.Data (Data)
import Data.Functor (($>))
import Data.Int (Int64)
import Data.Monoid ((<>))
import Data.Text.Buildable (Buildable, build)
import Data.Time.Clock.POSIX (getPOSIXTime)
import qualified Formatting as F
import GHC.Generics (Generic)
import Prelude hiding (takeWhile)
import Data.Attoparsec.Text (Parser, char, decimal, string, takeWhile)
import Control.TimeWarp.Rpc (Message (formatMessage), messageName')
import System.Wlog (Severity (..), WithLogger, initLoggingFromYaml,
lcTermSeverity, logInfo, productionB,
setupLogging)
-- * Transfered data types
type MsgId = Int
-- | Serializes into message of (given size + const)
data Payload = Payload
{ getPayload :: Int64
} deriving (Generic, Data)
data Ping = Ping MsgId Payload
deriving (Generic, Data, Binary)
data Pong = Pong MsgId Payload
deriving (Generic, Data, Binary)
instance Message Ping where
formatMessage = messageName'
instance Message Pong where
formatMessage = messageName'
instance Binary Payload where
get = Payload . BL.length <$> get
put (Payload l) = put $ BL.replicate l 42
-- * Util
type Timestamp = Integer
curTimeMcs :: MonadIO m => m Timestamp
curTimeMcs = liftIO $ round . ( * 1000000) <$> getPOSIXTime
logMeasure :: (MonadIO m, WithLogger m) => MeasureEvent -> MsgId -> Payload -> m ()
logMeasure miEvent miId miPayload = do
miTime <- curTimeMcs
logInfo $ F.sformat F.build $ LogMessage MeasureInfo{..}
loadLogConfig :: MonadIO m => Maybe FilePath -> m ()
loadLogConfig configFile = do
maybe setupDefaultLogging initLoggingFromYaml configFile
where
setupDefaultLogging =
let conf = productionB & lcTermSeverity ?~ Debug
in setupLogging Nothing conf
-- * Logging & parsing
-- ** Measure event
-- | Type of event in measurement.
data MeasureEvent
= PingSent
| PingReceived
| PongSent
| PongReceived
deriving (Show, Eq, Ord, Enum, Bounded)
instance Buildable MeasureEvent where
build PingSent = "• → "
build PingReceived = " → •"
build PongSent = " ← •"
build PongReceived = "• ← "
measureEventParser :: Parser MeasureEvent
measureEventParser = string "• → " $> PingSent
<|> string " → •" $> PingReceived
<|> string " ← •" $> PongSent
<|> string "• ← " $> PongReceived
-- ** Measure info
-- | Single event in measurement.
data MeasureInfo = MeasureInfo
{ miId :: MsgId
, miEvent :: MeasureEvent
, miTime :: Timestamp
, miPayload :: Payload
}
instance Buildable MeasureInfo where
build MeasureInfo{..} = mconcat
[ build miId
, " "
, build miEvent
, " ("
, build $ getPayload miPayload
, ") "
, build miTime
]
measureInfoParser :: Parser MeasureInfo
measureInfoParser = do
miId <- decimal
_ <- string " "
miEvent <- measureEventParser
_ <- string " ("
miPayload <- Payload <$> decimal
_ <- string ") "
miTime <- decimal
return MeasureInfo{..}
-- ** Log message
-- | Allows to extract bare message content from logs.
-- Just inserts separator at beginning.
data LogMessage a = LogMessage a
instance Buildable a => Buildable (LogMessage a) where
build (LogMessage a) = "#" <> build a
logMessageParser :: Parser a -> Parser (Maybe (LogMessage a))
logMessageParser p = (takeWhile (/= '#') >>) . join $ do
(char '#' *> pure (Just . LogMessage <$> p))
<|> pure (pure Nothing)
| serokell/time-warp | bench/Network/Common/Bench/Network/Commons.hs | mit | 4,517 | 0 | 14 | 1,351 | 1,154 | 644 | 510 | -1 | -1 |
{-# OPTIONS_HADDOCK hide, prune #-}
{-# LANGUAGE CPP #-}
module Handler.Mooc
( getMoocHomeR, postMoocHomeR
) where
import Import hiding ((/=.), (==.), (=.), on, isNothing, count)
import Handler.Mooc.BrowseProposals
#if EXPO
#else
import qualified Data.Maybe as Mb
import Database.Esqueleto
import Handler.Mooc.EdxLogin
import Handler.Mooc.User
import qualified Text.Blaze as Blaze
#endif
postMoocHomeR :: Handler TypedContent
#if EXPO
postMoocHomeR = toTypedContent <$> getBrowseProposalsR 1
#else
postMoocHomeR = do
master <- getYesod
yreq <- getRequest
dispatchLti (appLTICredentials $ appSettings master) yreq
#endif
getMoocHomeR :: Handler TypedContent
#if EXPO
getMoocHomeR = toTypedContent <$> getBrowseProposalsR 1
#else
getMoocHomeR = toTypedContent <$> do
setUltDestCurrent
muser <- maybeAuth
createAccW <- case muser of
Nothing -> return mempty
Just (Entity userId user) -> do
return $ if Mb.isNothing $ userEmail user
then setupLocalAccountFromExistingUserW userId
else mempty
-- ses <- map (\(k,v) -> k <> " - " <> decodeUtf8 v) . Map.toList <$> getSession
let urole = muserRole muser
mSubmissionsWidget <- case muser of
Just (Entity uId _) -> do
submissions <- runDB $ fetchLastSubmissions $ noProposalParams {
propLimit = Just 1
, onlyByAuthorId = Just uId
, sortOrder = Newest }
widget <- mkSubmissionsWidget submissions
return $ Just widget
-- fmap listToMaybe $ runDB $ selectList [CurrentScenarioAuthorId ==. uId] []
Nothing -> return Nothing
someSubmissionsWidget <- do
submissions <- runDB $ fetchLastSubmissions $ noProposalParams
{ propLimit = Just 6 }
mkSubmissionsWidget submissions
newsItems <- renderNewsItems muser
mvoteCountWidget <- renderVoteCountWidget muser
let showEditorBtn = Mb.isNothing mSubmissionsWidget || urole /= UR_STUDENT
fullLayout Nothing "Welcome to QUA-KIT!" $ do
setTitle "qua-kit"
toWidgetHead
[hamlet|
<meta property="og:url" content="@{MoocHomeR}" />
<meta property="og:type" content="website" />
<meta property="og:title" content="Quick Urban Analysis kit" />
<meta property="og:description" content="Qua-kit is an urban design, education, sharing, and analysis platform." />
<meta property="og:image" content="@{StaticR img_bgimg_png}" />
|]
toWidgetHead
[cassius|
.critIcon
position: relative
top: 5px
.stars
color: #ff6f00
.newscard
width: 100%
padding: 0 10px
.stars
margin: 8px 0
.commentPara
margin-top: 3px
>.icon24
margin-right: 3px
|]
$(widgetFile "mooc/home")
renderNewsItems :: Maybe (Entity User) -> Handler [(UTCTime, Widget)]
renderNewsItems Nothing = return []
renderNewsItems (Just (Entity uId _)) = do
rs <- fetchReviews uId
eRs <- fetchExpertReviews uId
bVs <- fetchBetterVotes uId
wVs <- fetchWorseVotes uId
let newestFirst (d1, _) (d2, _)
| d1 < d2 = GT
| otherwise = LT
return $ sortBy newestFirst $ rs ++ eRs ++ bVs ++ wVs
-- | TODO: at some point, it is better to implement pagination instead of a hard limit
newsLimit :: Int64
newsLimit = 20
fetchExpertReviews :: UserId -> Handler [(UTCTime, Widget)]
fetchExpertReviews uId = do
reviewScs <- runDB $ select $ from $ \(expReview `InnerJoin` scenario) -> do
on $ expReview ^. ExpertReviewScenarioId ==. scenario ^. ScenarioId
where_ $ scenario ^. ScenarioAuthorId ==. val uId
orderBy [desc $ expReview ^. ExpertReviewTimestamp]
limit newsLimit
return (expReview, scenario)
let renderReview (Entity _ r, Entity _ sc) =
let stars =
let grade = expertReviewGrade r
in mconcat $
(replicate grade [whamlet|<span.icon.icon-lg>star</span>|]) ++
replicate (5 - grade) [whamlet|<span.icon.icon-lg>star_border</span>|]
widget =
[whamlet|
^{viewSubmissionBtn sc}
<p .stars>
^{stars}
<p>#{expertReviewComment r}
|]
in (expertReviewTimestamp r, widget)
return $ map renderReview reviewScs
fetchReviews :: UserId -> Handler [(UTCTime, Widget)]
fetchReviews uId = do
reviewData <- runDB $ select $
from $ \(review
`InnerJoin` scenario
`InnerJoin` criterion
`InnerJoin` user
) -> do
on (review ^. ReviewReviewerId ==. user ^. UserId)
on (review ^. ReviewCriterionId ==. criterion ^. CriterionId)
on (review ^. ReviewScenarioId ==. scenario ^. ScenarioId)
where_ $ scenario ^. ScenarioAuthorId ==. val uId
orderBy [desc $ review ^. ReviewTimestamp]
limit newsLimit
return (review, scenario, criterion, user)
let renderReview (Entity _ r, Entity _ sc, Entity _ crit, Entity _ reviewer) =
let critIcon = Blaze.preEscapedToMarkup $ criterionIcon crit
widget =
[whamlet|
^{viewSubmissionBtn sc}
<p .commentPara>
<span .critIcon>#{ critIcon }
<span class="icon icon24 text-brand-accent">
$if reviewPositive r
thumb_up
$else
thumb_down
Review from #{userName reviewer}
<p>
#{reviewComment r}
|]
in (reviewTimestamp r, widget)
return $ map renderReview reviewData
fetchBetterVotes :: UserId -> Handler [(UTCTime, Widget)]
fetchBetterVotes = fetchVotesWithComment VoteBetterId renderReview
where
renderReview (Entity _ v, Entity _ sc) =
let widget =
[whamlet|
^{viewSubmissionBtn sc}
<p>
<strong>Your submission was voted better than another
$maybe expl <- voteExplanation v
– #{expl}
|]
in (voteTimestamp v, widget)
fetchWorseVotes :: UserId -> Handler [(UTCTime, Widget)]
fetchWorseVotes = fetchVotesWithComment VoteWorseId renderReview
where
renderReview (Entity _ v, Entity _ sc) =
let widget =
[whamlet|
^{viewSubmissionBtn sc}
<p>
<strong>Another submission was voted even better than yours
$maybe expl <- voteExplanation v
– #{expl}
|]
in (voteTimestamp v, widget)
fetchVotesWithComment :: EntityField Vote ScenarioId
-> ((Entity Vote, Entity Scenario) -> (UTCTime, Widget))
-> UserId
-> Handler [(UTCTime, Widget)]
fetchVotesWithComment voteBetterOrWorse renderReview uId = do
votes <- runDB $ select $ from $ \(vote `InnerJoin` scenario) -> do
on $ vote ^. voteBetterOrWorse ==. scenario ^. ScenarioId
where_ $ scenario ^. ScenarioAuthorId ==. val uId
&&. (not_ $ vote ^. VoteExplanation ==. nothing)
orderBy [desc $ vote ^. VoteTimestamp]
limit newsLimit
return (vote, scenario)
return $ map renderReview votes
renderVoteCountWidget :: Maybe (Entity User) -> Handler (Maybe Widget)
renderVoteCountWidget Nothing = return Nothing
renderVoteCountWidget (Just (Entity uId _)) = do
let countVotes voteBetterOrWorse = do
counts <- runDB $ select $ from $ \(vote `InnerJoin` scenario) -> do
on $ vote ^. voteBetterOrWorse ==. scenario ^. ScenarioId
where_ $ scenario ^. ScenarioAuthorId ==. val uId
return $ count $ vote ^. VoteId
return $ case counts of
c:_ -> unValue c
[] -> 0::Int
betterVoteCount <- countVotes VoteBetterId
worseVoteCount <- countVotes VoteWorseId
let totalVoteCount = betterVoteCount + worseVoteCount
widget =
[whamlet|
<div class="col-lg-4 col-md-6 col-sm-9">
<div .card>
<div .card-inner>
<p>
Your submission was compared #{totalVoteCount} times to another:
<p>
<span class="icon icon24 text-brand-accent">
thumb_up
#{betterVoteCount} times it was voted better,
<p>
<span class="icon icon24 text-brand-accent">
thumb_down
#{worseVoteCount} times the other one was voted better.
|]
return $ if totalVoteCount > 0
then Just widget
else Nothing
viewSubmissionBtn :: Scenario -> Widget
viewSubmissionBtn sc = [whamlet|
<div class="card-action-btn pull-right">
<a href=@{ SubmissionR (scenarioExerciseId sc) (scenarioAuthorId sc) }>
<span .icon>visibility
|]
#endif
| achirkin/qua-kit | apps/hs/qua-server/src/Handler/Mooc.hs | mit | 9,476 | 0 | 6 | 3,264 | 101 | 66 | 35 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, NoImplicitPrelude, NoRecordWildCards #-}
module Tach.Manager.Impulse.PluginSpec (main,spec) where
import Tach.Manager.Impulse.Plugin
import CorePrelude
import Filesystem
import Data.Default
import Keter.Types
import Keter.Main
import Data.Yaml
import Control.Monad
import Filesystem (createTree, isFile, rename)
import Filesystem.Path.CurrentOS (directory, encodeString, (<.>),(</>))
import Control.Concurrent.Chan
import Control.Concurrent
import Control.Concurrent.MVar
import qualified Control.Monad.Trans.State as S
import qualified Data.HashMap.Strict as HMap
import qualified Data.Map as Map
import qualified System.Random as R
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "someFunction in typeSpec" $ do
it "should have a definition" $ do
True `shouldBe` False
testFilePath = "."</>"testCFG"<.>"yaml"
testPlugin :: FilePath -> IO Plugin
testPlugin fp = return $ Plugin { pluginGetEnv = (\a o -> do
print "teest"
writeFile fp "Here is a test bytestring"
return []
)}
testPluginList = [] -- [\x -> (testPlugin x)]
| smurphy8/tach | apps/tach-manager-impulse/test/Tach/Manager/Impulse/PluginSpec.hs | mit | 1,352 | 0 | 13 | 400 | 292 | 174 | 118 | 34 | 1 |
module ByteStringUtils
( byteStringToLower
) where
import Data.Word (Word8)
import qualified Data.ByteString as BS
byteStringToLower :: BS.ByteString -> BS.ByteString
byteStringToLower = BS.map toLower
toLower :: Word8 -> Word8
toLower c
| c >= fromIntegral (fromEnum 'A') && c <= fromIntegral (fromEnum 'Z') =
c + (fromIntegral (fromEnum 'a')) - (fromIntegral (fromEnum 'A'))
| otherwise = c
| bitc/serverer | src/ByteStringUtils.hs | mit | 420 | 0 | 13 | 83 | 144 | 75 | 69 | 11 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Fun.Type
( Fun (..), Exp (..), Mark (..)
, RAM.Builtin.Builtin (..)
, Property (..)
)
where
import Autolib.ToDoc
import Autolib.Reader
import Autolib.Size
import Autolib.Set
import Autolib.Xml
import qualified RAM.Builtin
import Data.Typeable
data Property = Builtins [ RAM.Builtin.Builtin ]
deriving ( Eq, Ord, Typeable )
$(derives [makeReader, makeToDoc] [''Property])
instance Show Property where show = render . toDoc
data Fun =
-- | Grundfunktionen
Zero Int
| Succ Int
| Decr Int -- ^ naja
| Proj Int Int
| Binary_Succ0 Int
| Binary_Succ1 Int
-- | so tun, also ob Grundfunktion
| Builtin Int RAM.Builtin.Builtin
-- | Operatoren
| Sub Int [ Fun ]
| PR Int [ Fun ]
| Min Int [ Fun ]
| Binary_PR Int [ Fun ]
deriving (Eq, Ord, Typeable)
instance Size Fun where
size ( Sub i fs ) = succ $ sum $ map size fs
size ( PR i fs ) = succ $ sum $ map size fs
size ( Min i fs ) = succ $ sum $ map size fs
size _ = 1
data Exp
= Zahl Integer
-- | non-strikt
| App Fun [ Exp ]
-- | nur auf dem Stack benutzt, für Builtins (die sind strikt)
-- wende builtin auf die obersten stack-elemente an
| Builtin_ Int RAM.Builtin.Builtin
-- | benutzt für PRs, deren letztes arg schon auf stack steht
| App_ Fun [ Exp ]
-- | top of stack in cache eintragen
| M Mark
deriving ( Eq, Ord, Typeable )
-- | wollen wir nicht ausgeben
data Mark = Mark Exp deriving (Eq, Ord, Typeable)
instance ToDoc Mark where toDoc m = text "{..}"
instance Reader Mark -- ohne implementierung
$(derives [makeReader, makeToDoc] [''Fun])
$(derives [makeReader, makeToDoc] [''Exp])
| marcellussiegburg/autotool | collection/src/Fun/Type.hs | gpl-2.0 | 1,715 | 6 | 9 | 431 | 513 | 295 | 218 | 46 | 0 |
main= do
setHeader $ do
title $ "Accessing arguments in UI events"
meta ! name="viewport" ! content "initial-scale=1.0, user-scalable=no"
meta ! charset="utf-8"
style "\
\html, body, #map-canvas {\
\height: 100%;\
\margin: 0px;\
\padding: 0px"
script ! src "https://maps.googleapis.com/maps/api/js?v=3.exp"
runBody $ do
let initialize=
mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882,131.044922)
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
});
}
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body> | agocorona/tryhplay | examples/GoogleMaps.hs | gpl-3.0 | 978 | 26 | 16 | 223 | 335 | 175 | 160 | -1 | -1 |
-- Hmkdir, a haskell implementation of GNU mkdir.
module Main where
import System.Environment
import GUtils
main :: IO ()
main = do
args <- getArgs
let defaultConfig = ProgramData {
appName = "Hmkdir"
, appHelp = customHelp
, appVersion = customVersion
, argumentStrings = args
, configuration = customOptions
, parser = undefined -- needed anymore??
}
let config = parseArguments defaultConfig args
putStrLn ( showHelp config)
putStrLn (showVersion config)
doWork config
putStrLn ("\n\n"++(show config)++"\n") --debug opts
return ()
doWork :: ProgramData -> IO ()
doWork dat = do
-- putStrLn (concat targetList)--dbg
sequence_ (map (\x -> putStrLn (show x)) targetList)
sequence_ (map makeDirectory targetList)
where cfg = configuration dat
targets = getFlag "--" cfg
targetList = getList targets
modeOption, parentOption, verboseOption, zOption, contextOption :: Option
modeOption = Option "set file mode (as in chmod), not a=rwx - umask"
(Flags ["m"] ["mode"])
"=MODE"
(BoolOpt False)
(OptionEffect (\(opts) _ unused -> ((replaceFlag opts "long-flag" (BoolOpt True)), unused)))
parentOption = Option "no error if existing, make parent directories as needed"
(Flags ["p"] ["parents"])
""
(BoolOpt False)
(OptionEffect (\(opts) _ unused -> ((replaceFlag opts "parents" (BoolOpt True)), unused)))
verboseOption = Option "print a message for each created directory"
(Flags ["v"] ["verbose"])
"=<params>"
(BoolOpt False)
(OptionEffect (\(opts) _ unused -> ((replaceFlag opts "verbose" (BoolOpt True)), unused)))
zOption = Option "set SELinux security context of each created directory to the default type"
(Flags ["Z"] [""])
"=<params>"
(BoolOpt False)
(OptionEffect (\(opts) _ unused -> ((replaceFlag opts "Z" (BoolOpt True)), unused)))
contextOption = Option "like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX"
(Flags [""] ["context"])
"[=CTX]"
(BoolOpt False)
(OptionEffect (\(opts) _ unused -> ((replaceFlag opts "long-flag" (BoolOpt True)), unused)))
customOptions :: Options
customOptions = catOptions (Options [
modeOption, parentOption, verboseOption, zOption, contextOption
]) defaultOptions
customVersion :: String
customVersion = "Hmkdir, a Haskell clone of mkdir."
++ "\nmkdir (GNU coreutils) 8.23.126-99f76"
++ "\nCopyright (C) 2015 Free Software Foundation, Inc."
++ "\nLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>."
++ "\nThis is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law."
++ "\nWritten by David MacKenzie."
++ "\nPorted to Haskell by PuZZleDucK."
customHelp :: (String,String)
customHelp = ("Usage: H<app> ...."
++ "\nUsage: /home/bminerds/x/coreutils/src/mkdir [OPTION]... DIRECTORY..."
++ "\nCreate the DIRECTORY(ies), if they do not already exist."
++ "\nMandatory arguments to long options are mandatory for short options too."
, "\nGNU coreutils online help: <http://www.gnu.org/software/coreutils/>"
++ "\nFull documentation at: <http://www.gnu.org/software/coreutils/mkdir> or available locally via: info '(coreutils) mkdir invocation'"
)
| PuZZleDucK/Hls | Hmkdir.hs | gpl-3.0 | 3,318 | 0 | 14 | 637 | 771 | 417 | 354 | 71 | 1 |
module QFeldspar.Expression.Conversions.ScopeWithnessing () where
import QFeldspar.MyPrelude
import qualified QFeldspar.Expression.ADTUntypedDebruijn as AUD
import qualified QFeldspar.Expression.GADTTyped as GTD
import qualified QFeldspar.Type.ADT as TA
import qualified QFeldspar.Nat.ADT as NA
import QFeldspar.Nat.GADT
import QFeldspar.Conversion
import QFeldspar.Variable.Conversion ()
instance (m ~ m' , n ~ n') =>
Cnv (AUD.Exp , (Nat m , Nat n))
(GTD.Exp m' n' (Maybe TA.Typ)) where
cnv (ee , r@(m , n)) = case ee of
AUD.Var x -> GTD.Var <$> cnv (x , n)
AUD.Prm x es -> GTD.Prm <$> pure (fmap (const Nothing) es) <*> cnv (x , m)
<*> mapM (cnvWth r) es
AUD.App ef ea -> GTD.App <$> pure Nothing <*> cnvWth r ef <*> cnvWth r ea
AUD.Fst e -> GTD.Fst <$> pure Nothing <*> cnvWth r e
AUD.Snd e -> GTD.Snd <$> pure Nothing <*> cnvWth r e
AUD.Len e -> GTD.Len <$> pure Nothing <*> cnvWth r e
AUD.LenV e -> GTD.LenV <$> pure Nothing <*> cnvWth r e
AUD.Eql el eb -> GTD.Eql <$> pure Nothing <*> cnvWth r el <*> cnvWth r eb
AUD.Ltd el eb -> GTD.Ltd <$> pure Nothing <*> cnvWth r el <*> cnvWth r eb
AUD.LeT el eb -> GTD.LeT <$> pure Nothing <*> cnvWth r el <*> cnvWth r eb
AUD.May em en es -> GTD.May <$> pure Nothing <*> cnvWth r em <*> cnvWth r en <*> cnvWth r es
AUD.Typ t e -> GTD.Typ <$> pure (Just t) <*> cnvWth r e
_ -> $(biGenOverloadedM 'ee ''AUD.Exp "GTD"
['AUD.App,'AUD.Fst,'AUD.Snd,'AUD.Len,'AUD.LenV,'AUD.Eql,'AUD.Ltd,'AUD.Prm,'AUD.Var,
'AUD.LeT,'AUD.May,'AUD.Typ] (const [| cnvWth r |]))
instance (m ~ m' , n ~ n') =>
Cnv (AUD.Fun , (Nat m , Nat n)) (GTD.Exp m' ('NA.Suc n')
(Maybe TA.Typ)) where
cnv (AUD.Fun e , (m , n)) = cnv (e , (m , Suc n))
| shayan-najd/QFeldspar | QFeldspar/Expression/Conversions/ScopeWithnessing.hs | gpl-3.0 | 1,942 | 0 | 16 | 577 | 851 | 444 | 407 | -1 | -1 |
-- | Round 1B 2010
-- https://code.google.com/codejam/contest/635101/dashboard#s=p0
module FileFixIt where
-- constant imports
import Text.ParserCombinators.Parsec
import Text.Parsec
import System.IO (openFile, hClose, hGetContents, hPutStrLn, IOMode(ReadMode), stderr)
import Debug.Trace (trace)
-- variable imports
import qualified Data.Set as S
import Data.List (sort, sortBy, foldl', inits)
-- variable Data
data TestCase = TestCase
[String] -- ^ existing dirs
[String] -- ^ to be created
deriving (Show, Eq, Ord)
type Fs = S.Set Dir -- ^ Filesystem
type Dir = [String] -- ^ Directory
emptyFs = S.empty :: Fs
-- variable implementation
solveCase c@(TestCase dirs new) = show $ solve dirs new
solve :: [String] -> [String] -> Int
solve dirs new = S.size fs2 - S.size fs1
where
fs1 :: Fs
fs1 = mkdirAll emptyFs dirs
fs2 :: Fs
fs2 = mkdirAll fs1 new
strToDir :: String -> Dir
strToDir s = filter (not . null) $ nth : ls
where
(nth, ls) = foldr fn ("", []) s
fn ch (cur, ls)
| ch == '/' = ("", cur : ls)
| otherwise = (ch : cur, ls)
mkdir :: Fs -> String -> Fs
mkdir fs [] = fs
mkdir fs path = foldl' inserter fs initials
where
parts = strToDir path
initials = filter (not . null) (inits parts)
inserter fs path = S.insert path fs
mkdirAll :: Fs -> [String] -> Fs
mkdirAll fs = foldl' mkdir fs
-- Parser (variable part)
parseDir = do
dir <- many1 (oneOf ('/':['a'..'z'] ++ ['0'..'9']))
eol <|> eof
return dir
parseSingleCase = do
numExisting <- parseInt
char ' '
numCreate <- parseInt
eol
dirs <- count numExisting parseDir
create <- count numCreate parseDir
return $ TestCase dirs create
eol :: GenParser Char st ()
eol = char '\n' >> return ()
parseIntegral :: Integral a => (String -> a) -> GenParser Char st a
parseIntegral rd = rd <$> (plus <|> minus <|> number)
where
plus = char '+' *> number
minus = (:) <$> char '-' <*> number
number = many1 digit
parseInteger :: GenParser Char st Integer
parseInteger = parseIntegral (read :: String -> Integer)
parseIntegers :: GenParser Char st [Integer]
parseIntegers = parseInteger `sepBy` (char ' ')
parseInt :: GenParser Char st Int
parseInt = parseIntegral (read :: String -> Int)
parseInts :: GenParser Char st [Int]
parseInts = parseInt `sepBy` (char ' ')
--
-- constant part
--
-- Parsing (constant part)
-- | First number is number of test cases
data TestInput = TestInput
Int -- ^ number of 'TestCase's
[TestCase]
deriving (Show, Ord, Eq)
parseTestCases = do
numCases <- parseInt
eol
cases <- count numCases parseSingleCase
return $ TestInput numCases cases
parseCases :: String -> Either ParseError TestInput
parseCases contents = parse parseTestCases "(stdin)" contents
-- main
runOnContent :: String -> IO ()
runOnContent content = do
let parsed = parseCases content
case parsed of
Right (TestInput _ cases) -> mapM_ putStrLn (output (solveCases cases))
Left err -> hPutStrLn stderr $ show err
where
solveCases xs = map solveCase xs
consCase n s = "Case #" ++ (show n) ++ ": " ++ s
output xs = zipWith consCase [1..] xs
-- | command line implementation
run = do
cs <- getContents
runOnContent cs
main = run
| dirkz/google-code-jam-haskell | practice/src/FileFixIt.hs | mpl-2.0 | 3,330 | 0 | 14 | 794 | 1,147 | 601 | 546 | 86 | 2 |
{-# 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.CloudDebugger.Debugger.Debuggees.Breakpoints.Get
-- 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)
--
-- Gets breakpoint information.
--
-- /See:/ <https://cloud.google.com/debugger Cloud Debugger API Reference> for @clouddebugger.debugger.debuggees.breakpoints.get@.
module Network.Google.Resource.CloudDebugger.Debugger.Debuggees.Breakpoints.Get
(
-- * REST Resource
DebuggerDebuggeesBreakpointsGetResource
-- * Creating a Request
, debuggerDebuggeesBreakpointsGet
, DebuggerDebuggeesBreakpointsGet
-- * Request Lenses
, ddbgXgafv
, ddbgUploadProtocol
, ddbgAccessToken
, ddbgUploadType
, ddbgBreakpointId
, ddbgDebuggeeId
, ddbgClientVersion
, ddbgCallback
) where
import Network.Google.Debugger.Types
import Network.Google.Prelude
-- | A resource alias for @clouddebugger.debugger.debuggees.breakpoints.get@ method which the
-- 'DebuggerDebuggeesBreakpointsGet' request conforms to.
type DebuggerDebuggeesBreakpointsGetResource =
"v2" :>
"debugger" :>
"debuggees" :>
Capture "debuggeeId" Text :>
"breakpoints" :>
Capture "breakpointId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "clientVersion" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] GetBreakpointResponse
-- | Gets breakpoint information.
--
-- /See:/ 'debuggerDebuggeesBreakpointsGet' smart constructor.
data DebuggerDebuggeesBreakpointsGet =
DebuggerDebuggeesBreakpointsGet'
{ _ddbgXgafv :: !(Maybe Xgafv)
, _ddbgUploadProtocol :: !(Maybe Text)
, _ddbgAccessToken :: !(Maybe Text)
, _ddbgUploadType :: !(Maybe Text)
, _ddbgBreakpointId :: !Text
, _ddbgDebuggeeId :: !Text
, _ddbgClientVersion :: !(Maybe Text)
, _ddbgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DebuggerDebuggeesBreakpointsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ddbgXgafv'
--
-- * 'ddbgUploadProtocol'
--
-- * 'ddbgAccessToken'
--
-- * 'ddbgUploadType'
--
-- * 'ddbgBreakpointId'
--
-- * 'ddbgDebuggeeId'
--
-- * 'ddbgClientVersion'
--
-- * 'ddbgCallback'
debuggerDebuggeesBreakpointsGet
:: Text -- ^ 'ddbgBreakpointId'
-> Text -- ^ 'ddbgDebuggeeId'
-> DebuggerDebuggeesBreakpointsGet
debuggerDebuggeesBreakpointsGet pDdbgBreakpointId_ pDdbgDebuggeeId_ =
DebuggerDebuggeesBreakpointsGet'
{ _ddbgXgafv = Nothing
, _ddbgUploadProtocol = Nothing
, _ddbgAccessToken = Nothing
, _ddbgUploadType = Nothing
, _ddbgBreakpointId = pDdbgBreakpointId_
, _ddbgDebuggeeId = pDdbgDebuggeeId_
, _ddbgClientVersion = Nothing
, _ddbgCallback = Nothing
}
-- | V1 error format.
ddbgXgafv :: Lens' DebuggerDebuggeesBreakpointsGet (Maybe Xgafv)
ddbgXgafv
= lens _ddbgXgafv (\ s a -> s{_ddbgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ddbgUploadProtocol :: Lens' DebuggerDebuggeesBreakpointsGet (Maybe Text)
ddbgUploadProtocol
= lens _ddbgUploadProtocol
(\ s a -> s{_ddbgUploadProtocol = a})
-- | OAuth access token.
ddbgAccessToken :: Lens' DebuggerDebuggeesBreakpointsGet (Maybe Text)
ddbgAccessToken
= lens _ddbgAccessToken
(\ s a -> s{_ddbgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ddbgUploadType :: Lens' DebuggerDebuggeesBreakpointsGet (Maybe Text)
ddbgUploadType
= lens _ddbgUploadType
(\ s a -> s{_ddbgUploadType = a})
-- | Required. ID of the breakpoint to get.
ddbgBreakpointId :: Lens' DebuggerDebuggeesBreakpointsGet Text
ddbgBreakpointId
= lens _ddbgBreakpointId
(\ s a -> s{_ddbgBreakpointId = a})
-- | Required. ID of the debuggee whose breakpoint to get.
ddbgDebuggeeId :: Lens' DebuggerDebuggeesBreakpointsGet Text
ddbgDebuggeeId
= lens _ddbgDebuggeeId
(\ s a -> s{_ddbgDebuggeeId = a})
-- | Required. The client version making the call. Schema:
-- \`domain\/type\/version\` (e.g., \`google.com\/intellij\/v1\`).
ddbgClientVersion :: Lens' DebuggerDebuggeesBreakpointsGet (Maybe Text)
ddbgClientVersion
= lens _ddbgClientVersion
(\ s a -> s{_ddbgClientVersion = a})
-- | JSONP
ddbgCallback :: Lens' DebuggerDebuggeesBreakpointsGet (Maybe Text)
ddbgCallback
= lens _ddbgCallback (\ s a -> s{_ddbgCallback = a})
instance GoogleRequest
DebuggerDebuggeesBreakpointsGet
where
type Rs DebuggerDebuggeesBreakpointsGet =
GetBreakpointResponse
type Scopes DebuggerDebuggeesBreakpointsGet =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud_debugger"]
requestClient DebuggerDebuggeesBreakpointsGet'{..}
= go _ddbgDebuggeeId _ddbgBreakpointId _ddbgXgafv
_ddbgUploadProtocol
_ddbgAccessToken
_ddbgUploadType
_ddbgClientVersion
_ddbgCallback
(Just AltJSON)
debuggerService
where go
= buildClient
(Proxy ::
Proxy DebuggerDebuggeesBreakpointsGetResource)
mempty
| brendanhay/gogol | gogol-debugger/gen/Network/Google/Resource/CloudDebugger/Debugger/Debuggees/Breakpoints/Get.hs | mpl-2.0 | 6,244 | 0 | 20 | 1,442 | 867 | 504 | 363 | 134 | 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.Logging.Folders.Locations.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 information about the supported locations for this service.
--
-- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.folders.locations.list@.
module Network.Google.Resource.Logging.Folders.Locations.List
(
-- * REST Resource
FoldersLocationsListResource
-- * Creating a Request
, foldersLocationsList
, FoldersLocationsList
-- * Request Lenses
, fXgafv
, fUploadProtocol
, fAccessToken
, fUploadType
, fName
, fFilter
, fPageToken
, fPageSize
, fCallback
) where
import Network.Google.Logging.Types
import Network.Google.Prelude
-- | A resource alias for @logging.folders.locations.list@ method which the
-- 'FoldersLocationsList' request conforms to.
type FoldersLocationsListResource =
"v2" :>
Capture "name" Text :>
"locations" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListLocationsResponse
-- | Lists information about the supported locations for this service.
--
-- /See:/ 'foldersLocationsList' smart constructor.
data FoldersLocationsList =
FoldersLocationsList'
{ _fXgafv :: !(Maybe Xgafv)
, _fUploadProtocol :: !(Maybe Text)
, _fAccessToken :: !(Maybe Text)
, _fUploadType :: !(Maybe Text)
, _fName :: !Text
, _fFilter :: !(Maybe Text)
, _fPageToken :: !(Maybe Text)
, _fPageSize :: !(Maybe (Textual Int32))
, _fCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'FoldersLocationsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'fXgafv'
--
-- * 'fUploadProtocol'
--
-- * 'fAccessToken'
--
-- * 'fUploadType'
--
-- * 'fName'
--
-- * 'fFilter'
--
-- * 'fPageToken'
--
-- * 'fPageSize'
--
-- * 'fCallback'
foldersLocationsList
:: Text -- ^ 'fName'
-> FoldersLocationsList
foldersLocationsList pFName_ =
FoldersLocationsList'
{ _fXgafv = Nothing
, _fUploadProtocol = Nothing
, _fAccessToken = Nothing
, _fUploadType = Nothing
, _fName = pFName_
, _fFilter = Nothing
, _fPageToken = Nothing
, _fPageSize = Nothing
, _fCallback = Nothing
}
-- | V1 error format.
fXgafv :: Lens' FoldersLocationsList (Maybe Xgafv)
fXgafv = lens _fXgafv (\ s a -> s{_fXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
fUploadProtocol :: Lens' FoldersLocationsList (Maybe Text)
fUploadProtocol
= lens _fUploadProtocol
(\ s a -> s{_fUploadProtocol = a})
-- | OAuth access token.
fAccessToken :: Lens' FoldersLocationsList (Maybe Text)
fAccessToken
= lens _fAccessToken (\ s a -> s{_fAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
fUploadType :: Lens' FoldersLocationsList (Maybe Text)
fUploadType
= lens _fUploadType (\ s a -> s{_fUploadType = a})
-- | The resource that owns the locations collection, if applicable.
fName :: Lens' FoldersLocationsList Text
fName = lens _fName (\ s a -> s{_fName = a})
-- | A filter to narrow down results to a preferred subset. The filtering
-- language accepts strings like \"displayName=tokyo\", and is documented
-- in more detail in AIP-160 (https:\/\/google.aip.dev\/160).
fFilter :: Lens' FoldersLocationsList (Maybe Text)
fFilter = lens _fFilter (\ s a -> s{_fFilter = a})
-- | A page token received from the next_page_token field in the response.
-- Send that page token to receive the subsequent page.
fPageToken :: Lens' FoldersLocationsList (Maybe Text)
fPageToken
= lens _fPageToken (\ s a -> s{_fPageToken = a})
-- | The maximum number of results to return. If not set, the service selects
-- a default.
fPageSize :: Lens' FoldersLocationsList (Maybe Int32)
fPageSize
= lens _fPageSize (\ s a -> s{_fPageSize = a}) .
mapping _Coerce
-- | JSONP
fCallback :: Lens' FoldersLocationsList (Maybe Text)
fCallback
= lens _fCallback (\ s a -> s{_fCallback = a})
instance GoogleRequest FoldersLocationsList where
type Rs FoldersLocationsList = ListLocationsResponse
type Scopes FoldersLocationsList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/logging.admin",
"https://www.googleapis.com/auth/logging.read"]
requestClient FoldersLocationsList'{..}
= go _fName _fXgafv _fUploadProtocol _fAccessToken
_fUploadType
_fFilter
_fPageToken
_fPageSize
_fCallback
(Just AltJSON)
loggingService
where go
= buildClient
(Proxy :: Proxy FoldersLocationsListResource)
mempty
| brendanhay/gogol | gogol-logging/gen/Network/Google/Resource/Logging/Folders/Locations/List.hs | mpl-2.0 | 6,064 | 0 | 19 | 1,460 | 971 | 562 | 409 | 132 | 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.Tracing.Projects.Traces.BatchWrite
-- 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)
--
-- Sends new spans to Stackdriver Trace or updates existing traces. If the
-- name of a trace that you send matches that of an existing trace, new
-- spans are added to the existing trace. Attempt to update existing spans
-- results undefined behavior. If the name does not match, a new trace is
-- created with given set of spans.
--
-- /See:/ <https://cloud.google.com/trace Google Tracing API Reference> for @tracing.projects.traces.batchWrite@.
module Network.Google.Resource.Tracing.Projects.Traces.BatchWrite
(
-- * REST Resource
ProjectsTracesBatchWriteResource
-- * Creating a Request
, projectsTracesBatchWrite
, ProjectsTracesBatchWrite
-- * Request Lenses
, ptbwXgafv
, ptbwUploadProtocol
, ptbwPp
, ptbwAccessToken
, ptbwUploadType
, ptbwPayload
, ptbwBearerToken
, ptbwName
, ptbwCallback
) where
import Network.Google.Prelude
import Network.Google.Tracing.Types
-- | A resource alias for @tracing.projects.traces.batchWrite@ method which the
-- 'ProjectsTracesBatchWrite' request conforms to.
type ProjectsTracesBatchWriteResource =
"v2" :>
Capture "name" Text :>
"traces:batchWrite" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] BatchWriteSpansRequest :>
Post '[JSON] Empty
-- | Sends new spans to Stackdriver Trace or updates existing traces. If the
-- name of a trace that you send matches that of an existing trace, new
-- spans are added to the existing trace. Attempt to update existing spans
-- results undefined behavior. If the name does not match, a new trace is
-- created with given set of spans.
--
-- /See:/ 'projectsTracesBatchWrite' smart constructor.
data ProjectsTracesBatchWrite =
ProjectsTracesBatchWrite'
{ _ptbwXgafv :: !(Maybe Xgafv)
, _ptbwUploadProtocol :: !(Maybe Text)
, _ptbwPp :: !Bool
, _ptbwAccessToken :: !(Maybe Text)
, _ptbwUploadType :: !(Maybe Text)
, _ptbwPayload :: !BatchWriteSpansRequest
, _ptbwBearerToken :: !(Maybe Text)
, _ptbwName :: !Text
, _ptbwCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsTracesBatchWrite' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ptbwXgafv'
--
-- * 'ptbwUploadProtocol'
--
-- * 'ptbwPp'
--
-- * 'ptbwAccessToken'
--
-- * 'ptbwUploadType'
--
-- * 'ptbwPayload'
--
-- * 'ptbwBearerToken'
--
-- * 'ptbwName'
--
-- * 'ptbwCallback'
projectsTracesBatchWrite
:: BatchWriteSpansRequest -- ^ 'ptbwPayload'
-> Text -- ^ 'ptbwName'
-> ProjectsTracesBatchWrite
projectsTracesBatchWrite pPtbwPayload_ pPtbwName_ =
ProjectsTracesBatchWrite'
{ _ptbwXgafv = Nothing
, _ptbwUploadProtocol = Nothing
, _ptbwPp = True
, _ptbwAccessToken = Nothing
, _ptbwUploadType = Nothing
, _ptbwPayload = pPtbwPayload_
, _ptbwBearerToken = Nothing
, _ptbwName = pPtbwName_
, _ptbwCallback = Nothing
}
-- | V1 error format.
ptbwXgafv :: Lens' ProjectsTracesBatchWrite (Maybe Xgafv)
ptbwXgafv
= lens _ptbwXgafv (\ s a -> s{_ptbwXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ptbwUploadProtocol :: Lens' ProjectsTracesBatchWrite (Maybe Text)
ptbwUploadProtocol
= lens _ptbwUploadProtocol
(\ s a -> s{_ptbwUploadProtocol = a})
-- | Pretty-print response.
ptbwPp :: Lens' ProjectsTracesBatchWrite Bool
ptbwPp = lens _ptbwPp (\ s a -> s{_ptbwPp = a})
-- | OAuth access token.
ptbwAccessToken :: Lens' ProjectsTracesBatchWrite (Maybe Text)
ptbwAccessToken
= lens _ptbwAccessToken
(\ s a -> s{_ptbwAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ptbwUploadType :: Lens' ProjectsTracesBatchWrite (Maybe Text)
ptbwUploadType
= lens _ptbwUploadType
(\ s a -> s{_ptbwUploadType = a})
-- | Multipart request metadata.
ptbwPayload :: Lens' ProjectsTracesBatchWrite BatchWriteSpansRequest
ptbwPayload
= lens _ptbwPayload (\ s a -> s{_ptbwPayload = a})
-- | OAuth bearer token.
ptbwBearerToken :: Lens' ProjectsTracesBatchWrite (Maybe Text)
ptbwBearerToken
= lens _ptbwBearerToken
(\ s a -> s{_ptbwBearerToken = a})
-- | Name of the project where the spans belong to. Format is
-- \`projects\/PROJECT_ID\`.
ptbwName :: Lens' ProjectsTracesBatchWrite Text
ptbwName = lens _ptbwName (\ s a -> s{_ptbwName = a})
-- | JSONP
ptbwCallback :: Lens' ProjectsTracesBatchWrite (Maybe Text)
ptbwCallback
= lens _ptbwCallback (\ s a -> s{_ptbwCallback = a})
instance GoogleRequest ProjectsTracesBatchWrite where
type Rs ProjectsTracesBatchWrite = Empty
type Scopes ProjectsTracesBatchWrite =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/trace.append"]
requestClient ProjectsTracesBatchWrite'{..}
= go _ptbwName _ptbwXgafv _ptbwUploadProtocol
(Just _ptbwPp)
_ptbwAccessToken
_ptbwUploadType
_ptbwBearerToken
_ptbwCallback
(Just AltJSON)
_ptbwPayload
tracingService
where go
= buildClient
(Proxy :: Proxy ProjectsTracesBatchWriteResource)
mempty
| brendanhay/gogol | gogol-tracing/gen/Network/Google/Resource/Tracing/Projects/Traces/BatchWrite.hs | mpl-2.0 | 6,520 | 0 | 19 | 1,509 | 945 | 552 | 393 | 135 | 1 |
{-https://github.com/haskell-esp/ejercicios-beginning-haskell
##### 2-5. THE PERFECT MATCH FOR YOUR TIME MACHINES
1) For statistical purposes, write a function that
returns the number of clients of each gender.
* You may need to define an auxiliary data type to hold the results of this function.
2) Every year a time comes when time machines are
sold with a big discount to encourage potential buyers.
* Write a function that
* given a list of time machines,
decreases their price by some percentage.
* Use the Client and TimeMachine data type you can see just below.
-}
{- Client. There are three kinds of clients:
• Government organizations, which are known by
their name
• Companies, for which you need to record
its name,
an identification number,
a contact person (name, surname and gender) and
its position within the company hierarchy
• Individual clients, known by
being a person (name, surname and gender) and
whether they want to receive advertising
-}
-- Client
data Client
= GovOrg String
| Company String Integer Person String
| Individual Person Bool
deriving Show
data Person
= Person String String Gender
deriving Show
data Gender
= Male
| Female
| Unknown
deriving Show
-- TimeMachine
data TimeMachine
= TimeMachine Manufacturer Model Name Direction Price deriving Show
type Manufacturer = String
type Model = Integer
type Name = String
type Price = Double
data Direction
= ToPast
| ToFuture
| ToPastOrFuture
deriving Show
-- Test data
clientList = [ (GovOrg "Haskellnautas")
, (Company "TomaYa" 1 (Person "Jane" "Austen" Female) "Boss")
, (Individual (Person "Marco" "Polo" Male) True)
]
tmList = [ (TimeMachine "ACME" 123 "Ok1" ToPast 100.0)
, (TimeMachine "Hskl" 007 "Ok2" ToFuture 150.0)
]
| haskell-esp/ejercicios-beginning-haskell | cap02/src/2-5-Q-ThePerfectMatch.hs | mpl-2.0 | 1,904 | 0 | 9 | 463 | 227 | 131 | 96 | 29 | 1 |
{-# LANGUAGE CPP, ForeignFunctionInterface, InterruptibleFFI #-}
-- | Low level FFI interface. You should rarely need to use this directly.
module Sound.Honk.Internal
(
-- * Types
BeepFd(..)
-- * Core functions
, beepOpen
, beepDo
, beepClose
-- * Convenience functions
, withBeepFd
) where
import Control.Applicative
import Control.Exception (bracket)
import Foreign.C (throwErrnoIfMinus1, throwErrnoIfMinus1_)
import Foreign.C.Types
import Prelude -- GHC 7.10
newtype BeepFd = BeepFd CInt
-- | Open a handle to the console.
--
-- Use 'withBeepFd' instead if possible, since it keeps track of closing
-- the handle automatically.
beepOpen :: IO BeepFd
beepOpen = BeepFd <$> throwErrnoIfMinus1 "beepOpen" c_beepOpen
-- | Perform a beep.
beepDo :: BeepFd -- ^ A console handle, as returned by 'beepOpen'
-> Rational -- ^ Duration, in seconds
-> Double -- ^ Frequency of the beep, in hertz
-> IO ()
beepDo (BeepFd fd) dur freq =
throwErrnoIfMinus1_ "beepDo" $
c_beepDo fd (realToFrac freq) (realToFrac dur)
-- | Close the handle.
beepClose :: BeepFd -> IO ()
beepClose (BeepFd fd) = c_beepClose fd
-- | Run a function that uses a 'BeepFd', opening and closing the
-- handle automatically.
withBeepFd :: (BeepFd -> IO a) -> IO a
withBeepFd = bracket beepOpen beepClose
foreign import ccall "honk.h beep_open"
c_beepOpen :: IO CInt
foreign import ccall interruptible "honk.h beep_do"
c_beepDo :: CInt -> CDouble -> CDouble -> IO CInt
foreign import ccall "honk.h beep_close"
c_beepClose :: CInt -> IO ()
| lfairy/honk | Sound/Honk/Internal.hs | apache-2.0 | 1,605 | 0 | 9 | 342 | 306 | 172 | 134 | 33 | 1 |
--
-- Copyright (c) 2013, Carl Joachim Svenn
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- 1. Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
{-# LANGUAGE ForeignFunctionInterface #-}
module MEnv.Tick.IOS
(
Tick,
tickGet,
tickSet,
tickClockAGet,
tickClockASet,
tickClockAGetSpeed,
tickClockASetSpeed,
tickClockBGet,
tickClockBSet,
tickClockBGetSpeed,
tickClockBSetSpeed,
tickClockCGet,
tickClockCSet,
tickClockCGetSpeed,
tickClockCSetSpeed,
tickClockDGet,
tickClockDSet,
tickClockDGetSpeed,
tickClockDSetSpeed,
tickClockEGet,
tickClockESet,
tickClockEGetSpeed,
tickClockESetSpeed,
tickClockFGet,
tickClockFSet,
tickClockFGetSpeed,
tickClockFSetSpeed,
) where
import Foreign.C.Types
import MyPrelude
import MEnv
-- | time-type
type Tick =
Double
--------------------------------------------------------------------------------
--
foreign import ccall unsafe "ios_tickGet" ios_tickGet
:: IO CDouble
-- | get current tick
tickGet :: MEnv res Tick
tickGet = io $ do
fmap realToFrac ios_tickGet
foreign import ccall unsafe "ios_tickSet" ios_tickSet
:: CDouble -> IO ()
-- | set current tick
tickSet :: Tick -> MEnv res ()
tickSet t = io $ do
ios_tickSet (realToFrac t)
--------------------------------------------------------------------------------
-- clockA
foreign import ccall unsafe "ios_tickClockAGet" ios_tickClockAGet
:: IO CDouble
-- | get tick for ClockA
tickClockAGet :: MEnv res Tick
tickClockAGet = io $ do
fmap realToFrac ios_tickClockAGet
foreign import ccall unsafe "ios_tickClockASet" ios_tickClockASet
:: CDouble -> IO ()
-- | set tick for ClockA
tickClockASet :: Tick -> MEnv res ()
tickClockASet t = io $ do
ios_tickClockASet (realToFrac t)
foreign import ccall unsafe "ios_tickClockASetSpeed" ios_tickClockASetSpeed
:: CDouble -> IO ()
-- | set speed of ClockA.
-- todo: if speed is low, the clock runs less continuous. fix this.
tickClockASetSpeed :: Double -> MEnv res ()
tickClockASetSpeed a = io $ do
ios_tickClockASetSpeed (realToFrac a)
foreign import ccall unsafe "ios_tickClockAGetSpeed" ios_tickClockAGetSpeed
:: IO CDouble
-- | get speed of ClockA
tickClockAGetSpeed :: MEnv res Double
tickClockAGetSpeed = io $ do
fmap realToFrac ios_tickClockAGetSpeed
--------------------------------------------------------------------------------
-- clock B
foreign import ccall unsafe "ios_tickClockBGet" ios_tickClockBGet
:: IO CDouble
-- | get tick for ClockB
tickClockBGet :: MEnv res Tick
tickClockBGet = io $ do
fmap realToFrac ios_tickClockBGet
foreign import ccall unsafe "ios_tickClockBSet" ios_tickClockBSet
:: CDouble -> IO ()
-- | set tick for ClockB
tickClockBSet :: Tick -> MEnv res ()
tickClockBSet t = io $ do
ios_tickClockBSet (realToFrac t)
foreign import ccall unsafe "ios_tickClockBSetSpeed" ios_tickClockBSetSpeed
:: CDouble -> IO ()
-- | set speed of ClockB.
-- todo: if speed is low, the clock runs less continuous. fix this.
tickClockBSetSpeed :: Double -> MEnv res ()
tickClockBSetSpeed a = io $ do
ios_tickClockBSetSpeed (realToFrac a)
foreign import ccall unsafe "ios_tickClockBGetSpeed" ios_tickClockBGetSpeed
:: IO CDouble
-- | get speed of ClockB
tickClockBGetSpeed :: MEnv res Double
tickClockBGetSpeed = io $ do
fmap realToFrac ios_tickClockCGetSpeed
--------------------------------------------------------------------------------
-- clock C
foreign import ccall unsafe "ios_tickClockCGet" ios_tickClockCGet
:: IO CDouble
-- | get tick for ClockC
tickClockCGet :: MEnv res Tick
tickClockCGet = io $ do
fmap realToFrac ios_tickClockCGet
foreign import ccall unsafe "ios_tickClockCSet" ios_tickClockCSet
:: CDouble -> IO ()
-- | set tick for ClockC
tickClockCSet :: Tick -> MEnv res ()
tickClockCSet t = io $ do
ios_tickClockCSet (realToFrac t)
foreign import ccall unsafe "ios_tickClockCSetSpeed" ios_tickClockCSetSpeed
:: CDouble -> IO ()
-- | set speed of ClockC.
-- todo: if speed is low, the clock runs less continuous. fix this.
tickClockCSetSpeed :: Double -> MEnv res ()
tickClockCSetSpeed a = io $ do
ios_tickClockCSetSpeed (realToFrac a)
foreign import ccall unsafe "ios_tickClockCGetSpeed" ios_tickClockCGetSpeed
:: IO CDouble
-- | get speed of ClockC
tickClockCGetSpeed :: MEnv res Double
tickClockCGetSpeed = io $ do
fmap realToFrac ios_tickClockCGetSpeed
--------------------------------------------------------------------------------
-- clock D
foreign import ccall unsafe "ios_tickClockDGet" ios_tickClockDGet
:: IO CDouble
-- | get tick for ClockD
tickClockDGet :: MEnv res Tick
tickClockDGet = io $ do
fmap realToFrac ios_tickClockDGet
foreign import ccall unsafe "ios_tickClockDSet" ios_tickClockDSet
:: CDouble -> IO ()
-- | set tick for ClockD
tickClockDSet :: Tick -> MEnv res ()
tickClockDSet t = io $ do
ios_tickClockDSet (realToFrac t)
foreign import ccall unsafe "ios_tickClockDSetSpeed" ios_tickClockDSetSpeed
:: CDouble -> IO ()
-- | set speed of ClockD.
-- todo: if speed is low, the clock runs less continuous. fix this.
tickClockDSetSpeed :: Double -> MEnv res ()
tickClockDSetSpeed a = io $ do
ios_tickClockDSetSpeed (realToFrac a)
foreign import ccall unsafe "ios_tickClockDGetSpeed" ios_tickClockDGetSpeed
:: IO CDouble
-- | get speed of ClockD
tickClockDGetSpeed :: MEnv res Double
tickClockDGetSpeed = io $ do
fmap realToFrac ios_tickClockDGetSpeed
--------------------------------------------------------------------------------
-- clock E
foreign import ccall unsafe "ios_tickClockEGet" ios_tickClockEGet
:: IO CDouble
-- | get tick for ClockE
tickClockEGet :: MEnv res Tick
tickClockEGet = io $ do
fmap realToFrac ios_tickClockEGet
foreign import ccall unsafe "ios_tickClockESet" ios_tickClockESet
:: CDouble -> IO ()
-- | set tick for ClockE
tickClockESet :: Tick -> MEnv res ()
tickClockESet t = io $ do
ios_tickClockESet (realToFrac t)
foreign import ccall unsafe "ios_tickClockESetSpeed" ios_tickClockESetSpeed
:: CDouble -> IO ()
-- | set speed of ClockE.
-- todo: if speed is low, the clock runs less continuous. fix this.
tickClockESetSpeed :: Double -> MEnv res ()
tickClockESetSpeed a = io $ do
ios_tickClockESetSpeed (realToFrac a)
foreign import ccall unsafe "ios_tickClockEGetSpeed" ios_tickClockEGetSpeed
:: IO CDouble
-- | get speed of ClockE
tickClockEGetSpeed :: MEnv res Double
tickClockEGetSpeed = io $ do
fmap realToFrac ios_tickClockEGetSpeed
--------------------------------------------------------------------------------
-- clock F
foreign import ccall unsafe "ios_tickClockFGet" ios_tickClockFGet
:: IO CDouble
-- | get tick for ClockF
tickClockFGet :: MEnv res Tick
tickClockFGet = io $ do
fmap realToFrac ios_tickClockFGet
foreign import ccall unsafe "ios_tickClockFSet" ios_tickClockFSet
:: CDouble -> IO ()
-- | set tick for ClockF
tickClockFSet :: Tick -> MEnv res ()
tickClockFSet t = io $ do
ios_tickClockFSet (realToFrac t)
foreign import ccall unsafe "ios_tickClockFSetSpeed" ios_tickClockFSetSpeed
:: CDouble -> IO ()
-- | set speed of ClockF.
-- todo: if speed is low, the clock runs less continuous. fix this.
tickClockFSetSpeed :: Double -> MEnv res ()
tickClockFSetSpeed a = io $ do
ios_tickClockFSetSpeed (realToFrac a)
foreign import ccall unsafe "ios_tickClockFGetSpeed" ios_tickClockFGetSpeed
:: IO CDouble
-- | get speed of ClockF
tickClockFGetSpeed :: MEnv res Double
tickClockFGetSpeed = io $ do
fmap realToFrac ios_tickClockFGetSpeed
| karamellpelle/MEnv | source/MEnv/Tick/IOS.hs | bsd-2-clause | 9,072 | 0 | 10 | 1,745 | 1,572 | 834 | 738 | 165 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QDrag_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:18
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QDrag_h where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QDrag ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QDrag_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QDrag_unSetUserMethod" qtc_QDrag_unSetUserMethod :: Ptr (TQDrag a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QDragSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QDrag_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QDrag ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QDrag_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QDragSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QDrag_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QDrag ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QDrag_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QDragSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QDrag_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QDrag ()) (QDrag x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QDrag setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QDrag_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QDrag_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQDrag x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QDrag_setUserMethod" qtc_QDrag_setUserMethod :: Ptr (TQDrag a) -> CInt -> Ptr (Ptr (TQDrag x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QDrag :: (Ptr (TQDrag x0) -> IO ()) -> IO (FunPtr (Ptr (TQDrag x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QDrag_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QDragSc a) (QDrag x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QDrag setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QDrag_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QDrag_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQDrag x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QDrag ()) (QDrag x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QDrag setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QDrag_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QDrag_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQDrag x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QDrag_setUserMethodVariant" qtc_QDrag_setUserMethodVariant :: Ptr (TQDrag a) -> CInt -> Ptr (Ptr (TQDrag x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QDrag :: (Ptr (TQDrag x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQDrag x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QDrag_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QDragSc a) (QDrag x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QDrag setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QDrag_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QDrag_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQDrag x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QDrag ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QDrag_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QDrag_unSetHandler" qtc_QDrag_unSetHandler :: Ptr (TQDrag a) -> CWString -> IO (CBool)
instance QunSetHandler (QDragSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QDrag_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QDrag ()) (QDrag x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDrag1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDrag1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDrag_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDrag x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qDragFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QDrag_setHandler1" qtc_QDrag_setHandler1 :: Ptr (TQDrag a) -> CWString -> Ptr (Ptr (TQDrag x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QDrag1 :: (Ptr (TQDrag x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDrag x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QDrag1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QDragSc a) (QDrag x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDrag1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDrag1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDrag_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDrag x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qDragFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QDrag ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDrag_event cobj_x0 cobj_x1
foreign import ccall "qtc_QDrag_event" qtc_QDrag_event :: Ptr (TQDrag a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QDragSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDrag_event cobj_x0 cobj_x1
instance QsetHandler (QDrag ()) (QDrag x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDrag2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDrag2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDrag_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDrag x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qDragFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QDrag_setHandler2" qtc_QDrag_setHandler2 :: Ptr (TQDrag a) -> CWString -> Ptr (Ptr (TQDrag x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QDrag2 :: (Ptr (TQDrag x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDrag x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QDrag2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QDragSc a) (QDrag x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDrag2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDrag2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDrag_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDrag x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qDragFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QeventFilter_h (QDrag ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QDrag_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QDrag_eventFilter" qtc_QDrag_eventFilter :: Ptr (TQDrag a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QDragSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QDrag_eventFilter cobj_x0 cobj_x1 cobj_x2
| keera-studios/hsQt | Qtc/Gui/QDrag_h.hs | bsd-2-clause | 16,081 | 0 | 18 | 3,806 | 5,490 | 2,616 | 2,874 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
-- | Tests for the "Data.DAWG.Ord" module.
module Ord where
import qualified Control.Monad.State.Strict as E
import qualified Data.Set as S
import qualified Data.Map.Strict as M
import Test.Tasty
import qualified Test.Tasty.SmallCheck as SC
import qualified Test.SmallCheck.Series as SC
import qualified Test.Tasty.QuickCheck as QC
import Test.Tasty.HUnit
import qualified Data.DAWG.Ord as D
tests :: TestTree
tests = testGroup "Tests" [properties, unitTests]
properties :: TestTree
properties = testGroup "Properties" [scProps, qcProps]
scProps = testGroup "(checked by SmallCheck)"
[ SC.testProperty "id == assocs . fromList (up to order)" $
\xs -> M.fromList (D.assocs (D.fromList xs))
== M.fromList (xs :: [(String, Int)])
, SC.testProperty
"Number of states and transitions in a \"full\" langauge" $
SC.changeDepth (+1) $ \n k ->
let dawg = D.fromLang (genFull n k)
in D.numStates dawg == SC.getNonNegative k + 1 &&
D.numEdges dawg ==
SC.getPositive n * SC.getNonNegative k
, SC.testProperty "Actual number of transitions == D.numEdges" $
\xs -> let dawg = D.fromList (xs :: [(String, Int)])
in S.size (walk dawg) == D.numEdges dawg
, SC.testProperty "Actual number of states == D.numStates" $
\xs -> let dawg = D.fromList (xs :: [(String, Int)])
in D.numStates dawg ==
S.size (states (D.root dawg) (walk dawg))
]
qcProps = testGroup "(checked by QuickCheck)"
[ QC.testProperty "id == assocs . fromList (up to order)" $
\xs -> M.fromList (D.assocs (D.fromList xs))
== M.fromList (xs :: [(String, Int)])
, QC.testProperty "Actual number of transitions == D.numEdges" $
\xs -> let dawg = D.fromList (xs :: [(String, Int)])
in S.size (walk dawg) == D.numEdges dawg
, QC.testProperty "Actual number of states == D.numStates" $
\xs -> let dawg = D.fromList (xs :: [(String, Int)])
in D.numStates dawg ==
S.size (states (D.root dawg) (walk dawg))
]
unitTests = testGroup "Unit tests"
[ testCase "Size of a DAWG build from sample data" $ do
let dawg = D.fromList dataSet1
D.numStates dawg @?= 11
D.numEdges dawg @?= 12
]
---------------------------------------------------------------------
-- Sample Data
---------------------------------------------------------------------
-- | Sample dataset no. 1. See also `unitTests`.
dataSet1 :: [(String, Int)]
dataSet1 =
[ ("asdf", 1)
, ("asd", 1)
, ("adf", 1)
, ("df", 1)
, ("asdfg", 3)
, ("sdfg", 3) ]
---------------------------------------------------------------------
-- Utils
---------------------------------------------------------------------
-- | Generate a \"full\" language of words of length `k` over
-- an alphabet of size `n`.
genFull :: SC.Positive Int -> SC.NonNegative Int -> [[Int]]
genFull (SC.Positive n) (SC.NonNegative k) =
genLang n k
where
genLang n 0 = [[]]
genLang n k =
[ x:xs
| xs <- genLang n (k - 1)
, x <- [1 .. n]]
-- | Traverse the automaton and collect all the transitions.
walk :: Ord a => D.DAWG a b -> S.Set (D.ID, a, D.ID)
walk dawg =
flip E.execState S.empty $
flip E.evalStateT S.empty $
doit (D.root dawg)
where
-- The embedded state serves to store the resulting set of
-- transitions; the surface state serves to keep track of
-- already visited nodes.
doit i = do
b <- E.gets $ S.member i
E.when (not b) $ do
E.modify $ S.insert i
E.forM_ (D.edges i dawg) $ \(x, j) -> do
E.lift . E.modify $ S.insert (i, x, j)
-- E.lift . E.modify $ S.insert (i, j)
doit j
-- | Compute the set of states given the set of transitions and
-- the root ID. It works under the assumption that all states
-- are reachable from the start state.
states :: Ord a => a -> S.Set (a, b, a) -> S.Set a
states rootID edgeSet = S.fromList $ rootID : concat
[[i, j] | (i, _, j) <- S.toList edgeSet]
| kawu/dawg-ord | tests/Ord.hs | bsd-2-clause | 4,260 | 0 | 18 | 1,164 | 1,254 | 674 | 580 | 80 | 2 |
module My.Data.SetBy (SetBy
,empty,fromList,fromAscList
,null
,toList,toAscList
,insert,delete,deleteMany,member
,findMin
,partition
,union) where
import Prelude hiding (null)
import qualified Data.Tree.AVL as AVL
import Data.COrdering
import Data.Maybe
import qualified Data.List as L
data SetBy a = SetBy {
cmpFunc :: a -> a -> COrdering a,
tree :: AVL.AVL a
}
instance Show a => Show (SetBy a) where
show (SetBy _ t) = case AVL.asListL t of
[] -> "empty"
l -> "fromList "++show l
empty cmp = SetBy (fstByCC cmp) AVL.empty
fromList cmp l = fromAscList cmp (L.sortBy cmp l)
fromAscList = fromAscList' . fstByCC
fromAscList' cmp l = SetBy cmp (AVL.asTreeL l)
null = AVL.isEmpty . tree
toList = toAscList
toAscList (SetBy _ t) = AVL.asListL t
insert e (SetBy cmp t) = SetBy cmp (AVL.push (cmp e) e t)
delete e (SetBy cmp t) = SetBy cmp (fromMaybe t $ fmap snd $ AVL.tryPop (cmp e) t)
deleteMany l s = foldr delete s l
member e (SetBy cmp t) = isJust $ AVL.tryRead t (cmp e)
findMin (SetBy _ t) = AVL.assertReadL t
partition p s@(SetBy c t) = (fromAscList' c a,fromAscList' c b)
where ~(a,b) = L.partition p $ toAscList s
union (SetBy c t) (SetBy _ t') = SetBy c (AVL.union c t t')
| lih/Alpha | src/My/Data/SetBy.hs | bsd-2-clause | 1,355 | 0 | 11 | 383 | 581 | 302 | 279 | 35 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Database.Drasil.ChunkDB (ChunkDB(defTable), RefbyMap, TraceMap, UMap,
asOrderedList, cdb, collectUnits, conceptMap, conceptinsLookup,
conceptinsTable, dataDefnTable, datadefnLookup, defResolve, gendefLookup,
gendefTable, generateRefbyMap, idMap, insmodelLookup, insmodelTable, -- idMap for docLang
labelledconLookup, labelledcontentTable, refbyLookup, refbyTable,
sectionLookup, sectionTable, symbResolve, termResolve, termTable,
theoryModelLookup, theoryModelTable, traceLookup, traceMap, traceTable) where
import Language.Drasil
import Theory.Drasil (DataDefinition, GenDefn, InstanceModel, TheoryModel)
import Control.Lens ((^.), makeLenses)
import Data.List (sortOn)
import Data.Maybe (fromMaybe, mapMaybe)
import qualified Data.Map as Map
-- The misnomers below are not actually a bad thing, we want to ensure data can't
-- be added to a map if it's not coming from a chunk, and there's no point confusing
-- what the map is for. One is for symbols + their units, and the others are for
-- what they state.
type UMap a = Map.Map UID (a, Int)
-- | A bit of a misnomer as it's really a map of all quantities, for retrieving
-- symbols and their units.
type SymbolMap = UMap QuantityDict
-- | A map of all concepts, normally used for retrieving definitions.
type ConceptMap = UMap ConceptChunk
-- | A map of all the units used. Should be restricted to base units/synonyms.
type UnitMap = UMap UnitDefn
-- | Again a bit of a misnomer as it's really a map of all NamedIdeas.
-- Until these are built through automated means, there will
-- likely be some 'manual' duplication of terms as this map will contain all
-- quantities, concepts, etc.
type TermMap = UMap IdeaDict
type TraceMap = Map.Map UID [UID]
type RefbyMap = Map.Map UID [UID]
type DatadefnMap = UMap DataDefinition
type InsModelMap = UMap InstanceModel
type GendefMap = UMap GenDefn
type TheoryModelMap = UMap TheoryModel
type ConceptInstanceMap = UMap ConceptInstance
type SectionMap = UMap Section
type LabelledContentMap = UMap LabelledContent
cdbMap :: HasUID a => (a -> b) -> [a] -> Map.Map UID (b, Int)
cdbMap fn = Map.fromList . map (\(x,y) -> (x ^. uid, (fn x, y))) . flip zip [1..]
-- | Smart constructor for a 'SymbolMap'
symbolMap :: (Quantity c, MayHaveUnit c) => [c] -> SymbolMap
symbolMap = cdbMap qw
-- | Smart constructor for a 'TermMap'
termMap :: (Idea c) => [c] -> TermMap
termMap = cdbMap nw
-- | Smart constructor for a 'ConceptMap'
conceptMap :: (Concept c) => [c] -> ConceptMap
conceptMap = cdbMap cw
-- | Smart constructor for a 'UnitMap'
unitMap :: (IsUnit u) => [u] -> UnitMap
unitMap = cdbMap unitWrapper
idMap :: HasUID a => [a] -> Map.Map UID (a, Int)
idMap = cdbMap id
traceMap :: [(UID, [UID])] -> TraceMap
traceMap = Map.fromList
-- | Gets a unit if it exists, or Nothing.
getUnitLup :: HasUID c => ChunkDB -> c -> Maybe UnitDefn
getUnitLup m c = getUnit $ symbResolve m (c ^. uid)
-- | Looks up a UID in a UMap table. If nothing is found an error is thrown
uMapLookup :: String -> String -> UID -> UMap a -> a
uMapLookup tys ms u t = getFM $ Map.lookup u t
where getFM = maybe (error $ tys ++ ": " ++ u ++ " not found in " ++ ms) fst
-- | Looks up a UID in the symbol table from the ChunkDB. If nothing is found, an error is thrown.
symbResolve :: ChunkDB -> UID -> QuantityDict
symbResolve m x = uMapLookup "Symbol" "SymbolMap" x $ symbolTable m
-- | Looks up a UID in the term table from the ChunkDB. If nothing is found, an error is thrown.
termResolve :: ChunkDB -> UID -> IdeaDict
termResolve m x = uMapLookup "Term" "TermMap" x $ termTable m
-- | Looks up a UID in the unit table. If nothing is found, an error is thrown.
unitLookup :: UID -> UnitMap -> UnitDefn
unitLookup = uMapLookup "Unit" "UnitMap"
-- | Looks up a UID in the definition table from the ChunkDB. If nothing is found, an error is thrown.
defResolve :: ChunkDB -> UID -> ConceptChunk
defResolve m x = uMapLookup "Concept" "ConceptMap" x $ defTable m
-- | Looks up a uid in the datadefinition table. If nothing is found, an error is thrown.
datadefnLookup :: UID -> DatadefnMap -> DataDefinition
datadefnLookup = uMapLookup "DataDefinition" "DatadefnMap"
-- | Looks up a uid in the instance model table. If nothing is found, an error is thrown.
insmodelLookup :: UID -> InsModelMap -> InstanceModel
insmodelLookup = uMapLookup "InstanceModel" "InsModelMap"
-- | Looks up a uid in the general definition table. If nothing is found, an error is thrown.
gendefLookup :: UID -> GendefMap -> GenDefn
gendefLookup = uMapLookup "GenDefn" "GenDefnMap"
-- | Looks up a uid in the theory model table. If nothing is found, an error is thrown.
theoryModelLookup :: UID -> TheoryModelMap -> TheoryModel
theoryModelLookup = uMapLookup "TheoryModel" "TheoryModelMap"
-- | Looks up a uid in the concept instance table. If nothing is found, an error is thrown.
conceptinsLookup :: UID -> ConceptInstanceMap -> ConceptInstance
conceptinsLookup = uMapLookup "ConceptInstance" "ConceptInstanceMap"
-- | Looks up a uid in the section table. If nothing is found, an error is thrown.
sectionLookup :: UID -> SectionMap -> Section
sectionLookup = uMapLookup "Section" "SectionMap"
-- | Looks up a uid in the labelled content table. If nothing is found, an error is thrown.
labelledconLookup :: UID -> LabelledContentMap -> LabelledContent
labelledconLookup = uMapLookup "LabelledContent" "LabelledContentMap"
asOrderedList :: UMap a -> [a]
asOrderedList = map fst . sortOn snd . map snd . Map.toList
-- | Our chunk databases. Should contain all the maps we will need.
data ChunkDB = CDB { symbolTable :: SymbolMap
, termTable :: TermMap
, defTable :: ConceptMap
, _unitTable :: UnitMap
, _traceTable :: TraceMap
, _refbyTable :: RefbyMap
, _dataDefnTable :: DatadefnMap
, _insmodelTable :: InsModelMap
, _gendefTable :: GendefMap
, _theoryModelTable :: TheoryModelMap
, _conceptinsTable :: ConceptInstanceMap
, _sectionTable :: SectionMap
, _labelledcontentTable :: LabelledContentMap
} --TODO: Expand and add more databases
makeLenses ''ChunkDB
-- | Smart constructor for chunk databases. Takes a list of Quantities
-- (for SymbolTable), NamedIdeas (for TermTable), Concepts (for DefinitionTable),
-- and Units (for UnitTable)
cdb :: (Quantity q, MayHaveUnit q, Idea t, Concept c, IsUnit u) =>
[q] -> [t] -> [c] -> [u] -> [DataDefinition] -> [InstanceModel] ->
[GenDefn] -> [TheoryModel] -> [ConceptInstance] -> [Section] ->
[LabelledContent] -> ChunkDB
cdb s t c u d ins gd tm ci sect lc = CDB (symbolMap s) (termMap t) (conceptMap c)
(unitMap u) Map.empty Map.empty (idMap d) (idMap ins) (idMap gd) (idMap tm)
(idMap ci) (idMap sect) (idMap lc)
collectUnits :: Quantity c => ChunkDB -> [c] -> [UnitDefn]
collectUnits m = map (unitWrapper . flip unitLookup (m ^. unitTable))
. concatMap getUnits . mapMaybe (getUnitLup m)
traceLookup :: UID -> TraceMap -> [UID]
traceLookup c = fromMaybe [] . Map.lookup c
invert :: (Ord v) => Map.Map k [v] -> Map.Map v [k]
invert m = Map.fromListWith (++) pairs
where pairs = [(v, [k]) | (k, vs) <- Map.toList m, v <- vs]
generateRefbyMap :: TraceMap -> RefbyMap
generateRefbyMap = invert
refbyLookup :: UID -> RefbyMap -> [UID]
refbyLookup c = fromMaybe [] . Map.lookup c
| JacquesCarette/literate-scientific-software | code/drasil-database/Database/Drasil/ChunkDB.hs | bsd-2-clause | 7,533 | 0 | 17 | 1,514 | 1,737 | 965 | 772 | 107 | 1 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls #-}
module Nlopt.Bindings( c_nlopt_algorithm_name
, c_nlopt_srand
, c_nlopt_srand_time
, c_nlopt_version
-- * api
, c_nlopt_create
, c_nlopt_destroy
, c_nlopt_copy
, c_nlopt_optimize
, c_nlopt_set_min_objective
, w_nlopt_set_min_objective_1
, c_nlopt_set_max_objective
, w_nlopt_set_max_objective_1
, c_nlopt_get_algorithm
, c_nlopt_get_dimension
-- * constraints
, c_nlopt_set_lower_bounds
, c_nlopt_set_lower_bounds1
, c_nlopt_get_lower_bounds
, c_nlopt_set_upper_bounds
, c_nlopt_set_upper_bounds1
, c_nlopt_get_upper_bounds
, c_nlopt_remove_inequality_constraints
, c_nlopt_add_inequality_constraint
, w_nlopt_add_inequality_constraint_1
, c_nlopt_add_inequality_mconstraint
, w_nlopt_add_inequality_mconstraint_1
, c_nlopt_remove_equality_constraints
, c_nlopt_add_equality_constraint
, w_nlopt_add_equality_constraint_1
, c_nlopt_add_equality_mconstraint
, w_nlopt_add_equality_mconstraint_1
-- * stopping criteria
, c_nlopt_set_stopval
, c_nlopt_get_stopval
, c_nlopt_set_ftol_rel
, c_nlopt_get_ftol_rel
, c_nlopt_set_ftol_abs
, c_nlopt_get_ftol_abs
, c_nlopt_set_xtol_rel
, c_nlopt_get_xtol_rel
, c_nlopt_set_xtol_abs1
, c_nlopt_set_xtol_abs
, c_nlopt_get_xtol_abs
, c_nlopt_set_maxeval
, c_nlopt_get_maxeval
, c_nlopt_set_maxtime
, c_nlopt_get_maxtime
, c_nlopt_force_stop
, c_nlopt_set_force_stop
, c_nlopt_get_force_stop
-- * more algorithm-specific parameters
, c_nlopt_set_local_optimizer
, c_nlopt_set_population
, c_nlopt_get_population
, c_nlopt_set_vector_storage
, c_nlopt_get_vector_storage
, c_nlopt_set_default_initial_step
, c_nlopt_set_initial_step
, c_nlopt_set_initial_step1
, c_nlopt_get_initial_step
, T_nlopt_func
, T_nlopt_mfunc
, S_nlopt_opt_s
) where
import Foreign(Ptr, FunPtr)
import Foreign.C.Types(CUInt(..), CInt(..), CDouble(..), CChar, CULong(..))
import Nlopt.Enums(T_nlopt_result, T_nlopt_algorithm)
type T_nlopt_func = CUInt -> Ptr CDouble -> Ptr CDouble -> Ptr CChar -> IO CDouble
type T_nlopt_mfunc = CUInt -> Ptr CDouble -> CUInt -> Ptr CDouble -> Ptr CDouble -> Ptr CChar -> IO ()
data S_nlopt_opt_s
foreign import ccall "static /usr/local/include/nlopt.h nlopt_algorithm_name"
c_nlopt_algorithm_name :: T_nlopt_algorithm -> IO (Ptr CChar)
foreign import ccall "static /usr/local/include/nlopt.h nlopt_srand"
c_nlopt_srand :: CULong -> IO ()
foreign import ccall "static /usr/local/include/nlopt.h nlopt_srand_time"
c_nlopt_srand_time :: IO ()
foreign import ccall "static /usr/local/include/nlopt.h nlopt_version"
c_nlopt_version :: Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
----------------------------------------------------------------------------------
foreign import ccall "static /usr/local/include/nlopt.h nlopt_create"
c_nlopt_create :: T_nlopt_algorithm -> CUInt -> IO (Ptr S_nlopt_opt_s)
foreign import ccall "static /usr/local/include/nlopt.h &nlopt_destroy"
c_nlopt_destroy :: FunPtr (Ptr S_nlopt_opt_s -> IO ())
foreign import ccall "static /usr/local/include/nlopt.h nlopt_copy"
c_nlopt_copy :: Ptr S_nlopt_opt_s -> IO (Ptr S_nlopt_opt_s)
foreign import ccall "static /usr/local/include/nlopt.h nlopt_optimize"
c_nlopt_optimize :: Ptr S_nlopt_opt_s -> Ptr CDouble -> Ptr CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_min_objective"
c_nlopt_set_min_objective :: Ptr S_nlopt_opt_s -> FunPtr T_nlopt_func -> Ptr CChar -> IO T_nlopt_result
foreign import ccall "wrapper"
w_nlopt_set_min_objective_1 :: T_nlopt_func -> IO (FunPtr T_nlopt_func)
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_max_objective"
c_nlopt_set_max_objective :: Ptr S_nlopt_opt_s -> FunPtr T_nlopt_func -> Ptr CChar -> IO T_nlopt_result
foreign import ccall "wrapper"
w_nlopt_set_max_objective_1 :: T_nlopt_func -> IO (FunPtr T_nlopt_func)
foreign import ccall "static /usr/local/include/nlopt.h nlopt_get_algorithm"
c_nlopt_get_algorithm :: Ptr S_nlopt_opt_s -> IO T_nlopt_algorithm
foreign import ccall "static /usr/local/include/nlopt.h nlopt_get_dimension"
c_nlopt_get_dimension :: Ptr S_nlopt_opt_s -> IO CUInt
-- /* constraints: */
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_lower_bounds"
c_nlopt_set_lower_bounds :: Ptr S_nlopt_opt_s -> Ptr CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_lower_bounds1"
c_nlopt_set_lower_bounds1 :: Ptr S_nlopt_opt_s -> CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_get_lower_bounds"
c_nlopt_get_lower_bounds :: Ptr S_nlopt_opt_s -> Ptr CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_upper_bounds"
c_nlopt_set_upper_bounds :: Ptr S_nlopt_opt_s -> Ptr CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_upper_bounds1"
c_nlopt_set_upper_bounds1 :: Ptr S_nlopt_opt_s -> CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_get_upper_bounds"
c_nlopt_get_upper_bounds :: Ptr S_nlopt_opt_s -> Ptr CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_remove_inequality_constraints"
c_nlopt_remove_inequality_constraints :: Ptr S_nlopt_opt_s -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_add_inequality_constraint"
c_nlopt_add_inequality_constraint :: Ptr S_nlopt_opt_s -> FunPtr T_nlopt_func -> Ptr CChar -> CDouble -> IO T_nlopt_result
foreign import ccall "wrapper"
w_nlopt_add_inequality_constraint_1 :: T_nlopt_func -> IO (FunPtr T_nlopt_func)
foreign import ccall "static /usr/local/include/nlopt.h nlopt_add_inequality_mconstraint"
c_nlopt_add_inequality_mconstraint :: Ptr S_nlopt_opt_s -> CUInt -> FunPtr T_nlopt_mfunc -> Ptr CChar -> Ptr CDouble -> IO T_nlopt_result
foreign import ccall "wrapper"
w_nlopt_add_inequality_mconstraint_1 :: T_nlopt_mfunc -> IO (FunPtr T_nlopt_mfunc)
foreign import ccall "static /usr/local/include/nlopt.h nlopt_remove_equality_constraints"
c_nlopt_remove_equality_constraints :: Ptr S_nlopt_opt_s -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_add_equality_constraint"
c_nlopt_add_equality_constraint :: Ptr S_nlopt_opt_s -> FunPtr T_nlopt_func -> Ptr CChar -> CDouble -> IO T_nlopt_result
foreign import ccall "wrapper"
w_nlopt_add_equality_constraint_1 :: T_nlopt_func -> IO (FunPtr T_nlopt_func)
foreign import ccall "static /usr/local/include/nlopt.h nlopt_add_equality_mconstraint"
c_nlopt_add_equality_mconstraint :: Ptr S_nlopt_opt_s -> CUInt -> FunPtr T_nlopt_mfunc -> Ptr CChar -> Ptr CDouble -> IO T_nlopt_result
foreign import ccall "wrapper"
w_nlopt_add_equality_mconstraint_1 :: T_nlopt_mfunc -> IO (FunPtr T_nlopt_mfunc)
-- /* stopping criteria: */
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_stopval"
c_nlopt_set_stopval :: Ptr S_nlopt_opt_s -> CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_get_stopval"
c_nlopt_get_stopval :: Ptr S_nlopt_opt_s -> IO CDouble
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_ftol_rel"
c_nlopt_set_ftol_rel :: Ptr S_nlopt_opt_s -> CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_get_ftol_rel"
c_nlopt_get_ftol_rel :: Ptr S_nlopt_opt_s -> IO CDouble
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_ftol_abs"
c_nlopt_set_ftol_abs :: Ptr S_nlopt_opt_s -> CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_get_ftol_abs"
c_nlopt_get_ftol_abs :: Ptr S_nlopt_opt_s -> IO CDouble
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_xtol_rel"
c_nlopt_set_xtol_rel :: Ptr S_nlopt_opt_s -> CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_get_xtol_rel"
c_nlopt_get_xtol_rel :: Ptr S_nlopt_opt_s -> IO CDouble
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_xtol_abs1"
c_nlopt_set_xtol_abs1 :: Ptr S_nlopt_opt_s -> CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_xtol_abs"
c_nlopt_set_xtol_abs :: Ptr S_nlopt_opt_s -> Ptr CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_get_xtol_abs"
c_nlopt_get_xtol_abs :: Ptr S_nlopt_opt_s -> Ptr CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_maxeval"
c_nlopt_set_maxeval :: Ptr S_nlopt_opt_s -> CInt -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_get_maxeval"
c_nlopt_get_maxeval :: Ptr S_nlopt_opt_s -> IO CInt
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_maxtime"
c_nlopt_set_maxtime :: Ptr S_nlopt_opt_s -> CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_get_maxtime"
c_nlopt_get_maxtime :: Ptr S_nlopt_opt_s -> IO CDouble
foreign import ccall "static /usr/local/include/nlopt.h nlopt_force_stop"
c_nlopt_force_stop :: Ptr S_nlopt_opt_s -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_force_stop"
c_nlopt_set_force_stop :: Ptr S_nlopt_opt_s -> CInt -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_get_force_stop"
c_nlopt_get_force_stop :: Ptr S_nlopt_opt_s -> IO CInt
-- /* more algorithm-specific parameters */
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_local_optimizer"
c_nlopt_set_local_optimizer :: Ptr S_nlopt_opt_s -> Ptr S_nlopt_opt_s -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_population"
c_nlopt_set_population :: Ptr S_nlopt_opt_s -> CUInt -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_get_population"
c_nlopt_get_population :: Ptr S_nlopt_opt_s -> IO CUInt
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_vector_storage"
c_nlopt_set_vector_storage :: Ptr S_nlopt_opt_s -> CUInt -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_get_vector_storage"
c_nlopt_get_vector_storage :: Ptr S_nlopt_opt_s -> IO CUInt
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_default_initial_step"
c_nlopt_set_default_initial_step :: Ptr S_nlopt_opt_s -> Ptr CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_initial_step"
c_nlopt_set_initial_step :: Ptr S_nlopt_opt_s -> Ptr CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_set_initial_step1"
c_nlopt_set_initial_step1 :: Ptr S_nlopt_opt_s -> CDouble -> IO T_nlopt_result
foreign import ccall "static /usr/local/include/nlopt.h nlopt_get_initial_step"
c_nlopt_get_initial_step :: Ptr S_nlopt_opt_s -> Ptr CDouble -> Ptr CDouble -> IO T_nlopt_result
| ghorn/nlopt-haskell | Nlopt/Bindings.hs | bsd-3-clause | 12,342 | 0 | 12 | 2,599 | 1,908 | 989 | 919 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Web.Stripe.Card
( Card(..)
, RequestCard(..)
, rCardKV
) where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero)
import Data.Aeson (FromJSON (..), Value (..), (.:))
import qualified Data.ByteString as B
import qualified Data.Text as T
import Web.Stripe.Utils (optionalArgs, showByteString,
textToByteString)
-- | Represents a credit card in the Stripe system.
data Card = Card
{ cardType :: T.Text
, cardCountry :: Maybe T.Text
, cardLastFour :: T.Text
, cardExpMonth :: Int
, cardExpYear :: Int
} deriving Show
-- | Represents a credit car (with full details) that is used as input to the
-- Stripe API.
data RequestCard = RequestCard
{ rCardNumber :: T.Text
, rCardExpMonth :: Int
, rCardExpYear :: Int
, rCardCVC :: Maybe T.Text -- ^ Highly recommended to supply
, rCardFullName :: Maybe T.Text
, rCardAddrLineOne :: Maybe T.Text
, rCardAddrLineTwo :: Maybe T.Text
, rCardAddrZip :: Maybe T.Text
, rCardAddrState :: Maybe T.Text
, rCardAddrCountry :: Maybe T.Text
} deriving Show
-- | Turns a 'RequestCard' into a list of key-value pairs that can be submitted
-- to the Stripe API in a query.
rCardKV :: RequestCard -> [(B.ByteString, B.ByteString)]
rCardKV rc = fd ++ optionalArgs md
where
-- Required
fd = [ ("card[number]", textToByteString $ rCardNumber rc)
, ("card[exp_month]", showByteString $ rCardExpMonth rc)
, ("card[exp_year]", showByteString $ rCardExpYear rc)
]
-- Optional
md = [ ("card[cvc]", textToByteString <$> rCardCVC rc)
, ("card[name]", textToByteString <$> rCardFullName rc)
, ("card[address_line_1]", textToByteString <$> rCardAddrLineOne rc)
, ("card[address_line_2]", textToByteString <$> rCardAddrLineTwo rc)
, ("card[address_zip]", textToByteString <$> rCardAddrZip rc)
, ("card[address_state]", textToByteString <$> rCardAddrState rc)
, ("card[address_country]", textToByteString <$> rCardAddrCountry rc)
]
------------------
-- JSON Parsing --
------------------
-- | Attempts to parse JSON into a credit 'Card'.
instance FromJSON Card where
parseJSON (Object v) = Card
<$> v .: "type"
<*> v .: "country"
<*> v .: "last4"
<*> v .: "exp_month"
<*> v .: "exp_year"
parseJSON _ = mzero
| dbp/hs-stripe | src/Web/Stripe/Card.hs | bsd-3-clause | 2,675 | 0 | 15 | 811 | 564 | 335 | 229 | 51 | 1 |
module Module5.Task21 where
import Control.Monad.State (State, state)
import Control.Monad.Writer (Writer, runWriter)
writerToState :: Monoid w => Writer w a -> State w a
writerToState m = let
(a, w) = runWriter m
in state $ \e -> (a, e `mappend` w)
| dstarcev/stepic-haskell | src/Module5/Task21.hs | bsd-3-clause | 255 | 0 | 10 | 46 | 110 | 61 | 49 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Test.Hspec
import Vim
import Data.Text (Text)
main :: IO ()
main = hspec $ do
describe "parseMsg" $ do
it "parses nicely" $ do
parseMsg "[1,\"Hello!\"]" `shouldBe` (1,"Hello!")
| lesguillemets/rainfall-vim-hs | test/TVim.hs | bsd-3-clause | 245 | 0 | 15 | 59 | 77 | 40 | 37 | 9 | 1 |
module Email where
-- Modification of the Email example, that leaves the validation
-- functions polymorphic.
-- This lets us choose whether to accumulate all errors, by specialising
-- to AccValidation, or abort on the first error with Validation.
-- Aside from main, the code is unchanged but the type signatures have
-- been relaxed to be as polymorphic as possible.
import Prelude
import Control.Applicative
import Control.Lens
import Data.List (isInfixOf)
import Data.Validation
newtype Email = Email String deriving (Show)
data VError = MustNotBeEmpty
| MustContainAt
| MustContainPeriod
deriving (Show)
-- ***** Base smart constructors *****
-- String must contain an '@' character
atString :: Validate f => String -> f [VError] ()
atString x = if "@" `isInfixOf` x
then _Success # ()
else _Failure # [MustContainAt]
-- String must contain an '.' character
periodString :: Validate f => String -> f [VError] ()
periodString x = if "." `isInfixOf` x
then _Success # ()
else _Failure # [MustContainPeriod]
-- String must not be empty
nonEmptyString :: Validate f => String -> f [VError] ()
nonEmptyString x = if x /= []
then _Success # ()
else _Failure # [MustNotBeEmpty]
-- ***** Combining smart constructors *****
email :: (Validate f, Applicative (f [VError])) => String -> f [VError] Email
email x = pure (Email x) <*
nonEmptyString x <*
atString x <*
periodString x
-- ***** Example usage *****
success :: (Applicative (f [VError]), Validate f) => f [VError] Email
success = email "[email protected]"
-- AccSuccess (Email "[email protected]")
failureAt :: (Applicative (f [VError]), Validate f) => f [VError] Email
failureAt = email "bobgmail.com"
-- AccFailure [MustContainAt]
failurePeriod :: (Applicative (f [VError]), Validate f) => f [VError] Email
failurePeriod = email "bob@gmailcom"
-- AccFailure [MustContainPeriod]
failureAll :: (Applicative (f [VError]), Validate f) => f [VError] Email
failureAll = email ""
-- AccFailure [MustNotBeEmpty,MustContainAt,MustContainPeriod]
-- Helper to force a validation to AccValidation
asAcc :: AccValidation a b -> AccValidation a b
asAcc = id
-- Helper to force a validation to Validation
asVal :: Validation a b -> Validation a b
asVal = id
main :: IO ()
main = do
putStrLn "Collect all errors"
putStrLn $ "email \"[email protected]\": " ++ show (asAcc success)
putStrLn $ "email \"bobgmail.com\": " ++ show (asAcc failureAt)
putStrLn $ "email \"bob@gmailcom\": " ++ show (asAcc failurePeriod)
putStrLn $ "email \"\": " ++ show (asAcc failureAll)
putStrLn "Stop at the first error"
putStrLn $ "email \"[email protected]\": " ++ show (asVal success)
putStrLn $ "email \"\": " ++ show (asVal failureAll)
| tonymorris/validation | examples/PolymorphicEmail.hs | bsd-3-clause | 2,881 | 0 | 10 | 649 | 722 | 382 | 340 | 50 | 2 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Snap.Chat.Types.Tests (tests) where
------------------------------------------------------------------------------
import Control.Applicative
import Control.Monad
import Data.Aeson
import Data.Aeson.Types
import qualified Data.Attoparsec as A
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as L
import Data.Text (Text)
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2
------------------------------------------------------------------------------
import Snap.Chat.Test.Common
import Snap.Chat.Internal.Types
------------------------------------------------------------------------------
tests :: [Test]
tests = [ testMessageJsonInvertible
, testMessageJsonInstance
, testTrivials
]
------------------------------------------------------------------------------
testMessageJsonInvertible :: Test
testMessageJsonInvertible = testProperty "types/messageJsonInvertible" prop
where
prop :: Message -> Bool
prop = propJSONInvertible
------------------------------------------------------------------------------
testMessageJsonInstance :: Test
testMessageJsonInstance = testCase "types/messageJsonInstance" $ do
!_ <- return $! res1
!_ <- return $! res2
!_ <- return $! res3
!_ <- return $! res4
return ()
where
text1 = "foo-text-1"
text2 = "foo-text-2"
text4 = "foo-text-4"
contents1 = Talk text1
contents2 = Action text2
contents3 = Join
contents4 = Leave text4
tm = 12345678
msg1 = Message "user1" tm contents1
msg2 = Message "user2" tm contents2
msg3 = Message "user3" tm contents3
msg4 = Message "user4" tm contents4
str1 = S.concat $ L.toChunks $ encode msg1
str2 = S.concat $ L.toChunks $ encode msg2
str3 = S.concat $ L.toChunks $ encode msg3
str4 = S.concat $ L.toChunks $ encode msg4
(Object json1) = fromRight $ A.parseOnly json str1
(Object json2) = fromRight $ A.parseOnly json str2
(Object json3) = fromRight $ A.parseOnly json str3
(Object json4) = fromRight $ A.parseOnly json str4
check :: String -> (a -> Bool) -> Parser a -> Parser ()
check s f p = do
v <- p
if f v then return () else fail s
p1 = do
check "user not user1" (==("user1"::Text)) $ json1 .: "user"
check "time doesn't match" (==tm) (toEnum <$> json1 .: "time")
contents <- json1 .: "contents"
check "type isn't talk" (==("talk"::Text)) $ contents .: "type"
check "text doesn't match" (==text1) $ contents .: "text"
return ()
p2 = do
check "user not user2" (==("user2"::Text)) $ json2 .: "user"
check "time doesn't match" (==tm) (toEnum <$> json2 .: "time")
contents <- json2 .: "contents"
check "type isn't action" (==("action"::Text)) $ contents .: "type"
check "text doesn't match" (==text2) $ contents .: "text"
return ()
p3 = do
check "user not user3" (==("user3"::Text)) $ json3 .: "user"
check "time doesn't match" (==tm) (toEnum <$> json3 .: "time")
contents <- json3 .: "contents"
check "type isn't join" (==("join"::Text)) $ contents .: "type"
return ()
p4 = do
check "user not user4" (==("user4"::Text)) $ json4 .: "user"
check "time doesn't match" (==tm) (toEnum <$> json4 .: "time")
contents <- json4 .: "contents"
check "type isn't leave" (==("leave"::Text)) $ contents .: "type"
check "text doesn't match" (==text4) $ contents .: "text"
return ()
res1 = fromRight $ parseEither (const p1) ()
res2 = fromRight $ parseEither (const p2) ()
res3 = fromRight $ parseEither (const p3) ()
res4 = fromRight $ parseEither (const p4) ()
------------------------------------------------------------------------------
testTrivials :: Test
testTrivials = testCase "types/trivials" $ do
mapM_ coverEqInstance contents
mapM_ coverShowInstance contents
mapM_ coverEqInstance messages
mapM_ coverShowInstance messages
where
contents = [ Talk ""
, Action ""
, Join
, Leave ""
]
messages = map (Message "" 0) contents
| snapframework/cufp2011 | test/suite/Snap/Chat/Types/Tests.hs | bsd-3-clause | 4,495 | 0 | 13 | 1,118 | 1,230 | 642 | 588 | 98 | 2 |
-- |
-- Module : Language.CFamily.C.Parser.Builtin
-- Copyright : (c) 2001 Manuel M. T. Chakravarty
-- License : BSD-style
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module provides information about builtin entities.
--
-- Currently, only builtin type names are supported. The only builtin type
-- name is `__builtin_va_list', which is a builtin of GNU C.
--
module Language.CFamily.C.Builtin (
builtinTypeNames
) where
import Language.CFamily.Data.Ident (Ident, builtinIdent)
-- predefined type names
--
builtinTypeNames :: [Ident]
builtinTypeNames = [builtinIdent "__builtin_va_list"]
| micknelso/language-c | src/Language/CFamily/C/Builtin.hs | bsd-3-clause | 647 | 0 | 6 | 107 | 61 | 44 | 17 | 5 | 1 |
module SAWScript.Prover.ABC
( proveABC
, w4AbcAIGER
, w4AbcVerilog
, abcSatExternal
) where
import Control.Monad (unless)
import Control.Monad.IO.Class
import qualified Data.ByteString.Char8 as C8
import Data.Char (isSpace)
import Data.List (isPrefixOf)
import qualified Data.Map as Map
import Data.Maybe
import Data.Set (Set)
import qualified Data.Text as Text
import Text.Read (readMaybe)
import System.Directory
import System.IO
import System.IO.Temp (emptySystemTempFile)
import System.Process (readProcessWithExitCode)
import qualified Data.AIG as AIG
import Verifier.SAW.FiniteValue
import Verifier.SAW.Name
import Verifier.SAW.SATQuery
import Verifier.SAW.SharedTerm
import qualified Verifier.SAW.Simulator.BitBlast as BBSim
import SAWScript.Proof(Prop, propToSATQuery, propSize, goalProp, ProofGoal, goalType, goalNum, CEX)
import SAWScript.Prover.SolverStats (SolverStats, solverStats)
import qualified SAWScript.Prover.Exporter as Exporter
import SAWScript.Prover.Util (liftCexBB, liftLECexBB)
import SAWScript.Value
-- crucible-jvm
-- TODO, very weird import
import Lang.JVM.ProcessUtils (readProcessExitIfFailure)
-- | Bit-blast a proposition and check its validity using ABC.
proveABC ::
(AIG.IsAIG l g) =>
AIG.Proxy l g ->
Prop ->
TopLevel (Maybe CEX, SolverStats)
proveABC proxy goal = getSharedContext >>= \sc -> liftIO $
do satq <- propToSATQuery sc mempty goal
BBSim.withBitBlastedSATQuery proxy sc mempty satq $ \be lit shapes ->
do let (ecs,fts) = unzip shapes
res <- getModel ecs fts =<< AIG.checkSat be lit
let stats = solverStats "ABC" (propSize goal)
return (res, stats)
getModel ::
Show name =>
[name] ->
[FiniteType] ->
AIG.SatResult ->
IO (Maybe [(name, FirstOrderValue)])
getModel argNames shapes satRes =
case satRes of
AIG.Unsat -> return Nothing
AIG.Sat cex -> do
case liftCexBB shapes cex of
Left err -> fail ("Can't parse counterexample: " ++ err)
Right vs
| length argNames == length vs ->
return (Just (zip argNames (map toFirstOrderValue vs)))
| otherwise ->
fail $ unwords [ "ABC SAT results do not match expected arguments"
, show argNames, show vs]
AIG.SatUnknown -> fail "Unknown result from ABC"
w4AbcVerilog ::
Set VarIndex ->
Bool ->
Prop ->
TopLevel (Maybe CEX, SolverStats)
w4AbcVerilog = w4AbcExternal Exporter.writeVerilogSAT cmd
where cmd tmp tmpCex = "%read " ++ tmp ++
"; %blast; &sweep -C 5000; &syn4; &cec -m; write_aiger_cex " ++
tmpCex
w4AbcAIGER ::
Set VarIndex ->
Bool ->
Prop ->
TopLevel (Maybe CEX, SolverStats)
w4AbcAIGER =
do w4AbcExternal Exporter.writeAIG_SAT cmd
where cmd tmp tmpCex = "read_aiger " ++ tmp ++ "; sat; write_cex " ++ tmpCex
w4AbcExternal ::
(FilePath -> SATQuery -> TopLevel [(ExtCns Term, FiniteType)]) ->
(String -> String -> String) ->
Set VarIndex ->
Bool ->
Prop ->
TopLevel (Maybe CEX, SolverStats)
w4AbcExternal exporter argFn unints _hashcons goal =
-- Create temporary files
do let tpl = "abc_verilog.v"
tplCex = "abc_verilog.cex"
sc <- getSharedContext
tmp <- liftIO $ emptySystemTempFile tpl
tmpCex <- liftIO $ emptySystemTempFile tplCex
satq <- liftIO $ propToSATQuery sc unints goal
(argNames, argTys) <- unzip <$> exporter tmp satq
-- Run ABC and remove temporaries
let execName = "abc"
args = ["-q", argFn tmp tmpCex]
(_out, _err) <- liftIO $ readProcessExitIfFailure execName args
cexText <- liftIO $ C8.unpack <$> C8.readFile tmpCex
liftIO $ removeFile tmp
liftIO $ removeFile tmpCex
-- Parse and report results
let stats = solverStats "abc_verilog" (propSize goal)
res <- if all isSpace cexText
then return Nothing
else do cex <- liftIO $ parseAigerCex cexText argTys
case cex of
Left parseErr -> fail parseErr
Right vs -> return $ Just model
where model = zip argNames (map toFirstOrderValue vs)
return (res, stats)
parseAigerCex :: String -> [FiniteType] -> IO (Either String [FiniteValue])
parseAigerCex text tys =
case lines text of
-- Output from `write_cex`
[cex] ->
case words cex of
[bits] -> liftCexBB tys <$> mapM bitToBool bits
_ -> fail $ "invalid counterexample line: " ++ cex
-- Output from `write_aiger_cex`
[_, cex] ->
case words cex of
[bits, _] -> liftLECexBB tys <$> mapM bitToBool bits
_ -> fail $ "invalid counterexample line: " ++ cex
_ -> fail $ "invalid counterexample text: " ++ text
where
bitToBool '0' = return False
bitToBool '1' = return True
bitToBool c = fail ("invalid bit: " ++ [c])
abcSatExternal :: MonadIO m =>
(AIG.IsAIG l g) =>
AIG.Proxy l g ->
SharedContext ->
Bool ->
String ->
[String] ->
ProofGoal ->
m (Maybe CEX, SolverStats)
abcSatExternal proxy sc doCNF execName args g = liftIO $
do satq <- propToSATQuery sc mempty (goalProp g)
let cnfName = goalType g ++ show (goalNum g) ++ ".cnf"
(path, fh) <- openTempFile "." cnfName
hClose fh -- Yuck. TODO: allow writeCNF et al. to work on handles.
let args' = map replaceFileName args
replaceFileName "%f" = path
replaceFileName a = a
BBSim.withBitBlastedSATQuery proxy sc mempty satq $ \be l shapes -> do
variables <- (if doCNF then AIG.writeCNF else writeAIGWithMapping) be l path
(_ec, out, err) <- readProcessWithExitCode execName args' ""
removeFile path
unless (null err) $
print $ unlines ["Standard error from SAT solver:", err]
let ls = lines out
sls = filter ("s " `isPrefixOf`) ls
vls = filter ("v " `isPrefixOf`) ls
let stats = solverStats ("external SAT:" ++ execName) (propSize (goalProp g))
case (sls, vls) of
(["s SATISFIABLE"], _) -> do
let bs = parseDimacsSolution variables vls
let r = liftCexBB (map snd shapes) bs
argNames = map (Text.unpack . toShortName . ecName . fst) shapes
ecs = map fst shapes
case r of
Left msg -> fail $ "Can't parse counterexample: " ++ msg
Right vs
| length ecs == length vs -> do
return (Just (zip ecs (map toFirstOrderValue vs)), stats)
| otherwise -> fail $ unwords ["external SAT results do not match expected arguments", show argNames, show vs]
(["s UNSATISFIABLE"], []) ->
return (Nothing, stats)
_ -> fail $ "Unexpected result from SAT solver:\n" ++ out
parseDimacsSolution :: [Int] -- ^ The list of CNF variables to return
-> [String] -- ^ The value lines from the solver
-> [Bool]
parseDimacsSolution vars ls = map lkup vars
where
vs :: [Int]
vs = concatMap (filter (/= 0) . mapMaybe readMaybe . tail . words) ls
varToPair n | n < 0 = (-n, False)
| otherwise = (n, True)
assgnMap = Map.fromList (map varToPair vs)
lkup v = Map.findWithDefault False v assgnMap
writeAIGWithMapping :: AIG.IsAIG l g => g s -> l s -> FilePath -> IO [Int]
writeAIGWithMapping be l path = do
nins <- AIG.inputCount be
AIG.writeAiger path (AIG.Network be [l])
return [1..nins]
| GaloisInc/saw-script | src/SAWScript/Prover/ABC.hs | bsd-3-clause | 7,588 | 3 | 29 | 2,102 | 2,317 | 1,182 | 1,135 | -1 | -1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TemplateHaskell #-}
module Kalium.Pascal.Convert (convert) where
import Kalium.Prelude
import Kalium.Util
import Control.Monad.Reader
import Control.Monad.Except
import Control.Monad.Rename
import Control.Exception
import Control.Lens (ix)
import qualified Data.Map as M
import Control.Monad.Trans.Maybe
-- S for Src, D for Dest
import qualified Kalium.Pascal.Program as S
import qualified Kalium.Nucleus.Scalar.Program as D
import qualified Kalium.Nucleus.Scalar.Build as D
declareLenses [d|
data TypeScope = TypeScope
{ tsFunctions :: Map S.Name S.FuncSig
, tsVariables :: Map S.Name S.Type
} deriving (Eq)
data ConvScope = ConvScope
{ csTypes :: TypeScope
, csNames :: Map Bool (Map S.Name D.Name)
} deriving (Eq)
|]
instance Exception ErrorTypecheck
data ErrorTypecheck = ErrorTypecheck
deriving (Show)
instance Exception ErrorNoAccess
data ErrorNoAccess = ErrorNoAccess String [String]
deriving (Show)
instance Exception ErrorNoFunction
data ErrorNoFunction = ErrorNoFunction String
deriving (Show)
instance Exception ErrorNotImplemented
data ErrorNotImplemented = ErrorNotImplemented String
deriving (Show)
instance Exception ErrorArgumentMismatch
data ErrorArgumentMismatch = ErrorArgumentMismatch String
deriving (Show)
type E e m = (Applicative m, MonadError SomeException m)
type (~>) a b = forall e m . (MonadReader ConvScope m, E e m) => Kleisli' m a b
type (~>.) a b = forall e m . (MonadReader ConvScope m, E e m, MonadNameGen m) => Kleisli' m a b
convert :: (E e m, MonadNameGen m) => S.Program -> m (D.Complex D.Program)
convert program = do
let initScope = ConvScope (TypeScope mempty mempty)
(M.fromList (liftA2(,)[True,False][mempty]))
runReaderT (conv program) initScope
nameV, nameF :: S.Name ~> D.Name
nameV = lookupName False
nameF = lookupName True
lookupName :: Bool -> S.Name ~> D.Name
lookupName ct name = do
names <- views csNames (M.! ct)
let mname = M.lookup name names
(throwMaybe.SomeException) (ErrorNoAccess name (M.keys names)) mname
alias :: (Applicative m, MonadNameGen m) => Kleisli' m S.Name D.Name
alias name = D.NameGen <$> mkname (Just name)
opUnit = D.Call (D.NameSpecial D.OpUnit) [] []
opTrue = D.Call (D.NameSpecial D.OpTrue) [] []
opFalse = D.Call (D.NameSpecial D.OpFalse) [] []
opNil t = D.Call (D.NameSpecial D.OpNil) [t] []
opCons x xs = D.Call (D.NameSpecial D.OpCons) [] [x, xs]
opAssign :: D.Name -> a -> D.Statement (D.Configuration param D.Pattern a)
opAssign name a = D.statement $ D.Exec (D.PAccess name) (D.NameSpecial D.OpId) [] [a]
class Conv s where
type Scalar s :: *
conv :: s ~>. Scalar s
instance Conv S.Program where
type Scalar S.Program = D.Complex D.Program
conv (S.Program funcs vars body) = do
(mconcat -> funcNames) <- for funcs $ \(S.Func name _ _ _) -> do
funcName <- alias name
return $ M.singleton name funcName
local ( (csTypes . tsFunctions %~ mappend funcSigs)
. (csNames %~ M.adjust (mappend funcNames) True)
) $ do
clMain <- do
clBody <- convScope vars
$ D.Body <$> conv body <*> pure opUnit
let noparams = D.Scope ([] :: Pairs D.Name D.ByType)
return $ D.Func D.TypeUnit (noparams clBody)
clFuncs <- traverse conv funcs
let programFuncs = (D.NameSpecial D.OpMain, clMain):clFuncs
return $ D.Program (M.fromList programFuncs)
where funcSigs = mconcat (map funcSigOf funcs)
funcSigOf (S.Func name funcSig _ _) = M.singleton name funcSig
convScope vardecls inner = do
(mconcat -> varNames, scopeVars)
<- unzip <$> traverse convVardecl (M.toList vardecls)
scopeElem <- local ( (csTypes . tsVariables %~ mappend vardecls)
. (csNames %~ M.adjust (mappend varNames) False)
) inner
return $ D.Scope (D.scoping scopeVars) scopeElem
where convVardecl (name, pasType) = do
varName <- alias name
ty <- conv pasType
return (M.singleton name varName, (varName, ty))
convScope' paramdecls inner = do
(mconcat -> paramNames, scopeVars)
<- unzip <$> traverse convParamdecl paramdecls
scopeElem <- local ( (csTypes . tsVariables %~ mappend vardecls)
. (csNames %~ M.adjust (mappend paramNames) False)
) inner
return $ D.Scope scopeVars scopeElem
where paramDeclToTup (S.ParamDecl name (_, ty)) = (name, ty)
vardecls = M.fromList $ map paramDeclToTup paramdecls
convParamdecl (S.ParamDecl name (r, pasType)) = do
paramName <- alias name
r' <- conv r
ty <- conv pasType
return (M.singleton name paramName, (paramName, (r', ty)))
instance Conv S.Body where
type Scalar S.Body = D.Complex D.Statement
conv statements = D.follow <$> traverse conv statements
instance Conv S.Func where
type Scalar S.Func = (D.Name, D.Complex D.Func)
conv (S.Func name (S.FuncSig params pasType) vars body) = case pasType of
Nothing -> do
clScope <- convScope' params
$ convScope vars
$ D.Body <$> conv body <*> pure opUnit
fname <- nameF name
return $ (fname, D.Func D.TypeUnit clScope)
Just ty -> do
let retVars = M.singleton name ty
clScope <- convScope' params
$ convScope (vars <> retVars)
$ D.Body <$> conv body <*> (D.Atom . D.Access <$> nameV name)
retType <- conv ty
fname <- nameF name
return (fname, D.Func retType clScope)
instance Conv S.By where
type Scalar S.By = D.By
conv S.ByValue = pure D.ByValue
conv S.ByReference = pure D.ByReference
instance Conv S.Type where
type Scalar S.Type = D.Type
conv = \case
S.TypeInteger -> return D.TypeInteger
S.TypeReal -> return D.TypeDouble
S.TypeBoolean -> return D.TypeBoolean
S.TypeChar -> return D.TypeChar
S.TypeString -> return D.TypeString
S.TypeArray t -> D.TypeApp1 D.TypeList <$> conv t
S.TypeCustom _ -> (throwError.SomeException) (ErrorNotImplemented "Custom types")
binary op a b = D.Call op [] [a,b]
convSetLength [S.Access name', lenExpr'] = do
name <- nameV name'
lenExpr <- typecastConv (==S.TypeInteger) lenExpr'
return $ D.Exec (D.PAccess name) (D.NameSpecial D.OpSetLength) []
[D.expression name, lenExpr]
convSetLength _ = (throwError.SomeException) (ErrorArgumentMismatch "SetLength")
convReadLn [e@(S.Access name')] = do
name <- nameV name'
typecheck e >>= \case
S.TypeString -> return $ D.Exec (D.PAccess name) (D.NameSpecial D.OpGetLn) [] []
ty' -> do
ty <- conv ty'
return $ D.Exec (D.PAccess name) (D.NameSpecial D.OpReadLn) [ty] []
convReadLn _ = (throwError.SomeException) (ErrorArgumentMismatch "ReadLn")
convRead [e@(S.Access name')] = do
name <- nameV name'
typecheck e >>= \case
S.TypeChar -> return $ D.Exec (D.PAccess name) (D.NameSpecial D.OpGetChar) [] []
_ -> (throwError.SomeException) ErrorTypecheck
convRead _ = (throwError.SomeException) (ErrorArgumentMismatch "Read")
convWriteLn ln exprs = do
arg <- traverse convArg exprs <&> \case
[] -> opNil D.TypeChar
args -> foldr1 (binary (D.NameSpecial D.OpConcat)) args
let op | ln = D.NameSpecial D.OpPutLn
| otherwise = D.NameSpecial D.OpPut
return $ D.Exec D.PUnit op [] [arg]
where
convArg expr = do
tcs <- typecasts expr
case keepByFst (==S.TypeString) tcs of
tc:_ -> convExpr tc
[] -> case keepByFst (==S.TypeChar) tcs of
tc:_ -> do
e <- convExpr tc
return $ D.Call (D.NameSpecial D.OpSingleton) [] [e]
[] -> case listToMaybe (map snd tcs) of
Nothing -> (throwError.SomeException) ErrorTypecheck
Just expr' -> do
e <- convExpr expr'
return $ D.Call (D.NameSpecial D.OpShow) [] [e]
typeOfLiteral :: S.Literal -> S.Type
typeOfLiteral = \case
S.LitBool _ -> S.TypeBoolean
S.LitInt _ -> S.TypeInteger
S.LitReal _ -> S.TypeReal
S.LitChar _ -> S.TypeChar
S.LitStr _ -> S.TypeString
typeOfAccess :: S.Name ~> S.Type
typeOfAccess name = do
types <- view (csTypes.tsVariables)
let mtype = M.lookup name types
(throwMaybe.SomeException) (ErrorNoAccess name (M.keys types)) mtype
typecasts :: S.Expression ~> Pairs S.Type S.Expression
typecasts expr = case expr of
S.Primary lit -> nice $ typecasting (typeOfLiteral lit) expr
S.Access name -> do
ty <- typeOfAccess name
nice $ typecasting ty expr
S.Call nameOp args -> do
possibleArgs <- traverse typecasts' args
let calls = S.Call nameOp <$> sequenceA possibleArgs
nice calls
where
nice :: [S.Expression] ~> Pairs S.Type S.Expression
nice exprs = join <$> traverse typechecking exprs
typecasts' expr = map snd <$> typecasts expr
typechecking :: S.Expression ~> Pairs S.Type S.Expression
typechecking expr = maybe empty (\ty -> pure (ty, expr)) <$> typecheck' expr
typecasting :: S.Type -> S.Expression -> [S.Expression]
typecasting ty expr = expr : [op1App tc expr | tc <- tcs]
where tcs = case ty of
S.TypeChar -> [S.OpCharToString]
S.TypeInteger -> [S.OpIntToReal]
_ -> []
typecheck :: S.Expression ~> S.Type
typecheck expr = typecheck' expr >>= (throwMaybe.SomeException) ErrorTypecheck
typecheck' :: S.Expression ~> Maybe S.Type
typecheck' = runMaybeT . \case
S.Primary lit -> return (typeOfLiteral lit)
S.Access name -> typeOfAccess name
S.Call (Right "chr") args -> do
traverse typecheck args >>= \case
[S.TypeInteger] -> return S.TypeChar
_ -> badType
S.Call (Right "ord") args -> do
traverse typecheck args >>= \case
[S.TypeChar] -> return S.TypeInteger
_ -> badType
S.Call (Right "length") args -> do
traverse typecheck args >>= \case
[S.TypeString ] -> return S.TypeInteger
[S.TypeArray _] -> return S.TypeInteger
_ -> badType
S.Call (Right name) args -> do
mfuncsig <- views (csTypes.tsFunctions) (M.lookup name)
case mfuncsig of
Nothing -> (throwError.SomeException) (ErrorNoFunction name)
Just (S.FuncSig params mtype) -> case mtype of
Nothing -> badType
Just t -> do
let tys = params & map (\(S.ParamDecl _ (_, ty)) -> ty)
(sequenceA -> mtyArgs) <- traverse typecheck' args
case mtyArgs of
Just tyArgs | tyArgs == tys -> return t
_ -> badType
S.Call (Left op) args -> do
tys <- traverse typecheck args
let isNumeric = liftA2 (||) (== S.TypeInteger) (== S.TypeReal)
case (op, tys) of
(S.OpAdd , [t1, t2]) | t1 == t2, isNumeric t1 || t1 == S.TypeString -> return t1
(S.OpSubtract, [t1, t2]) | t1 == t2, isNumeric t1 -> return t1
(S.OpMultiply, [t1, t2]) | t1 == t2, isNumeric t1 -> return t1
(S.OpDivide , [S.TypeReal , S.TypeReal ]) -> return S.TypeReal
(S.OpDiv , [S.TypeInteger, S.TypeInteger]) -> return S.TypeInteger
(S.OpMod , [S.TypeInteger, S.TypeInteger]) -> return S.TypeInteger
(S.OpLess , [t1, t2]) | t1 == t2 -> return S.TypeBoolean
(S.OpMore , [t1, t2]) | t1 == t2 -> return S.TypeBoolean
(S.OpLessEquals, [t1, t2]) | t1 == t2 -> return S.TypeBoolean
(S.OpMoreEquals, [t1, t2]) | t1 == t2 -> return S.TypeBoolean
(S.OpEquals , [t1, t2]) | t1 == t2 -> return S.TypeBoolean
(S.OpNotEquals, [t1, t2]) | t1 == t2 -> return S.TypeBoolean
(S.OpAnd , [S.TypeBoolean, S.TypeBoolean]) -> return S.TypeBoolean
(S.OpOr , [S.TypeBoolean, S.TypeBoolean]) -> return S.TypeBoolean
(S.OpXor , [S.TypeBoolean, S.TypeBoolean]) -> return S.TypeBoolean
(S.OpNegate , [t1]) | isNumeric t1 -> return t1
(S.OpPlus , [t1]) | isNumeric t1 -> return t1
(S.OpNot , [S.TypeBoolean]) -> return S.TypeBoolean
(S.OpIx , [S.TypeString , S.TypeInteger]) -> return S.TypeChar
(S.OpIx , [S.TypeArray t1, S.TypeInteger]) -> return t1
(S.OpCharToString, [S.TypeChar ]) -> return S.TypeString
(S.OpIntToReal , [S.TypeInteger]) -> return S.TypeReal
_ -> badType
where badType = MaybeT (return Nothing)
op1App :: S.Operator -> S.Expression -> S.Expression
op1App op e = S.Call (Left op) [e]
typecastConv :: (S.Type -> Bool) -> S.Expression ~>. D.Expression
typecastConv p expr = do
tcs <- typecasts expr
tc <- case keepByFst p tcs of
[] -> (throwError.SomeException) ErrorTypecheck
tc:_ -> return tc
convExpr tc
typecastConv' :: S.Expression ~>. D.Expression
typecastConv' = typecastConv (const True)
instance Conv S.Statement where
type Scalar S.Statement = D.Complex D.Statement
conv = \case
S.BodyStatement body -> D.statement <$> conv body
S.Assign name' mIxExpr' expr' ->
case mIxExpr' of
Nothing -> do
name <- nameV name'
tyW <- typecheck (S.Access name')
expr <- typecastConv (==tyW) expr'
return $ opAssign name expr
Just ixExpr' -> do
ixExpr <- typecastConv (==S.TypeInteger) ixExpr'
name <- nameV name'
tyW <- typecheck (S.Access name') >>= \case
S.TypeString ->
(throwError.SomeException)
(ErrorNotImplemented "String indexing")
S.TypeArray ty -> return ty
_ -> (throwError.SomeException) ErrorTypecheck
elemExpr <- typecastConv (==tyW) expr'
let expr = D.Call (D.NameSpecial D.OpIxSet) []
[ ixExpr, elemExpr
, D.expression (D.Access name) ]
return $ opAssign name expr
S.Execute "read" exprs -> D.statement <$> convRead exprs
S.Execute "readln" exprs -> D.statement <$> convReadLn exprs
S.Execute "write" exprs -> D.statement <$> convWriteLn False exprs
S.Execute "writeln" exprs -> D.statement <$> convWriteLn True exprs
S.Execute "setlength" exprs -> D.statement <$> convSetLength exprs
S.Execute name' exprs' -> do
name <- nameF name'
exprs <- traverse typecastConv' exprs'
return $ D.statement $ D.Exec D.PWildCard name [] exprs
S.ForCycle name fromExpr toExpr statement -> do
clName <- nameV name
clFromExpr <- typecastConv' fromExpr
clToExpr <- typecastConv' toExpr
let clRange = binary (D.NameSpecial D.OpRange) clFromExpr clToExpr
clAction <- conv statement
let clForCycle = D.statement (D.ForCycle clName clRange clAction)
return $ D.follow [clForCycle, opAssign clName clToExpr]
S.IfBranch expr bodyThen mBodyElse
-> fmap D.statement
$ D.If
<$> typecastConv (==S.TypeBoolean) expr
<*> conv bodyThen
<*> (D.statements <$> traverse conv mBodyElse)
S.CaseBranch expr leafs mBodyElse -> do
clType <- typecheck expr >>= conv
clExpr <- typecastConv' expr
clName <- alias "case"
let clCaseExpr = D.expression clName
let instRange = \case
Right (exprFrom, exprTo)
-> binary (D.NameSpecial D.OpElem) clCaseExpr
<$> (binary (D.NameSpecial D.OpRange)
<$> typecastConv' exprFrom <*> typecastConv' exprTo)
Left expr
-> binary (D.NameSpecial D.OpEquals) clCaseExpr
<$> typecastConv' expr
let instLeaf (exprs, body)
= (,)
<$> (foldr1 (binary (D.NameSpecial D.OpOr)) <$> traverse instRange exprs)
<*> conv body
leafs <- traverse instLeaf leafs
leafElse <- D.statements <$> traverse conv mBodyElse
let statement = foldr
(\(cond, ifThen) ifElse ->
D.statement $ D.If cond ifThen ifElse)
leafElse leafs
return $ D.statement $ D.Scope
(M.singleton clName clType)
(D.follow [opAssign clName clExpr, statement])
-- use typecastConv to get typecasting
convExpr :: S.Expression ~>. D.Expression
convExpr = \case
S.Access name -> D.expression <$> nameV name
S.Call name' exprs -> do
let direct' op = D.Call op [] <$> traverse convExpr exprs
let direct = direct' . D.NameSpecial
case name' of
Left S.OpAdd -> do
traverse typecheck' exprs >>= \case
Just S.TypeString : _ -> direct D.OpConcat
_ -> direct D.OpAdd
Left S.OpSubtract -> direct D.OpSubtract
Left S.OpMultiply -> direct D.OpMultiply
Left S.OpDivide -> direct D.OpDivide
Left S.OpDiv -> direct D.OpDiv
Left S.OpMod -> direct D.OpMod
Left S.OpLess -> direct D.OpLess
Left S.OpMore -> direct D.OpMore
Left S.OpLessEquals -> direct D.OpLessEquals
Left S.OpMoreEquals -> direct D.OpMoreEquals
Left S.OpNotEquals -> direct D.OpNotEquals
Left S.OpEquals -> direct D.OpEquals
Left S.OpAnd -> direct D.OpAnd
Left S.OpOr -> direct D.OpOr
Left S.OpXor -> direct D.OpXor
Left S.OpPlus -> direct D.OpId
Left S.OpNegate -> direct D.OpNegate
Left S.OpNot -> direct D.OpNot
Left S.OpIx -> do
let sub e a = D.Call (D.NameSpecial D.OpSubtract) [] [a, e]
one = D.expression (D.LitInteger 1)
traverse typecheck' exprs >>= \case
Just S.TypeString : _ -> D.Call (D.NameSpecial D.OpIx) []
<$> (traverse convExpr exprs <&> ix 1 %~ sub one)
_ -> direct D.OpIx
Left S.OpCharToString -> direct D.OpSingleton
Left S.OpIntToReal -> direct D.OpIntToDouble
Right "length" -> direct D.OpLength
Right "chr" -> direct D.OpChr
Right "ord" -> direct D.OpChrOrd
Right name -> nameF name >>= direct'
S.Primary lit -> conv lit
convLiteral = \case
S.LitInt x -> D.expression (D.LitInteger x)
S.LitReal x -> D.expression (D.LitDouble x)
S.LitStr x -> map (convLiteral . S.LitChar) x & foldr opCons (opNil D.TypeChar)
S.LitChar x -> D.expression (D.LitChar x)
S.LitBool x -> if x then opTrue else opFalse
instance Conv S.Literal where
type Scalar S.Literal = D.Expression
conv = return . convLiteral
| rscprof/kalium | src/Kalium/Pascal/Convert.hs | bsd-3-clause | 19,910 | 13 | 28 | 6,287 | 6,898 | 3,374 | 3,524 | -1 | -1 |
module Write.CycleBreak
( writeHsBootFiles
) where
import Data.HashMap.Strict as M
import Spec.Graph
import Write.Module
import Write.Utils
import Control.Monad(void)
cycleBreakers :: HashMap ModuleName [String]
cycleBreakers = M.fromList [ (ModuleName "Graphics.Vulkan.Device", ["VkDevice"])
, (ModuleName "Graphics.Vulkan.Pass", ["VkRenderPass"])
]
writeHsBootFiles :: FilePath -> SpecGraph -> NameLocations -> IO ()
writeHsBootFiles root graph nameLocations =
void $ M.traverseWithKey (writeHsBootFile root graph nameLocations)
cycleBreakers
writeHsBootFile :: FilePath -- ^ The source root
-> SpecGraph -- ^ The specification graph
-> NameLocations -- ^ The map of names to modules
-> ModuleName -- ^ The module name we're writing
-> [String] -- ^ The symbols to export
-> IO ()
writeHsBootFile root graph nameLocations moduleName exports = do
createModuleDirectory root moduleName
let moduleString = writeModule graph nameLocations moduleName exports
writeFile (moduleNameToFile root moduleName) moduleString
| oldmanmike/vulkan | generate/src/Write/BreakCycle.hs | bsd-3-clause | 1,214 | 0 | 11 | 327 | 248 | 133 | 115 | 24 | 1 |
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}
module Main where
import Lib
import Data.Aeson
import Data.List
import Debug.Trace
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Lazy as B
import GHC.Generics
import Data.Maybe
data Card = Card { name :: String,
manaCost :: Int,
attack :: Maybe Int,
life :: Maybe Int,
cardType :: String,
damage :: Maybe Int
} deriving (Show,Generic)
type Deck = [Card]
type CardWithCost = (Int, Card)
type ZippedCurve = [(Int, [Card])]
data AvailableMana = AvailableMana Int deriving (Ord, Eq, Show)
manaCurve = [1,2,3,4,5,6,7,8,9,10]
manaCurveQuantities = [4,6,6,4,4,4,0,0,0,2]
type Collection = [Card]
jsonFile :: FilePath
jsonFile = "data/cards.json"
instance FromJSON Card
instance ToJSON Card
getJSON :: IO B.ByteString
getJSON = B.readFile jsonFile
baseScore :: (Maybe Int, Maybe Int, Maybe Int ,Int) -> Int
baseScore (Just damage, Nothing, Nothing, manaCost) = damage
baseScore (Nothing, Just attack, Just life, manaCost) = (attack + life)
evaluateCard :: Int -> Card -> Int
evaluateCard mana card =
if mana >= manaCost card
then baseScore (damage card, attack card, life card, manaCost card)
else -100
withMana :: Int -> Card -> CardWithCost
withMana mana card = (mana, card)
sortCollectionForMana :: Int -> Collection -> [CardWithCost]
sortCollectionForMana mana collection = sortBy sortCard (map (withMana mana) collection)
sortCard :: CardWithCost -> CardWithCost -> Ordering
sortCard (m1,c1) (m2,c2)
| evaluateCard m1 c1 < evaluateCard m2 c2 = GT
| evaluateCard m1 c1 > evaluateCard m2 c2 = LT
| evaluateCard m1 c1 == evaluateCard m2 c2 = EQ
createCurve :: Collection -> [[Card]]
createCurve collection = map (removeManaCost) [ sortCollectionForMana mana collection | mana <- manaCurve ]
removeManaCost :: [CardWithCost] -> [Card]
removeManaCost list = map (snd) list
zipCurve :: [[Card]] -> ZippedCurve
zipCurve curve = zip manaCurveQuantities curve
applyCurve :: ZippedCurve -> Deck
applyCurve list = concat [ take quantity cards | (quantity, cards) <- list]
buildDeck :: Collection -> Deck
buildDeck [] = []
buildDeck collection = applyCurve (zipCurve (createCurve collection))
main :: IO ()
main = do
-- Get JSON data and decode it
d <- (eitherDecode <$> getJSON) :: IO (Either String [Card])
-- If d is Left, the JSON was malformed.
-- In that case, we report the error.
-- Otherwise, we perform the operation of
-- our choice. In this case, just print it.
case d of
Left err -> putStrLn err
Right collection -> print (map name (buildDeck collection))
| JoePym/hs-deck-builder | app/Main.hs | bsd-3-clause | 2,703 | 0 | 14 | 551 | 919 | 503 | 416 | 65 | 2 |
module AERN2.Local.SineCosine where
import MixedTypesNumPrelude
-- import AERN2.RealFun.SineCosine
-- import AERN2.MP
-- import AERN2.Real
-- import AERN2.RealFun.Operations
import AERN2.Local.Basics
instance
-- (HasDomain f, CanApplyApprox f (Domain f)
-- , ConvertibleExactly (ApplyApproxType f (Domain f)) MPBall
-- , CanNegSameType f, CanAddSameType f, CanMulSameType f
-- , CanAddSubMulDivCNBy f Integer, CanAddSubMulDivCNBy f CauchyReal
-- , HasAccuracy f, CanSetPrecision f, CanReduceSizeUsingAccuracyGuide f
-- , IsBall f
-- , Show f)
(CanSinCosSameType f)
=>
CanSinCos (Local f)
where
sin f =
\l r ac -> sin (f l r ac)
cos f =
\l r ac -> cos (f l r ac)
| michalkonecny/aern2 | aern2-fun-univariate/src/AERN2/Local/SineCosine.hs | bsd-3-clause | 698 | 0 | 9 | 134 | 110 | 64 | 46 | 10 | 0 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Text.CSL.Data
-- Copyright : (c) John MacFarlane
-- License : BSD-style (see LICENSE)
--
-- Maintainer : John MacFarlane <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-----------------------------------------------------------------------------
module Text.CSL.Data
( getLocale
, getDefaultCSL
, langBase
) where
import System.FilePath ()
import qualified Data.ByteString.Lazy as L
#ifdef EMBED_DATA_FILES
import Data.Maybe (fromMaybe)
import Text.CSL.Data.Embedded (localeFiles, defaultCSL)
import qualified Data.ByteString as S
#else
import Paths_pandoc_citeproc (getDataFileName)
import System.Directory (doesFileExist)
#endif
getLocale :: String -> IO L.ByteString
getLocale s = do
#ifdef EMBED_DATA_FILES
f <- case length s of
0 -> maybe (return S.empty) return
$ lookup "locales-en-US.xml" localeFiles
2 -> let fn = ("locales-" ++ fromMaybe s (lookup s langBase) ++ ".xml")
in case lookup fn localeFiles of
Just x' -> return x'
_ -> error $ "could not find locale data for " ++ s
_ -> case lookup ("locales-" ++ take 5 s ++ ".xml") localeFiles of
Just x' -> return x'
_ -> -- try again with 2-letter locale
let s' = take 2 s in
case lookup ("locales-" ++ fromMaybe s'
(lookup s' langBase) ++ ".xml") localeFiles of
Just x'' -> return x''
_ -> error $
"could not find locale data for " ++ s
return $ L.fromChunks [f]
#else
f <- case length s of
0 -> return "locales/locales-en-US.xml"
2 -> getDataFileName ("locales/locales-" ++
maybe "en-US" id (lookup s langBase) ++ ".xml")
_ -> getDataFileName ("locales/locales-" ++ take 5 s ++ ".xml")
exists <- doesFileExist f
if not exists && length s > 2
then getLocale $ take 2 s -- try again with base locale
else L.readFile f
#endif
getDefaultCSL :: IO L.ByteString
getDefaultCSL =
#ifdef EMBED_DATA_FILES
return $ L.fromChunks [defaultCSL]
#else
getDataFileName "chicago-author-date.csl" >>= L.readFile
#endif
langBase :: [(String, String)]
langBase
= [("af", "af-ZA")
,("ar", "ar-AR")
,("bg", "bg-BG")
,("ca", "ca-AD")
,("cs", "cs-CZ")
,("da", "da-DK")
,("de", "de-DE")
,("el", "el-GR")
,("en", "en-US")
,("es", "es-ES")
,("et", "et-EE")
,("fa", "fa-IR")
,("fi", "fi-FI")
,("fr", "fr-FR")
,("he", "he-IL")
,("hr", "hr-HR")
,("hu", "hu-HU")
,("is", "is-IS")
,("it", "it-IT")
,("ja", "ja-JP")
,("km", "km-KH")
,("ko", "ko-KR")
,("lt", "lt-LT")
,("lv", "lv-LV")
,("mn", "mn-MN")
,("nb", "nb-NO")
,("nl", "nl-NL")
,("nn", "nn-NO")
,("pl", "pl-PL")
,("pt", "pt-PT")
,("ro", "ro-RO")
,("ru", "ru-RU")
,("sk", "sk-SK")
,("sl", "sl-SI")
,("sr", "sr-RS")
,("sv", "sv-SE")
,("th", "th-TH")
,("tr", "tr-TR")
,("uk", "uk-UA")
,("vi", "vi-VN")
,("zh", "zh-CN")
]
| nickbart1980/pandoc-citeproc | src/Text/CSL/Data.hs | bsd-3-clause | 3,467 | 0 | 23 | 1,098 | 784 | 471 | 313 | 66 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : Aws.DynamoDb.Core
-- Copyright : Soostone Inc, Chris Allen
-- License : BSD3
--
-- Maintainer : Ozgun Ataman, Chris Allen
-- Stability : experimental
--
-- Shared types and utilities for DyanmoDb functionality.
----------------------------------------------------------------------------
module Aws.DynamoDb.Core
(
-- * Configuration and Regions
Region (..)
, ddbLocal
, ddbUsEast1
, ddbUsWest1
, ddbUsWest2
, ddbEuWest1
, ddbApNe1
, ddbApSe1
, ddbApSe2
, ddbSaEast1
, DdbConfiguration (..)
-- * DynamoDB values
, DValue (..)
-- * Converting to/from 'DValue'
, DynVal(..)
, toValue, fromValue
, Bin (..)
-- * Defining new 'DynVal' instances
, DynData(..)
, DynBinary(..), DynNumber(..), DynString(..)
-- * Working with key/value pairs
, Attribute (..)
, parseAttributeJson
, attributeJson
, attributesJson
, attrTuple
, attr
, attrAs
, text, int, double
, PrimaryKey (..)
, hk
, hrk
-- * Working with objects (attribute collections)
, Item
, item
, attributes
-- * Common types used by operations
, Conditions (..)
, conditionsJson
, expectsJson
, Condition (..)
, conditionJson
, CondOp (..)
, CondMerge (..)
, ConsumedCapacity (..)
, ReturnConsumption (..)
, ItemCollectionMetrics (..)
, ReturnItemCollectionMetrics (..)
, UpdateReturn (..)
, QuerySelect
, querySelectJson
-- * Size estimation
, DynSize (..)
, nullAttr
-- * Responses & Errors
, DdbResponse (..)
, DdbErrCode (..)
, shouldRetry
, DdbError (..)
-- * Internal Helpers
, ddbSignQuery
, AmazonError (..)
, ddbResponseConsumer
, ddbHttp
, ddbHttps
) where
-------------------------------------------------------------------------------
import Control.Applicative
import qualified Control.Exception as C
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Trans.Resource (throwM)
import Crypto.Hash
import Data.Aeson
import qualified Data.Aeson as A
import Data.Aeson.Types (Pair, parseEither)
import qualified Data.Aeson.Types as A
import qualified Data.Attoparsec.ByteString as AttoB (endOfInput)
import qualified Data.Attoparsec.Text as Atto
import Data.Byteable
import qualified Data.ByteString.Base16 as Base16
import qualified Data.ByteString.Base64 as Base64
import qualified Data.ByteString.Char8 as B
import qualified Data.CaseInsensitive as CI
import Data.Conduit
import Data.Conduit.Attoparsec (sinkParser)
import Data.Default
import Data.Function (on)
import qualified Data.HashMap.Strict as HM
import Data.Int
import Data.IORef
import Data.List
import qualified Data.Map as M
import Data.Maybe
import Data.Monoid
import Data.Proxy
import Data.Scientific
import qualified Data.Serialize as Ser
import qualified Data.Set as S
import Data.String
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Time
import Data.Typeable
import Data.Word
import qualified Network.HTTP.Conduit as HTTP
import qualified Network.HTTP.Types as HTTP
import Safe
-------------------------------------------------------------------------------
import Aws.Core
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- | Numeric values stored in DynamoDb. Only used in defining new
-- 'DynVal' instances.
newtype DynNumber = DynNumber { unDynNumber :: Scientific }
deriving (Eq,Show,Read,Ord,Typeable)
-------------------------------------------------------------------------------
-- | String values stored in DynamoDb. Only used in defining new
-- 'DynVal' instances.
newtype DynString = DynString { unDynString :: T.Text }
deriving (Eq,Show,Read,Ord,Typeable)
-------------------------------------------------------------------------------
-- | Binary values stored in DynamoDb. Only used in defining new
-- 'DynVal' instances.
newtype DynBinary = DynBinary { unDynBinary :: B.ByteString }
deriving (Eq,Show,Read,Ord,Typeable)
-------------------------------------------------------------------------------
-- | An internally used closed typeclass for values that have direct
-- DynamoDb representations. Based on AWS API, this is basically
-- numbers, strings and binary blobs.
--
-- This is here so that any 'DynVal' haskell value can automatically
-- be lifted to a list or a 'Set' without any instance code
-- duplication.
--
-- Do not try to create your own instances.
class Ord a => DynData a where
fromData :: a -> DValue
toData :: DValue -> Maybe a
instance DynData DynNumber where
fromData (DynNumber i) = DNum i
toData (DNum i) = Just $ DynNumber i
toData _ = Nothing
instance DynData (S.Set DynNumber) where
fromData set = DNumSet (S.map unDynNumber set)
toData (DNumSet i) = Just $ S.map DynNumber i
toData _ = Nothing
instance DynData DynString where
fromData (DynString i) = DString i
toData (DString i) = Just $ DynString i
toData _ = Nothing
instance DynData (S.Set DynString) where
fromData set = DStringSet (S.map unDynString set)
toData (DStringSet i) = Just $ S.map DynString i
toData _ = Nothing
instance DynData DynBinary where
fromData (DynBinary i) = DBinary i
toData (DBinary i) = Just $ DynBinary i
toData _ = Nothing
instance DynData (S.Set DynBinary) where
fromData set = DBinSet (S.map unDynBinary set)
toData (DBinSet i) = Just $ S.map DynBinary i
toData _ = Nothing
instance DynData DValue where
fromData = id
toData = Just
-------------------------------------------------------------------------------
-- | Class of Haskell types that can be represented as DynamoDb values.
--
-- This is the conversion layer; instantiate this class for your own
-- types and then use the 'toValue' and 'fromValue' combinators to
-- convert in application code.
--
-- Each Haskell type instantiated with this class will map to a
-- DynamoDb-supported type that most naturally represents it.
class DynData (DynRep a) => DynVal a where
-- | Which of the 'DynData' instances does this data type directly
-- map to?
type DynRep a
-- | Convert to representation
toRep :: a -> DynRep a
-- | Convert from representation
fromRep :: DynRep a -> Maybe a
-------------------------------------------------------------------------------
-- | Any singular 'DynVal' can be upgraded to a list.
instance (DynData (DynRep [a]), DynVal a) => DynVal [a] where
type DynRep [a] = S.Set (DynRep a)
fromRep set = mapM fromRep $ S.toList set
toRep as = S.fromList $ map toRep as
-------------------------------------------------------------------------------
-- | Any singular 'DynVal' can be upgraded to a 'Set'.
instance (DynData (DynRep (S.Set a)), DynVal a, Ord a) => DynVal (S.Set a) where
type DynRep (S.Set a) = S.Set (DynRep a)
fromRep set = fmap S.fromList . mapM fromRep $ S.toList set
toRep as = S.map toRep as
instance DynVal DValue where
type DynRep DValue = DValue
fromRep = Just
toRep = id
instance DynVal Int where
type DynRep Int = DynNumber
fromRep (DynNumber i) = toIntegral i
toRep i = DynNumber (fromIntegral i)
instance DynVal Int8 where
type DynRep Int8 = DynNumber
fromRep (DynNumber i) = toIntegral i
toRep i = DynNumber (fromIntegral i)
instance DynVal Int16 where
type DynRep Int16 = DynNumber
fromRep (DynNumber i) = toIntegral i
toRep i = DynNumber (fromIntegral i)
instance DynVal Int32 where
type DynRep Int32 = DynNumber
fromRep (DynNumber i) = toIntegral i
toRep i = DynNumber (fromIntegral i)
instance DynVal Int64 where
type DynRep Int64 = DynNumber
fromRep (DynNumber i) = toIntegral i
toRep i = DynNumber (fromIntegral i)
instance DynVal Word8 where
type DynRep Word8 = DynNumber
fromRep (DynNumber i) = toIntegral i
toRep i = DynNumber (fromIntegral i)
instance DynVal Word16 where
type DynRep Word16 = DynNumber
fromRep (DynNumber i) = toIntegral i
toRep i = DynNumber (fromIntegral i)
instance DynVal Word32 where
type DynRep Word32 = DynNumber
fromRep (DynNumber i) = toIntegral i
toRep i = DynNumber (fromIntegral i)
instance DynVal Word64 where
type DynRep Word64 = DynNumber
fromRep (DynNumber i) = toIntegral i
toRep i = DynNumber (fromIntegral i)
instance DynVal Integer where
type DynRep Integer = DynNumber
fromRep (DynNumber i) = toIntegral i
toRep i = DynNumber (fromIntegral i)
instance DynVal T.Text where
type DynRep T.Text = DynString
fromRep (DynString i) = Just i
toRep i = DynString i
instance DynVal B.ByteString where
type DynRep B.ByteString = DynBinary
fromRep (DynBinary i) = Just i
toRep i = DynBinary i
instance DynVal Double where
type DynRep Double = DynNumber
fromRep (DynNumber i) = Just $ toRealFloat i
toRep i = DynNumber (fromFloatDigits i)
-------------------------------------------------------------------------------
-- | Encoded as number of days
instance DynVal Day where
type DynRep Day = DynNumber
fromRep (DynNumber i) = ModifiedJulianDay <$> (toIntegral i)
toRep (ModifiedJulianDay i) = DynNumber (fromIntegral i)
-------------------------------------------------------------------------------
-- | Losslessly encoded via 'Integer' picoseconds
instance DynVal UTCTime where
type DynRep UTCTime = DynNumber
fromRep num = fromTS <$> fromRep num
toRep x = toRep (toTS x)
-------------------------------------------------------------------------------
pico :: Integer
pico = 10 ^ (12 :: Integer)
-------------------------------------------------------------------------------
dayPico :: Integer
dayPico = 86400 * pico
-------------------------------------------------------------------------------
-- | Convert UTCTime to picoseconds
--
-- TODO: Optimize performance?
toTS :: UTCTime -> Integer
toTS (UTCTime (ModifiedJulianDay i) diff) = i' + diff'
where
diff' = floor (toRational diff * pico')
pico' = toRational pico
i' = i * dayPico
-------------------------------------------------------------------------------
-- | Convert picoseconds to UTCTime
--
-- TODO: Optimize performance?
fromTS :: Integer -> UTCTime
fromTS i = UTCTime (ModifiedJulianDay days) diff
where
(days, secs) = i `divMod` dayPico
diff = fromRational ((toRational secs) / toRational pico)
-- | Encoded as 0 and 1.
instance DynVal Bool where
type DynRep Bool = DynNumber
fromRep (DynNumber i) = do
(i' :: Int) <- toIntegral i
case i' of
0 -> return False
1 -> return True
_ -> Nothing
toRep b = DynNumber (if b then 1 else 0)
-- | Type wrapper for binary data to be written to DynamoDB. Wrap any
-- 'Serialize' instance in there and 'DynVal' will know how to
-- automatically handle conversions in binary form.
newtype Bin a = Bin a deriving (Eq,Show,Read,Ord)
instance (Ser.Serialize a) => DynVal (Bin a) where
type DynRep (Bin a) = DynBinary
toRep (Bin i) = DynBinary (Ser.encode i)
fromRep (DynBinary i) = either (const Nothing) (Just . Bin) $
Ser.decode i
-------------------------------------------------------------------------------
-- | Encode a Haskell value.
toValue :: DynVal a => a -> DValue
toValue a = fromData $ toRep a
-------------------------------------------------------------------------------
-- | Decode a Haskell value.
fromValue :: DynVal a => DValue -> Maybe a
fromValue d = toData d >>= fromRep
toIntegral :: (Integral a, RealFrac a1) => a1 -> Maybe a
toIntegral sc = Just $ floor sc
-- | Value types natively recognized by DynamoDb. We pretty much
-- exactly reflect the AWS API onto Haskell types.
data DValue
= DNum Scientific
| DString T.Text
| DBinary B.ByteString
-- ^ Binary data will automatically be base64 marshalled.
| DNumSet (S.Set Scientific)
| DStringSet (S.Set T.Text)
| DBinSet (S.Set B.ByteString)
-- ^ Binary data will automatically be base64 marshalled.
deriving (Eq,Show,Read,Ord,Typeable)
instance IsString DValue where
fromString t = DString (T.pack t)
-------------------------------------------------------------------------------
-- | Primary keys consist of either just a Hash key (mandatory) or a
-- hash key and a range key (optional).
data PrimaryKey = PrimaryKey {
pkHash :: Attribute
, pkRange :: Maybe Attribute
} deriving (Read,Show,Ord,Eq,Typeable)
-------------------------------------------------------------------------------
-- | Construct a hash-only primary key.
--
-- >>> hk "user-id" "ABCD"
--
-- >>> hk "user-id" (mkVal 23)
hk :: T.Text -> DValue -> PrimaryKey
hk k v = PrimaryKey (attr k v) Nothing
-------------------------------------------------------------------------------
-- | Construct a hash-and-range primary key.
hrk :: T.Text -- ^ Hash key name
-> DValue -- ^ Hash key value
-> T.Text -- ^ Range key name
-> DValue -- ^ Range key value
-> PrimaryKey
hrk k v k2 v2 = PrimaryKey (attr k v) (Just (attr k2 v2))
instance ToJSON PrimaryKey where
toJSON (PrimaryKey h Nothing) = toJSON h
toJSON (PrimaryKey h (Just r)) =
let Object p1 = toJSON h
Object p2 = toJSON r
in Object (p1 `HM.union` p2)
-- | A key-value pair
data Attribute = Attribute {
attrName :: T.Text
, attrVal :: DValue
} deriving (Read,Show,Ord,Eq,Typeable)
-- | Convert attribute to a tuple representation
attrTuple :: Attribute -> (T.Text, DValue)
attrTuple (Attribute a b) = (a,b)
-- | Convenience function for constructing key-value pairs
attr :: DynVal a => T.Text -> a -> Attribute
attr k v = Attribute k (toValue v)
-- | 'attr' with type witness to help with cases where you're manually
-- supplying values in code.
--
-- >> item [ attrAs text "name" "john" ]
attrAs :: DynVal a => Proxy a -> T.Text -> a -> Attribute
attrAs _ k v = attr k v
-- | Type witness for 'Text'. See 'attrAs'.
text :: Proxy T.Text
text = Proxy
-- | Type witness for 'Integer'. See 'attrAs'.
int :: Proxy Integer
int = Proxy
-- | Type witness for 'Double'. See 'attrAs'.
double :: Proxy Double
double = Proxy
-- | A DynamoDb object is simply a key-value dictionary.
type Item = M.Map T.Text DValue
-------------------------------------------------------------------------------
-- | Pack a list of attributes into an Item.
item :: [Attribute] -> Item
item = M.fromList . map attrTuple
-------------------------------------------------------------------------------
-- | Unpack an 'Item' into a list of attributes.
attributes :: M.Map T.Text DValue -> [Attribute]
attributes = map (\ (k, v) -> Attribute k v) . M.toList
showT :: Show a => a -> T.Text
showT = T.pack . show
instance ToJSON DValue where
toJSON (DNum i) = object ["N" .= showT i]
toJSON (DString i) = object ["S" .= i]
toJSON (DBinary i) = object ["B" .= (T.decodeUtf8 $ Base64.encode i)]
toJSON (DNumSet i) = object ["NS" .= map showT (S.toList i)]
toJSON (DStringSet i) = object ["SS" .= S.toList i]
toJSON (DBinSet i) = object ["BS" .= map (T.decodeUtf8 . Base64.encode) (S.toList i)]
toJSON x = error $ "aws: bug: DynamoDB can't handle " ++ show x
instance FromJSON DValue where
parseJSON o = do
(obj :: [(T.Text, Value)]) <- M.toList `liftM` parseJSON o
case obj of
[("N", numStr)] -> DNum <$> parseScientific numStr
[("S", str)] -> DString <$> parseJSON str
[("B", bin)] -> do
res <- (Base64.decode . T.encodeUtf8) <$> parseJSON bin
either fail (return . DBinary) res
[("NS", s)] -> do xs <- mapM parseScientific =<< parseJSON s
return $ DNumSet $ S.fromList xs
[("SS", s)] -> DStringSet <$> parseJSON s
[("BS", s)] -> do
xs <- mapM (either fail return . Base64.decode . T.encodeUtf8)
=<< parseJSON s
return $ DBinSet $ S.fromList xs
x -> fail $ "aws: unknown dynamodb value: " ++ show x
where
parseScientific (String str) =
case Atto.parseOnly Atto.scientific str of
Left e -> fail ("parseScientific failed: " ++ e)
Right a -> return a
parseScientific (Number n) = return n
parseScientific _ = fail "Unexpected JSON type in parseScientific"
instance ToJSON Attribute where
toJSON a = object $ [attributeJson a]
-------------------------------------------------------------------------------
-- | Parse a JSON object that contains attributes
parseAttributeJson :: Value -> A.Parser [Attribute]
parseAttributeJson (Object v) = mapM conv $ HM.toList v
where
conv (k, o) = Attribute k <$> parseJSON o
parseAttributeJson _ = error "Attribute JSON must be an Object"
-- | Convert into JSON object for AWS.
attributesJson :: [Attribute] -> Value
attributesJson as = object $ map attributeJson as
-- | Convert into JSON pair
attributeJson :: Attribute -> Pair
attributeJson (Attribute nm v) = nm .= v
-------------------------------------------------------------------------------
-- | Errors defined by AWS.
data DdbErrCode
= AccessDeniedException
| ConditionalCheckFailedException
| IncompleteSignatureException
| InvalidSignatureException
| LimitExceededException
| MissingAuthenticationTokenException
| ProvisionedThroughputExceededException
| ResourceInUseException
| ResourceNotFoundException
| ThrottlingException
| ValidationException
| RequestTooLarge
| InternalFailure
| InternalServerError
| ServiceUnavailableException
| SerializationException
-- ^ Raised by AWS when the request JSON is missing fields or is
-- somehow malformed.
deriving (Read,Show,Eq,Typeable)
-------------------------------------------------------------------------------
-- | Whether the action should be retried based on the received error.
shouldRetry :: DdbErrCode -> Bool
shouldRetry e = go e
where
go LimitExceededException = True
go ProvisionedThroughputExceededException = True
go ResourceInUseException = True
go ThrottlingException = True
go InternalFailure = True
go InternalServerError = True
go ServiceUnavailableException = True
go _ = False
-------------------------------------------------------------------------------
-- | Errors related to this library.
data DdbLibraryError
= UnknownDynamoErrCode T.Text
-- ^ A DynamoDB error code we do not know about.
| JsonProtocolError Value T.Text
-- ^ A JSON response we could not parse.
deriving (Show,Eq,Typeable)
-- | Potential errors raised by DynamoDB
data DdbError = DdbError {
ddbStatusCode :: Int
-- ^ 200 if successful, 400 for client errors and 500 for
-- server-side errors.
, ddbErrCode :: DdbErrCode
, ddbErrMsg :: T.Text
} deriving (Show,Eq,Typeable)
instance C.Exception DdbError
instance C.Exception DdbLibraryError
-- | Response metadata that is present in every DynamoDB response.
data DdbResponse = DdbResponse {
ddbrCrc :: Maybe T.Text
, ddbrMsgId :: Maybe T.Text
}
instance Loggable DdbResponse where
toLogText (DdbResponse id2 rid) =
"DynamoDB: request ID=" `mappend`
fromMaybe "<none>" rid `mappend`
", x-amz-id-2=" `mappend`
fromMaybe "<none>" id2
instance Monoid DdbResponse where
mempty = DdbResponse Nothing Nothing
mappend a b = DdbResponse (ddbrCrc a `mplus` ddbrCrc b) (ddbrMsgId a `mplus` ddbrMsgId b)
data Region = Region {
rUri :: B.ByteString
, rName :: B.ByteString
} deriving (Eq,Show,Read,Typeable)
data DdbConfiguration qt = DdbConfiguration {
ddbcRegion :: Region
-- ^ The regional endpoint. Ex: 'ddbUsEast'
, ddbcProtocol :: Protocol
-- ^ 'HTTP' or 'HTTPS'
, ddbcPort :: Maybe Int
-- ^ Port override (mostly for local dev connection)
} deriving (Show,Typeable)
instance Default (DdbConfiguration NormalQuery) where
def = DdbConfiguration ddbUsEast1 HTTPS Nothing
instance DefaultServiceConfiguration (DdbConfiguration NormalQuery) where
defServiceConfig = ddbHttps ddbUsEast1
debugServiceConfig = ddbHttp ddbUsEast1
-------------------------------------------------------------------------------
-- | DynamoDb local connection (for development)
ddbLocal :: Region
ddbLocal = Region "127.0.0.1" "local"
ddbUsEast1 :: Region
ddbUsEast1 = Region "dynamodb.us-east-1.amazonaws.com" "us-east-1"
ddbUsWest1 :: Region
ddbUsWest1 = Region "dynamodb.us-west-1.amazonaws.com" "us-west-1"
ddbUsWest2 :: Region
ddbUsWest2 = Region "dynamodb.us-west-2.amazonaws.com" "us-west-2"
ddbEuWest1 :: Region
ddbEuWest1 = Region "dynamodb.eu-west-1.amazonaws.com" "us-west-1"
ddbApNe1 :: Region
ddbApNe1 = Region "dynamodb.ap-northeast-1.amazonaws.com" "ap-northeast-1"
ddbApSe1 :: Region
ddbApSe1 = Region "dynamodb.ap-southeast-1.amazonaws.com" "ap-southeast-1"
ddbApSe2 :: Region
ddbApSe2 = Region "dynamodb.ap-southeast-2.amazonaws.com" "ap-southeast-2"
ddbSaEast1 :: Region
ddbSaEast1 = Region "dynamodb.sa-east-1.amazonaws.com" "sa-east-1"
ddbHttp :: Region -> DdbConfiguration NormalQuery
ddbHttp endpoint = DdbConfiguration endpoint HTTP Nothing
ddbHttps :: Region -> DdbConfiguration NormalQuery
ddbHttps endpoint = DdbConfiguration endpoint HTTPS Nothing
ddbSignQuery
:: A.ToJSON a
=> B.ByteString
-> a
-> DdbConfiguration qt
-> SignatureData
-> SignedQuery
ddbSignQuery target body di sd
= SignedQuery {
sqMethod = Post
, sqProtocol = ddbcProtocol di
, sqHost = host
, sqPort = fromMaybe (defaultPort (ddbcProtocol di)) (ddbcPort di)
, sqPath = "/"
, sqQuery = []
, sqDate = Just $ signatureTime sd
, sqAuthorization = Just auth
, sqContentType = Just "application/x-amz-json-1.0"
, sqContentMd5 = Nothing
, sqAmzHeaders = amzHeaders ++ maybe [] (\tok -> [("x-amz-security-token",tok)]) (iamToken credentials)
, sqOtherHeaders = []
, sqBody = Just $ HTTP.RequestBodyLBS bodyLBS
, sqStringToSign = canonicalRequest
}
where
credentials = signatureCredentials sd
Region{..} = ddbcRegion di
host = rUri
sigTime = fmtTime "%Y%m%dT%H%M%SZ" $ signatureTime sd
bodyLBS = A.encode body
bodyHash = Base16.encode $ toBytes (hashlazy bodyLBS :: Digest SHA256)
-- for some reason AWS doesn't want the x-amz-security-token in the canonical request
amzHeaders = [ ("x-amz-date", sigTime)
, ("x-amz-target", dyApiVersion <> target)
]
canonicalHeaders = sortBy (compare `on` fst) $ amzHeaders ++
[("host", host),
("content-type", "application/x-amz-json-1.0")]
canonicalRequest = B.concat $ intercalate ["\n"] (
[ ["POST"]
, ["/"]
, [] -- query string
] ++
map (\(a,b) -> [CI.foldedCase a,":",b]) canonicalHeaders ++
[ [] -- end headers
, intersperse ";" (map (CI.foldedCase . fst) canonicalHeaders)
, [bodyHash]
])
auth = authorizationV4 sd HmacSHA256 rName "dynamodb"
"content-type;host;x-amz-date;x-amz-target"
canonicalRequest
data AmazonError = AmazonError {
aeType :: T.Text
, aeMessage :: Maybe T.Text
}
instance FromJSON AmazonError where
parseJSON (Object v) = AmazonError
<$> v .: "__type"
<*> v .:? "message"
parseJSON _ = error $ "aws: unexpected AmazonError message"
-------------------------------------------------------------------------------
ddbResponseConsumer :: A.FromJSON a => IORef DdbResponse -> HTTPResponseConsumer a
ddbResponseConsumer ref resp = do
val <- HTTP.responseBody resp $$+- sinkParser (A.json' <* AttoB.endOfInput)
case statusCode of
200 -> rSuccess val
_ -> rError val
where
header = fmap T.decodeUtf8 . flip lookup (HTTP.responseHeaders resp)
amzId = header "x-amzn-RequestId"
amzCrc = header "x-amz-crc32"
meta = DdbResponse amzCrc amzId
tellMeta = liftIO $ tellMetadataRef ref meta
rSuccess val =
case A.fromJSON val of
A.Success a -> return a
A.Error err -> do
tellMeta
throwM $ JsonProtocolError val (T.pack err)
rError val = do
tellMeta
case parseEither parseJSON val of
Left e ->
throwM $ JsonProtocolError val (T.pack e)
Right err'' -> do
let e = T.drop 1 . snd . T.breakOn "#" $ aeType err''
errCode <- readErrCode e
throwM $ DdbError statusCode errCode (fromMaybe "" $ aeMessage err'')
readErrCode txt =
let txt' = T.unpack txt
in case readMay txt' of
Just e -> return $ e
Nothing -> throwM (UnknownDynamoErrCode txt)
HTTP.Status{..} = HTTP.responseStatus resp
-- | Conditions used by mutation operations ('PutItem', 'UpdateItem',
-- etc.). The default 'def' instance is empty (no condition).
data Conditions = Conditions CondMerge [Condition]
deriving (Eq,Show,Read,Ord,Typeable)
instance Default Conditions where
def = Conditions CondAnd []
expectsJson :: Conditions -> [A.Pair]
expectsJson = conditionsJson "Expected"
-- | JSON encoding of conditions parameter in various contexts.
conditionsJson :: T.Text -> Conditions -> [A.Pair]
conditionsJson key (Conditions op es) = b ++ a
where
a = if null es
then []
else [key .= object (map conditionJson es)]
b = if length (take 2 es) > 1
then ["ConditionalOperator" .= String (rendCondOp op) ]
else []
-------------------------------------------------------------------------------
rendCondOp :: CondMerge -> T.Text
rendCondOp CondAnd = "AND"
rendCondOp CondOr = "OR"
-------------------------------------------------------------------------------
-- | How to merge multiple conditions.
data CondMerge = CondAnd | CondOr
deriving (Eq,Show,Read,Ord,Typeable)
-- | A condition used by mutation operations ('PutItem', 'UpdateItem', etc.).
data Condition = Condition {
condAttr :: T.Text
-- ^ Attribute to use as the basis for this conditional
, condOp :: CondOp
-- ^ Operation on the selected attribute
} deriving (Eq,Show,Read,Ord,Typeable)
-------------------------------------------------------------------------------
-- | Conditional operation to perform on a field.
data CondOp
= DEq DValue
| NotEq DValue
| DLE DValue
| DLT DValue
| DGE DValue
| DGT DValue
| NotNull
| IsNull
| Contains DValue
| NotContains DValue
| Begins DValue
| In [DValue]
| Between DValue DValue
deriving (Eq,Show,Read,Ord,Typeable)
-------------------------------------------------------------------------------
getCondValues :: CondOp -> [DValue]
getCondValues c = case c of
DEq v -> [v]
NotEq v -> [v]
DLE v -> [v]
DLT v -> [v]
DGE v -> [v]
DGT v -> [v]
NotNull -> []
IsNull -> []
Contains v -> [v]
NotContains v -> [v]
Begins v -> [v]
In v -> v
Between a b -> [a,b]
-------------------------------------------------------------------------------
renderCondOp :: CondOp -> T.Text
renderCondOp c = case c of
DEq{} -> "EQ"
NotEq{} -> "NE"
DLE{} -> "LE"
DLT{} -> "LT"
DGE{} -> "GE"
DGT{} -> "GT"
NotNull -> "NOT_NULL"
IsNull -> "NULL"
Contains{} -> "CONTAINS"
NotContains{} -> "NOT_CONTAINS"
Begins{} -> "BEGINS_WITH"
In{} -> "IN"
Between{} -> "BETWEEN"
conditionJson :: Condition -> Pair
conditionJson Condition{..} = condAttr .= condOp
instance ToJSON CondOp where
toJSON c = object $ ("ComparisonOperator" .= String (renderCondOp c)) : valueList
where
valueList =
let vs = getCondValues c in
if null vs
then []
else ["AttributeValueList" .= vs]
-------------------------------------------------------------------------------
dyApiVersion :: B.ByteString
dyApiVersion = "DynamoDB_20120810."
-------------------------------------------------------------------------------
-- | The standard response metrics on capacity consumption.
data ConsumedCapacity = ConsumedCapacity {
capacityUnits :: Int64
, capacityGlobalIndex :: [(T.Text, Int64)]
, capacityLocalIndex :: [(T.Text, Int64)]
, capacityTableUnits :: Maybe Int64
, capacityTable :: T.Text
} deriving (Eq,Show,Read,Ord,Typeable)
instance FromJSON ConsumedCapacity where
parseJSON (Object v) = ConsumedCapacity
<$> v .: "CapacityUnits"
<*> (HM.toList <$> v .:? "GlobalSecondaryIndexes" .!= mempty)
<*> (HM.toList <$> v .:? "LocalSecondaryIndexes" .!= mempty)
<*> (v .:? "Table" >>= maybe (return Nothing) (.: "CapacityUnits"))
<*> v .: "TableName"
parseJSON _ = fail "ConsumedCapacity must be an Object."
data ReturnConsumption = RCIndexes | RCTotal | RCNone
deriving (Eq,Show,Read,Ord,Typeable)
instance ToJSON ReturnConsumption where
toJSON RCIndexes = String "INDEXES"
toJSON RCTotal = String "TOTAL"
toJSON RCNone = String "NONE"
instance Default ReturnConsumption where
def = RCNone
data ReturnItemCollectionMetrics = RICMSize | RICMNone
deriving (Eq,Show,Read,Ord,Typeable)
instance ToJSON ReturnItemCollectionMetrics where
toJSON RICMSize = String "SIZE"
toJSON RICMNone = String "NONE"
instance Default ReturnItemCollectionMetrics where
def = RICMNone
data ItemCollectionMetrics = ItemCollectionMetrics {
icmKey :: (T.Text, DValue)
, icmEstimate :: [Double]
} deriving (Eq,Show,Read,Ord,Typeable)
instance FromJSON ItemCollectionMetrics where
parseJSON (Object v) = ItemCollectionMetrics
<$> (do m <- v .: "ItemCollectionKey"
return $ head $ HM.toList m)
<*> v .: "SizeEstimateRangeGB"
parseJSON _ = fail "ItemCollectionMetrics must be an Object."
-------------------------------------------------------------------------------
-- | What to return from the current update operation
data UpdateReturn
= URNone -- ^ Return nothing
| URAllOld -- ^ Return old values
| URUpdatedOld -- ^ Return old values with a newer replacement
| URAllNew -- ^ Return new values
| URUpdatedNew -- ^ Return new values that were replacements
deriving (Eq,Show,Read,Ord,Typeable)
instance ToJSON UpdateReturn where
toJSON URNone = toJSON (String "NONE")
toJSON URAllOld = toJSON (String "ALL_OLD")
toJSON URUpdatedOld = toJSON (String "UPDATED_OLD")
toJSON URAllNew = toJSON (String "ALL_NEW")
toJSON URUpdatedNew = toJSON (String "UPDATED_NEW")
instance Default UpdateReturn where
def = URNone
-------------------------------------------------------------------------------
-- | What to return from a 'Query' or 'Scan' query.
data QuerySelect
= SelectSpecific [T.Text]
-- ^ Only return selected attributes
| SelectCount
-- ^ Return counts instead of attributes
| SelectProjected
-- ^ Return index-projected attributes
| SelectAll
-- ^ Default. Return everything.
deriving (Eq,Show,Read,Ord,Typeable)
instance Default QuerySelect where def = SelectAll
-------------------------------------------------------------------------------
querySelectJson (SelectSpecific as) =
[ "Select" .= String "SPECIFIC_ATTRIBUTES"
, "AttributesToGet" .= as]
querySelectJson SelectCount = ["Select" .= String "COUNT"]
querySelectJson SelectProjected = ["Select" .= String "ALL_PROJECTED_ATTRIBUTES"]
querySelectJson SelectAll = ["Select" .= String "ALL_ATTRIBUTES"]
-------------------------------------------------------------------------------
-- | A class to help predict DynamoDb size of values, attributes and
-- entire items. The result is given in number of bytes.
class DynSize a where
dynSize :: a -> Int
instance DynSize DValue where
dynSize (DNum _) = 8
dynSize (DString a) = T.length a
dynSize (DBinary bs) = T.length . T.decodeUtf8 $ Base64.encode bs
dynSize (DNumSet s) = 8 * S.size s
dynSize (DStringSet s) = sum $ map (dynSize . DString) $ S.toList s
dynSize (DBinSet s) = sum $ map (dynSize . DBinary) $ S.toList s
instance DynSize Attribute where
dynSize (Attribute k v) = T.length k + dynSize v
instance DynSize Item where
dynSize m = sum $ map dynSize $ attributes m
instance DynSize a => DynSize [a] where
dynSize as = sum $ map dynSize as
instance DynSize a => DynSize (Maybe a) where
dynSize = maybe 0 dynSize
instance (DynSize a, DynSize b) => DynSize (Either a b) where
dynSize = either dynSize dynSize
-------------------------------------------------------------------------------
-- | Will an attribute be considered empty by DynamoDb?
--
-- A 'PutItem' (or similar) with empty attributes will be rejection
-- with a 'ValidationException'.
nullAttr :: Attribute -> Bool
nullAttr (Attribute _ val) =
case val of
DString "" -> True
DBinary "" -> True
DNumSet s | S.null s -> True
DStringSet s | S.null s -> True
DBinSet s | S.null s -> True
_ -> False
| fpco/aws | Aws/DynamoDb/Core.hs | bsd-3-clause | 34,959 | 0 | 21 | 8,340 | 8,277 | 4,430 | 3,847 | 696 | 13 |
{-# OPTIONS_GHC -fbang-patterns #-}
module HMQ.Example.GeneratedEntities.Categories where
import Data.List
import Data.Maybe
import System.Time
import Database.HDBC
import HMQ.Metadata.TableMetadata
import HMQ.Query hiding(tableIdentifier)
import HMQ.ForeignKeyLink
import HMQ.MappedQuery
import HMQ.RowValueExtractors
data Category =
Category
{
categoryId :: Integer,
name :: String
}
deriving (Show)
-- The extractor function which creates a Category from a result row.
rowValueExtractor :: EntityRowValueExtractor Category
rowValueExtractor !tableAlias !qry =
let
leadingColIx = fromMaybe (error $ "No columns for table alias " ++ tableAlias ++ " found in query.") $
findIndex ((tableAlias ++ ".") `isPrefixOf`) (selectFieldExprs qry)
in
leadingColIx `seq`
(\(!row) ->
let
fv1:fv2:_ = drop leadingColIx row
in
-- Check first pk field to determine if there's a value for this row
if fv1 == SqlNull then
Nothing
else
Just $ Category (fromSql fv1) (fromSql fv2)
)
tableMetadata :: TableMetadata
tableMetadata =
TableMetadata {
tableIdentifier = TableIdentifier {tableSchema = Just "public", tableName = "categories"},
fieldMetadatas =
[
FieldMetadata {fieldName = "category_id", fieldSqlColDesc = SqlColDesc {colType = SqlBigIntT, colSize = Just 4, colOctetLength = Nothing, colDecDigits = Nothing, colNullable = Just False}},
FieldMetadata {fieldName = "name", fieldSqlColDesc = SqlColDesc {colType = SqlVarCharT, colSize = Just 80, colOctetLength = Nothing, colDecDigits = Nothing, colNullable = Just False}}
],
primaryKeyFieldNames = ["category_id"],
foreignKeyConstraints = []
}
mappedQuery :: MappedQuery Category Category Category
mappedQuery = MappedTable tableMetadata rowValueExtractor
| scharris/hmq | Example/GeneratedEntities/Categories.hs | bsd-3-clause | 2,020 | 0 | 16 | 540 | 434 | 251 | 183 | -1 | -1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.TimeGrain.NB.Rules
( rules ) where
import Data.Text (Text)
import Prelude
import Data.String
import Duckling.Dimensions.Types
import qualified Duckling.TimeGrain.Types as TG
import Duckling.Types
grains :: [(Text, String, TG.Grain)]
grains = [ ("second (grain)", "sek(und(er)?)?", TG.Second)
, ("minute (grain)", "min(utt(er)?)?", TG.Minute)
, ("hour (grain)", "t(ime(r)?)?", TG.Hour)
, ("day (grain)", "dag(er)?", TG.Day)
, ("week (grain)", "uke(r|n)?", TG.Week)
, ("month (grain)", "måned(er)?", TG.Month)
, ("quarter (grain)", "kvart(al|er)(et)?", TG.Quarter)
, ("year (grain)", "år", TG.Year)
]
rules :: [Rule]
rules = map go grains
where
go (name, regexPattern, grain) = Rule
{ name = name
, pattern = [regex regexPattern]
, prod = \_ -> Just $ Token TimeGrain grain
}
| facebookincubator/duckling | Duckling/TimeGrain/NB/Rules.hs | bsd-3-clause | 1,166 | 0 | 11 | 259 | 271 | 172 | 99 | 25 | 1 |
module Asteroids.UILogic.Display (
display,
idle
) where
import Asteroids.UILogic.AspectRatio
import Asteroids.UILogic.Drawable
import Control.Concurrent
import GameState
import Graphics.Rendering.OpenGL.GL.CoordTrans
import Graphics.UI.GLUT
display :: GameState -> DisplayCallback
display state = do
clear [ColorBuffer, DepthBuffer]
loadIdentity
aspect <- getAspectRatio state
adjustAspectRatio aspect
innerDrawing $ obscureBorders aspect
innerDrawing $ draw state
swapBuffers
idle :: GameState -> IdleCallback
idle state = do
threadDelay 20000
updateGame state
postRedisplay Nothing
| trenttobler/hs-asteroids | src/Asteroids/UILogic/Display.hs | bsd-3-clause | 699 | 0 | 8 | 176 | 155 | 79 | 76 | 23 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module GithubUser where
import JSONFormat
import DTypes
import Data.Aeson ((.=), (.:))
import qualified Data.Aeson as A
import qualified Data.Text as T
newtype GithubUserId
= GithubUserId
{ unGithubUserId :: Integer
} deriving (A.FromJSON, A.ToJSON)
newtype Url
= Url
{ unUrl :: T.Text
} deriving (A.ToJSON, A.FromJSON)
-- https://api.github.com/users/timjb
data GithubUser
= GithubUser
{ userLogin :: T.Text
, userId :: GithubUserId
, userAvatarUrl :: Url
-- ...
}
instance A.ToJSON GithubUser where
toJSON ghUser =
A.object
[ "login" .= userLogin ghUser
, "id" .= userId ghUser
, "avatar_url" .= userAvatarUrl ghUser
]
instance A.FromJSON GithubUser where
parseJSON =
A.withObject "GithubUser" $ \obj -> do
ghLogin <- obj .: "login"
ghId <- obj .: "id"
ghAvatarUrl <- obj .: "avatar_url"
pure GithubUser
{ userLogin = ghLogin
, userId = ghId
, userAvatarUrl = ghAvatarUrl
}
{-
-- Alternative:
instance A.FromJSON GithubUser where
parseJSON =
A.withObject "GithubUser" $ \obj -> do
GithubUser
<$> (obj .: "login")
<*> (obj .: "id")
<*> (obj .: "avatar_url")
-}
makeDType ''GithubUser
ghUserJSONFormat :: JSONFormat GithubUser
ghUserJSONFormat =
objectFormat "GithubUser" $
DGithubUser
{ duserLogin = field "login"
, duserId = field "id"
, duserAvatarUrl = field "avatar_url"
}
| timjb/frecords | examples/dtypes-aeson/GithubUser.hs | mit | 1,638 | 0 | 12 | 395 | 336 | 192 | 144 | 48 | 1 |
{-# OPTIONS -cpp #-}
-- HookGenerator.hs -*-haskell-*-
-- Takes a type list of possible hooks from the GTK+ distribution and produces
-- Haskell functions to connect to these callbacks.
module Main(main) where
import Data.Char (showLitChar)
import Data.List (nub, isPrefixOf)
import System.Environment (getArgs)
import System.Exit (exitWith, ExitCode(..))
import System.IO (stderr, hPutStr)
import Paths_gtk2hs_buildtools (getDataFileName)
-- Define all possible data types the GTK will supply in callbacks.
--
data Types = Tunit -- ()
| Tbool -- Bool
| Tchar
| Tuchar
| Tint -- Int
| Tuint
| Tlong
| Tulong
| Tenum
| Tflags
| Tfloat
| Tdouble
| Tstring
| Tmstring
| Tboxed -- a struct which is passed by value
| Tptr -- pointer
| Ttobject -- foreign with WidgetClass context
| Tmtobject -- foreign with WidgetClass context using a Maybe type
| Tobject -- foreign with GObjectClass context
| Tmobject -- foreign with GObjectClass context using a Maybe type
deriving Eq
type Signature = (Types,[Types])
type Signatures = [Signature]
-------------------------------------------------------------------------------
-- Parsing
-------------------------------------------------------------------------------
parseSignatures :: String -> Signatures
parseSignatures content = (nub.parseSig 1.scan) content
data Token = TokColon
| TokType Types
| TokComma
| TokEOL
instance Show Token where
showsPrec _ TokColon = shows ":"
showsPrec _ (TokType _) = shows "<type>"
showsPrec _ TokComma = shows ","
showsPrec _ TokEOL = shows "<EOL>"
parseSig :: Int -> [Token] -> Signatures
parseSig l [] = []
parseSig l (TokEOL: rem) = parseSig (l+1) rem
parseSig l (TokType ret: TokColon: TokType Tunit:rem) =
(ret,[]):parseSig l rem
parseSig l (TokType ret: TokColon: rem) =
let (args,rem') = parseArg l rem in
(ret,args): parseSig (l+1) rem'
parseSig l rem = error ("parse error on line "++show l++
": expected type and colon, found\n"++
concatMap show (take 5 rem))
parseArg :: Int -> [Token] -> ([Types],[Token])
parseArg l [TokType ty] = ([ty],[])
parseArg l (TokType ty: TokEOL:rem) = ([ty],rem)
parseArg l (TokType ty: TokComma:rem) =
let (args,rem') = parseArg l rem in
(ty:args, rem')
parseArg l rem = error ("parse error on line "++show l++": expected type"++
" followed by comma or EOL, found\n "++
concatMap show (take 5 rem))
scan :: String -> [Token]
scan "" = []
scan ('#':xs) = (scan.dropWhile (/='\n')) xs
scan ('\n':xs) = TokEOL:scan xs
scan (' ':xs) = scan xs
scan ('\t':xs) = scan xs
scan (':':xs) = TokColon:scan xs
scan (',':xs) = TokComma:scan xs
scan ('V':'O':'I':'D':xs) = TokType Tunit:scan xs
scan ('B':'O':'O':'L':'E':'A':'N':xs) = TokType Tbool:scan xs
scan ('C':'H':'A':'R':xs) = TokType Tchar:scan xs
scan ('U':'C':'H':'A':'R':xs) = TokType Tuchar:scan xs
scan ('I':'N':'T':xs) = TokType Tint:scan xs
scan ('U':'I':'N':'T':xs) = TokType Tuint:scan xs
scan ('L':'O':'N':'G':xs) = TokType Tuint:scan xs
scan ('U':'L':'O':'N':'G':xs) = TokType Tulong:scan xs
scan ('E':'N':'U':'M':xs) = TokType Tenum:scan xs
scan ('F':'L':'A':'G':'S':xs) = TokType Tflags:scan xs
scan ('F':'L':'O':'A':'T':xs) = TokType Tfloat:scan xs
scan ('D':'O':'U':'B':'L':'E':xs) = TokType Tdouble:scan xs
scan ('S':'T':'R':'I':'N':'G':xs) = TokType Tstring:scan xs
scan ('M':'S':'T':'R':'I':'N':'G':xs) = TokType Tmstring:scan xs
scan ('B':'O':'X':'E':'D':xs) = TokType Tboxed:scan xs
scan ('P':'O':'I':'N':'T':'E':'R':xs) = TokType Tptr:scan xs
scan ('T':'O':'B':'J':'E':'C':'T':xs) = TokType Ttobject:scan xs
scan ('M':'T':'O':'B':'J':'E':'C':'T':xs) = TokType Tmtobject:scan xs
scan ('O':'B':'J':'E':'C':'T':xs) = TokType Tobject:scan xs
scan ('M':'O':'B':'J':'E':'C':'T':xs) = TokType Tmobject:scan xs
scan ('N':'O':'N':'E':xs) = TokType Tunit:scan xs
scan ('B':'O':'O':'L':xs) = TokType Tbool:scan xs
scan str = error ("Invalid character in input file:\n"++
concatMap ((flip showLitChar) "") (take 5 str))
-------------------------------------------------------------------------------
-- Helper functions
-------------------------------------------------------------------------------
ss = showString
sc = showChar
indent :: Int -> ShowS
indent c = ss ("\n"++replicate (2*c) ' ')
-------------------------------------------------------------------------------
-- Tables of code fragments
-------------------------------------------------------------------------------
identifier :: Types -> ShowS
identifier Tunit = ss "NONE"
identifier Tbool = ss "BOOL"
identifier Tchar = ss "CHAR"
identifier Tuchar = ss "UCHAR"
identifier Tint = ss "INT"
identifier Tuint = ss "WORD"
identifier Tlong = ss "LONG"
identifier Tulong = ss "ULONG"
identifier Tenum = ss "ENUM"
identifier Tflags = ss "FLAGS"
identifier Tfloat = ss "FLOAT"
identifier Tdouble = ss "DOUBLE"
identifier Tstring = ss "STRING"
identifier Tmstring = ss "MSTRING"
identifier Tboxed = ss "BOXED"
identifier Tptr = ss "PTR"
identifier Ttobject = ss "OBJECT"
identifier Tmtobject = ss "MOBJECT"
identifier Tobject = ss "OBJECT"
identifier Tmobject = ss "MOBJECT"
#ifdef USE_GCLOSURE_SIGNALS_IMPL
-- The monomorphic type which is used to export the function signature.
rawtype :: Types -> ShowS
rawtype Tunit = ss "()"
rawtype Tbool = ss "Bool"
rawtype Tchar = ss "Char"
rawtype Tuchar = ss "Char"
rawtype Tint = ss "Int"
rawtype Tuint = ss "Word"
rawtype Tlong = ss "Int"
rawtype Tulong = ss "Word"
rawtype Tenum = ss "Int"
rawtype Tflags = ss "Word"
rawtype Tfloat = ss "Float"
rawtype Tdouble = ss "Double"
rawtype Tstring = ss "CString"
rawtype Tmstring = ss "CString"
rawtype Tboxed = ss "Ptr ()"
rawtype Tptr = ss "Ptr ()"
rawtype Ttobject = ss "Ptr GObject"
rawtype Tmtobject = ss "Ptr GObject"
rawtype Tobject = ss "Ptr GObject"
rawtype Tmobject = ss "Ptr GObject"
#else
-- The monomorphic type which is used to export the function signature.
rawtype :: Types -> ShowS
rawtype Tunit = ss "()"
rawtype Tbool = ss "{#type gboolean#}"
rawtype Tchar = ss "{#type gchar#}"
rawtype Tuchar = ss "{#type guchar#}"
rawtype Tint = ss "{#type gint#}"
rawtype Tuint = ss "{#type guint#}"
rawtype Tlong = ss "{#type glong#}"
rawtype Tulong = ss "{#type gulong#}"
rawtype Tenum = ss "{#type gint#}"
rawtype Tflags = ss "{#type guint#}"
rawtype Tfloat = ss "{#type gfloat#}"
rawtype Tdouble = ss "{#type gdouble#}"
rawtype Tstring = ss "CString"
rawtype Tmstring = ss "CString"
rawtype Tboxed = ss "Ptr ()"
rawtype Tptr = ss "Ptr ()"
rawtype Ttobject = ss "Ptr GObject"
rawtype Tmtobject = ss "Ptr GObject"
rawtype Tobject = ss "Ptr GObject"
rawtype Tmobject = ss "Ptr GObject"
#endif
-- The possibly polymorphic type which
usertype :: Types -> [Char] -> (ShowS,[Char])
usertype Tunit cs = (ss "()",cs)
usertype Tbool (c:cs) = (ss "Bool",cs)
usertype Tchar (c:cs) = (ss "Char",cs)
usertype Tuchar (c:cs) = (ss "Char",cs)
usertype Tint (c:cs) = (ss "Int",cs)
usertype Tuint (c:cs) = (ss "Word",cs)
usertype Tlong (c:cs) = (ss "Int",cs)
usertype Tulong (c:cs) = (ss "Int",cs)
usertype Tenum (c:cs) = (sc c,cs)
usertype Tflags cs = usertype Tenum cs
usertype Tfloat (c:cs) = (ss "Float",cs)
usertype Tdouble (c:cs) = (ss "Double",cs)
usertype Tstring (c:cs) = (ss "String",cs)
usertype Tmstring (c:cs) = (ss "Maybe String",cs)
usertype Tboxed (c:cs) = (sc c,cs)
usertype Tptr (c:cs) = (ss "Ptr ".sc c,cs)
usertype Ttobject (c:cs) = (sc c.sc '\'',cs)
usertype Tmtobject (c:cs) = (ss "Maybe ".sc c.sc '\'',cs)
usertype Tobject (c:cs) = (sc c.sc '\'',cs)
usertype Tmobject (c:cs) = (ss "Maybe ".sc c.sc '\'',cs)
-- type declaration: only consume variables when they are needed
--
-- * Tint is used as return value as well. Therefore Integral has to be added
-- to the context. Grrr.
--
context :: [Types] -> [Char] -> [ShowS]
context (Tenum:ts) (c:cs) = ss "Enum ".sc c: context ts cs
context (Tflags:ts) (c:cs) = ss "Flags ".sc c: context ts cs
context (Ttobject:ts) (c:cs) = ss "GObjectClass ".sc c.sc '\'': context ts cs
context (Tmtobject:ts) (c:cs) = ss "GObjectClass ".sc c.sc '\'': context ts cs
context (Tobject:ts) (c:cs) = ss "GObjectClass ".sc c.sc '\'': context ts cs
context (Tmobject:ts) (c:cs) = ss "GObjectClass ".sc c.sc '\'': context ts cs
context (_:ts) (c:cs) = context ts cs
context [] _ = []
marshType :: [Types] -> [Char] -> [ShowS]
marshType (Tint:ts) (c:cs) = marshType ts cs
marshType (Tuint:ts) (c:cs) = marshType ts cs
marshType (Tenum:ts) (c:cs) = marshType ts cs
marshType (Tflags:ts) cs = marshType (Tenum:ts) cs
marshType (Tboxed:ts) (c:cs) = ss "(Ptr ".sc c.ss "' -> IO ".
sc c.ss ") -> ":
marshType ts cs
marshType (Tptr:ts) (c:cs) = marshType ts cs
marshType (Tobject:ts) (c:cs) = marshType ts cs
marshType (_:ts) (c:cs) = marshType ts cs
marshType [] _ = []
-- arguments for user defined marshalling
type ArgNo = Int
marshArg :: Types -> ArgNo -> ShowS
marshArg Tboxed c = ss "boxedPre".shows c.sc ' '
marshArg _ _ = id
-- generate a name for every passed argument,
nameArg :: Types -> ArgNo -> ShowS
nameArg Tunit _ = id
nameArg Tbool c = ss "bool".shows c
nameArg Tchar c = ss "char".shows c
nameArg Tuchar c = ss "char".shows c
nameArg Tint c = ss "int".shows c
nameArg Tuint c = ss "int".shows c
nameArg Tlong c = ss "long".shows c
nameArg Tulong c = ss "long".shows c
nameArg Tenum c = ss "enum".shows c
nameArg Tflags c = ss "flags".shows c
nameArg Tfloat c = ss "float".shows c
nameArg Tdouble c = ss "double".shows c
nameArg Tstring c = ss "str".shows c
nameArg Tmstring c = ss "str".shows c
nameArg Tboxed c = ss "box".shows c
nameArg Tptr c = ss "ptr".shows c
nameArg Ttobject c = ss "obj".shows c
nameArg Tmtobject c = ss "obj".shows c
nameArg Tobject c = ss "obj".shows c
nameArg Tmobject c = ss "obj".shows c
-- describe marshalling between the data passed from the registered function
-- to the user supplied Haskell function
#ifdef USE_GCLOSURE_SIGNALS_IMPL
marshExec :: Types -> ShowS -> Int -> (ShowS -> ShowS)
marshExec Tbool arg _ body = body. sc ' '. arg
marshExec Tchar arg _ body = body. sc ' '. arg
marshExec Tuchar arg _ body = body. sc ' '. arg
marshExec Tint arg _ body = body. sc ' '. arg
marshExec Tuint arg _ body = body. sc ' '. arg
marshExec Tlong arg _ body = body. sc ' '. arg
marshExec Tulong arg _ body = body. sc ' '. arg
marshExec Tenum arg _ body = body. ss " (toEnum ". arg. sc ')'
marshExec Tflags arg _ body = body. ss " (toFlags ". arg. sc ')'
marshExec Tfloat arg _ body = body. sc ' '. arg
marshExec Tdouble arg _ body = body. sc ' '. arg
marshExec Tstring arg _ body = indent 5. ss "peekUTFString ". arg. ss " >>= \\". arg. ss "\' ->".
body. sc ' '. arg. sc '\''
marshExec Tmstring arg _ body = indent 5. ss "maybePeekUTFString ". arg. ss " >>= \\". arg. ss "\' ->".
body. sc ' '. arg. sc '\''
marshExec Tboxed arg n body = indent 5. ss "boxedPre". ss (show n). ss " (castPtr ". arg. ss ") >>= \\". arg. ss "\' ->".
body. sc ' '. arg. sc '\''
marshExec Tptr arg _ body = body. ss " (castPtr ". arg. sc ')'
marshExec Ttobject arg _ body = indent 5.ss "makeNewGObject (GObject, objectUnrefFromMainloop) (return ". arg. ss ") >>= \\". arg. ss "\' ->".
body. ss " (unsafeCastGObject ". arg. ss "\')"
marshExec Tmtobject arg _ body = indent 5.ss "maybeNull (makeNewGObject (GObject, objectUnrefFromMainloop)) (return ". arg. ss ") >>= \\". arg. ss "\' ->".
body. ss " (liftM unsafeCastGObject ". arg. ss "\')"
marshExec Tobject arg _ body = indent 5.ss "makeNewGObject (GObject, objectUnref) (return ". arg. ss ") >>= \\". arg. ss "\' ->".
body. ss " (unsafeCastGObject ". arg. ss "\')"
marshExec Tmobject arg _ body = indent 5.ss "maybeNull (makeNewGObject (GObject, objectUnref)) (return ". arg. ss ") >>= \\". arg. ss "\' ->".
body. ss " (liftM unsafeCastGObject ". arg. ss "\')"
marshRet :: Types -> (ShowS -> ShowS)
marshRet Tunit body = body
marshRet Tbool body = body
marshRet Tint body = body
marshRet Tuint body = body
marshRet Tlong body = body
marshRet Tulong body = body
marshRet Tenum body = indent 5. ss "liftM fromEnum $ ". body
marshRet Tflags body = indent 5. ss "liftM fromFlags $ ". body
marshRet Tfloat body = body
marshRet Tdouble body = body
marshRet Tstring body = body. indent 5. ss ">>= newUTFString"
marshRet Tptr body = indent 5. ss "liftM castPtr $ ". body
marshRet _ _ = error "Signal handlers cannot return structured types."
#else
marshExec :: Types -> ArgNo -> ShowS
marshExec Tbool n = indent 4.ss "let bool".shows n.
ss "' = toBool bool".shows n
marshExec Tchar n = indent 4.ss "let char".shows n.
ss "' = (toEnum.fromEnum) char".shows n
marshExec Tuchar n = indent 4.ss "let char".shows n.
ss "' = (toEnum.fromEnum) char".shows n
marshExec Tint n = indent 4.ss "let int".shows n.
ss "' = fromIntegral int".shows n
marshExec Tuint n = indent 4.ss "let int".shows n.
ss "' = fromIntegral int".shows n
marshExec Tlong n = indent 4.ss "let long".shows n.
ss "' = toInteger long".shows n
marshExec Tulong n = indent 4.ss "let long".shows n.
ss "' = toInteger long".shows n
marshExec Tenum n = indent 4.ss "let enum".shows n.
ss "' = (toEnum.fromEnum) enum".shows n
marshExec Tflags n = indent 4.ss "let flags".shows n.
ss "' = (toEnum.fromEnum) flags".shows n
marshExec Tfloat n = indent 4.ss "let float".shows n.
ss "' = (fromRational.toRational) float".shows n
marshExec Tdouble n = indent 4.ss "let double".shows n.
ss "' = (fromRational.toRational) double".shows n
marshExec Tstring n = indent 4.ss "str".shows n.
ss "' <- peekCString str".shows n
marshExec Tmstring n = indent 4.ss "str".shows n.
ss "' <- maybePeekCString str".shows n
marshExec Tboxed n = indent 4.ss "box".shows n.ss "' <- boxedPre".
shows n.ss " $ castPtr box".shows n
marshExec Tptr n = indent 4.ss "let ptr".shows n.ss "' = castPtr ptr".
shows n
marshExec Ttobject n = indent 4.ss "objectRef obj".shows n.
indent 4.ss "obj".shows n.
ss "' <- liftM (unsafeCastGObject. fst mkGObject) $".
indent 5.ss "newForeignPtr obj".shows n.ss " (snd mkGObject)"
marshExec Tobject n = indent 4.ss "objectRef obj".shows n.
indent 4.ss "obj".shows n.
ss "' <- liftM (unsafeCastGObject. fst mkGObject) $".
indent 5.ss "newForeignPtr obj".shows n.ss " (snd mkGObject)"
marshExec _ _ = id
marshRet :: Types -> ShowS
marshRet Tunit = ss "id"
marshRet Tbool = ss "fromBool"
marshRet Tint = ss "fromIntegral"
marshRet Tuint = ss "fromIntegral"
marshRet Tlong = ss "fromIntegral"
marshRet Tulong = ss "fromIntegral"
marshRet Tenum = ss "(toEnum.fromEnum)"
marshRet Tflags = ss "fromFlags"
marshRet Tfloat = ss "(toRational.fromRational)"
marshRet Tdouble = ss "(toRational.fromRational)"
marshRet Tptr = ss "castPtr"
marshRet _ = ss "(error \"Signal handlers cannot return structured types.\")"
#endif
-------------------------------------------------------------------------------
-- generation of parameterized fragments
-------------------------------------------------------------------------------
mkUserType :: Signature -> ShowS
mkUserType (ret,ts) = let
(str,cs) = foldl (\(str,cs) t ->
let (str',cs') = usertype t cs in (str.str'.ss " -> ",cs'))
(sc '(',['a'..]) ts
(str',_) = usertype ret cs
str'' = if ' ' `elem` (str' "") then (sc '('.str'.sc ')') else str'
in str.ss "IO ".str''.sc ')'
mkContext :: Signature -> ShowS
mkContext (ret,ts) = let ctxts = context (ts++[ret]) ['a'..] in
if null ctxts then ss "GObjectClass obj =>" else sc '('.
foldl1 (\a b -> a.ss ", ".b) ctxts.ss ", GObjectClass obj) =>"
mkMarshType :: Signature -> [ShowS]
mkMarshType (ret,ts) = marshType (ts++[ret]) ['a'..]
mkType sig = let types = mkMarshType sig in
if null types then id else foldl (.) (indent 1) types
mkMarshArg :: Signature -> [ShowS]
mkMarshArg (ret,ts) = zipWith marshArg (ts++[ret]) [1..]
mkArg sig = foldl (.) (sc ' ') $ mkMarshArg sig
#ifdef USE_GCLOSURE_SIGNALS_IMPL
mkMarshExec :: Signature -> ShowS
mkMarshExec (ret,ts) = foldl (\body marshaler -> marshaler body) (indent 5.ss "user")
(paramMarshalers++[returnMarshaler])
where paramMarshalers = [ marshExec t (nameArg t n) n | (t,n) <- zip ts [1..] ]
returnMarshaler = marshRet ret
#else
mkMarshExec :: Signature -> ShowS
mkMarshExec (_,ts) = foldl (.) id $
zipWith marshExec ts [1..]
#endif
mkIdentifier :: Signature -> ShowS
mkIdentifier (ret,[]) = identifier Tunit . ss "__".identifier ret
mkIdentifier (ret,ts) = foldl1 (\a b -> a.sc '_'.b) (map identifier ts).
ss "__".identifier ret
mkRawtype :: Signature -> ShowS
mkRawtype (ret,ts) =
foldl (.) id (map (\ty -> rawtype ty.ss " -> ") ts).
(case ret of
Tboxed -> ss "IO (".rawtype ret.sc ')'
Tptr -> ss "IO (".rawtype ret.sc ')'
Ttobject -> ss "IO (".rawtype ret.sc ')'
Tmtobject -> ss "IO (".rawtype ret.sc ')'
Tobject -> ss "IO (".rawtype ret.sc ')'
Tmobject -> ss "IO (".rawtype ret.sc ')'
_ -> ss "IO ".rawtype ret)
mkLambdaArgs :: Signature -> ShowS
mkLambdaArgs (_,ts) = foldl (.) id $
zipWith (\a b -> nameArg a b.sc ' ') ts [1..]
#ifndef USE_GCLOSURE_SIGNALS_IMPL
mkFuncArgs :: Signature -> ShowS
mkFuncArgs (_,ts) = foldl (.) id $
zipWith (\a b -> sc ' '.nameArg a b.sc '\'') ts [1..]
mkMarshRet :: Signature -> ShowS
mkMarshRet (ret,_) = marshRet ret
#endif
-------------------------------------------------------------------------------
-- start of code generation
-------------------------------------------------------------------------------
usage = do
hPutStr stderr $
"Program to generate callback hook for Gtk signals. Usage:\n\n"++
"HookGenerator [--template=<template-file>] --types=<types-file>\n"++
" [--import=<import>] --modname=<moduleName> > <outFile>\n"++
"where\n"++
" <moduleName> the module name for <outFile>\n"++
" <template-file> a path to the Signal.chs.template file\n"++
" <types-file> a path to a gtkmarshal.list file\n"++
" <import> a module to be imported into the template file\n"
exitWith $ ExitFailure 1
main = do
args <- getArgs
let showHelp = not (null (filter ("-h" `isPrefixOf`) args++
filter ("--help" `isPrefixOf`) args)) || null args
if showHelp then usage else do
let outModuleName = case map (drop 10) (filter ("--modname=" `isPrefixOf`) args) of
(modName:_) -> modName
templateFile <- case map (drop 11) (filter ("--template=" `isPrefixOf`) args) of
[tplName] -> return tplName
_ -> getDataFileName "callbackGen/Signal.chs.template"
typesFile <- case map (drop 8) (filter ("--types=" `isPrefixOf`) args) of
[typName] -> return typName
_ -> usage
let extraImports = map (drop 9) (filter ("--import=" `isPrefixOf`) args)
content <- readFile typesFile
let sigs = parseSignatures content
template <- readFile templateFile
putStr $
templateSubstitute template (\var ->
case var of
"MODULE_NAME" -> ss outModuleName
"MODULE_EXPORTS" -> genExport sigs
"MODULE_IMPORTS" -> genImports extraImports
"MODULE_BODY" -> foldl (.) id (map generate sigs)
_ -> error var
) ""
templateSubstitute :: String -> (String -> ShowS) -> ShowS
templateSubstitute template varSubst = doSubst template
where doSubst [] = id
doSubst ('\\':'@':cs) = sc '@' . doSubst cs
doSubst ('@':cs) = let (var,_:cs') = span ('@'/=) cs
in varSubst var . doSubst cs'
doSubst (c:cs) = sc c . doSubst cs
-------------------------------------------------------------------------------
-- generate dynamic fragments
-------------------------------------------------------------------------------
genExport :: Signatures -> ShowS
genExport sigs = foldl (.) id (map mkId sigs)
where
mkId sig = ss "connect_".mkIdentifier sig.sc ','.indent 1
genImports :: [String] -> ShowS
genImports mods = foldl (.) id (map mkImp mods)
where
mkImp m = ss "import " . ss m . indent 0
#ifdef USE_GCLOSURE_SIGNALS_IMPL
generate :: Signature -> ShowS
generate sig = let ident = mkIdentifier sig in
indent 0.ss "connect_".ident.ss " :: ".
indent 1.mkContext sig.ss " SignalName ->".
mkType sig.
indent 1.ss "ConnectAfter -> obj ->".
indent 1.mkUserType sig.ss " ->".
indent 1.ss "IO (ConnectId obj)".
indent 0.ss "connect_".ident.ss " signal". mkArg sig. ss "after obj user =".
indent 1.ss "connectGeneric signal after obj action".
indent 1.ss "where action :: Ptr GObject -> ".mkRawtype sig.
indent 1.ss " action _ ".mkLambdaArgs sig. sc '='.
indent 5.ss "failOnGError $".
mkMarshExec sig.
indent 0
#else
generate :: Signature -> ShowS
generate sig = let ident = mkIdentifier sig in
indent 0.ss "type Tag_".ident.ss " = Ptr () -> ".
indent 1.mkRawtype sig.
indent 0.
indent 0.ss "foreign".ss " import ccall \"wrapper\" ".ss "mkHandler_".ident.ss " ::".
indent 1.ss "Tag_".ident.ss " -> ".
indent 1.ss "IO (FunPtr ".ss "Tag_".ident.sc ')'.
indent 0.
indent 0.ss "connect_".ident.ss " :: ".
indent 1.mkContext sig.ss " SignalName ->".
mkType sig.
indent 1.ss "ConnectAfter -> obj ->".
indent 1.mkUserType sig.ss " ->".
indent 1.ss "IO (ConnectId obj)".
indent 0.ss "connect_".ident.ss " signal".
mkArg sig.
indent 1.ss "after obj user =".
indent 1.ss "do".
indent 2.ss "hPtr <- mkHandler_".ident.
indent 3.ss "(\\_ ".mkLambdaArgs sig.ss "-> failOnGError $ do".
mkMarshExec sig.
indent 4.ss "liftM ".mkMarshRet sig.ss " $".
indent 5.ss "user".mkFuncArgs sig.
indent 3.sc ')'.
indent 2.ss "dPtr <- mkFunPtrClosureNotify hPtr".
indent 2.ss "sigId <- withCString signal $ \\nPtr ->".
indent 3.ss "withForeignPtr ((unGObject.toGObject) obj) $ \\objPtr ->".
indent 4.ss "{#call unsafe g_signal_connect_data#} (castPtr objPtr)".
indent 5.ss "nPtr (castFunPtr hPtr) nullPtr dPtr (fromBool after)".
indent 2.ss "return $ ConnectId sigId obj".
indent 0
#endif
| phischu/gtk2hs | tools/callbackGen/HookGenerator.hs | lgpl-3.0 | 22,625 | 145 | 24 | 4,773 | 7,029 | 3,558 | 3,471 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- License : BSD-3-Clause
-- Maintainer : Oleg Grenrus <[email protected]>
--
-- The organization members API as described on
-- <http://developer.github.com/v3/orgs/members/>.
module GitHub.Endpoints.Organizations.Members (
membersOfR,
membersOfWithR,
isMemberOfR,
orgInvitationsR,
module GitHub.Data,
) where
import GitHub.Data
import GitHub.Internal.Prelude
import Prelude ()
-- | All the users who are members of the specified organization.
--
-- See <https://developer.github.com/v3/orgs/members/#members-list>
membersOfR :: Name Organization -> FetchCount -> Request k (Vector SimpleUser)
membersOfR organization =
pagedQuery ["orgs", toPathPart organization, "members"] []
-- | 'membersOfR' with filters.
--
-- See <https://developer.github.com/v3/orgs/members/#members-list>
membersOfWithR :: Name Organization -> OrgMemberFilter -> OrgMemberRole -> FetchCount -> Request k (Vector SimpleUser)
membersOfWithR org f r =
pagedQuery ["orgs", toPathPart org, "members"] [("filter", Just f'), ("role", Just r')]
where
f' = case f of
OrgMemberFilter2faDisabled -> "2fa_disabled"
OrgMemberFilterAll -> "all"
r' = case r of
OrgMemberRoleAll -> "all"
OrgMemberRoleAdmin -> "admin"
OrgMemberRoleMember -> "member"
-- | Check if a user is a member of an organization.
--
-- See <https://developer.github.com/v3/orgs/members/#check-membership>
isMemberOfR :: Name User -> Name Organization -> GenRequest 'MtStatus rw Bool
isMemberOfR user org =
Query [ "orgs", toPathPart org, "members", toPathPart user ] []
-- | List pending organization invitations
--
-- See <https://developer.github.com/v3/orgs/members/#list-pending-organization-invitations>
orgInvitationsR :: Name Organization -> FetchCount -> Request 'RA (Vector Invitation)
orgInvitationsR org = pagedQuery ["orgs", toPathPart org, "invitations"] []
| jwiegley/github | src/GitHub/Endpoints/Organizations/Members.hs | bsd-3-clause | 2,001 | 0 | 11 | 326 | 376 | 208 | 168 | -1 | -1 |
foo = doSomething 123 -- Do something important.
| ruchee/vimrc | vimfiles/bundle/vim-haskell/tests/indent/test006/test.hs | mit | 50 | 0 | 5 | 9 | 10 | 5 | 5 | 1 | 1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="fa-IR">
<title>Call Graph</title>
<maps>
<homeID>callgraph</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/callgraph/src/main/javahelp/help_fa_IR/helpset_fa_IR.hs | apache-2.0 | 961 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- The 'Functor', 'Monad' and 'MonadPlus' classes,
-- with some useful operations on monads.
module Control.Monad
(
-- * Functor and monad classes
Functor(fmap)
, Monad((>>=), (>>), return, fail)
, MonadPlus ( -- class context: Monad
mzero -- :: (MonadPlus m) => m a
, mplus -- :: (MonadPlus m) => m a -> m a -> m a
)
-- * Functions
-- ** Naming conventions
-- $naming
-- ** Basic @Monad@ functions
, mapM -- :: (Monad m) => (a -> m b) -> [a] -> m [b]
, mapM_ -- :: (Monad m) => (a -> m b) -> [a] -> m ()
, forM -- :: (Monad m) => [a] -> (a -> m b) -> m [b]
, forM_ -- :: (Monad m) => [a] -> (a -> m b) -> m ()
, sequence -- :: (Monad m) => [m a] -> m [a]
, sequence_ -- :: (Monad m) => [m a] -> m ()
, (=<<) -- :: (Monad m) => (a -> m b) -> m a -> m b
, (>=>) -- :: (Monad m) => (a -> m b) -> (b -> m c) -> (a -> m c)
, (<=<) -- :: (Monad m) => (b -> m c) -> (a -> m b) -> (a -> m c)
, forever -- :: (Monad m) => m a -> m b
, void
-- ** Generalisations of list functions
, join -- :: (Monad m) => m (m a) -> m a
, msum -- :: (MonadPlus m) => [m a] -> m a
, mfilter -- :: (MonadPlus m) => (a -> Bool) -> m a -> m a
, filterM -- :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
, mapAndUnzipM -- :: (Monad m) => (a -> m (b,c)) -> [a] -> m ([b], [c])
, zipWithM -- :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m [c]
, zipWithM_ -- :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m ()
, foldM -- :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
, foldM_ -- :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m ()
, replicateM -- :: (Monad m) => Int -> m a -> m [a]
, replicateM_ -- :: (Monad m) => Int -> m a -> m ()
-- ** Conditional execution of monadic expressions
, guard -- :: (MonadPlus m) => Bool -> m ()
, when -- :: (Monad m) => Bool -> m () -> m ()
, unless -- :: (Monad m) => Bool -> m () -> m ()
-- ** Monadic lifting operators
, liftM -- :: (Monad m) => (a -> b) -> (m a -> m b)
, liftM2 -- :: (Monad m) => (a -> b -> c) -> (m a -> m b -> m c)
, liftM3 -- :: ...
, liftM4 -- :: ...
, liftM5 -- :: ...
, ap -- :: (Monad m) => m (a -> b) -> m a -> m b
) where
import Data.Maybe
#ifdef __GLASGOW_HASKELL__
import GHC.List
import GHC.Base
#endif
#ifdef __GLASGOW_HASKELL__
infixr 1 =<<
-- -----------------------------------------------------------------------------
-- Prelude monad functions
-- | Same as '>>=', but with the arguments interchanged.
{-# SPECIALISE (=<<) :: (a -> [b]) -> [a] -> [b] #-}
(=<<) :: Monad m => (a -> m b) -> m a -> m b
f =<< x = x >>= f
-- | Evaluate each action in the sequence from left to right,
-- and collect the results.
sequence :: Monad m => [m a] -> m [a]
{-# INLINE sequence #-}
sequence ms = foldr k (return []) ms
where
k m m' = do { x <- m; xs <- m'; return (x:xs) }
-- | Evaluate each action in the sequence from left to right,
-- and ignore the results.
sequence_ :: Monad m => [m a] -> m ()
{-# INLINE sequence_ #-}
sequence_ ms = foldr (>>) (return ()) ms
-- | @'mapM' f@ is equivalent to @'sequence' . 'map' f@.
mapM :: Monad m => (a -> m b) -> [a] -> m [b]
{-# INLINE mapM #-}
mapM f as = sequence (map f as)
-- | @'mapM_' f@ is equivalent to @'sequence_' . 'map' f@.
mapM_ :: Monad m => (a -> m b) -> [a] -> m ()
{-# INLINE mapM_ #-}
mapM_ f as = sequence_ (map f as)
#endif /* __GLASGOW_HASKELL__ */
-- -----------------------------------------------------------------------------
-- The MonadPlus class definition
-- | Monads that also support choice and failure.
class Monad m => MonadPlus m where
-- | the identity of 'mplus'. It should also satisfy the equations
--
-- > mzero >>= f = mzero
-- > v >> mzero = mzero
--
mzero :: m a
-- | an associative operation
mplus :: m a -> m a -> m a
instance MonadPlus [] where
mzero = []
mplus = (++)
instance MonadPlus Maybe where
mzero = Nothing
Nothing `mplus` ys = ys
xs `mplus` _ys = xs
-- -----------------------------------------------------------------------------
-- Functions mandated by the Prelude
-- | @'guard' b@ is @'return' ()@ if @b@ is 'True',
-- and 'mzero' if @b@ is 'False'.
guard :: (MonadPlus m) => Bool -> m ()
guard True = return ()
guard False = mzero
-- | This generalizes the list-based 'filter' function.
filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
filterM _ [] = return []
filterM p (x:xs) = do
flg <- p x
ys <- filterM p xs
return (if flg then x:ys else ys)
-- | 'forM' is 'mapM' with its arguments flipped
forM :: Monad m => [a] -> (a -> m b) -> m [b]
{-# INLINE forM #-}
forM = flip mapM
-- | 'forM_' is 'mapM_' with its arguments flipped
forM_ :: Monad m => [a] -> (a -> m b) -> m ()
{-# INLINE forM_ #-}
forM_ = flip mapM_
-- | This generalizes the list-based 'concat' function.
msum :: MonadPlus m => [m a] -> m a
{-# INLINE msum #-}
msum = foldr mplus mzero
infixr 1 <=<, >=>
-- | Left-to-right Kleisli composition of monads.
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)
f >=> g = \x -> f x >>= g
-- | Right-to-left Kleisli composition of monads. @('>=>')@, with the arguments flipped
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)
(<=<) = flip (>=>)
-- | @'forever' act@ repeats the action infinitely.
forever :: (Monad m) => m a -> m b
{-# INLINE forever #-}
forever a = let a' = a >> a' in a'
-- Use explicit sharing here, as it is prevents a space leak regardless of
-- optimizations.
-- | @'void' value@ discards or ignores the result of evaluation, such as the return value of an 'IO' action.
void :: Functor f => f a -> f ()
void = fmap (const ())
-- -----------------------------------------------------------------------------
-- Other monad functions
-- | The 'join' function is the conventional monad join operator. It is used to
-- remove one level of monadic structure, projecting its bound argument into the
-- outer level.
join :: (Monad m) => m (m a) -> m a
join x = x >>= id
-- | The 'mapAndUnzipM' function maps its first argument over a list, returning
-- the result as a pair of lists. This function is mainly used with complicated
-- data structures or a state-transforming monad.
mapAndUnzipM :: (Monad m) => (a -> m (b,c)) -> [a] -> m ([b], [c])
mapAndUnzipM f xs = sequence (map f xs) >>= return . unzip
-- | The 'zipWithM' function generalizes 'zipWith' to arbitrary monads.
zipWithM :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m [c]
zipWithM f xs ys = sequence (zipWith f xs ys)
-- | 'zipWithM_' is the extension of 'zipWithM' which ignores the final result.
zipWithM_ :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m ()
zipWithM_ f xs ys = sequence_ (zipWith f xs ys)
{- | The 'foldM' function is analogous to 'foldl', except that its result is
encapsulated in a monad. Note that 'foldM' works from left-to-right over
the list arguments. This could be an issue where @('>>')@ and the `folded
function' are not commutative.
> foldM f a1 [x1, x2, ..., xm]
==
> do
> a2 <- f a1 x1
> a3 <- f a2 x2
> ...
> f am xm
If right-to-left evaluation is required, the input list should be reversed.
-}
foldM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
foldM _ a [] = return a
foldM f a (x:xs) = f a x >>= \fax -> foldM f fax xs
-- | Like 'foldM', but discards the result.
foldM_ :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m ()
foldM_ f a xs = foldM f a xs >> return ()
-- | @'replicateM' n act@ performs the action @n@ times,
-- gathering the results.
replicateM :: (Monad m) => Int -> m a -> m [a]
replicateM n x = sequence (replicate n x)
-- | Like 'replicateM', but discards the result.
replicateM_ :: (Monad m) => Int -> m a -> m ()
replicateM_ n x = sequence_ (replicate n x)
{- | Conditional execution of monadic expressions. For example,
> when debug (putStr "Debugging\n")
will output the string @Debugging\\n@ if the Boolean value @debug@ is 'True',
and otherwise do nothing.
-}
when :: (Monad m) => Bool -> m () -> m ()
when p s = if p then s else return ()
-- | The reverse of 'when'.
unless :: (Monad m) => Bool -> m () -> m ()
unless p s = if p then return () else s
-- | Promote a function to a monad.
liftM :: (Monad m) => (a1 -> r) -> m a1 -> m r
liftM f m1 = do { x1 <- m1; return (f x1) }
-- | Promote a function to a monad, scanning the monadic arguments from
-- left to right. For example,
--
-- > liftM2 (+) [0,1] [0,2] = [0,2,1,3]
-- > liftM2 (+) (Just 1) Nothing = Nothing
--
liftM2 :: (Monad m) => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
liftM2 f m1 m2 = do { x1 <- m1; x2 <- m2; return (f x1 x2) }
-- | Promote a function to a monad, scanning the monadic arguments from
-- left to right (cf. 'liftM2').
liftM3 :: (Monad m) => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r
liftM3 f m1 m2 m3 = do { x1 <- m1; x2 <- m2; x3 <- m3; return (f x1 x2 x3) }
-- | Promote a function to a monad, scanning the monadic arguments from
-- left to right (cf. 'liftM2').
liftM4 :: (Monad m) => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r
liftM4 f m1 m2 m3 m4 = do { x1 <- m1; x2 <- m2; x3 <- m3; x4 <- m4; return (f x1 x2 x3 x4) }
-- | Promote a function to a monad, scanning the monadic arguments from
-- left to right (cf. 'liftM2').
liftM5 :: (Monad m) => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r
liftM5 f m1 m2 m3 m4 m5 = do { x1 <- m1; x2 <- m2; x3 <- m3; x4 <- m4; x5 <- m5; return (f x1 x2 x3 x4 x5) }
{- | In many situations, the 'liftM' operations can be replaced by uses of
'ap', which promotes function application.
> return f `ap` x1 `ap` ... `ap` xn
is equivalent to
> liftMn f x1 x2 ... xn
-}
ap :: (Monad m) => m (a -> b) -> m a -> m b
ap = liftM2 id
-- -----------------------------------------------------------------------------
-- Other MonadPlus functions
-- | Direct 'MonadPlus' equivalent of 'filter'
-- @'filter'@ = @(mfilter:: (a -> Bool) -> [a] -> [a]@
-- applicable to any 'MonadPlus', for example
-- @mfilter odd (Just 1) == Just 1@
-- @mfilter odd (Just 2) == Nothing@
mfilter :: (MonadPlus m) => (a -> Bool) -> m a -> m a
mfilter p ma = do
a <- ma
if p a then return a else mzero
{- $naming
The functions in this library use the following naming conventions:
* A postfix \'@M@\' always stands for a function in the Kleisli category:
The monad type constructor @m@ is added to function results
(modulo currying) and nowhere else. So, for example,
> filter :: (a -> Bool) -> [a] -> [a]
> filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
* A postfix \'@_@\' changes the result type from @(m a)@ to @(m ())@.
Thus, for example:
> sequence :: Monad m => [m a] -> m [a]
> sequence_ :: Monad m => [m a] -> m ()
* A prefix \'@m@\' generalizes an existing function to a monadic form.
Thus, for example:
> sum :: Num a => [a] -> a
> msum :: MonadPlus m => [m a] -> m a
-}
| nyson/haste-compiler | libraries/ghc-7.8/base/Control/Monad.hs | bsd-3-clause | 12,115 | 0 | 12 | 3,533 | 2,602 | 1,410 | 1,192 | 123 | 2 |
{-# LANGUAGE TypeFamilies, RankNTypes, FlexibleContexts, ScopedTypeVariables #-}
module T4494 where
type family H s
type family F v
bar :: (forall t. Maybe t -> a) -> H a -> Int
bar = error "urk"
call :: F Bool -> Int
call x = bar (\_ -> x) (undefined :: H (F Bool))
{-
[W] H (F Bool) ~ H alpha
[W] alpha ~ F Bool
-->
F Bool ~ fuv0
H fuv0 ~ fuv1
H alpha ~ fuv2
fuv1 ~ fuv2
alpha ~ fuv0
flatten
~~~~~~~
fuv0 := alpha
fuv1 := fuv2
alpha := F Bool
-}
| urbanslug/ghc | testsuite/tests/indexed-types/should_compile/T4494.hs | bsd-3-clause | 474 | 0 | 9 | 124 | 105 | 58 | 47 | 8 | 1 |
{-# LANGUAGE NoImplicitPrelude, ParallelListComp #-}
module Tak.Buffer where
import Prelude as P
import Data.Sequence ((><), (|>), (<|))
import qualified Data.Sequence as Seq
import qualified Data.Text as Text
import Data.Char (isSpace)
import Data.Foldable (toList)
import Data.Monoid (mconcat)
import Control.Monad (when)
import Tak.Types as TT
import Tak.Util
import Tak.Display
import Tak.Text
import Tak.Buffer.LineSeq
import Tak.Buffer.Line
empty :: Buffer
empty = Buffer (Seq.singleton Text.empty)
handleEmptySeq :: Buffer -> Buffer
handleEmptySeq buf =
if (lineSeq buf) == Seq.empty
then empty
else buf
lineSeqToStr :: LineSeq -> String
lineSeqToStr seq = Text.unpack $ Text.unlines $ toList seq
strToBuffer :: String -> Buffer
strToBuffer s = textToBuffer $ Text.pack s
textToBuffer :: Line -> Buffer
textToBuffer t = handleEmptySeq $ Buffer (Seq.fromList $ Text.lines t)
bufferToStr :: Buffer -> String
bufferToStr buf = Text.unpack $ Text.unlines $ bufferToLines buf
bufferToLines :: Buffer -> [Line]
bufferToLines buf = toList (lineSeq buf)
lineAt :: Int -> Buffer -> Line
lineAt x buf = Seq.index (lineSeq buf) x
updateLineSeq :: (LineSeq -> LineSeq) -> Buffer -> Buffer
updateLineSeq f buf = buf { lineSeq = f $ lineSeq buf }
bufferDropLines :: Int -> Buffer -> Buffer
bufferDropLines lines buffer =
handleEmptySeq $ Buffer $ Seq.drop lines (lineSeq buffer)
posWithinBuffer :: Buffer -> Pos -> Pos
posWithinBuffer buf (Pos y x) =
let l = clamp 0 (lastLineIdx buf) y
r = clamp 0 (Text.length $ lineAt l buf) x
in Pos l r
renderLine idx str mHlReg = do
let hlRangeStart = maybe (-1) (\(Range (Pos l r) _) -> if l == idx then r else (-1)) mHlReg
hlRangeEnd = maybe (-1) (\(Range _ (Pos l r)) -> if l == idx then r else (-1)) mHlReg
rangeStarts = hlRangeStart > (-1)
rangeEnds = hlRangeEnd > (-1)
printStr (Pos idx 0) str
when (hlRangeStart > (-1)) (invertText >> (printStr (Pos idx hlRangeStart) (P.drop hlRangeStart str)))
when (hlRangeEnd > (-1)) (regularText >> (printStr (Pos idx hlRangeEnd) (P.drop hlRangeEnd str)))
renderBuffer :: WrapMode -> Buffer -> Maybe Range -> Int -> Int -> RenderW ()
renderBuffer wrapMode buffer mRange height width =
let lineStrs = linesToFixedLengthStrs wrapMode width (bufferToLines buffer)
yPosL = [0..height - 1]
in sequence_ [ renderLine y line mRng
| y <- yPosL
| line <- lineStrs ++ (repeat "")
| mRng <- repeat mRange ]
insertCharIntoBuffer :: Buffer -> Pos -> Char -> Buffer
insertCharIntoBuffer buf (Pos y x) char =
let seq = lineSeq buf
line = Seq.index seq y
(before, after) = Text.splitAt x line
in buf { lineSeq = Seq.update y (Text.concat [before, Text.singleton char, after]) seq }
deleteCharFromBuffer :: Buffer -> Pos -> Buffer
deleteCharFromBuffer buf (Pos y x) =
let seq = lineSeq buf
line = Seq.index seq y
(before, after) = Text.splitAt x line
newBefore = if not $ Text.null before
then Text.take (Text.length before - 1) before
else before
in buf { lineSeq = Seq.update y (Text.concat [newBefore, after]) seq }
insertLinebreakIntoBuffer :: Buffer -> Pos -> Buffer
insertLinebreakIntoBuffer buf (Pos y x) =
let seq = lineSeq buf
(seqBefore, seqRest) = Seq.splitAt y seq
seqAfter = if Seq.null seqRest
then Seq.empty
else Seq.drop 1 seqRest
(before, after) = Text.splitAt x (Seq.index seqRest 0)
seqMiddle = Seq.fromList [before, after]
in buf { lineSeq = (seqBefore >< seqMiddle >< seqAfter) }
numLines :: Buffer -> Int
numLines buf = Seq.length (lineSeq buf)
lastLineIdx :: Buffer -> Int
lastLineIdx buf = (numLines buf) - 1
deleteLine :: Buffer -> Int -> Buffer
deleteLine buf idx =
let seq = lineSeq buf
(left, right) = Seq.splitAt idx seq
in handleEmptySeq $ buf { lineSeq = (left >< (Seq.drop 1 right)) }
concatLine :: Buffer -> Int -> Buffer
concatLine buf idx =
let seq = lineSeq buf
(left, right) = Seq.splitAt (idx - 1) seq
concatted = Text.concat [(Seq.index right 0), (Seq.index right 1)]
in if idx <= 0 || (Seq.length right) < 2
then buf
else buf { lineSeq = (left |> concatted) >< (Seq.drop 2 right) }
cutSelectionLS :: LineSeq -> (Pos, Pos) -> (LineSeq, LineSeq)
cutSelectionLS src ((Pos sl sr), (Pos el er)) =
let splitOne seq = let (one, rest) = Seq.splitAt 1 seq in (Seq.index one 0, rest)
rl = (el - sl) - 1
(before, rem0) = Seq.splitAt sl src
(startLine, rem1) = splitOne rem0
(beforeLine, inLine) = Text.splitAt sr startLine
(inLines, _) = Seq.splitAt rl rem1
(_, rem2) = Seq.splitAt el src
(lastLine, after) = splitOne rem2
(outLine, afterLine) = Text.splitAt er lastLine
si = Seq.singleton
in (if sl == el
then si (Text.take (er - sr) inLine)
else mconcat [si inLine, inLines, si outLine],
mconcat [before, si $ Text.concat [beforeLine, afterLine], after])
cutSelection :: Buffer -> (Pos, Pos) -> (LineSeq, Buffer)
cutSelection buf r =
let (cut, rest) = cutSelectionLS (lineSeq buf) r
in (cut, buf { lineSeq = rest })
getSelection :: Buffer -> (Pos, Pos) -> LineSeq
getSelection b r = fst $ cutSelection b r
delSelection :: Buffer -> (Pos, Pos) -> Buffer
delSelection b r = snd $ cutSelection b r
insertLineSeqIntoBuffer :: Buffer -> Pos -> LineSeq -> Buffer
insertLineSeqIntoBuffer buf pos inSeq =
let Pos l r = posWithinBuffer buf pos
seq = lineSeq buf
seqBefore = Seq.take l seq
seqAfter = Seq.drop (l + 1) seq
line = Seq.index seq l
lineBefore = Text.take r line
lineAfter = Text.drop r line
in case Seq.length inSeq of
0 -> buf
1 -> buf { lineSeq = mconcat [seqBefore,
Seq.singleton (Text.concat [lineBefore, (Seq.index inSeq 0), lineAfter]),
seqAfter] }
otherwise ->
let firstLine = Seq.index inSeq 0
lastLine = Seq.index inSeq ((Seq.length inSeq) - 1)
midLines = Seq.drop 1 $ Seq.take ((Seq.length inSeq) - 1) inSeq
in buf { lineSeq = mconcat [seqBefore,
Seq.singleton (Text.concat [lineBefore, firstLine]),
midLines,
Seq.singleton (Text.concat [lastLine, lineAfter]),
seqAfter] }
posNextPara :: Buffer -> Pos -> Pos
posNextPara buf pos =
case idxParasAfter (lineSeq buf) (line pos) of
idx:_ -> Pos idx 0
otherwise -> posLastPos buf pos
posPrevPara :: Buffer -> Pos -> Pos
posPrevPara buf pos =
case idxParasBefore (lineSeq buf) (line pos) of
idx:_ -> Pos idx 0
otherwise -> posFirstPos buf pos
posNextWord :: Buffer -> Pos -> Pos
posNextWord buf pos =
let Pos l r = pos
in case idxWordsAfter (lineAt l buf) r of
idx:_ -> Pos l idx
otherwise -> if l < numLines buf
then Pos (l + 1) 0
else pos
posPrevWord :: Buffer -> Pos -> Pos
posPrevWord buf pos =
let Pos l r = pos
in case idxWordsBefore (lineAt (line pos) buf) (row pos) of
idx:_ -> Pos (line pos) idx
otherwise -> if r > 0
then Pos l 0
else if l > 0
then Pos (l - 1) ((Text.length $ lineAt (l - 1) buf) - 1)
else pos
posFirstPos :: Buffer -> Pos -> Pos
posFirstPos buf _ = idxFirstPos $ lineSeq buf
posLastPos :: Buffer -> Pos -> Pos
posLastPos buf _ = idxLastPos $ lineSeq buf
| sixohsix/tak | src/Tak/Buffer.hs | mit | 7,667 | 2 | 20 | 2,087 | 3,005 | 1,564 | 1,441 | 182 | 4 |
module ALibrary() where
aFunction::Int->Int
aFunction a = a | madmaw/grunt-haste-compiler | test/fixtures/ALibrary.hs | mit | 60 | 0 | 5 | 8 | 24 | 14 | 10 | 3 | 1 |
module Language.X86.Mangling
( mangleFuncName
) where
import System.Info ( os )
mangleFuncName :: String -> String
mangleFuncName s
| os == "darwin" = '_' : s
| otherwise = s
| djeik/goto | libgoto/Language/X86/Mangling.hs | mit | 185 | 0 | 8 | 40 | 62 | 33 | 29 | 7 | 1 |
module I2C where
baseNumComv :: Int -> Int -> [Int] -> [Int]
baseNumComv x n xs
| x == 0 = xs
| x == 1 = (1:xs)
| otherwise = ss : baseNumComv ns n xs
where ss = x `mod` n
ns = x `div` n
d2b :: Int -> [Int]
d2b n = reverse $ baseNumComv n 2 []
d2h :: Int -> [Int]
d2h n = reverse $ baseNumComv n 16 []
i2cStart = do
print "start_test" | SugimotoSohei/hask4raspi | lib/I2C.hs | mit | 377 | 0 | 8 | 123 | 190 | 99 | 91 | 14 | 1 |
{-# LANGUAGE ConstrainedClassMethods #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
-- | Type classes mirroring standard typeclasses, but working with monomorphic containers.
--
-- The motivation is that some commonly used data types (i.e., 'ByteString' and
-- 'Text') do not allow for instances of typeclasses like 'Functor' and
-- 'Foldable', since they are monomorphic structures. This module allows both
-- monomorphic and polymorphic data types to be instances of the same
-- typeclasses.
--
-- All of the laws for the polymorphic typeclasses apply to their monomorphic
-- cousins. Thus, even though a 'MonoFunctor' instance for 'Set' could
-- theoretically be defined, it is omitted since it could violate the functor
-- law of @'omap' f . 'omap' g = 'omap' (f . g)@.
--
-- Note that all typeclasses have been prefixed with @Mono@, and functions have
-- been prefixed with @o@. The mnemonic for @o@ is "only one", or alternatively
-- \"it's mono, but m is overused in Haskell, so we'll use the second letter
-- instead.\" (Agreed, it's not a great mangling scheme, input is welcome!)
module Data.MonoTraversable where
import Control.Applicative
import Control.Category
import Control.Monad (Monad (..), liftM)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import qualified Data.Foldable as F
import Data.Functor
import Data.Maybe (fromMaybe)
import Data.Monoid (Monoid (..), Any (..), All (..))
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Data.Traversable
import Data.Traversable.Instances ()
import Data.Word (Word8)
import Data.Int (Int, Int64)
import GHC.Exts (build)
import Prelude (Bool (..), const, Char, flip, IO, Maybe (..), Either (..),
(+), Integral, Ordering (..), compare, fromIntegral, Num, (>=),
seq, otherwise, Eq, Ord, (-), (*))
import qualified Prelude
import qualified Data.ByteString.Internal as Unsafe
import qualified Foreign.ForeignPtr.Unsafe as Unsafe
import Foreign.Ptr (plusPtr)
import Foreign.ForeignPtr (touchForeignPtr)
import Foreign.Storable (peek)
import Control.Arrow (Arrow)
import Data.Tree (Tree (..))
import Data.Sequence (Seq, ViewL (..), ViewR (..))
import qualified Data.Sequence as Seq
import Data.IntMap (IntMap)
import Data.IntSet (IntSet)
import qualified Data.List as List
import Data.List.NonEmpty (NonEmpty)
import Data.Functor.Identity (Identity)
import Data.Map (Map)
import Data.HashMap.Strict (HashMap)
import Data.Vector (Vector)
import Control.Monad.Trans.Maybe (MaybeT (..))
import Control.Monad.Trans.List (ListT)
import Control.Monad.Trans.Identity (IdentityT)
import Data.Functor.Apply (MaybeApply (..), WrappedApplicative)
import Control.Comonad (Cokleisli, Comonad, extract, extend)
import Control.Comonad.Store (StoreT)
import Control.Comonad.Env (EnvT)
import Control.Comonad.Traced (TracedT)
import Data.Functor.Coproduct (Coproduct)
import Control.Monad.Trans.Writer (WriterT)
import qualified Control.Monad.Trans.Writer.Strict as Strict (WriterT)
import Control.Monad.Trans.State (StateT(..))
import qualified Control.Monad.Trans.State.Strict as Strict (StateT(..))
import Control.Monad.Trans.RWS (RWST(..))
import qualified Control.Monad.Trans.RWS.Strict as Strict (RWST(..))
import Control.Monad.Trans.Reader (ReaderT)
import Control.Monad.Trans.Error (ErrorT(..))
import Control.Monad.Trans.Cont (ContT)
import Data.Functor.Compose (Compose)
import Data.Functor.Product (Product)
import Data.Semigroupoid.Static (Static)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.HashSet (HashSet)
import qualified Data.HashSet as HashSet
import Data.Hashable (Hashable)
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Storable as VS
import qualified Data.IntSet as IntSet
import Data.Semigroup (Semigroup, Option (..), Arg)
import qualified Data.ByteString.Unsafe as SU
import Data.DList (DList)
import qualified Data.DList as DL
-- | Type family for getting the type of the elements
-- of a monomorphic container.
type family Element mono
type instance Element S.ByteString = Word8
type instance Element L.ByteString = Word8
type instance Element T.Text = Char
type instance Element TL.Text = Char
type instance Element [a] = a
type instance Element (IO a) = a
type instance Element (ZipList a) = a
type instance Element (Maybe a) = a
type instance Element (Tree a) = a
type instance Element (Seq a) = a
type instance Element (DList a) = a
type instance Element (ViewL a) = a
type instance Element (ViewR a) = a
type instance Element (IntMap a) = a
type instance Element IntSet = Int
type instance Element (Option a) = a
type instance Element (NonEmpty a) = a
type instance Element (Identity a) = a
type instance Element (r -> a) = a
type instance Element (Either a b) = b
type instance Element (a, b) = b
type instance Element (Const m a) = a
type instance Element (WrappedMonad m a) = a
type instance Element (Map k v) = v
type instance Element (HashMap k v) = v
type instance Element (Set e) = e
type instance Element (HashSet e) = e
type instance Element (Vector a) = a
type instance Element (WrappedArrow a b c) = c
type instance Element (MaybeApply f a) = a
type instance Element (WrappedApplicative f a) = a
type instance Element (Cokleisli w a b) = b
type instance Element (MaybeT m a) = a
type instance Element (ListT m a) = a
type instance Element (IdentityT m a) = a
type instance Element (WriterT w m a) = a
type instance Element (Strict.WriterT w m a) = a
type instance Element (StateT s m a) = a
type instance Element (Strict.StateT s m a) = a
type instance Element (RWST r w s m a) = a
type instance Element (Strict.RWST r w s m a) = a
type instance Element (ReaderT r m a) = a
type instance Element (ErrorT e m a) = a
type instance Element (ContT r m a) = a
type instance Element (Compose f g a) = a
type instance Element (Product f g a) = a
type instance Element (Static f a b) = b
type instance Element (U.Vector a) = a
type instance Element (VS.Vector a) = a
type instance Element (Arg a b) = b
type instance Element (EnvT e w a) = a
type instance Element (StoreT s w a) = a
type instance Element (TracedT m w a) = a
type instance Element (Coproduct f g a) = a
-- | Monomorphic containers that can be mapped over.
class MonoFunctor mono where
-- | Map over a monomorphic container
omap :: (Element mono -> Element mono) -> mono -> mono
default omap :: (Functor f, Element (f a) ~ a, f a ~ mono) => (a -> a) -> f a -> f a
omap = fmap
{-# INLINE omap #-}
instance MonoFunctor S.ByteString where
omap = S.map
{-# INLINE omap #-}
instance MonoFunctor L.ByteString where
omap = L.map
{-# INLINE omap #-}
instance MonoFunctor T.Text where
omap = T.map
{-# INLINE omap #-}
instance MonoFunctor TL.Text where
omap = TL.map
{-# INLINE omap #-}
instance MonoFunctor [a]
instance MonoFunctor (IO a)
instance MonoFunctor (ZipList a)
instance MonoFunctor (Maybe a)
instance MonoFunctor (Tree a)
instance MonoFunctor (Seq a)
instance MonoFunctor (DList a)
instance MonoFunctor (ViewL a)
instance MonoFunctor (ViewR a)
instance MonoFunctor (IntMap a)
instance MonoFunctor (Option a)
instance MonoFunctor (NonEmpty a)
instance MonoFunctor (Identity a)
instance MonoFunctor (r -> a)
instance MonoFunctor (Either a b)
instance MonoFunctor (a, b)
instance MonoFunctor (Const m a)
instance Monad m => MonoFunctor (WrappedMonad m a)
instance MonoFunctor (Map k v)
instance MonoFunctor (HashMap k v)
instance MonoFunctor (Vector a)
instance MonoFunctor (Arg a b)
instance Functor w => MonoFunctor (EnvT e w a)
instance Functor w => MonoFunctor (StoreT s w a)
instance Functor w => MonoFunctor (TracedT m w a)
instance (Functor f, Functor g) => MonoFunctor (Coproduct f g a)
instance Arrow a => MonoFunctor (WrappedArrow a b c)
instance Functor f => MonoFunctor (MaybeApply f a)
instance Functor f => MonoFunctor (WrappedApplicative f a)
instance MonoFunctor (Cokleisli w a b)
instance Functor m => MonoFunctor (MaybeT m a)
instance Functor m => MonoFunctor (ListT m a)
instance Functor m => MonoFunctor (IdentityT m a)
instance Functor m => MonoFunctor (WriterT w m a)
instance Functor m => MonoFunctor (Strict.WriterT w m a)
instance Functor m => MonoFunctor (StateT s m a)
instance Functor m => MonoFunctor (Strict.StateT s m a)
instance Functor m => MonoFunctor (RWST r w s m a)
instance Functor m => MonoFunctor (Strict.RWST r w s m a)
instance Functor m => MonoFunctor (ReaderT r m a)
instance Functor m => MonoFunctor (ErrorT e m a)
instance Functor m => MonoFunctor (ContT r m a)
instance (Functor f, Functor g) => MonoFunctor (Compose f g a)
instance (Functor f, Functor g) => MonoFunctor (Product f g a)
instance Functor f => MonoFunctor (Static f a b)
instance U.Unbox a => MonoFunctor (U.Vector a) where
omap = U.map
{-# INLINE omap #-}
instance VS.Storable a => MonoFunctor (VS.Vector a) where
omap = VS.map
{-# INLINE omap #-}
-- | Monomorphic containers that can be folded.
class MonoFoldable mono where
-- | Map each element of a monomorphic container to a 'Monoid'
-- and combine the results.
ofoldMap :: Monoid m => (Element mono -> m) -> mono -> m
default ofoldMap :: (t a ~ mono, a ~ Element (t a), F.Foldable t, Monoid m) => (Element mono -> m) -> mono -> m
ofoldMap = F.foldMap
{-# INLINE ofoldMap #-}
-- | Right-associative fold of a monomorphic container.
ofoldr :: (Element mono -> b -> b) -> b -> mono -> b
default ofoldr :: (t a ~ mono, a ~ Element (t a), F.Foldable t) => (Element mono -> b -> b) -> b -> mono -> b
ofoldr = F.foldr
{-# INLINE ofoldr #-}
-- | Strict left-associative fold of a monomorphic container.
ofoldl' :: (a -> Element mono -> a) -> a -> mono -> a
default ofoldl' :: (t b ~ mono, b ~ Element (t b), F.Foldable t) => (a -> Element mono -> a) -> a -> mono -> a
ofoldl' = F.foldl'
{-# INLINE ofoldl' #-}
-- | Convert a monomorphic container to a list.
otoList :: mono -> [Element mono]
otoList t = build (\ mono n -> ofoldr mono n t)
{-# INLINE otoList #-}
-- | Are __all__ of the elements in a monomorphic container
-- converted to booleans 'True'?
oall :: (Element mono -> Bool) -> mono -> Bool
oall f = getAll . ofoldMap (All . f)
{-# INLINE oall #-}
-- | Are __any__ of the elements in a monomorphic container
-- converted to booleans 'True'?
oany :: (Element mono -> Bool) -> mono -> Bool
oany f = getAny . ofoldMap (Any . f)
{-# INLINE oany #-}
-- | Is the monomorphic container empty?
onull :: mono -> Bool
onull = oall (const False)
{-# INLINE onull #-}
-- | Length of a monomorphic container, returns a 'Int'.
olength :: mono -> Int
olength = ofoldl' (\i _ -> i + 1) 0
{-# INLINE olength #-}
-- | Length of a monomorphic container, returns a 'Int64'.
olength64 :: mono -> Int64
olength64 = ofoldl' (\i _ -> i + 1) 0
{-# INLINE olength64 #-}
-- | Compare the length of a monomorphic container and a given number.
ocompareLength :: Integral i => mono -> i -> Ordering
-- Basic implementation using length for most instance. See the list
-- instance below for support for infinite structures. Arguably, that
-- should be the default instead of this.
ocompareLength c0 i0 = olength c0 `compare` fromIntegral i0
{-# INLINE ocompareLength #-}
-- | Map each element of a monomorphic container to an action,
-- evaluate these actions from left to right, and ignore the results.
otraverse_ :: (MonoFoldable mono, Applicative f) => (Element mono -> f b) -> mono -> f ()
otraverse_ f = ofoldr ((*>) . f) (pure ())
{-# INLINE otraverse_ #-}
-- | 'ofor_' is 'otraverse_' with its arguments flipped.
ofor_ :: (MonoFoldable mono, Applicative f) => mono -> (Element mono -> f b) -> f ()
ofor_ = flip otraverse_
{-# INLINE ofor_ #-}
-- | Map each element of a monomorphic container to a monadic action,
-- evaluate these actions from left to right, and ignore the results.
omapM_ :: (MonoFoldable mono, Monad m) => (Element mono -> m ()) -> mono -> m ()
omapM_ f = ofoldr ((>>) . f) (return ())
{-# INLINE omapM_ #-}
-- | 'oforM_' is 'omapM_' with its arguments flipped.
oforM_ :: (MonoFoldable mono, Monad m) => mono -> (Element mono -> m ()) -> m ()
oforM_ = flip omapM_
{-# INLINE oforM_ #-}
-- | Monadic fold over the elements of a monomorphic container, associating to the left.
ofoldlM :: (MonoFoldable mono, Monad m) => (a -> Element mono -> m a) -> a -> mono -> m a
ofoldlM f z0 xs = ofoldr f' return xs z0
where f' x k z = f z x >>= k
{-# INLINE ofoldlM #-}
-- | Map each element of a monomorphic container to a semigroup,
-- and combine the results.
--
-- Note: this is a partial function. On an empty 'MonoFoldable', it will
-- throw an exception.
--
-- /See 'Data.MinLen.ofoldMap1' from "Data.MinLen" for a total version of this function./
ofoldMap1Ex :: Semigroup m => (Element mono -> m) -> mono -> m
ofoldMap1Ex f = fromMaybe (Prelude.error "Data.MonoTraversable.ofoldMap1Ex")
. getOption . ofoldMap (Option . Just . f)
-- | Right-associative fold of a monomorphic container with no base element.
--
-- Note: this is a partial function. On an empty 'MonoFoldable', it will
-- throw an exception.
--
-- /See 'Data.MinLen.ofoldr1Ex' from "Data.MinLen" for a total version of this function./
ofoldr1Ex :: (Element mono -> Element mono -> Element mono) -> mono -> Element mono
default ofoldr1Ex :: (t a ~ mono, a ~ Element (t a), F.Foldable t)
=> (a -> a -> a) -> mono -> a
ofoldr1Ex = F.foldr1
{-# INLINE ofoldr1Ex #-}
-- | Strict left-associative fold of a monomorphic container with no base
-- element.
--
-- Note: this is a partial function. On an empty 'MonoFoldable', it will
-- throw an exception.
--
-- /See 'Data.MinLen.ofoldl1Ex'' from "Data.MinLen" for a total version of this function./
ofoldl1Ex' :: (Element mono -> Element mono -> Element mono) -> mono -> Element mono
default ofoldl1Ex' :: (t a ~ mono, a ~ Element (t a), F.Foldable t)
=> (a -> a -> a) -> mono -> a
ofoldl1Ex' = F.foldl1
{-# INLINE ofoldl1Ex' #-}
-- | Get the first element of a monomorphic container.
--
-- Note: this is a partial function. On an empty 'MonoFoldable', it will
-- throw an exception.
--
-- /See 'Data.MinLen.head' from "Data.MinLen" for a total version of this function./
headEx :: mono -> Element mono
headEx = ofoldr const (Prelude.error "Data.MonoTraversable.headEx: empty")
{-# INLINE headEx #-}
-- | Get the last element of a monomorphic container.
--
-- Note: this is a partial function. On an empty 'MonoFoldable', it will
-- throw an exception.
--
-- /See 'Data.MinLen.last from "Data.MinLen" for a total version of this function./
lastEx :: mono -> Element mono
lastEx = ofoldl1Ex' (flip const)
{-# INLINE lastEx #-}
-- | Equivalent to 'headEx'.
unsafeHead :: mono -> Element mono
unsafeHead = headEx
{-# INLINE unsafeHead #-}
-- | Equivalent to 'lastEx'.
unsafeLast :: mono -> Element mono
unsafeLast = lastEx
{-# INLINE unsafeLast #-}
-- | Get the maximum element of a monomorphic container,
-- using a supplied element ordering function.
--
-- Note: this is a partial function. On an empty 'MonoFoldable', it will
-- throw an exception.
--
-- /See 'Data.MinLen.maximiumBy' from "Data.MinLen" for a total version of this function./
maximumByEx :: (Element mono -> Element mono -> Ordering) -> mono -> Element mono
maximumByEx f =
ofoldl1Ex' go
where
go x y =
case f x y of
LT -> y
_ -> x
{-# INLINE maximumByEx #-}
-- | Get the minimum element of a monomorphic container,
-- using a supplied element ordering function.
--
-- Note: this is a partial function. On an empty 'MonoFoldable', it will
-- throw an exception.
--
-- /See 'Data.MinLen.minimumBy' from "Data.MinLen" for a total version of this function./
minimumByEx :: (Element mono -> Element mono -> Ordering) -> mono -> Element mono
minimumByEx f =
ofoldl1Ex' go
where
go x y =
case f x y of
GT -> y
_ -> x
{-# INLINE minimumByEx #-}
instance MonoFoldable S.ByteString where
ofoldMap f = ofoldr (mappend . f) mempty
ofoldr = S.foldr
ofoldl' = S.foldl'
otoList = S.unpack
oall = S.all
oany = S.any
onull = S.null
olength = S.length
omapM_ f (Unsafe.PS fptr offset len) = do
let start = Unsafe.unsafeForeignPtrToPtr fptr `plusPtr` offset
end = start `plusPtr` len
loop ptr
| ptr >= end = Unsafe.inlinePerformIO (touchForeignPtr fptr) `seq` return ()
| otherwise = do
_ <- f (Unsafe.inlinePerformIO (peek ptr))
loop (ptr `plusPtr` 1)
loop start
ofoldr1Ex = S.foldr1
ofoldl1Ex' = S.foldl1'
headEx = S.head
lastEx = S.last
unsafeHead = SU.unsafeHead
{-# INLINE ofoldMap #-}
{-# INLINE ofoldr #-}
{-# INLINE ofoldl' #-}
{-# INLINE otoList #-}
{-# INLINE oall #-}
{-# INLINE oany #-}
{-# INLINE onull #-}
{-# INLINE olength #-}
{-# INLINE omapM_ #-}
{-# INLINE ofoldr1Ex #-}
{-# INLINE ofoldl1Ex' #-}
{-# INLINE headEx #-}
{-# INLINE lastEx #-}
{-# INLINE unsafeHead #-}
instance MonoFoldable L.ByteString where
ofoldMap f = ofoldr (mappend . f) mempty
ofoldr = L.foldr
ofoldl' = L.foldl'
otoList = L.unpack
oall = L.all
oany = L.any
onull = L.null
olength64 = L.length
omapM_ f = omapM_ (omapM_ f) . L.toChunks
ofoldr1Ex = L.foldr1
ofoldl1Ex' = L.foldl1'
headEx = L.head
lastEx = L.last
{-# INLINE ofoldMap #-}
{-# INLINE ofoldr #-}
{-# INLINE ofoldl' #-}
{-# INLINE otoList #-}
{-# INLINE oall #-}
{-# INLINE oany #-}
{-# INLINE onull #-}
{-# INLINE olength64 #-}
{-# INLINE omapM_ #-}
{-# INLINE ofoldr1Ex #-}
{-# INLINE ofoldl1Ex' #-}
{-# INLINE headEx #-}
{-# INLINE lastEx #-}
{-# INLINE unsafeHead #-}
instance MonoFoldable T.Text where
ofoldMap f = ofoldr (mappend . f) mempty
ofoldr = T.foldr
ofoldl' = T.foldl'
otoList = T.unpack
oall = T.all
oany = T.any
onull = T.null
olength = T.length
ofoldr1Ex = T.foldr1
ofoldl1Ex' = T.foldl1'
headEx = T.head
lastEx = T.last
{-# INLINE ofoldMap #-}
{-# INLINE ofoldr #-}
{-# INLINE ofoldl' #-}
{-# INLINE otoList #-}
{-# INLINE oall #-}
{-# INLINE oany #-}
{-# INLINE onull #-}
{-# INLINE olength #-}
{-# INLINE omapM_ #-}
{-# INLINE ofoldr1Ex #-}
{-# INLINE ofoldl1Ex' #-}
{-# INLINE headEx #-}
{-# INLINE lastEx #-}
{-# INLINE unsafeHead #-}
instance MonoFoldable TL.Text where
ofoldMap f = ofoldr (mappend . f) mempty
ofoldr = TL.foldr
ofoldl' = TL.foldl'
otoList = TL.unpack
oall = TL.all
oany = TL.any
onull = TL.null
olength64 = TL.length
ofoldr1Ex = TL.foldr1
ofoldl1Ex' = TL.foldl1'
headEx = TL.head
lastEx = TL.last
{-# INLINE ofoldMap #-}
{-# INLINE ofoldr #-}
{-# INLINE ofoldl' #-}
{-# INLINE otoList #-}
{-# INLINE oall #-}
{-# INLINE oany #-}
{-# INLINE onull #-}
{-# INLINE olength #-}
{-# INLINE omapM_ #-}
{-# INLINE ofoldr1Ex #-}
{-# INLINE ofoldl1Ex' #-}
{-# INLINE headEx #-}
{-# INLINE lastEx #-}
{-# INLINE unsafeHead #-}
instance MonoFoldable IntSet where
ofoldMap f = ofoldr (mappend . f) mempty
ofoldr = IntSet.foldr
ofoldl' = IntSet.foldl'
otoList = IntSet.toList
onull = IntSet.null
olength = IntSet.size
ofoldr1Ex f = ofoldr1Ex f . IntSet.toList
ofoldl1Ex' f = ofoldl1Ex' f . IntSet.toList
{-# INLINE ofoldMap #-}
{-# INLINE ofoldr #-}
{-# INLINE ofoldl' #-}
{-# INLINE otoList #-}
{-# INLINE oall #-}
{-# INLINE oany #-}
{-# INLINE onull #-}
{-# INLINE olength #-}
{-# INLINE omapM_ #-}
{-# INLINE ofoldr1Ex #-}
{-# INLINE ofoldl1Ex' #-}
{-# INLINE headEx #-}
{-# INLINE lastEx #-}
{-# INLINE unsafeHead #-}
instance MonoFoldable [a] where
otoList = id
{-# INLINE otoList #-}
ocompareLength [] i = 0 `compare` i
ocompareLength (_:xs) i
| i Prelude.<= 0 = GT
| otherwise = ocompareLength xs (i - 1)
instance MonoFoldable (Maybe a) where
omapM_ _ Nothing = return ()
omapM_ f (Just x) = f x
{-# INLINE omapM_ #-}
instance MonoFoldable (Tree a)
instance MonoFoldable (Seq a) where
headEx = flip Seq.index 1
lastEx xs = Seq.index xs (Seq.length xs - 1)
{-# INLINE headEx #-}
{-# INLINE lastEx #-}
instance MonoFoldable (ViewL a)
instance MonoFoldable (ViewR a)
instance MonoFoldable (IntMap a)
instance MonoFoldable (Option a)
instance MonoFoldable (NonEmpty a)
instance MonoFoldable (Identity a)
instance MonoFoldable (Map k v)
instance MonoFoldable (HashMap k v)
instance MonoFoldable (Vector a) where
ofoldr = V.foldr
ofoldl' = V.foldl'
otoList = V.toList
oall = V.all
oany = V.any
onull = V.null
olength = V.length
ofoldr1Ex = V.foldr1
ofoldl1Ex' = V.foldl1'
headEx = V.head
lastEx = V.last
unsafeHead = V.unsafeHead
unsafeLast = V.unsafeLast
maximumByEx = V.maximumBy
minimumByEx = V.minimumBy
{-# INLINE ofoldMap #-}
{-# INLINE ofoldr #-}
{-# INLINE ofoldl' #-}
{-# INLINE otoList #-}
{-# INLINE oall #-}
{-# INLINE oany #-}
{-# INLINE onull #-}
{-# INLINE olength #-}
{-# INLINE omapM_ #-}
{-# INLINE ofoldr1Ex #-}
{-# INLINE ofoldl1Ex' #-}
{-# INLINE headEx #-}
{-# INLINE lastEx #-}
{-# INLINE unsafeHead #-}
{-# INLINE maximumByEx #-}
{-# INLINE minimumByEx #-}
instance MonoFoldable (Set e)
instance MonoFoldable (HashSet e)
instance MonoFoldable (DList a) where
otoList = DL.toList
headEx = DL.head
{-# INLINE otoList #-}
{-# INLINE headEx #-}
instance U.Unbox a => MonoFoldable (U.Vector a) where
ofoldMap f = ofoldr (mappend . f) mempty
ofoldr = U.foldr
ofoldl' = U.foldl'
otoList = U.toList
oall = U.all
oany = U.any
onull = U.null
olength = U.length
ofoldr1Ex = U.foldr1
ofoldl1Ex' = U.foldl1'
headEx = U.head
lastEx = U.last
unsafeHead = U.unsafeHead
unsafeLast = U.unsafeLast
maximumByEx = U.maximumBy
minimumByEx = U.minimumBy
{-# INLINE ofoldMap #-}
{-# INLINE ofoldr #-}
{-# INLINE ofoldl' #-}
{-# INLINE otoList #-}
{-# INLINE oall #-}
{-# INLINE oany #-}
{-# INLINE onull #-}
{-# INLINE olength #-}
{-# INLINE omapM_ #-}
{-# INLINE ofoldr1Ex #-}
{-# INLINE ofoldl1Ex' #-}
{-# INLINE headEx #-}
{-# INLINE lastEx #-}
{-# INLINE unsafeHead #-}
{-# INLINE maximumByEx #-}
{-# INLINE minimumByEx #-}
instance VS.Storable a => MonoFoldable (VS.Vector a) where
ofoldMap f = ofoldr (mappend . f) mempty
ofoldr = VS.foldr
ofoldl' = VS.foldl'
otoList = VS.toList
oall = VS.all
oany = VS.any
onull = VS.null
olength = VS.length
ofoldr1Ex = VS.foldr1
ofoldl1Ex' = VS.foldl1'
headEx = VS.head
lastEx = VS.last
unsafeHead = VS.unsafeHead
unsafeLast = VS.unsafeLast
maximumByEx = VS.maximumBy
minimumByEx = VS.minimumBy
{-# INLINE ofoldMap #-}
{-# INLINE ofoldr #-}
{-# INLINE ofoldl' #-}
{-# INLINE otoList #-}
{-# INLINE oall #-}
{-# INLINE oany #-}
{-# INLINE onull #-}
{-# INLINE olength #-}
{-# INLINE omapM_ #-}
{-# INLINE ofoldr1Ex #-}
{-# INLINE ofoldl1Ex' #-}
{-# INLINE headEx #-}
{-# INLINE lastEx #-}
{-# INLINE unsafeHead #-}
{-# INLINE maximumByEx #-}
{-# INLINE minimumByEx #-}
instance MonoFoldable (Either a b) where
ofoldMap f = ofoldr (mappend . f) mempty
ofoldr f b (Right a) = f a b
ofoldr _ b (Left _) = b
ofoldl' f a (Right b) = f a b
ofoldl' _ a (Left _) = a
otoList (Left _) = []
otoList (Right b) = [b]
oall _ (Left _) = True
oall f (Right b) = f b
oany _ (Left _) = False
oany f (Right b) = f b
onull (Left _) = True
onull (Right _) = False
olength (Left _) = 0
olength (Right _) = 1
ofoldr1Ex _ (Left _) = Prelude.error "ofoldr1Ex on Either"
ofoldr1Ex _ (Right x) = x
ofoldl1Ex' _ (Left _) = Prelude.error "ofoldl1Ex' on Either"
ofoldl1Ex' _ (Right x) = x
omapM_ _ (Left _) = return ()
omapM_ f (Right x) = f x
{-# INLINE ofoldMap #-}
{-# INLINE ofoldr #-}
{-# INLINE ofoldl' #-}
{-# INLINE otoList #-}
{-# INLINE oall #-}
{-# INLINE oany #-}
{-# INLINE onull #-}
{-# INLINE olength #-}
{-# INLINE omapM_ #-}
{-# INLINE ofoldr1Ex #-}
{-# INLINE ofoldl1Ex' #-}
{-# INLINE headEx #-}
{-# INLINE lastEx #-}
{-# INLINE unsafeHead #-}
instance MonoFoldable (a, b)
instance MonoFoldable (Const m a)
instance F.Foldable f => MonoFoldable (MaybeT f a)
instance F.Foldable f => MonoFoldable (ListT f a)
instance F.Foldable f => MonoFoldable (IdentityT f a)
instance F.Foldable f => MonoFoldable (WriterT w f a)
instance F.Foldable f => MonoFoldable (Strict.WriterT w f a)
instance F.Foldable f => MonoFoldable (ErrorT e f a)
instance (F.Foldable f, F.Foldable g) => MonoFoldable (Compose f g a)
instance (F.Foldable f, F.Foldable g) => MonoFoldable (Product f g a)
-- | Safe version of 'headEx'.
--
-- Returns 'Nothing' instead of throwing an exception when encountering
-- an empty monomorphic container.
headMay :: MonoFoldable mono => mono -> Maybe (Element mono)
headMay mono
| onull mono = Nothing
| otherwise = Just (headEx mono)
{-# INLINE headMay #-}
-- | Safe version of 'lastEx'.
--
-- Returns 'Nothing' instead of throwing an exception when encountering
-- an empty monomorphic container.
lastMay :: MonoFoldable mono => mono -> Maybe (Element mono)
lastMay mono
| onull mono = Nothing
| otherwise = Just (lastEx mono)
{-# INLINE lastMay #-}
-- | 'osum' computes the sum of the numbers of a monomorphic container.
osum :: (MonoFoldable mono, Num (Element mono)) => mono -> Element mono
osum = ofoldl' (+) 0
{-# INLINE osum #-}
-- | 'oproduct' computes the product of the numbers of a monomorphic container.
oproduct :: (MonoFoldable mono, Num (Element mono)) => mono -> Element mono
oproduct = ofoldl' (*) 1
{-# INLINE oproduct #-}
-- | Are __all__ of the elements 'True'?
--
-- Since 0.6.0
oand :: (Element mono ~ Bool, MonoFoldable mono) => mono -> Bool
oand = oall id
{-# INLINE oand #-}
-- | Are __any__ of the elements 'True'?
--
-- Since 0.6.0
oor :: (Element mono ~ Bool, MonoFoldable mono) => mono -> Bool
oor = oany id
{-# INLINE oor #-}
-- | A typeclass for monomorphic containers that are 'Monoid's.
class (MonoFoldable mono, Monoid mono) => MonoFoldableMonoid mono where -- FIXME is this really just MonoMonad?
-- | Map a function over a monomorphic container and combine the results.
oconcatMap :: (Element mono -> mono) -> mono -> mono
oconcatMap = ofoldMap
{-# INLINE oconcatMap #-}
instance (MonoFoldable (t a), Monoid (t a)) => MonoFoldableMonoid (t a) -- FIXME
instance MonoFoldableMonoid S.ByteString where
oconcatMap = S.concatMap
{-# INLINE oconcatMap #-}
instance MonoFoldableMonoid L.ByteString where
oconcatMap = L.concatMap
{-# INLINE oconcatMap #-}
instance MonoFoldableMonoid T.Text where
oconcatMap = T.concatMap
{-# INLINE oconcatMap #-}
instance MonoFoldableMonoid TL.Text where
oconcatMap = TL.concatMap
{-# INLINE oconcatMap #-}
-- | A typeclass for monomorphic containers whose elements
-- are an instance of 'Eq'.
class (MonoFoldable mono, Eq (Element mono)) => MonoFoldableEq mono where
-- | Checks if the monomorphic container includes the supplied element.
oelem :: Element mono -> mono -> Bool
oelem e = List.elem e . otoList
-- | Checks if the monomorphic container does not include the supplied element.
onotElem :: Element mono -> mono -> Bool
onotElem e = List.notElem e . otoList
{-# INLINE oelem #-}
{-# INLINE onotElem #-}
instance Eq a => MonoFoldableEq (Seq.Seq a)
instance Eq a => MonoFoldableEq (V.Vector a)
instance (Eq a, U.Unbox a) => MonoFoldableEq (U.Vector a)
instance (Eq a, VS.Storable a) => MonoFoldableEq (VS.Vector a)
instance Eq a => MonoFoldableEq (NonEmpty a)
instance MonoFoldableEq T.Text
instance MonoFoldableEq TL.Text
instance MonoFoldableEq IntSet
instance Eq a => MonoFoldableEq (Maybe a)
instance Eq a => MonoFoldableEq (Tree a)
instance Eq a => MonoFoldableEq (ViewL a)
instance Eq a => MonoFoldableEq (ViewR a)
instance Eq a => MonoFoldableEq (IntMap a)
instance Eq a => MonoFoldableEq (Option a)
instance Eq a => MonoFoldableEq (Identity a)
instance Eq v => MonoFoldableEq (Map k v)
instance Eq v => MonoFoldableEq (HashMap k v)
instance Eq a => MonoFoldableEq (HashSet a)
instance Eq a => MonoFoldableEq (DList a)
instance Eq b => MonoFoldableEq (Either a b)
instance Eq b => MonoFoldableEq (a, b)
instance Eq a => MonoFoldableEq (Const m a)
instance (Eq a, F.Foldable f) => MonoFoldableEq (MaybeT f a)
instance (Eq a, F.Foldable f) => MonoFoldableEq (ListT f a)
instance (Eq a, F.Foldable f) => MonoFoldableEq (IdentityT f a)
instance (Eq a, F.Foldable f) => MonoFoldableEq (WriterT w f a)
instance (Eq a, F.Foldable f) => MonoFoldableEq (Strict.WriterT w f a)
instance (Eq a, F.Foldable f) => MonoFoldableEq (ErrorT e f a)
instance (Eq a, F.Foldable f, F.Foldable g) => MonoFoldableEq (Compose f g a)
instance (Eq a, F.Foldable f, F.Foldable g) => MonoFoldableEq (Product f g a)
instance Eq a => MonoFoldableEq [a] where
oelem = List.elem
onotElem = List.notElem
{-# INLINE oelem #-}
{-# INLINE onotElem #-}
instance MonoFoldableEq S.ByteString where
oelem = S.elem
onotElem = S.notElem
{-# INLINE oelem #-}
{-# INLINE onotElem #-}
instance MonoFoldableEq L.ByteString where
oelem = L.elem
onotElem = L.notElem
{-# INLINE oelem #-}
{-# INLINE onotElem #-}
instance (Eq a, Ord a) => MonoFoldableEq (Set a) where
oelem = Set.member
onotElem = Set.notMember
{-# INLINE oelem #-}
{-# INLINE onotElem #-}
-- | A typeclass for monomorphic containers whose elements
-- are an instance of 'Ord'.
class (MonoFoldable mono, Ord (Element mono)) => MonoFoldableOrd mono where
-- | Get the minimum element of a monomorphic container.
--
-- Note: this is a partial function. On an empty 'MonoFoldable', it will
-- throw an exception.
--
-- /See 'Data.MinLen.maximum' from "Data.MinLen" for a total version of this function./
maximumEx :: mono -> Element mono
maximumEx = maximumByEx compare
{-# INLINE maximumEx #-}
-- | Get the maximum element of a monomorphic container.
--
-- Note: this is a partial function. On an empty 'MonoFoldable', it will
-- throw an exception.
--
-- /See 'Data.MinLen.minimum' from "Data.MinLen" for a total version of this function./
minimumEx :: mono -> Element mono
minimumEx = minimumByEx compare
{-# INLINE minimumEx #-}
instance MonoFoldableOrd S.ByteString where
maximumEx = S.maximum
{-# INLINE maximumEx #-}
minimumEx = S.minimum
{-# INLINE minimumEx #-}
instance MonoFoldableOrd L.ByteString where
maximumEx = L.maximum
{-# INLINE maximumEx #-}
minimumEx = L.minimum
{-# INLINE minimumEx #-}
instance MonoFoldableOrd T.Text where
maximumEx = T.maximum
{-# INLINE maximumEx #-}
minimumEx = T.minimum
{-# INLINE minimumEx #-}
instance MonoFoldableOrd TL.Text where
maximumEx = TL.maximum
{-# INLINE maximumEx #-}
minimumEx = TL.minimum
{-# INLINE minimumEx #-}
instance MonoFoldableOrd IntSet
instance Ord a => MonoFoldableOrd [a]
instance Ord a => MonoFoldableOrd (Maybe a)
instance Ord a => MonoFoldableOrd (Tree a)
instance Ord a => MonoFoldableOrd (Seq a)
instance Ord a => MonoFoldableOrd (ViewL a)
instance Ord a => MonoFoldableOrd (ViewR a)
instance Ord a => MonoFoldableOrd (IntMap a)
instance Ord a => MonoFoldableOrd (Option a)
instance Ord a => MonoFoldableOrd (NonEmpty a)
instance Ord a => MonoFoldableOrd (Identity a)
instance Ord v => MonoFoldableOrd (Map k v)
instance Ord v => MonoFoldableOrd (HashMap k v)
instance Ord a => MonoFoldableOrd (Vector a) where
maximumEx = V.maximum
minimumEx = V.minimum
{-# INLINE maximumEx #-}
{-# INLINE minimumEx #-}
instance Ord e => MonoFoldableOrd (Set e)
instance Ord e => MonoFoldableOrd (HashSet e)
instance (U.Unbox a, Ord a) => MonoFoldableOrd (U.Vector a) where
maximumEx = U.maximum
minimumEx = U.minimum
{-# INLINE maximumEx #-}
{-# INLINE minimumEx #-}
instance (Ord a, VS.Storable a) => MonoFoldableOrd (VS.Vector a) where
maximumEx = VS.maximum
minimumEx = VS.minimum
{-# INLINE maximumEx #-}
{-# INLINE minimumEx #-}
instance Ord b => MonoFoldableOrd (Either a b) where
instance Ord a => MonoFoldableOrd (DList a)
instance Ord b => MonoFoldableOrd (a, b)
instance Ord a => MonoFoldableOrd (Const m a)
instance (Ord a, F.Foldable f) => MonoFoldableOrd (MaybeT f a)
instance (Ord a, F.Foldable f) => MonoFoldableOrd (ListT f a)
instance (Ord a, F.Foldable f) => MonoFoldableOrd (IdentityT f a)
instance (Ord a, F.Foldable f) => MonoFoldableOrd (WriterT w f a)
instance (Ord a, F.Foldable f) => MonoFoldableOrd (Strict.WriterT w f a)
instance (Ord a, F.Foldable f) => MonoFoldableOrd (ErrorT e f a)
instance (Ord a, F.Foldable f, F.Foldable g) => MonoFoldableOrd (Compose f g a)
instance (Ord a, F.Foldable f, F.Foldable g) => MonoFoldableOrd (Product f g a)
-- | Safe version of 'maximumEx'.
--
-- Returns 'Nothing' instead of throwing an exception when
-- encountering an empty monomorphic container.
maximumMay :: MonoFoldableOrd mono => mono -> Maybe (Element mono)
maximumMay mono
| onull mono = Nothing
| otherwise = Just (maximumEx mono)
{-# INLINE maximumMay #-}
-- | Safe version of 'maximumByEx'.
--
-- Returns 'Nothing' instead of throwing an exception when
-- encountering an empty monomorphic container.
maximumByMay :: MonoFoldable mono
=> (Element mono -> Element mono -> Ordering)
-> mono
-> Maybe (Element mono)
maximumByMay f mono
| onull mono = Nothing
| otherwise = Just (maximumByEx f mono)
{-# INLINE maximumByMay #-}
-- | Safe version of 'minimumEx'.
--
-- Returns 'Nothing' instead of throwing an exception when
-- encountering an empty monomorphic container.
minimumMay :: MonoFoldableOrd mono => mono -> Maybe (Element mono)
minimumMay mono
| onull mono = Nothing
| otherwise = Just (minimumEx mono)
{-# INLINE minimumMay #-}
-- | Safe version of 'minimumByEx'.
--
-- Returns 'Nothing' instead of throwing an exception when
-- encountering an empty monomorphic container.
minimumByMay :: MonoFoldable mono
=> (Element mono -> Element mono -> Ordering)
-> mono
-> Maybe (Element mono)
minimumByMay f mono
| onull mono = Nothing
| otherwise = Just (minimumByEx f mono)
{-# INLINE minimumByMay #-}
-- | Monomorphic containers that can be traversed from left to right.
class (MonoFunctor mono, MonoFoldable mono) => MonoTraversable mono where
-- | Map each element of a monomorphic container to an action,
-- evaluate these actions from left to right, and
-- collect the results.
otraverse :: Applicative f => (Element mono -> f (Element mono)) -> mono -> f mono
default otraverse :: (Traversable t, mono ~ t a, a ~ Element mono, Applicative f) => (Element mono -> f (Element mono)) -> mono -> f mono
otraverse = traverse
-- | Map each element of a monomorphic container to a monadic action,
-- evaluate these actions from left to right, and
-- collect the results.
omapM :: Monad m => (Element mono -> m (Element mono)) -> mono -> m mono
default omapM :: (Traversable t, mono ~ t a, a ~ Element mono, Monad m) => (Element mono -> m (Element mono)) -> mono -> m mono
omapM = mapM
{-# INLINE otraverse #-}
{-# INLINE omapM #-}
instance MonoTraversable S.ByteString where
otraverse f = fmap S.pack . traverse f . S.unpack
omapM f = liftM S.pack . mapM f . S.unpack
{-# INLINE otraverse #-}
{-# INLINE omapM #-}
instance MonoTraversable L.ByteString where
otraverse f = fmap L.pack . traverse f . L.unpack
omapM f = liftM L.pack . mapM f . L.unpack
{-# INLINE otraverse #-}
{-# INLINE omapM #-}
instance MonoTraversable T.Text where
otraverse f = fmap T.pack . traverse f . T.unpack
omapM f = liftM T.pack . mapM f . T.unpack
{-# INLINE otraverse #-}
{-# INLINE omapM #-}
instance MonoTraversable TL.Text where
otraverse f = fmap TL.pack . traverse f . TL.unpack
omapM f = liftM TL.pack . mapM f . TL.unpack
{-# INLINE otraverse #-}
{-# INLINE omapM #-}
instance MonoTraversable [a]
instance MonoTraversable (Maybe a)
instance MonoTraversable (Tree a)
instance MonoTraversable (Seq a)
instance MonoTraversable (ViewL a)
instance MonoTraversable (ViewR a)
instance MonoTraversable (IntMap a)
instance MonoTraversable (Option a)
instance MonoTraversable (NonEmpty a)
instance MonoTraversable (DList a) where
otraverse f = fmap DL.fromList . traverse f . DL.toList
omapM f = liftM DL.fromList . mapM f . DL.toList
instance MonoTraversable (Identity a)
instance MonoTraversable (Map k v)
instance MonoTraversable (HashMap k v)
instance MonoTraversable (Vector a)
instance U.Unbox a => MonoTraversable (U.Vector a) where
otraverse f = fmap U.fromList . traverse f . U.toList
omapM = U.mapM
{-# INLINE otraverse #-}
{-# INLINE omapM #-}
instance VS.Storable a => MonoTraversable (VS.Vector a) where
otraverse f = fmap VS.fromList . traverse f . VS.toList
omapM = VS.mapM
{-# INLINE otraverse #-}
{-# INLINE omapM #-}
instance MonoTraversable (Either a b) where
otraverse _ (Left a) = pure (Left a)
otraverse f (Right b) = fmap Right (f b)
omapM _ (Left a) = return (Left a)
omapM f (Right b) = liftM Right (f b)
{-# INLINE otraverse #-}
{-# INLINE omapM #-}
instance MonoTraversable (a, b)
instance MonoTraversable (Const m a)
instance Traversable f => MonoTraversable (MaybeT f a)
instance Traversable f => MonoTraversable (ListT f a)
instance Traversable f => MonoTraversable (IdentityT f a)
instance Traversable f => MonoTraversable (WriterT w f a)
instance Traversable f => MonoTraversable (Strict.WriterT w f a)
instance Traversable f => MonoTraversable (ErrorT e f a)
instance (Traversable f, Traversable g) => MonoTraversable (Compose f g a)
instance (Traversable f, Traversable g) => MonoTraversable (Product f g a)
-- | 'ofor' is 'otraverse' with its arguments flipped.
ofor :: (MonoTraversable mono, Applicative f) => mono -> (Element mono -> f (Element mono)) -> f mono
ofor = flip otraverse
{-# INLINE ofor #-}
-- | 'oforM' is 'omapM' with its arguments flipped.
oforM :: (MonoTraversable mono, Monad f) => mono -> (Element mono -> f (Element mono)) -> f mono
oforM = flip omapM
{-# INLINE oforM #-}
-- | A strict left fold, together with an unwrap function.
--
-- This is convenient when the accumulator value is not the same as the final
-- expected type. It is provided mainly for integration with the @foldl@
-- package, to be used in conjunction with @purely@.
--
-- Since 0.3.1
ofoldlUnwrap :: MonoFoldable mono
=> (x -> Element mono -> x) -> x -> (x -> b) -> mono -> b
ofoldlUnwrap f x unwrap mono = unwrap (ofoldl' f x mono)
-- | A monadic strict left fold, together with an unwrap function.
--
-- Similar to 'foldlUnwrap', but allows monadic actions. To be used with
-- @impurely@ from @foldl@.
--
-- Since 0.3.1
ofoldMUnwrap :: (Monad m, MonoFoldable mono)
=> (x -> Element mono -> m x) -> m x -> (x -> m b) -> mono -> m b
ofoldMUnwrap f mx unwrap mono = do
x <- mx
x' <- ofoldlM f x mono
unwrap x'
-- | Typeclass for monomorphic containers that an element can be
-- lifted into.
--
-- For any 'MonoFunctor', the following law holds:
--
-- @
-- 'omap' f . 'opoint' = 'opoint' . f
-- @
class MonoPointed mono where
-- | Lift an element into a monomorphic container.
--
-- 'opoint' is the same as 'Control.Applicative.pure' for an 'Applicative'
opoint :: Element mono -> mono
default opoint :: (Applicative f, (f a) ~ mono, Element (f a) ~ a)
=> Element mono -> mono
opoint = pure
{-# INLINE opoint #-}
-- monomorphic
instance MonoPointed S.ByteString where
opoint = S.singleton
{-# INLINE opoint #-}
instance MonoPointed L.ByteString where
opoint = L.singleton
{-# INLINE opoint #-}
instance MonoPointed T.Text where
opoint = T.singleton
{-# INLINE opoint #-}
instance MonoPointed TL.Text where
opoint = TL.singleton
{-# INLINE opoint #-}
-- Applicative
instance MonoPointed [a]
instance MonoPointed (Maybe a)
instance MonoPointed (Option a)
instance MonoPointed (NonEmpty a)
instance MonoPointed (Identity a)
instance MonoPointed (Vector a)
instance MonoPointed (DList a)
instance MonoPointed (IO a)
instance MonoPointed (ZipList a)
instance MonoPointed (r -> a)
instance Monoid a => MonoPointed (a, b)
instance Monoid m => MonoPointed (Const m a)
instance Monad m => MonoPointed (WrappedMonad m a)
instance Applicative m => MonoPointed (ListT m a)
instance Applicative m => MonoPointed (IdentityT m a)
instance Applicative f => MonoPointed (WrappedApplicative f a)
instance Arrow a => MonoPointed (WrappedArrow a b c)
instance (Monoid w, Applicative m) => MonoPointed (WriterT w m a)
instance (Monoid w, Applicative m) => MonoPointed (Strict.WriterT w m a)
instance Applicative m => MonoPointed (ReaderT r m a)
instance MonoPointed (ContT r m a)
instance (Applicative f, Applicative g) => MonoPointed (Compose f g a)
instance (Applicative f, Applicative g) => MonoPointed (Product f g a)
instance MonoPointed (Cokleisli w a b)
instance Applicative f => MonoPointed (Static f a b)
-- Not Applicative
instance MonoPointed (Seq a) where
opoint = Seq.singleton
{-# INLINE opoint #-}
instance U.Unbox a => MonoPointed (U.Vector a) where
opoint = U.singleton
{-# INLINE opoint #-}
instance VS.Storable a => MonoPointed (VS.Vector a) where
opoint = VS.singleton
{-# INLINE opoint #-}
instance MonoPointed (Either a b) where
opoint = Right
{-# INLINE opoint #-}
instance MonoPointed IntSet.IntSet where
opoint = IntSet.singleton
{-# INLINE opoint #-}
instance MonoPointed (Set a) where
opoint = Set.singleton
{-# INLINE opoint #-}
instance Hashable a => MonoPointed (HashSet a) where
opoint = HashSet.singleton
{-# INLINE opoint #-}
instance Applicative m => MonoPointed (ErrorT e m a) where
opoint = ErrorT . pure . Right
{-# INLINE opoint #-}
instance MonoPointed (MaybeApply f a) where
opoint = MaybeApply . Right
{-# INLINE opoint #-}
instance Applicative f => MonoPointed (MaybeT f a) where
opoint = MaybeT . fmap Just . pure
{-# INLINE opoint #-}
instance (Monoid w, Applicative m) => MonoPointed (RWST r w s m a) where
opoint a = RWST (\_ s -> pure (a, s, mempty))
{-# INLINE opoint #-}
instance (Monoid w, Applicative m) => MonoPointed (Strict.RWST r w s m a) where
opoint a = Strict.RWST (\_ s -> pure (a, s, mempty))
{-# INLINE opoint #-}
instance Applicative m => MonoPointed (StateT s m a) where
opoint a = StateT (\s -> pure (a, s))
{-# INLINE opoint #-}
instance Applicative m => MonoPointed (Strict.StateT s m a) where
opoint a = Strict.StateT (\s -> pure (a, s))
{-# INLINE opoint #-}
instance MonoPointed (ViewL a) where
opoint a = a :< Seq.empty
{-# INLINE opoint #-}
instance MonoPointed (ViewR a) where
opoint a = Seq.empty :> a
{-# INLINE opoint #-}
instance MonoPointed (Tree a) where
opoint a = Node a []
{-# INLINE opoint #-}
-- | Typeclass for monomorphic containers where it is always okay to
-- "extract" a value from with 'oextract', and where you can extrapolate
-- any "extracting" function to be a function on the whole part with
-- 'oextend'.
--
-- 'oextend' and 'oextract' should work together following the laws:
--
-- @
-- 'oextend' 'oextract' = 'id'
-- 'oextract' . 'oextend' f = f
-- 'oextend' f . 'oextend' g = 'oextend' (f . 'oextend' g)
-- @
--
-- As an intuition, @'oextend' f@ uses @f@ to "build up" a new @mono@ with
-- pieces from the old one received by @f@.
--
class MonoFunctor mono => MonoComonad mono where
-- | Extract an element from @mono@. Can be thought of as a dual
-- concept to @opoint@.
oextract :: mono -> Element mono
-- | "Extend" a @mono -> 'Element' mono@ function to be a @mono ->
-- mono@; that is, builds a new @mono@ from the old one by using pieces
-- glimpsed from the given function.
oextend :: (mono -> Element mono) -> mono -> mono
default oextract :: (Comonad w, (w a) ~ mono, Element (w a) ~ a)
=> mono -> Element mono
oextract = extract
{-# INLINE oextract #-}
default oextend :: (Comonad w, (w a) ~ mono, Element (w a) ~ a)
=> (mono -> Element mono) -> mono -> mono
oextend = extend
{-# INLINE oextend #-}
-- Comonad
instance MonoComonad (Tree a)
instance MonoComonad (NonEmpty a)
instance MonoComonad (Identity a)
instance Monoid m => MonoComonad (m -> a)
instance MonoComonad (e, a)
instance MonoComonad (Arg a b)
instance Comonad w => MonoComonad (IdentityT w a)
instance Comonad w => MonoComonad (EnvT e w a)
instance Comonad w => MonoComonad (StoreT s w a)
instance (Comonad w, Monoid m) => MonoComonad (TracedT m w a)
instance (Comonad f, Comonad g) => MonoComonad (Coproduct f g a)
-- Not Comonad
instance MonoComonad (ViewL a) where
oextract ~(x :< _) = x
{-# INLINE oextract #-}
oextend f w@ ~(_ :< xxs) =
f w :< case Seq.viewl xxs of
EmptyL -> Seq.empty
xs -> case oextend f xs of
EmptyL -> Seq.empty
y :< ys -> y Seq.<| ys
instance MonoComonad (ViewR a) where
oextract ~(_ :> x) = x
{-# INLINE oextract #-}
oextend f w@ ~(xxs :> _) =
(case Seq.viewr xxs of
EmptyR -> Seq.empty
xs -> case oextend f xs of
EmptyR -> Seq.empty
ys :> y -> ys Seq.|> y
) :> f w
| pikajude/mono-traversable | src/Data/MonoTraversable.hs | mit | 47,288 | 1 | 19 | 10,976 | 13,053 | 6,897 | 6,156 | 1,023 | 1 |
module PolyInstance2 where
class M a where
mempty :: a
instance M [a] where
mempty = []
| antalsz/hs-to-coq | examples/tests/PolyInstance2.hs | mit | 94 | 0 | 6 | 23 | 36 | 20 | 16 | 5 | 0 |
{-# LANGUAGE OverloadedStrings, DeriveGeneric, DuplicateRecordFields #-}
module GitHub.Api (
Repo (..), ErrorDescription (..), Commit (..), File(..), Person(..), CommitPerson(..), CommitPayload(..),
Auth (..), RepoSource (..), Error (..), CommitsCriteria (..), CommitDetailsCriteria (..),
fetchRepos, fetchCommits, fetchCommitDetails
) where
import GHC.Generics (Generic)
import Control.Arrow (left)
import Control.Monad ((>=>))
import Data.Monoid ((<>))
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import qualified Data.Text.Encoding as E
import qualified Data.Text.Lazy.Encoding as LE
import qualified Data.ByteString.Lazy.Char8 as LS8
import qualified Data.ByteString.Char8 as S8
import qualified Network.HTTP.Simple as HTTP
import qualified Data.Aeson as Aeson
import qualified Data.Time.Clock as Clock
import qualified Data.Time.Format as TimeFormat
import qualified Data.Maybe as Maybe
-- GitHub domain types
newtype ErrorDescription = ErrorDescription {
message :: T.Text
} deriving (Generic, Show)
data Repo = Repo {
id :: Int,
owner :: Person,
name :: T.Text,
full_name :: T.Text
} deriving (Generic, Show)
newtype Person = Person {
login :: T.Text
} deriving (Generic, Show)
data Commit = Commit {
sha :: T.Text,
commit :: CommitPayload,
author :: Maybe Person,
committer :: Maybe Person,
files :: Maybe [File]
} deriving (Generic, Show)
data CommitPayload = CommitPayload {
author :: CommitPerson,
committer :: CommitPerson
} deriving (Generic, Show)
data CommitPerson = CommitPerson {
name :: T.Text,
email :: T.Text,
date :: Clock.UTCTime
} deriving (Generic, Show)
data File = File {
filename :: T.Text,
additions :: Int,
deletions :: Int
} deriving (Generic, Show)
-- API types
newtype Auth = Auth {
token :: T.Text
} deriving (Show)
data Error =
InvalidPayload {payload :: T.Text, parserError :: T.Text} |
GitHubApiError {statusCode :: Int, errorDescription :: ErrorDescription} |
OtherError {reason :: T.Text}
deriving (Show)
data RepoSource = Own | User T.Text | Organization T.Text deriving (Show)
data CommitsCriteria = CommitsCriteria {
repoFullName :: T.Text,
since :: Maybe Clock.UTCTime,
until :: Maybe Clock.UTCTime
} deriving (Show)
data CommitDetailsCriteria = CommitDetailsCriteria {
repoFullName :: T.Text,
commitSha :: T.Text
} deriving (Show)
-- Api
fetchRepos :: Auth -> RepoSource -> IO (Either Error [Repo])
fetchRepos auth source =
fetchResource auth $ reposRequest source
fetchCommits :: Auth -> CommitsCriteria -> IO (Either Error [Commit])
fetchCommits auth criteria =
fetchResource auth $ commitsRequest criteria
fetchCommitDetails :: Auth -> CommitDetailsCriteria -> IO (Either Error Commit)
fetchCommitDetails auth criteria =
fetchResource auth $ commitDetailsRequest criteria
fetchResource :: (Aeson.FromJSON a, Show a) => Auth -> (HTTP.Request -> HTTP.Request) -> IO (Either Error a)
fetchResource auth request =
performRequest $ request $ authenticatedRequest auth githubRequest
performRequest :: (Aeson.FromJSON a, Show a) => HTTP.Request -> IO (Either Error a)
performRequest request = fmap parseResponse (HTTP.httpLBS request)
-- Payloads fetching
reposRequest :: RepoSource -> HTTP.Request -> HTTP.Request
reposRequest source =
HTTP.setRequestPath endpoint . HTTP.setRequestQueryString requestQueryString
where
endpoint = E.encodeUtf8 $ case source of
Own -> "/user/repos"
User name -> "/users/" <> name <> "/repos"
Organization name -> "/orgs/" <> name <> "/repos"
requestQueryString = [
("per_page", Just "100")
]
commitsRequest :: CommitsCriteria -> HTTP.Request -> HTTP.Request
commitsRequest criteria =
HTTP.setRequestPath requestPath . HTTP.setRequestQueryString requestQueryString
where
requestPath = E.encodeUtf8 ("/repos/" <> repoFullName (criteria :: CommitsCriteria) <> "/commits")
requestQueryString = withoutEmpty [
("since", formatTime <$> since criteria),
("until", formatTime <$> GitHub.Api.until criteria),
("per_page", Just "100")
]
withoutEmpty = filter $ Maybe.isJust . snd
commitDetailsRequest :: CommitDetailsCriteria -> HTTP.Request -> HTTP.Request
commitDetailsRequest criteria =
HTTP.setRequestPath . E.encodeUtf8 $
"/repos/" <>
repoFullName (criteria :: CommitDetailsCriteria) <>
"/commits/" <>
commitSha (criteria :: CommitDetailsCriteria)
authenticatedRequest :: Auth -> HTTP.Request -> HTTP.Request
authenticatedRequest auth =
HTTP.addRequestHeader "Authorization" $ E.encodeUtf8 ("token " <> token auth)
githubRequest :: HTTP.Request
githubRequest =
HTTP.setRequestHost "api.github.com" .
HTTP.setRequestMethod "GET" .
HTTP.setRequestHeaders [("User-Agent", "Velociraptor")] .
HTTP.setRequestSecure True .
HTTP.setRequestPort 443 $ HTTP.defaultRequest
formatTime :: Clock.UTCTime -> S8.ByteString
formatTime t =
S8.pack $ TimeFormat.formatTime TimeFormat.defaultTimeLocale format t
where format = "%Y-%m-%dT%H:%M:%SZ"
-- Response parsing
-- TODO: refactor me.
parseResponse :: (Aeson.FromJSON a, Show a) => HTTP.Response LS8.ByteString -> Either Error a
parseResponse response =
let statusCode = HTTP.getResponseStatusCode response
responseBody = HTTP.getResponseBody response
parser 200 = parsePayload
parser code = (parsePayload :: LS8.ByteString -> Either Error ErrorDescription) >=>
(\err -> Left GitHubApiError {statusCode = code, errorDescription = err})
in parser statusCode responseBody
parsePayload :: (Aeson.FromJSON a) => LS8.ByteString -> Either Error a
parsePayload json =
left wrapAesonError (Aeson.eitherDecode json)
where wrapAesonError aesonError = InvalidPayload {
payload = LT.toStrict $ LE.decodeUtf8 json,
parserError = T.pack aesonError}
instance Aeson.FromJSON ErrorDescription
instance Aeson.ToJSON ErrorDescription where
toEncoding = Aeson.genericToEncoding Aeson.defaultOptions
instance Aeson.FromJSON Repo
instance Aeson.ToJSON Repo where
toEncoding = Aeson.genericToEncoding Aeson.defaultOptions
instance Aeson.FromJSON Person
instance Aeson.ToJSON Person where
toEncoding = Aeson.genericToEncoding Aeson.defaultOptions
instance Aeson.FromJSON Commit
instance Aeson.ToJSON Commit where
toEncoding = Aeson.genericToEncoding Aeson.defaultOptions
instance Aeson.FromJSON CommitPayload
instance Aeson.ToJSON CommitPayload where
toEncoding = Aeson.genericToEncoding Aeson.defaultOptions
instance Aeson.FromJSON CommitPerson
instance Aeson.ToJSON CommitPerson where
toEncoding = Aeson.genericToEncoding Aeson.defaultOptions
instance Aeson.FromJSON File
instance Aeson.ToJSON File where
toEncoding = Aeson.genericToEncoding Aeson.defaultOptions
| ysukhoverkhov/velociraptor | src/GitHub/Api.hs | mit | 7,186 | 0 | 14 | 1,496 | 1,920 | 1,066 | 854 | 159 | 3 |
{-# OPTIONS_GHC -Wall #-}
module LogAnalysis where
import Log
-- | @parseMessage s@ parses a string @s@ containing a string form of log
-- message into a LogMessage object
parseMessage :: String -> LogMessage
parseMessage s
| head s == 'I' =
LogMessage Info
(read (getParam 2 ' ' ' ' s))
(getParam 3 ' ' '\n' s)
| head s == 'W' =
LogMessage Warning
(read (getParam 2 ' ' ' ' s))
(getParam 3 ' ' '\n' s)
| head s == 'E' =
LogMessage ( Error (read (getParam 2 ' ' ' ' s)) )
(read (getParam 3 ' ' ' ' s))
(getParam 4 ' ' '\n' s)
| otherwise =
Unknown (getParam 1 ' ' '\n' s)
-- | @getParam n d t s@ get a particular part number @n@ of a string @s@
-- by tokenizing based on delimiter @d@ and terminator @t@
getParam :: Int -> Char -> Char -> String -> String
getParam n d t s
| n <= 1 = takeWhile (/= t) (lstrip d s)
| otherwise = getParam ( n - 1 ) d t ( dropWhile (/= d) (lstrip d s) )
-- | @lstrip d s@ strips off all occurences of character @d@ from the left end
-- of a string @s@
lstrip :: Char -> String -> String
lstrip d s = dropWhile (== d) s
-- | @parse t@ breaks down given text @t@ into lines, prepares a
-- LogMessage for each of the lines, and returns a list of LogMessage
parse :: String -> [LogMessage]
parse t = map (parseMessage) ( lines t )
-- | @insert m t1 t2@ inserts a LogMessage @m@ into a message tree @t1@ to get
-- a new tree @t2@. (@t1@ and @t2@ are binary search trees)
insert :: LogMessage -> MessageTree -> MessageTree
insert (Unknown _) t = t -- prevent inserting an unknown into the tree
insert lm Leaf = Node Leaf lm Leaf
insert x@(LogMessage _ time _) (Node left root@(LogMessage _ rtime _) right)
| time < rtime = Node (insert x left) root right -- insert in left subtree
| time > rtime = Node left root (insert x right) -- insert in right subtree
| otherwise = (Node left x right) -- don't insert
-- root is unknown - invalid scenario - should never occur
-- replace with a proper tree
insert x (Node _ (Unknown _) _) = (Node Leaf x Leaf)
-- | @build lms@ builds a tree from a list of log messages
build :: [LogMessage] -> MessageTree
build lms = foldl (\t x -> insert x t) Leaf lms
-- | @inOrder t@ performs an in-order traversal of a message tree @t@ to get
-- a list of log messages sorter by key (timestamp)
inOrder :: MessageTree -> [LogMessage]
inOrder Leaf = []
inOrder (Node l x r) = (inOrder l) ++ [x] ++ (inOrder r)
-- | @sort@ performs a sorting of a list of log messages
sort :: [LogMessage] -> [LogMessage]
sort = inOrder.build
-- | @whatWentWrong lms@ composes a list of strings from a list of log messages
-- filtered based on a filter criterion
whatWentWrong :: [LogMessage] -> [String]
whatWentWrong lms =
[msg | Just (LogMessage _ _ msg) <- (map filterMessage lms)]
-- | @filterMessage lm@ performs a filter criterion check on a given log
-- message @lm@. Filter criterion: Error messages with severity @s@ > 50
filterMessage :: LogMessage -> Maybe LogMessage
filterMessage lm@(LogMessage (Error s) _ _) =
if s > 50 then (Just lm) else Nothing
filterMessage _ = Nothing
| vaibhav276/haskell_cs194_assignments | algebraic_data_types/LogAnalysis.hs | mit | 3,209 | 0 | 12 | 787 | 873 | 453 | 420 | 49 | 2 |
module Main where
import Network.Wai.Handler.Warp
import Rest.Driver.Wai
import System.Environment
import Constellation.Api
import Constellation.Types
main :: IO ()
main = do
port <- getEnv "CONSTELLATION_PORT"
let env = Environment
app = apiToApplication (runConstellation env) api
run (read port) app
| ClassyCoding/constellation-server | wai/Main.hs | mit | 392 | 0 | 12 | 127 | 96 | 51 | 45 | 12 | 1 |
{-# LANGUAGE ExistentialQuantification #-}
module Gnu.Plot.Types where
import Data.Monoid
import Data.String
import Data.Csv
data Axis = X | Y
deriving (Eq,Enum,Bounded,Read,Ord)
data Location = Point Double Double | Orientation VerticalOrientation HorizontalOrientaion
deriving (Eq,Show,Read)
data VerticalOrientation = Top | VertMid | Bottom
deriving (Eq,Ord,Bounded,Enum,Read)
data HorizontalOrientaion = OLeft | HorzMid | ORight
deriving (Eq,Ord,Bounded,Enum,Read)
instance Show VerticalOrientation where
show Top = "top"
show VertMid = "center"
show Bottom = "bottom"
instance Show HorizontalOrientaion where
show OLeft = "left"
show HorzMid = "center"
show ORight = "right"
instance Monoid VerticalOrientation where
mempty = VertMid
mappend Top Bottom = VertMid
mappend VertMid x = x
mappend x y = y <> x
instance Monoid HorizontalOrientaion where
mempty = HorzMid
mappend OLeft ORight = HorzMid
mappend HorzMid x = x
mappend x y = y <> x
instance Show Axis where
show X = "x"
show Y = "y"
data AxisFunc = Linear | NaturalLog | LogScale Double
deriving (Eq,Show,Read)
newtype PlotConfig = PlotConfig {plotInternal :: String}
deriving (Eq,Show)
instance Monoid PlotConfig where
mempty = PlotConfig mempty
mappend (PlotConfig a) (PlotConfig b) = PlotConfig $ a <> "\n" <> b
newtype DataConfig = DataConfig {dataInternal :: String}
deriving (Eq,Show)
instance Monoid DataConfig where
mempty = DataConfig mempty
mappend (DataConfig a) (DataConfig b) = DataConfig $ a <> " " <> b
data DataTypes = Lines | Points
deriving (Eq,Enum,Bounded)
instance Show DataTypes
where show Lines = "lines"
show Points = "points"
data PlotData = forall a . (Show a, ToRecord a) => PlotData {
internalData :: [a]
, dataConfig :: DataConfig
, dataTypes :: DataTypes
}
instance Show PlotData where
show (PlotData internalData dataConfig dataTypes) = "PlotData { internalData = " <>
show internalData <> ", DataConfig = " <> show dataConfig <> ", DataTypes = " <>
show dataTypes
data Plot = Plot {
plotConfig :: PlotConfig
, toPlot :: [PlotData]
} deriving (Show)
| edwardwas/gnuPlot | src/Gnu/Plot/Types.hs | mit | 2,242 | 0 | 11 | 509 | 706 | 381 | 325 | 63 | 0 |
{-# htermination readLn :: IO () #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_readLn_2.hs | mit | 37 | 0 | 2 | 7 | 3 | 2 | 1 | 1 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeSynonymInstances #-}
module IHaskell.Display.Widgets.Box.PlaceProxy (
-- * The PlaceProxy widget
PlaceProxy,
-- * Constructor
mkPlaceProxy) where
-- To keep `cabal repl` happy when running from the ihaskell repo
import Prelude
import Control.Monad (when, join)
import Data.Aeson
import Data.HashMap.Strict as HM
import Data.IORef (newIORef)
import Data.Text (Text)
import Data.Vinyl (Rec(..), (<+>))
import Data.Vinyl.Lens (rput)
import IHaskell.Display
import IHaskell.Eval.Widgets
import IHaskell.IPython.Message.UUID as U
import IHaskell.Display.Widgets.Types
import IHaskell.Display.Widgets.Common
-- | A 'Box' represents a Box widget from IPython.html.widgets.
type PlaceProxy = IPythonWidget PlaceProxyType
-- | Create a new box
mkPlaceProxy :: IO PlaceProxy
mkPlaceProxy = do
-- Default properties, with a random uuid
uuid <- U.random
let widgetClassState = defaultWidget "PlaceProxyView"
baseState = rput (ModelName =:: "ProxyModel") widgetClassState
proxyState = (Child =:: Nothing) :& (Selector =:: "") :& RNil
widgetState = WidgetState $ baseState <+> proxyState
stateIO <- newIORef widgetState
let widget = IPythonWidget uuid stateIO
-- Open a comm for this widget, and store it in the kernel state
widgetSendOpen widget $ toJSON widgetState
-- Return the widget
return widget
instance IHaskellDisplay PlaceProxy where
display b = do
widgetSendView b
return $ Display []
instance IHaskellWidget PlaceProxy where
getCommUUID = uuid
| beni55/IHaskell | ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Box/PlaceProxy.hs | mit | 1,758 | 0 | 13 | 404 | 332 | 190 | 142 | 38 | 1 |
module Board where
import System.IO (IOMode (..), withFile, hPutStrLn)
import Control.Monad.RWS.Strict (gets, modify, liftIO)
import Data.Array.IArray
import System.Random
import Graphics.UI.SDL
import Types
import Utils
randomBoard :: Int -> Int -> IO Board
randomBoard w h = do
seed <- newStdGen
return $ listArray ((1,1), (w, h)) $ zip (randomRs (1, 6) seed) (repeat True)
drawBoard :: Surface -> Board -> IO ()
drawBoard surface board = do
drawRect surface (Rect (bx1*s - 1) (by1*s - 1) (bx2*s + 2) (by2*s + 2)) 0
mapM_ (\i@(x,y) -> drawRect surface (Rect (x*s) (y*s) s s) (fst $ board ! i)) $ indices board
where s = tileSize
((bx1, by1), (bx2, by2)) = bounds board
changeColor :: Int -> Game ()
changeColor col = do
liftIO $ withFile "log.txt" AppendMode (\h -> hPutStrLn h ("Changed color to: " ++ show col))
board <- gets stateBoard
let newBoard = changeIndexColor board (1, 1) col
modify $ \s -> s {
stateBoard = newBoard // [(i, (col, True)) | i <- indices newBoard, not (snd $ newBoard ! i)]
}
changeIndexColor :: Board -> (Int, Int) -> Int -> Board
changeIndexColor board index col = foldl (\acc i -> changeIndexColor acc i col) newBoard nodes
where newBoard = setColor board index col
nodes = adjacentNodes board index
setColor :: Board -> (Int, Int) -> Int -> Board
setColor board index col = board // [(i, (col, False)) | i <- [index]]
inBounds :: (Int, Int) -> ((Int, Int), (Int, Int)) -> Bool
inBounds (i, j) ((x1, y1), (x2, y2)) =
let inX = (i >= x1 && i <= x2)
inY = (j >= y1 && j <= y2)
in inX && inY
adjacentNodes :: Board -> (Int, Int) -> [(Int, Int)]
adjacentNodes board index@(x, y) = filter (\i -> inBounds i (bounds board) && mutable i && sameCol i) nodes
where nodes = (x - 1, y):(x + 1, y):(x, y - 1):(x, y + 1):[]
mutable ni = snd $ board ! ni
sameCol ni = (fst $ board ! ni) == (fst $ board ! index)
| Chase-C/Flood-Haskell | src/Board.hs | mit | 1,964 | 0 | 17 | 478 | 985 | 537 | 448 | 41 | 1 |
module ProjectEuler.Problem012
( triangleNums
, numFactors
, solve
) where
import Data.Function
import Data.List
import Data.Numbers.Primes
triangleNums :: [Int]
triangleNums = map (\n -> sum [1..n]) [1..]
groupCount :: Eq a => [a] -> [Int]
groupCount = map length . group
-- http://www.wikihow.com/Find-How-Many-Factors-Are-in-a-Number
numFactors :: Int -> Int
numFactors = product . map succ . groupCount . primeFactors
solve :: Int
solve = fst
$ head
$ last
$ groupBy ((==) `on` snd)
$ sortOn snd
$ takeWhile ((< 600) . snd) [(n, numFactors n) | n <- triangleNums]
| hachibu/project-euler | src/ProjectEuler/Problem012.hs | mit | 611 | 0 | 10 | 132 | 217 | 122 | 95 | 20 | 1 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.ApplicationCache (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.ApplicationCache
#else
module Graphics.UI.Gtk.WebKit.DOM.ApplicationCache
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.ApplicationCache
#else
import Graphics.UI.Gtk.WebKit.DOM.ApplicationCache
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/ApplicationCache.hs | mit | 465 | 0 | 5 | 39 | 33 | 26 | 7 | 4 | 0 |
{-# LANGUAGE TupleSections #-}
module Y2018.M12.D03.Solution where
{--
The KAYAK puzzle.
A 30 x 30 grid contains a random dispersion of the letters A, K, and Y.
1. generate this grid; print it
2. Does this grid contain the word 'KAYAK' horizontally, vertically, or
BONUS: diagonally?
3. BONUS: How many occurances of the word 'KAYAK' are in this grid?
Hint: to generate a random number from 1 to 3
>>> randomRIO (1,3)
3
--}
import Control.Arrow (app)
import Data.Array
import Data.List (isInfixOf, stripPrefix)
import System.Random (randomRIO)
type Size = Int
type Grid = Array (Int,Int) Char
aky :: Array Int Char
aky = listArray (1,3) "AKY"
grid :: Size -> IO Grid
grid sz = array ((1,1), (sz,sz)) . concat <$> mapM (flip row sz) [1 .. sz]
{--
>>> grid 3
array ((1,1),(3,3)) [((1,1),'K'),((1,2),'A'),((1,3),'A'),
((2,1),'Y'),((2,2),'K'),((2,3),'K'),
((3,1),'K'),((3,2),'A'),((3,3),'A')]
--}
{-
array ((1,1), (sz,sz)) <$>
\r -> mapM (const (row r sz)) [1 .. sz]
-}
type Row = Int
row :: Row -> Size -> IO [((Int,Int), Char)]
row r sz = mapM (\c -> toAKY >>= return . ((r,c),)) [1 .. sz]
{--
>>> row 2 5
[((2,1),'Y'),((2,2),'K'),((2,3),'K'),((2,4),'K'),((2,5),'A')]
--}
toAKY :: IO Char
toAKY = (aky !) <$> randomRIO (1,3)
{--
>>> toAKY
'A'
>>> toAKY
'K'
>>> toAKY
'Y'
>>> toAKY
'Y'
--}
printGrid :: Grid -> IO ()
printGrid = pg' 1 . assocs
pg' :: Row -> [((Int, Int), Char)] -> IO ()
pg' _ [] = nl
pg' r (((a,b),c):elts) =
(if a > r then nl else noop) >> sp >> putChar c >> pg' a elts
sp :: IO ()
sp = putChar ' '
nl :: IO ()
nl = putStrLn ""
noop :: Applicative f => f ()
noop = pure ()
{--
>>> grid 3 >>= printGrid
Y Y Y
K Y K
A Y A
--}
hasKayakinRowOrColumn :: Grid -> Bool
hasKayakinRowOrColumn grid =
any (isInfixOf "KAYAK") (rows grid ++ cols grid)
rows, cols :: Grid -> [String]
rows = things (thingAsStr fst)
cols = things (thingAsStr snd)
things :: (Row -> Grid -> String) -> Grid -> [String]
things fn g = map app (zip (map fn [1 .. sz g]) (replicate (sz g) g))
sz :: Grid -> Size
sz = snd . snd . bounds
thingAsStr :: ((Int,Int) -> Int) -> Row -> Grid -> String
thingAsStr fn r = map snd . filter ((== r) . fn . fst) . assocs
-- BONUS -------------------------------------------------------
hasKayakinDiagonals :: Grid -> Bool
hasKayakinDiagonals grid =
any (isInfixOf "KAYAK") (lDiags grid ++ rDiags grid)
lDiags, rDiags :: Grid -> [String]
lDiags grid = map (flip lDiagRow grid) [1 .. sz grid]
++ map (flip lDiagCol grid) [2 .. sz grid]
rDiags grid = map (flip rDiagRow grid) [1 .. sz grid]
++ map (flip rDiagCol grid) [2 .. sz grid]
lDiagRow, rDiagRow, lDiagCol, rDiagCol :: Row -> Grid -> String
lDiagRow r grid = diagIt ([r .. sz grid], [1 .. sz grid]) grid
rDiagRow r grid = map (grid !) (zip [r, pred r .. 1] [1 .. sz grid])
lDiagCol c grid = map (grid !) (zip [1 .. sz grid] [c .. sz grid])
rDiagCol c grid = map (grid !) (zip [1 .. sz grid] [c, pred c .. 1])
diagIt :: ([Int], [Int]) -> Grid -> String
diagIt (rs,cs) grid = map (grid !) (zip rs cs)
-- eh, diagIt or spell it out ... which way is better?
kayaksCount :: Grid -> Int
kayaksCount grid =
sum (map countKayak (rows grid ++ cols grid ++ lDiags grid ++ rDiags grid))
countKayak :: String -> Int
countKayak = ck 0
ck :: Int -> String -> Int
ck ans "" = ans
ck acc str = let substr = str `minus` "KAYAK" in
if substr == "" then acc else ck (succ acc) substr
minus :: String -> String -> String
minus "" _ = ""
minus str@(_:t) pref = case stripPrefix pref str of
Nothing -> minus t pref
Just sommat -> sommat
{--
>>> grid 30 >>= \g ->
printGrid g >>
return (hasKayakinRowOrColumn g,
map (map countKayak) [rows g, cols g, lDiags g, rDiags g],
kayaksCount g)
Y A K K A Y A K A A Y K K K Y Y A K Y A K A Y Y K K A K K A
A A K A Y Y Y Y Y A Y A A K A K Y A K K K K A Y Y K Y Y Y A
K Y K K K Y Y A Y A Y A A A A Y K K Y Y A Y K A A A K K Y Y
A A Y Y K A K Y A K A K Y Y A K A A A A K Y A A A Y A K A Y
Y K A K Y A K Y Y Y K Y A A Y A A A A Y K Y Y A Y Y A K A Y
K A Y Y K A K K Y Y A K K K Y K A Y K Y K K Y K K K A K K A
A K A A Y K K K K Y A Y K K A K Y K Y Y K K K Y A Y Y Y K A
A A K Y Y K K Y K Y K Y Y K K K K K A A Y Y A K A A K K A Y
Y A Y A Y K Y A K Y K Y K A Y A K Y K K Y K K K A Y Y A A Y
A Y Y K K K A Y A A A A K A K K K A Y K K A K A K K K A K Y
Y A Y K A K Y A K K K Y K Y Y K Y A Y K K K A A A K A A Y Y
Y K A Y K A K A K K K Y K A A K Y Y Y Y K A Y K K K K A K Y
Y K K Y K Y A Y A K K K K Y A Y K Y Y K Y K A A A A Y Y K K
K Y K Y K A A A A A A A K A Y K K K Y A Y A A Y K Y K K A K
A A A Y Y A A A Y A Y A Y Y Y Y K A K A Y K A A A A K Y Y Y
A A A Y K K K A K Y K A Y K K Y K K Y Y K Y A Y A K A A K K
K Y Y A Y A Y K K K Y K A A K Y K A K K A Y A K A K A K A A
A A A A K K K Y K K Y A K Y Y A A A Y K K A Y A A Y A K K Y
K A A K A K Y Y K A A A K Y A K Y K A Y K K A Y Y A Y K K A
Y Y K Y Y A Y Y K A Y A Y A K Y A K K K A Y K K Y Y K K K K
Y K K K K A A Y K K A K K A Y A A K A A A A K Y K K Y A A K
A Y A K K Y A K Y K Y K K K Y A A A A K A A A K K A Y K K K
K K A K K Y K Y K K A Y A K Y A Y Y A K A A K Y Y K Y K K K
Y K K A A A Y A K A Y A Y Y K Y Y Y A K K Y Y Y A Y A A Y A
Y Y Y K K A A A Y K K Y A K Y A K Y A A A A Y Y K Y K Y Y K
K K A A A Y Y K A Y Y A A K Y Y Y A A A K A K A K Y A K Y Y
Y Y A K A K K Y A K Y Y Y K Y A K K A K K K K Y K K K K A K
K Y A K A Y K A K Y A K A K K A Y Y Y K K Y Y Y A A Y K K Y
K Y K Y K K K Y A Y Y Y A A A Y Y A Y A Y A K A K Y Y Y Y Y
K A A K K K Y K A Y K A K K A K A Y K A K A K K A Y Y Y K K
(True,[[1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0]],
9)
--}
| geophf/1HaskellADay | exercises/HAD/Y2018/M12/D03/Solution.hs | mit | 6,057 | 0 | 12 | 1,841 | 1,381 | 745 | 636 | 70 | 2 |
module Imp.AST (BExpr(..), BBinOp(..), RBinOp(..), AExpr(..), ABinOp(..), Cmd(..)) where
{-
a ::= x | n | - a | a opa a
b ::= true | false | not b | b opb b | a opr a
opa ::= + | -
opb ::= and | or
opr ::= > | < | =
c ::= x := a | skip | c ; c | ( c ) | if b then c else c
| input x from Agent | output x to Agent | x := a ? a
-}
data BExpr = BoolConst Bool
| Not BExpr
| BBinary BBinOp BExpr BExpr
| RBinary RBinOp AExpr AExpr
deriving (Show)
data BBinOp = And | Or deriving (Show)
data RBinOp = Greater | Less | Equal deriving (Show)
data AExpr = Var String
| IntConst Integer
| Neg AExpr
| ABinary ABinOp AExpr AExpr
deriving (Show)
data ABinOp = Add | Subtract deriving (Show)
data Cmd = Seq [Cmd]
| Assign String AExpr
| Random String AExpr AExpr
| If BExpr Cmd Cmd
| Input String String
| Output AExpr String
| Skip
deriving (Show)
| thinkmoore/influence-checker | src/Imp/AST.hs | mit | 1,006 | 2 | 7 | 357 | 242 | 146 | 96 | 22 | 0 |
{- |
module: Main
description: Prime natural numbers - testing
license: MIT
maintainer: Joe Leslie-Hurd <[email protected]>
stability: provisional
portability: portable
-}
module Main
( main )
where
import qualified OpenTheory.Natural.Divides as Divides
import qualified OpenTheory.Natural.Prime as Prime
import qualified OpenTheory.Primitive.Natural as Natural
import qualified OpenTheory.Stream as Stream
import OpenTheory.Primitive.Test
assertion0 :: Bool
assertion0 = not (Stream.nth Prime.primes 0 == 0)
proposition0 :: Natural.Natural -> Natural.Natural -> Bool
proposition0 i j =
(Stream.nth Prime.primes i <= Stream.nth Prime.primes j) == (i <= j)
proposition1 :: Natural.Natural -> Natural.Natural -> Bool
proposition1 i j =
not
(Divides.divides (Stream.nth Prime.primes i)
(Stream.nth Prime.primes (i + (j + 1))))
proposition2 :: Natural.Natural -> Natural.Natural -> Bool
proposition2 n i =
any (\p -> Divides.divides p (n + 2))
(Stream.naturalTake Prime.primes i) ||
Stream.nth Prime.primes i <= n + 2
main :: IO ()
main =
do assert "Assertion 0:\n ~(nth Prime.all 0 = 0)\n " assertion0
check "Proposition 0:\n !i j. nth Prime.all i <= nth Prime.all j <=> i <= j\n " proposition0
check "Proposition 1:\n !i j. ~divides (nth Prime.all i) (nth Prime.all (i + (j + 1)))\n " proposition1
check "Proposition 2:\n !n i.\n any (\\p. divides p (n + 2)) (take Prime.all i) \\/\n nth Prime.all i <= n + 2\n " proposition2
return ()
| gilith/opentheory | data/haskell/opentheory-prime/src/Test.hs | mit | 1,509 | 0 | 13 | 293 | 363 | 192 | 171 | 29 | 1 |
module Parser (
ident,
expr,
def,
context,
lineComment
) where
import Control.Monad (void)
import Control.Applicative hiding ((<|>), many)
import qualified Data.Map.Lazy as Map
import Data.ByteString.Char8 (ByteString, singleton, pack)
import Text.Parsec hiding (token)
import Text.Parsec.ByteString
import Expr
ident :: Parser Ident
ident = ident' <|> ident''
ident' :: Parser Ident
ident' = Ident . singleton <$> lower
ident'' :: Parser Ident
ident'' = Ident . pack <$> many1 (upper <|> digit <|> char '_')
--------------------------------------------------------------------------------
-- | 式
expr :: Parser Expr
expr = apply <|> lambda <|> var
-- | 関数適用
apply :: Parser Expr
apply = do
token $ char '`'
e <- token expr
e' <- token expr
return $ e :$ e'
-- | λ抽象
lambda :: Parser Expr
lambda = do
token $ char '^'
v <- token ident
vs <- many $ token ident
token $ char '.'
e <- token expr
return $ mkLambda (v:vs) e
-- | 変数
var :: Parser Expr
var = Var <$> ident
--------------------------------------------------------------------------------
-- | 関数定義
def :: Parser (Ident, Expr)
def = do
x <- token ident
token $ char '='
e <- token expr
spaces'
skipMany lineComment
void endOfLine <|> eof
return (x, e)
-- | 関数定義の組
context :: Parser Context
context = Map.fromList <$> many1 def
--------------------------------------------------------------------------------
-- | パーサーの前の空白, 空行, 行コメントを読み飛ばすような新しいパーサーを返す
token :: Parser a -> Parser a
token p = spaces >> skipMany (lineComment >> endOfLine) >> spaces >> p
-- | 行コメント
lineComment :: Parser ()
lineComment = char '#' >> skipMany (noneOf "\n\r") >> lookAhead (void endOfLine <|> eof) <?> "line comment"
-- | \t, \r を除く非印字文字
space' :: Parser Char
space' = oneOf " \t\v\f" <?> "space"
-- | 改行を許容しない white space の読み飛ばし
spaces' :: Parser ()
spaces' = skipMany space' <?> "white space"
--------------------------------------------------------------------------------
mkLambda :: [Ident] -> Expr -> Expr
mkLambda vs e = foldr (\v expr -> v :^ expr) e vs
| todays-mitsui/lambda2ski | src/Parser.hs | mit | 2,234 | 0 | 10 | 384 | 649 | 337 | 312 | 58 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.