code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
----------------------------------------------------------------------------
-- |
-- Module : Language.Core.Interpreter.Libraries.GHC.Real
-- Copyright : (c) Carlos López-Camey, University of Freiburg
-- License : BSD-3
--
-- Maintainer : c.lopez@kmels.net
-- Stability : stable
--
--
-- Defines functions defined in GHC.real
-----------------------------------------------------------------------------
module Language.Core.Interpreter.Libraries.GHC.Real(all) where
import DART.CmdLine
import Language.Core.Core
import Language.Core.Interpreter(evalId)
import Language.Core.Interpreter.Apply
import Language.Core.Interpreter.Libraries.Monomophy(monomophy_2,mkMonomophier)
import Language.Core.Interpreter.Structures
import Prelude hiding (all)
all :: [(Id, Either Thunk Value)]
all = [ mod'
, mkMonomophier "base:GHC.Real.$fIntegralInt"
, mkMonomophier "base:GHC.Real.$p1Integral"
, mkMonomophier "base:GHC.Real.$p1Real"
, mkMonomophier "base:GHC.Real.$p2Real"
]
-- | The polymorphic modulo function
-- mod :: Integral a => a -> a -> a
mod' :: (Id, Either Thunk Value)
mod' = (id, Right $ Fun (monomophy_2 "mod" modulo) "polymorphic(mod)")
where
id = "base:GHC.Real.mod"
modulo :: Value -> Value -> IM Value
modulo (Num x) (Num y) = return . Num $ x `mod` y
modulo x y = return . Wrong $ "Cannot calculate modulo between " ++ show x ++ " and " ++ show y
|
kmels/dart-haskell
|
src/Language/Core/Interpreter/Libraries/GHC/Real.hs
|
Haskell
|
bsd-3-clause
| 1,436
|
{-# LANGUAGE GADTs, NoMonoLocalBinds #-}
-- Norman likes local bindings
-- If this module lives on I'd like to get rid of the NoMonoLocalBinds
-- extension in due course
-- Todo: remove -fno-warn-warnings-deprecations
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
module CmmBuildInfoTables
( CAFSet, CAFEnv, cafAnal
, doSRTs, TopSRT, emptySRT, isEmptySRT, srtToData )
where
#include "HsVersions.h"
import Hoopl
import Digraph
import BlockId
import Bitmap
import CLabel
import PprCmmDecl ()
import Cmm
import CmmUtils
import CmmInfo
import Data.List
import DynFlags
import Maybes
import Outputable
import SMRep
import UniqSupply
import Util
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Control.Monad
import qualified Prelude as P
import Prelude hiding (succ)
foldSet :: (a -> b -> b) -> b -> Set a -> b
foldSet = Set.foldr
-----------------------------------------------------------------------
-- SRTs
{- EXAMPLE
f = \x. ... g ...
where
g = \y. ... h ... c1 ...
h = \z. ... c2 ...
c1 & c2 are CAFs
g and h are local functions, but they have no static closures. When
we generate code for f, we start with a CmmGroup of four CmmDecls:
[ f_closure, f_entry, g_entry, h_entry ]
we process each CmmDecl separately in cpsTop, giving us a list of
CmmDecls. e.g. for f_entry, we might end up with
[ f_entry, f1_ret, f2_proc ]
where f1_ret is a return point, and f2_proc is a proc-point. We have
a CAFSet for each of these CmmDecls, let's suppose they are
[ f_entry{g_closure}, f1_ret{g_closure}, f2_proc{} ]
[ g_entry{h_closure, c1_closure} ]
[ h_entry{c2_closure} ]
Now, note that we cannot use g_closure and h_closure in an SRT,
because there are no static closures corresponding to these functions.
So we have to flatten out the structure, replacing g_closure and
h_closure with their contents:
[ f_entry{c2_closure, c1_closure}, f1_ret{c2_closure,c1_closure}, f2_proc{} ]
[ g_entry{c2_closure, c1_closure} ]
[ h_entry{c2_closure} ]
This is what flattenCAFSets is doing.
-}
-----------------------------------------------------------------------
-- Finding the CAFs used by a procedure
type CAFSet = Set CLabel
type CAFEnv = BlockEnv CAFSet
-- First, an analysis to find live CAFs.
cafLattice :: DataflowLattice CAFSet
cafLattice = DataflowLattice "live cafs" Set.empty add
where add _ (OldFact old) (NewFact new) = case old `Set.union` new of
new' -> (changeIf $ Set.size new' > Set.size old, new')
cafTransfers :: BwdTransfer CmmNode CAFSet
cafTransfers = mkBTransfer3 first middle last
where first _ live = live
middle m live = foldExpDeep addCaf m live
last l live = foldExpDeep addCaf l (joinOutFacts cafLattice l live)
addCaf e set = case e of
CmmLit (CmmLabel c) -> add c set
CmmLit (CmmLabelOff c _) -> add c set
CmmLit (CmmLabelDiffOff c1 c2 _) -> add c1 $ add c2 set
_ -> set
add l s = if hasCAF l then Set.insert (toClosureLbl l) s
else s
cafAnal :: CmmGraph -> CAFEnv
cafAnal g = dataflowAnalBwd g [] $ analBwd cafLattice cafTransfers
-----------------------------------------------------------------------
-- Building the SRTs
-- Description of the SRT for a given module.
-- Note that this SRT may grow as we greedily add new CAFs to it.
data TopSRT = TopSRT { lbl :: CLabel
, next_elt :: Int -- the next entry in the table
, rev_elts :: [CLabel]
, elt_map :: Map CLabel Int }
-- map: CLabel -> its last entry in the table
instance Outputable TopSRT where
ppr (TopSRT lbl next elts eltmap) =
text "TopSRT:" <+> ppr lbl
<+> ppr next
<+> ppr elts
<+> ppr eltmap
emptySRT :: MonadUnique m => m TopSRT
emptySRT =
do top_lbl <- getUniqueM >>= \ u -> return $ mkTopSRTLabel u
return TopSRT { lbl = top_lbl, next_elt = 0, rev_elts = [], elt_map = Map.empty }
isEmptySRT :: TopSRT -> Bool
isEmptySRT srt = null (rev_elts srt)
cafMember :: TopSRT -> CLabel -> Bool
cafMember srt lbl = Map.member lbl (elt_map srt)
cafOffset :: TopSRT -> CLabel -> Maybe Int
cafOffset srt lbl = Map.lookup lbl (elt_map srt)
addCAF :: CLabel -> TopSRT -> TopSRT
addCAF caf srt =
srt { next_elt = last + 1
, rev_elts = caf : rev_elts srt
, elt_map = Map.insert caf last (elt_map srt) }
where last = next_elt srt
srtToData :: TopSRT -> CmmGroup
srtToData srt = [CmmData RelocatableReadOnlyData (Statics (lbl srt) tbl)]
where tbl = map (CmmStaticLit . CmmLabel) (reverse (rev_elts srt))
-- Once we have found the CAFs, we need to do two things:
-- 1. Build a table of all the CAFs used in the procedure.
-- 2. Compute the C_SRT describing the subset of CAFs live at each procpoint.
--
-- When building the local view of the SRT, we first make sure that all the CAFs are
-- in the SRT. Then, if the number of CAFs is small enough to fit in a bitmap,
-- we make sure they're all close enough to the bottom of the table that the
-- bitmap will be able to cover all of them.
buildSRT :: DynFlags -> TopSRT -> CAFSet -> UniqSM (TopSRT, Maybe CmmDecl, C_SRT)
buildSRT dflags topSRT cafs =
do let
-- For each label referring to a function f without a static closure,
-- replace it with the CAFs that are reachable from f.
sub_srt topSRT localCafs =
let cafs = Set.elems localCafs
mkSRT topSRT =
do localSRTs <- procpointSRT dflags (lbl topSRT) (elt_map topSRT) cafs
return (topSRT, localSRTs)
in if length cafs > maxBmpSize dflags then
mkSRT (foldl add_if_missing topSRT cafs)
else -- make sure all the cafs are near the bottom of the srt
mkSRT (add_if_too_far topSRT cafs)
add_if_missing srt caf =
if cafMember srt caf then srt else addCAF caf srt
-- If a CAF is more than maxBmpSize entries from the young end of the
-- SRT, then we add it to the SRT again.
-- (Note: Not in the SRT => infinitely far.)
add_if_too_far srt@(TopSRT {elt_map = m}) cafs =
add srt (sortBy farthestFst cafs)
where
farthestFst x y = case (Map.lookup x m, Map.lookup y m) of
(Nothing, Nothing) -> EQ
(Nothing, Just _) -> LT
(Just _, Nothing) -> GT
(Just d, Just d') -> compare d' d
add srt [] = srt
add srt@(TopSRT {next_elt = next}) (caf : rst) =
case cafOffset srt caf of
Just ix -> if next - ix > maxBmpSize dflags then
add (addCAF caf srt) rst
else srt
Nothing -> add (addCAF caf srt) rst
(topSRT, subSRTs) <- sub_srt topSRT cafs
let (sub_tbls, blockSRTs) = subSRTs
return (topSRT, sub_tbls, blockSRTs)
-- Construct an SRT bitmap.
-- Adapted from simpleStg/SRT.lhs, which expects Id's.
procpointSRT :: DynFlags -> CLabel -> Map CLabel Int -> [CLabel] ->
UniqSM (Maybe CmmDecl, C_SRT)
procpointSRT _ _ _ [] =
return (Nothing, NoC_SRT)
procpointSRT dflags top_srt top_table entries =
do (top, srt) <- bitmap `seq` to_SRT dflags top_srt offset len bitmap
return (top, srt)
where
ints = map (expectJust "constructSRT" . flip Map.lookup top_table) entries
sorted_ints = sort ints
offset = head sorted_ints
bitmap_entries = map (subtract offset) sorted_ints
len = P.last bitmap_entries + 1
bitmap = intsToBitmap dflags len bitmap_entries
maxBmpSize :: DynFlags -> Int
maxBmpSize dflags = widthInBits (wordWidth dflags) `div` 2
-- Adapted from codeGen/StgCmmUtils, which converts from SRT to C_SRT.
to_SRT :: DynFlags -> CLabel -> Int -> Int -> Bitmap -> UniqSM (Maybe CmmDecl, C_SRT)
to_SRT dflags top_srt off len bmp
| len > maxBmpSize dflags || bmp == [toStgWord dflags (fromStgHalfWord (srtEscape dflags))]
= do id <- getUniqueM
let srt_desc_lbl = mkLargeSRTLabel id
tbl = CmmData RelocatableReadOnlyData $
Statics srt_desc_lbl $ map CmmStaticLit
( cmmLabelOffW dflags top_srt off
: mkWordCLit dflags (fromIntegral len)
: map (mkStgWordCLit dflags) bmp)
return (Just tbl, C_SRT srt_desc_lbl 0 (srtEscape dflags))
| otherwise
= return (Nothing, C_SRT top_srt off (toStgHalfWord dflags (fromStgWord (head bmp))))
-- The fromIntegral converts to StgHalfWord
-- Gather CAF info for a procedure, but only if the procedure
-- doesn't have a static closure.
-- (If it has a static closure, it will already have an SRT to
-- keep its CAFs live.)
-- Any procedure referring to a non-static CAF c must keep live
-- any CAF that is reachable from c.
localCAFInfo :: CAFEnv -> CmmDecl -> (CAFSet, Maybe CLabel)
localCAFInfo _ (CmmData _ _) = (Set.empty, Nothing)
localCAFInfo cafEnv proc@(CmmProc _ top_l _ (CmmGraph {g_entry=entry})) =
case topInfoTable proc of
Just (CmmInfoTable { cit_rep = rep })
| not (isStaticRep rep) && not (isStackRep rep)
-> (cafs, Just (toClosureLbl top_l))
_other -> (cafs, Nothing)
where
cafs = expectJust "maybeBindCAFs" $ mapLookup entry cafEnv
-- Once we have the local CAF sets for some (possibly) mutually
-- recursive functions, we can create an environment mapping
-- each function to its set of CAFs. Note that a CAF may
-- be a reference to a function. If that function f does not have
-- a static closure, then we need to refer specifically
-- to the set of CAFs used by f. Of course, the set of CAFs
-- used by f must be included in the local CAF sets that are input to
-- this function. To minimize lookup time later, we return
-- the environment with every reference to f replaced by its set of CAFs.
-- To do this replacement efficiently, we gather strongly connected
-- components, then we sort the components in topological order.
mkTopCAFInfo :: [(CAFSet, Maybe CLabel)] -> Map CLabel CAFSet
mkTopCAFInfo localCAFs = foldl addToTop Map.empty g
where
addToTop env (AcyclicSCC (l, cafset)) =
Map.insert l (flatten env cafset) env
addToTop env (CyclicSCC nodes) =
let (lbls, cafsets) = unzip nodes
cafset = foldr Set.delete (foldl Set.union Set.empty cafsets) lbls
in foldl (\env l -> Map.insert l (flatten env cafset) env) env lbls
g = stronglyConnCompFromEdgedVertices
[ ((l,cafs), l, Set.elems cafs) | (cafs, Just l) <- localCAFs ]
flatten :: Map CLabel CAFSet -> CAFSet -> CAFSet
flatten env cafset = foldSet (lookup env) Set.empty cafset
where
lookup env caf cafset' =
case Map.lookup caf env of
Just cafs -> foldSet Set.insert cafset' cafs
Nothing -> Set.insert caf cafset'
bundle :: Map CLabel CAFSet
-> (CAFEnv, CmmDecl)
-> (CAFSet, Maybe CLabel)
-> (BlockEnv CAFSet, CmmDecl)
bundle flatmap (env, decl@(CmmProc infos lbl _ g)) (closure_cafs, mb_lbl)
= ( mapMapWithKey get_cafs (info_tbls infos), decl )
where
entry = g_entry g
entry_cafs
| Just l <- mb_lbl = expectJust "bundle" $ Map.lookup l flatmap
| otherwise = flatten flatmap closure_cafs
get_cafs l _
| l == entry = entry_cafs
| otherwise = if not (mapMember l env)
then pprPanic "bundle" (ppr l <+> ppr lbl <+> ppr (info_tbls infos))
else flatten flatmap $ expectJust "bundle" $ mapLookup l env
bundle _flatmap (_, decl) _
= ( mapEmpty, decl )
flattenCAFSets :: [(CAFEnv, [CmmDecl])] -> [(BlockEnv CAFSet, CmmDecl)]
flattenCAFSets cpsdecls = zipWith (bundle flatmap) zipped localCAFs
where
zipped = [ (env,decl) | (env,decls) <- cpsdecls, decl <- decls ]
localCAFs = unzipWith localCAFInfo zipped
flatmap = mkTopCAFInfo localCAFs -- transitive closure of localCAFs
doSRTs :: DynFlags
-> TopSRT
-> [(CAFEnv, [CmmDecl])]
-> IO (TopSRT, [CmmDecl])
doSRTs dflags topSRT tops
= do
let caf_decls = flattenCAFSets tops
us <- mkSplitUniqSupply 'u'
let (topSRT', gs') = initUs_ us $ foldM setSRT (topSRT, []) caf_decls
return (topSRT', reverse gs' {- Note [reverse gs] -})
where
setSRT (topSRT, rst) (caf_map, decl@(CmmProc{})) = do
(topSRT, srt_tables, srt_env) <- buildSRTs dflags topSRT caf_map
let decl' = updInfoSRTs srt_env decl
return (topSRT, decl': srt_tables ++ rst)
setSRT (topSRT, rst) (_, decl) =
return (topSRT, decl : rst)
buildSRTs :: DynFlags -> TopSRT -> BlockEnv CAFSet
-> UniqSM (TopSRT, [CmmDecl], BlockEnv C_SRT)
buildSRTs dflags top_srt caf_map
= foldM doOne (top_srt, [], mapEmpty) (mapToList caf_map)
where
doOne (top_srt, decls, srt_env) (l, cafs)
= do (top_srt, mb_decl, srt) <- buildSRT dflags top_srt cafs
return ( top_srt, maybeToList mb_decl ++ decls
, mapInsert l srt srt_env )
{-
- In each CmmDecl there is a mapping from BlockId -> CmmInfoTable
- The one corresponding to g_entry is the closure info table, the
rest are continuations.
- Each one needs an SRT.
- We get the CAFSet for each one from the CAFEnv
- flatten gives us
[(BlockEnv CAFSet, CmmDecl)]
-
-}
{- Note [reverse gs]
It is important to keep the code blocks in the same order,
otherwise binary sizes get slightly bigger. I'm not completely
sure why this is, perhaps the assembler generates bigger jump
instructions for forward refs. --SDM
-}
updInfoSRTs :: BlockEnv C_SRT -> CmmDecl -> CmmDecl
updInfoSRTs srt_env (CmmProc top_info top_l live g) =
CmmProc (top_info {info_tbls = mapMapWithKey updInfoTbl (info_tbls top_info)}) top_l live g
where updInfoTbl l info_tbl
= info_tbl { cit_srt = expectJust "updInfo" $ mapLookup l srt_env }
updInfoSRTs _ t = t
|
ekmett/ghc
|
compiler/cmm/CmmBuildInfoTables.hs
|
Haskell
|
bsd-3-clause
| 14,226
|
module PersistentPaint where
import Rumpus
import qualified Data.Sequence as Seq
maxBlots = 1000
-- This paintbrush is persistent, via
-- spawnPersistentEntity and sceneWatcherSaveEntity
start :: Start
start = do
initialPosition <- getPosition
setState (initialPosition, Seq.empty :: Seq EntityID)
myDragContinues ==> \_ -> withState $ \(lastPosition, blots) -> do
newPose <- getPose
let newPosition = newPose ^. translation
when (distance lastPosition newPosition > 0.05) $ do
newBlot <- spawnPersistentEntity $ do
myPose ==> newPose
myShape ==> Cube
mySize ==> 0.1
myBody ==> Animated
myColor ==> colorHSL
(newPosition ^. _x) 0.7 0.8
sceneWatcherSaveEntity newBlot
let (newBlots, oldBlots) = Seq.splitAt maxBlots blots
forM_ oldBlots removeEntity
setState (newPosition, newBlot <| newBlots)
|
lukexi/rumpus
|
pristine/Painting/PersistentPaint.hs
|
Haskell
|
bsd-3-clause
| 1,065
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.TextureCubeMapArray
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.TextureCubeMapArray (
-- * Extension Support
glGetARBTextureCubeMapArray,
gl_ARB_texture_cube_map_array,
-- * Enums
pattern GL_INT_SAMPLER_CUBE_MAP_ARRAY_ARB,
pattern GL_PROXY_TEXTURE_CUBE_MAP_ARRAY_ARB,
pattern GL_SAMPLER_CUBE_MAP_ARRAY_ARB,
pattern GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_ARB,
pattern GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB,
pattern GL_TEXTURE_CUBE_MAP_ARRAY_ARB,
pattern GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_ARB
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/ARB/TextureCubeMapArray.hs
|
Haskell
|
bsd-3-clause
| 970
|
{-|
Module : Grammar.CFG.Random
Description : Functions to randomly expand symbols and words according to a grammar.
Copyright : (c) Davide Mancusi, 2017
License : BSD3
Maintainer : arekfu@gmail.com
Stability : experimental
Portability : POSIX
This module contains the relevant tools to sample random words from a
context-free grammar. All computations take place in the 'MC' monad, which is
simply a practical way to thread the pseudo-random-number generator (PRNG)
state. Be careful: the expansion is currently totally unbiased -- it will
expand a given nonterminal by assuming that all of the production rules have
equal probability. Depending on the grammar, this may lead the size of the
generated word to grow without bound, or to become very large.
-}
module Grammar.CFG.Random
(
-- * Randomly expanding symbols and words
RandomGrammar(..)
, randomSymExpand
, randomWordExpand
, randomGrammarDerive
, randomGrammarDeriveN
, randomGrammarDeriveScan
) where
-- system imports
import Prelude hiding (words)
-- local imports
import Grammar.CFG
import Grammar.MC
import Grammar.Regex.Random (randomExpandRegex)
---------------------------------------------------------
-- functions to randomly derive sequences of symbols --
---------------------------------------------------------
{- | A typeclass for random generation of language strings starting from a
grammar specification, in the form of a type of the 'Grammar.CFG.Grammar'
class.
-}
class (Grammar g, Ord (Repr g)) => RandomGrammar g where
-- | Recursively and randomly expand a word until it consists solely of
-- terminals. WARNING: may produce infinite lists!
randomWordDerive :: g -- ^ the grammar
-> [Repr g] -- ^ the word to expand
-> MC [Repr g] -- ^ a fully expanded sequence of terminals
randomWordDerive grammar word =
do expanded <- randomWordExpand grammar word
if word == expanded
then return expanded
else randomWordDerive grammar expanded
-- | Recursively and randomly expand a word until it consists solely of
-- terminals or until @n@ expansion steps have been performed, whichever
-- comes first.
randomWordDeriveN :: Int -- ^ the maximum number of expansions
-> g -- ^ the grammar
-> [Repr g] -- ^ the starting word
-> MC [Repr g] -- ^ the resulting expansion
randomWordDeriveN 0 _ word = return word
randomWordDeriveN n grammar word = do expanded <- randomWordDerive grammar word
randomWordDeriveN (n-1) grammar expanded
-- | Recursively and randomly expand a word, and return all the
-- intermediate expansion results. WARNING: may produce infinite lists!
randomWordDeriveScan :: g -- ^ the grammar
-> [Repr g] -- ^ the starting word
-> MC [[Repr g]] -- ^ the list of all intermediate expansions
randomWordDeriveScan grammar word =
do expanded <- randomWordExpand grammar word
if word == expanded
then return [expanded]
else fmap (expanded:) (randomWordDeriveScan grammar expanded)
-- | Randomly expand a symbol using one of its production rules.
randomSymExpand :: (Grammar g, Ord (Repr g))
=> g -- ^ the grammar
-> Repr g -- ^ the symbol to expand
-> MC [Repr g] -- ^ the resulting word
randomSymExpand gr sym = case productions gr sym of
Nothing -> return [sym]
Just regex -> randomExpandRegex regex
-- | Expand a word (a sequence of symbols) using randomly selected
-- production rules for each nonterminal.
randomWordExpand :: (Grammar g, Ord (Repr g))
=> g -- ^ the grammar
-> [Repr g] -- ^ the word to expand
-> MC [Repr g] -- ^ the resulting word
randomWordExpand g syms = do words <- mapM (randomSymExpand g) syms
return $ concat words
-- | Recursively and randomly expand the start symbol of a grammar until it
-- consists solely of terminals. WARNING: may produce infinite lists!
randomGrammarDerive :: (RandomGrammar g, Ord (Repr g))
=> g -- ^ the grammar
-> MC [Repr g] -- ^ a fully expanded sequence of terminals
randomGrammarDerive grammar = randomWordDerive grammar [startSymbol grammar]
-- | Recursively and randomly expand the start symbol of a grammar until it
-- consists solely of terminals or until @n@ expansion steps have been
-- performed, whichever comes first.
randomGrammarDeriveN :: (RandomGrammar g, Ord (Repr g))
=> Int -- ^ the maximum number of expansions
-> g -- ^ the grammar
-> MC [Repr g] -- ^ the resulting expansion
randomGrammarDeriveN n grammar = randomWordDeriveN n grammar [startSymbol grammar]
-- | Recursively and randomly expand the start symbol of a grammar, and return
-- all the intermediate expansion results. WARNING: may produce infinite
-- lists!
randomGrammarDeriveScan :: (RandomGrammar g, Ord (Repr g))
=> g -- ^ the grammar
-> MC [[Repr g]] -- ^ the list of all intermediate expansions
randomGrammarDeriveScan grammar = randomWordDeriveScan grammar [startSymbol grammar]
delegateCFGToIntCFG :: (Functor f, Ord b)
=> (forall g. RandomGrammar g => g -> f (Repr g) -> MC (f (Repr g)))
-> CFG b
-> f (Repr (CFG b))
-> MC (f (Repr (CFG b)))
delegateCFGToIntCFG action (CFG _ iGr s2l l2s) word =
let labelWord = ReprInt <$> symbolsToLabels s2l (unReprCFG <$> word)
in do derived <- action iGr labelWord
return (ReprCFG <$> labelsToSymbols l2s (unReprInt <$> derived))
delegateCFGToIntCFG2 :: (Functor f, Ord b)
=> (forall g. RandomGrammar g => g -> f (Repr g) -> MC (f (f (Repr g))))
-> CFG b
-> f (Repr (CFG b))
-> MC (f (f (Repr (CFG b))))
delegateCFGToIntCFG2 action (CFG _ iGr s2l l2s) regex =
let labelRegex = ReprInt <$> symbolsToLabels s2l (unReprCFG <$> regex)
in do derived <- action iGr labelRegex
return (fmap ReprCFG <$> fmap (labelsToSymbols l2s) (fmap unReprInt <$> derived))
instance RandomGrammar IntCFG
instance (Ord a, Show a) => RandomGrammar (CFG a) where
randomWordDerive = delegateCFGToIntCFG randomWordDerive
randomWordDeriveN n = delegateCFGToIntCFG (randomWordDeriveN n)
randomWordDeriveScan = delegateCFGToIntCFG2 randomWordDeriveScan
instance RandomGrammar CharCFG where
randomWordDerive (CharCFG g) word =
map (ReprChar . unReprCFG)
<$> delegateCFGToIntCFG randomWordDerive g (map (ReprCFG . unReprChar) word)
randomWordDeriveN n (CharCFG g) word =
map (ReprChar . unReprCFG)
<$> delegateCFGToIntCFG (randomWordDeriveN n) g (map (ReprCFG . unReprChar) word)
randomWordDeriveScan (CharCFG g) word =
map (map (ReprChar . unReprCFG))
<$> delegateCFGToIntCFG2 randomWordDeriveScan g (map (ReprCFG . unReprChar) word)
instance RandomGrammar StringCFG where
randomWordDerive (StringCFG g) word =
map (ReprString . unReprCFG)
<$> delegateCFGToIntCFG randomWordDerive g (map (ReprCFG . unReprString) word)
randomWordDeriveN n (StringCFG g) word =
map (ReprString . unReprCFG)
<$> delegateCFGToIntCFG (randomWordDeriveN n) g (map (ReprCFG . unReprString) word)
randomWordDeriveScan (StringCFG g) word =
map (map (ReprString . unReprCFG))
<$> delegateCFGToIntCFG2 randomWordDeriveScan g (map (ReprCFG . unReprString) word)
|
arekfu/grammar-haskell
|
src/Grammar/CFG/Random.hs
|
Haskell
|
bsd-3-clause
| 8,040
|
{-# LANGUAGE OverloadedStrings #-}
module Config where
import Control.Lens ((&), (.~), (^.))
import Data.Yaml (ParseException, decodeFileEither)
import Filesystem.Path.CurrentOS (encodeString, fromText, parent, toText,
(</>))
import Turtle.Prelude
import Types
{- Find the root of a project in order to find the config
file, if it exists.
-}
projectRoot :: IO OSFilePath
projectRoot =
findProjectRoot pwd
{-| A React project must have a node_modules directory. |-}
findProjectRoot :: IO OSFilePath -> IO OSFilePath
findProjectRoot dir = do
isRoot <- hasConfigFile =<< dir
isSystemRoot <- dir >>= (\d -> return $ d == fromText "/")
if isSystemRoot
then return $ fromText "."
else if isRoot
then dir
else findProjectRoot $ recurseUp =<< dir
recurseUp :: OSFilePath -> IO OSFilePath
recurseUp dir =
return $ parent dir
hasConfigFile :: OSFilePath -> IO Bool
hasConfigFile dir =
testfile $ dir </> ".generate-component.yaml"
readConfig :: IO Config
readConfig = do
rootDir <- projectRoot
let configPath = rootDir </> ".generate-component.yaml" :: OSFilePath
let configContents = decodeFileEither $ encodeString configPath
configFromEither =<< configContents
configFromEither :: Either ParseException Config -> IO Config
configFromEither c =
case c of
Left _e -> defaultConfig
Right config -> return config
mergeConfig :: Config -> Settings -> Settings
mergeConfig c s =
s & sProjectType .~ (c ^. projectType)
& sComponentDir .~ dir
& sComponentType .~ cType
where
dir = case s ^. sComponentDir of
Nothing -> Just $ fromText $ c ^. defaultDirectory
Just d -> Just d
cType = case s ^. sComponentType of
Nothing -> Just $ c ^. componentType
Just ct -> Just ct
defaultConfig :: IO Config
defaultConfig = do
d <- pwd
let dir = toText d
let buildConfig = Config ReactNative ES6Class
return $ either buildConfig buildConfig dir
|
tpoulsen/generate-component
|
src/Config.hs
|
Haskell
|
bsd-3-clause
| 2,056
|
module Main where
import qualified Data.Map.Strict as M
import Data.Monoid
import Data.List (delete)
import Options.Applicative
import qualified Sound.MIDI.File.Load as L
import qualified Sound.MIDI.File.Save as S
import qualified Sound.MIDI.Message.Channel as CM
import qualified Sound.MIDI.Message.Channel.Voice as VM
import Filter
import Instances
import Arguments
testMap :: ChannelInstrumentMap
testMap = M.fromList [(CM.toChannel 0, VM.toProgram 0)
,(CM.toChannel 1, VM.toProgram 0)]
defaultMap :: VM.Program -> ChannelInstrumentMap
defaultMap p =
M.fromList $ map (\n -> (CM.toChannel n, p)) (delete 9 [0..15])
mapFromArgs :: Args -> ChannelInstrumentMap
mapFromArgs args =
let base = if useSameInstr args
then defaultMap (defaultInstr args)
else M.empty
specified = M.fromList $ instrumentSpecs args
in M.union specified base
main = do
args <- execParser (info parseArgs mempty)
before <- L.fromFile (infile args)
let instrumentMap = mapFromArgs args
after <- return $ modifyFileWithMap instrumentMap before
S.toSeekableFile (outfile args) after
|
jarmar/change-instrument
|
src/Main.hs
|
Haskell
|
bsd-3-clause
| 1,155
|
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveDataTypeable, OverlappingInstances, FlexibleContexts #-}
-- The Timber compiler <timber-lang.org>
--
-- Copyright 2008-2009 Johan Nordlander <nordland@csee.ltu.se>
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the names of the copyright holder and any identified
-- contributors, nor the names of their affiliations, may be used to
-- endorse or promote products derived from this software without
-- specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
-- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
-- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
-- ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
module Common (module Common, module Name, isDigit) where
import PP
import qualified List
import qualified Maybe
import Monad(liftM2)
import Control.Exception
import Char
import Config
import Name
import Data.Typeable
import Data.Binary
import Debug.Trace
fromJust = Maybe.fromJust
isJust = Maybe.isJust
listToMaybe = Maybe.listToMaybe
fst3 (a,b,c) = a
snd3 (a,b,c) = b
thd3 (a,b,c) = c
dom = map fst
rng = map snd
partition p xs = List.partition p xs
nub xs = List.nub xs
xs \\ ys = filter (`notElem` ys) xs
xs `intersect` ys = xs `List.intersect` ys
xs `union` ys = xs `List.union` ys
disjoint xs ys = xs `intersect` ys == []
overlaps xs ys = not (disjoint xs ys)
intersperse x xs = List.intersperse x xs
duplicates xs = filter (`elem` dups) xs1
where xs1 = nub xs
dups = foldl (flip List.delete) xs xs1
rotate n xs = let (xs1,xs2) = splitAt n xs in xs2++xs1
separate [] = ([],[])
separate (Left x : xs) = let (ls,rs) = separate xs in (x:ls,rs)
separate (Right x : xs) = let (ls,rs) = separate xs in (ls,x:rs)
showids vs = concat (intersperse ", " (map show vs))
fmapM f g xs = do ys <- mapM g xs
return (f ys)
mapFst f xs = [ (f a, b) | (a,b) <- xs ]
mapSnd f xs = [ (a, f b) | (a,b) <- xs ]
zipFilter (f:fs) (x:xs)
| f = x : zipFilter fs xs
| otherwise = zipFilter fs xs
zipFilter _ _ = []
zip4 = List.zip4
noDups mess vs
| not (null dups) = errorIds mess dups
| otherwise = vs
where dups = duplicates vs
uncurry3 f (x,y,z) = f x y z
-- String manipulation -----------------------------------------------------
rmSuffix :: String -> String -> String
rmSuffix suf = reverse . rmPrefix (reverse suf) . reverse
rmPrefix :: String -> String -> String
rmPrefix pre str
| pre `List.isPrefixOf` str = drop (length pre) str
| otherwise = internalError0 $ "rmPrefix: " ++ str ++ " is not a prefix of " ++ show pre
rmDirs :: String -> String
rmDirs = reverse . fst . span (/='/') . reverse
dropPrefix [] s = (True, s)
dropPrefix (x:xs) (y:ys)
| x == y = dropPrefix xs ys
dropPrefix xs ys = (False, ys)
dropDigits xs = drop 0 xs
where drop n (x:xs)
| isDigit x = drop (10*n + ord x - ord '0') xs
drop n xs = (n, xs)
-- Error reporting ---------------------------------------------------------
errorIds mess ns = compileError (unlines ((mess++":") : map pos ns))
where pos n = case loc n of
Just (r,c) -> rJust 15 (show n) ++ " at line " ++ show r ++ ", column " ++ show c
Nothing -> rJust 15 (show n) ++ modInfo n
loc n = location (annot n)
rJust w str = replicate (w-length str) ' ' ++ str
modInfo (Name _ _ (Just m) a) = " defined in " ++ m
modInfo _ = " (unknown position)"
errorTree mess t = compileError (errorMsg mess t)
compileError mess = throw (CompileError mess)
errorMsg mess t = mess ++ pos ++ (if length (lines str) > 1 then "\n"++str++"\n" else str)
where str = render (pr t)
pos = " ("++ show (posInfo t) ++"): "
internalError mess t = internalError0 (errorMsg mess t)
internalError0 mess = throw (Panic mess)
-- PosInfo ---------------------------------------------------------
data PosInfo = Between {start :: (Int,Int), end :: (Int,Int)}
| Unknown
instance Show PosInfo where
show (Between (l1,c1) (l2,c2))
= case l1==l2 of
True -> case c1 == c2 of
True -> "close to line "++show l1++", column "++show c1
False -> "close to line "++show l1++", columns "++show c1++" -- "++show c2
False -> "close to lines "++show l1++" -- "++show l2
show Unknown = "at unknown position"
between (Between s1 e1) (Between s2 e2)
= Between (min s1 s2) (max e1 e2)
between b@(Between _ _) Unknown = b
between Unknown b@(Between _ _) = b
between Unknown Unknown = Unknown
startPos (Between s _) = Just s
startPos Unknown = Nothing
class HasPos a where
posInfo :: a -> PosInfo
instance HasPos a => HasPos [a] where
posInfo xs = foldr between Unknown (map posInfo xs)
instance (HasPos a, HasPos b) => HasPos (a,b) where
posInfo (a,b) = between (posInfo a) (posInfo b)
instance HasPos a => HasPos (Maybe a) where
posInfo Nothing = Unknown
posInfo (Just a) = posInfo a
instance HasPos Bool where
posInfo _ = Unknown
instance HasPos Name where
posInfo n = case location (annot n) of
Just (l,c)
|l==0 && c==0 -> Unknown -- artificially introduced name
|otherwise -> Between (l,c) (l,c+len n-1)
Nothing -> Unknown
where len(Name s _ _ _) = length s
len(Prim p _) = length (strRep p)
len(Tuple n _) = n+2
-- Literals ----------------------------------------------------------------
data Lit = LInt (Maybe (Int,Int)) Integer
| LRat (Maybe (Int,Int)) Rational
| LChr (Maybe (Int,Int)) Char
| LStr (Maybe (Int,Int)) String
-- deriving (Eq)
instance Eq Lit where
LInt _ m == LInt _ n = m == n
LRat _ m == LRat _ n = m == n
LChr _ m == LChr _ n = m == n
LStr _ m == LStr _ n = m == n
_ == _ = False
instance Show Lit where
show (LInt _ i) = "LInt " ++ show i
show (LRat _ r) = "LRat " ++ show r
show (LChr _ c) = "LChr " ++ show c
show (LStr _ s) = "LStr " ++ show s
instance Pr Lit where
prn _ (LInt _ i) = integer i
prn 0 (LRat _ r) = rational r
prn _ (LRat _ r) = parens (rational r)
prn _ (LChr _ c) = litChar c
prn _ (LStr _ s) = litString s
instance HasPos Lit where
posInfo (LInt (Just (l,c)) i) = Between (l,c) (l,c+length(show i)-1)
posInfo (LRat (Just (l,c)) r) = Between (l,c) (l,c) -- check length of rationals)
posInfo (LChr (Just (l,c)) _) = Between (l,c) (l,c)
posInfo (LStr (Just (l,c)) cs) = Between (l,c) (l,c+length cs+1)
posInfo _ = Unknown
lInt n = LInt Nothing (toInteger n)
lRat r = LRat Nothing r
lChr c = LChr Nothing c
lStr s = LStr Nothing s
-- Underlying monad ----------------------------------------------------------------------
newtype M s a = M ((Int,[s]) -> Either String ((Int,[s]), a))
instance Functor (M s) where
fmap f x = x >>= (return . f)
instance Monad (M s) where
M m >>= f = M $ \k ->
case m k of
Right (k',a) -> m' k' where M m' = f a
Left s -> Left s
return a = M $ \k -> Right (k,a)
fail s = M $ \k -> Left s
handle (M m) f = M $ \k ->
case m k of
Right r -> Right r
Left s -> m' k where M m' = f s
expose (M m) = M $ \k ->
case m k of
Right (k',a) -> Right (k',Right a)
Left s -> Right (k, Left s)
unexpose (Right a) = return a
unexpose (Left b) = fail b
runM (M m) = case m (1,[]) of
Right (_,x) -> x
Left s -> compileError s
newNum = M $ \(n,s) -> Right ((n+1,s), n)
currentNum = M $ \(n,s) -> Right ((n,s), n)
addToStore x = M $ \(n,s) -> Right ((n,x:s), ())
currentStore = M $ \(n,s) -> Right ((n,s), s)
localStore (M m) = M $ \(n0,s0) ->
case m (n0,[]) of
Right ((n,s), x) -> Right ((n,s0), x)
Left s -> Left s
newNameMod m s = do n <- newNum
return (Name s n m ann)
where ann = if s `elem` explicitSyms then suppAnnot { explicit = True } else suppAnnot
suppAnnot = genAnnot { suppress = True }
newNameModPub m pub s = do n <- newNameMod m s
return (n {annot = (annot n) {public = pub}})
newName s = newNameMod Nothing s
newNames s n = mapM (const (newName s)) [1..n]
newNamesPos s ps = mapM (newNamePos s) ps
newNamePos s p = do n <- newName s
return (n {annot = (annot n) {location = startPos(posInfo p)}})
renaming vs = mapM f vs
where f v | tag v == 0 = do n <- newNum
return (v, v { tag = n })
| otherwise = return (v, v)
-- Merging renamings ------------------------------------------------------
-- Here we cannot use equality of names (Eq instance), since two unqualified
-- imported names with the same string will have non-zero tags and hence not be compared
-- for str equality.
-- remove pairs from rn2 that are shadowed by rn1; return also shadowed names
deleteRenamings [] rn2 = (rn2,[])
deleteRenamings ((n,_):rn1) rn2
| not (isQualified n) = (rn',if b then n:ns else ns)
| otherwise = (rn,ns)
where (rn,ns) = deleteRenamings rn1 rn2
(b,rn') = deleteName n rn
deleteName _ [] = (False,[])
deleteName n ((Name s t Nothing a,_):rn)
| str n == s = (True,rn)
deleteName n (p:rn) = let (b,rn') = deleteName n rn
in (b,p:rn')
-- for merging renaming for locally bound names with ditto for imported names;
-- removes unqualified form of imported name
mergeRenamings1 rn1 rn2 = rn1 ++ rn2'
where (rn2',_) = deleteRenamings rn1 rn2
-- for merging renamings from two imported modules;
-- removes both occurrences when two unqualified names clash
mergeRenamings2 rn1 rn2 = rn1' ++ rn2'
where (rn2',ns) = deleteRenamings rn1 rn2
rn1' = deleteNames ns rn1
ns' = filter (not . isGenerated) ns
deleteNames [] rn = rn
deleteNames (n:ns) rn = deleteNames ns (snd (deleteName n rn))
-- Assertions -----------------------------------------------------------------------
assert e msg ns
| e = return ()
| otherwise = errorIds msg ns
assert1 e msg ts
| e = return ()
| otherwise = errorTree msg ts
-- Poor man's exception datatype ------------------------------------------------------
encodeError msg ids = msg ++ ": " ++ concat (intersperse " " (map packName ids))
decodeError str
| msg `elem` encodedMsgs = Just (msg, map unpackName (words rest))
| otherwise = Nothing
where (msg,_:rest) = span (/=':') str
encodedMsgs = [circularSubMsg, ambigInstMsg, ambigSubMsg]
circularSubMsg = "Circular subtyping"
ambigInstMsg = "Ambiguous instances"
ambigSubMsg = "Ambiguous subtyping"
assert0 e msg
| e = return ()
| otherwise = fail msg
-- Tracing -----------------------------------------------------------------------------
tr m = trace (m++"\n") (return ())
tr' m e = trace ("\n"++m++"\n") e
trNum str = do n <- currentNum
tr ("At "++show n++": "++str)
-- Free variables -----------------------------------------------------------------------
class Ids a where
idents :: a -> [Name]
instance Ids a => Ids [a] where
idents xs = concatMap idents xs
instance Ids a => Ids (Name,a) where
idents (v,a) = idents a
tycons x = filter isCon (idents x)
tyvars x = filter isVar (idents x)
evars x = filter isVar (idents x)
svars x = filter isState (idents x)
vclose vss vs
| null vss2 = nub vs
| otherwise = vclose vss1 (concat vss2 ++ vs)
where (vss1,vss2) = partition (null . intersect vs) vss
-- Bound variables -----------------------------------------------------------------------
class BVars a where
bvars :: a -> [Name]
bvars _ = []
-- Mappings -----------------------------------------------------------------------------
infixr 4 @@
type Map a b = [(a,b)]
lookup' assoc x = case lookup x assoc of
Just e -> e
Nothing -> internalError "lookup': did not find" x
lookup'' s assoc x = case lookup x assoc of
Just e -> e
Nothing -> internalError ("lookup' (" ++ s ++ "): did not find") x
inv assoc = map (\(a,b) -> (b,a)) assoc
delete k [] = []
delete k (x:xs)
| fst x == k = xs
| otherwise = x : delete k xs
delete' ks xs = foldr delete xs ks
insert k x [] = [(k,x)]
insert k x ((k',x'):assoc)
| k == k' = (k,x) : assoc
| otherwise = (k',x') : insert k x assoc
update k f [] = internalError0 "Internal: Common.update"
update k f ((k',x):assoc)
| k == k' = (k, f x) : assoc
| otherwise = (k',x) : update k f assoc
search p [] = Nothing
search p (a:assoc)
| p a = Just a
| otherwise = search p assoc
insertBefore kx ks [] = [kx]
insertBefore kx ks ((k,x'):assoc)
| k `elem` ks = kx:(k,x'):assoc
| otherwise = (k,x') : insertBefore kx ks assoc
(@@) :: Subst b a b => Map a b -> Map a b -> Map a b
s1 @@ s2 = [(u,subst s1 t) | (u,t) <- s2] ++ s1
merge :: (Eq a, Eq b) => Map a b -> Map a b -> Maybe (Map a b)
merge [] s' = Just s'
merge ((v,t):s) s' = case lookup v s' of
Nothing -> merge s ((v,t):s')
Just t' | t==t' -> merge s s'
_ -> Nothing
nullSubst = []
a +-> b = [(a,b)]
restrict s vs = filter ((`elem` vs) . fst) s
prune s vs = filter ((`notElem` vs) . fst) s
class Subst a i e where
subst :: Map i e -> a -> a
substVars s xs = map (substVar s) xs
substVar s x = case lookup x s of
Just x' -> x'
Nothing -> x
instance Subst Name Name Name where
subst s x = case lookup x s of
Just x' -> x'
_ -> x
instance Subst a i e => Subst [a] i e where
subst [] xs = xs
subst s xs = map (subst s) xs
instance Subst a Name Name => Subst (Name,a) Name Name where
subst s (v,a) = (subst s v, subst s a)
instance Subst a i e => Subst (Name,a) i e where
subst s (v,a) = (v, subst s a)
instance Subst a i e => Subst (Maybe a) i e where
subst s Nothing = Nothing
subst s (Just a) = Just (subst s a)
newEnv x ts = do vs <- mapM (const (newName x)) ts
return (vs `zip` ts)
newEnvPos x ts e = do vs <- mapM (const (newNamePos x e)) ts
return (vs `zip` ts)
-- Kinds ---------------------------------------------------------------------------------
data Kind = Star
| KFun Kind Kind
| KWild
| KVar Int
deriving (Eq,Show)
type KEnv = Map Name Kind
instance HasPos Kind where
posInfo _ = Unknown
newKVar = do n <- newNum
return (KVar n)
kvars Star = []
kvars (KVar n) = [n]
kvars (KFun k1 k2) = kvars k1 ++ kvars k2
kArgs (KFun k k') = k : kArgs k'
kArgs k = []
kFlat k = (kArgs k, kRes k)
kRes (KFun k k') = kRes k'
kRes k = k
instance Subst Kind Int Kind where
subst s Star = Star
subst s k@(KVar n) = case lookup n s of
Just k' -> k'
Nothing -> k
subst s (KFun k1 k2) = KFun (subst s k1) (subst s k2)
instance Subst (Kind,Kind) Int Kind where
subst s (a,b) = (subst s a, subst s b)
instance Pr (Name,Kind) where
pr (n,k) = prId n <+> text "::" <+> pr k
instance Pr Kind where
prn 0 (KFun k1 k2) = prn 1 k1 <+> text "->" <+> prn 0 k2
prn 0 k = prn 1 k
prn 1 Star = text "*"
prn 1 (KVar n) = text ('_':show n)
prn 1 KWild = text "_"
prn 1 k = parens (prn 0 k)
-- Defaults ------------------------------------------
data Default a = Default Bool Name Name -- First arg is True if declaration is in public part
| Derive Name a
deriving (Eq, Show)
instance Pr a => Pr(Default a) where
pr (Default _ a b) = pr a <+> text "<" <+> pr b
pr (Derive v t) = pr v <+> text "::" <+> pr t
instance HasPos a => HasPos (Default a) where
posInfo (Default _ a b) = between (posInfo a) (posInfo b)
posInfo (Derive v t) = between (posInfo v) (posInfo t)
-- Externals -----------------------------------------
data Extern a = Extern Name a
deriving (Eq, Show)
instance Pr a => Pr (Extern a) where
pr (Extern n t) = prId n <+> text "::" <+> pr t
instance BVars [Extern a] where
bvars (Extern n _ : es) = n : bvars es
bvars [] = []
instance Binary a => Binary (Extern a) where
put (Extern a b) = put a >> put b
get = get >>= \a -> get >>= \b -> return (Extern a b)
extsMap es = map (\(Extern v t) -> (v,t)) es
-- Pattern matching ---------------------------------------------------------------
-- The M prefix allows coexistence with older PMC primites
data Match p e bs r = MCommit r
| MFail
| MFatbar (Match p e bs r) (Match p e bs r)
| Case e [(p,Match p e bs r)]
| Let bs (Match p e bs r)
deriving (Eq,Show)
alt p rhs = (p,rhs)
foldMatch commit fail fatbar mcase mlet = f
where f m = case m of
MCommit r -> commit r
MFail -> fail
MFatbar m1 m2 -> fatbar (f m1) (f m2)
Case e alts -> mcase e (mapSnd f alts)
Let bs m -> mlet bs (f m)
mapMatch pf ef bsf rf = foldMatch commit fail fatbar mcase mlet
where
commit r = MCommit (rf r)
fail = MFail
fatbar = MFatbar
mcase e alts = Case (ef e) (mapFst pf alts)
mlet bs e = Let (bsf bs) e
mapMMatch pf ef bsf rf = foldMatch commit fail fatbar mcase mlet
where
commit r = MCommit `fmap` rf r
fail = return MFail
fatbar = liftM2 MFatbar
mcase e alts = liftM2 Case (ef e) (sequence [liftM2 (,) (pf p) m|(p,m)<-alts])
mlet bs e = liftM2 Let (bsf bs) e
instance (Ids p,Ids e, Ids bs,Ids r,BVars bs) => Ids (Match p e bs r) where
idents m =
case m of
MCommit r -> idents r
MFail -> []
MFatbar m1 m2 -> idents m1 ++ idents m2
Case e alts -> idents e ++ concat [idents m\\idents p|(p,m)<-alts]
Let bs m -> idents bs ++ (idents m \\ bvars bs)
instance (Subst e n e,Subst bs n e,Subst r n e) => Subst (Match p e bs r) n e where
subst s = mapMatch id (subst s) (subst s) (subst s)
instance (Pr p, Pr e,Pr bs,Pr r) => Pr (Match p e bs r) where
prn 0 (MFatbar m1 m2) = text "Fatbar" <+> prn 12 m1 <+> prn 12 m2
prn 0 (Case e alts) = text "case" <+> pr e <+> text "of" $$
nest 2 (vcat (map pralt alts))
where pralt (p,m) = pr p <+> text "->" <+> pr m
prn 0 (Let bs m) = text "let" <+> pr bs $$ text "in" <+> pr m
prn 0 m = prn 11 m
prn 11 (MCommit r) = text "Commit" <+> prn 12 r
prn 11 m = prn 12 m
prn 12 m = prn 13 m
prn 13 MFail = text "Fail"
prn 13 m = parens (prn 0 m)
prn n e = prn 11 e
instance (HasPos p, HasPos e,HasPos bs,HasPos r) => HasPos (Match p e bs r) where
posInfo m =
case m of
MCommit r -> posInfo r
MFail -> Unknown
MFatbar m1 m2 -> posInfo (m1,m2)
Case e alts -> posInfo (e,alts)
Let bs m -> posInfo (bs,m)
-- Binary --------------------------------------------
instance Binary Lit where
put (LInt _ a) = putWord8 0 >> put a
put (LRat _ a) = putWord8 1 >> put a
put (LChr _ a) = putWord8 2 >> put a
put (LStr _ a) = putWord8 3 >> put a
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> return (lInt (a::Integer))
1 -> get >>= \a -> return (lRat a)
2 -> get >>= \a -> return (lChr a)
3 -> get >>= \a -> return (lStr a)
_ -> fail "no parse"
instance Binary Kind where
put Star = putWord8 0
put (KFun a b) = putWord8 1 >> put a >> put b
put KWild = putWord8 2
put (KVar a) = putWord8 3 >> put a
get = do
tag_ <- getWord8
case tag_ of
0 -> return Star
1 -> get >>= \a -> get >>= \b -> return (KFun a b)
2 -> return KWild
3 -> get >>= \a -> return (KVar a)
_ -> fail "no parse"
instance Binary a => Binary (Default a) where
put (Default a b c) = putWord8 0 >> put a >> put b >> put c
put (Derive a b) = putWord8 1 >> put a >> put b
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> get >>= \b -> get >>= \c -> return (Default a b c)
1 -> get >>= \a -> get >>= \b -> return (Derive a b)
|
mattias-lundell/timber-llvm
|
src/Common.hs
|
Haskell
|
bsd-3-clause
| 26,557
|
import qualified Data.ByteString.Lazy as BL
import Lib
main :: IO ()
main = do
putStrLn "read - this would fail with the output of relink1, but should work with the transformed pointers"
serialized <- BL.readFile "serialized_transformed"
print serialized
unserialized <- unwrapFromBinary serialized
putStrLn $ unserialized "qwe"
|
michaxm/packman-exploration
|
app/NoTopLevelFunctions2.hs
|
Haskell
|
bsd-3-clause
| 341
|
{-# LANGUAGE JavaScriptFFI #-}
module Famous.Components.Origin where
import GHCJS.Types
import GHCJS.Foreign
import Famous.Core.Node
import Famous.Components.Position
data Origin_ a
type Origin a = Position (Origin_ a)
-- | Add a new Origin component to a node
foreign import javascript unsafe "new window.famous.components.Origin($1)"
fms_addOrigin :: Node a -> IO (Origin ())
addOrigin = fms_addOrigin
|
manyoo/ghcjs-famous
|
src/Famous/Components/Origin.hs
|
Haskell
|
bsd-3-clause
| 412
|
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Parts (
Version(..), Parsable(..), Random(..), CipherSuite(..),
HashAlgorithm(..), SignatureAlgorithm(..),
parseSignatureAlgorithm,
-- list1,
whole, ByteStringM, runByteStringM, evalByteStringM, headBS,
lenBodyToByteString, emptyBS, concat,
fst3, fromInt,
byteStringToInt, intToByteString, showKeySingle, showKey,
section, takeWords, takeLen, take,
NamedCurve(..),
) where
import Prelude hiding (head, take, concat)
import qualified Prelude
import Numeric
import Control.Applicative ((<$>))
import Basic
import ByteStringMonad
-- import ToByteString
instance Show Random where
show (Random r) =
"(Random " ++ concatMap (`showHex` "") (unpack r) ++ ")"
instance Parsable Random where
parse = parseRandom
toByteString = randomToByteString
listLength _ = Nothing
parseRandom :: ByteStringM Random
parseRandom = Random <$> take 32
randomToByteString :: Random -> ByteString
randomToByteString (Random r) = r
instance Parsable CipherSuite where
parse = parseCipherSuite
toByteString = cipherSuiteToByteString
listLength _ = Just 2
parseCipherSuite :: ByteStringM CipherSuite
parseCipherSuite = do
[w1, w2] <- takeWords 2
return $ case (w1, w2) of
(0x00, 0x00) -> CipherSuite KeyExNULL MsgEncNULL
(0x00, 0x2f) -> CipherSuite RSA AES_128_CBC_SHA
(0x00, 0x33) -> CipherSuite DHE_RSA AES_128_CBC_SHA
(0x00, 0x39) -> CipherSuite ECDHE_PSK NULL_SHA
(0x00, 0x3c) -> CipherSuite RSA AES_128_CBC_SHA256
(0x00, 0x45) -> CipherSuite DHE_RSA CAMELLIA_128_CBC_SHA
(0x00, 0x67) -> CipherSuite DHE_RSA AES_128_CBC_SHA256
(0xc0, 0x09) -> CipherSuite ECDHE_ECDSA AES_128_CBC_SHA
(0xc0, 0x13) -> CipherSuite ECDHE_RSA AES_128_CBC_SHA
(0xc0, 0x23) -> CipherSuite ECDHE_ECDSA AES_128_CBC_SHA256
(0xc0, 0x27) -> CipherSuite ECDHE_RSA AES_128_CBC_SHA256
_ -> CipherSuiteRaw w1 w2
cipherSuiteToByteString :: CipherSuite -> ByteString
cipherSuiteToByteString (CipherSuite KeyExNULL MsgEncNULL) = "\x00\x00"
cipherSuiteToByteString (CipherSuite RSA AES_128_CBC_SHA) = "\x00\x2f"
cipherSuiteToByteString (CipherSuite DHE_RSA AES_128_CBC_SHA) = "\x00\x33"
cipherSuiteToByteString (CipherSuite ECDHE_PSK NULL_SHA) = "\x00\x39"
cipherSuiteToByteString (CipherSuite RSA AES_128_CBC_SHA256) = "\x00\x3c"
cipherSuiteToByteString (CipherSuite DHE_RSA CAMELLIA_128_CBC_SHA) = "\x00\x45"
cipherSuiteToByteString (CipherSuite DHE_RSA AES_128_CBC_SHA256) = "\x00\x67"
cipherSuiteToByteString (CipherSuite ECDHE_ECDSA AES_128_CBC_SHA) = "\xc0\x09"
cipherSuiteToByteString (CipherSuite ECDHE_RSA AES_128_CBC_SHA) = "\xc0\x13"
cipherSuiteToByteString (CipherSuite ECDHE_ECDSA AES_128_CBC_SHA256) = "\xc0\x23"
cipherSuiteToByteString (CipherSuite ECDHE_RSA AES_128_CBC_SHA256) = "\xc0\x27"
cipherSuiteToByteString (CipherSuiteRaw w1 w2) = pack [w1, w2]
cipherSuiteToByteString _ = error "Parts.cipherSuiteToByteString"
data HashAlgorithm
= HashAlgorithmSha1
| HashAlgorithmSha224
| HashAlgorithmSha256
| HashAlgorithmSha384
| HashAlgorithmSha512
| HashAlgorithmRaw Word8
deriving Show
instance Parsable HashAlgorithm where
parse = parseHashAlgorithm
toByteString = hashAlgorithmToByteString
listLength _ = Just 1
parseHashAlgorithm :: ByteStringM HashAlgorithm
parseHashAlgorithm = do
ha <- headBS
return $ case ha of
2 -> HashAlgorithmSha1
3 -> HashAlgorithmSha224
4 -> HashAlgorithmSha256
5 -> HashAlgorithmSha384
6 -> HashAlgorithmSha512
_ -> HashAlgorithmRaw ha
hashAlgorithmToByteString :: HashAlgorithm -> ByteString
hashAlgorithmToByteString HashAlgorithmSha1 = "\x02"
hashAlgorithmToByteString HashAlgorithmSha224 = "\x03"
hashAlgorithmToByteString HashAlgorithmSha256 = "\x04"
hashAlgorithmToByteString HashAlgorithmSha384 = "\x05"
hashAlgorithmToByteString HashAlgorithmSha512 = "\x06"
hashAlgorithmToByteString (HashAlgorithmRaw w) = pack [w]
data SignatureAlgorithm
= SignatureAlgorithmRsa
| SignatureAlgorithmDsa
| SignatureAlgorithmEcdsa
| SignatureAlgorithmRaw Word8
deriving Show
instance Parsable SignatureAlgorithm where
parse = parseSignatureAlgorithm
toByteString = signatureAlgorithmToByteString
listLength _ = Just 1
parseSignatureAlgorithm :: ByteStringM SignatureAlgorithm
parseSignatureAlgorithm = do
sa <- headBS
return $ case sa of
1 -> SignatureAlgorithmRsa
2 -> SignatureAlgorithmDsa
3 -> SignatureAlgorithmEcdsa
_ -> SignatureAlgorithmRaw sa
signatureAlgorithmToByteString :: SignatureAlgorithm -> ByteString
signatureAlgorithmToByteString SignatureAlgorithmRsa = "\x01"
signatureAlgorithmToByteString SignatureAlgorithmDsa = "\x02"
signatureAlgorithmToByteString SignatureAlgorithmEcdsa = "\x03"
signatureAlgorithmToByteString (SignatureAlgorithmRaw w) = pack [w]
instance Parsable Version where
parse = parseVersion
toByteString = versionToByteString
listLength _ = Nothing
parseVersion :: ByteStringM Version
parseVersion = do
[vmjr, vmnr] <- takeWords 2
return $ Version vmjr vmnr
instance Parsable NamedCurve where
parse = parseNamedCurve
toByteString = namedCurveToByteString
listLength _ = Nothing
parseNamedCurve :: ByteStringM NamedCurve
parseNamedCurve = do
nc <- takeWord16
return $ case nc of
23 -> Secp256r1
24 -> Secp384r1
25 -> Secp521r1
_ -> NamedCurveRaw nc
namedCurveToByteString :: NamedCurve -> ByteString
namedCurveToByteString (Secp256r1) = word16ToByteString 23
namedCurveToByteString (Secp384r1) = word16ToByteString 24
namedCurveToByteString (Secp521r1) = word16ToByteString 25
namedCurveToByteString (NamedCurveRaw nc) = word16ToByteString nc
|
YoshikuniJujo/forest
|
subprojects/tls-analysis/client/Parts.hs
|
Haskell
|
bsd-3-clause
| 5,566
|
module Sim where
import qualified Dummy as D
import Message
import Node
import RoutingData
import Utils
import qualified Data.HashMap.Strict as HM
import qualified Data.Text as T
import Data.Time.Clock
import System.Random
idBits :: Int
idBits = 10
idRange :: (Int, Int)
idRange = (0, (2 ^ idBits) - 1)
data Sim = Sim { nodes :: HM.HashMap IPInfo Node
, queue :: [Message]
, gen :: StdGen
}
testNode :: ID -> ID -> UTCTime -> Node
testNode ours theirs now = Node { nPort = 0
, nIP = ours
, nNodeID = ours
, nTree = Leaf [theirs]
, nStore = HM.empty
, nFindValueQueries = HM.empty
, nFindNodeQueries = HM.empty
, nIncoming = []
, nOutgoing = []
, nPendingStores = []
, nPendingFinds = []
, nLastSeen = HM.fromList [(theirs, now)]
, nLastSent = HM.empty
, nNodeInfos = HM.fromList [(theirs, (theirs, 0))]
, nPrintBuffer = []
}
intToID :: Int -> ID
intToID i = zeroPad idBits $ decToBitString i
randLog :: (Random a, Show a) => String -> (a, a) -> IO a
randLog logMe r@(lo, hi) = do
putStrLn $ "Generating " ++ logMe ++ " between " ++ (show lo) ++ " - " ++ (show hi)
getStdRandom $ randomR r
getNode :: Int -> [Node] -> Node
getNode i nodes =
case get nodes i of
Nothing -> error $ "Node list no index " ++ (show i)
Just node -> node
initNodes :: Int -> Int -> UTCTime -> HM.HashMap ID Node
initNodes i1 i2 now = HM.fromList [(aID, nodeA), (bID, nodeB)]
where aID = intToID i1
bID = intToID i2
nodeA = testNode aID bID now
nodeB = testNode bID aID now
execute :: Node -> Node
execute node = node
start :: StdGen -> IO ()
start gen = do
now <- getCurrentTime
setStdGen gen
id1 <- randLog "node A ID" idRange
id2 <- randLog "node B ID" idRange
let nodes = initNodes id1 id2 now
run nodes [] [] HM.empty
data Command = Put { key :: ID
, value :: T.Text
, triggered :: UTCTime
, success :: Bool
}
| Get { key :: ID
, triggered :: UTCTime
, success :: Bool
}
run :: HM.HashMap ID Node -- ^ ID -> Node with that ID
-> [Message] -- ^ Message queue between nodes
-> [Command] -- ^ Commands sent
-> HM.HashMap ID T.Text -- ^ Reference hashmap (DHT map should emulate this)
-> IO ()
run nodes messages commands refStore = do
putStrLn "sup"
|
semaj/hademlia
|
src/Sim.hs
|
Haskell
|
bsd-3-clause
| 2,990
|
module Language.C.Syntax.BinaryInstances where
import Data.Binary
import Language.C.Syntax.AST
import Language.C.Syntax.Constants
import Language.C.Syntax.Ops
import Language.C.Syntax.ManualBinaryInstances
instance (Binary a) => Binary (Language.C.Syntax.AST.CTranslationUnit a) where
put (CTranslUnit a b) = put a >> put b
get = get >>= \a -> get >>= \b -> return (CTranslUnit a b)
instance (Binary a) => Binary (Language.C.Syntax.AST.CExternalDeclaration a) where
put (CDeclExt a) = putWord8 0 >> put a
put (CFDefExt a) = putWord8 1 >> put a
put (CAsmExt a b) = putWord8 2 >> put a >> put b
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> return (CDeclExt a)
1 -> get >>= \a -> return (CFDefExt a)
2 -> get >>= \a -> get >>= \b -> return (CAsmExt a b)
_ -> fail "no parse"
instance (Binary a) => Binary (Language.C.Syntax.AST.CFunctionDef a) where
put (CFunDef a b c d e) = put a >> put b >> put c >> put d >> put e
get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> get >>= \e -> return (CFunDef a b c d e)
instance (Binary a) => Binary (Language.C.Syntax.AST.CDeclaration a) where
put (CDecl a b c) = put a >> put b >> put c
get = get >>= \a -> get >>= \b -> get >>= \c -> return (CDecl a b c)
instance (Binary a) => Binary (Language.C.Syntax.AST.CStructureUnion a) where
put (CStruct a b c d e) = put a >> put b >> put c >> put d >> put e
get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> get >>= \e -> return (CStruct a b c d e)
instance Binary Language.C.Syntax.AST.CStructTag where
put CStructTag = putWord8 0
put CUnionTag = putWord8 1
get = do
tag_ <- getWord8
case tag_ of
0 -> return CStructTag
1 -> return CUnionTag
_ -> fail "no parse"
instance (Binary a) => Binary (Language.C.Syntax.AST.CEnumeration a) where
put (CEnum a b c d) = put a >> put b >> put c >> put d
get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CEnum a b c d)
instance (Binary a) => Binary (Language.C.Syntax.AST.CDeclarationSpecifier a) where
put (CStorageSpec a) = putWord8 0 >> put a
put (CTypeSpec a) = putWord8 1 >> put a
put (CTypeQual a) = putWord8 2 >> put a
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> return (CStorageSpec a)
1 -> get >>= \a -> return (CTypeSpec a)
2 -> get >>= \a -> return (CTypeQual a)
_ -> fail "no parse"
instance (Binary a) => Binary (Language.C.Syntax.AST.CStorageSpecifier a) where
put (CAuto a) = putWord8 0 >> put a
put (CRegister a) = putWord8 1 >> put a
put (CStatic a) = putWord8 2 >> put a
put (CExtern a) = putWord8 3 >> put a
put (CTypedef a) = putWord8 4 >> put a
put (CThread a) = putWord8 5 >> put a
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> return (CAuto a)
1 -> get >>= \a -> return (CRegister a)
2 -> get >>= \a -> return (CStatic a)
3 -> get >>= \a -> return (CExtern a)
4 -> get >>= \a -> return (CTypedef a)
5 -> get >>= \a -> return (CThread a)
_ -> fail "no parse"
instance (Binary a) => Binary (Language.C.Syntax.AST.CTypeSpecifier a) where
put (CVoidType a) = putWord8 0 >> put a
put (CCharType a) = putWord8 1 >> put a
put (CShortType a) = putWord8 2 >> put a
put (CIntType a) = putWord8 3 >> put a
put (CLongType a) = putWord8 4 >> put a
put (CFloatType a) = putWord8 5 >> put a
put (CDoubleType a) = putWord8 6 >> put a
put (CSignedType a) = putWord8 7 >> put a
put (CUnsigType a) = putWord8 8 >> put a
put (CBoolType a) = putWord8 9 >> put a
put (CComplexType a) = putWord8 10 >> put a
put (CSUType a b) = putWord8 11 >> put a >> put b
put (CEnumType a b) = putWord8 12 >> put a >> put b
put (CTypeDef a b) = putWord8 13 >> put a >> put b
put (CTypeOfExpr a b) = putWord8 14 >> put a >> put b
put (CTypeOfType a b) = putWord8 15 >> put a >> put b
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> return (CVoidType a)
1 -> get >>= \a -> return (CCharType a)
2 -> get >>= \a -> return (CShortType a)
3 -> get >>= \a -> return (CIntType a)
4 -> get >>= \a -> return (CLongType a)
5 -> get >>= \a -> return (CFloatType a)
6 -> get >>= \a -> return (CDoubleType a)
7 -> get >>= \a -> return (CSignedType a)
8 -> get >>= \a -> return (CUnsigType a)
9 -> get >>= \a -> return (CBoolType a)
10 -> get >>= \a -> return (CComplexType a)
11 -> get >>= \a -> get >>= \b -> return (CSUType a b)
12 -> get >>= \a -> get >>= \b -> return (CEnumType a b)
13 -> get >>= \a -> get >>= \b -> return (CTypeDef a b)
14 -> get >>= \a -> get >>= \b -> return (CTypeOfExpr a b)
15 -> get >>= \a -> get >>= \b -> return (CTypeOfType a b)
_ -> fail "no parse"
instance (Binary a) => Binary (Language.C.Syntax.AST.CTypeQualifier a) where
put (CConstQual a) = putWord8 0 >> put a
put (CVolatQual a) = putWord8 1 >> put a
put (CRestrQual a) = putWord8 2 >> put a
put (CInlineQual a) = putWord8 3 >> put a
put (CAttrQual a) = putWord8 4 >> put a
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> return (CConstQual a)
1 -> get >>= \a -> return (CVolatQual a)
2 -> get >>= \a -> return (CRestrQual a)
3 -> get >>= \a -> return (CInlineQual a)
4 -> get >>= \a -> return (CAttrQual a)
_ -> fail "no parse"
instance (Binary a) => Binary (Language.C.Syntax.AST.CAttribute a) where
put (CAttr a b c) = put a >> put b >> put c
get = get >>= \a -> get >>= \b -> get >>= \c -> return (CAttr a b c)
instance (Binary a) => Binary (Language.C.Syntax.AST.CDeclarator a) where
put (CDeclr a b c d e) = put a >> put b >> put c >> put d >> put e
get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> get >>= \e -> return (CDeclr a b c d e)
instance (Binary a) => Binary (Language.C.Syntax.AST.CDerivedDeclarator a) where
put (CPtrDeclr a b) = putWord8 0 >> put a >> put b
put (CArrDeclr a b c) = putWord8 1 >> put a >> put b >> put c
put (CFunDeclr a b c) = putWord8 2 >> put a >> put b >> put c
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> get >>= \b -> return (CPtrDeclr a b)
1 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CArrDeclr a b c)
2 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CFunDeclr a b c)
_ -> fail "no parse"
instance (Binary a) => Binary (Language.C.Syntax.AST.CArraySize a) where
put (CNoArrSize a) = putWord8 0 >> put a
put (CArrSize a b) = putWord8 1 >> put a >> put b
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> return (CNoArrSize a)
1 -> get >>= \a -> get >>= \b -> return (CArrSize a b)
_ -> fail "no parse"
instance (Binary a) => Binary (Language.C.Syntax.AST.CInitializer a) where
put (CInitExpr a b) = putWord8 0 >> put a >> put b
put (CInitList a b) = putWord8 1 >> put a >> put b
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> get >>= \b -> return (CInitExpr a b)
1 -> get >>= \a -> get >>= \b -> return (CInitList a b)
_ -> fail "no parse"
instance (Binary a) => Binary (Language.C.Syntax.AST.CPartDesignator a) where
put (CArrDesig a b) = putWord8 0 >> put a >> put b
put (CMemberDesig a b) = putWord8 1 >> put a >> put b
put (CRangeDesig a b c) = putWord8 2 >> put a >> put b >> put c
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> get >>= \b -> return (CArrDesig a b)
1 -> get >>= \a -> get >>= \b -> return (CMemberDesig a b)
2 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CRangeDesig a b c)
_ -> fail "no parse"
instance (Binary a) => Binary (Language.C.Syntax.AST.CStatement a) where
put (CLabel a b c d) = putWord8 0 >> put a >> put b >> put c >> put d
put (CCase a b c) = putWord8 1 >> put a >> put b >> put c
put (CCases a b c d) = putWord8 2 >> put a >> put b >> put c >> put d
put (CDefault a b) = putWord8 3 >> put a >> put b
put (CExpr a b) = putWord8 4 >> put a >> put b
put (CCompound a b c) = putWord8 5 >> put a >> put b >> put c
put (CIf a b c d) = putWord8 6 >> put a >> put b >> put c >> put d
put (CSwitch a b c) = putWord8 7 >> put a >> put b >> put c
put (CWhile a b c d) = putWord8 8 >> put a >> put b >> put c >> put d
put (CFor a b c d e) = putWord8 9 >> put a >> put b >> put c >> put d >> put e
put (CGoto a b) = putWord8 10 >> put a >> put b
put (CGotoPtr a b) = putWord8 11 >> put a >> put b
put (CCont a) = putWord8 12 >> put a
put (CBreak a) = putWord8 13 >> put a
put (CReturn a b) = putWord8 14 >> put a >> put b
put (CAsm a b) = putWord8 15 >> put a >> put b
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CLabel a b c d)
1 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CCase a b c)
2 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CCases a b c d)
3 -> get >>= \a -> get >>= \b -> return (CDefault a b)
4 -> get >>= \a -> get >>= \b -> return (CExpr a b)
5 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CCompound a b c)
6 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CIf a b c d)
7 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CSwitch a b c)
8 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CWhile a b c d)
9 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> get >>= \e -> return (CFor a b c d e)
10 -> get >>= \a -> get >>= \b -> return (CGoto a b)
11 -> get >>= \a -> get >>= \b -> return (CGotoPtr a b)
12 -> get >>= \a -> return (CCont a)
13 -> get >>= \a -> return (CBreak a)
14 -> get >>= \a -> get >>= \b -> return (CReturn a b)
15 -> get >>= \a -> get >>= \b -> return (CAsm a b)
_ -> fail "no parse"
instance (Binary a) => Binary (Language.C.Syntax.AST.CCompoundBlockItem a) where
put (CBlockStmt a) = putWord8 0 >> put a
put (CBlockDecl a) = putWord8 1 >> put a
put (CNestedFunDef a) = putWord8 2 >> put a
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> return (CBlockStmt a)
1 -> get >>= \a -> return (CBlockDecl a)
2 -> get >>= \a -> return (CNestedFunDef a)
_ -> fail "no parse"
instance (Binary a) => Binary (Language.C.Syntax.AST.CAssemblyStatement a) where
put (CAsmStmt a b c d e f) = put a >> put b >> put c >> put d >> put e >> put f
get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> get >>= \e -> get >>= \f -> return (CAsmStmt a b c d e f)
instance (Binary a) => Binary (Language.C.Syntax.AST.CAssemblyOperand a) where
put (CAsmOperand a b c d) = put a >> put b >> put c >> put d
get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CAsmOperand a b c d)
instance (Binary a) => Binary (Language.C.Syntax.AST.CExpression a) where
put (CComma a b) = putWord8 0 >> put a >> put b
put (CAssign a b c d) = putWord8 1 >> put a >> put b >> put c >> put d
put (CCond a b c d) = putWord8 2 >> put a >> put b >> put c >> put d
put (CBinary a b c d) = putWord8 3 >> put a >> put b >> put c >> put d
put (CCast a b c) = putWord8 4 >> put a >> put b >> put c
put (CUnary a b c) = putWord8 5 >> put a >> put b >> put c
put (CSizeofExpr a b) = putWord8 6 >> put a >> put b
put (CSizeofType a b) = putWord8 7 >> put a >> put b
put (CAlignofExpr a b) = putWord8 8 >> put a >> put b
put (CAlignofType a b) = putWord8 9 >> put a >> put b
put (CComplexReal a b) = putWord8 10 >> put a >> put b
put (CComplexImag a b) = putWord8 11 >> put a >> put b
put (CIndex a b c) = putWord8 12 >> put a >> put b >> put c
put (CCall a b c) = putWord8 13 >> put a >> put b >> put c
put (CMember a b c d) = putWord8 14 >> put a >> put b >> put c >> put d
put (CVar a b) = putWord8 15 >> put a >> put b
put (CConst a) = putWord8 16 >> put a
put (CCompoundLit a b c) = putWord8 17 >> put a >> put b >> put c
put (CStatExpr a b) = putWord8 18 >> put a >> put b
put (CLabAddrExpr a b) = putWord8 19 >> put a >> put b
put (CBuiltinExpr a) = putWord8 20 >> put a
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> get >>= \b -> return (CComma a b)
1 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CAssign a b c d)
2 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CCond a b c d)
3 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CBinary a b c d)
4 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CCast a b c)
5 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CUnary a b c)
6 -> get >>= \a -> get >>= \b -> return (CSizeofExpr a b)
7 -> get >>= \a -> get >>= \b -> return (CSizeofType a b)
8 -> get >>= \a -> get >>= \b -> return (CAlignofExpr a b)
9 -> get >>= \a -> get >>= \b -> return (CAlignofType a b)
10 -> get >>= \a -> get >>= \b -> return (CComplexReal a b)
11 -> get >>= \a -> get >>= \b -> return (CComplexImag a b)
12 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CIndex a b c)
13 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CCall a b c)
14 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CMember a b c d)
15 -> get >>= \a -> get >>= \b -> return (CVar a b)
16 -> get >>= \a -> return (CConst a)
17 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CCompoundLit a b c)
18 -> get >>= \a -> get >>= \b -> return (CStatExpr a b)
19 -> get >>= \a -> get >>= \b -> return (CLabAddrExpr a b)
20 -> get >>= \a -> return (CBuiltinExpr a)
_ -> fail "no parse"
instance Binary Language.C.Syntax.Ops.CAssignOp where
put CAssignOp = putWord8 0
put CMulAssOp = putWord8 1
put CDivAssOp = putWord8 2
put CRmdAssOp = putWord8 3
put CAddAssOp = putWord8 4
put CSubAssOp = putWord8 5
put CShlAssOp = putWord8 6
put CShrAssOp = putWord8 7
put CAndAssOp = putWord8 8
put CXorAssOp = putWord8 9
put COrAssOp = putWord8 10
get = do
tag_ <- getWord8
case tag_ of
0 -> return CAssignOp
1 -> return CMulAssOp
2 -> return CDivAssOp
3 -> return CRmdAssOp
4 -> return CAddAssOp
5 -> return CSubAssOp
6 -> return CShlAssOp
7 -> return CShrAssOp
8 -> return CAndAssOp
9 -> return CXorAssOp
10 -> return COrAssOp
_ -> fail "no parse"
instance Binary Language.C.Syntax.Ops.CBinaryOp where
put CMulOp = putWord8 0
put CDivOp = putWord8 1
put CRmdOp = putWord8 2
put CAddOp = putWord8 3
put CSubOp = putWord8 4
put CShlOp = putWord8 5
put CShrOp = putWord8 6
put CLeOp = putWord8 7
put CGrOp = putWord8 8
put CLeqOp = putWord8 9
put CGeqOp = putWord8 10
put CEqOp = putWord8 11
put CNeqOp = putWord8 12
put CAndOp = putWord8 13
put CXorOp = putWord8 14
put COrOp = putWord8 15
put CLndOp = putWord8 16
put CLorOp = putWord8 17
get = do
tag_ <- getWord8
case tag_ of
0 -> return CMulOp
1 -> return CDivOp
2 -> return CRmdOp
3 -> return CAddOp
4 -> return CSubOp
5 -> return CShlOp
6 -> return CShrOp
7 -> return CLeOp
8 -> return CGrOp
9 -> return CLeqOp
10 -> return CGeqOp
11 -> return CEqOp
12 -> return CNeqOp
13 -> return CAndOp
14 -> return CXorOp
15 -> return COrOp
16 -> return CLndOp
17 -> return CLorOp
_ -> fail "no parse"
instance Binary Language.C.Syntax.Ops.CUnaryOp where
put CPreIncOp = putWord8 0
put CPreDecOp = putWord8 1
put CPostIncOp = putWord8 2
put CPostDecOp = putWord8 3
put CAdrOp = putWord8 4
put CIndOp = putWord8 5
put CPlusOp = putWord8 6
put CMinOp = putWord8 7
put CCompOp = putWord8 8
put CNegOp = putWord8 9
get = do
tag_ <- getWord8
case tag_ of
0 -> return CPreIncOp
1 -> return CPreDecOp
2 -> return CPostIncOp
3 -> return CPostDecOp
4 -> return CAdrOp
5 -> return CIndOp
6 -> return CPlusOp
7 -> return CMinOp
8 -> return CCompOp
9 -> return CNegOp
_ -> fail "no parse"
instance (Binary a) => Binary (Language.C.Syntax.AST.CBuiltinThing a) where
put (CBuiltinVaArg a b c) = putWord8 0 >> put a >> put b >> put c
put (CBuiltinOffsetOf a b c) = putWord8 1 >> put a >> put b >> put c
put (CBuiltinTypesCompatible a b c) = putWord8 2 >> put a >> put b >> put c
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CBuiltinVaArg a b c)
1 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CBuiltinOffsetOf a b c)
2 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CBuiltinTypesCompatible a b c)
_ -> fail "no parse"
instance (Binary a) => Binary (Language.C.Syntax.AST.CConstant a) where
put (CIntConst a b) = putWord8 0 >> put a >> put b
put (CCharConst a b) = putWord8 1 >> put a >> put b
put (CFloatConst a b) = putWord8 2 >> put a >> put b
put (CStrConst a b) = putWord8 3 >> put a >> put b
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> get >>= \b -> return (CIntConst a b)
1 -> get >>= \a -> get >>= \b -> return (CCharConst a b)
2 -> get >>= \a -> get >>= \b -> return (CFloatConst a b)
3 -> get >>= \a -> get >>= \b -> return (CStrConst a b)
_ -> fail "no parse"
instance (Binary a) => Binary (Language.C.Syntax.AST.CStringLiteral a) where
put (CStrLit a b) = put a >> put b
get = get >>= \a -> get >>= \b -> return (CStrLit a b)
|
atomb/language-c-binary
|
Language/C/Syntax/BinaryInstances.hs
|
Haskell
|
bsd-3-clause
| 17,644
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.NV.ViewportSwizzle
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.NV.ViewportSwizzle (
-- * Extension Support
glGetNVViewportSwizzle,
gl_NV_viewport_swizzle,
-- * Enums
pattern GL_VIEWPORT_SWIZZLE_NEGATIVE_W_NV,
pattern GL_VIEWPORT_SWIZZLE_NEGATIVE_X_NV,
pattern GL_VIEWPORT_SWIZZLE_NEGATIVE_Y_NV,
pattern GL_VIEWPORT_SWIZZLE_NEGATIVE_Z_NV,
pattern GL_VIEWPORT_SWIZZLE_POSITIVE_W_NV,
pattern GL_VIEWPORT_SWIZZLE_POSITIVE_X_NV,
pattern GL_VIEWPORT_SWIZZLE_POSITIVE_Y_NV,
pattern GL_VIEWPORT_SWIZZLE_POSITIVE_Z_NV,
pattern GL_VIEWPORT_SWIZZLE_W_NV,
pattern GL_VIEWPORT_SWIZZLE_X_NV,
pattern GL_VIEWPORT_SWIZZLE_Y_NV,
pattern GL_VIEWPORT_SWIZZLE_Z_NV,
-- * Functions
glViewportSwizzleNV
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/NV/ViewportSwizzle.hs
|
Haskell
|
bsd-3-clause
| 1,196
|
module Main where
import Run
main :: IO ()
main = runMain
|
nejla/auth-service
|
service/app/Main.hs
|
Haskell
|
bsd-3-clause
| 60
|
{-# LANGUAGE RankNTypes #-}
module Abstract.Interfaces.Stack.Push (
StackPush (..),
push,
pushBatch,
stackToPush
) where
import qualified Abstract.Interfaces.Stack as S
data StackPush m t = StackPush {
_sPush :: S.Stack m t
}
stackToPush :: S.Stack m t -> StackPush m t
stackToPush s = StackPush { _sPush = s }
push :: (Monad m) => forall t. StackPush m t -> t -> m ()
push (StackPush s') t = S.push s' t
pushBatch :: (Monad m) => forall t. StackPush m t -> [t] -> m ()
pushBatch (StackPush s') ts = S.pushBatch s' ts
|
adarqui/Abstract-Interfaces
|
src/Abstract/Interfaces/Stack/Push.hs
|
Haskell
|
bsd-3-clause
| 533
|
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple
-- Copyright : Isaac Jones 2003-2005
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This is the command line front end to the Simple build system. When given
-- the parsed command-line args and package information, is able to perform
-- basic commands like configure, build, install, register, etc.
--
-- This module exports the main functions that Setup.hs scripts use. It
-- re-exports the 'UserHooks' type, the standard entry points like
-- 'defaultMain' and 'defaultMainWithHooks' and the predefined sets of
-- 'UserHooks' that custom @Setup.hs@ scripts can extend to add their own
-- behaviour.
--
-- This module isn't called \"Simple\" because it's simple. Far from
-- it. It's called \"Simple\" because it does complicated things to
-- simple software.
--
-- The original idea was that there could be different build systems that all
-- presented the same compatible command line interfaces. There is still a
-- "Distribution.Make" system but in practice no packages use it.
{- All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
* Neither the name of Isaac Jones nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
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
OWNER 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. -}
{-
Work around this warning:
libraries/Cabal/Distribution/Simple.hs:78:0:
Warning: In the use of `runTests'
(imported from Distribution.Simple.UserHooks):
Deprecated: "Please use the new testing interface instead!"
-}
{-# OPTIONS_GHC -fno-warn-deprecations #-}
module Distribution.Simple (
module Distribution.Package,
module Distribution.Version,
module Distribution.License,
module Distribution.Simple.Compiler,
module Language.Haskell.Extension,
-- * Simple interface
defaultMain, defaultMainNoRead, defaultMainArgs,
-- * Customization
UserHooks(..), Args,
defaultMainWithHooks, defaultMainWithHooksArgs,
-- ** Standard sets of hooks
simpleUserHooks,
autoconfUserHooks,
emptyUserHooks,
-- ** Utils
defaultHookedPackageDesc
) where
-- local
import Distribution.Simple.Compiler hiding (Flag)
import Distribution.Simple.UserHooks
import Distribution.Package --must not specify imports, since we're exporting moule.
import Distribution.PackageDescription
( PackageDescription(..), GenericPackageDescription, Executable(..)
, updatePackageDescription, hasLibs
, HookedBuildInfo, emptyHookedBuildInfo )
import Distribution.PackageDescription.Parse
( readPackageDescription, readHookedBuildInfo )
import Distribution.PackageDescription.Configuration
( flattenPackageDescription )
import Distribution.Simple.Program
( defaultProgramConfiguration, addKnownPrograms, builtinPrograms
, restoreProgramConfiguration, reconfigurePrograms )
import Distribution.Simple.PreProcess (knownSuffixHandlers, PPSuffixHandler)
import Distribution.Simple.Setup
import Distribution.Simple.Command
import Distribution.Simple.Build ( build )
import Distribution.Simple.SrcDist ( sdist )
import Distribution.Simple.Register
( register, unregister )
import Distribution.Simple.Configure
( getPersistBuildConfig, maybeGetPersistBuildConfig
, writePersistBuildConfig, checkPersistBuildConfigOutdated
, configure, checkForeignDeps )
import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..) )
import Distribution.Simple.Bench (bench)
import Distribution.Simple.BuildPaths ( srcPref)
import Distribution.Simple.Test (test)
import Distribution.Simple.Install (install)
import Distribution.Simple.Haddock (haddock, hscolour)
import Distribution.Simple.Utils
(die, notice, info, setupMessage, chattyTry,
defaultPackageDesc, defaultHookedPackageDesc,
rawSystemExitWithEnv, factionVersion, topHandler )
import Distribution.System
( OS(..), buildOS )
import Distribution.Verbosity
import Language.Haskell.Extension
import Distribution.Version
import Distribution.License
import Distribution.Text
( display )
-- Base
import System.Environment(getArgs, getProgName, getEnvironment)
import System.Directory(removeFile, doesFileExist,
doesDirectoryExist, removeDirectoryRecursive)
import System.Exit
import System.IO.Error (isDoesNotExistError)
import Distribution.Compat.Exception (catchIO, throwIOIO)
import Control.Monad (when)
import Data.List (intersperse, unionBy, nub, (\\))
-- | A simple implementation of @main@ for a Faction setup script.
-- It reads the package description file using IO, and performs the
-- action specified on the command line.
defaultMain :: IO ()
defaultMain = getArgs >>= defaultMainHelper simpleUserHooks
-- | A version of 'defaultMain' that is passed the command line
-- arguments, rather than getting them from the environment.
defaultMainArgs :: [String] -> IO ()
defaultMainArgs = defaultMainHelper simpleUserHooks
-- | A customizable version of 'defaultMain'.
defaultMainWithHooks :: UserHooks -> IO ()
defaultMainWithHooks hooks = getArgs >>= defaultMainHelper hooks
-- | A customizable version of 'defaultMain' that also takes the command
-- line arguments.
defaultMainWithHooksArgs :: UserHooks -> [String] -> IO ()
defaultMainWithHooksArgs = defaultMainHelper
-- | Like 'defaultMain', but accepts the package description as input
-- rather than using IO to read it.
defaultMainNoRead :: GenericPackageDescription -> IO ()
defaultMainNoRead pkg_descr =
getArgs >>=
defaultMainHelper simpleUserHooks { readDesc = return (Just pkg_descr) }
defaultMainHelper :: UserHooks -> Args -> IO ()
defaultMainHelper hooks args = topHandler $
case commandsRun globalCommand commands args of
CommandHelp help -> printHelp help
CommandList opts -> printOptionsList opts
CommandErrors errs -> printErrors errs
CommandReadyToGo (flags, commandParse) ->
case commandParse of
_ | fromFlag (globalVersion flags) -> printVersion
| fromFlag (globalNumericVersion flags) -> printNumericVersion
CommandHelp help -> printHelp help
CommandList opts -> printOptionsList opts
CommandErrors errs -> printErrors errs
CommandReadyToGo action -> action
where
printHelp help = getProgName >>= putStr . help
printOptionsList = putStr . unlines
printErrors errs = do
putStr (concat (intersperse "\n" errs))
exitWith (ExitFailure 1)
printNumericVersion = putStrLn $ display factionVersion
printVersion = putStrLn $ "Faction library version "
++ display factionVersion
progs = addKnownPrograms (hookedPrograms hooks) defaultProgramConfiguration
commands =
[configureCommand progs `commandAddAction` \fs as ->
configureAction hooks fs as >> return ()
,buildCommand progs `commandAddAction` buildAction hooks
,installCommand `commandAddAction` installAction hooks
,copyCommand `commandAddAction` copyAction hooks
,haddockCommand `commandAddAction` haddockAction hooks
,cleanCommand `commandAddAction` cleanAction hooks
,sdistCommand `commandAddAction` sdistAction hooks
,hscolourCommand `commandAddAction` hscolourAction hooks
,registerCommand `commandAddAction` registerAction hooks
,unregisterCommand `commandAddAction` unregisterAction hooks
,testCommand `commandAddAction` testAction hooks
,benchmarkCommand `commandAddAction` benchAction hooks
]
-- | Combine the preprocessors in the given hooks with the
-- preprocessors built into faction.
allSuffixHandlers :: UserHooks
-> [PPSuffixHandler]
allSuffixHandlers hooks
= overridesPP (hookedPreProcessors hooks) knownSuffixHandlers
where
overridesPP :: [PPSuffixHandler] -> [PPSuffixHandler] -> [PPSuffixHandler]
overridesPP = unionBy (\x y -> fst x == fst y)
configureAction :: UserHooks -> ConfigFlags -> Args -> IO LocalBuildInfo
configureAction hooks flags args = do
let distPref = fromFlag $ configDistPref flags
pbi <- preConf hooks args flags
(mb_pd_file, pkg_descr0) <- confPkgDescr
-- get_pkg_descr (configVerbosity flags')
--let pkg_descr = updatePackageDescription pbi pkg_descr0
let epkg_descr = (pkg_descr0, pbi)
--(warns, ers) <- sanityCheckPackage pkg_descr
--errorOut (configVerbosity flags') warns ers
localbuildinfo0 <- confHook hooks epkg_descr flags
-- remember the .faction filename if we know it
-- and all the extra command line args
let localbuildinfo = localbuildinfo0 {
pkgDescrFile = mb_pd_file,
extraConfigArgs = args
}
writePersistBuildConfig distPref localbuildinfo
let pkg_descr = localPkgDescr localbuildinfo
postConf hooks args flags pkg_descr localbuildinfo
return localbuildinfo
where
verbosity = fromFlag (configVerbosity flags)
confPkgDescr :: IO (Maybe FilePath, GenericPackageDescription)
confPkgDescr = do
mdescr <- readDesc hooks
case mdescr of
Just descr -> return (Nothing, descr)
Nothing -> do
pdfile <- defaultPackageDesc verbosity
descr <- readPackageDescription verbosity pdfile
return (Just pdfile, descr)
buildAction :: UserHooks -> BuildFlags -> Args -> IO ()
buildAction hooks flags args = do
let distPref = fromFlag $ buildDistPref flags
verbosity = fromFlag $ buildVerbosity flags
lbi <- getBuildConfig hooks verbosity distPref
progs <- reconfigurePrograms verbosity
(buildProgramPaths flags)
(buildProgramArgs flags)
(withPrograms lbi)
hookedAction preBuild buildHook postBuild
(return lbi { withPrograms = progs })
hooks flags args
hscolourAction :: UserHooks -> HscolourFlags -> Args -> IO ()
hscolourAction hooks flags args
= do let distPref = fromFlag $ hscolourDistPref flags
verbosity = fromFlag $ hscolourVerbosity flags
hookedAction preHscolour hscolourHook postHscolour
(getBuildConfig hooks verbosity distPref)
hooks flags args
haddockAction :: UserHooks -> HaddockFlags -> Args -> IO ()
haddockAction hooks flags args = do
let distPref = fromFlag $ haddockDistPref flags
verbosity = fromFlag $ haddockVerbosity flags
lbi <- getBuildConfig hooks verbosity distPref
progs <- reconfigurePrograms verbosity
(haddockProgramPaths flags)
(haddockProgramArgs flags)
(withPrograms lbi)
hookedAction preHaddock haddockHook postHaddock
(return lbi { withPrograms = progs })
hooks flags args
cleanAction :: UserHooks -> CleanFlags -> Args -> IO ()
cleanAction hooks flags args = do
pbi <- preClean hooks args flags
pdfile <- defaultPackageDesc verbosity
ppd <- readPackageDescription verbosity pdfile
let pkg_descr0 = flattenPackageDescription ppd
-- We don't sanity check for clean as an error
-- here would prevent cleaning:
--sanityCheckHookedBuildInfo pkg_descr0 pbi
let pkg_descr = updatePackageDescription pbi pkg_descr0
cleanHook hooks pkg_descr () hooks flags
postClean hooks args flags pkg_descr ()
where verbosity = fromFlag (cleanVerbosity flags)
copyAction :: UserHooks -> CopyFlags -> Args -> IO ()
copyAction hooks flags args
= do let distPref = fromFlag $ copyDistPref flags
verbosity = fromFlag $ copyVerbosity flags
hookedAction preCopy copyHook postCopy
(getBuildConfig hooks verbosity distPref)
hooks flags args
installAction :: UserHooks -> InstallFlags -> Args -> IO ()
installAction hooks flags args
= do let distPref = fromFlag $ installDistPref flags
verbosity = fromFlag $ installVerbosity flags
hookedAction preInst instHook postInst
(getBuildConfig hooks verbosity distPref)
hooks flags args
sdistAction :: UserHooks -> SDistFlags -> Args -> IO ()
sdistAction hooks flags args = do
let distPref = fromFlag $ sDistDistPref flags
pbi <- preSDist hooks args flags
mlbi <- maybeGetPersistBuildConfig distPref
pdfile <- defaultPackageDesc verbosity
ppd <- readPackageDescription verbosity pdfile
let pkg_descr0 = flattenPackageDescription ppd
sanityCheckHookedBuildInfo pkg_descr0 pbi
let pkg_descr = updatePackageDescription pbi pkg_descr0
sDistHook hooks pkg_descr mlbi hooks flags
postSDist hooks args flags pkg_descr mlbi
where verbosity = fromFlag (sDistVerbosity flags)
testAction :: UserHooks -> TestFlags -> Args -> IO ()
testAction hooks flags args = do
let distPref = fromFlag $ testDistPref flags
verbosity = fromFlag $ testVerbosity flags
localBuildInfo <- getBuildConfig hooks verbosity distPref
let pkg_descr = localPkgDescr localBuildInfo
-- It is safe to do 'runTests' before the new test handler because the
-- default action is a no-op and if the package uses the old test interface
-- the new handler will find no tests.
runTests hooks args False pkg_descr localBuildInfo
--FIXME: this is a hack, passing the args inside the flags
-- it's because the args to not get passed to the main test hook
let flags' = flags { testList = Flag args }
hookedAction preTest testHook postTest
(getBuildConfig hooks verbosity distPref)
hooks flags' args
benchAction :: UserHooks -> BenchmarkFlags -> Args -> IO ()
benchAction hooks flags args = do
let distPref = fromFlag $ benchmarkDistPref flags
verbosity = fromFlag $ benchmarkVerbosity flags
hookedActionWithArgs preBench benchHook postBench
(getBuildConfig hooks verbosity distPref)
hooks flags args
registerAction :: UserHooks -> RegisterFlags -> Args -> IO ()
registerAction hooks flags args
= do let distPref = fromFlag $ regDistPref flags
verbosity = fromFlag $ regVerbosity flags
hookedAction preReg regHook postReg
(getBuildConfig hooks verbosity distPref)
hooks flags args
unregisterAction :: UserHooks -> RegisterFlags -> Args -> IO ()
unregisterAction hooks flags args
= do let distPref = fromFlag $ regDistPref flags
verbosity = fromFlag $ regVerbosity flags
hookedAction preUnreg unregHook postUnreg
(getBuildConfig hooks verbosity distPref)
hooks flags args
hookedAction :: (UserHooks -> Args -> flags -> IO HookedBuildInfo)
-> (UserHooks -> PackageDescription -> LocalBuildInfo
-> UserHooks -> flags -> IO ())
-> (UserHooks -> Args -> flags -> PackageDescription
-> LocalBuildInfo -> IO ())
-> IO LocalBuildInfo
-> UserHooks -> flags -> Args -> IO ()
hookedAction pre_hook cmd_hook =
hookedActionWithArgs pre_hook (\h _ pd lbi uh flags -> cmd_hook h pd lbi uh flags)
hookedActionWithArgs :: (UserHooks -> Args -> flags -> IO HookedBuildInfo)
-> (UserHooks -> Args -> PackageDescription -> LocalBuildInfo
-> UserHooks -> flags -> IO ())
-> (UserHooks -> Args -> flags -> PackageDescription
-> LocalBuildInfo -> IO ())
-> IO LocalBuildInfo
-> UserHooks -> flags -> Args -> IO ()
hookedActionWithArgs pre_hook cmd_hook post_hook get_build_config hooks flags args = do
pbi <- pre_hook hooks args flags
localbuildinfo <- get_build_config
let pkg_descr0 = localPkgDescr localbuildinfo
--pkg_descr0 <- get_pkg_descr (get_verbose flags)
sanityCheckHookedBuildInfo pkg_descr0 pbi
let pkg_descr = updatePackageDescription pbi pkg_descr0
-- TODO: should we write the modified package descr back to the
-- localbuildinfo?
cmd_hook hooks args pkg_descr localbuildinfo hooks flags
post_hook hooks args flags pkg_descr localbuildinfo
sanityCheckHookedBuildInfo :: PackageDescription -> HookedBuildInfo -> IO ()
sanityCheckHookedBuildInfo PackageDescription { library = Nothing } (Just _,_)
= die $ "The buildinfo contains info for a library, "
++ "but the package does not have a library."
sanityCheckHookedBuildInfo pkg_descr (_, hookExes)
| not (null nonExistant)
= die $ "The buildinfo contains info for an executable called '"
++ head nonExistant ++ "' but the package does not have a "
++ "executable with that name."
where
pkgExeNames = nub (map exeName (executables pkg_descr))
hookExeNames = nub (map fst hookExes)
nonExistant = hookExeNames \\ pkgExeNames
sanityCheckHookedBuildInfo _ _ = return ()
getBuildConfig :: UserHooks -> Verbosity -> FilePath -> IO LocalBuildInfo
getBuildConfig hooks verbosity distPref = do
lbi_wo_programs <- getPersistBuildConfig distPref
-- Restore info about unconfigured programs, since it is not serialized
let lbi = lbi_wo_programs {
withPrograms = restoreProgramConfiguration
(builtinPrograms ++ hookedPrograms hooks)
(withPrograms lbi_wo_programs)
}
case pkgDescrFile lbi of
Nothing -> return lbi
Just pkg_descr_file -> do
outdated <- checkPersistBuildConfigOutdated distPref pkg_descr_file
if outdated
then reconfigure pkg_descr_file lbi
else return lbi
where
reconfigure :: FilePath -> LocalBuildInfo -> IO LocalBuildInfo
reconfigure pkg_descr_file lbi = do
notice verbosity $ pkg_descr_file ++ " has been changed. "
++ "Re-configuring with most recently used options. "
++ "If this fails, please run configure manually.\n"
let cFlags = configFlags lbi
let cFlags' = cFlags {
-- Since the list of unconfigured programs is not serialized,
-- restore it to the same value as normally used at the beginning
-- of a conigure run:
configPrograms = restoreProgramConfiguration
(builtinPrograms ++ hookedPrograms hooks)
(configPrograms cFlags),
-- Use the current, not saved verbosity level:
configVerbosity = Flag verbosity
}
configureAction hooks cFlags' (extraConfigArgs lbi)
-- --------------------------------------------------------------------------
-- Cleaning
clean :: PackageDescription -> CleanFlags -> IO ()
clean pkg_descr flags = do
let distPref = fromFlag $ cleanDistPref flags
notice verbosity "cleaning..."
maybeConfig <- if fromFlag (cleanSaveConf flags)
then maybeGetPersistBuildConfig distPref
else return Nothing
-- remove the whole dist/ directory rather than tracking exactly what files
-- we created in there.
chattyTry "removing dist/" $ do
exists <- doesDirectoryExist distPref
when exists (removeDirectoryRecursive distPref)
-- Any extra files the user wants to remove
mapM_ removeFileOrDirectory (extraTmpFiles pkg_descr)
-- If the user wanted to save the config, write it back
maybe (return ()) (writePersistBuildConfig distPref) maybeConfig
where
removeFileOrDirectory :: FilePath -> IO ()
removeFileOrDirectory fname = do
isDir <- doesDirectoryExist fname
isFile <- doesFileExist fname
if isDir then removeDirectoryRecursive fname
else if isFile then removeFile fname
else return ()
verbosity = fromFlag (cleanVerbosity flags)
-- --------------------------------------------------------------------------
-- Default hooks
-- | Hooks that correspond to a plain instantiation of the
-- \"simple\" build system
simpleUserHooks :: UserHooks
simpleUserHooks =
emptyUserHooks {
confHook = configure,
postConf = finalChecks,
buildHook = defaultBuildHook,
copyHook = \desc lbi _ f -> install desc lbi f, -- has correct 'copy' behavior with params
testHook = defaultTestHook,
benchHook = defaultBenchHook,
instHook = defaultInstallHook,
sDistHook = \p l h f -> sdist p l f srcPref (allSuffixHandlers h),
cleanHook = \p _ _ f -> clean p f,
hscolourHook = \p l h f -> hscolour p l (allSuffixHandlers h) f,
haddockHook = \p l h f -> haddock p l (allSuffixHandlers h) f,
regHook = defaultRegHook,
unregHook = \p l _ f -> unregister p l f
}
where
finalChecks _args flags pkg_descr lbi =
checkForeignDeps distPref pkg_descr lbi (lessVerbose verbosity)
where
distPref = fromFlag (configDistPref flags)
verbosity = fromFlag (configVerbosity flags)
-- | Basic autoconf 'UserHooks':
--
-- * 'postConf' runs @.\/configure@, if present.
--
-- * the pre-hooks 'preBuild', 'preClean', 'preCopy', 'preInst',
-- 'preReg' and 'preUnreg' read additional build information from
-- /package/@.buildinfo@, if present.
--
-- Thus @configure@ can use local system information to generate
-- /package/@.buildinfo@ and possibly other files.
autoconfUserHooks :: UserHooks
autoconfUserHooks
= simpleUserHooks
{
postConf = defaultPostConf,
preBuild = readHook buildVerbosity,
preClean = readHook cleanVerbosity,
preCopy = readHook copyVerbosity,
preInst = readHook installVerbosity,
preHscolour = readHook hscolourVerbosity,
preHaddock = readHook haddockVerbosity,
preReg = readHook regVerbosity,
preUnreg = readHook regVerbosity
}
where defaultPostConf :: Args -> ConfigFlags -> PackageDescription -> LocalBuildInfo -> IO ()
defaultPostConf args flags pkg_descr lbi
= do let verbosity = fromFlag (configVerbosity flags)
noExtraFlags args
confExists <- doesFileExist "configure"
if confExists
then runConfigureScript verbosity
backwardsCompatHack flags lbi
else die "configure script not found."
pbi <- getHookedBuildInfo verbosity
sanityCheckHookedBuildInfo pkg_descr pbi
let pkg_descr' = updatePackageDescription pbi pkg_descr
postConf simpleUserHooks args flags pkg_descr' lbi
backwardsCompatHack = False
readHook :: (a -> Flag Verbosity) -> Args -> a -> IO HookedBuildInfo
readHook get_verbosity a flags = do
noExtraFlags a
getHookedBuildInfo verbosity
where
verbosity = fromFlag (get_verbosity flags)
runConfigureScript :: Verbosity -> Bool -> ConfigFlags -> LocalBuildInfo
-> IO ()
runConfigureScript verbosity backwardsCompatHack flags lbi = do
env <- getEnvironment
let programConfig = withPrograms lbi
(ccProg, ccFlags) <- configureCCompiler verbosity programConfig
-- The C compiler's compilation and linker flags (e.g.
-- "C compiler flags" and "Gcc Linker flags" from GHC) have already
-- been merged into ccFlags, so we set both CFLAGS and LDFLAGS
-- to ccFlags
-- We don't try and tell configure which ld to use, as we don't have
-- a way to pass its flags too
let env' = appendToEnvironment ("CFLAGS", unwords ccFlags)
env
args' = args ++ ["--with-gcc=" ++ ccProg]
handleNoWindowsSH $
rawSystemExitWithEnv verbosity "sh" args' env'
where
args = "configure" : configureArgs backwardsCompatHack flags
appendToEnvironment (key, val) [] = [(key, val)]
appendToEnvironment (key, val) (kv@(k, v) : rest)
| key == k = (key, v ++ " " ++ val) : rest
| otherwise = kv : appendToEnvironment (key, val) rest
handleNoWindowsSH action
| buildOS /= Windows
= action
| otherwise
= action
`catchIO` \ioe -> if isDoesNotExistError ioe
then die notFoundMsg
else throwIOIO ioe
notFoundMsg = "The package has a './configure' script. This requires a "
++ "Unix compatibility toolchain such as MinGW+MSYS or Cygwin."
getHookedBuildInfo :: Verbosity -> IO HookedBuildInfo
getHookedBuildInfo verbosity = do
maybe_infoFile <- defaultHookedPackageDesc
case maybe_infoFile of
Nothing -> return emptyHookedBuildInfo
Just infoFile -> do
info verbosity $ "Reading parameters from " ++ infoFile
readHookedBuildInfo verbosity infoFile
defaultTestHook :: PackageDescription -> LocalBuildInfo
-> UserHooks -> TestFlags -> IO ()
defaultTestHook pkg_descr localbuildinfo _ flags =
test pkg_descr localbuildinfo flags
defaultBenchHook :: Args -> PackageDescription -> LocalBuildInfo
-> UserHooks -> BenchmarkFlags -> IO ()
defaultBenchHook args pkg_descr localbuildinfo _ flags =
bench args pkg_descr localbuildinfo flags
defaultInstallHook :: PackageDescription -> LocalBuildInfo
-> UserHooks -> InstallFlags -> IO ()
defaultInstallHook pkg_descr localbuildinfo _ flags = do
let copyFlags = defaultCopyFlags {
copyDistPref = installDistPref flags,
copyDest = toFlag NoCopyDest,
copyVerbosity = installVerbosity flags
}
install pkg_descr localbuildinfo copyFlags
let registerFlags = defaultRegisterFlags {
regDistPref = installDistPref flags,
regInPlace = installInPlace flags,
regPackageDB = installPackageDB flags,
regVerbosity = installVerbosity flags
}
when (hasLibs pkg_descr) $ register pkg_descr localbuildinfo registerFlags
defaultBuildHook :: PackageDescription -> LocalBuildInfo
-> UserHooks -> BuildFlags -> IO ()
defaultBuildHook pkg_descr localbuildinfo hooks flags =
build pkg_descr localbuildinfo flags (allSuffixHandlers hooks)
defaultRegHook :: PackageDescription -> LocalBuildInfo
-> UserHooks -> RegisterFlags -> IO ()
defaultRegHook pkg_descr localbuildinfo _ flags =
if hasLibs pkg_descr
then register pkg_descr localbuildinfo flags
else setupMessage verbosity
"Package contains no library to register:" (packageId pkg_descr)
where verbosity = fromFlag (regVerbosity flags)
|
IreneKnapp/Faction
|
libfaction/Distribution/Simple.hs
|
Haskell
|
bsd-3-clause
| 28,933
|
-- 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 NoRebindableSyntax #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Time.GA.Rules
( rules
) where
import Data.Text (Text)
import Prelude
import Duckling.Dimensions.Types
import Duckling.Duration.Helpers (isGrain)
import Duckling.Numeral.Helpers (parseInt)
import Duckling.Regex.Types
import Duckling.Time.Helpers
import Duckling.Types
import qualified Duckling.Ordinal.Types as TOrdinal
import qualified Duckling.TimeGrain.Types as TG
ruleArInn :: Rule
ruleArInn = Rule
{ name = "arú inné"
, pattern =
[ regex "ar(ú|u) inn(é|e)"
]
, prod = \_ -> tt . cycleNth TG.Day $ - 2
}
ruleNollaigNaMban :: Rule
ruleNollaigNaMban = Rule
{ name = "Nollaig na mBan"
, pattern =
[ regex "(l(á|a) |an )?nollaig (bheag|na mban)"
]
, prod = \_ -> tt $ monthDay 1 6
}
ruleInniu :: Rule
ruleInniu = Rule
{ name = "inniu"
, pattern =
[ regex "inniu"
]
, prod = \_ -> tt today
}
ruleAnOrdinalCycleINdiaidhTime :: Rule
ruleAnOrdinalCycleINdiaidhTime = Rule
{ name = "an <ordinal> <cycle> i ndiaidh <time>"
, pattern =
[ regex "an"
, dimension Ordinal
, dimension TimeGrain
, regex "(i ndiaidh|tar (é|e)is)"
, dimension Time
]
, prod = \tokens -> case tokens of
(_:Token Ordinal od:Token TimeGrain grain:_:Token Time td:_) ->
tt $ cycleNthAfter True grain (TOrdinal.value od - 1) td
_ -> Nothing
}
ruleInn :: Rule
ruleInn = Rule
{ name = "inné"
, pattern =
[ regex "inn(é|e)"
]
, prod = \_ -> tt . cycleNth TG.Day $ - 1
}
ruleLFhileBrde :: Rule
ruleLFhileBrde = Rule
{ name = "Lá Fhéile Bríde"
, pattern =
[ regex "(l(á|a) )?(fh(e|é)ile|'?le) bh?r(í|i)de"
]
, prod = \_ -> tt $ monthDay 2 1
}
ruleLFhileVailintn :: Rule
ruleLFhileVailintn = Rule
{ name = "Lá Fhéile Vailintín"
, pattern =
[ regex "(l(á|a) )?(fh(e|é)ile|'?le) vailint(í|i)n"
]
, prod = \_ -> tt $ monthDay 2 14
}
ruleTimeSeo :: Rule
ruleTimeSeo = Rule
{ name = "<time> seo"
, pattern =
[ dimension Time
, regex "seo"
]
, prod = \tokens -> case tokens of
(Token Time td:_) ->
tt $ predNth 0 False td
_ -> Nothing
}
ruleTimeSeoChaite :: Rule
ruleTimeSeoChaite = Rule
{ name = "<time> seo chaite"
, pattern =
[ dimension Time
, regex "seo ch?aite"
]
, prod = \tokens -> case tokens of
(Token Time td:_) ->
tt $ predNth (-1) False td
_ -> Nothing
}
ruleTimeSeoChugainn :: Rule
ruleTimeSeoChugainn = Rule
{ name = "<time> seo chugainn"
, pattern =
[ Predicate isNotLatent
, regex "seo (chugainn|at(a|á) ag teacht)"
]
, prod = \tokens -> case tokens of
(Token Time td:_) ->
tt $ predNth 0 True td
_ -> Nothing
}
ruleAmrach :: Rule
ruleAmrach = Rule
{ name = "amárach"
, pattern =
[ regex "am(á|a)rach"
]
, prod = \_ -> tt $ cycleNth TG.Day 1
}
ruleYearLatent2 :: Rule
ruleYearLatent2 = Rule
{ name = "year (latent)"
, pattern =
[ Predicate $ isIntegerBetween 2101 10000
]
, prod = \tokens -> case tokens of
(token:_) -> do
n <- getIntValue token
tt . mkLatent $ year n
_ -> Nothing
}
ruleOrdinalRithe :: Rule
ruleOrdinalRithe = Rule
{ name = "<ordinal> ráithe"
, pattern =
[ dimension Ordinal
, Predicate $ isGrain TG.Quarter
]
, prod = \tokens -> case tokens of
(token:_) -> do
n <- getIntValue token
tt . cycleNthAfter True TG.Quarter (n - 1) $
cycleNth TG.Year 0
_ -> Nothing
}
ruleAnnaCycleRoimhTime :: Rule
ruleAnnaCycleRoimhTime = Rule
{ name = "(an|na) <cycle> roimh <time>"
, pattern =
[ regex "the"
, dimension TimeGrain
, regex "roimh"
, dimension Time
]
, prod = \tokens -> case tokens of
(_:Token TimeGrain grain:_:Token Time td:_) ->
tt $ cycleNthAfter False grain (-1) td
_ -> Nothing
}
ruleCycleShin :: Rule
ruleCycleShin = Rule
{ name = "<cycle> ó shin"
, pattern =
[ dimension TimeGrain
, regex "(ó|o) shin"
]
, prod = \tokens -> case tokens of
(Token TimeGrain grain:_) ->
tt . cycleNth grain $ 1
_ -> Nothing
}
ruleDdmm :: Rule
ruleDdmm = Rule
{ name = "dd/mm"
, pattern =
[ regex "(3[01]|[12]\\d|0?[1-9])/(0?[1-9]|1[0-2])"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (m1:m2:_)):_) -> do
m <- parseInt m2
d <- parseInt m1
tt $ monthDay m d
_ -> Nothing
}
ruleIGceannCycle :: Rule
ruleIGceannCycle = Rule
{ name = "i gceann <cycle>"
, pattern =
[ regex "(i|faoi) g?ch?eann"
, Predicate $ isIntegerBetween 1 9999
, dimension TimeGrain
]
, prod = \tokens -> case tokens of
(_:Token Ordinal od:Token TimeGrain grain:_) ->
tt $ cycleN True grain (TOrdinal.value od)
_ -> Nothing
}
ruleAnCycleDeTime :: Rule
ruleAnCycleDeTime = Rule
{ name = "an <cycle> de <time>"
, pattern =
[ regex "an"
, dimension TimeGrain
, regex "d[e']"
, dimension Time
]
, prod = \tokens -> case tokens of
(_:Token TimeGrain grain:_:Token Time td:_) ->
tt $ cycleNthAfter True grain 0 td
_ -> Nothing
}
ruleDayofmonthordinalNamedmonth :: Rule
ruleDayofmonthordinalNamedmonth = Rule
{ name = "<day-of-month>(ordinal) <named-month>"
, pattern =
[ Predicate isDOMOrdinal
, Predicate isAMonth
]
, prod = \tokens -> case tokens of
(token:Token Time td:_) -> Token Time <$> intersectDOM td token
_ -> Nothing
}
ruleIntersectBy :: Rule
ruleIntersectBy = Rule
{ name = "intersect by \",\""
, pattern =
[ Predicate isNotLatent
, regex ","
, Predicate isNotLatent
]
, prod = \tokens -> case tokens of
(Token Time td1:_:Token Time td2:_) ->
Token Time <$> intersect td1 td2
_ -> Nothing
}
ruleOrdinalRitheYear :: Rule
ruleOrdinalRitheYear = Rule
{ name = "<ordinal> ráithe <year>"
, pattern =
[ dimension Ordinal
, Predicate $ isGrain TG.Quarter
, dimension Time
]
, prod = \tokens -> case tokens of
(Token Ordinal od:_:Token Time td:_) ->
tt $ cycleNthAfter False TG.Quarter (TOrdinal.value od - 1) td
_ -> Nothing
}
ruleCycleInniu :: Rule
ruleCycleInniu = Rule
{ name = "<cycle> ó inniu"
, pattern =
[ Predicate $ isIntegerBetween 1 9999
, dimension TimeGrain
, regex "(ó|o)(n l(á|a) (at(á|a) )?)?inniu"
]
, prod = \tokens -> case tokens of
(token:Token TimeGrain grain:_) -> do
v <- getIntValue token
tt $ cycleN True grain v
_ -> Nothing
}
ruleOrdinalCycleINdiaidhTime :: Rule
ruleOrdinalCycleINdiaidhTime = Rule
{ name = "<ordinal> <cycle> i ndiaidh <time>"
, pattern =
[ dimension Ordinal
, dimension TimeGrain
, regex "(i ndiaidh|tar (é|e)is)"
, dimension Time
]
, prod = \tokens -> case tokens of
(Token Ordinal od:Token TimeGrain grain:_:Token Time td:_) ->
tt $ cycleNthAfter True grain (TOrdinal.value od - 1) td
_ -> Nothing
}
ruleAnDayofmonthOrdinal :: Rule
ruleAnDayofmonthOrdinal = Rule
{ name = "an <day-of-month> (ordinal)"
, pattern =
[ regex "an|na"
, Predicate isDOMOrdinal
]
, prod = \tokens -> case tokens of
(_:token:_) -> do
n <- getIntValue token
tt $ dayOfMonth n
_ -> Nothing
}
ruleIntersect :: Rule
ruleIntersect = Rule
{ name = "intersect"
, pattern =
[ Predicate isNotLatent
, Predicate isNotLatent
]
, prod = \tokens -> case tokens of
(Token Time td1:Token Time td2:_) ->
Token Time <$> intersect td1 td2
_ -> Nothing
}
ruleAnOrdinalCycleDeTime :: Rule
ruleAnOrdinalCycleDeTime = Rule
{ name = "an <ordinal> <cycle> de <time>"
, pattern =
[ regex "an"
, dimension Ordinal
, dimension TimeGrain
, regex "d[e']"
, dimension Time
]
, prod = \tokens -> case tokens of
(_:Token Ordinal od:Token TimeGrain grain:_:Token Time td:_) ->
tt $ cycleNthAfter True grain (TOrdinal.value od - 1) td
_ -> Nothing
}
ruleLNaNaithreacha :: Rule
ruleLNaNaithreacha = Rule
{ name = "Lá na nAithreacha"
, pattern =
[ regex "l(á|a) na naithreacha"
]
, prod = \_ -> tt $ nthDOWOfMonth 2 7 6
}
ruleArAmrach :: Rule
ruleArAmrach = Rule
{ name = "arú amárach"
, pattern =
[ regex "ar(ú|u) am(á|a)rach"
]
, prod = \_ -> tt $ cycleNth TG.Day 2
}
ruleOrdinalCycleDeTime :: Rule
ruleOrdinalCycleDeTime = Rule
{ name = "<ordinal> <cycle> de <time>"
, pattern =
[ dimension Ordinal
, dimension TimeGrain
, regex "d[e']"
, dimension Time
]
, prod = \tokens -> case tokens of
(Token Ordinal od:Token TimeGrain grain:_:Token Time td:_) ->
tt $ cycleNthAfter True grain (TOrdinal.value od - 1) td
_ -> Nothing
}
ruleYyyymmdd :: Rule
ruleYyyymmdd = Rule
{ name = "yyyy-mm-dd"
, pattern =
[ regex "(\\d{2,4})-(0?[1-9]|1[0-2])-(3[01]|[12]\\d|0?[1-9])"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (m1:m2:m3:_)):_) -> do
y <- parseInt m1
m <- parseInt m2
d <- parseInt m3
tt $ yearMonthDay y m d
_ -> Nothing
}
ruleArDate :: Rule
ruleArDate = Rule
{ name = "ar <date>"
, pattern =
[ regex "ar"
, dimension Time
]
, prod = \tokens -> case tokens of
(_:x:_) -> Just x
_ -> Nothing
}
ruleAnNollaig :: Rule
ruleAnNollaig = Rule
{ name = "An Nollaig"
, pattern =
[ regex "(l(á|a) |an )?(nollai?g)"
]
, prod = \_ -> tt $ monthDay 12 25
}
ruleOnANamedday :: Rule
ruleOnANamedday = Rule
{ name = "on a named-day"
, pattern =
[ regex "ar an"
, Predicate isADayOfWeek
]
, prod = \tokens -> case tokens of
(_:x:_) -> Just x
_ -> Nothing
}
ruleYearLatent :: Rule
ruleYearLatent = Rule
{ name = "year (latent)"
, pattern =
[ Predicate $ isIntegerBetween (- 10000) 999
]
, prod = \tokens -> case tokens of
(token:_) -> do
n <- getIntValue token
tt . mkLatent $ year n
_ -> Nothing
}
ruleAnois :: Rule
ruleAnois = Rule
{ name = "anois"
, pattern =
[ regex "anois|(ag an (t-?)?am seo)"
]
, prod = \_ -> tt now
}
ruleLFhilePdraig :: Rule
ruleLFhilePdraig = Rule
{ name = "Lá Fhéile Pádraig"
, pattern =
[ regex "(l(á|a) )?(fh(e|é)ile|'?le) ph?(á|a)draig"
]
, prod = \_ -> tt $ monthDay 3 17
}
ruleAnCycleINdiaidhTime :: Rule
ruleAnCycleINdiaidhTime = Rule
{ name = "an <cycle> i ndiaidh <time>"
, pattern =
[ regex "the"
, dimension TimeGrain
, regex "(i ndiaidh|tar (é|e)is)"
, dimension Time
]
, prod = \tokens -> case tokens of
(_:Token TimeGrain grain:_:Token Time td:_) ->
tt $ cycleNthAfter False grain 1 td
_ -> Nothing
}
ruleDayofmonthOrdinal :: Rule
ruleDayofmonthOrdinal = Rule
{ name = "<day-of-month> (ordinal)"
, pattern =
[ Predicate isDOMOrdinal
]
, prod = \tokens -> case tokens of
(token:_) -> do
n <- getIntValue token
tt . mkLatent $ dayOfMonth n
_ -> Nothing
}
ruleAnCycleSeo :: Rule
ruleAnCycleSeo = Rule
{ name = "an <cycle> seo"
, pattern =
[ regex "an"
, dimension TimeGrain
, regex "seo"
]
, prod = \tokens -> case tokens of
(_:Token TimeGrain grain:_) ->
tt $ cycleNth grain 0
_ -> Nothing
}
ruleAnDayofmonthNonOrdinal :: Rule
ruleAnDayofmonthNonOrdinal = Rule
{ name = "an <day-of-month> (non ordinal)"
, pattern =
[ regex "an|na"
, Predicate isDOMInteger
]
, prod = \tokens -> case tokens of
(_:token:_) -> do
v <- getIntValue token
tt . mkLatent $ dayOfMonth v
_ -> Nothing
}
ruleDNamedday :: Rule
ruleDNamedday = Rule
{ name = "dé named-day"
, pattern =
[ regex "d(é|e)"
, Predicate isADayOfWeek
]
, prod = \tokens -> case tokens of
(_:x:_) -> Just x
_ -> Nothing
}
ruleYear :: Rule
ruleYear = Rule
{ name = "year"
, pattern =
[ Predicate $ isIntegerBetween 1000 2100
]
, prod = \tokens -> case tokens of
(token:_) -> do
v <- getIntValue token
tt $ year v
_ -> Nothing
}
ruleCycleRoimhTime :: Rule
ruleCycleRoimhTime = Rule
{ name = "<cycle> roimh <time>"
, pattern =
[ dimension TimeGrain
, regex "roimhe?"
, dimension Time
]
, prod = \tokens -> case tokens of
(Token TimeGrain grain:_:Token Time td:_) ->
tt $ cycleNthAfter False grain (-1) td
_ -> Nothing
}
ruleAbsorptionOfAfterNamedDay :: Rule
ruleAbsorptionOfAfterNamedDay = Rule
{ name = "absorption of , after named day"
, pattern =
[ Predicate isADayOfWeek
, regex ","
]
, prod = \tokens -> case tokens of
(x:_) -> Just x
_ -> Nothing
}
ruleDdmmyyyy :: Rule
ruleDdmmyyyy = Rule
{ name = "dd/mm/yyyy"
, pattern =
[ regex "(3[01]|[12]\\d|0?[1-9])[-/](0?[1-9]|1[0-2])[/-](\\d{2,4})"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (m1:m2:m3:_)):_) -> do
y <- parseInt m3
m <- parseInt m2
d <- parseInt m1
tt $ yearMonthDay y m d
_ -> Nothing
}
ruleAnNamedday :: Rule
ruleAnNamedday = Rule
{ name = "an named-day"
, pattern =
[ regex "an"
, Predicate isADayOfWeek
]
, prod = \tokens -> case tokens of
(_:x:_) -> Just x
_ -> Nothing
}
ruleDaysOfWeek :: [Rule]
ruleDaysOfWeek = mkRuleDaysOfWeek
[ ( "Monday" , "luai?n|lu\\.?" )
, ( "Tuesday" , "mh?(á|a)irt|m(á|a)?\\.?" )
, ( "Wednesday", "ch?(é|e)adaoin|c(é|e)\\.?" )
, ( "Thursday" , "d(é|e)ardaoin|d(é|e)?\\.?" )
, ( "Friday" , "h?aoine|ao\\.?" )
, ( "Saturday" , "sathai?rn|sa\\.?" )
, ( "Sunday" , "domhnai?[cg]h|do\\.?" )
]
ruleMonths :: [Rule]
ruleMonths = mkRuleMonths
[ ( "January" , "(mh?(í|i) )?(an )?t?ean(á|a)ir|ean\\.?" )
, ( "February" , "(mh?(í|i) )?(na )?feabhra|fea\\.?" )
, ( "March" , "(mh?(í|i) )?(an )?mh?(á|a)rta|m(á|a)r\\.?" )
, ( "April" , "(mh?(í|i) )?(an )?t?aibre(á|a)i?n|abr\\.?" )
, ( "May" , "(mh?(í|i) )?(na )?bh?ealtaine|bea\\.?" )
, ( "June" , "(mh?(í|i) )?(an )?mh?eith(ea|i)mh|mei\\.?" )
, ( "July" , "(mh?(í|i) )?i(ú|u)il|i(ú|u)i\\.?" )
, ( "August" , "(mh?(í|i) )?(na )?l(ú|u)nasa|l(ú|u)n\\.?" )
, ( "September", "(mh?(í|i) )?mh?e(á|a)n f(ó|o)mhair|mef?\\.?")
, ( "October" , "(mh?(í|i) )?(na )?nollai?g|nol\\.?" )
, ( "November" , "(mh?(í|i) )?(na )?samh(ain|na)|sam\\.?" )
, ( "December" , "(mh?(í|i) )?(na )?nollai?g|nol\\.?" )
]
ruleCycleINdiaidhTime :: Rule
ruleCycleINdiaidhTime = Rule
{ name = "<cycle> i ndiaidh <time>"
, pattern =
[ dimension TimeGrain
, regex "(i ndiaidh|tar (é|e)is)"
, dimension Time
]
, prod = \tokens -> case tokens of
(Token TimeGrain grain:_:Token Time td:_) ->
tt $ cycleNthAfter False grain 1 td
_ -> Nothing
}
ruleDayofmonthordinalNamedmonthYear :: Rule
ruleDayofmonthordinalNamedmonthYear = Rule
{ name = "<day-of-month>(ordinal) <named-month> year"
, pattern =
[ Predicate isDOMOrdinal
, Predicate isAMonth
, regex "(\\d{2,4})"
]
, prod = \tokens -> case tokens of
(token:Token Time td:Token RegexMatch (GroupMatch (match:_)):_) -> do
intVal <- parseInt match
dom <- intersectDOM td token
Token Time <$> intersect dom (year intVal)
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleAbsorptionOfAfterNamedDay
, ruleAmrach
, ruleAnCycleDeTime
, ruleAnCycleINdiaidhTime
, ruleAnCycleSeo
, ruleAnDayofmonthNonOrdinal
, ruleAnDayofmonthOrdinal
, ruleAnNamedday
, ruleAnNollaig
, ruleAnOrdinalCycleDeTime
, ruleAnOrdinalCycleINdiaidhTime
, ruleAnnaCycleRoimhTime
, ruleAnois
, ruleArAmrach
, ruleArDate
, ruleArInn
, ruleCycleINdiaidhTime
, ruleCycleInniu
, ruleCycleRoimhTime
, ruleCycleShin
, ruleDNamedday
, ruleDayofmonthOrdinal
, ruleDayofmonthordinalNamedmonth
, ruleDayofmonthordinalNamedmonthYear
, ruleDdmm
, ruleDdmmyyyy
, ruleIGceannCycle
, ruleInn
, ruleInniu
, ruleIntersect
, ruleIntersectBy
, ruleLFhileBrde
, ruleLFhilePdraig
, ruleLFhileVailintn
, ruleLNaNaithreacha
, ruleNollaigNaMban
, ruleOnANamedday
, ruleOrdinalCycleDeTime
, ruleOrdinalCycleINdiaidhTime
, ruleOrdinalRithe
, ruleOrdinalRitheYear
, ruleTimeSeo
, ruleTimeSeoChaite
, ruleTimeSeoChugainn
, ruleYear
, ruleYearLatent
, ruleYearLatent2
, ruleYyyymmdd
]
++ ruleDaysOfWeek
++ ruleMonths
|
facebookincubator/duckling
|
Duckling/Time/GA/Rules.hs
|
Haskell
|
bsd-3-clause
| 16,978
|
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE DoAndIfThenElse #-}
----------------------------------------------------------------------------
-- |
-- Module : Language.Core.Interpreter.Acknowledge
-- Copyright : (c) Carlos López-Camey, University of Freiburg
-- License : BSD-3
--
-- Maintainer : c.lopez@kmels.net
-- Stability : stable
--
--
-- When the interpreter reads a module, it should acknowledge type and value definitions
-- and save them in the heap, before going on to lazily evaluation.
-----------------------------------------------------------------------------
module Language.Core.Interpreter.Acknowledge(acknowledgeModule,acknowledgeTypes,acknowledgeVdefgs,acknowledgeVdefg) where
import DART.CmdLine(beVerboseM,showIncludeDefinitionM)
import DART.DARTSettings
import Language.Core.Core
import Language.Core.Interpreter.Structures
import Language.Core.Util
import Language.Core.Vdefg(vdefId,vdefgNames,vdefQualId)
-- | Given a parsed module, recognize type constructors and value definitions
-- and save them in the heap
acknowledgeModule :: Module -> IM Env
acknowledgeModule modl@(Module mname tdefs vdefgs) = do
tycons_env <- acknowledgeTypes tdefs -- type constructors
vdefs_env <- acknowledgeVdefgs vdefgs -- value definitions
--io . putStrLn $ "Types of: " ++ show mname
--mapM (io . putStrLn) $ map fst tycons_env
return $ tycons_env ++ vdefs_env
-- | Given a module, recognize type constructors and put them in the heap
-- so that we can build values for custom types afterwards.
acknowledgeTypes :: [Tdef] -> IM Env
acknowledgeTypes tdefs = mapM acknowledgeType tdefs >>= return . concat
-- | Given a data type or a newtype definition, memorize their type constructors,
-- create an environment variable for each of them and return an environment that holds
-- all the created heap references
acknowledgeType :: Tdef -> IM Env
acknowledgeType tdef@(Data qdname@(_,dname) tbinds cdefs) =
do
let type_name = zDecodeQualified qdname
type_constructors = map mkDataCon cdefs
--io . putStrLn $ "Type constructors: " ++ show type_constructors
--printTypesCons type_constructors
beVerboseM $ "Acknowledging type " ++ type_name
tyCon_refs <- mapM insertTyCon type_constructors
-- the sum type itself
sumtype_ref <- mkDataTypeRef type_constructors type_name
-- make overall env
return (sumtype_ref:tyCon_refs)
where
printTypesCons :: [DataCon] -> IM ()
printTypesCons [] = return ()
printTypesCons ((MkDataCon id tys _):ds) = do
io . putStrLn $ id ++ " expects " ++ show tys
printTypesCons ds
mkDataTypeRef :: [DataCon] -> Id -> IM HeapReference
mkDataTypeRef cons tname = memorize (mkVal . SumType $ cons) tname
mkDataCon :: Cdef -> DataCon
mkDataCon tcon@(Constr qcname tbinds' datacon_signature) =
let
no_types_applied = []
in
MkDataCon (zDecodeQualified qcname) datacon_signature no_types_applied
insertTyCon :: DataCon -> IM HeapReference
insertTyCon tyCon@(MkDataCon tyConName tys _) = memorize (mkVal $ TyConApp tyCon []) (tyConName)
-- | Given a module, recognize all of its value definitions, functions, and put them in the heap so that we can evaluate them when required.
acknowledgeVdefgs :: [Vdefg] -> IM Env
acknowledgeVdefgs vdefgs = acknowledgeVdefgs' vdefgs []
where
acknowledgeVdefgs' :: [Vdefg] -> Env -> IM Env
acknowledgeVdefgs' [vdefg] env = acknowledgeVdefg vdefg env >>= return . flip (++) env
acknowledgeVdefgs' (v:vs) env = acknowledgeVdefg v env >>= \e -> acknowledgeVdefgs' vs (e ++ env)
-- | Acknowledges a generic value definition
acknowledgeVdefg :: Vdefg -> Env -> IM Env
acknowledgeVdefg (Nonrec vdef) env =
let mkList x = [x]
in
showIncludeDefinitionM vdef >> newAddress >>= storeVdef vdef env >>= return . mkList
--beVerboseM $ "Acknowledging non-recursive definition: " ++ vdefQualId vdef
--sequence [(flip acknowledgeVdef env) vdef]
acknowledgeVdefg v@(Rec vdefs) env = do
beVerboseM $ "Acknowledging recursive definitions: " ++ (show . vdefgNames $ v)
--beVerboseM $ "with env: " ++ show (map fst env)
addresses <- allocate $ length vdefs
let ids = map vdefId vdefs
let env' = env ++ zip ids addresses
let vdefsWithAddress = zip vdefs addresses
beVerboseM $ "Made extended environment: " ++ show (map fst env')
mapM (\(vdef,address) -> storeVdef vdef env' address) vdefsWithAddress
-- | Stores a value definition in the given address.
storeVdef :: Vdef -> Env -> HeapAddress -> IM HeapReference
storeVdef (Vdef (qid, ty, exp)) env address= do
beVerboseM $ "Acknowledging value definition " ++ zDecodeQualified qid
--beVerboseM $ "\twith env = " ++ show (map fst env)
--beVerboseM $ "\tin address = " ++ show address
store address (Left $ Thunk exp env) (zDecodeQualified qid)
|
kmels/dart-haskell
|
src/Language/Core/Interpreter/Acknowledge.hs
|
Haskell
|
bsd-3-clause
| 4,932
|
{-# LANGUAGE PackageImports #-}
import "ouch-web" Application (getApplicationDev)
import Network.Wai.Handler.Warp
(runSettings, defaultSettings, settingsPort)
import Control.Concurrent (forkIO)
import System.Directory (doesFileExist, removeFile)
import System.Exit (exitSuccess)
import Control.Concurrent (threadDelay)
main :: IO ()
main = do
putStrLn "Starting devel application"
(port, app) <- getApplicationDev
forkIO $ runSettings defaultSettings
{ settingsPort = port
} app
loop
loop :: IO ()
loop = do
threadDelay 100000
e <- doesFileExist "yesod-devel/devel-terminate"
if e then terminateDevel else loop
terminateDevel :: IO ()
terminateDevel = exitSuccess
|
mkrauskopf/ouch-web
|
devel.hs
|
Haskell
|
bsd-3-clause
| 709
|
module Doukaku.DiceTest (tests) where
import Distribution.TestSuite
import Doukaku.TestHelper
import qualified Doukaku.Dice as Dice
tests :: IO [Test]
tests = createTests $ newDoukakuTest {
tsvPath = "test/Doukaku/dice.tsv"
, solve = Dice.solve
}
|
hiratara/doukaku-past-questions-advent-2013
|
test/Doukaku/DiceTest.hs
|
Haskell
|
bsd-3-clause
| 255
|
{-# LANGUAGE OverloadedStrings #-}
module Network.Monitoring.Riemann (
module Network.Monitoring.Riemann.Types,
module Data.Int,
Client, makeClient,
sendEvent, sendEvent'
{-, sendEvent'-}
) where
import Network.Monitoring.Riemann.Types
import Data.Default
import Data.Int
import Data.ProtocolBuffers
import Data.Serialize.Put
import Data.Time.Clock
import Data.Time.Clock.POSIX
import Control.Applicative
import qualified Control.Error as Error
import Control.Exception
import Control.Lens
import qualified Control.Monad as CM
import qualified Control.Monad.IO.Class as CMIC
import Control.Monad.Trans.Either
import qualified Control.Monad.Trans.Except as Except
import Network.Socket hiding (recv, recvFrom, send,
sendTo)
import Network.Socket.ByteString
{-%
In brief, a Riemann client has two operating conditions: (a) as a
decoration of *real* code or (b) as a component of self-reflecting
system component. In 95% of cases the client will be used for (a), so
that's the easiest way to use the client.
An (a)-style Riemann client should allow for liberal *decoration* of
code with monitoring keys. These decorations should trivially reduce
to nops if there is no connection to a Riemann server and they should
silently ignore all server errors. The (a)-style Riemann decorations
should never slow real code and thus must either be very, very fast or
asynchronous.
As a tradeoff, we can never be sure that *all* (a)-style decorations
fire and are observed by a Riemann server. Neither the client or the
server can take note of or be affected by packet failure.
A (b)-style Riemann client should allow for smart load balancing. It
should be able to guarantee connectivity to the Riemann server and
failover along with the server should Riemann ever die or become
partitioned. (To this end, there's some need for pools of Riemann
servers, but this may be non-critical.) Riemann (b)-style interactions
also include querying the Riemann server --- so we'll need a query
combinator language.
-}
{-%
API Design
----------
Basic events ought to be generated very easily. Sane defaults ought to
be built-in---we shouldn't be specifying the host in every decorated
call, we shouldn't have any concept of the current time when we
decorate an action. To this end the Monoid instances for `Event`s,
`State`s, `Msg`s, and `Query`s are designed to either grow or be
overridden to the right (using lots of `Last` newtypes over maybes and
inner `(<>)` applications).
The Client also should be defaulted at as high a level as possible.
e.g.
```
withClient :: Client -> IO a -> IO a
withDefaultEvent :: Event -> IO a -> IO a
withEventTiming :: IO a -> IO a
withHostname :: Text -> IO a -> IO a
```
-}
{-%
Implementation
--------------
There are roughly two independent factors for library design. First,
we can use UDP or TCP---Riemann size limits UDP datagrams, but the
limit is high (16 mb by default), so there's theoretically a corner
case there but it's a fair bet that we won't hit it---and secondly we
can deliver them in the main thread or asynchronously via a concurrent
process.
There's a tradeoff here between throughput and assurance. Asynch+UDP
has the highest throughput, while Synch+TCP has the greatest
assurance. We'll optimize for (a)-type decoration via Asynch+UDP.
Can we do the same and optimize (b)-type calls as Synch+TCP? Probably.
-}
{-%
Syntax
------
riemann $ ev "<service>" <metric> & tags <>~ "foo"
-}
data Client = UDP (Maybe (Socket, AddrInfo))
deriving (Show, Eq)
type Hostname = String
type Port = Int
-- | Attempts to bind a UDP client at the passed 'Hostname' and
-- 'Port'. Failures are silently ignored---failure in monitoring
-- should not cause an application failure...
makeClient :: Hostname -> Port -> IO Client
makeClient hn po = UDP . Error.rightMay <$> sock
where sock :: IO (Either SomeException (Socket, AddrInfo))
sock =
try $ do addrs <- getAddrInfo
(Just $ defaultHints {
addrFlags = [AI_NUMERICSERV] })
(Just hn)
(Just $ show po)
case addrs of
[] -> fail "No accessible addresses"
(addy:_) -> do
s <- socket (addrFamily addy)
Datagram
(addrProtocol addy)
return (s, addy)
-- | Attempts to forward an event to a client. Fails silently.
sendEvent :: CMIC.MonadIO m => Client -> Event -> m ()
sendEvent c = CMIC.liftIO . CM.void . runEitherT . sendEvent' c
-- | Attempts to forward an event to a client. If it fails, it'll
-- return an 'IOException' in the 'Either'.
sendEvent' :: Client -> Event -> EitherT IOException IO ()
sendEvent' (UDP Nothing) _ = return ()
sendEvent' (UDP (Just (s, addy))) e = Error.tryIO $ do
current <- getCurrentTime
let now = round (utcTimeToPOSIXSeconds current)
let msg = def & events .~ [e & time ?~ now]
CM.void $ sendTo s (runPut $ encodeMessage msg) (addrAddress addy)
|
telser/riemann-hs
|
src/Network/Monitoring/Riemann.hs
|
Haskell
|
mit
| 5,379
|
module Codec.Encryption.Historical.XOR.Analysis
( crack
, crack_key_length
)
where
-- Module to Analyse
import Codec.Encryption.Historical.XOR.Implementation
import Codec.Encryption.Historical.Utilities.Histogram
import Data.Ord
import Data.List
import Data.List.Split
import Control.Arrow
import qualified Data.ByteString.Internal as B
-- TODO: Take advantage of some of the properties of XOR to crack this better
crack :: Int -> Histogram Char -> String -> String
crack mkl h cypher = xor_decode key cypher
where
key = map (crackPart h) chopped
chopped = transpose $ chunksOf klen cypher
klen = crack_key_length mkl h cypher
crackPart :: Histogram Char -> String -> Char
crackPart h cypher = fst $ head $ sortBy (comparing best) goodSolutions
where
best :: (Char, Histogram Char) -> Float
best = histogramDelta h . snd
goodSolutions :: [(Char, Histogram Char)]
goodSolutions = filter ((>20) . length . snd) solutions
solutions :: [(Char, Histogram Char)]
solutions = map ((id &&& histogram . singletonDecode cypher) . B.w2c) [minBound..maxBound]
singletonDecode :: String -> Char -> String
singletonDecode cypher c = xor_decode [c] cypher
crack_key_length :: Int -> Histogram a -> String -> Int
crack_key_length keyLen h s = head $ sortBy (comparing best) [1..keyLen]
where
hv = histogramVar h
best :: Int -> (Float, Int)
best n = (abs (hv - compute n), n)
compute :: Int -> Float
compute n = average
$ map (histogramVar . histogram)
$ transpose
$ chunksOf n s
average :: [Float] -> Float
average l = sum l / fromIntegral (length l)
|
beni55/Historical-Cryptography
|
Codec/Encryption/Historical/XOR/Analysis.hs
|
Haskell
|
mit
| 1,672
|
module Command.TyProjection
( tyValue
, tyEither
, tyAddress
, tyPublicKey
, tyTxOut
, tyAddrStakeDistr
, tyFilePath
, tyInt
, tyWord
, tyWord32
, tyByte
, tySecond
, tyBool
, tyScriptVersion
, tyCoin
, tyCoinPortion
, tyStakeholderId
, tyAddrDistrPart
, tyEpochIndex
, tyHash
, tyBlockVersion
, tySoftwareVersion
, tyBlockVersionModifier
, tyProposeUpdateSystem
, tySystemTag
, tyApplicationName
, tyString
) where
import Universum
import Data.Scientific (Scientific, floatingOrInteger,
toBoundedInteger, toRealFloat)
import Data.Time.Units (Microsecond, TimeUnit, convertUnit,
fromMicroseconds)
import Serokell.Data.Memory.Units (Byte, fromBytes)
import Pos.Chain.Txp (TxOut (..))
import Pos.Chain.Update (ApplicationName (..), BlockVersion,
BlockVersionModifier (..), SoftwareVersion,
SystemTag (..))
import Pos.Core (AddrStakeDistribution (..), Address, Coin,
CoinPortion, EpochIndex, ScriptVersion, StakeholderId,
mkCoin, unsafeCoinPortionFromDouble, unsafeGetCoin)
import Pos.Crypto (AHash (..), Hash, PublicKey)
import Lang.Argument (TyProjection (..), TypeName (..))
import Lang.Value (AddrDistrPart (..), ProposeUpdateSystem (..),
Value (..), _ValueAddrDistrPart,
_ValueAddrStakeDistribution, _ValueAddress,
_ValueBlockVersion, _ValueBlockVersionModifier,
_ValueBool, _ValueFilePath, _ValueHash, _ValueNumber,
_ValueProposeUpdateSystem, _ValuePublicKey,
_ValueSoftwareVersion, _ValueStakeholderId, _ValueString,
_ValueTxOut)
tyValue :: TyProjection Value
tyValue = TyProjection "Value" Just
infixr `tyEither`
tyEither :: TyProjection a -> TyProjection b -> TyProjection (Either a b)
tyEither tpa tpb = TyProjection
{ tpTypeName = TypeNameEither (tpTypeName tpa) (tpTypeName tpb)
, tpMatcher = \v ->
Left <$> tpMatcher tpa v <|>
Right <$> tpMatcher tpb v
}
tyAddress :: TyProjection Address
tyAddress = TyProjection "Address" (preview _ValueAddress)
tyPublicKey :: TyProjection PublicKey
tyPublicKey = TyProjection "PublicKey" (preview _ValuePublicKey)
tyTxOut :: TyProjection TxOut
tyTxOut = TyProjection "TxOut" (preview _ValueTxOut)
tyAddrStakeDistr :: TyProjection AddrStakeDistribution
tyAddrStakeDistr = TyProjection "AddrStakeDistribution" (preview _ValueAddrStakeDistribution)
tyFilePath :: TyProjection FilePath
tyFilePath = TyProjection "FilePath" (preview _ValueFilePath)
tyInt :: TyProjection Int
tyInt = TyProjection "Int" (toBoundedInteger <=< preview _ValueNumber)
tyWord :: TyProjection Word
tyWord = TyProjection "Word" (toBoundedInteger <=< preview _ValueNumber)
tyWord32 :: TyProjection Word32
tyWord32 = TyProjection "Word32" (toBoundedInteger <=< preview _ValueNumber)
tyByte :: TyProjection Byte
tyByte = fromBytes <$> TyProjection "Byte" (sciToInteger <=< preview _ValueNumber)
sciToInteger :: Scientific -> Maybe Integer
sciToInteger = either (const Nothing) Just . floatingOrInteger @Double @Integer
tySecond :: forall a . TimeUnit a => TyProjection a
tySecond =
convertUnit . (fromMicroseconds . fromIntegral . (*) 1000000 :: Int -> Microsecond) <$>
TyProjection "Second" (toBoundedInteger <=< preview _ValueNumber)
tyScriptVersion :: TyProjection ScriptVersion
tyScriptVersion = TyProjection "ScriptVersion" (toBoundedInteger <=< preview _ValueNumber)
tyBool :: TyProjection Bool
tyBool = TyProjection "Bool" (preview _ValueBool)
-- | Small hack to use 'toBoundedInteger' for 'Coin'.
newtype PreCoin = PreCoin { getPreCoin :: Word64 }
deriving (Eq, Ord, Num, Enum, Real, Integral)
instance Bounded PreCoin where
minBound = PreCoin . unsafeGetCoin $ minBound
maxBound = PreCoin . unsafeGetCoin $ maxBound
fromPreCoin :: PreCoin -> Coin
fromPreCoin = mkCoin . getPreCoin
tyCoin :: TyProjection Coin
tyCoin = fromPreCoin <$> TyProjection "Coin" (toBoundedInteger <=< preview _ValueNumber)
coinPortionFromDouble :: Double -> Maybe CoinPortion
coinPortionFromDouble a
| a >= 0, a <= 1 = Just $ unsafeCoinPortionFromDouble a
| otherwise = Nothing
tyCoinPortion :: TyProjection CoinPortion
tyCoinPortion = TyProjection "CoinPortion" (coinPortionFromDouble . toRealFloat <=< preview _ValueNumber)
tyStakeholderId :: TyProjection StakeholderId
tyStakeholderId = TyProjection "StakeholderId" (preview _ValueStakeholderId)
tyAddrDistrPart :: TyProjection AddrDistrPart
tyAddrDistrPart = TyProjection "AddrDistrPart" (preview _ValueAddrDistrPart)
tyEpochIndex :: TyProjection EpochIndex
tyEpochIndex = TyProjection "EpochIndex" (toBoundedInteger <=< preview _ValueNumber)
tyHash :: TyProjection (Hash a)
tyHash = getAHash <$> TyProjection "Hash" (preview _ValueHash)
tyBlockVersion :: TyProjection BlockVersion
tyBlockVersion = TyProjection "BlockVersion" (preview _ValueBlockVersion)
tySoftwareVersion :: TyProjection SoftwareVersion
tySoftwareVersion = TyProjection "SoftwareVersion" (preview _ValueSoftwareVersion)
tyBlockVersionModifier :: TyProjection BlockVersionModifier
tyBlockVersionModifier = TyProjection "BlockVersionModifier" (preview _ValueBlockVersionModifier)
tyProposeUpdateSystem :: TyProjection ProposeUpdateSystem
tyProposeUpdateSystem = TyProjection "ProposeUpdateSystem" (preview _ValueProposeUpdateSystem)
tySystemTag :: TyProjection SystemTag
tySystemTag = TyProjection "SystemTag" ((fmap . fmap) (SystemTag) (preview _ValueString))
tyApplicationName :: TyProjection ApplicationName
tyApplicationName = TyProjection "ApplicationName" ((fmap . fmap) (ApplicationName) (preview _ValueString))
tyString :: TyProjection Text
tyString = TyProjection "String" (preview _ValueString)
|
input-output-hk/pos-haskell-prototype
|
auxx/src/Command/TyProjection.hs
|
Haskell
|
mit
| 6,086
|
-- Unpack a tarball containing a Cabal package
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Distribution.Server.Packages.Unpack (
unpackPackage,
unpackPackageRaw,
) where
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
import qualified Codec.Archive.Tar.Check as Tar
import Distribution.Version
( Version(..) )
import Distribution.Package
( PackageIdentifier, packageVersion, packageName, PackageName(..) )
import Distribution.PackageDescription
( GenericPackageDescription(..), PackageDescription(..)
, exposedModules )
import Distribution.PackageDescription.Parse
( parsePackageDescription )
import Distribution.PackageDescription.Configuration
( flattenPackageDescription )
import Distribution.PackageDescription.Check
( PackageCheck(..), checkPackage )
import Distribution.ParseUtils
( ParseResult(..), locatedErrorMsg, showPWarning )
import Distribution.Text
( display, simpleParse )
import Distribution.ModuleName
( components )
import Distribution.Server.Util.Parse
( unpackUTF8 )
import Data.List
( nub, (\\), partition, intercalate )
import Data.Time
( UTCTime(..), fromGregorian, addUTCTime )
import Data.Time.Clock.POSIX
( posixSecondsToUTCTime )
import Control.Monad
( unless, when )
import Control.Monad.Error
( ErrorT(..) )
import Control.Monad.Writer
( WriterT(..), MonadWriter, tell )
import Control.Monad.Identity
( Identity(..) )
import qualified Distribution.Server.Util.GZip as GZip
import Data.ByteString.Lazy
( ByteString )
import qualified Data.ByteString.Lazy as LBS
import System.FilePath
( (</>), (<.>), splitDirectories, splitExtension, normalise )
import qualified System.FilePath.Windows
( takeFileName )
-- | Upload or check a tarball containing a Cabal package.
-- Returns either an fatal error or a package description and a list
-- of warnings.
unpackPackage :: UTCTime -> FilePath -> ByteString
-> Either String
((GenericPackageDescription, ByteString), [String])
unpackPackage now tarGzFile contents =
runUploadMonad $ do
(pkgDesc, warnings, cabalEntry) <- basicChecks False now tarGzFile contents
mapM_ fail warnings
extraChecks pkgDesc
return (pkgDesc, cabalEntry)
unpackPackageRaw :: FilePath -> ByteString
-> Either String
((GenericPackageDescription, ByteString), [String])
unpackPackageRaw tarGzFile contents =
runUploadMonad $ do
(pkgDesc, _warnings, cabalEntry) <- basicChecks True noTime tarGzFile contents
return (pkgDesc, cabalEntry)
where
noTime = UTCTime (fromGregorian 1970 1 1) 0
basicChecks :: Bool -> UTCTime -> FilePath -> ByteString
-> UploadMonad (GenericPackageDescription, [String], ByteString)
basicChecks lax now tarGzFile contents = do
let (pkgidStr, ext) = (base, tar ++ gz)
where (tarFile, gz) = splitExtension (portableTakeFileName tarGzFile)
(base, tar) = splitExtension tarFile
unless (ext == ".tar.gz") $
fail $ tarGzFile ++ " is not a gzipped tar file, it must have the .tar.gz extension"
pkgid <- case simpleParse pkgidStr of
Just pkgid
| null . versionBranch . packageVersion $ pkgid
-> fail $ "Invalid package id " ++ quote pkgidStr
++ ". It must include the package version number, and not just "
++ "the package name, e.g. 'foo-1.0'."
| display pkgid == pkgidStr -> return (pkgid :: PackageIdentifier)
| not . null . versionTags . packageVersion $ pkgid
-> fail $ "Hackage no longer accepts packages with version tags: "
++ intercalate ", " (versionTags (packageVersion pkgid))
_ -> fail $ "Invalid package id " ++ quote pkgidStr
++ ". The tarball must use the name of the package."
-- Extract entries and check the tar format / portability
let entries = tarballChecks lax now expectedDir
$ Tar.read (GZip.decompressNamed tarGzFile contents)
expectedDir = display pkgid
-- Extract the .cabal file from the tarball
let selectEntry entry = case Tar.entryContent entry of
Tar.NormalFile bs _ | cabalFileName == normalise (Tar.entryPath entry)
-> Just bs
_ -> Nothing
PackageName name = packageName pkgid
cabalFileName = display pkgid </> name <.> "cabal"
cabalEntries <- selectEntries explainTarError selectEntry entries
cabalEntry <- case cabalEntries of
-- NB: tar files *can* contain more than one entry for the same filename.
-- (This was observed in practice with the package CoreErlang-0.0.1).
-- In this case, after extracting the tar the *last* file in the archive
-- wins. Since selectEntries returns results in reverse order we use the head:
cabalEntry:_ -> -- We tend to keep hold of the .cabal file, but
-- cabalEntry itself is part of a much larger
-- ByteString (the whole tar file), so we make a
-- copy of it
return $ LBS.copy cabalEntry
[] -> fail $ "The " ++ quote cabalFileName
++ " file is missing from the package tarball."
-- Parse the Cabal file
let cabalFileContent = unpackUTF8 cabalEntry
(pkgDesc, warnings) <- case parsePackageDescription cabalFileContent of
ParseFailed err -> fail $ showError (locatedErrorMsg err)
ParseOk warnings pkgDesc ->
return (pkgDesc, map (showPWarning cabalFileName) warnings)
-- Check that the name and version in Cabal file match
when (packageName pkgDesc /= packageName pkgid) $
fail "Package name in the cabal file does not match the file name."
when (packageVersion pkgDesc /= packageVersion pkgid) $
fail "Package version in the cabal file does not match the file name."
return (pkgDesc, warnings, cabalEntry)
where
showError (Nothing, msg) = msg
showError (Just n, msg) = "line " ++ show n ++ ": " ++ msg
-- | The issue is that browsers can upload the file name using either unix
-- or windows convention, so we need to take the basename using either
-- convention. Since windows allows the unix '/' as a separator then we can
-- use the Windows.takeFileName as a portable solution.
--
portableTakeFileName :: FilePath -> String
portableTakeFileName = System.FilePath.Windows.takeFileName
-- Miscellaneous checks on package description
extraChecks :: GenericPackageDescription -> UploadMonad ()
extraChecks genPkgDesc = do
let pkgDesc = flattenPackageDescription genPkgDesc
-- various checks
--FIXME: do the content checks. The dev version of Cabal generalises
-- checkPackageContent to work in any monad, we just need to provide
-- a record of ops that will do checks inside the tarball. We should
-- gather a map of files and dirs and have these just to map lookups:
--
-- > checkTarballContents = CheckPackageContentOps {
-- > doesFileExist = Set.member fileMap,
-- > doesDirectoryExist = Set.member dirsMap
-- > }
-- > fileChecks <- checkPackageContent checkTarballContents pkgDesc
let pureChecks = checkPackage genPkgDesc (Just pkgDesc)
checks = pureChecks -- ++ fileChecks
isDistError (PackageDistSuspicious {}) = False
isDistError _ = True
(errors, warnings) = partition isDistError checks
mapM_ (fail . explanation) errors
mapM_ (warn . explanation) warnings
-- Check reasonableness of names of exposed modules
let topLevel = case library pkgDesc of
Nothing -> []
Just l ->
nub $ map head $ filter (not . null) $ map components $ exposedModules l
badTopLevel = topLevel \\ allocatedTopLevelNodes
unless (null badTopLevel) $
warn $ "Exposed modules use unallocated top-level names: " ++
unwords badTopLevel
-- Monad for uploading packages:
-- WriterT for warning messages
-- Either for fatal errors
newtype UploadMonad a = UploadMonad (WriterT [String] (ErrorT String Identity) a)
deriving (Monad, MonadWriter [String])
warn :: String -> UploadMonad ()
warn msg = tell [msg]
runUploadMonad :: UploadMonad a -> Either String (a, [String])
runUploadMonad (UploadMonad m) = runIdentity . runErrorT . runWriterT $ m
-- | Registered top-level nodes in the class hierarchy.
allocatedTopLevelNodes :: [String]
allocatedTopLevelNodes = [
"Algebra", "Codec", "Control", "Data", "Database", "Debug",
"Distribution", "DotNet", "Foreign", "Graphics", "Language",
"Network", "Numeric", "Prelude", "Sound", "System", "Test", "Text"]
selectEntries :: (err -> String)
-> (Tar.Entry -> Maybe a)
-> Tar.Entries err
-> UploadMonad [a]
selectEntries formatErr select = extract []
where
extract _ (Tar.Fail err) = fail (formatErr err)
extract selected Tar.Done = return selected
extract selected (Tar.Next entry entries) =
case select entry of
Nothing -> extract selected entries
Just saved -> extract (saved : selected) entries
data CombinedTarErrs =
FormatError Tar.FormatError
| PortabilityError Tar.PortabilityError
| TarBombError FilePath FilePath
| FutureTimeError FilePath UTCTime
tarballChecks :: Bool -> UTCTime -> FilePath
-> Tar.Entries Tar.FormatError
-> Tar.Entries CombinedTarErrs
tarballChecks lax now expectedDir =
(if not lax then checkFutureTimes now else id)
. checkTarbomb expectedDir
. (if lax then ignoreShortTrailer
else fmapTarError (either id PortabilityError)
. Tar.checkPortability)
. fmapTarError FormatError
where
ignoreShortTrailer =
Tar.foldEntries Tar.Next Tar.Done
(\e -> case e of
FormatError Tar.ShortTrailer -> Tar.Done
_ -> Tar.Fail e)
fmapTarError f = Tar.foldEntries Tar.Next Tar.Done (Tar.Fail . f)
checkFutureTimes :: UTCTime
-> Tar.Entries CombinedTarErrs
-> Tar.Entries CombinedTarErrs
checkFutureTimes now =
checkEntries checkEntry
where
-- Allow 30s for client clock skew
now' = addUTCTime 30 now
checkEntry entry
| entryUTCTime > now'
= Just (FutureTimeError posixPath entryUTCTime)
where
entryUTCTime = posixSecondsToUTCTime (realToFrac (Tar.entryTime entry))
posixPath = Tar.fromTarPathToPosixPath (Tar.entryTarPath entry)
checkEntry _ = Nothing
checkTarbomb :: FilePath -> Tar.Entries CombinedTarErrs -> Tar.Entries CombinedTarErrs
checkTarbomb expectedTopDir =
checkEntries checkEntry
where
checkEntry entry =
case splitDirectories (Tar.entryPath entry) of
(topDir:_) | topDir == expectedTopDir -> Nothing
_ -> Just $ TarBombError (Tar.entryPath entry) expectedTopDir
checkEntries :: (Tar.Entry -> Maybe e) -> Tar.Entries e -> Tar.Entries e
checkEntries checkEntry =
Tar.foldEntries (\entry rest -> maybe (Tar.Next entry rest) Tar.Fail
(checkEntry entry))
Tar.Done Tar.Fail
explainTarError :: CombinedTarErrs -> String
explainTarError (TarBombError filename expectedDir) =
"Bad file name in package tarball: " ++ quote filename
++ "\nAll the file in the package tarball must be in the subdirectory "
++ quote expectedDir ++ "."
explainTarError (PortabilityError (Tar.NonPortableFormat Tar.GnuFormat)) =
"This tarball is in the non-standard GNU tar format. "
++ "For portability and long-term data preservation, hackage requires that "
++ "package tarballs use the standard 'ustar' format. If you are using GNU "
++ "tar, use --format=ustar to get the standard portable format."
explainTarError (PortabilityError (Tar.NonPortableFormat Tar.V7Format)) =
"This tarball is in the old Unix V7 tar format. "
++ "For portability and long-term data preservation, hackage requires that "
++ "package tarballs use the standard 'ustar' format. Virtually all tar "
++ "programs can now produce ustar format (POSIX 1988). For example if you "
++ "are using GNU tar, use --format=ustar to get the standard portable format."
explainTarError (PortabilityError (Tar.NonPortableFormat Tar.UstarFormat)) =
error "explainTarError: impossible UstarFormat"
explainTarError (PortabilityError Tar.NonPortableFileType) =
"The package tarball contains a non-portable entry type. "
++ "For portability, package tarballs should use the 'ustar' format "
++ "and only contain normal files, directories and file links."
explainTarError (PortabilityError (Tar.NonPortableEntryNameChar _)) =
"The package tarball contains an entry with a non-ASCII file name. "
++ "For portability, package tarballs should contain only ASCII file names "
++ "(e.g. not UTF8 encoded Unicode)."
explainTarError (PortabilityError (err@Tar.NonPortableFileName {})) =
show err
++ ". For portability, hackage requires that file names be valid on both Unix "
++ "and Windows systems, and not refer outside of the tarball."
explainTarError (FormatError formateror) =
"There is an error in the format of the tar file: " ++ show formateror
++ ". Check that it is a valid tar file (e.g. 'tar -xtf thefile.tar'). "
++ "You may need to re-create the package tarball and try again."
explainTarError (FutureTimeError entryname time) =
"The tarball entry " ++ quote entryname ++ " has a file timestamp that is "
++ "in the future (" ++ show time ++ "). This tends to cause problems "
++ "for build systems and other tools, so hackage does not allow it. This "
++ "problem can be caused by having a misconfigured system time, or by bugs "
++ "in the tools (tarballs created by 'cabal sdist' on Windows with "
++ "cabal-install-1.18.0.2 or older have this problem)."
quote :: String -> String
quote s = "'" ++ s ++ "'"
|
haskell-infra/hackage-server
|
Distribution/Server/Packages/Unpack.hs
|
Haskell
|
bsd-3-clause
| 14,144
|
{-# OPTIONS_GHC -fglasgow-exts #-}
{-# OPTIONS_GHC -fno-spec-constr-count #-}
--
-- TODO:
-- permute operations, which are fairly important for this algorithm, are currently
-- all sequential
module QSortPar (qsortPar)
where
import Data.Array.Parallel.Unlifted.Distributed
import Data.Array.Parallel.Unlifted.Parallel
import Data.Array.Parallel.Unlifted
import Debug.Trace
-- I'm lazy here and use the lifted qsort instead of writing a flat version
qsortPar :: UArr Double -> UArr Double
{-# NOINLINE qsortPar #-}
qsortPar = concatSU . qsortLifted . singletonSU
-- Remove the trivially sorted segments
qsortLifted:: SUArr Double -> SUArr Double
qsortLifted xssArr =
splitApplySUP flags qsortLifted' id xssArr
where
flags = mapUP ((> 1)) $ lengthsSU xssArr
-- Actual sorting
qsortLifted' xssarr =
if (xssLen == 0)
then xssarr
else (takeCU xssLen sorted) ^+:+^ equal ^+:+^ (dropCU xssLen sorted)
where
xssLen = lengthSU xssarr
xsLens = lengthsSU xssarr
pivots = xssarr !:^ mapUP (flip div 2) xsLens
pivotss = replicateSUP xsLens pivots
xarrLens = zipSU xssarr pivotss
sorted = qsortLifted (smaller +:+^ greater)
smaller = fstSU $ filterSUP (uncurryS (<)) xarrLens
greater = fstSU $ filterSUP (uncurryS (>)) xarrLens
equal = fstSU $ filterSUP (uncurryS (==)) xarrLens
splitApplySUP:: (UA e, UA e', Show e, Show e') =>
UArr Bool -> (SUArr e -> SUArr e') -> (SUArr e -> SUArr e') -> SUArr e -> SUArr e'
{-# INLINE splitApplySUP #-}
splitApplySUP flags f1 f2 xssArr =
if (lengthSU xssArr == 0)
then segmentArrU emptyU emptyU
else combineCU flags res1 res2
where
res1 = f1 $ packCUP flags xssArr
res2 = f2 $ packCUP (mapUP not flags) xssArr
|
mainland/dph
|
icebox/examples/qsort/QSortPar.hs
|
Haskell
|
bsd-3-clause
| 1,777
|
module Language.Haskell.GhcMod.Debug (debugInfo, rootInfo) where
import Control.Applicative ((<$>))
import Data.List (intercalate)
import Data.Maybe (isJust, fromJust)
import Language.Haskell.GhcMod.Convert
import Language.Haskell.GhcMod.Monad
import Language.Haskell.GhcMod.Types
import Language.Haskell.GhcMod.Internal
----------------------------------------------------------------
-- | Obtaining debug information.
debugInfo :: IOish m => GhcModT m String
debugInfo = cradle >>= \c -> convert' =<< do
CompilerOptions gopts incDir pkgs <-
if isJust $ cradleCabalFile c then
fromCabalFile c ||> simpleCompilerOption
else
simpleCompilerOption
return [
"Root directory: " ++ cradleRootDir c
, "Current directory: " ++ cradleCurrentDir c
, "Cabal file: " ++ show (cradleCabalFile c)
, "GHC options: " ++ unwords gopts
, "Include directories: " ++ unwords incDir
, "Dependent packages: " ++ intercalate ", " (map showPkg pkgs)
, "System libraries: " ++ ghcLibDir
]
where
simpleCompilerOption = options >>= \op ->
return $ CompilerOptions (ghcUserOptions op) [] []
fromCabalFile c = options >>= \opts -> do
pkgDesc <- parseCabalFile c $ fromJust $ cradleCabalFile c
getCompilerOptions (ghcUserOptions opts) c pkgDesc
----------------------------------------------------------------
-- | Obtaining root information.
rootInfo :: IOish m => GhcModT m String
rootInfo = convert' =<< cradleRootDir <$> cradle
|
cabrera/ghc-mod
|
Language/Haskell/GhcMod/Debug.hs
|
Haskell
|
bsd-3-clause
| 1,569
|
import ChineseCheckers
import Table
import Test.QuickCheck
import Haste.Graphics.Canvas
newtype TableCoords = TableCoords (Table, Content, (Int,Int))
deriving (Show)
newtype OnlyPiece = OnlyPiece Content
deriving (Show)
newtype TableCoords2 = TableCoords2 (Table, Content, (Int,Int))
deriving (Show)
instance Arbitrary OnlyPiece where
arbitrary = do
con <- arbitrary :: Gen Color
return $ OnlyPiece (Piece con)
-- | Generates non-empty tables with a coord that exists in the table
instance Arbitrary TableCoords where
arbitrary = do
con <- arbitrary :: Gen Content
table <- listOf1 arbitrary :: Gen Table
coord <- elements $ map getCoord' table
return $ TableCoords (table,con,coord)
instance Arbitrary TableCoords2 where
arbitrary = do
con <- arbitrary :: Gen Content
coord <- elements $ map getCoord' startTable
return $ TableCoords2 (startTable,con,coord)
getCoord' :: Square -> Coord
getCoord' (Square _ _ c) = c
instance Arbitrary Color where
arbitrary = elements [white, red, blue, green]
instance Arbitrary Content where
arbitrary = do
col <- arbitrary
frequency [(1, return Empty),(4,return (Piece col))]
instance Arbitrary Square where
arbitrary = do
content <- arbitrary :: Gen Content
color <- arbitrary :: Gen Color
x <- arbitrary :: Gen Int
y <- arbitrary :: Gen Int
return $ Square content color (x,y)
prop_removePiece :: TableCoords -> Bool
prop_removePiece (TableCoords (t, c, coord)) = squareContent (removePiece (putPiece t c coord) coord) coord == Empty
prop_putPiece :: TableCoords -> OnlyPiece -> Bool
prop_putPiece (TableCoords (t, _, coord)) (OnlyPiece p) = squareContent (putPiece t p coord) coord /= Empty
prop_move :: TableCoords2 -> Bool
prop_move (TableCoords2 (t, _, coord)) = all (dist coord) (canMove coord t)
dist :: Coord -> Square -> Bool
dist (x2,y2) (Square _ _ (x1,y1)) = sqrt(fromIntegral(x2-x1)^2 + fromIntegral(y2-y1)^2) <= 4
--test startTable if all squares with no pieces are white
testStartTable :: Table -> Bool
testStartTable xs
|testStartTable' xs > 1 = False
|otherwise = True
testStartTable' :: Table -> Int
testStartTable' [] = 0
testStartTable' (Square (Piece _) color _ :xs) = testStartTable' xs
testStartTable' (Square Empty color _ :xs)
|color == white = testStartTable' xs
|otherwise = 1 + testStartTable' xs
|
DATx02-16-14/Hastings
|
test/Tests.hs
|
Haskell
|
bsd-3-clause
| 2,636
|
-----------------------------------------------------------------------------
-- |
-- Module : CppIfdef
-- Copyright : 1999-2004 Malcolm Wallace
-- Licence : LGPL
--
-- Maintainer : Malcolm Wallace <Malcolm.Wallace@cs.york.ac.uk>
-- Stability : experimental
-- Portability : All
--
-- Perform a cpp.first-pass, gathering \#define's and evaluating \#ifdef's.
-- and \#include's.
-----------------------------------------------------------------------------
module Language.Preprocessor.Cpphs.CppIfdef
( cppIfdef -- :: FilePath -> [(String,String)] -> [String] -> Bool -> Bool
-- -> String -> [(Posn,String)]
) where
import Language.Preprocessor.Cpphs.SymTab
import Text.ParserCombinators.HuttonMeijer
-- import HashDefine
import Language.Preprocessor.Cpphs.Position (Posn,newfile,newline,newlines,cppline,newpos)
import Language.Preprocessor.Cpphs.ReadFirst (readFirst)
import Language.Preprocessor.Cpphs.Tokenise (linesCpp,reslash)
import Char (isDigit)
import Numeric (readHex,readOct,readDec)
import System.IO.Unsafe (unsafePerformIO)
import IO (hPutStrLn,stderr)
-- | Run a first pass of cpp, evaluating \#ifdef's and processing \#include's,
-- whilst taking account of \#define's and \#undef's as we encounter them.
cppIfdef :: FilePath -- ^ File for error reports
-> [(String,String)] -- ^ Pre-defined symbols and their values
-> [String] -- ^ Search path for \#includes
-> Bool -- ^ Leave \#define and \#undef in output?
-> Bool -- ^ Place \#line droppings in output?
-> String -- ^ The input file content
-> [(Posn,String)] -- ^ The file after processing (in lines)
cppIfdef fp syms search leave locat =
cpp posn defs search leave locat Keep . (cppline posn:) . linesCpp
where
posn = newfile fp
defs = foldr insertST emptyST syms
-- Notice that the symbol table is a very simple one mapping strings
-- to strings. This pass does not need anything more elaborate, in
-- particular it is not required to deal with any parameterised macros.
-- | Internal state for whether lines are being kept or dropped.
-- In @Drop n b@, @n@ is the depth of nesting, @b@ is whether
-- we have already succeeded in keeping some lines in a chain of
-- @elif@'s
data KeepState = Keep | Drop Int Bool
-- | Return just the list of lines that the real cpp would decide to keep.
cpp :: Posn -> SymTab String -> [String] -> Bool -> Bool -> KeepState
-> [String] -> [(Posn,String)]
cpp _ _ _ _ _ _ [] = []
cpp p syms path leave ln Keep (l@('#':x):xs) =
let ws = words x
cmd = head ws
sym = head (tail ws)
rest = tail (tail ws)
val = maybe "1" id (un rest)
un v = if null v then Nothing else Just (unwords v)
down = if definedST sym syms then (Drop 1 False) else Keep
up = if definedST sym syms then Keep else (Drop 1 False)
keep str = if gatherDefined p syms str then Keep else (Drop 1 False)
skipn cpp' p' syms' path' ud xs' =
let n = 1 + length (filter (=='\n') l) in
(if leave then ((p,reslash l):) else (replicate n (p,"") ++)) $
cpp' (newlines n p') syms' path' leave ln ud xs'
in case cmd of
"define" -> skipn cpp p (insertST (sym,val) syms) path Keep xs
"undef" -> skipn cpp p (deleteST sym syms) path Keep xs
"ifndef" -> skipn cpp p syms path down xs
"ifdef" -> skipn cpp p syms path up xs
"if" -> skipn cpp p syms path (keep (unwords (tail ws))) xs
"else" -> skipn cpp p syms path (Drop 1 False) xs
"elif" -> skipn cpp p syms path (Drop 1 True) xs
"endif" -> skipn cpp p syms path Keep xs
"pragma" -> skipn cpp p syms path Keep xs
('!':_) -> skipn cpp p syms path Keep xs -- \#!runhs scripts
"include"-> let (inc,content) =
unsafePerformIO (readFirst (unwords (tail ws))
p path syms)
in
cpp p syms path leave ln Keep (("#line 1 "++show inc)
: linesCpp content
++ cppline p :"": xs)
"warning"-> unsafePerformIO $ do
hPutStrLn stderr (l++"\nin "++show p)
return $ skipn cpp p syms path Keep xs
"error" -> error (l++"\nin "++show p)
"line" | all isDigit sym
-> (if ln then ((p,l):) else id) $
cpp (newpos (read sym) (un rest) p)
syms path leave ln Keep xs
n | all isDigit n
-> (if ln then ((p,l):) else id) $
cpp (newpos (read n) (un (tail ws)) p)
syms path leave ln Keep xs
| otherwise
-> unsafePerformIO $ do
hPutStrLn stderr ("Warning: unknown directive #"++n
++"\nin "++show p)
return $
((p,l): cpp (newline p) syms path leave ln Keep xs)
cpp p syms path leave ln (Drop n b) (('#':x):xs) =
let ws = words x
cmd = head ws
delse | n==1 && b = Drop 1 b
| n==1 = Keep
| otherwise = Drop n b
dend | n==1 = Keep
| otherwise = Drop (n-1) b
keep str | n==1 = if not b && gatherDefined p syms str then Keep
else (Drop 1) b
| otherwise = Drop n b
skipn cpp' p' syms' path' ud xs' =
let n' = 1 + length (filter (=='\n') x) in
replicate n' (p,"")
++ cpp' (newlines n' p') syms' path' leave ln ud xs'
in
if cmd == "ifndef" ||
cmd == "if" ||
cmd == "ifdef" then skipn cpp p syms path (Drop (n+1) b) xs
else if cmd == "elif" then skipn cpp p syms path
(keep (unwords (tail ws))) xs
else if cmd == "else" then skipn cpp p syms path delse xs
else if cmd == "endif" then skipn cpp p syms path dend xs
else skipn cpp p syms path (Drop n b) xs
-- define, undef, include, error, warning, pragma, line
cpp p syms path leave ln Keep (x:xs) =
let p' = newline p in seq p' $
(p,x): cpp p' syms path leave ln Keep xs
cpp p syms path leave ln d@(Drop _ _) (_:xs) =
let p' = newline p in seq p' $
(p,""): cpp p' syms path leave ln d xs
----
gatherDefined :: Posn -> SymTab String -> String -> Bool
gatherDefined p st inp =
case papply (parseBoolExp st) inp of
[] -> error ("Cannot parse #if directive in file "++show p)
[(b,_)] -> b
_ -> error ("Ambiguous parse for #if directive in file "++show p)
parseBoolExp :: SymTab String -> Parser Bool
parseBoolExp st =
do a <- parseExp1 st
skip (string "||")
b <- first (skip (parseBoolExp st))
return (a || b)
+++
parseExp1 st
parseExp1 :: SymTab String -> Parser Bool
parseExp1 st =
do a <- parseExp0 st
skip (string "&&")
b <- first (skip (parseExp1 st))
return (a && b)
+++
parseExp0 st
parseExp0 :: SymTab String -> Parser Bool
parseExp0 st =
do skip (string "defined")
sym <- bracket (skip (char '(')) (skip (many1 alphanum)) (skip (char ')'))
return (definedST sym st)
+++
do bracket (skip (char '(')) (parseBoolExp st) (skip (char ')'))
+++
do skip (char '!')
a <- parseExp0 st
return (not a)
+++
do sym1 <- skip (many1 alphanum)
op <- parseOp st
sym2 <- skip (many1 alphanum)
let val1 = convert sym1 st
let val2 = convert sym2 st
return (op val1 val2)
+++
do sym <- skip (many1 alphanum)
case convert sym st of
0 -> return False
_ -> return True
where
convert sym st' =
case lookupST sym st' of
Nothing -> safeRead sym
(Just a) -> safeRead a
safeRead s =
case s of
'0':'x':s' -> number readHex s'
'0':'o':s' -> number readOct s'
_ -> number readDec s
number rd s =
case rd s of
[] -> 0 :: Integer
((n,_):_) -> n :: Integer
parseOp :: SymTab String -> Parser (Integer -> Integer -> Bool)
parseOp _ =
do skip (string ">=")
return (>=)
+++
do skip (char '>')
return (>)
+++
do skip (string "<=")
return (<=)
+++
do skip (char '<')
return (<)
+++
do skip (string "==")
return (==)
+++
do skip (string "!=")
return (/=)
|
FranklinChen/hugs98-plus-Sep2006
|
cpphs/Language/Preprocessor/Cpphs/CppIfdef.hs
|
Haskell
|
bsd-3-clause
| 8,470
|
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
-------------------------------------------------------------------------------------
-- |
-- Copyright : (c) Hans Hoglund 2012-2014
--
-- License : BSD-style
--
-- Maintainer : hans@hanshoglund.se
-- Stability : experimental
-- Portability : non-portable (TF,GNTD)
--
-- Provides various forms of title, subtitle etc. and related meta-data.
--
-------------------------------------------------------------------------------------
module Music.Score.Meta.Title (
-- * Title type
Title,
-- ** Creating and modifying
-- titleFromString,
denoteTitle,
getTitle,
getTitleAt,
-- * Adding titles to scores
title,
titleDuring,
subtitle,
subtitleDuring,
subsubtitle,
subsubtitleDuring,
-- * Extracting titles
withTitle,
) where
import Control.Lens (view)
import Control.Monad.Plus
import Data.Foldable (Foldable)
import qualified Data.Foldable as F
import qualified Data.List as List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Semigroup
import Data.Set (Set)
import qualified Data.Set as Set
import Data.String
import Data.Traversable (Traversable)
import qualified Data.Traversable as T
import Data.Typeable
import Music.Pitch.Literal
import Music.Score.Meta
import Music.Score.Part
import Music.Score.Pitch
import Music.Score.Internal.Util
import Music.Time
import Music.Time.Reactive
-- |
-- A title is a sequence of 'String' values, representing the name of a work or part of a work.
-- An arbitrary depth of title sections can be used.
--
-- Title is an instance of 'IsString' and can be used with the 'OverloadedStrings' extension as
-- follows:
--
-- > title "Le Nozze di Figaro"
-- >
-- > subtitle "Atto primo"
-- > subsubtitle "Scena I"
-- > subsubtitle "Scena II"
-- > ...
-- >
-- > subtitle "Atto secundo"
-- > ...
--
newtype Title = Title (Int -> Option (Last String))
deriving (Typeable, Monoid, Semigroup)
instance IsString Title where
fromString x = Title $ \n -> if n == 0 then Option (Just (Last x)) else Option Nothing
instance Show Title where
show = List.intercalate " " . getTitle
-- | Create a title from a string. See also 'fromString'.
titleFromString :: String -> Title
titleFromString = fromString
-- | Denote a title to a lower level, i.e title becomes subtitle, subtitle becomes subsubtitle etc.
denoteTitle :: Title -> Title
denoteTitle (Title t) = Title (t . subtract 1)
-- | Extract the title as a descending list of title levels (i.e. title, subtitle, subsubtitle...).
getTitle :: Title -> [String]
getTitle t = untilFail . fmap (getTitleAt t) $ [0..]
where
untilFail = fmap fromJust . takeWhile isJust
-- | Extract the title of the given level. Semantic function.
getTitleAt :: Title -> Int -> Maybe String
getTitleAt (Title t) n = fmap getLast . getOption . t $ n
-- | Set title of the given score.
title :: (HasMeta a, HasPosition a) => Title -> a -> a
title t x = titleDuring (_era x) t x
-- | Set title of the given part of a score.
titleDuring :: HasMeta a => Span -> Title -> a -> a
titleDuring s t = addMetaNote $ view event (s, t)
-- | Set subtitle of the given score.
subtitle :: (HasMeta a, HasPosition a) => Title -> a -> a
subtitle t x = subtitleDuring (_era x) t x
-- | Set subtitle of the given part of a score.
subtitleDuring :: HasMeta a => Span -> Title -> a -> a
subtitleDuring s t = addMetaNote $ view event (s, denoteTitle t)
-- | Set subsubtitle of the given score.
subsubtitle :: (HasMeta a, HasPosition a) => Title -> a -> a
subsubtitle t x = subsubtitleDuring (_era x) t x
-- | Set subsubtitle of the given part of a score.
subsubtitleDuring :: HasMeta a => Span -> Title -> a -> a
subsubtitleDuring s t = addMetaNote $ view event (s, denoteTitle (denoteTitle t))
-- | Extract the title in from the given score.
withTitle :: (Title -> Score a -> Score a) -> Score a -> Score a
withTitle = withMetaAtStart
|
music-suite/music-score
|
src/Music/Score/Meta/Title.hs
|
Haskell
|
bsd-3-clause
| 4,776
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Language.Nix.Identifier ( Identifier(..), ident, quote, needsQuoting ) where
import Control.Lens
import Data.Char
import Data.Function ( on )
import Data.String
import Distribution.Nixpkgs.Util.PrettyPrinting ( Pretty(..), text )
import Text.Regex.Posix
-- | Identifiers in Nix are essentially strings. Reasonable people restrict
-- themselves to identifiers of the form @[a-zA-Z\_][a-zA-Z0-9\_\'\-]*@,
-- because these don't need quoting. The @Identifier@ type is an instance of
-- the 'IsString' class for convenience. The methods of the 'Pretty' class can
-- be used to pretty-print an identifier with proper quoting.
--
-- >>> let i = Identifier "test" in (i, pPrint i)
-- (Identifier "test",test)
-- >>> let i = Identifier "foo.bar" in (i, pPrint i)
-- (Identifier "foo.bar","foo.bar")
--
-- The 'Ord' instance for identifiers is unusual in that it's aware of
-- character's case:
--
-- >>> Identifier "abc" == Identifier "ABC"
-- False
-- >>> Identifier "abc" > Identifier "ABC"
-- True
-- >>> Identifier "abc" > Identifier "ABC"
-- True
-- >>> Identifier "X" > Identifier "a"
-- True
-- >>> Identifier "x" > Identifier "A"
-- True
--
-- prop> \str -> Identifier str == Identifier str
-- prop> \str -> any (`elem` ['a'..'z']) str ==> Identifier (map toLower str) /= Identifier (map toUpper str)
newtype Identifier = Identifier String
deriving (Show, Eq, IsString)
instance Pretty Identifier where
pPrint i = text (i ^. ident . to quote)
instance Ord Identifier where
compare (Identifier a) (Identifier b) =
case (compare `on` map toLower) a b of
EQ -> compare a b
r -> r
-- | Checks whether a given string would need quoting when interpreted as an
-- intentifier.
needsQuoting :: String -> Bool
needsQuoting str = not (str =~ grammar)
where grammar :: String -- TODO: should be a compiled regular expression
grammar = "^[a-zA-Z\\_][a-zA-Z0-9\\_\\'\\-]*$"
-- | Lens that allows conversion from/to the standard 'String' type. The setter
-- does not evaluate its input, so it's safe to use with 'undefined'.
--
-- >>> putStrLn $ Identifier "abc.def" ^. ident
-- abc.def
--
-- >>> pPrint $ undefined & ident .~ "abcdef"
-- abcdef
ident :: Lens' Identifier String
ident f (Identifier str) = Identifier `fmap` f str
-- | Help function that quotes a given identifier string (if necessary).
--
-- >>> putStrLn (quote "abc")
-- abc
--
-- >>> putStrLn (quote "abc.def")
-- "abc.def"
quote :: String -> String
quote s = if needsQuoting s then show s else s
|
spencerjanssen/cabal2nix
|
src/Language/Nix/Identifier.hs
|
Haskell
|
bsd-3-clause
| 2,554
|
{-# LANGUAGE DeriveDataTypeable, TemplateHaskell,
FlexibleInstances, FlexibleContexts, MultiParamTypeClasses #-}
-- TypeOperators, TypeSynonymInstances, TypeFamilies
module Distribution.Server.Util.NameIndex where
import Data.Map (Map)
import Data.Typeable (Typeable)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Char (toLower)
import Data.List (unfoldr, foldl')
import Data.Maybe (maybeToList)
import Control.DeepSeq
import Data.SafeCopy
import Distribution.Server.Framework.MemSize
-- | Case-insensitive name search. This is meant to be an enhanced set of
-- names, not a full text search. It's also meant to be a sort of a short-term
-- solution for name suggestion searches; e.g., package searches should also
-- consider the tagline of a package.
data NameIndex = NameIndex {
-- | This is the mapping from case-insensitive search term -> name.
nameIndex :: Map String (Set String),
-- | This is the set of names.
storedNamesIndex :: Set String,
-- | This is the specification of the type of generator, mainly here because
-- functions can't be serialized. Just str means to break on any char in
-- str (breakGenerator); Nothing is defaultGenerator.
nameGenType :: Maybe [Char],
-- | This is the generator of search terms from names.
nameSearchGenerator :: String -> [String]
} deriving (Typeable)
emptyNameIndex :: Maybe [Char] -> NameIndex
emptyNameIndex gen = NameIndex Map.empty Set.empty gen $ case gen of
Nothing -> defaultGenerator
Just st -> breakGenerator st
defaultGenerator :: String -> [String]
defaultGenerator name = [name]
breakGenerator :: [Char] -> String -> [String]
breakGenerator breakStr name = name:unfoldr unfoldName name
where unfoldName str = case break (`elem` breakStr) str of
([], _) -> Nothing
(_, []) -> Nothing
(_, _:str') -> Just (str', str')
constructIndex :: [String] -> Maybe [Char] -> NameIndex
constructIndex strs gen = foldl' (flip addName) (emptyNameIndex gen) strs
addName :: String -> NameIndex -> NameIndex
addName caseName (NameIndex index stored gen' gen) =
let name = map toLower caseName
nameSet = Set.singleton caseName
forName = Map.fromList $ map (\term -> (term, nameSet)) (gen name)
in NameIndex (Map.unionWith Set.union index forName)
(Set.insert caseName stored) gen' gen
deleteName :: String -> NameIndex -> NameIndex
deleteName caseName (NameIndex index stored gen' gen) =
let name = map toLower caseName
nameSet = Set.singleton caseName
forName = Map.fromList $ map (\term -> (term, nameSet)) (gen name)
in NameIndex (Map.differenceWith (\a b -> keepSet $ Set.difference a b) index forName)
(Set.delete caseName stored) gen' gen
where keepSet s = if Set.null s then Nothing else Just s
lookupName :: String -> NameIndex -> Set String
lookupName caseName (NameIndex index _ _ _) =
Map.findWithDefault Set.empty (map toLower caseName) index
lookupPrefix :: String -> NameIndex -> Set String
lookupPrefix caseName (NameIndex index _ _ _) =
let name = map toLower caseName
(_, mentry, startTree) = Map.splitLookup name index
-- the idea is, select all names in the range [name, mapLast succ name)
-- an alternate idea would just be to takeWhile (`isPrefixOf` name)
(totalTree, _, _) = Map.splitLookup (mapLast succ name) startTree
nameSets = maybeToList mentry ++ Map.elems totalTree
in Set.unions nameSets
takeSetPrefix :: String -> Set String -> Set String
takeSetPrefix name strs =
let (_, present, startSet) = Set.splitMember name strs
(totalSet, _, _) = Set.splitMember (mapLast succ name) startSet
in (if present then Set.insert name else id) totalSet
-- | Map only the last element of a list
mapLast :: (a -> a) -> [a] -> [a]
mapLast f (x:[]) = f x:[]
mapLast f (x:xs) = x:mapLast f xs
mapLast _ [] = []
-- store arguments which can be sent to constructIndex :: [String] -> Maybe [Char] -> NameIndex
instance SafeCopy NameIndex where
putCopy index = contain $ safePut (nameGenType index) >> safePut (storedNamesIndex index)
getCopy = contain $ do
gen <- safeGet
index <- safeGet
return $ constructIndex (Set.toList index) gen
instance NFData NameIndex where
rnf (NameIndex a b _ _) = rnf a `seq` rnf b
instance MemSize NameIndex where
memSize (NameIndex a b c d) = memSize4 a b c d
|
mpickering/hackage-server
|
Distribution/Server/Util/NameIndex.hs
|
Haskell
|
bsd-3-clause
| 4,508
|
<?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="hr-HR">
<title>Port Scan | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/zest/src/main/javahelp/org/zaproxy/zap/extension/zest/resources/help_hr_HR/helpset_hr_HR.hs
|
Haskell
|
apache-2.0
| 971
|
module FunIn2 where
--The application of a function is replaced by the right-hand side of the definition,
--with actual parameters replacing formals.
--In this example, unfold 'addthree'.
--This example aims to test unfolding a function defintion.
main :: Int -> Int
main = \x -> case x of
1 -> 1 + main 0
0 ->((1 + 2) + 3)
addthree :: Int -> Int -> Int -> Int
addthree a b c = a + b + c
|
mpickering/HaRe
|
old/testing/unfoldDef/FunIn2_TokOut.hs
|
Haskell
|
bsd-3-clause
| 424
|
import Test.Cabal.Prelude
import Data.Maybe
main = cabalTest $ do
withPackageDb $ do
withSandbox $ do
fails $ cabal "exec" ["my-executable"]
cabal "install" []
-- The library should not be available outside the sandbox
ghcPkg' "list" [] >>= assertOutputDoesNotContain "my-0.1"
-- Execute ghc-pkg inside the sandbox; it should find my-0.1
cabal' "exec" ["ghc-pkg", "list"]
>>= assertOutputContains "my-0.1"
|
mydaum/cabal
|
cabal-testsuite/PackageTests/Exec/sandbox-ghc-pkg.test.hs
|
Haskell
|
bsd-3-clause
| 506
|
module Foo where
-- TODO: return a civilized error message about the line number with the
-- problematic predicate application, instead of just a groan about safeZip
-- failing.
{-@ predicate Rng Lo V Hi = (Lo <= V && V < Hi) @-}
{-@ type NNN a b = {v:[(a, b)] | 0 <= 0} @-}
{-@ bog :: {v:Int | (Rng 0 10 11)} @-}
bog :: Int
bog = 5
{-@ foo :: NNN Int @-}
foo :: [(Int, Char)]
foo = [(1, 'c')]
|
mightymoose/liquidhaskell
|
tests/todo/aliasError.hs
|
Haskell
|
bsd-3-clause
| 399
|
module IdIn2 where
{-To rename an identifier name, stop the cursor at any occurrence of the name,
then input the new name in the mini-buffer, after that, select the 'rename'
command from the 'Refactor' menu.-}
--Any value variable name declared in this module can be renamed.
--Rename local 'x' to 'x1'
x=5
foo=x+3
bar z=x+y+z
where x=7
y=3
main=(foo,bar x, foo)
|
kmate/HaRe
|
test/testdata/Renaming/IdIn2.hs
|
Haskell
|
bsd-3-clause
| 390
|
{-# LANGUAGE CPP #-}
import Control.Concurrent
import Control.Exception
import Foreign
import System.IO (hFlush,stdout)
#if __GLASGOW_HASKELL__ < 705
import Prelude hiding (catch)
#endif
-- !!! Try to get two threads into a knot depending on each other.
-- This should result in the main thread being sent a NonTermination
-- exception (in GHC 5.02, the program is terminated with "no threads
-- to run" instead).
main = do
Foreign.newStablePtr stdout
-- HACK, because when these two threads get blocked on each other,
-- there's nothing keeping stdout alive so it will get finalized.
-- SDM 12/3/2004
let a = last ([1..10000] ++ [b])
b = last ([2..10000] ++ [a])
-- we have to be careful to ensure that the strictness analyser
-- can't see that a and b are both bottom, otherwise the
-- simplifier will go to town here, resulting in something like
-- a = a and b = a.
forkIO (print a `catch` \NonTermination -> return ())
-- we need to catch in the child thread too, because it might
-- get sent the NonTermination exception first.
r <- Control.Exception.try (print b)
print (r :: Either NonTermination ())
|
lukexi/ghc
|
testsuite/tests/concurrent/should_run/conc034.hs
|
Haskell
|
bsd-3-clause
| 1,140
|
-- A second test for trac #3001, which segfaults when compiled by
-- GHC 6.10.1 and run with +RTS -hb. Most of the code is from the
-- binary 0.4.4 package.
{-# LANGUAGE CPP, FlexibleInstances, FlexibleContexts, MagicHash #-}
module Main (main) where
import Data.Monoid
import Data.ByteString.Internal (inlinePerformIO)
import qualified Data.ByteString as S
import qualified Data.ByteString.Internal as S
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Internal as L
import GHC.Exts
import GHC.Word
import Control.Monad
import Foreign
import System.IO.Unsafe
import System.IO
import Data.Char (chr,ord)
import Control.Applicative
main :: IO ()
main = do
encodeFile "test.bin" $ replicate 10000 'x'
print =<< (decodeFile "test.bin" :: IO String)
class Binary t where
put :: t -> Put
get :: Get t
encodeFile :: Binary a => FilePath -> a -> IO ()
encodeFile f v = L.writeFile f $ runPut $ put v
decodeFile :: Binary a => FilePath -> IO a
decodeFile f = do
s <- L.readFile f
return $ runGet (do v <- get
m <- isEmpty
m `seq` return v) s
instance Binary Word8 where
put = putWord8
get = getWord8
instance Binary Word32 where
put = putWord32be
get = getWord32be
instance Binary Int32 where
put i = put (fromIntegral i :: Word32)
get = liftM fromIntegral (get :: Get Word32)
instance Binary Int where
put i = put (fromIntegral i :: Int32)
get = liftM fromIntegral (get :: Get Int32)
instance Binary Char where
put a = put (ord a)
get = do w <- get
return $! chr w
instance Binary a => Binary [a] where
put l = put (length l) >> mapM_ put l
get = do n <- get
replicateM n get
data PairS a = PairS a !Builder
sndS :: PairS a -> Builder
sndS (PairS _ b) = b
newtype PutM a = Put { unPut :: PairS a }
type Put = PutM ()
instance Functor PutM where
fmap f m = Put $ let PairS a w = unPut m in PairS (f a) w
instance Monad PutM where
return a = Put $ PairS a mempty
m >>= k = Put $
let PairS a w = unPut m
PairS b w' = unPut (k a)
in PairS b (w `mappend` w')
m >> k = Put $
let PairS _ w = unPut m
PairS b w' = unPut k
in PairS b (w `mappend` w')
instance Applicative PutM where
pure = return
(<*>) = ap
tell :: Builder -> Put
tell b = Put $ PairS () b
runPut :: Put -> L.ByteString
runPut = toLazyByteString . sndS . unPut
putWord8 :: Word8 -> Put
putWord8 = tell . singletonB
putWord32be :: Word32 -> Put
putWord32be = tell . putWord32beB
-----
newtype Get a = Get { unGet :: S -> (a, S) }
data S = S {-# UNPACK #-} !S.ByteString -- current chunk
L.ByteString -- the rest of the input
{-# UNPACK #-} !Int64 -- bytes read
runGet :: Get a -> L.ByteString -> a
runGet m str = case unGet m (initState str) of (a, _) -> a
isEmpty :: Get Bool
isEmpty = do
S s ss _ <- getZ
return (S.null s && L.null ss)
initState :: L.ByteString -> S
initState xs = mkState xs 0
getWord32be :: Get Word32
getWord32be = do
s <- readN 4 id
return $! (fromIntegral (s `S.index` 0) `shiftl_w32` 24) .|.
(fromIntegral (s `S.index` 1) `shiftl_w32` 16) .|.
(fromIntegral (s `S.index` 2) `shiftl_w32` 8) .|.
(fromIntegral (s `S.index` 3) )
getWord8 :: Get Word8
getWord8 = getPtr (sizeOf (undefined :: Word8))
mkState :: L.ByteString -> Int64 -> S
mkState l = case l of
L.Empty -> S S.empty L.empty
L.Chunk x xs -> S x xs
readN :: Int -> (S.ByteString -> a) -> Get a
readN n f = fmap f $ getBytes n
shiftl_w32 :: Word32 -> Int -> Word32
shiftl_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftL#` i)
getPtr :: Storable a => Int -> Get a
getPtr n = do
(fp,o,_) <- readN n S.toForeignPtr
return . S.inlinePerformIO $ withForeignPtr fp $ \p -> peek (castPtr $ p `plusPtr` o)
getBytes :: Int -> Get S.ByteString
getBytes n = do
S s ss bytes <- getZ
if n <= S.length s
then do let (consume,rest) = S.splitAt n s
putZ $! S rest ss (bytes + fromIntegral n)
return $! consume
else
case L.splitAt (fromIntegral n) (s `joinZ` ss) of
(consuming, rest) ->
do let now = S.concat . L.toChunks $ consuming
putZ $! mkState rest (bytes + fromIntegral n)
-- forces the next chunk before this one is returned
if (S.length now < n)
then
fail "too few bytes"
else
return now
joinZ :: S.ByteString -> L.ByteString -> L.ByteString
joinZ bb lb
| S.null bb = lb
| otherwise = L.Chunk bb lb
instance Monad Get where
return a = Get (\s -> (a, s))
{-# INLINE return #-}
m >>= k = Get (\s -> let (a, s') = unGet m s
in unGet (k a) s')
{-# INLINE (>>=) #-}
fail = error "failDesc"
instance Applicative Get where
pure = return
(<*>) = ap
getZ :: Get S
getZ = Get (\s -> (s, s))
putZ :: S -> Get ()
putZ s = Get (\_ -> ((), s))
instance Functor Get where
fmap f m = Get (\s -> case unGet m s of
(a, s') -> (f a, s'))
-----
singletonB :: Word8 -> Builder
singletonB = writeN 1 . flip poke
writeN :: Int -> (Ptr Word8 -> IO ()) -> Builder
writeN n f = ensureFree n `append` unsafeLiftIO (writeNBuffer n f)
unsafeLiftIO :: (Buffer -> IO Buffer) -> Builder
unsafeLiftIO f = Builder $ \ k buf -> inlinePerformIO $ do
buf' <- f buf
return (k buf')
append :: Builder -> Builder -> Builder
append (Builder f) (Builder g) = Builder (f . g)
writeNBuffer :: Int -> (Ptr Word8 -> IO ()) -> Buffer -> IO Buffer
writeNBuffer n f (Buffer fp o u l) = do
withForeignPtr fp (\p -> f (p `plusPtr` (o+u)))
return (Buffer fp o (u+n) (l-n))
newtype Builder = Builder {
-- Invariant (from Data.ByteString.Lazy):
-- The lists include no null ByteStrings.
runBuilder :: (Buffer -> [S.ByteString]) -> Buffer -> [S.ByteString]
}
data Buffer = Buffer {-# UNPACK #-} !(ForeignPtr Word8)
{-# UNPACK #-} !Int -- offset
{-# UNPACK #-} !Int -- used bytes
{-# UNPACK #-} !Int -- length left
toLazyByteString :: Builder -> L.ByteString
toLazyByteString m = L.fromChunks $ unsafePerformIO $ do
buf <- newBuffer defaultSize
return (runBuilder (m `append` flush) (const []) buf)
ensureFree :: Int -> Builder
ensureFree n = n `seq` withSize $ \ l ->
if n <= l then emptyBuilder else
flush `append` unsafeLiftIO (const (newBuffer (max n defaultSize)))
withSize :: (Int -> Builder) -> Builder
withSize f = Builder $ \ k buf@(Buffer _ _ _ l) ->
runBuilder (f l) k buf
defaultSize :: Int
defaultSize = 32 * k - overhead
where k = 1024
overhead = 2 * sizeOf (undefined :: Int)
newBuffer :: Int -> IO Buffer
newBuffer size = do
fp <- S.mallocByteString size
return $! Buffer fp 0 0 size
putWord32beB :: Word32 -> Builder
putWord32beB w = writeN 4 $ \p -> do
poke p (fromIntegral (shiftr_w32 w 24) :: Word8)
poke (p `plusPtr` 1) (fromIntegral (shiftr_w32 w 16) :: Word8)
poke (p `plusPtr` 2) (fromIntegral (shiftr_w32 w 8) :: Word8)
poke (p `plusPtr` 3) (fromIntegral (w) :: Word8)
shiftr_w32 :: Word32 -> Int -> Word32
shiftr_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftRL#` i)
flush :: Builder
flush = Builder $ \ k buf@(Buffer p o u l) ->
if u == 0
then k buf
else S.PS p o u : k (Buffer p (o+u) 0 l)
emptyBuilder :: Builder
emptyBuilder = Builder id
instance Monoid Builder where
mempty = emptyBuilder
mappend = append
|
urbanslug/ghc
|
testsuite/tests/profiling/should_run/T3001-2.hs
|
Haskell
|
bsd-3-clause
| 8,019
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module Data.CBar where
import Control.Lens hiding (to, each)
import Control.Monad.Trans.State.Strict (State)
import Control.SFold
import Control.SFold.Util
import Data.Binary (Binary)
import Data.ByteString (ByteString)
import qualified Data.Map as Map
import Data.Mark
import Data.Monoid
import qualified Data.Semigroup as Semi
import Data.Text (Text)
import Data.Text.Encoding
import Data.Time
import Data.Time.Extended
import Formatting
import GHC.Generics (Generic)
data CBar =
CBar {_cbarCloseTime :: UTCTime
,_cbarFirstTime :: UTCTime
,_cbarLastTime :: UTCTime
,_cbarBidPrice :: Double
,_cbarAskPrice :: Double
,_cbarPrice :: Double
,_cbarBidVolume :: Int
,_cbarAskVolume :: Int
,_cbarVolume :: Int}
deriving (Show,Eq,Generic)
makeLenses ''CBar
instance Binary CBar
instance Semi.Semigroup CBar where
(CBar ct ft lt _ _ _ _ _ v) <> (CBar ct' ft' lt' bp' ap' p' bv' av' v') =
CBar ct'' ft'' lt'' bp' ap' p' bv' av' (v + v')
where ct'' = max ct ct'
ft'' = min ft ft'
lt'' = max lt lt'
data CBarX =
CBarX {_xOpen :: Maybe CBar
,_xClosed :: [CBar]}
deriving (Show,Eq)
makeLenses ''CBarX
toCbar :: Mark -> CBar
toCbar (Mark t bp ap' p bv av v _ _ _) =
CBar t t t bp ap' p bv av v
instance Monoid CBarX where
mempty = CBarX Nothing []
mappend (CBarX o0 c0) (CBarX o1 c1) =
case o0 of
Nothing -> CBarX o1 c
Just m0 ->
case o1 of
Nothing -> CBarX o0 c
Just m1 ->
case compare (m0 ^. cbarCloseTime)
(m1 ^. cbarCloseTime) of
EQ ->
CBarX (Just (m0 Semi.<> m1)) c
LT ->
CBarX (Just m1)
(c <>
[m0])
GT ->
CBarX (Just m0)
(c <>
[m1])
where c = c0 <> c1
release :: CBarX -> (CBarX,[CBar])
release (CBarX o c) = (CBarX o [],c)
flush :: CBarX -> CBarX
flush (CBarX o c) =
case o of
Nothing -> CBarX Nothing c
Just o' ->
CBarX Nothing
(c <>
[o'])
timeFold :: NominalDiffTime -> SFold Mark CBar
timeFold grain =
SFold toNextClose mappend mempty release flush
where toNextClose (Mark t bp ap' p bv av v _ _ _) =
CBarX (Just $
CBar (ceilingTime t grain) t t bp ap' p bv av v)
[]
volumeFold :: Int -> SFold Mark CBar
volumeFold grain =
SFold toVol step mempty release flush
where step x0 x1 =
case o0' of
Nothing -> CBarX o1' c'
Just m0 ->
case o1' of
Nothing -> CBarX o0' c'
Just m1 ->
if m0 ^. cbarVolume + m1 ^. cbarVolume < grain
then CBarX (Just (m0 Semi.<> m1)) c'
else CBarX mrem
(c' <>
[mfirst] <>
mquot)
where m' = m0 Semi.<> m1
(_,cm') = budVol m'
mfirst = cbarVolume .~ grain $ head cm'
(mrem,mquot) =
budVol (cbarVolume .~
(m1 ^. cbarVolume -
(grain - m0 ^. cbarVolume)) $
m1)
where (CBarX o0' c0') = budVolCBarX x0
(CBarX o1' c1') = budVolCBarX x1
c' = c0' <> c1'
toVol m =
uncurry CBarX (budVol (toCbar m))
budVol :: CBar -> (Maybe CBar,[CBar])
budVol x =
(,) (if vrem > 0
then Just (cbarVolume .~ vrem $ x)
else Nothing)
(replicate vquot (cbarVolume .~ grain $ x))
where (vquot,vrem) =
quotRem (x ^. cbarVolume) grain
budVolCBarX :: CBarX -> CBarX
budVolCBarX x@(CBarX o c) =
case o of
Nothing -> x
Just m -> CBarX o' (c <> c')
where (o',c') = budVol m
mark2TimeBar :: NominalDiffTime -> SFold (ByteString,Mark) (ByteString,CBar)
mark2TimeBar grain = keyFold (timeFold grain)
mark2VolumeBar :: Int -> SFold (ByteString,Mark) (ByteString,CBar)
mark2VolumeBar grain = keyFold (volumeFold grain)
renderCBar :: CBar -> Text
renderCBar cbar =
fTimeMilli (utctDayTime $ _cbarCloseTime cbar) <>
sformat (left 15 ' ' %.
(" " % float % ":" % float % ":" % float))
(_cbarBidPrice cbar)
(_cbarAskPrice cbar)
(_cbarPrice cbar) <>
sformat (left 10 ' ' %.
(" " % int % ":" % int % ":" % int))
(_cbarBidVolume cbar)
(_cbarAskVolume cbar)
(_cbarVolume cbar)
renderCBar' :: (ByteString,CBar) -> Text
renderCBar' (sym,cbar) =
sformat (stext % " ")
(decodeUtf8 sym) <>
fTimeMilli (utctDayTime $ _cbarCloseTime cbar) <>
sformat (left 15 ' ' %.
(" " % float % ":" % float % ":" % float))
(_cbarBidPrice cbar)
(_cbarAskPrice cbar)
(_cbarPrice cbar) <>
sformat (left 10 ' ' %.
(" " % int % ":" % int % ":" % int))
(_cbarBidVolume cbar)
(_cbarAskVolume cbar)
(_cbarVolume cbar)
-- statistics
data StatsCBar =
StatsCBar {_scbarCount :: Int
,_scbarSymbolCount :: Map.Map ByteString Int
,_scbarSymbolVolumeSum :: Map.Map ByteString Int}
deriving (Show,Eq,Read,Generic)
instance Binary StatsCBar
makeLenses ''StatsCBar
initialScbar :: StatsCBar
initialScbar = StatsCBar 0 mempty mempty
scbarUpdate :: (ByteString,CBar) -> (State StatsCBar) ()
scbarUpdate (sym,c) =
do scbarCount += 1
scbarSymbolCount %=
Map.insertWith (+) sym 1
scbarSymbolVolumeSum %=
Map.insertWith (+)
sym
(c ^. cbarVolume)
scbarRender :: StatsCBar -> Text
scbarRender s =
sformat ("Count: " % int % "\n")
(s ^. scbarCount) <>
"Count by Symbol: " <>
Map.foldWithKey
(\k a b ->
b <>
sformat (stext % ":" % int % " ")
(decodeUtf8 k)
a)
mempty
(s ^. scbarSymbolCount) <>
"\n" <>
"Volume by Symbol: " <>
Map.foldWithKey
(\k a b ->
b <>
sformat (stext % ":" % int % " ")
(decodeUtf8 k)
a)
mempty
(s ^. scbarSymbolVolumeSum)
|
tonyday567/trade
|
src/Data/CBar.hs
|
Haskell
|
mit
| 6,865
|
module Proteome.Test.DiagTest where
import Hedgehog ((===))
import Path (Abs, Dir, Path, absdir, toFilePath)
import Ribosome.Api.Buffer (currentBufferContent)
import Ribosome.Test.Run (UnitTest)
import Proteome.Data.Env (Env)
import qualified Proteome.Data.Env as Env (configLog, mainProject)
import Proteome.Data.Project (Project(Project))
import Proteome.Data.ProjectMetadata (ProjectMetadata(DirProject))
import Proteome.Data.ProjectRoot (ProjectRoot(ProjectRoot))
import Proteome.Diag (proDiag)
import Proteome.Test.Config (vars)
import Proteome.Test.Project (ag, flag, fn, hask, idr, l, la, li, ti, tp)
import Proteome.Test.Unit (ProteomeTest, testWithDef)
root :: Path Abs Dir
root = [absdir|/projects/flagellum|]
main :: Project
main = Project (DirProject fn (ProjectRoot root) (Just tp)) [ti] (Just l) [la, li]
confLog :: [Text]
confLog = ["/conf/project/haskell/flagellum.vim", "/conf/project_after/all.vim"]
target :: [Text]
target = [
"Diagnostics",
"",
"Main project",
"",
"name: " <> flag,
"root: " <> toText (toFilePath root),
"type: " <> hask,
"tags cmd: ctags -R --languages=agda,idris -f /projects/flagellum/.tags.tmp /projects/flagellum/",
"types: " <> idr,
"main language: " <> hask,
"languages: " <> ag <> ", " <> idr,
"",
"loaded config files:"
] <> confLog
diagSpec :: ProteomeTest ()
diagSpec = do
setL @Env Env.mainProject main
setL @Env Env.configLog confLog
proDiag def
content <- currentBufferContent
target === content
test_diag :: UnitTest
test_diag =
vars >>= testWithDef diagSpec
|
tek/proteome
|
packages/test/test/Proteome/Test/DiagTest.hs
|
Haskell
|
mit
| 1,559
|
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls #-}
import Foreign
import Foreign.C.Types
import System.IO.Unsafe
data CFoo
foreign import ccall unsafe "foo_c.h foo_ctor"
c_foo_ctor :: CInt -> IO (Ptr CFoo)
data Foo = Foo !(Ptr CFoo)
deriving (Eq, Ord, Show)
newFoo :: Int -> Either String Foo
newFoo x = unsafePerformIO $ do
foo_ptr <- c_foo_ctor (fromIntegral x)
if foo_ptr == nullPtr
then
return (Left "Failed to construct Foo")
else
return (Right (Foo foo_ptr))
foreign import ccall unsafe "foo_c.h foo_get"
c_foo_get :: Ptr CFoo -> IO CInt
getFoo :: Foo -> Int
getFoo (Foo foo_ptr) = unsafePerformIO $ do
c <- c_foo_get foo_ptr
return $ fromIntegral c
foreign import ccall unsafe "foo_c.h foo_dtor"
c_foo_dtor :: Ptr CFoo -> IO ()
delFoo :: Foo -> IO ()
delFoo (Foo foo_ptr) = c_foo_dtor foo_ptr
main :: IO ()
main = do
let r = newFoo 10
case r of
Left e -> print e
Right f ->
do
print (getFoo f)
delFoo f
print "foo deleted"
|
hnfmr/cpp-class-ffi
|
ffi.hs
|
Haskell
|
mit
| 1,026
|
-- https://www.fpcomplete.com/blog/2017/09/all-about-strictness
{-# LANGUAGE BangPatterns #-}
{-
Run with:
stack --resolver lts-8.6 ghc
--package conduit-combinators
--package deepseq
-- StrictnessPlayground.hs -O2
./StrictnessPlayground +RTS -s
-}
import Debug.Trace
import Control.DeepSeq (NFData, rnf, deepseq, force)
import Prelude hiding (($!))
import Conduit
-- What would happen if, instead of in part1, the code said in part2? How about in answer?
add :: Int -> Int -> Int
add x y =
let
part1 = seq x part2
part2 = seq y answer
answer = x + y
in
part1
-- part2 -- x isn't evaluated
-- answer -- x and y aren't evaluated
main1 :: IO ()
main1 = do
let five = trace "five" $ add (1 + 1) (1 + 2)
seven = trace "seven" $ add (1 + 2) undefined -- (1 + 3)
putStrLn $ "Five: " ++ show five
where
add :: Int -> Int -> Int
add !x !y = x + y
main2 :: IO ()
main2 = do
putStrLn $ ((+) undefined) `seq` "Not throwing. I'm in WHNF."
putStrLn $ Just undefined `seq` "Not throwing. I'm in WHNF."
putStrLn $ undefined 5 `seq` "Throwing"
putStrLn $ (error "foo" :: Int -> Double) `seq` "Throwing"
myDeepSeq :: NFData a => a -> b -> b
myDeepSeq x y =
rnf x `seq` y
data Foo =
Foo Int
data Bar =
Bar !Int
newtype Baz =
Baz Int
-- it throws since `Baz undefined` ~= `undefined` and `seq` forces
-- its evaluation
main3 :: IO ()
main3 =
Baz undefined `seq` putStrLn "Still alive!"
mysum :: [Int] -> Int
mysum list0 =
go list0 0
where
go [] total = total
go (x:xs) total = go xs $! total + x
-- go (x:xs) total =
-- let newTotal = total + x in newTotal `seq` go xs newTotal
-- go (x:xs) total =
-- let !newTotal = total + x in go xs newTotal
($!) :: (a -> b) -> a -> b
f $! x =
let y = f x in y `seq` y
($!!) :: NFData b => (a -> b) -> a -> b
f $!! x =
let y = f x in y `deepseq` y
infixr 0 $!
infixr 0 $!!
{-
Data.Sequence.Seq is defined as follows: `newtype Seq a = Seq (FingerTree (Elem a))`
and FingerTree as follows:
```
data FingerTree a
= Empty
| Single a
| Deep {-# UNPACK #-} !Int !(Digit a) (FingerTree (Node a)) !(Digit a)
```
To me Seq seems to be just spine strict since the evaluation of the value `a`
is never forced.
-}
average :: Monad m => ConduitM Int o m Double
average =
divide <$> foldlC add (0, 0)
where
divide (total, count) = fromIntegral total / count
add (total, count) x = (total + x, count + 1)
averageForce :: Monad m => ConduitM Int o m Double
averageForce =
divide <$> foldlC add (0, 0)
where
divide (total, count) = fromIntegral total / count
add (total, count) x = force (total + x, count + 1)
averageBangs :: Monad m => ConduitM Int o m Double
averageBangs =
divide <$> foldlC add (0, 0)
where
divide (total, count) = fromIntegral total / count
add (total, count) x =
let
!total' = total + x
!count' = count + 1
in
(total', count')
data StrictPair =
P !Int !Int
averageCustom :: Monad m => ConduitM Int o m Double
averageCustom =
divide <$> foldlC add (P 0 0)
where
divide :: StrictPair -> Double
divide (P total count) = fromIntegral total / fromIntegral count
add (P total count) x = P (total + x) (count + 1)
main :: IO ()
main =
print $ runConduitPure $ enumFromToC 1 1000000 .| averageCustom
data StrictList a =
Cons !a !(StrictList a) | Nil
strictMap :: (a -> b) -> StrictList a -> StrictList b
strictMap _ Nil = Nil
strictMap f (Cons a list) =
let !b = f a
!list' = strictMap f list
in b `seq` list' `seq` Cons b list'
strictEnum :: Int -> Int -> StrictList Int
strictEnum low high =
go low where
go !x
| x == high = Cons x Nil
| otherwise = Cons x (go $! x + 1)
double :: Int -> Int
double !x = x * 2
evens :: StrictList Int
evens = strictMap double $! strictEnum 1 1000000
main5 :: IO ()
main5 = do
let string = "Hello World"
-- !string' = evens `seq` string -- max mem usage
string' = evens `seq` string
-- putStrLn $ string' `seq` string -- max mem usage
putStrLn string
|
futtetennista/IntroductionToFunctionalProgramming
|
src/StrictnessPlayground.hs
|
Haskell
|
mit
| 4,098
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DuplicateRecordFields #-}
module Language.LSP.Types.DocumentSymbol where
import Data.Aeson
import Data.Aeson.TH
import Data.Scientific
import Data.Text (Text)
import Language.LSP.Types.TextDocument
import Language.LSP.Types.Common
import Language.LSP.Types.Location
import Language.LSP.Types.Progress
import Language.LSP.Types.Utils
-- ---------------------------------------------------------------------
makeExtendingDatatype "DocumentSymbolOptions"
[''WorkDoneProgressOptions]
[ ("_label", [t| Maybe Bool |])]
deriveJSON lspOptions ''DocumentSymbolOptions
makeExtendingDatatype "DocumentSymbolRegistrationOptions"
[ ''TextDocumentRegistrationOptions
, ''DocumentSymbolOptions
] []
deriveJSON lspOptions ''DocumentSymbolRegistrationOptions
-- ---------------------------------------------------------------------
makeExtendingDatatype "DocumentSymbolParams"
[ ''WorkDoneProgressParams
, ''PartialResultParams
]
[ ("_textDocument", [t| TextDocumentIdentifier |])]
deriveJSON lspOptions ''DocumentSymbolParams
-- -------------------------------------
data SymbolKind
= SkFile
| SkModule
| SkNamespace
| SkPackage
| SkClass
| SkMethod
| SkProperty
| SkField
| SkConstructor
| SkEnum
| SkInterface
| SkFunction
| SkVariable
| SkConstant
| SkString
| SkNumber
| SkBoolean
| SkArray
| SkObject
| SkKey
| SkNull
| SkEnumMember
| SkStruct
| SkEvent
| SkOperator
| SkTypeParameter
| SkUnknown Scientific
deriving (Read,Show,Eq)
instance ToJSON SymbolKind where
toJSON SkFile = Number 1
toJSON SkModule = Number 2
toJSON SkNamespace = Number 3
toJSON SkPackage = Number 4
toJSON SkClass = Number 5
toJSON SkMethod = Number 6
toJSON SkProperty = Number 7
toJSON SkField = Number 8
toJSON SkConstructor = Number 9
toJSON SkEnum = Number 10
toJSON SkInterface = Number 11
toJSON SkFunction = Number 12
toJSON SkVariable = Number 13
toJSON SkConstant = Number 14
toJSON SkString = Number 15
toJSON SkNumber = Number 16
toJSON SkBoolean = Number 17
toJSON SkArray = Number 18
toJSON SkObject = Number 19
toJSON SkKey = Number 20
toJSON SkNull = Number 21
toJSON SkEnumMember = Number 22
toJSON SkStruct = Number 23
toJSON SkEvent = Number 24
toJSON SkOperator = Number 25
toJSON SkTypeParameter = Number 26
toJSON (SkUnknown x) = Number x
instance FromJSON SymbolKind where
parseJSON (Number 1) = pure SkFile
parseJSON (Number 2) = pure SkModule
parseJSON (Number 3) = pure SkNamespace
parseJSON (Number 4) = pure SkPackage
parseJSON (Number 5) = pure SkClass
parseJSON (Number 6) = pure SkMethod
parseJSON (Number 7) = pure SkProperty
parseJSON (Number 8) = pure SkField
parseJSON (Number 9) = pure SkConstructor
parseJSON (Number 10) = pure SkEnum
parseJSON (Number 11) = pure SkInterface
parseJSON (Number 12) = pure SkFunction
parseJSON (Number 13) = pure SkVariable
parseJSON (Number 14) = pure SkConstant
parseJSON (Number 15) = pure SkString
parseJSON (Number 16) = pure SkNumber
parseJSON (Number 17) = pure SkBoolean
parseJSON (Number 18) = pure SkArray
parseJSON (Number 19) = pure SkObject
parseJSON (Number 20) = pure SkKey
parseJSON (Number 21) = pure SkNull
parseJSON (Number 22) = pure SkEnumMember
parseJSON (Number 23) = pure SkStruct
parseJSON (Number 24) = pure SkEvent
parseJSON (Number 25) = pure SkOperator
parseJSON (Number 26) = pure SkTypeParameter
parseJSON (Number x) = pure (SkUnknown x)
parseJSON _ = fail "SymbolKind"
{-|
Symbol tags are extra annotations that tweak the rendering of a symbol.
@since 3.16.0
-}
data SymbolTag =
StDeprecated -- ^ Render a symbol as obsolete, usually using a strike-out.
| StUnknown Scientific
deriving (Read, Show, Eq)
instance ToJSON SymbolTag where
toJSON StDeprecated = Number 1
toJSON (StUnknown x) = Number x
instance FromJSON SymbolTag where
parseJSON (Number 1) = pure StDeprecated
parseJSON (Number x) = pure (StUnknown x)
parseJSON _ = fail "SymbolTag"
-- -------------------------------------
data DocumentSymbolKindClientCapabilities =
DocumentSymbolKindClientCapabilities
{ -- | The symbol kind values the client supports. When this
-- property exists the client also guarantees that it will
-- handle values outside its set gracefully and falls back
-- to a default value when unknown.
--
-- If this property is not present the client only supports
-- the symbol kinds from `File` to `Array` as defined in
-- the initial version of the protocol.
_valueSet :: Maybe (List SymbolKind)
}
deriving (Show, Read, Eq)
deriveJSON lspOptions ''DocumentSymbolKindClientCapabilities
data DocumentSymbolTagClientCapabilities =
DocumentSymbolTagClientCapabilities
{ -- | The tags supported by the client.
_valueSet :: Maybe (List SymbolTag)
}
deriving (Show, Read, Eq)
deriveJSON lspOptions ''DocumentSymbolTagClientCapabilities
data DocumentSymbolClientCapabilities =
DocumentSymbolClientCapabilities
{ -- | Whether document symbol supports dynamic registration.
_dynamicRegistration :: Maybe Bool
-- | Specific capabilities for the `SymbolKind`.
, _symbolKind :: Maybe DocumentSymbolKindClientCapabilities
, _hierarchicalDocumentSymbolSupport :: Maybe Bool
-- | The client supports tags on `SymbolInformation`.
-- Clients supporting tags have to handle unknown tags gracefully.
--
-- @since 3.16.0
, _tagSupport :: Maybe DocumentSymbolTagClientCapabilities
-- | The client supports an additional label presented in the UI when
-- registering a document symbol provider.
--
-- @since 3.16.0
, _labelSupport :: Maybe Bool
} deriving (Show, Read, Eq)
deriveJSON lspOptions ''DocumentSymbolClientCapabilities
-- ---------------------------------------------------------------------
-- | Represents programming constructs like variables, classes, interfaces etc.
-- that appear in a document. Document symbols can be hierarchical and they
-- have two ranges: one that encloses its definition and one that points to its
-- most interesting range, e.g. the range of an identifier.
data DocumentSymbol =
DocumentSymbol
{ _name :: Text -- ^ The name of this symbol.
-- | More detail for this symbol, e.g the signature of a function. If not
-- provided the name is used.
, _detail :: Maybe Text
, _kind :: SymbolKind -- ^ The kind of this symbol.
, _tags :: Maybe (List SymbolTag) -- ^ Tags for this document symbol.
, _deprecated :: Maybe Bool -- ^ Indicates if this symbol is deprecated. Deprecated, use tags instead.
-- | The range enclosing this symbol not including leading/trailing
-- whitespace but everything else like comments. This information is
-- typically used to determine if the the clients cursor is inside the symbol
-- to reveal in the symbol in the UI.
, _range :: Range
-- | The range that should be selected and revealed when this symbol is being
-- picked, e.g the name of a function. Must be contained by the the '_range'.
, _selectionRange :: Range
-- | Children of this symbol, e.g. properties of a class.
, _children :: Maybe (List DocumentSymbol)
} deriving (Read,Show,Eq)
deriveJSON lspOptions ''DocumentSymbol
-- ---------------------------------------------------------------------
-- | Represents information about programming constructs like variables, classes,
-- interfaces etc.
data SymbolInformation =
SymbolInformation
{ _name :: Text -- ^ The name of this symbol.
, _kind :: SymbolKind -- ^ The kind of this symbol.
, _tags :: Maybe (List SymbolTag) -- ^ Tags for this symbol.
, _deprecated :: Maybe Bool -- ^ Indicates if this symbol is deprecated. Deprecated, use tags instead.
-- | The location of this symbol. The location's range is used by a tool
-- to reveal the location in the editor. If the symbol is selected in the
-- tool the range's start information is used to position the cursor. So
-- the range usually spans more then the actual symbol's name and does
-- normally include things like visibility modifiers.
--
-- The range doesn't have to denote a node range in the sense of a abstract
-- syntax tree. It can therefore not be used to re-construct a hierarchy of
-- the symbols.
, _location :: Location
-- | The name of the symbol containing this symbol. This information is for
-- user interface purposes (e.g. to render a qualifier in the user interface
-- if necessary). It can't be used to re-infer a hierarchy for the document
-- symbols.
, _containerName :: Maybe Text
} deriving (Read,Show,Eq)
{-# DEPRECATED _deprecated "Use tags instead" #-}
deriveJSON lspOptions ''SymbolInformation
|
wz1000/haskell-lsp
|
lsp-types/src/Language/LSP/Types/DocumentSymbol.hs
|
Haskell
|
mit
| 9,390
|
-- | Main module
module Main where
import Network.HTTP.Conduit
import System.Environment (getArgs)
import qualified Data.Text as T
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as L
import Control.Monad.IO.Class (liftIO)
import Text.Playlist
import Control.Concurrent
import Control.Monad
-- | Fetches the playlist from the given url
fetchPlaylist :: String -> IO BS.ByteString
fetchPlaylist urlString = do
case parseUrl urlString of
Nothing -> fail "Sorry, invalid URL"
Just req -> withManager $ \manager -> do
res <- httpLbs req manager
return $ L.toStrict $ responseBody res
runJob urlString = threadDelay (1000 * 1000) >> do
content <- fetchPlaylist urlString
case parsePlaylist M3U content of
Left err -> fail $ "failed to parse playlist on stdin: " ++ err
Right x -> liftIO $ putStr $ unlines $ map (T.unpack . trackURL) x
-- | Application entry point
main :: IO ()
main = do
args <- getArgs
case args of
[urlString] -> forever $ runJob urlString
_ -> putStrLn "Sorry, please provide exactly one URL"
|
DavidKlassen/haschup
|
src/Haschup.hs
|
Haskell
|
mit
| 1,135
|
-----------------------------------------------------------------------------
--
-- Module : TypeNum.Test.Int
-- Copyright :
-- License : MIT
--
-- Maintainer : -
-- Stability :
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module TypeNum.Test.Int where
import TypeNum.Test.Common
import TypeNum.Integer
-----------------------------------------------------------------------------
intSpec = describe "TypeNum.Integer.TInt" $ do
describe "is comparable at type-level ((==), TypesEq and TypesOrd)" $ do
specify "==" $ correct (B::B (Pos 1 == Pos 1))
&& correct (B::B (Pos 1 ~=~ 1))
&& correct (B::B (Neg 5 == Neg 5))
&& correct (B::B (Pos 0 == Neg 0))
&& correct (B::B (Pos 0 ~=~ 0))
&& mistake (B::B (Neg 1 ~=~ 1))
&& mistake (B::B (Pos 5 == Pos 2))
specify ">" $ correct (B::B (Pos 2 > Pos 1))
&& correct (B::B (Neg 1 > Neg 2))
&& correct (B::B (Pos 0 > Neg 2))
&& mistake (B::B (Pos 2 > Pos 5))
&& mistake (B::B (Pos 0 > Pos 1))
&& mistake (B::B (Neg 1 > Pos 1))
specify "<" $ correct (B::B (Pos 1 < Pos 2))
&& correct (B::B (Neg 1 < Pos 2))
&& correct (B::B (Neg 2 < Neg 1))
&& mistake (B::B (Neg 4 < Neg 4))
&& mistake (B::B (Pos 4 < Neg 1))
specify ">=" $ correct (B::B (Pos 2 >= Pos 1))
&& correct (B::B (Neg 1 >= Neg 2))
&& correct (B::B (Pos 0 >= Neg 2))
&& correct (B::B (Pos 2 >= Pos 2))
&& mistake (B::B (Pos 0 >= Pos 1))
&& mistake (B::B (Neg 1 >= Pos 1))
--
specify "<=" $ correct (B::B (Pos 1 <= Pos 2))
&& correct (B::B (Neg 1 <= Pos 2))
&& correct (B::B (Neg 2 <= Neg 1))
&& correct (B::B (Neg 4 <= Neg 4))
&& mistake (B::B (Pos 4 <= Neg 1))
describe "has natural number operations at type-level (TypesNat)" $ do
it "provides type-level sum '(+)'" $
correct (B::B ((Pos 1 + Pos 1 :: TInt) == Pos 2))
&& correct (B::B ((Pos 4 + Pos 5 :: TInt) == Pos 9))
&& correct (B::B ((Neg 4 + Pos 5 :: TInt) == Pos 1))
&& correct (B::B ((Neg 5 + Pos 5 :: TInt) == Pos 0))
&& correct (B::B ((Pos 4 + Pos 5 :: TInt) == (Pos 2 + Pos 7 :: TInt)))
&& correct (B::B ((Neg 4 + Pos 5 :: TInt) == (Pos 5 + Neg 4 :: TInt)))
&& correct (B::B ((Neg 5 + Pos 5 :: TInt) == (Pos 4 + Neg 4 :: TInt)))
&& mistake (B::B ((Neg 4 + Pos 5 :: TInt) == Pos 4))
&& mistake (B::B ((Neg 5 + Pos 5 :: TInt) == Neg 1))
&& mistake (B::B ((Pos 4 + Pos 5 :: TInt) == (Pos 2 + Pos 2 :: TInt)))
&& mistake (B::B ((Neg 4 + Pos 5 :: TInt) == (Pos 5 + Pos 4 :: TInt)))
it "provides type-level absolute difference '(/-)'" $
correct (B::B ((Pos 1 /- Pos 3 :: TInt) ~=~ 2))
&& correct (B::B ((Pos 3 /- Pos 1 :: TInt) ~=~ 2))
&& correct (B::B ((Pos 3 /- Pos 3 :: TInt) ~=~ 0))
&& correct (B::B ((Neg 1 /- Neg 3 :: TInt) ~=~ 2))
&& correct (B::B ((Neg 1 /- Pos 3 :: TInt) ~=~ 4))
&& correct (B::B ((Pos 1 /- Neg 3 :: TInt) ~=~ 4))
&& mistake (B::B ((Pos 3 /- Pos 3 :: TInt) ~=~ 2))
it "provides type-level multiplication '(*)'" $
correct (B::B ((Pos 1 * Pos 3 :: TInt) ~=~ 3))
&& correct (B::B ((Pos 3 * Pos 1 :: TInt) ~=~ 3))
&& correct (B::B ((Neg 3 * Pos 1 :: TInt) == Neg 3))
&& correct (B::B ((Neg 3 * Neg 1 :: TInt) == Pos 3))
&& correct (B::B ((Neg 3 * Zero :: TInt) ~=~ 0))
&& correct (B::B ((Zero * Pos 9 :: TInt) ~=~ 0))
&& mistake (B::B ((Pos 2 * Pos 3 :: TInt) ~=~ 9))
it "provides type-level power '(^)'" $ pending
describe "has integral number operations at type-level (TypesIntegral)" $ do
it "provides type-level integer division truncated toward zero 'Quot'" $
correct (B::B (((QuotRem (Pos 3) (Pos 3)) :: (TInt, TInt)) == ('(Pos 1, Zero))))
&& correct (B::B (((QuotRem (Pos 1) (Pos 2)) :: (TInt, TInt)) == ('(Zero, Pos 1))))
&& correct (B::B (((QuotRem (Pos 2) (Pos 1)) :: (TInt, TInt)) == ('(Pos 2, Zero))))
&& correct (B::B (((QuotRem (Pos 4) (Pos 3)) :: (TInt, TInt)) == ('(Pos 1, Pos 1))))
&& correct (B::B (((QuotRem (Neg 4) (Pos 3)) :: (TInt, TInt)) == ('(Neg 1, Neg 1))))
&& correct (B::B (((Rem (Pos 3) (Pos 3)) :: TInt) == Zero))
&& correct (B::B (((Rem (Pos 3) (Pos 3)) :: TInt) < Pos 1))
&& correct (B::B (((Rem (Pos 4) (Pos 3)) :: TInt) == Pos 1))
&& correct (B::B (Zero < Pos 1))
&& correct (B::B ( ((Rem (Pos 3) (Pos 3)) :: TInt) < ((Rem (Pos 4) (Pos 3)) :: TInt) ))
it "provides type-level integer division truncated toward negative infinity 'Div'" $
example pending
describe "has sign operations at type-level (TypeSign)" $ do
it "provides type-level sign" $ example pending
it "provides type-level absolute value" $ example pending
it "provides type-level unary negation" $ example pending
it "provides type-level sign to number transformation" $ example pending
describe "has subtraction operation at type-level (TypesSubtraction)" $
it "provides type-level subtraction (-)" $ example pending
|
fehu/TypeNumerics
|
test/TypeNum/Test/Int.hs
|
Haskell
|
mit
| 5,791
|
{-# htermination (until :: (a -> MyBool) -> (a -> a) -> a -> a) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
until0 x p f MyTrue = x;
until0 x p f MyFalse = until p f (f x);
until :: (a -> MyBool) -> (a -> a) -> a -> a;
until p f x = until0 x p f (p x);
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/basic_haskell/until_1.hs
|
Haskell
|
mit
| 331
|
import System.Environment (getArgs)
interactWith function inputFile outputFile = do
input <- readFile inputFile
writeFile outputFile (function input)
main = mainWith myFunction
where mainWith function = do
args <- getArgs
case args of
[input, output] -> interactWith function input output
_ -> putStrLn "error: exactly two arguments needed"
myFunction = id
|
zhangjiji/real-world-haskell
|
ch4-interactWith.hs
|
Haskell
|
mit
| 418
|
module Main where
import Test.HUnit (runTestTT, Test(TestList))
import Tests.IRC.Commands (respondTest)
main :: IO ()
main = do
_ <- runTestTT $ TestList [respondTest]
return ()
|
jdiez17/HaskellHawk
|
test/Main.hs
|
Haskell
|
mit
| 191
|
module Lexer where
import Text.Parsec.String (Parser)
import Text.Parsec.Language (emptyDef)
import qualified Text.Parsec.Token as Tok
lexer :: Tok.TokenParser ()
lexer = Tok.makeTokenParser style
where
ops = ["+","*","-","/",";",",","<"]
names = ["def","extern"]
style = emptyDef {
Tok.commentLine = "#"
, Tok.reservedOpNames = ops
, Tok.reservedNames = names
}
integer = Tok.integer lexer
float = Tok.float lexer
parens = Tok.parens lexer
commaSep = Tok.commaSep lexer
semiSep = Tok.semiSep lexer
identifier = Tok.identifier lexer
whitespace = Tok.whiteSpace lexer
reserved = Tok.reserved lexer
reservedOp = Tok.reservedOp lexer
|
TorosFanny/kaleidoscope
|
src/chapter3/Lexer.hs
|
Haskell
|
mit
| 722
|
{-# htermination max :: () -> () -> () #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_max_1.hs
|
Haskell
|
mit
| 43
|
module System.Random.PCG
(
mkPCGGen
, getPCGGen
, newPCGGen
, getPCGRandom
)
where
import System.CPUTime (getCPUTime)
import Data.Time.Clock.POSIX (getPOSIXTime)
import System.Random
import System.Random.PCG.Internal
import Data.IORef
import System.IO.Unsafe ( unsafePerformIO )
{-# NOINLINE globalGen #-}
globalGen :: IORef PCGGen
globalGen = unsafePerformIO $ do
gen <- mkPCGGen'
newIORef gen
-- | This is not really robust.
mkPCGGen' :: IO PCGGen
mkPCGGen' = do
pTime <- getPOSIXTime
sTime <- getCPUTime
pure $ mkPCGGen (floor pTime) (fromInteger sTime)
newPCGGen :: IO PCGGen
newPCGGen = atomicModifyIORef' globalGen split
getPCGGen :: IO PCGGen
getPCGGen = readIORef globalGen
getPCGRandom :: (PCGGen -> (a, PCGGen)) -> IO a
getPCGRandom f = atomicModifyIORef' globalGen (swap . f)
where swap (b, a) = (a, b)
|
wmarvel/haskellrogue
|
src/System/Random/PCG.hs
|
Haskell
|
mit
| 849
|
module Vacchi.Fractals.Types where
------------------------------------------
-- config types (used in config.hs)
------------------------------------------
data Fractal = Fractal {
fractal :: [IFS], -- IFS list
scaleFactor :: Float, -- scaling factor
iterations :: Int, -- number of iterations
offsetX :: Float, -- horizontal offset on the canvas
offsetY :: Float -- vertical offset on the canvas
}
data Params = Params {
penSize :: Float, -- size of the circles on the canvas
palette :: (Float,Float), -- color interval of the palette (subrange in [0,1])
alpha :: Float -> Float, -- function from a hue value to an alpha value [0,1]
saturation :: Float->Float, -- function from a hue value to a saturation value [0,1]
lightness :: Float->Float, -- function from a hue value to a lightness value [0,1]
animated :: Bool -- True for an animated visualization, False for static
}
------------------------------------------
-- types used in actual computations
------------------------------------------
-- A variation is just a function R^2->R^2
type Variation = (Float,Float) -> (Float,Float)
-- IFS data type
--
-- it represents a IFS function as a pair of triples
-- specifying the coefficients for x, y
-- the last float value is a probability
--
-- the IfsVar alternate datatype provides a Variation type, which is a function
data IFS = Ifs (Float,Float,Float) (Float,Float,Float) Float
| IfsVar (Float,Float,Float) (Float,Float,Float) Float Variation
-- definition of an IFS function:
ifs_def :: (Float,Float) -- input point (x_0,y_0)
-> (Float,Float,Float) -- coefficients for the x coord
-> (Float,Float,Float) -- coefficients for the y coord
-> (Float,Float) -- result (x_1, y_1)
ifs_def (x,y) (a,b,c) (d,e,f) = (a*x + b*y + c, d*x + e*y + f)
-- default implementation for non-variated IFS
ifs :: (Float,Float) -> IFS -> (Float,Float)
ifs point (Ifs param1 param2 _) =
let result = ifs_def point param1 param2
in (fst result, snd result)
-- implementation for variated IFS
ifs point (IfsVar param1 param2 _ variation_function) =
let result = variation_function (ifs_def point param1 param2)
in (fst result, snd result)
|
evacchi/chaosgame
|
src/Vacchi/Fractals/Types.hs
|
Haskell
|
mit
| 2,207
|
-- | Author : John Allard
-- | Date : Feb 5th 2016
-- | Class : CMPS 112 UCSC
-- | I worked alone, no partners to list.
-- | Homework #3 |--
import Data.Char
import Data.List
-- | 1. Suppose we have the following type of binary search trees with
-- keys of type k and values of type v:
data BST k v = Empty |
Node k v (BST k v) (BST k v)
-- | Write a val function that returns Just the stored value at the
-- root node of the tree. If the tree is empty, val returns Nothing.
val :: BST k v -> Maybe v
val Empty = Nothing
val (Node key val lbst rbst) = Just val
-- | 2. Write a size function that returns the number of nodes in the tree.
size :: BST k v -> Int
size Empty = 0
size (Node key val lbst rbst) = 1 + (size lbst) + (size rbst)
-- | 3. Write an ins function that inserts a value v using k as key. If the
-- key is already used in the tree, it just updates the value, otherwise
-- it will add a new node while maintaining the order of the binary search tree.
ins :: (Ord k) => k -> v -> BST k v -> BST k v
ins key val Empty = (Node key val (Empty) (Empty))
ins key val (Node k v lbst rbst) = if key < k
then Node k v (ins key val (lbst)) rbst
else Node k v lbst (ins key val (rbst))
-- | 4. Make BST an instance of the Show type class. You will have to implement the
-- show function such that the result every node of the tree is shown as "(leftTree value rightTree)".
instance (Show v) => Show (BST k v) where
show Empty = ""
show (Node k v left right) = "(" ++ show left ++ " " ++ show v ++ " " ++ show right ++ ")"
-- | 5. Suppose we had the following datatype
data JSON = JStr String
| JNum Double
| JArr [JSON]
| JObj [(String, JSON)]
-- | make JSON an instance of the Show type class. You will have to implement the show function such that the
-- output looks like normal JSON.
instance Show JSON where
show (JStr s) = show s
show (JNum d) = show d
show (JArr a) = "[" ++ intercalate ", " (map show a) ++ "]"
show (JObj lst) = "{" ++ intercalate ", " (map (\x -> show (fst x) ++ ":" ++ show (snd x)) lst) ++ "}"
|
jhallard/WinterClasses16
|
CS112/hw/hw3/hw3.hs
|
Haskell
|
mit
| 2,208
|
module HandBrake.Encode
( AudioTracks(..), Chapters(..), EncodeDetails, EncodeRequest, Numbering(..)
, Profile(..), SubtitleTracks( SubtitleTracks ), TwoPass(..)
, audioEncoder, audios, chapters, details, encodeArgs, encodeRequest
, encodeRequest1, input, name, numbering, options, outputDir, outputName
, profile, quality, subtitles, titleID, twoPass
, parseEncodeDetails
, readNT
)
where
import Prelude ( Float, (+), (-), fromIntegral )
-- base --------------------------------
import Control.Applicative ( optional, pure, some )
import Control.Monad ( mapM, return )
import Data.Eq ( Eq )
import Data.Function ( ($), id )
import Data.List.NonEmpty ( NonEmpty( (:|) ) )
import Data.Maybe ( maybe )
import Data.Ord ( Ordering( GT, EQ, LT ), (<), compare )
import Data.String ( unwords )
import GHC.Generics ( Generic )
import Text.Read ( read )
import Text.Show ( Show( show ) )
-- base-unicode-symbols ----------------
import Data.Eq.Unicode ( (≡) )
import Data.Function.Unicode ( (∘) )
import Data.Monoid.Unicode ( (⊕) )
import Numeric.Natural.Unicode ( ℕ )
import Prelude.Unicode ( ℤ )
-- data-textual ------------------------
import Data.Textual ( Printable( print ), toText )
-- deepseq -----------------------------
import Control.DeepSeq ( NFData )
-- fpath -------------------------------
import qualified FPath.Parseable
import FPath.AbsDir ( AbsDir )
import FPath.AbsFile ( AbsFile )
import FPath.AppendableFPath ( (⫻) )
import FPath.Error.FPathError ( AsFPathError )
import FPath.Parseable ( readM )
import FPath.PathComponent ( PathComponent )
import FPath.RelFile ( RelFile )
-- lens --------------------------------
import Control.Lens.Lens ( Lens', lens )
-- more-unicode ------------------------
import Data.MoreUnicode.Applicative ( (⋪), (⋫), (⊵), (∤) )
import Data.MoreUnicode.Functor ( (⊳) )
import Data.MoreUnicode.Lens ( (⊣) )
import Data.MoreUnicode.Maybe ( 𝕄, pattern 𝕵, pattern 𝕹 )
import Data.MoreUnicode.Monad ( (≫) )
import Data.MoreUnicode.Monoid ( ю )
import Data.MoreUnicode.Text ( 𝕋 )
-- mtl ---------------------------------
import Control.Monad.Except ( MonadError )
-- optparse-applicative ----------------
import Options.Applicative.Builder ( auto, flag, flag', help
, long, option, short, strOption, value )
import Options.Applicative.Types ( Parser )
-- optparse-plus -----------------------
import OptParsePlus ( parsecReader, parsecReadM, readNT )
-- parsec-plus -------------------------
import ParsecPlus ( Parsecable( parser ) )
-- parsers -----------------------------
import Text.Parser.Char ( CharParsing, char, digit, string )
import Text.Parser.Combinators ( sepBy, eof )
-- parser-plus -------------------------
import ParserPlus ( parseFloat2_1, sepByNE, tries )
-- range -------------------------------
import Data.Range ( Bound( Bound ), BoundType( Exclusive, Inclusive ),
Range( InfiniteRange, LowerBoundRange, SingletonRange
, SpanRange, UpperBoundRange )
, (+=+)
)
-- stdmain -----------------------------
import StdMain.UsageError ( AsUsageError, throwUsage )
-- text --------------------------------
import Data.Text ( map, pack )
-- text-printer ------------------------
import qualified Text.Printer as P
-- tfmt --------------------------------
import Text.Fmt ( fmt, fmtT )
--------------------------------------------------------------------------------
data TwoPass = TwoPass | NoTwoPass
deriving (Eq,Generic,NFData,Show)
parseTwoPass ∷ Parser TwoPass
parseTwoPass = flag TwoPass NoTwoPass
(ю [ short 'S'
, long "--single-pass"
, help "single-pass encoding (faster, worse" ])
------------------------------------------------------------
data Numbering = NoNumber
| Number ℤ {- with output offset -}
| Series (ℕ,𝕋) ℤ {- title, series number, output offset -}
deriving (Eq,Generic,NFData,Show)
parseNumbering ∷ Parser Numbering
parseNumbering =
let
parseNumber ∷ Parser (ℤ → Numbering)
parseNumber = pure Number
parseSeries ∷ Parser (ℤ → Numbering)
parseSeries = Series ⊳ option readNT (ю [ short 'e', long "series"
, help "series NUM=NAME" ])
parseOffset ∷ Parser ℤ
parseOffset = option auto (ю [ short 'i', long "input-offset", value 0
, help "offset output numbers" ])
parseNoNumber ∷ Parser Numbering
parseNoNumber = flag' NoNumber (short 'N' ⊕ long "no-number")
in
(((parseNumber ∤ parseSeries) ⊵ parseOffset) ∤ parseNoNumber)
------------------------------------------------------------
data Profile = ProfileH265_2160P | ProfileH265_1080P | ProfileH265_720P
| ProfileH265_576P | ProfileH265_480P
-- Dead Video is a super-simple video profile, meant for
-- throwaway video (e.g., tracks where the video is static,
-- that we'll later just rip the audio from)
| Profile_DeadVideo
deriving (Eq,Generic,NFData,Show)
instance Printable Profile where
print ProfileH265_2160P = P.text "H.265 MKV 2160p60"
print ProfileH265_1080P = P.text "H.265 MKV 1080p30"
print ProfileH265_720P = P.text "H.265 MKV 720p30"
print ProfileH265_576P = P.text "H.265 MKV 576p25"
print ProfileH265_480P = P.text "H.265 MKV 480p30"
print Profile_DeadVideo = P.text "H.265 MKV 480p30"
instance Parsecable Profile where
parser = let names ∷ CharParsing ψ ⇒ (NonEmpty (ψ Profile))
names = (pure ProfileH265_2160P ⋪ string "2160")
:| [ pure ProfileH265_1080P ⋪ string "1080"
, pure ProfileH265_2160P ⋪ string "1080"
, pure ProfileH265_720P ⋪ string "720"
, pure ProfileH265_576P ⋪ string "576"
, pure ProfileH265_480P ⋪ string "480"
, pure Profile_DeadVideo ⋪ string "D"
]
in tries names ⋪ optional (char 'p' ∤ char 'P') ⋪ eof
parseProfile ∷ Parser Profile
parseProfile =
option parsecReader (ю [ short 'p', long "profile" , help "encoding profile"
, value ProfileH265_2160P ])
------------------------------------------------------------
newtype Chapters = Chapters { unChapters ∷ 𝕄 (Range ℕ) }
instance Show Chapters where
show c = [fmt|Chapters «%T»|] c
instance Printable Chapters where
print (Chapters 𝕹) = P.text ""
print (Chapters (𝕵 (SingletonRange n))) = P.text $ [fmt|%d|] n
print (Chapters (𝕵 (InfiniteRange))) = P.text $ [fmt|-|]
print (Chapters (𝕵 (LowerBoundRange (Bound a Inclusive)))) =
P.text $ [fmt|[%d-|] a
print (Chapters (𝕵 (LowerBoundRange (Bound a Exclusive)))) =
P.text $ [fmt|(%d-|] a
print (Chapters (𝕵 (UpperBoundRange (Bound a Inclusive)))) =
P.text $ [fmt|-%d]|] a
print (Chapters (𝕵 (UpperBoundRange (Bound a Exclusive)))) =
P.text $ [fmt|-%d)|] a
print (Chapters (𝕵 (SpanRange (Bound a Inclusive) (Bound b Inclusive)))) =
P.text $ [fmt|[%d-%d]|] a b
print (Chapters (𝕵 (SpanRange (Bound a Exclusive) (Bound b Inclusive)))) =
P.text $ [fmt|(%d-%d]|] a b
print (Chapters (𝕵 (SpanRange (Bound a Inclusive) (Bound b Exclusive)))) =
P.text $ [fmt|[%d-%d)|] a b
print (Chapters (𝕵 (SpanRange (Bound a Exclusive) (Bound b Exclusive)))) =
P.text $ [fmt|(%d-%d)|] a b
parseSimpleNRange ∷ CharParsing γ ⇒ γ (Range ℕ)
parseSimpleNRange =
let readN ∷ CharParsing γ ⇒ γ ℕ
readN = read ⊳ some digit
toRange ∷ ℕ → 𝕄 ℕ → Range ℕ
toRange a 𝕹 = SingletonRange a
toRange a (𝕵 b) = a +=+ b
in toRange ⊳ readN ⊵ optional (char '-' ⋫ readN)
instance Parsecable Chapters where
parser = Chapters ∘ 𝕵 ⊳ parseSimpleNRange
parseChapters ∷ Parser Chapters
parseChapters =
option parsecReader (ю [ short 'c', long "chapters", value (Chapters 𝕹)
, help "select chapters to encode" ])
------------------------------------------------------------
defaultQuality ∷ Float
defaultQuality = 26
parseQuality ∷ Parser Float
parseQuality =
option (parsecReadM "-q" parseFloat2_1)
(ю [ short 'q', long "quality", value defaultQuality
, help $ [fmt|encoding quality (default %3.1f)|] defaultQuality
])
----------------------------------------
parseOutputName ∷ Parser (𝕄 PathComponent)
parseOutputName =
let mods = ю [ short 'o', long "output", help "output file base name" ]
in optional (option readM mods)
----------------------------------------
parseAudioEncoder ∷ Parser (𝕄 𝕋)
parseAudioEncoder =
let mods = ю [ short 'E', long "aencoder", long "audio-encoder"
, help "set audio encoder(s) (see HandBrakeCLI -E)" ]
in optional (strOption mods)
------------------------------------------------------------
{- | Options that have standard values, but may be adjusted for encodes. -}
data EncodeOptions = EncodeOptions { _numbering ∷ Numbering
, _chapters ∷ Chapters
, _twoPass ∷ TwoPass
, _profile ∷ Profile
-- 20 is default, use 26 for 1080p
, _quality ∷ Float
, _outputName ∷ 𝕄 PathComponent
, _audioEncoder ∷ 𝕄 𝕋
}
deriving Show
------------------------------------------------------------
class HasEncodeOptions α where
_EncodeOptions ∷ Lens' α EncodeOptions
numbering ∷ Lens' α Numbering
numbering = _EncodeOptions ∘ numbering
chapters ∷ Lens' α Chapters
chapters = _EncodeOptions ∘ chapters
twoPass ∷ Lens' α TwoPass
twoPass = _EncodeOptions ∘ twoPass
profile ∷ Lens' α Profile
profile = _EncodeOptions ∘ profile
quality ∷ Lens' α Float
quality = _EncodeOptions ∘ quality
outputName ∷ Lens' α (𝕄 PathComponent)
outputName = _EncodeOptions ∘ outputName
audioEncoder ∷ Lens' α (𝕄 𝕋)
audioEncoder = _EncodeOptions ∘ audioEncoder
instance HasEncodeOptions EncodeOptions where
_EncodeOptions = id
numbering = lens _numbering (\ eo x → eo { _numbering = x })
chapters = lens _chapters (\ eo x → eo { _chapters = x })
twoPass = lens _twoPass (\ eo x → eo { _twoPass = x })
profile = lens _profile (\ eo x → eo { _profile = x })
quality = lens _quality (\ eo x → eo { _quality = x })
audioEncoder = lens _audioEncoder (\ eo x → eo { _audioEncoder = x })
outputName = lens _outputName (\ eo n → eo { _outputName = n })
----------------------------------------
parseEncodeOptions ∷ Parser EncodeOptions
parseEncodeOptions =
EncodeOptions ⊳ parseNumbering
⊵ parseChapters
⊵ parseTwoPass
⊵ parseProfile
⊵ parseQuality
⊵ parseOutputName
⊵ parseAudioEncoder
------------------------------------------------------------
newtype AudioTracks = AudioTracks { unAudioTracks ∷ NonEmpty ℕ }
deriving Show
instance Parsecable AudioTracks where
parser = AudioTracks ⊳ sepByNE (read ⊳ some digit) (char ',')
parseAudioTracks ∷ Parser AudioTracks
parseAudioTracks =
option parsecReader
(ю [ short 'a', long "audios"
, help (unwords [ "audio track ids; as reported by scan. These will"
, "be a 1-based index." ])
]
)
------------------------------------------------------------
newtype SubtitleTracks = SubtitleTracks { unSubtitleTracks ∷ [ℕ] }
deriving Show
instance Parsecable SubtitleTracks where
parser = SubtitleTracks ⊳ sepBy (read ⊳ some digit) (char ',')
parseSubtitleTracks ∷ Parser SubtitleTracks
parseSubtitleTracks =
option parsecReader
(ю [ help (unwords [ "subtitle track ids; as reported by scan. These"
, "will be a 1-based index. The first subtitle"
, "selected will be set as the default."
]
)
, value $ SubtitleTracks []
, short 's'
, long "subs"
, long "subtitles"
])
------------------------------------------------------------
{- | Everything that must be specified for an encode, 'cept input, titleID &
name. -}
data EncodeDetails = EncodeDetails { _audios ∷ AudioTracks
-- first, if any, is the default
-- this is because --subtitle-default
-- a HandBrakeCLI argument is actually an
-- index into the --subtitle list argument
, _subtitles ∷ SubtitleTracks
, _options ∷ EncodeOptions
}
deriving Show
parseEncodeDetails ∷ Parser EncodeDetails
parseEncodeDetails =
EncodeDetails ⊳ parseAudioTracks
⊵ parseSubtitleTracks
⊵ parseEncodeOptions
class HasEncodeDetails α where
_EncodeDetails ∷ Lens' α EncodeDetails
audios ∷ Lens' α AudioTracks
audios = _EncodeDetails ∘ audios
subtitles ∷ Lens' α SubtitleTracks
subtitles = _EncodeDetails ∘ subtitles
options ∷ Lens' α EncodeOptions
options = _EncodeDetails ∘ options
instance HasEncodeDetails EncodeDetails where
_EncodeDetails = id
audios = lens _audios (\ ed x → ed { _audios = x })
subtitles = lens _subtitles (\ ed x → ed { _subtitles = x })
options = lens _options (\ ed x → ed { _options = x })
instance HasEncodeOptions EncodeDetails where
_EncodeOptions = options
------------------------------------------------------------
data EncodeRequest = EncodeRequest { _input ∷ AbsFile
, _titleID ∷ ℕ
, _name ∷ 𝕄 𝕋
, _details ∷ EncodeDetails
, _outputDir ∷ AbsDir
}
deriving Show
class HasEncodeRequest α where
_EncodeRequest ∷ Lens' α EncodeRequest
input ∷ Lens' α AbsFile
input = _EncodeRequest ∘ input
titleID ∷ Lens' α ℕ
titleID = _EncodeRequest ∘ titleID
name ∷ Lens' α (𝕄 𝕋)
name = _EncodeRequest ∘ name
details ∷ Lens' α EncodeDetails
details = _EncodeRequest ∘ details
outputDir ∷ Lens' α AbsDir
outputDir = _EncodeRequest ∘ outputDir
instance HasEncodeRequest EncodeRequest where
_EncodeRequest = id
titleID = lens _titleID (\ er t → er { _titleID = t })
name = lens _name (\ er n → er { _name = n })
input = lens _input (\ er f → er { _input = f })
details = lens _details (\ er d → er { _details = d })
outputDir = lens _outputDir (\ er d → er { _outputDir = d })
instance HasEncodeDetails EncodeRequest where
_EncodeDetails = details
instance HasEncodeOptions EncodeRequest where
_EncodeOptions = details ∘ options
------------------------------------------------------------
{- Output basename, sanitized for safety. -}
nameSafe ∷ EncodeRequest → 𝕄 𝕋
nameSafe er = map go ⊳ er ⊣ name
where go '/' = '-'
go ':' = '-'
go c = c
--------------------
outputNum ∷ (AsUsageError ε, MonadError ε η) ⇒ EncodeRequest → η ℕ
outputNum er =
let (on,oo) = case er ⊣ numbering of
NoNumber → (0,0)
Number o → (o + (fromIntegral $ er ⊣ titleID),o)
Series _ o → (o + (fromIntegral $ er ⊣ titleID),o)
in if on < 1
then throwUsage $
[fmtT|output number %d (%d+(%d)) < 0|] on (er ⊣ titleID) oo
else return $ fromIntegral on
----------------------------------------
{- | Create a basic `EncodeRequest` with mandatory arguments. -}
encodeRequest ∷ AbsFile -- ^ video input
→ AbsDir -- ^ output directory
→ ℕ -- ^ titleID within input to encode
→ 𝕄 𝕋 -- ^ output base name
→ AudioTracks -- ^ input audio IDs to encode
→ EncodeRequest
encodeRequest i d t n as =
EncodeRequest { _input = i
, _titleID = t
, _name = n
, _outputDir = d
, _details =
EncodeDetails
{ _audios = as
, _subtitles = SubtitleTracks $ []
, _options =
EncodeOptions
{ _numbering = Number 0
, _chapters = Chapters 𝕹
, _twoPass = TwoPass
, _profile = ProfileH265_2160P
, _quality = defaultQuality
, _outputName = 𝕹
, _audioEncoder = 𝕹
}
}
}
{- | `encodeRequest` with single audio track 1. -}
encodeRequest1 ∷ AbsFile -- ^ video input
→ AbsDir -- ^ output dir
→ ℕ -- ^ titleID within input to encode
→ 𝕄 𝕋 -- ^ output base name
→ EncodeRequest
encodeRequest1 i d t n = encodeRequest i d t n (AudioTracks $ pure 1)
----------------------------------------
{- | Implied output file of an `EncodeRequest`. -}
erImpliedName ∷ (AsUsageError ε, AsFPathError ε, MonadError ε η) ⇒
EncodeRequest → η 𝕋
erImpliedName er = do
case er ⊣ numbering of
NoNumber → case nameSafe er of
𝕵 n → return $ [fmtT|%t.mkv|] n
𝕹 → throwUsage $ [fmtT|no number & no title|]
Number _ → do output_num ← outputNum er
case nameSafe er of
𝕵 n → return $ [fmtT|%02d-%t.mkv|] output_num n
𝕹 → return $ [fmtT|%02d.mkv|] output_num
Series (s,nm) _ → do output_num ← outputNum er
case nameSafe er of
𝕵 n → return $ [fmtT|%t - %02dx%02d - %t.mkv|]
nm s output_num n
𝕹 → return $ [fmtT|%t - %02dx%02d.mkv|]
nm s output_num
--------------------
{- | Chosen output file of an `EncodeRequest`. -}
erOutput ∷ (AsUsageError ε, AsFPathError ε, MonadError ε η) ⇒
EncodeRequest → η AbsFile
erOutput er = do
p ← case er ⊣ outputName of
𝕹 → erImpliedName er ≫ FPath.Parseable.parse @RelFile
𝕵 f → FPath.Parseable.parse @RelFile f
return $ (er ⊣ outputDir) ⫻ p
--------------------
{- | Arguments to HandBrakeCLI for a given `EncodeRequest`. -}
encodeArgs ∷ ∀ ε η . (AsUsageError ε, AsFPathError ε, MonadError ε η) ⇒
EncodeRequest → η ([𝕋],AbsFile)
encodeArgs er = do
output ← erOutput er
cs ← mapM formatBoundedNRange (unChapters $ er ⊣ chapters)
let args = ю [ [ "--input" , toText $ er ⊣ input
, "--title" , pack (show $ er ⊣ titleID)
, "--markers" -- chapter markers
]
, if er ⊣ profile ≡ Profile_DeadVideo then []
else [ "--deinterlace" ]
, [ "--audio-copy-mask"
, "aac,ac3,eac3,truehd,dts,dtshd,mp3,flac" ]
, case er ⊣ twoPass of
TwoPass → if er ⊣ profile ≡ Profile_DeadVideo
then []
else [ "--two-pass", "--turbo" ]
NoTwoPass → []
, [ "--preset", toText $ er ⊣ profile ]
, case er ⊣ audioEncoder of
𝕹 → [ "--aencoder", "copy" ]
𝕵 t → [ "--aencoder", t ]
, [ "--audio", [fmt|%L|] (show ⊳ unAudioTracks (er ⊣ audios)) ]
, case unSubtitleTracks (er ⊣ subtitles) of
[] → []
ss → [ "--subtitle", [fmt|%L|] (show ⊳ ss)
-- note that with HandBrakeCLI, subtitle-default is an
-- index into the list provided to --subtitle. If
-- this doesn't work, maybe it's 1-based…
, "--subtitle-default", "0" ]
, [ "--quality", [fmt|%03.1f|] (er ⊣ quality) ]
, maybe [] (\ c → ["--chapters" , [fmt|%t|] c]) cs
, [ "--output", toText output ]
]
return (args,output)
{- | Take a range, which must be a single SingletonRange or a single SpanRange,
and format that as `x` or `y-z`. For a span range, the lower bound must be
less than or equal to the upper bound; XXX
-}
formatBoundedNRange ∷ (AsUsageError ε, MonadError ε μ) ⇒ Range ℕ → μ 𝕋
formatBoundedNRange InfiniteRange = throwUsage $ [fmtT|illegal range «-»|]
formatBoundedNRange (SingletonRange n) = return $ [fmt|%d|] n
formatBoundedNRange (LowerBoundRange (Bound a Inclusive)) =
throwUsage $ [fmtT|illegal range «[%d-»|] a
formatBoundedNRange (LowerBoundRange (Bound a Exclusive)) =
throwUsage $ [fmtT|illegal range «(%d-»|] a
formatBoundedNRange (UpperBoundRange (Bound a Inclusive)) =
throwUsage $ [fmtT|illegal range «-%d]»|] a
formatBoundedNRange (UpperBoundRange (Bound a Exclusive)) =
throwUsage $ [fmtT|illegal range «-%d)»|] a
formatBoundedNRange (SpanRange (Bound a Inclusive) (Bound b Inclusive)) =
case compare a b of
LT → return $ [fmt|%d-%d|] a b
EQ → return $ [fmt|%d|] a
GT → throwUsage $ [fmtT|Range [%d-%d] is inverted|] a b
formatBoundedNRange (SpanRange (Bound a Exclusive) (Bound b Inclusive)) =
case compare (a+1) b of
LT → return $ [fmt|%d-%d|] (a+1) b
EQ → return $ [fmt|%d|] b
GT → throwUsage $ [fmtT|Range (%d-%d] is inverted|] a b
formatBoundedNRange (SpanRange (Bound a Inclusive) (Bound b Exclusive)) =
if b ≡ 0
then throwUsage $ [fmtT|Range [%d-%d) is illegal|] a b
else case compare a (b-1) of
LT → return $ [fmt|%d-%d|] a (b-1)
EQ → return $ [fmt|%d|] a
GT → throwUsage $ [fmtT|Range [%d-%d) is inverted|] a b
formatBoundedNRange (SpanRange (Bound a Exclusive) (Bound b Exclusive)) =
if b ≡ 0
then throwUsage $ [fmtT|Range [%d-%d) is illegal|] a b
else case compare (a+1) (b-1) of
LT → return $ [fmt|%d-%d|] (a+1) (b-1)
EQ → return $ [fmt|%d|] (a+1)
GT → throwUsage $ [fmtT|Range (%d-%d) is inverted|] a b
-- that's all, folks! ----------------------------------------------------------
|
sixears/handbrake
|
src/HandBrake/Encode.hs
|
Haskell
|
mit
| 24,206
|
module Audit.Options (
Opts(..),
fullOpts,
module Options.Applicative.Extra
) where
import Options.Applicative
import Options.Applicative.Extra
data Opts = Opts { cabalFile :: Maybe FilePath } deriving Show
opts :: Parser Opts
opts = Opts <$> optional (argument str ( metavar "FILE"
<> help ".cabal file to parse" ))
fullOpts :: ParserInfo Opts
fullOpts = info (helper <*> opts)
( fullDesc
<> progDesc "Audit your .cabal file" )
|
pikajude/cabal-audit
|
src/Audit/Options.hs
|
Haskell
|
mit
| 508
|
module Triangle (TriangleType(..), triangleType) where
data TriangleType = Equilateral
| Isosceles
| Scalene
| Illegal
| Degenerate
deriving (Eq, Show)
triangleType :: Float -> Float -> Float -> TriangleType
triangleType a b c
| a > (b+c) || b > (a+c) || c > (a+b) = Illegal
| a <= 0.0 || b <= 0.0 || c <= 0.0 = Illegal
| a == (b+c) || b == (a+c) || c == (a+b) = Degenerate
| a == b && a == c = Equilateral
| a == b || a == c || b == c = Isosceles
| a /= b && a /= c && b /= c = Scalene
| otherwise = Illegal
|
vaibhav276/exercism_haskell
|
triangle/src/Triangle.hs
|
Haskell
|
mit
| 713
|
main :: IO ()
main = do
contents <- getContents
putStrLn contents
let myLines = lines contents
mapM putStrLn myLines
mainloop myLines
return ()
mainloop :: [String] -> IO ()
mainloop contents@(x:xs) = do
words x
mapM putStrLn words
if xs == [] then
return ()
else
mainloop xs
|
doylew/practice
|
haskell/readthenwrite.hs
|
Haskell
|
mit
| 315
|
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Hadoop.Protos.RpcHeaderProtos.RpcResponseHeaderProto.RpcErrorCodeProto (RpcErrorCodeProto(..)) where
import Prelude ((+), (/), (.))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data RpcErrorCodeProto = ERROR_APPLICATION
| ERROR_NO_SUCH_METHOD
| ERROR_NO_SUCH_PROTOCOL
| ERROR_RPC_SERVER
| ERROR_SERIALIZING_RESPONSE
| ERROR_RPC_VERSION_MISMATCH
| FATAL_UNKNOWN
| FATAL_UNSUPPORTED_SERIALIZATION
| FATAL_INVALID_RPC_HEADER
| FATAL_DESERIALIZING_REQUEST
| FATAL_VERSION_MISMATCH
| FATAL_UNAUTHORIZED
deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable RpcErrorCodeProto
instance Prelude'.Bounded RpcErrorCodeProto where
minBound = ERROR_APPLICATION
maxBound = FATAL_UNAUTHORIZED
instance P'.Default RpcErrorCodeProto where
defaultValue = ERROR_APPLICATION
toMaybe'Enum :: Prelude'.Int -> P'.Maybe RpcErrorCodeProto
toMaybe'Enum 1 = Prelude'.Just ERROR_APPLICATION
toMaybe'Enum 2 = Prelude'.Just ERROR_NO_SUCH_METHOD
toMaybe'Enum 3 = Prelude'.Just ERROR_NO_SUCH_PROTOCOL
toMaybe'Enum 4 = Prelude'.Just ERROR_RPC_SERVER
toMaybe'Enum 5 = Prelude'.Just ERROR_SERIALIZING_RESPONSE
toMaybe'Enum 6 = Prelude'.Just ERROR_RPC_VERSION_MISMATCH
toMaybe'Enum 10 = Prelude'.Just FATAL_UNKNOWN
toMaybe'Enum 11 = Prelude'.Just FATAL_UNSUPPORTED_SERIALIZATION
toMaybe'Enum 12 = Prelude'.Just FATAL_INVALID_RPC_HEADER
toMaybe'Enum 13 = Prelude'.Just FATAL_DESERIALIZING_REQUEST
toMaybe'Enum 14 = Prelude'.Just FATAL_VERSION_MISMATCH
toMaybe'Enum 15 = Prelude'.Just FATAL_UNAUTHORIZED
toMaybe'Enum _ = Prelude'.Nothing
instance Prelude'.Enum RpcErrorCodeProto where
fromEnum ERROR_APPLICATION = 1
fromEnum ERROR_NO_SUCH_METHOD = 2
fromEnum ERROR_NO_SUCH_PROTOCOL = 3
fromEnum ERROR_RPC_SERVER = 4
fromEnum ERROR_SERIALIZING_RESPONSE = 5
fromEnum ERROR_RPC_VERSION_MISMATCH = 6
fromEnum FATAL_UNKNOWN = 10
fromEnum FATAL_UNSUPPORTED_SERIALIZATION = 11
fromEnum FATAL_INVALID_RPC_HEADER = 12
fromEnum FATAL_DESERIALIZING_REQUEST = 13
fromEnum FATAL_VERSION_MISMATCH = 14
fromEnum FATAL_UNAUTHORIZED = 15
toEnum
= P'.fromMaybe
(Prelude'.error
"hprotoc generated code: toEnum failure for type Hadoop.Protos.RpcHeaderProtos.RpcResponseHeaderProto.RpcErrorCodeProto")
. toMaybe'Enum
succ ERROR_APPLICATION = ERROR_NO_SUCH_METHOD
succ ERROR_NO_SUCH_METHOD = ERROR_NO_SUCH_PROTOCOL
succ ERROR_NO_SUCH_PROTOCOL = ERROR_RPC_SERVER
succ ERROR_RPC_SERVER = ERROR_SERIALIZING_RESPONSE
succ ERROR_SERIALIZING_RESPONSE = ERROR_RPC_VERSION_MISMATCH
succ ERROR_RPC_VERSION_MISMATCH = FATAL_UNKNOWN
succ FATAL_UNKNOWN = FATAL_UNSUPPORTED_SERIALIZATION
succ FATAL_UNSUPPORTED_SERIALIZATION = FATAL_INVALID_RPC_HEADER
succ FATAL_INVALID_RPC_HEADER = FATAL_DESERIALIZING_REQUEST
succ FATAL_DESERIALIZING_REQUEST = FATAL_VERSION_MISMATCH
succ FATAL_VERSION_MISMATCH = FATAL_UNAUTHORIZED
succ _
= Prelude'.error
"hprotoc generated code: succ failure for type Hadoop.Protos.RpcHeaderProtos.RpcResponseHeaderProto.RpcErrorCodeProto"
pred ERROR_NO_SUCH_METHOD = ERROR_APPLICATION
pred ERROR_NO_SUCH_PROTOCOL = ERROR_NO_SUCH_METHOD
pred ERROR_RPC_SERVER = ERROR_NO_SUCH_PROTOCOL
pred ERROR_SERIALIZING_RESPONSE = ERROR_RPC_SERVER
pred ERROR_RPC_VERSION_MISMATCH = ERROR_SERIALIZING_RESPONSE
pred FATAL_UNKNOWN = ERROR_RPC_VERSION_MISMATCH
pred FATAL_UNSUPPORTED_SERIALIZATION = FATAL_UNKNOWN
pred FATAL_INVALID_RPC_HEADER = FATAL_UNSUPPORTED_SERIALIZATION
pred FATAL_DESERIALIZING_REQUEST = FATAL_INVALID_RPC_HEADER
pred FATAL_VERSION_MISMATCH = FATAL_DESERIALIZING_REQUEST
pred FATAL_UNAUTHORIZED = FATAL_VERSION_MISMATCH
pred _
= Prelude'.error
"hprotoc generated code: pred failure for type Hadoop.Protos.RpcHeaderProtos.RpcResponseHeaderProto.RpcErrorCodeProto"
instance P'.Wire RpcErrorCodeProto where
wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum)
wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum)
wireGet 14 = P'.wireGetEnum toMaybe'Enum
wireGet ft' = P'.wireGetErr ft'
wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum
wireGetPacked ft' = P'.wireGetErr ft'
instance P'.GPB RpcErrorCodeProto
instance P'.MessageAPI msg' (msg' -> RpcErrorCodeProto) RpcErrorCodeProto where
getVal m' f' = f' m'
instance P'.ReflectEnum RpcErrorCodeProto where
reflectEnum
= [(1, "ERROR_APPLICATION", ERROR_APPLICATION), (2, "ERROR_NO_SUCH_METHOD", ERROR_NO_SUCH_METHOD),
(3, "ERROR_NO_SUCH_PROTOCOL", ERROR_NO_SUCH_PROTOCOL), (4, "ERROR_RPC_SERVER", ERROR_RPC_SERVER),
(5, "ERROR_SERIALIZING_RESPONSE", ERROR_SERIALIZING_RESPONSE), (6, "ERROR_RPC_VERSION_MISMATCH", ERROR_RPC_VERSION_MISMATCH),
(10, "FATAL_UNKNOWN", FATAL_UNKNOWN), (11, "FATAL_UNSUPPORTED_SERIALIZATION", FATAL_UNSUPPORTED_SERIALIZATION),
(12, "FATAL_INVALID_RPC_HEADER", FATAL_INVALID_RPC_HEADER), (13, "FATAL_DESERIALIZING_REQUEST", FATAL_DESERIALIZING_REQUEST),
(14, "FATAL_VERSION_MISMATCH", FATAL_VERSION_MISMATCH), (15, "FATAL_UNAUTHORIZED", FATAL_UNAUTHORIZED)]
reflectEnumInfo _
= P'.EnumInfo
(P'.makePNF (P'.pack ".hadoop.common.RpcResponseHeaderProto.RpcErrorCodeProto") ["Hadoop", "Protos"]
["RpcHeaderProtos", "RpcResponseHeaderProto"]
"RpcErrorCodeProto")
["Hadoop", "Protos", "RpcHeaderProtos", "RpcResponseHeaderProto", "RpcErrorCodeProto.hs"]
[(1, "ERROR_APPLICATION"), (2, "ERROR_NO_SUCH_METHOD"), (3, "ERROR_NO_SUCH_PROTOCOL"), (4, "ERROR_RPC_SERVER"),
(5, "ERROR_SERIALIZING_RESPONSE"), (6, "ERROR_RPC_VERSION_MISMATCH"), (10, "FATAL_UNKNOWN"),
(11, "FATAL_UNSUPPORTED_SERIALIZATION"), (12, "FATAL_INVALID_RPC_HEADER"), (13, "FATAL_DESERIALIZING_REQUEST"),
(14, "FATAL_VERSION_MISMATCH"), (15, "FATAL_UNAUTHORIZED")]
instance P'.TextType RpcErrorCodeProto where
tellT = P'.tellShow
getT = P'.getRead
|
alexbiehl/hoop
|
hadoop-protos/src/Hadoop/Protos/RpcHeaderProtos/RpcResponseHeaderProto/RpcErrorCodeProto.hs
|
Haskell
|
mit
| 6,436
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-ondemandoptionsrequest.html
module Stratosphere.ResourceProperties.EC2EC2FleetOnDemandOptionsRequest where
import Stratosphere.ResourceImports
-- | Full data type definition for EC2EC2FleetOnDemandOptionsRequest. See
-- 'ec2EC2FleetOnDemandOptionsRequest' for a more convenient constructor.
data EC2EC2FleetOnDemandOptionsRequest =
EC2EC2FleetOnDemandOptionsRequest
{ _eC2EC2FleetOnDemandOptionsRequestAllocationStrategy :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToJSON EC2EC2FleetOnDemandOptionsRequest where
toJSON EC2EC2FleetOnDemandOptionsRequest{..} =
object $
catMaybes
[ fmap (("AllocationStrategy",) . toJSON) _eC2EC2FleetOnDemandOptionsRequestAllocationStrategy
]
-- | Constructor for 'EC2EC2FleetOnDemandOptionsRequest' containing required
-- fields as arguments.
ec2EC2FleetOnDemandOptionsRequest
:: EC2EC2FleetOnDemandOptionsRequest
ec2EC2FleetOnDemandOptionsRequest =
EC2EC2FleetOnDemandOptionsRequest
{ _eC2EC2FleetOnDemandOptionsRequestAllocationStrategy = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-ondemandoptionsrequest.html#cfn-ec2-ec2fleet-ondemandoptionsrequest-allocationstrategy
ececfodorAllocationStrategy :: Lens' EC2EC2FleetOnDemandOptionsRequest (Maybe (Val Text))
ececfodorAllocationStrategy = lens _eC2EC2FleetOnDemandOptionsRequestAllocationStrategy (\s a -> s { _eC2EC2FleetOnDemandOptionsRequestAllocationStrategy = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/EC2EC2FleetOnDemandOptionsRequest.hs
|
Haskell
|
mit
| 1,687
|
{-# LANGUAGE TemplateHaskell #-}
module IFind.Config (
IFindConfig(..),
FindFilters(..),
UIColors(..),
readConfFile
) where
import Data.Aeson
import Data.Aeson.Encode.Pretty
import Data.Aeson.TH
import Graphics.Vty.Attributes
import System.Directory
import System.Exit (exitFailure)
import qualified Data.ByteString.Lazy as L
import IFind.Opts
instance FromJSON Color where
parseJSON = fmap ISOColor . parseJSON
instance ToJSON Color where
toJSON (ISOColor c) = toJSON c
toJSON (Color240 _) = error "Expected ISOColor, got Color240"
data UIColors =
UIColors { helpColorDescription :: [String]
, focusedItemForegroundColor:: Color
, focusedItemBackgroundColor:: Color
, searchCountForegroundColor:: Color
, searchCountBackgroundColor:: Color
} deriving (Show)
$(deriveJSON defaultOptions ''UIColors)
-- | regex filters we apply to recursive find
data FindFilters = FindFilters { excludeDirectories:: [String]
, excludePaths:: [String]
} deriving (Show)
$(deriveJSON defaultOptions ''FindFilters)
-- | Common config parameters
-- initially read from $HOME/.iconfig
data IFindConfig =
IFindConfig { uiColors:: UIColors
, findFilters:: FindFilters
} deriving (Show)
$(deriveJSON defaultOptions ''IFindConfig)
emptyFilters:: FindFilters
emptyFilters =
FindFilters { excludeDirectories = []
, excludePaths = []
}
defaultFilters:: FindFilters
defaultFilters =
FindFilters { excludeDirectories = ["\\.git$"
, "\\.svn$"
]
, excludePaths = [ "\\.class$"
, "\\.swp$"
, "\\.hi$"
, "\\.o$"
, "\\.jar$"
]
}
defaultUIColors:: UIColors
defaultUIColors =
UIColors { helpColorDescription = [
"Color mappings:",
"black = 0",
"red = 1",
"green = 2",
"yellow = 3",
"blue = 4",
"magenta = 5",
"cyan = 6",
"white = 7",
"bright_black = 8",
"bright_red = 9",
"bright_green = 10",
"bright_yellow = 11",
"bright_blue = 12",
"bright_magenta= 13",
"bright_cyan = 14",
"bright_white = 15"
]
, focusedItemForegroundColor = black
, focusedItemBackgroundColor = white
, searchCountForegroundColor = black
, searchCountBackgroundColor = yellow
}
defaultConfig:: IFindConfig
defaultConfig =
IFindConfig { uiColors = defaultUIColors
, findFilters = defaultFilters
}
confFileName:: IO FilePath
confFileName = do
homeDir <- getHomeDirectory
return $ homeDir ++ "/.ifind"
createDefaultConfFile:: IO ()
createDefaultConfFile = do
fName <- confFileName
let jsonTxt = encodePretty $ defaultConfig
L.writeFile fName jsonTxt
readConfFile:: IFindOpts -> IO IFindConfig
readConfFile opts = do
fName <- confFileName
foundConfFile <- doesFileExist fName
_ <- if not foundConfFile then createDefaultConfFile else return ()
r <- if noDefaultFilters opts
then return $ Right defaultConfig { findFilters = emptyFilters }
else eitherDecode' <$> L.readFile fName
case r of
Left e -> putStrLn e >> exitFailure
Right ff -> return ff
|
andreyk0/ifind
|
IFind/Config.hs
|
Haskell
|
apache-2.0
| 3,744
|
-- Copyright (c) 2010 - Seweryn Dynerowicz
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- imitations under the License.
module Algebra.Constructs.Lexicographic
( Lexicographic(..)
, lexicographic
) where
import LaTeX
import Algebra.Matrix
import Algebra.Semiring
data Lexicographic s t = Lex (s,t)
deriving (Eq)
instance (Show s, Show t) => Show (Lexicographic s t) where
show (Lex l) = show l
instance (LaTeX s, LaTeX t) => LaTeX (Lexicographic s t) where
toLaTeX (Lex p) = toLaTeX p
instance (Semiring s, Semiring t) => Semiring (Lexicographic s t) where
zero = Lex (zero, zero)
unit = Lex (unit, unit)
add (Lex (s1,t1)) (Lex (s2,t2))
| (addS == s1 && addS == s2) = Lex (addS,add t1 t2)
| (addS == s1) = Lex (s1,t1)
| (addS == s2) = Lex (s2,t2)
| otherwise = Lex (addS, zero)
where addS = add s1 s2
mul (Lex (s1, t1)) (Lex (s2, t2)) = Lex (mul s1 s2, mul t1 t2)
lub (Lex (s1, t1)) (Lex (s2, t2))
| (lubS == s1 && lubS == s2) = Lex (lubS,add t1 t2)
| (lubS == s1) = Lex (s1,t1)
| (lubS == s2) = Lex (s2,t2)
| otherwise = Lex (lubS, zero)
where lubS = add s1 s2
lexicographic :: (Semiring s, Semiring t) => Matrix s -> Matrix t -> Matrix (Lexicographic s t)
lexicographic as bs | (order as) == (order bs) = pointwise as bs zipL
| otherwise = error "Incompatibles matrice sizes"
zipL :: s -> t -> Lexicographic s t
zipL s t = Lex (s, t)
|
sdynerow/Semirings-Library
|
haskell/Algebra/Constructs/Lexicographic.hs
|
Haskell
|
apache-2.0
| 1,925
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-
Copyright 2018 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Compile
( compileSource
, Stage(..)
) where
import Control.Concurrent
import Control.Monad
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.ByteString.Char8 (pack)
import Data.Monoid
import ErrorSanitizer
import System.Directory
import System.FilePath
import System.IO
import System.IO.Temp (withSystemTempDirectory)
import System.Process
import Text.Regex.TDFA
import ParseCode
data Stage
= FullBuild
| GenBase String
FilePath
FilePath
| UseBase FilePath
compileSource :: Stage -> FilePath -> FilePath -> FilePath -> String -> IO Bool
compileSource stage src out err mode =
checkDangerousSource src >>= \case
True -> do
B.writeFile
err
"Sorry, but your program refers to forbidden language features."
return False
False ->
withSystemTempDirectory "build" $ \tmpdir -> do
parenProblem <-
case mode of
"codeworld" -> not <$> checkParsedCode src err
_ -> return False
copyFile src (tmpdir </> "program.hs")
baseArgs <-
case mode of
"haskell" -> return haskellCompatibleBuildArgs
"codeworld" -> standardBuildArgs <$> hasOldStyleMain src
linkArgs <-
case stage of
FullBuild -> return []
GenBase mod base _ -> do
copyFile base (tmpdir </> mod <.> "hs")
return ["-generate-base", mod]
UseBase syms -> do
copyFile syms (tmpdir </> "out.base.symbs")
return ["-use-base", "out.base.symbs"]
let ghcjsArgs = ["program.hs"] ++ baseArgs ++ linkArgs
runCompiler tmpdir userCompileMicros ghcjsArgs >>= \case
Nothing -> return False
Just output -> do
let filteredOutput =
case mode of
"codeworld" -> filterOutput output
_ -> output
when (not parenProblem) $ B.writeFile err ""
B.appendFile err filteredOutput
let target = tmpdir </> "program.jsexe"
case stage of
GenBase _ _ syms -> do
hasTarget <-
and <$>
mapM
doesFileExist
[ target </> "rts.js"
, target </> "lib.base.js"
, target </> "out.base.js"
, target </> "out.base.symbs"
]
when hasTarget $ do
rtsCode <- B.readFile $ target </> "rts.js"
libCode <-
B.readFile $ target </> "lib.base.js"
outCode <-
B.readFile $ target </> "out.base.js"
B.writeFile
out
(rtsCode <> libCode <> outCode)
copyFile (target </> "out.base.symbs") syms
return hasTarget
UseBase _ -> do
hasTarget <-
and <$>
mapM
doesFileExist
[ target </> "lib.js"
, target </> "out.js"
]
when hasTarget $ do
libCode <- B.readFile $ target </> "lib.js"
outCode <- B.readFile $ target </> "out.js"
B.writeFile out (libCode <> outCode)
return hasTarget
FullBuild -> do
hasTarget <-
and <$>
mapM
doesFileExist
[ target </> "rts.js"
, target </> "lib.js"
, target </> "out.js"
]
when hasTarget $ do
rtsCode <- B.readFile $ target </> "rts.js"
libCode <- B.readFile $ target </> "lib.js"
outCode <- B.readFile $ target </> "out.js"
B.writeFile
out
(rtsCode <> libCode <> outCode)
return hasTarget
userCompileMicros :: Int
userCompileMicros = 45 * 1000000
checkDangerousSource :: FilePath -> IO Bool
checkDangerousSource dir = do
contents <- B.readFile dir
return $
matches contents ".*TemplateHaskell.*" ||
matches contents ".*QuasiQuotes.*" ||
matches contents ".*glasgow-exts.*"
hasOldStyleMain :: FilePath -> IO Bool
hasOldStyleMain fname = do
contents <- B.readFile fname
return (matches contents "(^|\\n)main[ \\t]*=")
matches :: ByteString -> ByteString -> Bool
matches txt pat = txt =~ pat
runCompiler :: FilePath -> Int -> [String] -> IO (Maybe ByteString)
runCompiler dir micros args = do
(Just inh, Just outh, Just errh, pid) <-
createProcess
(proc "ghcjs" args)
{ cwd = Just dir
, std_in = CreatePipe
, std_out = CreatePipe
, std_err = CreatePipe
, close_fds = True
}
hClose inh
result <- withTimeout micros $ B.hGetContents errh
hClose outh
terminateProcess pid
_ <- waitForProcess pid
return result
standardBuildArgs :: Bool -> [String]
standardBuildArgs True =
[ "-DGHCJS_BROWSER"
, "-dedupe"
, "-Wall"
, "-O2"
, "-fno-warn-deprecated-flags"
, "-fno-warn-amp"
, "-fno-warn-missing-signatures"
, "-fno-warn-incomplete-patterns"
, "-fno-warn-unused-matches"
, "-hide-package"
, "base"
, "-package"
, "codeworld-base"
, "-XBangPatterns"
, "-XDisambiguateRecordFields"
, "-XEmptyDataDecls"
, "-XExistentialQuantification"
, "-XForeignFunctionInterface"
, "-XGADTs"
, "-XJavaScriptFFI"
, "-XKindSignatures"
, "-XLiberalTypeSynonyms"
, "-XNamedFieldPuns"
, "-XNoMonomorphismRestriction"
, "-XNoQuasiQuotes"
, "-XNoTemplateHaskell"
, "-XNoUndecidableInstances"
, "-XOverloadedStrings"
, "-XPackageImports"
, "-XParallelListComp"
, "-XPatternGuards"
, "-XRankNTypes"
, "-XRebindableSyntax"
, "-XRecordWildCards"
, "-XScopedTypeVariables"
, "-XTypeOperators"
, "-XViewPatterns"
, "-XImplicitPrelude" -- MUST come after RebindableSyntax.
]
standardBuildArgs False = standardBuildArgs True ++ ["-main-is", "Main.program"]
haskellCompatibleBuildArgs :: [String]
haskellCompatibleBuildArgs =
[ "-DGHCJS_BROWSER"
, "-dedupe"
, "-Wall"
, "-O2"
, "-package"
, "codeworld-api"
, "-package"
, "QuickCheck"
]
withTimeout :: Int -> IO a -> IO (Maybe a)
withTimeout micros action = do
result <- newEmptyMVar
killer <- forkIO $ threadDelay micros >> putMVar result Nothing
runner <- forkIO $ action >>= putMVar result . Just
r <- takeMVar result
killThread killer
killThread runner
return r
|
tgdavies/codeworld
|
codeworld-compiler/src/Compile.hs
|
Haskell
|
apache-2.0
| 8,890
|
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE BangPatterns #-}
module Data.CRF.Chain1.Constrained.Intersect
( intersect
) where
import qualified Data.Vector.Unboxed as U
import Data.CRF.Chain1.Constrained.Dataset.Internal (Lb, AVec, unAVec)
import Data.CRF.Chain1.Constrained.Model (FeatIx)
-- | Assumption: both input list are given in an ascending order.
intersect
:: AVec (Lb, FeatIx) -- ^ Vector of (label, features index) pairs
-> AVec Lb -- ^ Vector of labels
-- | Intersection of arguments: vector indices from the second list
-- and feature indices from the first list.
-> [(Int, FeatIx)]
intersect xs' ys'
| n == 0 || m == 0 = []
| otherwise = merge xs ys
where
xs = unAVec xs'
ys = unAVec ys'
n = U.length ys
m = U.length xs
merge :: U.Vector (Lb, FeatIx) -> U.Vector Lb -> [(Int, FeatIx)]
merge xs ys = doIt 0 0
where
m = U.length xs
n = U.length ys
doIt i j
| i >= m || j >= n = []
| otherwise = case compare x y of
EQ -> (j, ix) : doIt (i+1) (j+1)
LT -> doIt (i+1) j
GT -> doIt i (j+1)
where
(x, ix) = xs `U.unsafeIndex` i
y = ys `U.unsafeIndex` j
---------------------------------------------
-- Alternative version
---------------------------------------------
-- -- | Assumption: both input list are given in an ascending order.
-- intersect'
-- :: AVec (Lb, FeatIx) -- ^ Vector of (label, features index) pairs
-- -> AVec (Lb, Prob) -- ^ Vector of labels
-- -- | Intersection of arguments: vector indices from the second list
-- -- and feature indices from the first list.
-- -> [(Int, FeatIx)]
-- intersect' xs' ys'
-- | n == 0 || m == 0 = []
-- | otherwise = merge xs ys
-- where
-- xs = unAVec xs'
-- ys = unAVec ys'
-- n = U.length ys
-- m = U.length xs
--
--
-- merge :: U.Vector (Lb, FeatIx) -> U.Vector Lb -> [(Int, FeatIx)]
-- merge xs ys = doIt 0 0
-- where
-- m = U.length xs
-- n = U.length ys
-- doIt i j
-- | i >= m || j >= n = []
-- | otherwise = case compare x y of
-- EQ -> (j, ix) : doIt (i+1) (j+1)
-- LT -> doIt (i+1) j
-- GT -> doIt i (j+1)
-- where
-- (x, ix) = xs `U.unsafeIndex` i
-- y = ys `U.unsafeIndex` j
|
kawu/crf-chain1-constrained
|
src/Data/CRF/Chain1/Constrained/Intersect.hs
|
Haskell
|
bsd-2-clause
| 2,352
|
{-# LANGUAGE OverloadedStrings #-}
module RefTrack.OAI.Arxiv ( getRecord
) where
import Control.Applicative
import Control.Error
import Data.Char (isSpace)
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Set as S
import Network.URI
import Text.XML
import Text.XML.Cursor
import RefTrack.OAI hiding (getRecord)
import RefTrack.Types
getRecord :: URI -> Identifier -> EitherT String IO Ref
getRecord baseUri id =
oaiRequest baseUri [ ("verb", "GetRecord")
, ("identifier", id)
, ("metadataPrefix", "arXiv")
]
>>= parseRecord . fromDocument
parseAuthor :: Cursor -> Maybe Person
parseAuthor cur =
Person <$> listToMaybe (cur $/ laxElement "forenames" &/ content)
<*> listToMaybe (cur $/ laxElement "keyname" &/ content)
parseRecord :: Monad m => Cursor -> EitherT String m Ref
parseRecord cur = do
metad <- tryHead "Couldn't find arXiv metadata"
$ cur $/ laxElement "GetRecord"
&/ laxElement "record"
&/ laxElement "metadata"
&/ laxElement "arXiv"
arxivId <- tryHead "Couldn't find arXiv ID"
$ metad $/ laxElement "id" &/ content
let authors = mapMaybe parseAuthor $ metad $/ laxElement "authors"
&/ laxElement "author"
title <- tryHead "Couldn't find title"
$ metad $/ laxElement "title" &/ content
let categories = concatMap (T.split isSpace)
$ metad $/ laxElement "categories" &/ content
abstract = T.intercalate " " $ T.lines $ T.intercalate " " $ map T.strip
$ metad $/ laxElement "abstract" &/ content
created = metad $/ laxElement "created" &/ content
return $ Ref { _refId = RefId arxivId
, _refTitle = title
, _refAuthors = authors
, _refPubDate = Nothing
, _refYear = Year 0
, _refExternalRefs = [ ArxivRef $ ArxivId arxivId ]
, _refPublication = OtherPub
, _refAbstract = if T.null abstract then Nothing
else Just abstract
, _refTags = S.fromList $ map Tag $ map ("arxiv:"<>) categories
}
|
bgamari/reftrack
|
RefTrack/OAI/Arxiv.hs
|
Haskell
|
bsd-3-clause
| 2,516
|
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
-------------------------------------------------------------------------------
-- |
-- Module : Yesod.Comments.Storage
-- Copyright : (c) Patrick Brisbin 2010
-- License : as-is
--
-- Maintainer : pbrisbin@gmail.com
-- Stability : unstable
-- Portability : unportable
--
-------------------------------------------------------------------------------
module Yesod.Comments.Storage
( persistStorage
, migrateComments
, SqlComment
, SqlCommentGeneric (..)
, EntityField (..)
) where
import Yesod
import Yesod.Comments.Core
import Yesod.Markdown (Markdown(..))
import Data.Text (Text)
import Data.Time (UTCTime)
import Database.Persist.Sql (SqlPersist)
share [mkPersist sqlSettings, mkMigrate "migrateComments"] [persistUpperCase|
SqlComment
threadId Text Eq noreference
commentId Int Eq Asc noreference
timeStamp UTCTime
ipAddress Text
userName Text
userEmail Text
content Markdown Update
isAuth Bool
UniqueSqlComment threadId commentId
|]
toSqlComment :: Comment -> SqlComment
toSqlComment comment = SqlComment
{ sqlCommentCommentId = commentId comment
, sqlCommentThreadId = cThreadId comment
, sqlCommentTimeStamp = cTimeStamp comment
, sqlCommentIpAddress = cIpAddress comment
, sqlCommentUserName = cUserName comment
, sqlCommentUserEmail = cUserEmail comment
, sqlCommentContent = cContent comment
, sqlCommentIsAuth = cIsAuth comment
}
fromSqlComment :: SqlComment -> Comment
fromSqlComment sqlComment = Comment
{ commentId = sqlCommentCommentId sqlComment
, cThreadId = sqlCommentThreadId sqlComment
, cTimeStamp = sqlCommentTimeStamp sqlComment
, cIpAddress = sqlCommentIpAddress sqlComment
, cUserName = sqlCommentUserName sqlComment
, cUserEmail = sqlCommentUserEmail sqlComment
, cContent = sqlCommentContent sqlComment
, cIsAuth = sqlCommentIsAuth sqlComment
}
-- | Store comments in an instance of YesodPersit with a SQL backend
persistStorage :: ( YesodPersist m
, YesodPersistBackend m ~ SqlPersist
) => CommentStorage s m
persistStorage = CommentStorage
{ csGet = \tid cid -> do
mentity <- runDB (getBy $ UniqueSqlComment tid cid)
return $ fmap (fromSqlComment . entityVal) mentity
, csStore = \c -> do
_ <- runDB (insert $ toSqlComment c)
return ()
, csUpdate = \(Comment cid tid _ _ _ _ _ _) (Comment _ _ _ _ _ _ newContent _) -> do
mres <- runDB (getBy $ UniqueSqlComment tid cid)
case mres of
Just (Entity k _) -> runDB $ update k [SqlCommentContent =. newContent]
_ -> return ()
, csDelete = \c -> do
_ <- runDB (deleteBy $ UniqueSqlComment (cThreadId c) (commentId c))
return ()
, csLoad = \mthread -> do
entities <- case mthread of
(Just tid) -> runDB (selectList [SqlCommentThreadId ==. tid] [Asc SqlCommentCommentId])
Nothing -> runDB (selectList [] [Asc SqlCommentCommentId])
return $ map (fromSqlComment . entityVal) entities
}
|
pbrisbin/yesod-comments
|
Yesod/Comments/Storage.hs
|
Haskell
|
bsd-3-clause
| 3,542
|
module Anatomy.Debug where
import Debug.Trace
import Text.Show.Pretty
debugging :: Bool
debugging = False
debug :: (Show a, Show b) => b -> a -> a
debug s v
| debugging = trace (prettyShow s ++ ": " ++ prettyShow v) v
| otherwise = v
dump :: (Monad m, Show a) => a -> m ()
dump x
| debugging = trace (prettyShow x) (return ())
| otherwise = return ()
prettyShow :: Show a => a -> String
prettyShow = ppShow
|
vito/atomo-anatomy
|
src/Anatomy/Debug.hs
|
Haskell
|
bsd-3-clause
| 429
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.SGIS.TextureBorderClamp
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.SGIS.TextureBorderClamp (
-- * Extension Support
glGetSGISTextureBorderClamp,
gl_SGIS_texture_border_clamp,
-- * Enums
pattern GL_CLAMP_TO_BORDER_SGIS
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/SGIS/TextureBorderClamp.hs
|
Haskell
|
bsd-3-clause
| 679
|
-----------------------------------------------------------------------------
-- |
-- Module : TestSuite.Uninterpreted.Function
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- Testsuite for Data.SBV.Examples.Uninterpreted.Function
-----------------------------------------------------------------------------
module TestSuite.Uninterpreted.Function(tests) where
import Data.SBV.Examples.Uninterpreted.Function
import Utils.SBVTestFramework
tests :: TestTree
tests =
testGroup "Uninterpreted.Function"
[ testCase "aufunc-0" (assertIsThm thmGood)
]
|
josefs/sbv
|
SBVTestSuite/TestSuite/Uninterpreted/Function.hs
|
Haskell
|
bsd-3-clause
| 645
|
-- |
-- Module: Graphics.LWGL.Vertex_P
-- Copyright: (c) 2017 Patrik Sandahl
-- Licence: BSD3
-- Maintainer: Patrik Sandahl <patrik.sandahl@gmail.com>
-- Stability: experimental
-- Portability: portable
-- Language: Haskell2010
module Graphics.LWGL.Vertex_P
( Vertex (..)
, makeVertexArrayObject
) where
import Control.Monad (void)
import Foreign (Storable (..), castPtr)
import Linear (V3)
import Graphics.LWGL.Api
import Graphics.LWGL.Mesh
import Graphics.LWGL.Types
-- | A vertex record with just one field: position.
data Vertex = Vertex
{ position :: !(V3 GLfloat)
} deriving Show
instance Storable Vertex where
sizeOf v = sizeOf $ position v
alignment v = alignment $ position v
peek ptr = Vertex <$> peek (castPtr ptr)
poke ptr v = poke (castPtr ptr) $ position v
instance Meshable Vertex where
fromList bufferUsage =
makeVertexArrayObject . setBufferFromList bufferUsage
fromVector bufferUsage =
makeVertexArrayObject . setBufferFromVector bufferUsage
-- | Create a Vertex Array Object, with the specified BufferUsage and the
-- given vertices. The vertex attributes are populated (location = 0). At the
-- return the Vertex Array Object is still bound.
makeVertexArrayObject :: IO Vertex -> IO VertexArrayObject
makeVertexArrayObject setBuffer = do
[vaoId] <- glGenVertexArray 1
glBindVertexArray vaoId
[vboId] <- glGenBuffers 1
glBindBuffer ArrayBuffer vboId
void setBuffer
-- Setting position - three components of type GLfloat
glEnableVertexAttribArray (AttributeIndex 0)
glVertexAttribPointer (AttributeIndex 0) Three GLFloat False 0 0
return vaoId
|
psandahl/light-weight-opengl
|
src/Graphics/LWGL/Vertex_P.hs
|
Haskell
|
bsd-3-clause
| 1,759
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module HaskellCI.Config.CopyFields where
import HaskellCI.Prelude
import qualified Distribution.Compat.CharParsing as C
import qualified Distribution.Parsec as C
import qualified Distribution.Pretty as C
import qualified Text.PrettyPrint as PP
data CopyFields
= CopyFieldsNone
| CopyFieldsSome
| CopyFieldsAll
deriving (Eq, Ord, Show, Enum, Bounded)
-------------------------------------------------------------------------------
-- Functions
-------------------------------------------------------------------------------
showCopyFields :: CopyFields -> String
showCopyFields CopyFieldsNone = "none"
showCopyFields CopyFieldsSome = "some"
showCopyFields CopyFieldsAll = "all"
instance C.Pretty CopyFields where
pretty = PP.text . showCopyFields
instance C.Parsec CopyFields where
parsec = C.choice
[ f <$ C.string (showCopyFields f)
| f <- [ minBound .. maxBound ]
]
|
hvr/multi-ghc-travis
|
src/HaskellCI/Config/CopyFields.hs
|
Haskell
|
bsd-3-clause
| 1,039
|
module Distribution.ArchLinux.Libalpm.Wrapper.Options where
import Control.Monad.Reader
import Distribution.ArchLinux.Libalpm.Wrapper.Types
import Distribution.ArchLinux.Libalpm.Wrapper.Callbacks
import Distribution.ArchLinux.Libalpm.Wrapper.Alpm
type AlpmOptions = [AlpmOption]
data AlpmOption = AlpmOption
withAlpmOptions :: AlpmOptions -> Alpm a -> Alpm a
withAlpmOptions options a = loadOptions options >> a
loadOptions = undefined
-- | Execute 'Alpm' monadic action with specified event handlers.
withEventHandlers :: EventHandlers -> Alpm a -> Alpm a
withEventHandlers eh a = do
cb <- liftIO $ makeEventCallback eh
local (updater cb) a
where
updater cb env =
env {
envCallbacks = Just $
(maybe defaultCallbacks id (envCallbacks env)) {
callbackEvents = Just cb
}
}
|
netvl/alpmhs
|
lib/Distribution/ArchLinux/Libalpm/Wrapper/Options.hs
|
Haskell
|
bsd-3-clause
| 841
|
import Data.List
import Data.List.Split
import Data.Ord
flipLog (b:e) = (head e) * (log b)
largestExponential xs = snd . maximum $ zip (map flipLog xs) [1..]
main = readFile "099.txt" >>= print . largestExponential . map (map (read::String->Float) . (splitOn ",")) . lines
|
JacksonGariety/euler.hs
|
099.hs
|
Haskell
|
bsd-3-clause
| 274
|
module Main where
import GraphDraw.TestFgl
import Data.Graph.Inductive.Graph
import Data.Graph.Inductive
import Diagrams.Prelude
import Diagrams.Backend.SVG.CmdLine
import Data.List
myGraph :: Gr [Char] ()
myGraph = mkGraph
[(1, "A"), (2, "B"), (3, "C"), (4, "D"), (5, "E"), (6, "E"), (7, "E")]
[(1,2, ()),(2,3, ()),(3,4, ()),(4,5, ()),(5,6, ()),(6,7, ())]
--________________________________________________________________________________________________________________________________
{-
myGraph = mkGraph
[(1, "A"), (2, "B"), (3, "C"), (4, "D"), (5, "E")]
[(1,2, ()),(2,3, ()),(3,4, ()),(4,2, ()),(1,3, ()),(1,4, ()),(1,5, ()),(2,5, ()),(3,5, ())]
-}
{-
myGraph = mkGraph
[(1, "A"), (2, "B"), (3, "C"), (4, "D"), (5, "E"), (6, "F"), (7, "G")]
[(2,1, ()),(2,3, ()),(2,4, ()),(2,5, ()),(2,6, ()),(2,7, ())]
-}
{-
myGraph = mkGraph
[(1, "A"), (2, "B"), (3, "C"), (4, "D"), (5, "E")]
[(1,2, ()),(2,3, ()),(3,4, ()),(4,5, ()),(5,1,()),(1,3,())]
-}
--_________________________________________________________________________________________________________________________________
node :: Int -> Diagram B R2
node n = text (show n) # scale 2.3 # fc white
<> circle 2.3 # fc green # named n
arrowOpts = with Diagrams.Prelude.& arrowHead .~ dart Diagrams.Prelude.& headSize .~ 1.2
Diagrams.Prelude.& shaftStyle %~ lw 0.2
example :: Diagram B R2
example = position . flip zip (map node (nodes myGraph)) . map p2 $ (giveList myGraph 50)
main = mainWith (example # applyAll (map (\(x,y) -> connectOutside' arrowOpts x y ) (edges myGraph)) ::Diagram B R2)
|
prash471/GraphDraw
|
Main.hs
|
Haskell
|
bsd-3-clause
| 1,661
|
module Text.XML.YJSVG (
SVG(..), Position(..), Color(..), Transform(..),
Font(..), FontWeight(..),
showSVG, topleft, center,
) where
import Text.XML.HaXml(
AttValue(..), QName(..), Prolog(..),
EncodingDecl(..), XMLDecl(..), SystemLiteral(..), PubidLiteral(..),
ExternalID(..), DocTypeDecl(..), Misc(..), Element(..), Content(..),
Document(..) )
import Text.XML.HaXml.Pretty (document)
import Data.Word(Word8)
data FontWeight = Normal | Bold deriving (Show, Read)
weightValue :: FontWeight -> String
weightValue Normal = "normal"
weightValue Bold = "bold"
data Font = Font{ fontName :: String, fontWeight :: FontWeight }
deriving (Show, Read)
data Position
= TopLeft { posX :: Double, posY :: Double }
| Center { posX :: Double, posY :: Double }
deriving (Show, Read)
topleft, center :: Double -> Double -> Position -> Position
topleft w h Center { posX = x, posY = y } =
TopLeft { posX = x + w / 2, posY = - y + h / 2 }
topleft _ _ pos = pos
center w h TopLeft { posX = x, posY = y } =
Center { posX = x - w / 2, posY = - y + h / 2 }
center _ _ pos = pos
getPos :: Double -> Double -> Position -> (Double, Double)
getPos _ _ TopLeft { posX = x, posY = y } = (x, y)
getPos w h Center { posX = x, posY = y } = (x + w / 2, - y + h / 2)
type Id = String
data SVG = Line Position Position Color Double |
Polyline [Position] Color Color Double |
Rect Position Double Double Double Color Color |
Fill Color |
Circle Position Double Color |
Text Position Double Color Font String |
Image Position Double Double FilePath |
Use Position Double Double String |
Group [ Transform ] [ (Id,SVG) ] |
Defs [ (Id,SVG) ]
--Symbol [ (Id,SVG) ]
deriving (Show, Read)
data Color
= ColorName{ colorName :: String }
| RGB { colorRed :: Word8,
colorGreen :: Word8,
colorBlue :: Word8 }
deriving (Eq, Show, Read)
mkColorStr :: Color -> String
mkColorStr ColorName { colorName = n } = n
mkColorStr RGB { colorRed = r, colorGreen = g, colorBlue = b } =
"rgb(" ++ show r ++ "," ++ show g ++ "," ++ show b ++ ")"
data Transform
= Matrix Double Double Double Double Double Double
| Translate Double Double
| Scale Double Double
| Rotate Double (Maybe (Double, Double))
| SkewX Double
| SkewY Double
deriving (Show, Read)
showTrans :: Transform -> String
showTrans (Translate tx ty) = "translate(" ++ show tx ++ "," ++ show ty ++ ") "
showTrans (Scale sx sy) = "scale(" ++ show sx ++ "," ++ show sy ++ ") "
showTrans (SkewX s) = "skewX(" ++ show s ++ ") "
showTrans (SkewY s) = "skewY(" ++ show s ++ ") "
showTrans (Rotate s _) = "rotate(" ++ show s ++ ") "
showTrans (Matrix a b c d e f) = "matrix(" ++
show a ++ "," ++ show b ++ "," ++ show c ++ "," ++
show d ++ "," ++ show e ++ "," ++ show f ++ ") "
-- showTrans _ = error "not implemented yet"
showSVG :: Double -> Double -> [ (Id, SVG) ] -> String
showSVG w h = show . document . svgToXml w h
svgToElem :: Double -> Double -> (Id, SVG) -> Element ()
svgToElem pw ph (idn, (Line p1 p2 color lineWidth)) = Elem (N "line") [
(N "id", AttValue [Left idn]),
(N "x1", AttValue [Left $ show x1]),
(N "y1", AttValue [Left $ show y1]),
(N "x2", AttValue [Left $ show x2]),
(N "y2", AttValue [Left $ show y2]),
(N "stroke", AttValue [Left $ mkColorStr color]),
(N "stroke-width", AttValue [Left $ show lineWidth]),
(N "stroke-linecap", AttValue [Left "round"]) ] []
where
(x1, y1) = getPos pw ph p1
(x2, y2) = getPos pw ph p2
svgToElem pw ph (idn, (Polyline points fillColor lineColor lineWidth)) =
Elem (N "polyline") [
(N "id", AttValue [ Left $ idn ]),
(N "points", AttValue [ Left $ pointsToAttVal points ]),
(N "fill" , AttValue [ Left $ mkColorStr fillColor ]),
(N "stroke", AttValue [ Left $ mkColorStr lineColor ]),
(N "stroke-width", AttValue [ Left $ show lineWidth ]) ] []
where
pointsToAttVal :: [Position] -> String
pointsToAttVal [] = ""
pointsToAttVal (p : ps) = let (x, y) = getPos pw ph p in
show x ++ "," ++ show y ++ " " ++ pointsToAttVal ps
svgToElem pw ph (idn, (Rect p w h sw cf cs)) = Elem (N "rect") [
(N "id", AttValue [Left $ idn]),
(N "x", AttValue [Left $ show x]),
(N "y", AttValue [Left $ show y]),
(N "width", AttValue [Left $ show w]),
(N "height", AttValue [Left $ show h]),
(N "stroke-width", AttValue [Left $ show sw]),
(N "fill", AttValue [Left $ mkColorStr cf]),
(N "stroke", AttValue [Left $ mkColorStr cs]) ] []
where (x, y) = getPos pw ph p
svgToElem pw ph (idn, (Fill c)) =
svgToElem pw ph $ (idn, Rect (TopLeft 0 0) pw ph 0 c c)
svgToElem pw ph (idn, (Text p s c f t)) = Elem (N "text") [
(N "id", AttValue [Left $ idn]),
(N "x", AttValue [Left $ show x]),
(N "y", AttValue [Left $ show y]),
(N "font-family", AttValue [Left $ fontName f]),
(N "font-weight", AttValue [Left $ weightValue $ fontWeight f]),
(N "font-size", AttValue [Left $ show s]),
(N "fill", AttValue [Left $ mkColorStr c]) ]
[CString False (escape t) ()]
where (x, y) = getPos pw ph p
svgToElem pw ph (idn, (Circle p r c)) = Elem (N "circle") [
(N "id", AttValue [Left $ idn]),
(N "cx", AttValue [Left $ show x]),
(N "cy", AttValue [Left $ show y]),
(N "r", AttValue [Left $ show r]),
(N "fill", AttValue [Left $ mkColorStr c]) ] []
where (x, y) = getPos pw ph p
svgToElem pw ph (idn, (Image p w h path)) = Elem (N "image") [
(N "id", AttValue [Left $ idn]),
(N "x", AttValue [Left $ show x]),
(N "y", AttValue [Left $ show y]),
(N "width", AttValue [Left $ show w]),
(N "height", AttValue [Left $ show h]),
(N "xlink:href", AttValue [Left path]) ] []
where (x, y) = getPos pw ph p
svgToElem pw ph (_idn, (Use p w h path)) = Elem (N "use") [
(N "x", AttValue [Left $ show x]),
(N "y", AttValue [Left $ show y]),
(N "width", AttValue [Left $ show w]),
(N "height", AttValue [Left $ show h]),
(N "xlink:href", AttValue [Left ("url(#"++path++")")]) ] []
where (x, y) = getPos pw ph p
svgToElem pw ph (_idn, (Group trs svgs)) = Elem (N "g")
[(N "transform", AttValue (map Left (map showTrans trs)))]
$ map (flip CElem () . svgToElem pw ph) svgs
svgToElem pw ph (_idn, (Defs svgs)) = Elem (N "defs") []
$ map (flip CElem () . svgToElem pw ph) svgs
-- svgToElem pw ph (id, (Symbol svgs)) = Elem (N "symbol") []
-- $ map (flip CElem () . svgToElem pw ph) svgs
svgToXml :: Double -> Double -> [ (Id,SVG) ] -> Document ()
svgToXml w h svgs = Document prlg [] (Elem (N "svg") (emAtt w h)
$ map (flip CElem () . svgToElem w h) svgs) []
pmsc :: [Misc]
pmsc = [ Comment " MADE BY SVG.HS " ]
pblit, sslit :: String
pblit = "-//W3C//DTD SVG 1.1//EN"
sslit = "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"
doctype :: DocTypeDecl
doctype = DTD (N "svg")
(Just (PUBLIC (PubidLiteral pblit) (SystemLiteral sslit))) []
xmldcl :: XMLDecl
xmldcl = XMLDecl "1.0" (Just (EncodingDecl "UTF-8")) Nothing
prlg :: Prolog
prlg = Prolog (Just xmldcl) pmsc (Just doctype) []
xmlns, ver, xlink :: String
xmlns = "http://www.w3.org/2000/svg"
ver = "1.1"
xlink = "http://www.w3.org/1999/xlink"
emAtt :: (Show a, Show b) => a -> b -> [(QName, AttValue)]
emAtt w h = [
(N "xmlns", AttValue [Left xmlns]),
(N "version", AttValue [Left ver]),
(N "xmlns:xlink", AttValue [Left xlink]),
(N "width", AttValue [Left $ show w]),
(N "height", AttValue [Left $ show h]) ]
escape :: String -> String
escape "" = ""
escape ('&' : cs) = "&" ++ escape cs
escape ('<' : cs) = "<" ++ escape cs
escape ('>' : cs) = ">" ++ escape cs
escape (c : cs) = c : escape cs
|
YoshikuniJujo/yjsvg_haskell
|
src/Text/XML/YJSVG.hs
|
Haskell
|
bsd-3-clause
| 7,487
|
{-# LANGUAGE OverloadedStrings #-}
module Redeux.DOM (module Redeux.DOM, DOM) where
import Redeux.Core
import Redeux.DOM.Core
import Data.Text (Text)
import qualified Data.Text as Text
div_, span_, p_, a_, h1_, h2_, h3_
, section_, footer_, header_, strong_
, label_, ul_, li_
, button_ :: [AttrOrHandler g] -> DOM g a -> DOM g a
div_ = el_ "div"
section_ = el_ "section"
footer_ = el_ "footer"
header_ = el_ "header"
label_ = el_ "label"
span_ = el_ "span"
strong_ = el_ "strong"
button_ = el_ "button"
ul_ = el_ "ul"
li_ = el_ "li"
p_ = el_ "p"
a_ = el_ "a"
h1_ = el_ "h1"
h2_ = el_ "h2"
h3_ = el_ "h3"
input_ :: [AttrOrHandler g] -> DOM g ()
input_ a = el_ "input" a (pure ())
attr_ :: Text -> Text -> AttrOrHandler g
attr_ name value = OrAttr (name, value)
text_ :: Text -> DOM g ()
text_ = text
class_, placeholder_, type_, value_
, href_ :: Text -> AttrOrHandler g
class_ = attr_ "class"
placeholder_ = attr_ "placeholder"
type_ = attr_ "type"
value_ = attr_ "value"
href_ = attr_ "href"
classes_ :: [Text] -> AttrOrHandler g
classes_ xs =
let classes = Text.intercalate " " $ xs
in if Text.null classes then OrEmpty
else class_ classes
checked_ :: Bool -> AttrOrHandler g
checked_ b =
if b then attr_ "checked" "checked"
else OrEmpty
onClick, onDoubleClick :: MouseHandler grammer -> AttrOrHandler grammer
onClick f = OrHandler $ Click f
onDoubleClick f = OrHandler $ DoubleClick f
onBlur :: FocusHandler grammer -> AttrOrHandler grammer
onBlur f = OrHandler $ Blur f
onKeyUp, onKeyDown :: KeyboardHandler grammer -> AttrOrHandler grammer
onKeyUp f = OrHandler $ KeyUp f
onKeyDown f = OrHandler $ KeyDown f
onClick_, onDoubleClick_, onBlur_, onKeyUp_, onKeyDown_ :: Command grammer () -> AttrOrHandler grammer
onClick_ = onClick . const
onDoubleClick_ = onDoubleClick . const
onBlur_ = onBlur . const
onKeyUp_ = onKeyUp . const
onKeyDown_ = onKeyDown . const
|
eborden/redeux
|
src/Redeux/DOM.hs
|
Haskell
|
bsd-3-clause
| 1,992
|
{-# LANGUAGE DeriveDataTypeable #-}
module Missile where
import Data.Data
import Data.Typeable
import Coordinate
type Missile = String
type Missiles = [String]
data Speed = Speed { x :: Float, y :: Float } deriving (Data, Typeable, Show)
data MissileLaunched = MissileLaunched { code :: String, speed :: Speed, pos :: Coordinates, launchTime :: Int } deriving (Data, Typeable, Show)
removeMissedMissiles :: Int -> Float -> [MissileLaunched] -> [MissileLaunched]
removeMissedMissiles currentTime maxWidth missiles = filter (inBoard currentTime maxWidth) missiles
inBoard :: Int -> Float -> MissileLaunched -> Bool
inBoard currentTime maxWidth missile = do
let currentX = missileCurrentX currentTime missile
(currentX > -2000) && (currentX < (maxWidth + 2000))
missileStartX :: MissileLaunched -> Float
missileStartX = Coordinate.x . Missile.pos
missileCurrentX :: Int -> MissileLaunched -> Float
missileCurrentX currentTime missile = startX + (runtime * missileSpeed)
where startX = missileStartX missile
runtime = fromIntegral $ currentTime - (launchTime $ missile)
missileSpeed = Missile.x $ speed $ missile
|
timorantalaiho/pong11
|
src/Missile.hs
|
Haskell
|
bsd-3-clause
| 1,142
|
{-# LANGUAGE MultiParamTypeClasses, TypeFamilies, FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances,Rank2Types, ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS -Wall #-}
module PushdownAutomaton.State (
PDAState(PDAState),
PDAStaten, initialStackn, initialPDAStaten,
PDATransn, gcompile, translate
) where
import Basic.Types (GetValue, Forward, Trans(Trans), readMem, next)
import Basic.Memory --(Stack(..), empty, MapLike(..))
import Basic.Features (HasQ(..), HasMemory(..), HasIP(..))
import Control.Lens (makeLenses, (%~), (^.), (.~))
import PushdownAutomaton.Operations
---------------------------------------------------------------------
---- PDAState
---------------------------------------------------------------------
data PDAState qs stk ptr = PDAState {_cs :: qs, _mem :: stk, _inptp :: ptr}
makeLenses ''PDAState
instance HasQ (PDAState qs stk ptr) where
type Q (PDAState qs stk ptr) = qs
q = cs
instance HasMemory (PDAState qs stk ptr) where
type Memory (PDAState qs stk ptr) = stk
memory = mem
instance HasIP (PDAState qs stk ptr) where
type IP (PDAState qs stk ptr) = ptr
ip = inptp
---------------------------------------------------------------------
---- PDAState with n stack
---------------------------------------------------------------------
type PDAStaten qs map n stack s ptr = PDAState qs (map n (stack s)) ptr
initialStackn :: (Stack s, MapLike m) => v -> m a (s v) -> m a (s v)
initialStackn v mapn = mapWithKeyM mapn (\_ _ -> push v empty)
initialPDAStaten :: (Stack stack, MapLike map, Ord n, Bounded n, Enum n) =>
qs -> v -> ptr -> PDAStaten qs map n stack v ptr
initialPDAStaten qs v ptr = PDAState qs (initialStackn v emptyM') ptr
type PDATransn m n ch s qs = ch -> m n s -> qs -> (qs, m n (StackCommd s))
gcompile :: (Ord a, HasQ st, HasIP st, HasMemory st, Stack s, MapLike m,
Memory st ~ m a (s v), Forward (IP st), GetValue (IP st) mem b ) =>
(b -> m a v -> Q st -> (Q st, m a (StackCommd v))) -> Trans (x, mem b) st
gcompile f = Trans g
where g (_, inpt) st = ip %~ next $ q .~ qs' $ memory %~ (stackoperate comds') $ st
where stkm = mapWithKeyM (st^.memory) (\_ -> top)
ch = readMem (st^.ip) inpt
(qs', comds') = f ch stkm (st^.q)
stackoperate comds stkmap = mapWithKeyM stkmap sop
where sop k sta = stackoperation (lookupM comds k) sta
translate :: forall a b qs m n. (Ord n, Bounded n, Enum n, AscListLike m) =>
(a -> [b] -> qs -> (qs, [StackCommd b])) -> PDATransn m n a b qs
translate f inp stak qs = (qs', mapFromL (minBound::n) stakctrl)
where
(qs', stakctrl) = f inp stak' qs
stak' = map snd $ mapToL stak
|
davidzhulijun/TAM
|
PushdownAutomaton/State.hs
|
Haskell
|
bsd-3-clause
| 2,717
|
-----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 2006
--
-- The purpose of this module is to transform an HsExpr into a CoreExpr which
-- when evaluated, returns a (Meta.Q Meta.Exp) computation analogous to the
-- input HsExpr. We do this in the DsM monad, which supplies access to
-- CoreExpr's of the "smart constructors" of the Meta.Exp datatype.
--
-- It also defines a bunch of knownKeyNames, in the same way as is done
-- in prelude/PrelNames. It's much more convenient to do it here, becuase
-- otherwise we have to recompile PrelNames whenever we add a Name, which is
-- a Royal Pain (triggers other recompilation).
-----------------------------------------------------------------------------
{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
-- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details
module DsMeta( dsBracket,
templateHaskellNames, qTyConName, nameTyConName,
liftName, liftStringName, expQTyConName, patQTyConName,
decQTyConName, decsQTyConName, typeQTyConName,
decTyConName, typeTyConName, mkNameG_dName, mkNameG_vName, mkNameG_tcName,
quoteExpName, quotePatName, quoteDecName, quoteTypeName
) where
#include "HsVersions.h"
import {-# SOURCE #-} DsExpr ( dsExpr )
import MatchLit
import DsMonad
import qualified Language.Haskell.TH as TH
import HsSyn
import Class
import PrelNames
-- To avoid clashes with DsMeta.varName we must make a local alias for
-- OccName.varName we do this by removing varName from the import of
-- OccName above, making a qualified instance of OccName and using
-- OccNameAlias.varName where varName ws previously used in this file.
import qualified OccName( isDataOcc, isVarOcc, isTcOcc, varName, tcName, dataName )
import Module
import Id
import Name hiding( isVarOcc, isTcOcc, varName, tcName )
import NameEnv
import TcType
import TyCon
import TysWiredIn
import TysPrim ( liftedTypeKindTyConName, constraintKindTyConName )
import CoreSyn
import MkCore
import CoreUtils
import SrcLoc
import Unique
import BasicTypes
import Outputable
import Bag
import FastString
import ForeignCall
import MonadUtils
import Util
import Data.Maybe
import Control.Monad
import Data.List
-----------------------------------------------------------------------------
dsBracket :: HsBracket Name -> [PendingSplice] -> DsM CoreExpr
-- Returns a CoreExpr of type TH.ExpQ
-- The quoted thing is parameterised over Name, even though it has
-- been type checked. We don't want all those type decorations!
dsBracket brack splices
= dsExtendMetaEnv new_bit (do_brack brack)
where
new_bit = mkNameEnv [(n, Splice (unLoc e)) | (n,e) <- splices]
do_brack (VarBr _ n) = do { MkC e1 <- lookupOcc n ; return e1 }
do_brack (ExpBr e) = do { MkC e1 <- repLE e ; return e1 }
do_brack (PatBr p) = do { MkC p1 <- repTopP p ; return p1 }
do_brack (TypBr t) = do { MkC t1 <- repLTy t ; return t1 }
do_brack (DecBrG gp) = do { MkC ds1 <- repTopDs gp ; return ds1 }
do_brack (DecBrL _) = panic "dsBracket: unexpected DecBrL"
{- -------------- Examples --------------------
[| \x -> x |]
====>
gensym (unpackString "x"#) `bindQ` \ x1::String ->
lam (pvar x1) (var x1)
[| \x -> $(f [| x |]) |]
====>
gensym (unpackString "x"#) `bindQ` \ x1::String ->
lam (pvar x1) (f (var x1))
-}
-------------------------------------------------------
-- Declarations
-------------------------------------------------------
repTopP :: LPat Name -> DsM (Core TH.PatQ)
repTopP pat = do { ss <- mkGenSyms (collectPatBinders pat)
; pat' <- addBinds ss (repLP pat)
; wrapGenSyms ss pat' }
repTopDs :: HsGroup Name -> DsM (Core (TH.Q [TH.Dec]))
repTopDs group
= do { let { tv_bndrs = hsSigTvBinders (hs_valds group)
; bndrs = tv_bndrs ++ hsGroupBinders group } ;
ss <- mkGenSyms bndrs ;
-- Bind all the names mainly to avoid repeated use of explicit strings.
-- Thus we get
-- do { t :: String <- genSym "T" ;
-- return (Data t [] ...more t's... }
-- The other important reason is that the output must mention
-- only "T", not "Foo:T" where Foo is the current module
decls <- addBinds ss (do {
fix_ds <- mapM repFixD (hs_fixds group) ;
val_ds <- rep_val_binds (hs_valds group) ;
tycl_ds <- mapM repTyClD (concat (hs_tyclds group)) ;
inst_ds <- mapM repInstD (hs_instds group) ;
rule_ds <- mapM repRuleD (hs_ruleds group) ;
for_ds <- mapM repForD (hs_fords group) ;
-- more needed
return (de_loc $ sort_by_loc $
val_ds ++ catMaybes tycl_ds ++ fix_ds
++ inst_ds ++ rule_ds ++ for_ds) }) ;
decl_ty <- lookupType decQTyConName ;
let { core_list = coreList' decl_ty decls } ;
dec_ty <- lookupType decTyConName ;
q_decs <- repSequenceQ dec_ty core_list ;
wrapGenSyms ss q_decs
}
hsSigTvBinders :: HsValBinds Name -> [Name]
-- See Note [Scoped type variables in bindings]
hsSigTvBinders binds
= [hsLTyVarName tv | L _ (TypeSig _ (L _ (HsForAllTy Explicit qtvs _ _))) <- sigs
, tv <- hsQTvBndrs qtvs]
where
sigs = case binds of
ValBindsIn _ sigs -> sigs
ValBindsOut _ sigs -> sigs
{- Notes
Note [Scoped type variables in bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f :: forall a. a -> a
f x = x::a
Here the 'forall a' brings 'a' into scope over the binding group.
To achieve this we
a) Gensym a binding for 'a' at the same time as we do one for 'f'
collecting the relevant binders with hsSigTvBinders
b) When processing the 'forall', don't gensym
The relevant places are signposted with references to this Note
Note [Binders and occurrences]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we desugar [d| data T = MkT |]
we want to get
Data "T" [] [Con "MkT" []] []
and *not*
Data "Foo:T" [] [Con "Foo:MkT" []] []
That is, the new data decl should fit into whatever new module it is
asked to fit in. We do *not* clone, though; no need for this:
Data "T79" ....
But if we see this:
data T = MkT
foo = reifyDecl T
then we must desugar to
foo = Data "Foo:T" [] [Con "Foo:MkT" []] []
So in repTopDs we bring the binders into scope with mkGenSyms and addBinds.
And we use lookupOcc, rather than lookupBinder
in repTyClD and repC.
-}
-- represent associated family instances
--
repTyClDs :: [LTyClDecl Name] -> DsM [Core TH.DecQ]
repTyClDs ds = liftM de_loc (mapMaybeM repTyClD ds)
repTyClD :: LTyClDecl Name -> DsM (Maybe (SrcSpan, Core TH.DecQ))
repTyClD (L loc (TyFamily { tcdFlavour = flavour,
tcdLName = tc, tcdTyVars = tvs,
tcdKindSig = opt_kind }))
= do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences]
; dec <- addTyClTyVarBinds tvs $ \bndrs ->
do { flav <- repFamilyFlavour flavour
; case opt_kind of
Nothing -> repFamilyNoKind flav tc1 bndrs
Just ki -> do { ki1 <- repLKind ki
; repFamilyKind flav tc1 bndrs ki1 }
}
; return $ Just (loc, dec)
}
repTyClD (L loc (TyDecl { tcdLName = tc, tcdTyVars = tvs, tcdTyDefn = defn }))
= do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences]
; tc_tvs <- mk_extra_tvs tc tvs defn
; dec <- addTyClTyVarBinds tc_tvs $ \bndrs ->
repTyDefn tc1 bndrs Nothing (hsLTyVarNames tc_tvs) defn
; return (Just (loc, dec)) }
repTyClD (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls,
tcdTyVars = tvs, tcdFDs = fds,
tcdSigs = sigs, tcdMeths = meth_binds,
tcdATs = ats, tcdATDefs = [] }))
= do { cls1 <- lookupLOcc cls -- See note [Binders and occurrences]
; dec <- addTyVarBinds tvs $ \bndrs ->
do { cxt1 <- repLContext cxt
; sigs1 <- rep_sigs sigs
; binds1 <- rep_binds meth_binds
; fds1 <- repLFunDeps fds
; ats1 <- repTyClDs ats
; decls1 <- coreList decQTyConName (ats1 ++ sigs1 ++ binds1)
; repClass cxt1 cls1 bndrs fds1 decls1
}
; return $ Just (loc, dec)
}
-- Un-handled cases
repTyClD (L loc d) = putSrcSpanDs loc $
do { warnDs (hang ds_msg 4 (ppr d))
; return Nothing }
-------------------------
repTyDefn :: Core TH.Name -> Core [TH.TyVarBndr]
-> Maybe (Core [TH.TypeQ])
-> [Name] -> HsTyDefn Name
-> DsM (Core TH.DecQ)
repTyDefn tc bndrs opt_tys tv_names
(TyData { td_ND = new_or_data, td_ctxt = cxt
, td_cons = cons, td_derivs = mb_derivs })
= do { cxt1 <- repLContext cxt
; derivs1 <- repDerivs mb_derivs
; case new_or_data of
NewType -> do { con1 <- repC tv_names (head cons)
; repNewtype cxt1 tc bndrs opt_tys con1 derivs1 }
DataType -> do { cons1 <- mapM (repC tv_names) cons
; cons2 <- coreList conQTyConName cons1
; repData cxt1 tc bndrs opt_tys cons2 derivs1 } }
repTyDefn tc bndrs opt_tys _ (TySynonym { td_synRhs = ty })
= do { ty1 <- repLTy ty
; repTySyn tc bndrs opt_tys ty1 }
-------------------------
mk_extra_tvs :: Located Name -> LHsTyVarBndrs Name
-> HsTyDefn Name -> DsM (LHsTyVarBndrs Name)
-- If there is a kind signature it must be of form
-- k1 -> .. -> kn -> *
-- Return type variables [tv1:k1, tv2:k2, .., tvn:kn]
mk_extra_tvs tc tvs defn
| TyData { td_kindSig = Just hs_kind } <- defn
= do { extra_tvs <- go hs_kind
; return (tvs { hsq_tvs = hsq_tvs tvs ++ extra_tvs }) }
| otherwise
= return tvs
where
go :: LHsKind Name -> DsM [LHsTyVarBndr Name]
go (L loc (HsFunTy kind rest))
= do { uniq <- newUnique
; let { occ = mkTyVarOccFS (fsLit "t")
; nm = mkInternalName uniq occ loc
; hs_tv = L loc (KindedTyVar nm kind) }
; hs_tvs <- go rest
; return (hs_tv : hs_tvs) }
go (L _ (HsTyVar n))
| n == liftedTypeKindTyConName
= return []
go _ = failWithDs (ptext (sLit "Malformed kind signature for") <+> ppr tc)
-------------------------
-- represent fundeps
--
repLFunDeps :: [Located (FunDep Name)] -> DsM (Core [TH.FunDep])
repLFunDeps fds = do fds' <- mapM repLFunDep fds
fdList <- coreList funDepTyConName fds'
return fdList
repLFunDep :: Located (FunDep Name) -> DsM (Core TH.FunDep)
repLFunDep (L _ (xs, ys)) = do xs' <- mapM lookupBinder xs
ys' <- mapM lookupBinder ys
xs_list <- coreList nameTyConName xs'
ys_list <- coreList nameTyConName ys'
repFunDep xs_list ys_list
-- represent family declaration flavours
--
repFamilyFlavour :: FamilyFlavour -> DsM (Core TH.FamFlavour)
repFamilyFlavour TypeFamily = rep2 typeFamName []
repFamilyFlavour DataFamily = rep2 dataFamName []
-- Represent instance declarations
--
repInstD :: LInstDecl Name -> DsM (SrcSpan, Core TH.DecQ)
repInstD (L loc (FamInstD { lid_inst = fi_decl }))
= do { dec <- repFamInstD fi_decl
; return (loc, dec) }
repInstD (L loc (ClsInstD { cid_poly_ty = ty, cid_binds = binds
, cid_sigs = prags, cid_fam_insts = ats }))
= do { dec <- addTyVarBinds tvs $ \_ ->
-- We must bring the type variables into scope, so their
-- occurrences don't fail, even though the binders don't
-- appear in the resulting data structure
--
-- But we do NOT bring the binders of 'binds' into scope
-- becuase they are properly regarded as occurrences
-- For example, the method names should be bound to
-- the selector Ids, not to fresh names (Trac #5410)
--
do { cxt1 <- repContext cxt
; cls_tcon <- repTy (HsTyVar (unLoc cls))
; cls_tys <- repLTys tys
; inst_ty1 <- repTapps cls_tcon cls_tys
; binds1 <- rep_binds binds
; prags1 <- rep_sigs prags
; ats1 <- mapM (repFamInstD . unLoc) ats
; decls <- coreList decQTyConName (ats1 ++ binds1 ++ prags1)
; repInst cxt1 inst_ty1 decls }
; return (loc, dec) }
where
Just (tvs, cxt, cls, tys) = splitLHsInstDeclTy_maybe ty
repFamInstD :: FamInstDecl Name -> DsM (Core TH.DecQ)
repFamInstD (FamInstDecl { fid_tycon = tc_name
, fid_pats = HsWB { hswb_cts = tys, hswb_kvs = kv_names, hswb_tvs = tv_names }
, fid_defn = defn })
= WARN( not (null kv_names), ppr kv_names ) -- We have not yet dealt with kind
-- polymorphism in Template Haskell (sigh)
do { tc <- lookupLOcc tc_name -- See note [Binders and occurrences]
; let loc = getLoc tc_name
hs_tvs = HsQTvs { hsq_kvs = kv_names, hsq_tvs = userHsTyVarBndrs loc tv_names } -- Yuk
; addTyClTyVarBinds hs_tvs $ \ bndrs ->
do { tys1 <- repLTys tys
; tys2 <- coreList typeQTyConName tys1
; repTyDefn tc bndrs (Just tys2) tv_names defn } }
repForD :: Located (ForeignDecl Name) -> DsM (SrcSpan, Core TH.DecQ)
repForD (L loc (ForeignImport name typ _ (CImport cc s mch cis)))
= do MkC name' <- lookupLOcc name
MkC typ' <- repLTy typ
MkC cc' <- repCCallConv cc
MkC s' <- repSafety s
cis' <- conv_cimportspec cis
MkC str <- coreStringLit (static ++ chStr ++ cis')
dec <- rep2 forImpDName [cc', s', str, name', typ']
return (loc, dec)
where
conv_cimportspec (CLabel cls) = notHandled "Foreign label" (doubleQuotes (ppr cls))
conv_cimportspec (CFunction DynamicTarget) = return "dynamic"
conv_cimportspec (CFunction (StaticTarget fs _ True)) = return (unpackFS fs)
conv_cimportspec (CFunction (StaticTarget _ _ False)) = panic "conv_cimportspec: values not supported yet"
conv_cimportspec CWrapper = return "wrapper"
static = case cis of
CFunction (StaticTarget _ _ _) -> "static "
_ -> ""
chStr = case mch of
Nothing -> ""
Just (Header h) -> unpackFS h ++ " "
repForD decl = notHandled "Foreign declaration" (ppr decl)
repCCallConv :: CCallConv -> DsM (Core TH.Callconv)
repCCallConv CCallConv = rep2 cCallName []
repCCallConv StdCallConv = rep2 stdCallName []
repCCallConv callConv = notHandled "repCCallConv" (ppr callConv)
repSafety :: Safety -> DsM (Core TH.Safety)
repSafety PlayRisky = rep2 unsafeName []
repSafety PlayInterruptible = rep2 interruptibleName []
repSafety PlaySafe = rep2 safeName []
repFixD :: LFixitySig Name -> DsM (SrcSpan, Core TH.DecQ)
repFixD (L loc (FixitySig name (Fixity prec dir)))
= do { MkC name' <- lookupLOcc name
; MkC prec' <- coreIntLit prec
; let rep_fn = case dir of
InfixL -> infixLDName
InfixR -> infixRDName
InfixN -> infixNDName
; dec <- rep2 rep_fn [prec', name']
; return (loc, dec) }
repRuleD :: LRuleDecl Name -> DsM (SrcSpan, Core TH.DecQ)
repRuleD (L loc (HsRule n act bndrs lhs _ rhs _))
= do { n' <- coreStringLit $ unpackFS n
; phases <- repPhases act
; bndrs' <- mapM repRuleBndr bndrs >>= coreList ruleBndrQTyConName
; lhs' <- repLE lhs
; rhs' <- repLE rhs
; pragma <- repPragRule n' bndrs' lhs' rhs' phases
; return (loc, pragma) }
repRuleBndr :: RuleBndr Name -> DsM (Core TH.RuleBndrQ)
repRuleBndr (RuleBndr n)
= do { MkC n' <- lookupLOcc n
; rep2 ruleVarName [n'] }
repRuleBndr (RuleBndrSig n (HsWB { hswb_cts = ty }))
= do { MkC n' <- lookupLOcc n
; MkC ty' <- repLTy ty
; rep2 typedRuleVarName [n', ty'] }
ds_msg :: SDoc
ds_msg = ptext (sLit "Cannot desugar this Template Haskell declaration:")
-------------------------------------------------------
-- Constructors
-------------------------------------------------------
repC :: [Name] -> LConDecl Name -> DsM (Core TH.ConQ)
repC _ (L _ (ConDecl { con_name = con, con_qvars = con_tvs, con_cxt = L _ []
, con_details = details, con_res = ResTyH98 }))
| null (hsQTvBndrs con_tvs)
= do { con1 <- lookupLOcc con -- See Note [Binders and occurrences]
; repConstr con1 details }
repC tvs (L _ (ConDecl { con_name = con
, con_qvars = con_tvs, con_cxt = L _ ctxt
, con_details = details
, con_res = res_ty }))
= do { (eq_ctxt, con_tv_subst) <- mkGadtCtxt tvs res_ty
; let ex_tvs = HsQTvs { hsq_kvs = filterOut (in_subst con_tv_subst) (hsq_kvs con_tvs)
, hsq_tvs = filterOut (in_subst con_tv_subst . hsLTyVarName) (hsq_tvs con_tvs) }
; binds <- mapM dupBinder con_tv_subst
; dsExtendMetaEnv (mkNameEnv binds) $ -- Binds some of the con_tvs
addTyVarBinds ex_tvs $ \ ex_bndrs -> -- Binds the remaining con_tvs
do { con1 <- lookupLOcc con -- See Note [Binders and occurrences]
; c' <- repConstr con1 details
; ctxt' <- repContext (eq_ctxt ++ ctxt)
; rep2 forallCName [unC ex_bndrs, unC ctxt', unC c'] } }
in_subst :: [(Name,Name)] -> Name -> Bool
in_subst [] _ = False
in_subst ((n',_):ns) n = n==n' || in_subst ns n
mkGadtCtxt :: [Name] -- Tyvars of the data type
-> ResType (LHsType Name)
-> DsM (HsContext Name, [(Name,Name)])
-- Given a data type in GADT syntax, figure out the equality
-- context, so that we can represent it with an explicit
-- equality context, because that is the only way to express
-- the GADT in TH syntax
--
-- Example:
-- data T a b c where { MkT :: forall d e. d -> e -> T d [e] e
-- mkGadtCtxt [a,b,c] [d,e] (T d [e] e)
-- returns
-- (b~[e], c~e), [d->a]
--
-- This function is fiddly, but not really hard
mkGadtCtxt _ ResTyH98
= return ([], [])
mkGadtCtxt data_tvs (ResTyGADT res_ty)
| let (head_ty, tys) = splitHsAppTys res_ty []
, Just _ <- is_hs_tyvar head_ty
, data_tvs `equalLength` tys
= return (go [] [] (data_tvs `zip` tys))
| otherwise
= failWithDs (ptext (sLit "Malformed constructor result type:") <+> ppr res_ty)
where
go cxt subst [] = (cxt, subst)
go cxt subst ((data_tv, ty) : rest)
| Just con_tv <- is_hs_tyvar ty
, isTyVarName con_tv
, not (in_subst subst con_tv)
= go cxt ((con_tv, data_tv) : subst) rest
| otherwise
= go (eq_pred : cxt) subst rest
where
loc = getLoc ty
eq_pred = L loc (HsEqTy (L loc (HsTyVar data_tv)) ty)
is_hs_tyvar (L _ (HsTyVar n)) = Just n -- Type variables *and* tycons
is_hs_tyvar (L _ (HsParTy ty)) = is_hs_tyvar ty
is_hs_tyvar _ = Nothing
repBangTy :: LBangType Name -> DsM (Core (TH.StrictTypeQ))
repBangTy ty= do
MkC s <- rep2 str []
MkC t <- repLTy ty'
rep2 strictTypeName [s, t]
where
(str, ty') = case ty of
L _ (HsBangTy HsUnpack ty) -> (unpackedName, ty)
L _ (HsBangTy _ ty) -> (isStrictName, ty)
_ -> (notStrictName, ty)
-------------------------------------------------------
-- Deriving clause
-------------------------------------------------------
repDerivs :: Maybe [LHsType Name] -> DsM (Core [TH.Name])
repDerivs Nothing = coreList nameTyConName []
repDerivs (Just ctxt)
= do { strs <- mapM rep_deriv ctxt ;
coreList nameTyConName strs }
where
rep_deriv :: LHsType Name -> DsM (Core TH.Name)
-- Deriving clauses must have the simple H98 form
rep_deriv ty
| Just (cls, []) <- splitHsClassTy_maybe (unLoc ty)
= lookupOcc cls
| otherwise
= notHandled "Non-H98 deriving clause" (ppr ty)
-------------------------------------------------------
-- Signatures in a class decl, or a group of bindings
-------------------------------------------------------
rep_sigs :: [LSig Name] -> DsM [Core TH.DecQ]
rep_sigs sigs = do locs_cores <- rep_sigs' sigs
return $ de_loc $ sort_by_loc locs_cores
rep_sigs' :: [LSig Name] -> DsM [(SrcSpan, Core TH.DecQ)]
-- We silently ignore ones we don't recognise
rep_sigs' sigs = do { sigs1 <- mapM rep_sig sigs ;
return (concat sigs1) }
rep_sig :: LSig Name -> DsM [(SrcSpan, Core TH.DecQ)]
-- Singleton => Ok
-- Empty => Too hard, signature ignored
rep_sig (L loc (TypeSig nms ty)) = mapM (rep_ty_sig loc ty) nms
rep_sig (L _ (GenericSig nm _)) = failWithDs msg
where msg = vcat [ ptext (sLit "Illegal default signature for") <+> quotes (ppr nm)
, ptext (sLit "Default signatures are not supported by Template Haskell") ]
rep_sig (L loc (InlineSig nm ispec)) = rep_inline nm ispec loc
rep_sig (L loc (SpecSig nm ty ispec)) = rep_specialise nm ty ispec loc
rep_sig (L loc (SpecInstSig ty)) = rep_specialiseInst ty loc
rep_sig _ = return []
rep_ty_sig :: SrcSpan -> LHsType Name -> Located Name
-> DsM (SrcSpan, Core TH.DecQ)
rep_ty_sig loc (L _ ty) nm
= do { nm1 <- lookupLOcc nm
; ty1 <- rep_ty ty
; sig <- repProto nm1 ty1
; return (loc, sig) }
where
-- We must special-case the top-level explicit for-all of a TypeSig
-- See Note [Scoped type variables in bindings]
rep_ty (HsForAllTy Explicit tvs ctxt ty)
= do { let rep_in_scope_tv tv = do { name <- lookupBinder (hsLTyVarName tv)
; repTyVarBndrWithKind tv name }
; bndrs1 <- mapM rep_in_scope_tv (hsQTvBndrs tvs)
; bndrs2 <- coreList tyVarBndrTyConName bndrs1
; ctxt1 <- repLContext ctxt
; ty1 <- repLTy ty
; repTForall bndrs2 ctxt1 ty1 }
rep_ty ty = repTy ty
rep_inline :: Located Name
-> InlinePragma -- Never defaultInlinePragma
-> SrcSpan
-> DsM [(SrcSpan, Core TH.DecQ)]
rep_inline nm ispec loc
= do { nm1 <- lookupLOcc nm
; inline <- repInline $ inl_inline ispec
; rm <- repRuleMatch $ inl_rule ispec
; phases <- repPhases $ inl_act ispec
; pragma <- repPragInl nm1 inline rm phases
; return [(loc, pragma)]
}
rep_specialise :: Located Name -> LHsType Name -> InlinePragma -> SrcSpan
-> DsM [(SrcSpan, Core TH.DecQ)]
rep_specialise nm ty ispec loc
= do { nm1 <- lookupLOcc nm
; ty1 <- repLTy ty
; phases <- repPhases $ inl_act ispec
; let inline = inl_inline ispec
; pragma <- if isEmptyInlineSpec inline
then -- SPECIALISE
repPragSpec nm1 ty1 phases
else -- SPECIALISE INLINE
do { inline1 <- repInline inline
; repPragSpecInl nm1 ty1 inline1 phases }
; return [(loc, pragma)]
}
rep_specialiseInst :: LHsType Name -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)]
rep_specialiseInst ty loc
= do { ty1 <- repLTy ty
; pragma <- repPragSpecInst ty1
; return [(loc, pragma)] }
repInline :: InlineSpec -> DsM (Core TH.Inline)
repInline NoInline = dataCon noInlineDataConName
repInline Inline = dataCon inlineDataConName
repInline Inlinable = dataCon inlinableDataConName
repInline spec = notHandled "repInline" (ppr spec)
repRuleMatch :: RuleMatchInfo -> DsM (Core TH.RuleMatch)
repRuleMatch ConLike = dataCon conLikeDataConName
repRuleMatch FunLike = dataCon funLikeDataConName
repPhases :: Activation -> DsM (Core TH.Phases)
repPhases (ActiveBefore i) = do { MkC arg <- coreIntLit i
; dataCon' beforePhaseDataConName [arg] }
repPhases (ActiveAfter i) = do { MkC arg <- coreIntLit i
; dataCon' fromPhaseDataConName [arg] }
repPhases _ = dataCon allPhasesDataConName
-------------------------------------------------------
-- Types
-------------------------------------------------------
addTyVarBinds :: LHsTyVarBndrs Name -- the binders to be added
-> (Core [TH.TyVarBndr] -> DsM (Core (TH.Q a))) -- action in the ext env
-> DsM (Core (TH.Q a))
-- gensym a list of type variables and enter them into the meta environment;
-- the computations passed as the second argument is executed in that extended
-- meta environment and gets the *new* names on Core-level as an argument
addTyVarBinds tvs m
= do { freshNames <- mkGenSyms (hsLKiTyVarNames tvs)
; term <- addBinds freshNames $
do { kbs1 <- mapM mk_tv_bndr (hsQTvBndrs tvs `zip` freshNames)
; kbs2 <- coreList tyVarBndrTyConName kbs1
; m kbs2 }
; wrapGenSyms freshNames term }
where
mk_tv_bndr (tv, (_,v)) = repTyVarBndrWithKind tv (coreVar v)
addTyClTyVarBinds :: LHsTyVarBndrs Name
-> (Core [TH.TyVarBndr] -> DsM (Core (TH.Q a)))
-> DsM (Core (TH.Q a))
-- Used for data/newtype declarations, and family instances,
-- so that the nested type variables work right
-- instance C (T a) where
-- type W (T a) = blah
-- The 'a' in the type instance is the one bound by the instance decl
addTyClTyVarBinds tvs m
= do { let tv_names = hsLKiTyVarNames tvs
; env <- dsGetMetaEnv
; freshNames <- mkGenSyms (filterOut (`elemNameEnv` env) tv_names)
-- Make fresh names for the ones that are not already in scope
-- This makes things work for family declarations
; term <- addBinds freshNames $
do { kbs1 <- mapM mk_tv_bndr (hsQTvBndrs tvs)
; kbs2 <- coreList tyVarBndrTyConName kbs1
; m kbs2 }
; wrapGenSyms freshNames term }
where
mk_tv_bndr tv = do { v <- lookupOcc (hsLTyVarName tv)
; repTyVarBndrWithKind tv v }
-- Produce kinded binder constructors from the Haskell tyvar binders
--
repTyVarBndrWithKind :: LHsTyVarBndr Name
-> Core TH.Name -> DsM (Core TH.TyVarBndr)
repTyVarBndrWithKind (L _ (UserTyVar {})) nm
= repPlainTV nm
repTyVarBndrWithKind (L _ (KindedTyVar _ ki)) nm
= repLKind ki >>= repKindedTV nm
-- represent a type context
--
repLContext :: LHsContext Name -> DsM (Core TH.CxtQ)
repLContext (L _ ctxt) = repContext ctxt
repContext :: HsContext Name -> DsM (Core TH.CxtQ)
repContext ctxt = do
preds <- mapM repLPred ctxt
predList <- coreList predQTyConName preds
repCtxt predList
-- represent a type predicate
--
repLPred :: LHsType Name -> DsM (Core TH.PredQ)
repLPred (L _ p) = repPred p
repPred :: HsType Name -> DsM (Core TH.PredQ)
repPred ty
| Just (cls, tys) <- splitHsClassTy_maybe ty
= do
cls1 <- lookupOcc cls
tys1 <- repLTys tys
tys2 <- coreList typeQTyConName tys1
repClassP cls1 tys2
repPred (HsEqTy tyleft tyright)
= do
tyleft1 <- repLTy tyleft
tyright1 <- repLTy tyright
repEqualP tyleft1 tyright1
repPred ty
= notHandled "Exotic predicate type" (ppr ty)
-- yield the representation of a list of types
--
repLTys :: [LHsType Name] -> DsM [Core TH.TypeQ]
repLTys tys = mapM repLTy tys
-- represent a type
--
repLTy :: LHsType Name -> DsM (Core TH.TypeQ)
repLTy (L _ ty) = repTy ty
repTy :: HsType Name -> DsM (Core TH.TypeQ)
repTy (HsForAllTy _ tvs ctxt ty) =
addTyVarBinds tvs $ \bndrs -> do
ctxt1 <- repLContext ctxt
ty1 <- repLTy ty
repTForall bndrs ctxt1 ty1
repTy (HsTyVar n)
| isTvOcc occ = do tv1 <- lookupOcc n
repTvar tv1
| isDataOcc occ = do tc1 <- lookupOcc n
repPromotedTyCon tc1
| otherwise = do tc1 <- lookupOcc n
repNamedTyCon tc1
where
occ = nameOccName n
repTy (HsAppTy f a) = do
f1 <- repLTy f
a1 <- repLTy a
repTapp f1 a1
repTy (HsFunTy f a) = do
f1 <- repLTy f
a1 <- repLTy a
tcon <- repArrowTyCon
repTapps tcon [f1, a1]
repTy (HsListTy t) = do
t1 <- repLTy t
tcon <- repListTyCon
repTapp tcon t1
repTy (HsPArrTy t) = do
t1 <- repLTy t
tcon <- repTy (HsTyVar (tyConName parrTyCon))
repTapp tcon t1
repTy (HsTupleTy HsUnboxedTuple tys) = do
tys1 <- repLTys tys
tcon <- repUnboxedTupleTyCon (length tys)
repTapps tcon tys1
repTy (HsTupleTy _ tys) = do tys1 <- repLTys tys
tcon <- repTupleTyCon (length tys)
repTapps tcon tys1
repTy (HsOpTy ty1 (_, n) ty2) = repLTy ((nlHsTyVar (unLoc n) `nlHsAppTy` ty1)
`nlHsAppTy` ty2)
repTy (HsParTy t) = repLTy t
repTy (HsKindSig t k) = do
t1 <- repLTy t
k1 <- repLKind k
repTSig t1 k1
repTy (HsSpliceTy splice _ _) = repSplice splice
repTy (HsExplicitListTy _ tys) = do
tys1 <- repLTys tys
repTPromotedList tys1
repTy (HsExplicitTupleTy _ tys) = do
tys1 <- repLTys tys
tcon <- repPromotedTupleTyCon (length tys)
repTapps tcon tys1
repTy (HsTyLit lit) = do
lit' <- repTyLit lit
repTLit lit'
repTy ty = notHandled "Exotic form of type" (ppr ty)
repTyLit :: HsTyLit -> DsM (Core TH.TyLitQ)
repTyLit (HsNumTy i) = rep2 numTyLitName [mkIntExpr i]
repTyLit (HsStrTy s) = do { s' <- mkStringExprFS s
; rep2 strTyLitName [s']
}
-- represent a kind
--
repLKind :: LHsKind Name -> DsM (Core TH.Kind)
repLKind ki
= do { let (kis, ki') = splitHsFunType ki
; kis_rep <- mapM repLKind kis
; ki'_rep <- repNonArrowLKind ki'
; kcon <- repKArrow
; let f k1 k2 = repKApp kcon k1 >>= flip repKApp k2
; foldrM f ki'_rep kis_rep
}
repNonArrowLKind :: LHsKind Name -> DsM (Core TH.Kind)
repNonArrowLKind (L _ ki) = repNonArrowKind ki
repNonArrowKind :: HsKind Name -> DsM (Core TH.Kind)
repNonArrowKind (HsTyVar name)
| name == liftedTypeKindTyConName = repKStar
| name == constraintKindTyConName = repKConstraint
| isTvOcc (nameOccName name) = lookupOcc name >>= repKVar
| otherwise = lookupOcc name >>= repKCon
repNonArrowKind (HsAppTy f a) = do { f' <- repLKind f
; a' <- repLKind a
; repKApp f' a'
}
repNonArrowKind (HsListTy k) = do { k' <- repLKind k
; kcon <- repKList
; repKApp kcon k'
}
repNonArrowKind (HsTupleTy _ ks) = do { ks' <- mapM repLKind ks
; kcon <- repKTuple (length ks)
; repKApps kcon ks'
}
repNonArrowKind k = notHandled "Exotic form of kind" (ppr k)
-----------------------------------------------------------------------------
-- Splices
-----------------------------------------------------------------------------
repSplice :: HsSplice Name -> DsM (Core a)
-- See Note [How brackets and nested splices are handled] in TcSplice
-- We return a CoreExpr of any old type; the context should know
repSplice (HsSplice n _)
= do { mb_val <- dsLookupMetaEnv n
; case mb_val of
Just (Splice e) -> do { e' <- dsExpr e
; return (MkC e') }
_ -> pprPanic "HsSplice" (ppr n) }
-- Should not happen; statically checked
-----------------------------------------------------------------------------
-- Expressions
-----------------------------------------------------------------------------
repLEs :: [LHsExpr Name] -> DsM (Core [TH.ExpQ])
repLEs es = do { es' <- mapM repLE es ;
coreList expQTyConName es' }
-- FIXME: some of these panics should be converted into proper error messages
-- unless we can make sure that constructs, which are plainly not
-- supported in TH already lead to error messages at an earlier stage
repLE :: LHsExpr Name -> DsM (Core TH.ExpQ)
repLE (L loc e) = putSrcSpanDs loc (repE e)
repE :: HsExpr Name -> DsM (Core TH.ExpQ)
repE (HsVar x) =
do { mb_val <- dsLookupMetaEnv x
; case mb_val of
Nothing -> do { str <- globalVar x
; repVarOrCon x str }
Just (Bound y) -> repVarOrCon x (coreVar y)
Just (Splice e) -> do { e' <- dsExpr e
; return (MkC e') } }
repE e@(HsIPVar _) = notHandled "Implicit parameters" (ppr e)
-- Remember, we're desugaring renamer output here, so
-- HsOverlit can definitely occur
repE (HsOverLit l) = do { a <- repOverloadedLiteral l; repLit a }
repE (HsLit l) = do { a <- repLiteral l; repLit a }
repE (HsLam (MatchGroup [m] _)) = repLambda m
repE (HsLamCase _ (MatchGroup ms _))
= do { ms' <- mapM repMatchTup ms
; repLamCase (nonEmptyCoreList ms') }
repE (HsApp x y) = do {a <- repLE x; b <- repLE y; repApp a b}
repE (OpApp e1 op _ e2) =
do { arg1 <- repLE e1;
arg2 <- repLE e2;
the_op <- repLE op ;
repInfixApp arg1 the_op arg2 }
repE (NegApp x _) = do
a <- repLE x
negateVar <- lookupOcc negateName >>= repVar
negateVar `repApp` a
repE (HsPar x) = repLE x
repE (SectionL x y) = do { a <- repLE x; b <- repLE y; repSectionL a b }
repE (SectionR x y) = do { a <- repLE x; b <- repLE y; repSectionR a b }
repE (HsCase e (MatchGroup ms _))
= do { arg <- repLE e
; ms2 <- mapM repMatchTup ms
; repCaseE arg (nonEmptyCoreList ms2) }
repE (HsIf _ x y z) = do
a <- repLE x
b <- repLE y
c <- repLE z
repCond a b c
repE (HsMultiIf _ alts)
= do { (binds, alts') <- liftM unzip $ mapM repLGRHS alts
; expr' <- repMultiIf (nonEmptyCoreList alts')
; wrapGenSyms (concat binds) expr' }
repE (HsLet bs e) = do { (ss,ds) <- repBinds bs
; e2 <- addBinds ss (repLE e)
; z <- repLetE ds e2
; wrapGenSyms ss z }
-- FIXME: I haven't got the types here right yet
repE e@(HsDo ctxt sts _)
| case ctxt of { DoExpr -> True; GhciStmt -> True; _ -> False }
= do { (ss,zs) <- repLSts sts;
e' <- repDoE (nonEmptyCoreList zs);
wrapGenSyms ss e' }
| ListComp <- ctxt
= do { (ss,zs) <- repLSts sts;
e' <- repComp (nonEmptyCoreList zs);
wrapGenSyms ss e' }
| otherwise
= notHandled "mdo, monad comprehension and [: :]" (ppr e)
repE (ExplicitList _ es) = do { xs <- repLEs es; repListExp xs }
repE e@(ExplicitPArr _ _) = notHandled "Parallel arrays" (ppr e)
repE e@(ExplicitTuple es boxed)
| not (all tupArgPresent es) = notHandled "Tuple sections" (ppr e)
| isBoxed boxed = do { xs <- repLEs [e | Present e <- es]; repTup xs }
| otherwise = do { xs <- repLEs [e | Present e <- es]; repUnboxedTup xs }
repE (RecordCon c _ flds)
= do { x <- lookupLOcc c;
fs <- repFields flds;
repRecCon x fs }
repE (RecordUpd e flds _ _ _)
= do { x <- repLE e;
fs <- repFields flds;
repRecUpd x fs }
repE (ExprWithTySig e ty) = do { e1 <- repLE e; t1 <- repLTy ty; repSigExp e1 t1 }
repE (ArithSeq _ aseq) =
case aseq of
From e -> do { ds1 <- repLE e; repFrom ds1 }
FromThen e1 e2 -> do
ds1 <- repLE e1
ds2 <- repLE e2
repFromThen ds1 ds2
FromTo e1 e2 -> do
ds1 <- repLE e1
ds2 <- repLE e2
repFromTo ds1 ds2
FromThenTo e1 e2 e3 -> do
ds1 <- repLE e1
ds2 <- repLE e2
ds3 <- repLE e3
repFromThenTo ds1 ds2 ds3
repE (HsSpliceE splice) = repSplice splice
repE e@(PArrSeq {}) = notHandled "Parallel arrays" (ppr e)
repE e@(HsCoreAnn {}) = notHandled "Core annotations" (ppr e)
repE e@(HsSCC {}) = notHandled "Cost centres" (ppr e)
repE e@(HsTickPragma {}) = notHandled "Tick Pragma" (ppr e)
repE e@(HsBracketOut {}) = notHandled "TH brackets" (ppr e)
repE e = notHandled "Expression form" (ppr e)
-----------------------------------------------------------------------------
-- Building representations of auxillary structures like Match, Clause, Stmt,
repMatchTup :: LMatch Name -> DsM (Core TH.MatchQ)
repMatchTup (L _ (Match [p] _ (GRHSs guards wheres))) =
do { ss1 <- mkGenSyms (collectPatBinders p)
; addBinds ss1 $ do {
; p1 <- repLP p
; (ss2,ds) <- repBinds wheres
; addBinds ss2 $ do {
; gs <- repGuards guards
; match <- repMatch p1 gs ds
; wrapGenSyms (ss1++ss2) match }}}
repMatchTup _ = panic "repMatchTup: case alt with more than one arg"
repClauseTup :: LMatch Name -> DsM (Core TH.ClauseQ)
repClauseTup (L _ (Match ps _ (GRHSs guards wheres))) =
do { ss1 <- mkGenSyms (collectPatsBinders ps)
; addBinds ss1 $ do {
ps1 <- repLPs ps
; (ss2,ds) <- repBinds wheres
; addBinds ss2 $ do {
gs <- repGuards guards
; clause <- repClause ps1 gs ds
; wrapGenSyms (ss1++ss2) clause }}}
repGuards :: [LGRHS Name] -> DsM (Core TH.BodyQ)
repGuards [L _ (GRHS [] e)]
= do { a <- repLE e
; repNormal a }
repGuards alts
= do { (binds, alts') <- liftM unzip $ mapM repLGRHS alts
; body <- repGuarded (nonEmptyCoreList alts')
; wrapGenSyms (concat binds) body }
repLGRHS :: LGRHS Name -> DsM ([GenSymBind], (Core (TH.Q (TH.Guard, TH.Exp))))
repLGRHS (L _ (GRHS [L _ (ExprStmt guard _ _ _)] rhs))
= do { guarded <- repLNormalGE guard rhs
; return ([], guarded) }
repLGRHS (L _ (GRHS stmts rhs))
= do { (gs, stmts') <- repLSts stmts
; rhs' <- addBinds gs $ repLE rhs
; guarded <- repPatGE (nonEmptyCoreList stmts') rhs'
; return (gs, guarded) }
repFields :: HsRecordBinds Name -> DsM (Core [TH.Q TH.FieldExp])
repFields (HsRecFields { rec_flds = flds })
= do { fnames <- mapM lookupLOcc (map hsRecFieldId flds)
; es <- mapM repLE (map hsRecFieldArg flds)
; fs <- zipWithM repFieldExp fnames es
; coreList fieldExpQTyConName fs }
-----------------------------------------------------------------------------
-- Representing Stmt's is tricky, especially if bound variables
-- shadow each other. Consider: [| do { x <- f 1; x <- f x; g x } |]
-- First gensym new names for every variable in any of the patterns.
-- both static (x'1 and x'2), and dynamic ((gensym "x") and (gensym "y"))
-- if variables didn't shaddow, the static gensym wouldn't be necessary
-- and we could reuse the original names (x and x).
--
-- do { x'1 <- gensym "x"
-- ; x'2 <- gensym "x"
-- ; doE [ BindSt (pvar x'1) [| f 1 |]
-- , BindSt (pvar x'2) [| f x |]
-- , NoBindSt [| g x |]
-- ]
-- }
-- The strategy is to translate a whole list of do-bindings by building a
-- bigger environment, and a bigger set of meta bindings
-- (like: x'1 <- gensym "x" ) and then combining these with the translations
-- of the expressions within the Do
-----------------------------------------------------------------------------
-- The helper function repSts computes the translation of each sub expression
-- and a bunch of prefix bindings denoting the dynamic renaming.
repLSts :: [LStmt Name] -> DsM ([GenSymBind], [Core TH.StmtQ])
repLSts stmts = repSts (map unLoc stmts)
repSts :: [Stmt Name] -> DsM ([GenSymBind], [Core TH.StmtQ])
repSts (BindStmt p e _ _ : ss) =
do { e2 <- repLE e
; ss1 <- mkGenSyms (collectPatBinders p)
; addBinds ss1 $ do {
; p1 <- repLP p;
; (ss2,zs) <- repSts ss
; z <- repBindSt p1 e2
; return (ss1++ss2, z : zs) }}
repSts (LetStmt bs : ss) =
do { (ss1,ds) <- repBinds bs
; z <- repLetSt ds
; (ss2,zs) <- addBinds ss1 (repSts ss)
; return (ss1++ss2, z : zs) }
repSts (ExprStmt e _ _ _ : ss) =
do { e2 <- repLE e
; z <- repNoBindSt e2
; (ss2,zs) <- repSts ss
; return (ss2, z : zs) }
repSts [LastStmt e _]
= do { e2 <- repLE e
; z <- repNoBindSt e2
; return ([], [z]) }
repSts [] = return ([],[])
repSts other = notHandled "Exotic statement" (ppr other)
-----------------------------------------------------------
-- Bindings
-----------------------------------------------------------
repBinds :: HsLocalBinds Name -> DsM ([GenSymBind], Core [TH.DecQ])
repBinds EmptyLocalBinds
= do { core_list <- coreList decQTyConName []
; return ([], core_list) }
repBinds b@(HsIPBinds _) = notHandled "Implicit parameters" (ppr b)
repBinds (HsValBinds decs)
= do { let { bndrs = hsSigTvBinders decs ++ collectHsValBinders decs }
-- No need to worrry about detailed scopes within
-- the binding group, because we are talking Names
-- here, so we can safely treat it as a mutually
-- recursive group
-- For hsSigTvBinders see Note [Scoped type variables in bindings]
; ss <- mkGenSyms bndrs
; prs <- addBinds ss (rep_val_binds decs)
; core_list <- coreList decQTyConName
(de_loc (sort_by_loc prs))
; return (ss, core_list) }
rep_val_binds :: HsValBinds Name -> DsM [(SrcSpan, Core TH.DecQ)]
-- Assumes: all the binders of the binding are alrady in the meta-env
rep_val_binds (ValBindsOut binds sigs)
= do { core1 <- rep_binds' (unionManyBags (map snd binds))
; core2 <- rep_sigs' sigs
; return (core1 ++ core2) }
rep_val_binds (ValBindsIn _ _)
= panic "rep_val_binds: ValBindsIn"
rep_binds :: LHsBinds Name -> DsM [Core TH.DecQ]
rep_binds binds = do { binds_w_locs <- rep_binds' binds
; return (de_loc (sort_by_loc binds_w_locs)) }
rep_binds' :: LHsBinds Name -> DsM [(SrcSpan, Core TH.DecQ)]
rep_binds' binds = mapM rep_bind (bagToList binds)
rep_bind :: LHsBind Name -> DsM (SrcSpan, Core TH.DecQ)
-- Assumes: all the binders of the binding are alrady in the meta-env
-- Note GHC treats declarations of a variable (not a pattern)
-- e.g. x = g 5 as a Fun MonoBinds. This is indicated by a single match
-- with an empty list of patterns
rep_bind (L loc (FunBind { fun_id = fn,
fun_matches = MatchGroup [L _ (Match [] _ (GRHSs guards wheres))] _ }))
= do { (ss,wherecore) <- repBinds wheres
; guardcore <- addBinds ss (repGuards guards)
; fn' <- lookupLBinder fn
; p <- repPvar fn'
; ans <- repVal p guardcore wherecore
; ans' <- wrapGenSyms ss ans
; return (loc, ans') }
rep_bind (L loc (FunBind { fun_id = fn, fun_matches = MatchGroup ms _ }))
= do { ms1 <- mapM repClauseTup ms
; fn' <- lookupLBinder fn
; ans <- repFun fn' (nonEmptyCoreList ms1)
; return (loc, ans) }
rep_bind (L loc (PatBind { pat_lhs = pat, pat_rhs = GRHSs guards wheres }))
= do { patcore <- repLP pat
; (ss,wherecore) <- repBinds wheres
; guardcore <- addBinds ss (repGuards guards)
; ans <- repVal patcore guardcore wherecore
; ans' <- wrapGenSyms ss ans
; return (loc, ans') }
rep_bind (L _ (VarBind { var_id = v, var_rhs = e}))
= do { v' <- lookupBinder v
; e2 <- repLE e
; x <- repNormal e2
; patcore <- repPvar v'
; empty_decls <- coreList decQTyConName []
; ans <- repVal patcore x empty_decls
; return (srcLocSpan (getSrcLoc v), ans) }
rep_bind (L _ (AbsBinds {})) = panic "rep_bind: AbsBinds"
-----------------------------------------------------------------------------
-- Since everything in a Bind is mutually recursive we need rename all
-- all the variables simultaneously. For example:
-- [| AndMonoBinds (f x = x + g 2) (g x = f 1 + 2) |] would translate to
-- do { f'1 <- gensym "f"
-- ; g'2 <- gensym "g"
-- ; [ do { x'3 <- gensym "x"; fun f'1 [pvar x'3] [| x + g2 |]},
-- do { x'4 <- gensym "x"; fun g'2 [pvar x'4] [| f 1 + 2 |]}
-- ]}
-- This requires collecting the bindings (f'1 <- gensym "f"), and the
-- environment ( f |-> f'1 ) from each binding, and then unioning them
-- together. As we do this we collect GenSymBinds's which represent the renamed
-- variables bound by the Bindings. In order not to lose track of these
-- representations we build a shadow datatype MB with the same structure as
-- MonoBinds, but which has slots for the representations
-----------------------------------------------------------------------------
-- GHC allows a more general form of lambda abstraction than specified
-- by Haskell 98. In particular it allows guarded lambda's like :
-- (\ x | even x -> 0 | odd x -> 1) at the moment we can't represent this in
-- Haskell Template's Meta.Exp type so we punt if it isn't a simple thing like
-- (\ p1 .. pn -> exp) by causing an error.
repLambda :: LMatch Name -> DsM (Core TH.ExpQ)
repLambda (L _ (Match ps _ (GRHSs [L _ (GRHS [] e)] EmptyLocalBinds)))
= do { let bndrs = collectPatsBinders ps ;
; ss <- mkGenSyms bndrs
; lam <- addBinds ss (
do { xs <- repLPs ps; body <- repLE e; repLam xs body })
; wrapGenSyms ss lam }
repLambda (L _ m) = notHandled "Guarded labmdas" (pprMatch (LambdaExpr :: HsMatchContext Name) m)
-----------------------------------------------------------------------------
-- Patterns
-- repP deals with patterns. It assumes that we have already
-- walked over the pattern(s) once to collect the binders, and
-- have extended the environment. So every pattern-bound
-- variable should already appear in the environment.
-- Process a list of patterns
repLPs :: [LPat Name] -> DsM (Core [TH.PatQ])
repLPs ps = do { ps' <- mapM repLP ps ;
coreList patQTyConName ps' }
repLP :: LPat Name -> DsM (Core TH.PatQ)
repLP (L _ p) = repP p
repP :: Pat Name -> DsM (Core TH.PatQ)
repP (WildPat _) = repPwild
repP (LitPat l) = do { l2 <- repLiteral l; repPlit l2 }
repP (VarPat x) = do { x' <- lookupBinder x; repPvar x' }
repP (LazyPat p) = do { p1 <- repLP p; repPtilde p1 }
repP (BangPat p) = do { p1 <- repLP p; repPbang p1 }
repP (AsPat x p) = do { x' <- lookupLBinder x; p1 <- repLP p; repPaspat x' p1 }
repP (ParPat p) = repLP p
repP (ListPat ps _) = do { qs <- repLPs ps; repPlist qs }
repP (TuplePat ps boxed _)
| isBoxed boxed = do { qs <- repLPs ps; repPtup qs }
| otherwise = do { qs <- repLPs ps; repPunboxedTup qs }
repP (ConPatIn dc details)
= do { con_str <- lookupLOcc dc
; case details of
PrefixCon ps -> do { qs <- repLPs ps; repPcon con_str qs }
RecCon rec -> do { let flds = rec_flds rec
; vs <- sequence $ map lookupLOcc (map hsRecFieldId flds)
; ps <- sequence $ map repLP (map hsRecFieldArg flds)
; fps <- zipWithM (\x y -> rep2 fieldPatName [unC x,unC y]) vs ps
; fps' <- coreList fieldPatQTyConName fps
; repPrec con_str fps' }
InfixCon p1 p2 -> do { p1' <- repLP p1;
p2' <- repLP p2;
repPinfix p1' con_str p2' }
}
repP (NPat l Nothing _) = do { a <- repOverloadedLiteral l; repPlit a }
repP (ViewPat e p _) = do { e' <- repLE e; p' <- repLP p; repPview e' p' }
repP p@(NPat _ (Just _) _) = notHandled "Negative overloaded patterns" (ppr p)
repP p@(SigPatIn {}) = notHandled "Type signatures in patterns" (ppr p)
-- The problem is to do with scoped type variables.
-- To implement them, we have to implement the scoping rules
-- here in DsMeta, and I don't want to do that today!
-- do { p' <- repLP p; t' <- repLTy t; repPsig p' t' }
-- repPsig :: Core TH.PatQ -> Core TH.TypeQ -> DsM (Core TH.PatQ)
-- repPsig (MkC p) (MkC t) = rep2 sigPName [p, t]
repP other = notHandled "Exotic pattern" (ppr other)
----------------------------------------------------------
-- Declaration ordering helpers
sort_by_loc :: [(SrcSpan, a)] -> [(SrcSpan, a)]
sort_by_loc xs = sortBy comp xs
where comp x y = compare (fst x) (fst y)
de_loc :: [(a, b)] -> [b]
de_loc = map snd
----------------------------------------------------------
-- The meta-environment
-- A name/identifier association for fresh names of locally bound entities
type GenSymBind = (Name, Id) -- Gensym the string and bind it to the Id
-- I.e. (x, x_id) means
-- let x_id = gensym "x" in ...
-- Generate a fresh name for a locally bound entity
mkGenSyms :: [Name] -> DsM [GenSymBind]
-- We can use the existing name. For example:
-- [| \x_77 -> x_77 + x_77 |]
-- desugars to
-- do { x_77 <- genSym "x"; .... }
-- We use the same x_77 in the desugared program, but with the type Bndr
-- instead of Int
--
-- We do make it an Internal name, though (hence localiseName)
--
-- Nevertheless, it's monadic because we have to generate nameTy
mkGenSyms ns = do { var_ty <- lookupType nameTyConName
; return [(nm, mkLocalId (localiseName nm) var_ty) | nm <- ns] }
addBinds :: [GenSymBind] -> DsM a -> DsM a
-- Add a list of fresh names for locally bound entities to the
-- meta environment (which is part of the state carried around
-- by the desugarer monad)
addBinds bs m = dsExtendMetaEnv (mkNameEnv [(n,Bound id) | (n,id) <- bs]) m
dupBinder :: (Name, Name) -> DsM (Name, DsMetaVal)
dupBinder (new, old)
= do { mb_val <- dsLookupMetaEnv old
; case mb_val of
Just val -> return (new, val)
Nothing -> pprPanic "dupBinder" (ppr old) }
-- Look up a locally bound name
--
lookupLBinder :: Located Name -> DsM (Core TH.Name)
lookupLBinder (L _ n) = lookupBinder n
lookupBinder :: Name -> DsM (Core TH.Name)
lookupBinder = lookupOcc
-- Binders are brought into scope before the pattern or what-not is
-- desugared. Moreover, in instance declaration the binder of a method
-- will be the selector Id and hence a global; so we need the
-- globalVar case of lookupOcc
-- Look up a name that is either locally bound or a global name
--
-- * If it is a global name, generate the "original name" representation (ie,
-- the <module>:<name> form) for the associated entity
--
lookupLOcc :: Located Name -> DsM (Core TH.Name)
-- Lookup an occurrence; it can't be a splice.
-- Use the in-scope bindings if they exist
lookupLOcc (L _ n) = lookupOcc n
lookupOcc :: Name -> DsM (Core TH.Name)
lookupOcc n
= do { mb_val <- dsLookupMetaEnv n ;
case mb_val of
Nothing -> globalVar n
Just (Bound x) -> return (coreVar x)
Just (Splice _) -> pprPanic "repE:lookupOcc" (ppr n)
}
globalVar :: Name -> DsM (Core TH.Name)
-- Not bound by the meta-env
-- Could be top-level; or could be local
-- f x = $(g [| x |])
-- Here the x will be local
globalVar name
| isExternalName name
= do { MkC mod <- coreStringLit name_mod
; MkC pkg <- coreStringLit name_pkg
; MkC occ <- occNameLit name
; rep2 mk_varg [pkg,mod,occ] }
| otherwise
= do { MkC occ <- occNameLit name
; MkC uni <- coreIntLit (getKey (getUnique name))
; rep2 mkNameLName [occ,uni] }
where
mod = ASSERT( isExternalName name) nameModule name
name_mod = moduleNameString (moduleName mod)
name_pkg = packageIdString (modulePackageId mod)
name_occ = nameOccName name
mk_varg | OccName.isDataOcc name_occ = mkNameG_dName
| OccName.isVarOcc name_occ = mkNameG_vName
| OccName.isTcOcc name_occ = mkNameG_tcName
| otherwise = pprPanic "DsMeta.globalVar" (ppr name)
lookupType :: Name -- Name of type constructor (e.g. TH.ExpQ)
-> DsM Type -- The type
lookupType tc_name = do { tc <- dsLookupTyCon tc_name ;
return (mkTyConApp tc []) }
wrapGenSyms :: [GenSymBind]
-> Core (TH.Q a) -> DsM (Core (TH.Q a))
-- wrapGenSyms [(nm1,id1), (nm2,id2)] y
-- --> bindQ (gensym nm1) (\ id1 ->
-- bindQ (gensym nm2 (\ id2 ->
-- y))
wrapGenSyms binds body@(MkC b)
= do { var_ty <- lookupType nameTyConName
; go var_ty binds }
where
[elt_ty] = tcTyConAppArgs (exprType b)
-- b :: Q a, so we can get the type 'a' by looking at the
-- argument type. NB: this relies on Q being a data/newtype,
-- not a type synonym
go _ [] = return body
go var_ty ((name,id) : binds)
= do { MkC body' <- go var_ty binds
; lit_str <- occNameLit name
; gensym_app <- repGensym lit_str
; repBindQ var_ty elt_ty
gensym_app (MkC (Lam id body')) }
occNameLit :: Name -> DsM (Core String)
occNameLit n = coreStringLit (occNameString (nameOccName n))
-- %*********************************************************************
-- %* *
-- Constructing code
-- %* *
-- %*********************************************************************
-----------------------------------------------------------------------------
-- PHANTOM TYPES for consistency. In order to make sure we do this correct
-- we invent a new datatype which uses phantom types.
newtype Core a = MkC CoreExpr
unC :: Core a -> CoreExpr
unC (MkC x) = x
rep2 :: Name -> [ CoreExpr ] -> DsM (Core a)
rep2 n xs = do { id <- dsLookupGlobalId n
; return (MkC (foldl App (Var id) xs)) }
dataCon' :: Name -> [CoreExpr] -> DsM (Core a)
dataCon' n args = do { id <- dsLookupDataCon n
; return $ MkC $ mkConApp id args }
dataCon :: Name -> DsM (Core a)
dataCon n = dataCon' n []
-- Then we make "repConstructors" which use the phantom types for each of the
-- smart constructors of the Meta.Meta datatypes.
-- %*********************************************************************
-- %* *
-- The 'smart constructors'
-- %* *
-- %*********************************************************************
--------------- Patterns -----------------
repPlit :: Core TH.Lit -> DsM (Core TH.PatQ)
repPlit (MkC l) = rep2 litPName [l]
repPvar :: Core TH.Name -> DsM (Core TH.PatQ)
repPvar (MkC s) = rep2 varPName [s]
repPtup :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
repPtup (MkC ps) = rep2 tupPName [ps]
repPunboxedTup :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
repPunboxedTup (MkC ps) = rep2 unboxedTupPName [ps]
repPcon :: Core TH.Name -> Core [TH.PatQ] -> DsM (Core TH.PatQ)
repPcon (MkC s) (MkC ps) = rep2 conPName [s, ps]
repPrec :: Core TH.Name -> Core [(TH.Name,TH.PatQ)] -> DsM (Core TH.PatQ)
repPrec (MkC c) (MkC rps) = rep2 recPName [c,rps]
repPinfix :: Core TH.PatQ -> Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ)
repPinfix (MkC p1) (MkC n) (MkC p2) = rep2 infixPName [p1, n, p2]
repPtilde :: Core TH.PatQ -> DsM (Core TH.PatQ)
repPtilde (MkC p) = rep2 tildePName [p]
repPbang :: Core TH.PatQ -> DsM (Core TH.PatQ)
repPbang (MkC p) = rep2 bangPName [p]
repPaspat :: Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ)
repPaspat (MkC s) (MkC p) = rep2 asPName [s, p]
repPwild :: DsM (Core TH.PatQ)
repPwild = rep2 wildPName []
repPlist :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
repPlist (MkC ps) = rep2 listPName [ps]
repPview :: Core TH.ExpQ -> Core TH.PatQ -> DsM (Core TH.PatQ)
repPview (MkC e) (MkC p) = rep2 viewPName [e,p]
--------------- Expressions -----------------
repVarOrCon :: Name -> Core TH.Name -> DsM (Core TH.ExpQ)
repVarOrCon vc str | isDataOcc (nameOccName vc) = repCon str
| otherwise = repVar str
repVar :: Core TH.Name -> DsM (Core TH.ExpQ)
repVar (MkC s) = rep2 varEName [s]
repCon :: Core TH.Name -> DsM (Core TH.ExpQ)
repCon (MkC s) = rep2 conEName [s]
repLit :: Core TH.Lit -> DsM (Core TH.ExpQ)
repLit (MkC c) = rep2 litEName [c]
repApp :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repApp (MkC x) (MkC y) = rep2 appEName [x,y]
repLam :: Core [TH.PatQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repLam (MkC ps) (MkC e) = rep2 lamEName [ps, e]
repLamCase :: Core [TH.MatchQ] -> DsM (Core TH.ExpQ)
repLamCase (MkC ms) = rep2 lamCaseEName [ms]
repTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
repTup (MkC es) = rep2 tupEName [es]
repUnboxedTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
repUnboxedTup (MkC es) = rep2 unboxedTupEName [es]
repCond :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repCond (MkC x) (MkC y) (MkC z) = rep2 condEName [x,y,z]
repMultiIf :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.ExpQ)
repMultiIf (MkC alts) = rep2 multiIfEName [alts]
repLetE :: Core [TH.DecQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repLetE (MkC ds) (MkC e) = rep2 letEName [ds, e]
repCaseE :: Core TH.ExpQ -> Core [TH.MatchQ] -> DsM( Core TH.ExpQ)
repCaseE (MkC e) (MkC ms) = rep2 caseEName [e, ms]
repDoE :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
repDoE (MkC ss) = rep2 doEName [ss]
repComp :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
repComp (MkC ss) = rep2 compEName [ss]
repListExp :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
repListExp (MkC es) = rep2 listEName [es]
repSigExp :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ)
repSigExp (MkC e) (MkC t) = rep2 sigEName [e,t]
repRecCon :: Core TH.Name -> Core [TH.Q TH.FieldExp]-> DsM (Core TH.ExpQ)
repRecCon (MkC c) (MkC fs) = rep2 recConEName [c,fs]
repRecUpd :: Core TH.ExpQ -> Core [TH.Q TH.FieldExp] -> DsM (Core TH.ExpQ)
repRecUpd (MkC e) (MkC fs) = rep2 recUpdEName [e,fs]
repFieldExp :: Core TH.Name -> Core TH.ExpQ -> DsM (Core (TH.Q TH.FieldExp))
repFieldExp (MkC n) (MkC x) = rep2 fieldExpName [n,x]
repInfixApp :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repInfixApp (MkC x) (MkC y) (MkC z) = rep2 infixAppName [x,y,z]
repSectionL :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repSectionL (MkC x) (MkC y) = rep2 sectionLName [x,y]
repSectionR :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repSectionR (MkC x) (MkC y) = rep2 sectionRName [x,y]
------------ Right hand sides (guarded expressions) ----
repGuarded :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.BodyQ)
repGuarded (MkC pairs) = rep2 guardedBName [pairs]
repNormal :: Core TH.ExpQ -> DsM (Core TH.BodyQ)
repNormal (MkC e) = rep2 normalBName [e]
------------ Guards ----
repLNormalGE :: LHsExpr Name -> LHsExpr Name -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
repLNormalGE g e = do g' <- repLE g
e' <- repLE e
repNormalGE g' e'
repNormalGE :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
repNormalGE (MkC g) (MkC e) = rep2 normalGEName [g, e]
repPatGE :: Core [TH.StmtQ] -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
repPatGE (MkC ss) (MkC e) = rep2 patGEName [ss, e]
------------- Stmts -------------------
repBindSt :: Core TH.PatQ -> Core TH.ExpQ -> DsM (Core TH.StmtQ)
repBindSt (MkC p) (MkC e) = rep2 bindSName [p,e]
repLetSt :: Core [TH.DecQ] -> DsM (Core TH.StmtQ)
repLetSt (MkC ds) = rep2 letSName [ds]
repNoBindSt :: Core TH.ExpQ -> DsM (Core TH.StmtQ)
repNoBindSt (MkC e) = rep2 noBindSName [e]
-------------- Range (Arithmetic sequences) -----------
repFrom :: Core TH.ExpQ -> DsM (Core TH.ExpQ)
repFrom (MkC x) = rep2 fromEName [x]
repFromThen :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repFromThen (MkC x) (MkC y) = rep2 fromThenEName [x,y]
repFromTo :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repFromTo (MkC x) (MkC y) = rep2 fromToEName [x,y]
repFromThenTo :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repFromThenTo (MkC x) (MkC y) (MkC z) = rep2 fromThenToEName [x,y,z]
------------ Match and Clause Tuples -----------
repMatch :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.MatchQ)
repMatch (MkC p) (MkC bod) (MkC ds) = rep2 matchName [p, bod, ds]
repClause :: Core [TH.PatQ] -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.ClauseQ)
repClause (MkC ps) (MkC bod) (MkC ds) = rep2 clauseName [ps, bod, ds]
-------------- Dec -----------------------------
repVal :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
repVal (MkC p) (MkC b) (MkC ds) = rep2 valDName [p, b, ds]
repFun :: Core TH.Name -> Core [TH.ClauseQ] -> DsM (Core TH.DecQ)
repFun (MkC nm) (MkC b) = rep2 funDName [nm, b]
repData :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr]
-> Maybe (Core [TH.TypeQ])
-> Core [TH.ConQ] -> Core [TH.Name] -> DsM (Core TH.DecQ)
repData (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC cons) (MkC derivs)
= rep2 dataDName [cxt, nm, tvs, cons, derivs]
repData (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC cons) (MkC derivs)
= rep2 dataInstDName [cxt, nm, tys, cons, derivs]
repNewtype :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr]
-> Maybe (Core [TH.TypeQ])
-> Core TH.ConQ -> Core [TH.Name] -> DsM (Core TH.DecQ)
repNewtype (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC con) (MkC derivs)
= rep2 newtypeDName [cxt, nm, tvs, con, derivs]
repNewtype (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC con) (MkC derivs)
= rep2 newtypeInstDName [cxt, nm, tys, con, derivs]
repTySyn :: Core TH.Name -> Core [TH.TyVarBndr]
-> Maybe (Core [TH.TypeQ])
-> Core TH.TypeQ -> DsM (Core TH.DecQ)
repTySyn (MkC nm) (MkC tvs) Nothing (MkC rhs)
= rep2 tySynDName [nm, tvs, rhs]
repTySyn (MkC nm) (MkC _) (Just (MkC tys)) (MkC rhs)
= rep2 tySynInstDName [nm, tys, rhs]
repInst :: Core TH.CxtQ -> Core TH.TypeQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
repInst (MkC cxt) (MkC ty) (MkC ds) = rep2 instanceDName [cxt, ty, ds]
repClass :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr]
-> Core [TH.FunDep] -> Core [TH.DecQ]
-> DsM (Core TH.DecQ)
repClass (MkC cxt) (MkC cls) (MkC tvs) (MkC fds) (MkC ds)
= rep2 classDName [cxt, cls, tvs, fds, ds]
repPragInl :: Core TH.Name -> Core TH.Inline -> Core TH.RuleMatch
-> Core TH.Phases -> DsM (Core TH.DecQ)
repPragInl (MkC nm) (MkC inline) (MkC rm) (MkC phases)
= rep2 pragInlDName [nm, inline, rm, phases]
repPragSpec :: Core TH.Name -> Core TH.TypeQ -> Core TH.Phases
-> DsM (Core TH.DecQ)
repPragSpec (MkC nm) (MkC ty) (MkC phases)
= rep2 pragSpecDName [nm, ty, phases]
repPragSpecInl :: Core TH.Name -> Core TH.TypeQ -> Core TH.Inline
-> Core TH.Phases -> DsM (Core TH.DecQ)
repPragSpecInl (MkC nm) (MkC ty) (MkC inline) (MkC phases)
= rep2 pragSpecInlDName [nm, ty, inline, phases]
repPragSpecInst :: Core TH.TypeQ -> DsM (Core TH.DecQ)
repPragSpecInst (MkC ty) = rep2 pragSpecInstDName [ty]
repPragRule :: Core String -> Core [TH.RuleBndrQ] -> Core TH.ExpQ
-> Core TH.ExpQ -> Core TH.Phases -> DsM (Core TH.DecQ)
repPragRule (MkC nm) (MkC bndrs) (MkC lhs) (MkC rhs) (MkC phases)
= rep2 pragRuleDName [nm, bndrs, lhs, rhs, phases]
repFamilyNoKind :: Core TH.FamFlavour -> Core TH.Name -> Core [TH.TyVarBndr]
-> DsM (Core TH.DecQ)
repFamilyNoKind (MkC flav) (MkC nm) (MkC tvs)
= rep2 familyNoKindDName [flav, nm, tvs]
repFamilyKind :: Core TH.FamFlavour -> Core TH.Name -> Core [TH.TyVarBndr]
-> Core TH.Kind
-> DsM (Core TH.DecQ)
repFamilyKind (MkC flav) (MkC nm) (MkC tvs) (MkC ki)
= rep2 familyKindDName [flav, nm, tvs, ki]
repFunDep :: Core [TH.Name] -> Core [TH.Name] -> DsM (Core TH.FunDep)
repFunDep (MkC xs) (MkC ys) = rep2 funDepName [xs, ys]
repProto :: Core TH.Name -> Core TH.TypeQ -> DsM (Core TH.DecQ)
repProto (MkC s) (MkC ty) = rep2 sigDName [s, ty]
repCtxt :: Core [TH.PredQ] -> DsM (Core TH.CxtQ)
repCtxt (MkC tys) = rep2 cxtName [tys]
repClassP :: Core TH.Name -> Core [TH.TypeQ] -> DsM (Core TH.PredQ)
repClassP (MkC cla) (MkC tys) = rep2 classPName [cla, tys]
repEqualP :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.PredQ)
repEqualP (MkC ty1) (MkC ty2) = rep2 equalPName [ty1, ty2]
repConstr :: Core TH.Name -> HsConDeclDetails Name
-> DsM (Core TH.ConQ)
repConstr con (PrefixCon ps)
= do arg_tys <- mapM repBangTy ps
arg_tys1 <- coreList strictTypeQTyConName arg_tys
rep2 normalCName [unC con, unC arg_tys1]
repConstr con (RecCon ips)
= do arg_vs <- mapM lookupLOcc (map cd_fld_name ips)
arg_tys <- mapM repBangTy (map cd_fld_type ips)
arg_vtys <- zipWithM (\x y -> rep2 varStrictTypeName [unC x, unC y])
arg_vs arg_tys
arg_vtys' <- coreList varStrictTypeQTyConName arg_vtys
rep2 recCName [unC con, unC arg_vtys']
repConstr con (InfixCon st1 st2)
= do arg1 <- repBangTy st1
arg2 <- repBangTy st2
rep2 infixCName [unC arg1, unC con, unC arg2]
------------ Types -------------------
repTForall :: Core [TH.TyVarBndr] -> Core TH.CxtQ -> Core TH.TypeQ
-> DsM (Core TH.TypeQ)
repTForall (MkC tvars) (MkC ctxt) (MkC ty)
= rep2 forallTName [tvars, ctxt, ty]
repTvar :: Core TH.Name -> DsM (Core TH.TypeQ)
repTvar (MkC s) = rep2 varTName [s]
repTapp :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ)
repTapp (MkC t1) (MkC t2) = rep2 appTName [t1, t2]
repTapps :: Core TH.TypeQ -> [Core TH.TypeQ] -> DsM (Core TH.TypeQ)
repTapps f [] = return f
repTapps f (t:ts) = do { f1 <- repTapp f t; repTapps f1 ts }
repTSig :: Core TH.TypeQ -> Core TH.Kind -> DsM (Core TH.TypeQ)
repTSig (MkC ty) (MkC ki) = rep2 sigTName [ty, ki]
repTPromotedList :: [Core TH.TypeQ] -> DsM (Core TH.TypeQ)
repTPromotedList [] = repPromotedNilTyCon
repTPromotedList (t:ts) = do { tcon <- repPromotedConsTyCon
; f <- repTapp tcon t
; t' <- repTPromotedList ts
; repTapp f t'
}
repTLit :: Core TH.TyLitQ -> DsM (Core TH.TypeQ)
repTLit (MkC lit) = rep2 litTName [lit]
--------- Type constructors --------------
repNamedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ)
repNamedTyCon (MkC s) = rep2 conTName [s]
repTupleTyCon :: Int -> DsM (Core TH.TypeQ)
-- Note: not Core Int; it's easier to be direct here
repTupleTyCon i = rep2 tupleTName [mkIntExprInt i]
repUnboxedTupleTyCon :: Int -> DsM (Core TH.TypeQ)
-- Note: not Core Int; it's easier to be direct here
repUnboxedTupleTyCon i = rep2 unboxedTupleTName [mkIntExprInt i]
repArrowTyCon :: DsM (Core TH.TypeQ)
repArrowTyCon = rep2 arrowTName []
repListTyCon :: DsM (Core TH.TypeQ)
repListTyCon = rep2 listTName []
repPromotedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ)
repPromotedTyCon (MkC s) = rep2 promotedTName [s]
repPromotedTupleTyCon :: Int -> DsM (Core TH.TypeQ)
repPromotedTupleTyCon i = rep2 promotedTupleTName [mkIntExprInt i]
repPromotedNilTyCon :: DsM (Core TH.TypeQ)
repPromotedNilTyCon = rep2 promotedNilTName []
repPromotedConsTyCon :: DsM (Core TH.TypeQ)
repPromotedConsTyCon = rep2 promotedConsTName []
------------ Kinds -------------------
repPlainTV :: Core TH.Name -> DsM (Core TH.TyVarBndr)
repPlainTV (MkC nm) = rep2 plainTVName [nm]
repKindedTV :: Core TH.Name -> Core TH.Kind -> DsM (Core TH.TyVarBndr)
repKindedTV (MkC nm) (MkC ki) = rep2 kindedTVName [nm, ki]
repKVar :: Core TH.Name -> DsM (Core TH.Kind)
repKVar (MkC s) = rep2 varKName [s]
repKCon :: Core TH.Name -> DsM (Core TH.Kind)
repKCon (MkC s) = rep2 conKName [s]
repKTuple :: Int -> DsM (Core TH.Kind)
repKTuple i = rep2 tupleKName [mkIntExprInt i]
repKArrow :: DsM (Core TH.Kind)
repKArrow = rep2 arrowKName []
repKList :: DsM (Core TH.Kind)
repKList = rep2 listKName []
repKApp :: Core TH.Kind -> Core TH.Kind -> DsM (Core TH.Kind)
repKApp (MkC k1) (MkC k2) = rep2 appKName [k1, k2]
repKApps :: Core TH.Kind -> [Core TH.Kind] -> DsM (Core TH.Kind)
repKApps f [] = return f
repKApps f (k:ks) = do { f' <- repKApp f k; repKApps f' ks }
repKStar :: DsM (Core TH.Kind)
repKStar = rep2 starKName []
repKConstraint :: DsM (Core TH.Kind)
repKConstraint = rep2 constraintKName []
----------------------------------------------------------
-- Literals
repLiteral :: HsLit -> DsM (Core TH.Lit)
repLiteral lit
= do lit' <- case lit of
HsIntPrim i -> mk_integer i
HsWordPrim w -> mk_integer w
HsInt i -> mk_integer i
HsFloatPrim r -> mk_rational r
HsDoublePrim r -> mk_rational r
_ -> return lit
lit_expr <- dsLit lit'
case mb_lit_name of
Just lit_name -> rep2 lit_name [lit_expr]
Nothing -> notHandled "Exotic literal" (ppr lit)
where
mb_lit_name = case lit of
HsInteger _ _ -> Just integerLName
HsInt _ -> Just integerLName
HsIntPrim _ -> Just intPrimLName
HsWordPrim _ -> Just wordPrimLName
HsFloatPrim _ -> Just floatPrimLName
HsDoublePrim _ -> Just doublePrimLName
HsChar _ -> Just charLName
HsString _ -> Just stringLName
HsRat _ _ -> Just rationalLName
_ -> Nothing
mk_integer :: Integer -> DsM HsLit
mk_integer i = do integer_ty <- lookupType integerTyConName
return $ HsInteger i integer_ty
mk_rational :: FractionalLit -> DsM HsLit
mk_rational r = do rat_ty <- lookupType rationalTyConName
return $ HsRat r rat_ty
mk_string :: FastString -> DsM HsLit
mk_string s = return $ HsString s
repOverloadedLiteral :: HsOverLit Name -> DsM (Core TH.Lit)
repOverloadedLiteral (OverLit { ol_val = val})
= do { lit <- mk_lit val; repLiteral lit }
-- The type Rational will be in the environment, becuase
-- the smart constructor 'TH.Syntax.rationalL' uses it in its type,
-- and rationalL is sucked in when any TH stuff is used
mk_lit :: OverLitVal -> DsM HsLit
mk_lit (HsIntegral i) = mk_integer i
mk_lit (HsFractional f) = mk_rational f
mk_lit (HsIsString s) = mk_string s
--------------- Miscellaneous -------------------
repGensym :: Core String -> DsM (Core (TH.Q TH.Name))
repGensym (MkC lit_str) = rep2 newNameName [lit_str]
repBindQ :: Type -> Type -- a and b
-> Core (TH.Q a) -> Core (a -> TH.Q b) -> DsM (Core (TH.Q b))
repBindQ ty_a ty_b (MkC x) (MkC y)
= rep2 bindQName [Type ty_a, Type ty_b, x, y]
repSequenceQ :: Type -> Core [TH.Q a] -> DsM (Core (TH.Q [a]))
repSequenceQ ty_a (MkC list)
= rep2 sequenceQName [Type ty_a, list]
------------ Lists and Tuples -------------------
-- turn a list of patterns into a single pattern matching a list
coreList :: Name -- Of the TyCon of the element type
-> [Core a] -> DsM (Core [a])
coreList tc_name es
= do { elt_ty <- lookupType tc_name; return (coreList' elt_ty es) }
coreList' :: Type -- The element type
-> [Core a] -> Core [a]
coreList' elt_ty es = MkC (mkListExpr elt_ty (map unC es ))
nonEmptyCoreList :: [Core a] -> Core [a]
-- The list must be non-empty so we can get the element type
-- Otherwise use coreList
nonEmptyCoreList [] = panic "coreList: empty argument"
nonEmptyCoreList xs@(MkC x:_) = MkC (mkListExpr (exprType x) (map unC xs))
coreStringLit :: String -> DsM (Core String)
coreStringLit s = do { z <- mkStringExpr s; return(MkC z) }
------------ Literals & Variables -------------------
coreIntLit :: Int -> DsM (Core Int)
coreIntLit i = return (MkC (mkIntExprInt i))
coreVar :: Id -> Core TH.Name -- The Id has type Name
coreVar id = MkC (Var id)
----------------- Failure -----------------------
notHandled :: String -> SDoc -> DsM a
notHandled what doc = failWithDs msg
where
msg = hang (text what <+> ptext (sLit "not (yet) handled by Template Haskell"))
2 doc
-- %************************************************************************
-- %* *
-- The known-key names for Template Haskell
-- %* *
-- %************************************************************************
-- To add a name, do three things
--
-- 1) Allocate a key
-- 2) Make a "Name"
-- 3) Add the name to knownKeyNames
templateHaskellNames :: [Name]
-- The names that are implicitly mentioned by ``bracket''
-- Should stay in sync with the import list of DsMeta
templateHaskellNames = [
returnQName, bindQName, sequenceQName, newNameName, liftName,
mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName,
liftStringName,
-- Lit
charLName, stringLName, integerLName, intPrimLName, wordPrimLName,
floatPrimLName, doublePrimLName, rationalLName,
-- Pat
litPName, varPName, tupPName, unboxedTupPName,
conPName, tildePName, bangPName, infixPName,
asPName, wildPName, recPName, listPName, sigPName, viewPName,
-- FieldPat
fieldPatName,
-- Match
matchName,
-- Clause
clauseName,
-- Exp
varEName, conEName, litEName, appEName, infixEName,
infixAppName, sectionLName, sectionRName, lamEName, lamCaseEName,
tupEName, unboxedTupEName,
condEName, multiIfEName, letEName, caseEName, doEName, compEName,
fromEName, fromThenEName, fromToEName, fromThenToEName,
listEName, sigEName, recConEName, recUpdEName,
-- FieldExp
fieldExpName,
-- Body
guardedBName, normalBName,
-- Guard
normalGEName, patGEName,
-- Stmt
bindSName, letSName, noBindSName, parSName,
-- Dec
funDName, valDName, dataDName, newtypeDName, tySynDName,
classDName, instanceDName, sigDName, forImpDName,
pragInlDName, pragSpecDName, pragSpecInlDName, pragSpecInstDName,
pragRuleDName,
familyNoKindDName, familyKindDName, dataInstDName, newtypeInstDName,
tySynInstDName, infixLDName, infixRDName, infixNDName,
-- Cxt
cxtName,
-- Pred
classPName, equalPName,
-- Strict
isStrictName, notStrictName, unpackedName,
-- Con
normalCName, recCName, infixCName, forallCName,
-- StrictType
strictTypeName,
-- VarStrictType
varStrictTypeName,
-- Type
forallTName, varTName, conTName, appTName,
tupleTName, unboxedTupleTName, arrowTName, listTName, sigTName, litTName,
promotedTName, promotedTupleTName, promotedNilTName, promotedConsTName,
-- TyLit
numTyLitName, strTyLitName,
-- TyVarBndr
plainTVName, kindedTVName,
-- Kind
varKName, conKName, tupleKName, arrowKName, listKName, appKName,
starKName, constraintKName,
-- Callconv
cCallName, stdCallName,
-- Safety
unsafeName,
safeName,
interruptibleName,
-- Inline
noInlineDataConName, inlineDataConName, inlinableDataConName,
-- RuleMatch
conLikeDataConName, funLikeDataConName,
-- Phases
allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName,
-- RuleBndr
ruleVarName, typedRuleVarName,
-- FunDep
funDepName,
-- FamFlavour
typeFamName, dataFamName,
-- And the tycons
qTyConName, nameTyConName, patTyConName, fieldPatTyConName, matchQTyConName,
clauseQTyConName, expQTyConName, fieldExpTyConName, predTyConName,
stmtQTyConName, decQTyConName, conQTyConName, strictTypeQTyConName,
varStrictTypeQTyConName, typeQTyConName, expTyConName, decTyConName,
typeTyConName, tyVarBndrTyConName, matchTyConName, clauseTyConName,
patQTyConName, fieldPatQTyConName, fieldExpQTyConName, funDepTyConName,
predQTyConName, decsQTyConName, ruleBndrQTyConName,
-- Quasiquoting
quoteDecName, quoteTypeName, quoteExpName, quotePatName]
thSyn, thLib, qqLib :: Module
thSyn = mkTHModule (fsLit "Language.Haskell.TH.Syntax")
thLib = mkTHModule (fsLit "Language.Haskell.TH.Lib")
qqLib = mkTHModule (fsLit "Language.Haskell.TH.Quote")
mkTHModule :: FastString -> Module
mkTHModule m = mkModule thPackageId (mkModuleNameFS m)
libFun, libTc, thFun, thTc, thCon, qqFun :: FastString -> Unique -> Name
libFun = mk_known_key_name OccName.varName thLib
libTc = mk_known_key_name OccName.tcName thLib
thFun = mk_known_key_name OccName.varName thSyn
thTc = mk_known_key_name OccName.tcName thSyn
thCon = mk_known_key_name OccName.dataName thSyn
qqFun = mk_known_key_name OccName.varName qqLib
-------------------- TH.Syntax -----------------------
qTyConName, nameTyConName, fieldExpTyConName, patTyConName,
fieldPatTyConName, expTyConName, decTyConName, typeTyConName,
tyVarBndrTyConName, matchTyConName, clauseTyConName, funDepTyConName,
predTyConName :: Name
qTyConName = thTc (fsLit "Q") qTyConKey
nameTyConName = thTc (fsLit "Name") nameTyConKey
fieldExpTyConName = thTc (fsLit "FieldExp") fieldExpTyConKey
patTyConName = thTc (fsLit "Pat") patTyConKey
fieldPatTyConName = thTc (fsLit "FieldPat") fieldPatTyConKey
expTyConName = thTc (fsLit "Exp") expTyConKey
decTyConName = thTc (fsLit "Dec") decTyConKey
typeTyConName = thTc (fsLit "Type") typeTyConKey
tyVarBndrTyConName= thTc (fsLit "TyVarBndr") tyVarBndrTyConKey
matchTyConName = thTc (fsLit "Match") matchTyConKey
clauseTyConName = thTc (fsLit "Clause") clauseTyConKey
funDepTyConName = thTc (fsLit "FunDep") funDepTyConKey
predTyConName = thTc (fsLit "Pred") predTyConKey
returnQName, bindQName, sequenceQName, newNameName, liftName,
mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName,
mkNameLName, liftStringName :: Name
returnQName = thFun (fsLit "returnQ") returnQIdKey
bindQName = thFun (fsLit "bindQ") bindQIdKey
sequenceQName = thFun (fsLit "sequenceQ") sequenceQIdKey
newNameName = thFun (fsLit "newName") newNameIdKey
liftName = thFun (fsLit "lift") liftIdKey
liftStringName = thFun (fsLit "liftString") liftStringIdKey
mkNameName = thFun (fsLit "mkName") mkNameIdKey
mkNameG_vName = thFun (fsLit "mkNameG_v") mkNameG_vIdKey
mkNameG_dName = thFun (fsLit "mkNameG_d") mkNameG_dIdKey
mkNameG_tcName = thFun (fsLit "mkNameG_tc") mkNameG_tcIdKey
mkNameLName = thFun (fsLit "mkNameL") mkNameLIdKey
-------------------- TH.Lib -----------------------
-- data Lit = ...
charLName, stringLName, integerLName, intPrimLName, wordPrimLName,
floatPrimLName, doublePrimLName, rationalLName :: Name
charLName = libFun (fsLit "charL") charLIdKey
stringLName = libFun (fsLit "stringL") stringLIdKey
integerLName = libFun (fsLit "integerL") integerLIdKey
intPrimLName = libFun (fsLit "intPrimL") intPrimLIdKey
wordPrimLName = libFun (fsLit "wordPrimL") wordPrimLIdKey
floatPrimLName = libFun (fsLit "floatPrimL") floatPrimLIdKey
doublePrimLName = libFun (fsLit "doublePrimL") doublePrimLIdKey
rationalLName = libFun (fsLit "rationalL") rationalLIdKey
-- data Pat = ...
litPName, varPName, tupPName, unboxedTupPName, conPName, infixPName, tildePName, bangPName,
asPName, wildPName, recPName, listPName, sigPName, viewPName :: Name
litPName = libFun (fsLit "litP") litPIdKey
varPName = libFun (fsLit "varP") varPIdKey
tupPName = libFun (fsLit "tupP") tupPIdKey
unboxedTupPName = libFun (fsLit "unboxedTupP") unboxedTupPIdKey
conPName = libFun (fsLit "conP") conPIdKey
infixPName = libFun (fsLit "infixP") infixPIdKey
tildePName = libFun (fsLit "tildeP") tildePIdKey
bangPName = libFun (fsLit "bangP") bangPIdKey
asPName = libFun (fsLit "asP") asPIdKey
wildPName = libFun (fsLit "wildP") wildPIdKey
recPName = libFun (fsLit "recP") recPIdKey
listPName = libFun (fsLit "listP") listPIdKey
sigPName = libFun (fsLit "sigP") sigPIdKey
viewPName = libFun (fsLit "viewP") viewPIdKey
-- type FieldPat = ...
fieldPatName :: Name
fieldPatName = libFun (fsLit "fieldPat") fieldPatIdKey
-- data Match = ...
matchName :: Name
matchName = libFun (fsLit "match") matchIdKey
-- data Clause = ...
clauseName :: Name
clauseName = libFun (fsLit "clause") clauseIdKey
-- data Exp = ...
varEName, conEName, litEName, appEName, infixEName, infixAppName,
sectionLName, sectionRName, lamEName, lamCaseEName, tupEName,
unboxedTupEName, condEName, multiIfEName, letEName, caseEName,
doEName, compEName :: Name
varEName = libFun (fsLit "varE") varEIdKey
conEName = libFun (fsLit "conE") conEIdKey
litEName = libFun (fsLit "litE") litEIdKey
appEName = libFun (fsLit "appE") appEIdKey
infixEName = libFun (fsLit "infixE") infixEIdKey
infixAppName = libFun (fsLit "infixApp") infixAppIdKey
sectionLName = libFun (fsLit "sectionL") sectionLIdKey
sectionRName = libFun (fsLit "sectionR") sectionRIdKey
lamEName = libFun (fsLit "lamE") lamEIdKey
lamCaseEName = libFun (fsLit "lamCaseE") lamCaseEIdKey
tupEName = libFun (fsLit "tupE") tupEIdKey
unboxedTupEName = libFun (fsLit "unboxedTupE") unboxedTupEIdKey
condEName = libFun (fsLit "condE") condEIdKey
multiIfEName = libFun (fsLit "multiIfE") multiIfEIdKey
letEName = libFun (fsLit "letE") letEIdKey
caseEName = libFun (fsLit "caseE") caseEIdKey
doEName = libFun (fsLit "doE") doEIdKey
compEName = libFun (fsLit "compE") compEIdKey
-- ArithSeq skips a level
fromEName, fromThenEName, fromToEName, fromThenToEName :: Name
fromEName = libFun (fsLit "fromE") fromEIdKey
fromThenEName = libFun (fsLit "fromThenE") fromThenEIdKey
fromToEName = libFun (fsLit "fromToE") fromToEIdKey
fromThenToEName = libFun (fsLit "fromThenToE") fromThenToEIdKey
-- end ArithSeq
listEName, sigEName, recConEName, recUpdEName :: Name
listEName = libFun (fsLit "listE") listEIdKey
sigEName = libFun (fsLit "sigE") sigEIdKey
recConEName = libFun (fsLit "recConE") recConEIdKey
recUpdEName = libFun (fsLit "recUpdE") recUpdEIdKey
-- type FieldExp = ...
fieldExpName :: Name
fieldExpName = libFun (fsLit "fieldExp") fieldExpIdKey
-- data Body = ...
guardedBName, normalBName :: Name
guardedBName = libFun (fsLit "guardedB") guardedBIdKey
normalBName = libFun (fsLit "normalB") normalBIdKey
-- data Guard = ...
normalGEName, patGEName :: Name
normalGEName = libFun (fsLit "normalGE") normalGEIdKey
patGEName = libFun (fsLit "patGE") patGEIdKey
-- data Stmt = ...
bindSName, letSName, noBindSName, parSName :: Name
bindSName = libFun (fsLit "bindS") bindSIdKey
letSName = libFun (fsLit "letS") letSIdKey
noBindSName = libFun (fsLit "noBindS") noBindSIdKey
parSName = libFun (fsLit "parS") parSIdKey
-- data Dec = ...
funDName, valDName, dataDName, newtypeDName, tySynDName, classDName,
instanceDName, sigDName, forImpDName, pragInlDName, pragSpecDName,
pragSpecInlDName, pragSpecInstDName, pragRuleDName, familyNoKindDName,
familyKindDName, dataInstDName, newtypeInstDName, tySynInstDName,
infixLDName, infixRDName, infixNDName :: Name
funDName = libFun (fsLit "funD") funDIdKey
valDName = libFun (fsLit "valD") valDIdKey
dataDName = libFun (fsLit "dataD") dataDIdKey
newtypeDName = libFun (fsLit "newtypeD") newtypeDIdKey
tySynDName = libFun (fsLit "tySynD") tySynDIdKey
classDName = libFun (fsLit "classD") classDIdKey
instanceDName = libFun (fsLit "instanceD") instanceDIdKey
sigDName = libFun (fsLit "sigD") sigDIdKey
forImpDName = libFun (fsLit "forImpD") forImpDIdKey
pragInlDName = libFun (fsLit "pragInlD") pragInlDIdKey
pragSpecDName = libFun (fsLit "pragSpecD") pragSpecDIdKey
pragSpecInlDName = libFun (fsLit "pragSpecInlD") pragSpecInlDIdKey
pragSpecInstDName = libFun (fsLit "pragSpecInstD") pragSpecInstDIdKey
pragRuleDName = libFun (fsLit "pragRuleD") pragRuleDIdKey
familyNoKindDName = libFun (fsLit "familyNoKindD") familyNoKindDIdKey
familyKindDName = libFun (fsLit "familyKindD") familyKindDIdKey
dataInstDName = libFun (fsLit "dataInstD") dataInstDIdKey
newtypeInstDName = libFun (fsLit "newtypeInstD") newtypeInstDIdKey
tySynInstDName = libFun (fsLit "tySynInstD") tySynInstDIdKey
infixLDName = libFun (fsLit "infixLD") infixLDIdKey
infixRDName = libFun (fsLit "infixRD") infixRDIdKey
infixNDName = libFun (fsLit "infixND") infixNDIdKey
-- type Ctxt = ...
cxtName :: Name
cxtName = libFun (fsLit "cxt") cxtIdKey
-- data Pred = ...
classPName, equalPName :: Name
classPName = libFun (fsLit "classP") classPIdKey
equalPName = libFun (fsLit "equalP") equalPIdKey
-- data Strict = ...
isStrictName, notStrictName, unpackedName :: Name
isStrictName = libFun (fsLit "isStrict") isStrictKey
notStrictName = libFun (fsLit "notStrict") notStrictKey
unpackedName = libFun (fsLit "unpacked") unpackedKey
-- data Con = ...
normalCName, recCName, infixCName, forallCName :: Name
normalCName = libFun (fsLit "normalC") normalCIdKey
recCName = libFun (fsLit "recC") recCIdKey
infixCName = libFun (fsLit "infixC") infixCIdKey
forallCName = libFun (fsLit "forallC") forallCIdKey
-- type StrictType = ...
strictTypeName :: Name
strictTypeName = libFun (fsLit "strictType") strictTKey
-- type VarStrictType = ...
varStrictTypeName :: Name
varStrictTypeName = libFun (fsLit "varStrictType") varStrictTKey
-- data Type = ...
forallTName, varTName, conTName, tupleTName, unboxedTupleTName, arrowTName,
listTName, appTName, sigTName, litTName,
promotedTName, promotedTupleTName,
promotedNilTName, promotedConsTName :: Name
forallTName = libFun (fsLit "forallT") forallTIdKey
varTName = libFun (fsLit "varT") varTIdKey
conTName = libFun (fsLit "conT") conTIdKey
tupleTName = libFun (fsLit "tupleT") tupleTIdKey
unboxedTupleTName = libFun (fsLit "unboxedTupleT") unboxedTupleTIdKey
arrowTName = libFun (fsLit "arrowT") arrowTIdKey
listTName = libFun (fsLit "listT") listTIdKey
appTName = libFun (fsLit "appT") appTIdKey
sigTName = libFun (fsLit "sigT") sigTIdKey
litTName = libFun (fsLit "litT") litTIdKey
promotedTName = libFun (fsLit "promotedT") promotedTIdKey
promotedTupleTName = libFun (fsLit "promotedTupleT") promotedTupleTIdKey
promotedNilTName = libFun (fsLit "promotedNilT") promotedNilTIdKey
promotedConsTName = libFun (fsLit "promotedConsT") promotedConsTIdKey
-- data TyLit = ...
numTyLitName, strTyLitName :: Name
numTyLitName = libFun (fsLit "numTyLit") numTyLitIdKey
strTyLitName = libFun (fsLit "strTyLit") strTyLitIdKey
-- data TyVarBndr = ...
plainTVName, kindedTVName :: Name
plainTVName = libFun (fsLit "plainTV") plainTVIdKey
kindedTVName = libFun (fsLit "kindedTV") kindedTVIdKey
-- data Kind = ...
varKName, conKName, tupleKName, arrowKName, listKName, appKName,
starKName, constraintKName :: Name
varKName = libFun (fsLit "varK") varKIdKey
conKName = libFun (fsLit "conK") conKIdKey
tupleKName = libFun (fsLit "tupleK") tupleKIdKey
arrowKName = libFun (fsLit "arrowK") arrowKIdKey
listKName = libFun (fsLit "listK") listKIdKey
appKName = libFun (fsLit "appK") appKIdKey
starKName = libFun (fsLit "starK") starKIdKey
constraintKName = libFun (fsLit "constraintK") constraintKIdKey
-- data Callconv = ...
cCallName, stdCallName :: Name
cCallName = libFun (fsLit "cCall") cCallIdKey
stdCallName = libFun (fsLit "stdCall") stdCallIdKey
-- data Safety = ...
unsafeName, safeName, interruptibleName :: Name
unsafeName = libFun (fsLit "unsafe") unsafeIdKey
safeName = libFun (fsLit "safe") safeIdKey
interruptibleName = libFun (fsLit "interruptible") interruptibleIdKey
-- data Inline = ...
noInlineDataConName, inlineDataConName, inlinableDataConName :: Name
noInlineDataConName = thCon (fsLit "NoInline") noInlineDataConKey
inlineDataConName = thCon (fsLit "Inline") inlineDataConKey
inlinableDataConName = thCon (fsLit "Inlinable") inlinableDataConKey
-- data RuleMatch = ...
conLikeDataConName, funLikeDataConName :: Name
conLikeDataConName = thCon (fsLit "ConLike") conLikeDataConKey
funLikeDataConName = thCon (fsLit "FunLike") funLikeDataConKey
-- data Phases = ...
allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName :: Name
allPhasesDataConName = thCon (fsLit "AllPhases") allPhasesDataConKey
fromPhaseDataConName = thCon (fsLit "FromPhase") fromPhaseDataConKey
beforePhaseDataConName = thCon (fsLit "BeforePhase") beforePhaseDataConKey
-- data RuleBndr = ...
ruleVarName, typedRuleVarName :: Name
ruleVarName = libFun (fsLit ("ruleVar")) ruleVarIdKey
typedRuleVarName = libFun (fsLit ("typedRuleVar")) typedRuleVarIdKey
-- data FunDep = ...
funDepName :: Name
funDepName = libFun (fsLit "funDep") funDepIdKey
-- data FamFlavour = ...
typeFamName, dataFamName :: Name
typeFamName = libFun (fsLit "typeFam") typeFamIdKey
dataFamName = libFun (fsLit "dataFam") dataFamIdKey
matchQTyConName, clauseQTyConName, expQTyConName, stmtQTyConName,
decQTyConName, conQTyConName, strictTypeQTyConName,
varStrictTypeQTyConName, typeQTyConName, fieldExpQTyConName,
patQTyConName, fieldPatQTyConName, predQTyConName, decsQTyConName,
ruleBndrQTyConName :: Name
matchQTyConName = libTc (fsLit "MatchQ") matchQTyConKey
clauseQTyConName = libTc (fsLit "ClauseQ") clauseQTyConKey
expQTyConName = libTc (fsLit "ExpQ") expQTyConKey
stmtQTyConName = libTc (fsLit "StmtQ") stmtQTyConKey
decQTyConName = libTc (fsLit "DecQ") decQTyConKey
decsQTyConName = libTc (fsLit "DecsQ") decsQTyConKey -- Q [Dec]
conQTyConName = libTc (fsLit "ConQ") conQTyConKey
strictTypeQTyConName = libTc (fsLit "StrictTypeQ") strictTypeQTyConKey
varStrictTypeQTyConName = libTc (fsLit "VarStrictTypeQ") varStrictTypeQTyConKey
typeQTyConName = libTc (fsLit "TypeQ") typeQTyConKey
fieldExpQTyConName = libTc (fsLit "FieldExpQ") fieldExpQTyConKey
patQTyConName = libTc (fsLit "PatQ") patQTyConKey
fieldPatQTyConName = libTc (fsLit "FieldPatQ") fieldPatQTyConKey
predQTyConName = libTc (fsLit "PredQ") predQTyConKey
ruleBndrQTyConName = libTc (fsLit "RuleBndrQ") ruleBndrQTyConKey
-- quasiquoting
quoteExpName, quotePatName, quoteDecName, quoteTypeName :: Name
quoteExpName = qqFun (fsLit "quoteExp") quoteExpKey
quotePatName = qqFun (fsLit "quotePat") quotePatKey
quoteDecName = qqFun (fsLit "quoteDec") quoteDecKey
quoteTypeName = qqFun (fsLit "quoteType") quoteTypeKey
-- TyConUniques available: 200-299
-- Check in PrelNames if you want to change this
expTyConKey, matchTyConKey, clauseTyConKey, qTyConKey, expQTyConKey,
decQTyConKey, patTyConKey, matchQTyConKey, clauseQTyConKey,
stmtQTyConKey, conQTyConKey, typeQTyConKey, typeTyConKey, tyVarBndrTyConKey,
decTyConKey, varStrictTypeQTyConKey, strictTypeQTyConKey,
fieldExpTyConKey, fieldPatTyConKey, nameTyConKey, patQTyConKey,
fieldPatQTyConKey, fieldExpQTyConKey, funDepTyConKey, predTyConKey,
predQTyConKey, decsQTyConKey, ruleBndrQTyConKey :: Unique
expTyConKey = mkPreludeTyConUnique 200
matchTyConKey = mkPreludeTyConUnique 201
clauseTyConKey = mkPreludeTyConUnique 202
qTyConKey = mkPreludeTyConUnique 203
expQTyConKey = mkPreludeTyConUnique 204
decQTyConKey = mkPreludeTyConUnique 205
patTyConKey = mkPreludeTyConUnique 206
matchQTyConKey = mkPreludeTyConUnique 207
clauseQTyConKey = mkPreludeTyConUnique 208
stmtQTyConKey = mkPreludeTyConUnique 209
conQTyConKey = mkPreludeTyConUnique 210
typeQTyConKey = mkPreludeTyConUnique 211
typeTyConKey = mkPreludeTyConUnique 212
decTyConKey = mkPreludeTyConUnique 213
varStrictTypeQTyConKey = mkPreludeTyConUnique 214
strictTypeQTyConKey = mkPreludeTyConUnique 215
fieldExpTyConKey = mkPreludeTyConUnique 216
fieldPatTyConKey = mkPreludeTyConUnique 217
nameTyConKey = mkPreludeTyConUnique 218
patQTyConKey = mkPreludeTyConUnique 219
fieldPatQTyConKey = mkPreludeTyConUnique 220
fieldExpQTyConKey = mkPreludeTyConUnique 221
funDepTyConKey = mkPreludeTyConUnique 222
predTyConKey = mkPreludeTyConUnique 223
predQTyConKey = mkPreludeTyConUnique 224
tyVarBndrTyConKey = mkPreludeTyConUnique 225
decsQTyConKey = mkPreludeTyConUnique 226
ruleBndrQTyConKey = mkPreludeTyConUnique 227
-- IdUniques available: 200-499
-- If you want to change this, make sure you check in PrelNames
returnQIdKey, bindQIdKey, sequenceQIdKey, liftIdKey, newNameIdKey,
mkNameIdKey, mkNameG_vIdKey, mkNameG_dIdKey, mkNameG_tcIdKey,
mkNameLIdKey :: Unique
returnQIdKey = mkPreludeMiscIdUnique 200
bindQIdKey = mkPreludeMiscIdUnique 201
sequenceQIdKey = mkPreludeMiscIdUnique 202
liftIdKey = mkPreludeMiscIdUnique 203
newNameIdKey = mkPreludeMiscIdUnique 204
mkNameIdKey = mkPreludeMiscIdUnique 205
mkNameG_vIdKey = mkPreludeMiscIdUnique 206
mkNameG_dIdKey = mkPreludeMiscIdUnique 207
mkNameG_tcIdKey = mkPreludeMiscIdUnique 208
mkNameLIdKey = mkPreludeMiscIdUnique 209
-- data Lit = ...
charLIdKey, stringLIdKey, integerLIdKey, intPrimLIdKey, wordPrimLIdKey,
floatPrimLIdKey, doublePrimLIdKey, rationalLIdKey :: Unique
charLIdKey = mkPreludeMiscIdUnique 220
stringLIdKey = mkPreludeMiscIdUnique 221
integerLIdKey = mkPreludeMiscIdUnique 222
intPrimLIdKey = mkPreludeMiscIdUnique 223
wordPrimLIdKey = mkPreludeMiscIdUnique 224
floatPrimLIdKey = mkPreludeMiscIdUnique 225
doublePrimLIdKey = mkPreludeMiscIdUnique 226
rationalLIdKey = mkPreludeMiscIdUnique 227
liftStringIdKey :: Unique
liftStringIdKey = mkPreludeMiscIdUnique 228
-- data Pat = ...
litPIdKey, varPIdKey, tupPIdKey, unboxedTupPIdKey, conPIdKey, infixPIdKey, tildePIdKey, bangPIdKey,
asPIdKey, wildPIdKey, recPIdKey, listPIdKey, sigPIdKey, viewPIdKey :: Unique
litPIdKey = mkPreludeMiscIdUnique 240
varPIdKey = mkPreludeMiscIdUnique 241
tupPIdKey = mkPreludeMiscIdUnique 242
unboxedTupPIdKey = mkPreludeMiscIdUnique 243
conPIdKey = mkPreludeMiscIdUnique 244
infixPIdKey = mkPreludeMiscIdUnique 245
tildePIdKey = mkPreludeMiscIdUnique 246
bangPIdKey = mkPreludeMiscIdUnique 247
asPIdKey = mkPreludeMiscIdUnique 248
wildPIdKey = mkPreludeMiscIdUnique 249
recPIdKey = mkPreludeMiscIdUnique 250
listPIdKey = mkPreludeMiscIdUnique 251
sigPIdKey = mkPreludeMiscIdUnique 252
viewPIdKey = mkPreludeMiscIdUnique 253
-- type FieldPat = ...
fieldPatIdKey :: Unique
fieldPatIdKey = mkPreludeMiscIdUnique 260
-- data Match = ...
matchIdKey :: Unique
matchIdKey = mkPreludeMiscIdUnique 261
-- data Clause = ...
clauseIdKey :: Unique
clauseIdKey = mkPreludeMiscIdUnique 262
-- data Exp = ...
varEIdKey, conEIdKey, litEIdKey, appEIdKey, infixEIdKey, infixAppIdKey,
sectionLIdKey, sectionRIdKey, lamEIdKey, lamCaseEIdKey, tupEIdKey,
unboxedTupEIdKey, condEIdKey, multiIfEIdKey,
letEIdKey, caseEIdKey, doEIdKey, compEIdKey,
fromEIdKey, fromThenEIdKey, fromToEIdKey, fromThenToEIdKey,
listEIdKey, sigEIdKey, recConEIdKey, recUpdEIdKey :: Unique
varEIdKey = mkPreludeMiscIdUnique 270
conEIdKey = mkPreludeMiscIdUnique 271
litEIdKey = mkPreludeMiscIdUnique 272
appEIdKey = mkPreludeMiscIdUnique 273
infixEIdKey = mkPreludeMiscIdUnique 274
infixAppIdKey = mkPreludeMiscIdUnique 275
sectionLIdKey = mkPreludeMiscIdUnique 276
sectionRIdKey = mkPreludeMiscIdUnique 277
lamEIdKey = mkPreludeMiscIdUnique 278
lamCaseEIdKey = mkPreludeMiscIdUnique 279
tupEIdKey = mkPreludeMiscIdUnique 280
unboxedTupEIdKey = mkPreludeMiscIdUnique 281
condEIdKey = mkPreludeMiscIdUnique 282
multiIfEIdKey = mkPreludeMiscIdUnique 283
letEIdKey = mkPreludeMiscIdUnique 284
caseEIdKey = mkPreludeMiscIdUnique 285
doEIdKey = mkPreludeMiscIdUnique 286
compEIdKey = mkPreludeMiscIdUnique 287
fromEIdKey = mkPreludeMiscIdUnique 288
fromThenEIdKey = mkPreludeMiscIdUnique 289
fromToEIdKey = mkPreludeMiscIdUnique 290
fromThenToEIdKey = mkPreludeMiscIdUnique 291
listEIdKey = mkPreludeMiscIdUnique 292
sigEIdKey = mkPreludeMiscIdUnique 293
recConEIdKey = mkPreludeMiscIdUnique 294
recUpdEIdKey = mkPreludeMiscIdUnique 295
-- type FieldExp = ...
fieldExpIdKey :: Unique
fieldExpIdKey = mkPreludeMiscIdUnique 310
-- data Body = ...
guardedBIdKey, normalBIdKey :: Unique
guardedBIdKey = mkPreludeMiscIdUnique 311
normalBIdKey = mkPreludeMiscIdUnique 312
-- data Guard = ...
normalGEIdKey, patGEIdKey :: Unique
normalGEIdKey = mkPreludeMiscIdUnique 313
patGEIdKey = mkPreludeMiscIdUnique 314
-- data Stmt = ...
bindSIdKey, letSIdKey, noBindSIdKey, parSIdKey :: Unique
bindSIdKey = mkPreludeMiscIdUnique 320
letSIdKey = mkPreludeMiscIdUnique 321
noBindSIdKey = mkPreludeMiscIdUnique 322
parSIdKey = mkPreludeMiscIdUnique 323
-- data Dec = ...
funDIdKey, valDIdKey, dataDIdKey, newtypeDIdKey, tySynDIdKey,
classDIdKey, instanceDIdKey, sigDIdKey, forImpDIdKey, pragInlDIdKey,
pragSpecDIdKey, pragSpecInlDIdKey, pragSpecInstDIdKey, pragRuleDIdKey,
familyNoKindDIdKey, familyKindDIdKey,
dataInstDIdKey, newtypeInstDIdKey, tySynInstDIdKey,
infixLDIdKey, infixRDIdKey, infixNDIdKey :: Unique
funDIdKey = mkPreludeMiscIdUnique 330
valDIdKey = mkPreludeMiscIdUnique 331
dataDIdKey = mkPreludeMiscIdUnique 332
newtypeDIdKey = mkPreludeMiscIdUnique 333
tySynDIdKey = mkPreludeMiscIdUnique 334
classDIdKey = mkPreludeMiscIdUnique 335
instanceDIdKey = mkPreludeMiscIdUnique 336
sigDIdKey = mkPreludeMiscIdUnique 337
forImpDIdKey = mkPreludeMiscIdUnique 338
pragInlDIdKey = mkPreludeMiscIdUnique 339
pragSpecDIdKey = mkPreludeMiscIdUnique 340
pragSpecInlDIdKey = mkPreludeMiscIdUnique 341
pragSpecInstDIdKey = mkPreludeMiscIdUnique 412
pragRuleDIdKey = mkPreludeMiscIdUnique 413
familyNoKindDIdKey = mkPreludeMiscIdUnique 342
familyKindDIdKey = mkPreludeMiscIdUnique 343
dataInstDIdKey = mkPreludeMiscIdUnique 344
newtypeInstDIdKey = mkPreludeMiscIdUnique 345
tySynInstDIdKey = mkPreludeMiscIdUnique 346
infixLDIdKey = mkPreludeMiscIdUnique 347
infixRDIdKey = mkPreludeMiscIdUnique 348
infixNDIdKey = mkPreludeMiscIdUnique 349
-- type Cxt = ...
cxtIdKey :: Unique
cxtIdKey = mkPreludeMiscIdUnique 360
-- data Pred = ...
classPIdKey, equalPIdKey :: Unique
classPIdKey = mkPreludeMiscIdUnique 361
equalPIdKey = mkPreludeMiscIdUnique 362
-- data Strict = ...
isStrictKey, notStrictKey, unpackedKey :: Unique
isStrictKey = mkPreludeMiscIdUnique 363
notStrictKey = mkPreludeMiscIdUnique 364
unpackedKey = mkPreludeMiscIdUnique 365
-- data Con = ...
normalCIdKey, recCIdKey, infixCIdKey, forallCIdKey :: Unique
normalCIdKey = mkPreludeMiscIdUnique 370
recCIdKey = mkPreludeMiscIdUnique 371
infixCIdKey = mkPreludeMiscIdUnique 372
forallCIdKey = mkPreludeMiscIdUnique 373
-- type StrictType = ...
strictTKey :: Unique
strictTKey = mkPreludeMiscIdUnique 374
-- type VarStrictType = ...
varStrictTKey :: Unique
varStrictTKey = mkPreludeMiscIdUnique 375
-- data Type = ...
forallTIdKey, varTIdKey, conTIdKey, tupleTIdKey, unboxedTupleTIdKey, arrowTIdKey,
listTIdKey, appTIdKey, sigTIdKey, litTIdKey,
promotedTIdKey, promotedTupleTIdKey,
promotedNilTIdKey, promotedConsTIdKey :: Unique
forallTIdKey = mkPreludeMiscIdUnique 380
varTIdKey = mkPreludeMiscIdUnique 381
conTIdKey = mkPreludeMiscIdUnique 382
tupleTIdKey = mkPreludeMiscIdUnique 383
unboxedTupleTIdKey = mkPreludeMiscIdUnique 384
arrowTIdKey = mkPreludeMiscIdUnique 385
listTIdKey = mkPreludeMiscIdUnique 386
appTIdKey = mkPreludeMiscIdUnique 387
sigTIdKey = mkPreludeMiscIdUnique 388
litTIdKey = mkPreludeMiscIdUnique 389
promotedTIdKey = mkPreludeMiscIdUnique 390
promotedTupleTIdKey = mkPreludeMiscIdUnique 391
promotedNilTIdKey = mkPreludeMiscIdUnique 392
promotedConsTIdKey = mkPreludeMiscIdUnique 393
-- data TyLit = ...
numTyLitIdKey, strTyLitIdKey :: Unique
numTyLitIdKey = mkPreludeMiscIdUnique 394
strTyLitIdKey = mkPreludeMiscIdUnique 395
-- data TyVarBndr = ...
plainTVIdKey, kindedTVIdKey :: Unique
plainTVIdKey = mkPreludeMiscIdUnique 396
kindedTVIdKey = mkPreludeMiscIdUnique 397
-- data Kind = ...
varKIdKey, conKIdKey, tupleKIdKey, arrowKIdKey, listKIdKey, appKIdKey,
starKIdKey, constraintKIdKey :: Unique
varKIdKey = mkPreludeMiscIdUnique 398
conKIdKey = mkPreludeMiscIdUnique 399
tupleKIdKey = mkPreludeMiscIdUnique 400
arrowKIdKey = mkPreludeMiscIdUnique 401
listKIdKey = mkPreludeMiscIdUnique 402
appKIdKey = mkPreludeMiscIdUnique 403
starKIdKey = mkPreludeMiscIdUnique 404
constraintKIdKey = mkPreludeMiscIdUnique 405
-- data Callconv = ...
cCallIdKey, stdCallIdKey :: Unique
cCallIdKey = mkPreludeMiscIdUnique 406
stdCallIdKey = mkPreludeMiscIdUnique 407
-- data Safety = ...
unsafeIdKey, safeIdKey, interruptibleIdKey :: Unique
unsafeIdKey = mkPreludeMiscIdUnique 408
safeIdKey = mkPreludeMiscIdUnique 409
interruptibleIdKey = mkPreludeMiscIdUnique 411
-- data Inline = ...
noInlineDataConKey, inlineDataConKey, inlinableDataConKey :: Unique
noInlineDataConKey = mkPreludeDataConUnique 40
inlineDataConKey = mkPreludeDataConUnique 41
inlinableDataConKey = mkPreludeDataConUnique 42
-- data RuleMatch = ...
conLikeDataConKey, funLikeDataConKey :: Unique
conLikeDataConKey = mkPreludeDataConUnique 43
funLikeDataConKey = mkPreludeDataConUnique 44
-- data Phases = ...
allPhasesDataConKey, fromPhaseDataConKey, beforePhaseDataConKey :: Unique
allPhasesDataConKey = mkPreludeDataConUnique 45
fromPhaseDataConKey = mkPreludeDataConUnique 46
beforePhaseDataConKey = mkPreludeDataConUnique 47
-- data FunDep = ...
funDepIdKey :: Unique
funDepIdKey = mkPreludeMiscIdUnique 414
-- data FamFlavour = ...
typeFamIdKey, dataFamIdKey :: Unique
typeFamIdKey = mkPreludeMiscIdUnique 415
dataFamIdKey = mkPreludeMiscIdUnique 416
-- quasiquoting
quoteExpKey, quotePatKey, quoteDecKey, quoteTypeKey :: Unique
quoteExpKey = mkPreludeMiscIdUnique 418
quotePatKey = mkPreludeMiscIdUnique 419
quoteDecKey = mkPreludeMiscIdUnique 420
quoteTypeKey = mkPreludeMiscIdUnique 421
-- data RuleBndr = ...
ruleVarIdKey, typedRuleVarIdKey :: Unique
ruleVarIdKey = mkPreludeMiscIdUnique 422
typedRuleVarIdKey = mkPreludeMiscIdUnique 423
|
nomeata/ghc
|
compiler/deSugar/DsMeta.hs
|
Haskell
|
bsd-3-clause
| 103,047
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
import Control.Monad
import Control.Monad.Identity
import Control.Monad.Trans
import Reflex.Dom
import qualified Data.Text as T
import Control.Concurrent
import Control.Monad.State.Strict
import Data.Functor.Misc
import Data.Monoid
import Data.Word
import qualified Data.Map as Map
import qualified Data.Dependent.Map as DMap
import Data.Dependent.Sum
import qualified Reflex.Patch.DMapWithMove as PatchDMapWithMove
main :: IO ()
main = mainWidget w
w :: forall t m. (MonadWidget t m, DomRenderHook t m, MountableDomBuilder t m) => m ()
w = do
let slow :: forall m'. (MonadWidget t m', DomRenderHook t m') => m' ()
{-
performEventChain = do
postBuild <- delay 0 =<< getPostBuild
rec let maxN = 10000
n = leftmost [0 <$ postBuild, ffilter (<=maxN) $ succ <$> n']
n' <- performEvent $ return <$> n
pausedUntil $ ffilter (==maxN) n'
_ <- widgetHold (text "Starting") $ text . T.pack . show <$> n
return ()
-}
-- {- Many dyns
slow = elAttr "div" ("style" =: "position:relative;width:256px;height:256px") $ go maxDepth
where maxDepth = 6 :: Int
go 0 = blank
go n = void $ dyn $ pure $ do
let bgcolor = "rgba(0,0,0," <> T.pack (show (1 - (fromIntegral n / fromIntegral maxDepth) :: Double)) <> ")"
s pos = pos <> ";position:absolute;border:1px solid white;background-color:" <> bgcolor
elAttr "div" ("style" =: s "left:0;right:50%;top:0;bottom:50%") $ go $ pred n
elAttr "div" ("style" =: s "left:50%;right:0;top:0;bottom:50%") $ go $ pred n
elAttr "div" ("style" =: s "left:50%;right:0;top:50%;bottom:0") $ go $ pred n
elAttr "div" ("style" =: s "left:0;right:50%;top:50%;bottom:0") $ go $ pred n
-- -}
{- Many elDynAttrs
slow = do
let size = 64
replicateM_ size $ elAttr "div" ("style" =: ("height:4px;width:" <> T.pack (show (size*4)) <> "px;line-height:0;background-color:gray")) $ do
replicateM_ size $ elDynAttr "div" (pure $ "style" =: "display:inline-block;width:4px;height:4px;background-color:black") blank
-}
{- Many dynTexts
slow = el "table" $ do
let size = 64
replicateM_ size $ el "tr" $ do
replicateM_ size $ el "td" $ do
dynText $ pure "."
-}
{- Many simultaneous performEvents
slow = do
postBuild <- getPostBuild
replicateM_ ((2 :: Int) ^ (14 :: Int)) $ performEvent_ $ return () <$ postBuild
done <- performEvent $ return () <$ postBuild
_ <- widgetHold (text "Doing performEvent") $ text "Done" <$ done
return ()
-}
{-
slow = do
postBuild <- getPostBuild
postBuild' <- performEvent . (return () <$) =<< performEvent . (return () <$) =<< getPostBuild
let f x = Map.fromList [(n, x) | n <- [1 :: Int .. 4096]]
listHoldWithKey (f False) (f (Just True) <$ postBuild') $ \k -> \case
False -> do
text "X "
notReadyUntil =<< getPostBuild
True -> do
text ". "
return ()
-}
{-
slow = do
let f :: forall a. EitherTag () () a -> Const2 () () a -> m' (Const2 () () a)
f _ (Const2 ()) = do
notReadyUntil =<< delay 0.5 =<< getPostBuild
text "Done"
return $ Const2 ()
postBuild <- getPostBuild
traverseDMapWithKeyWithAdjustWithMove f (DMap.singleton LeftTag $ Const2 ()) $ (PatchDMapWithMove.moveDMapKey LeftTag RightTag) <$ postBuild
return ()
-}
{-
slow = do
let h x = do
liftIO $ putStrLn "render hook"
result <- x
liftIO $ putStrLn "render hook done"
return result
f :: forall a. Const2 () () a -> Identity a -> m' (Identity a)
f (Const2 ()) (Identity ()) = do
liftIO $ putStrLn "f"
widgetHold notReady . (blank <$) =<< delay 0.1 =<< getPostBuild
liftIO $ putStrLn "f done"
return $ Identity ()
withRenderHook h $ do
postBuild <- getPostBuild
_ <- traverseDMapWithKeyWithAdjust f mempty $ PatchDMap (DMap.singleton (Const2 () :: Const2 () () ()) (ComposeMaybe $ Just $ Identity ())) <$ postBuild
return ()
-}
el "div" $ do
draw <- button "Draw"
widgetHold blank $ ffor draw $ \_ -> do
_ <- untilReady (text "Loading...") slow
return ()
return ()
#ifdef EXPERIMENTAL_DEPENDENT_SUM_INSTANCES
instance {-# INCOHERENT #-} (Show (f a), Show (f b)) => ShowTag (EitherTag a b) f where
showTagToShow e _ = case e of
LeftTag -> id
RightTag -> id
#endif
|
mightybyte/reflex-dom
|
test/prebuild.hs
|
Haskell
|
bsd-3-clause
| 5,028
|
{-|
Module : Diplomacy.Occupation
Description : Definition of Zone/ProvinceTarget occupation.
Copyright : (c) Alexander Vieth, 2015
Licence : BSD3
Maintainer : aovieth@gmail.com
Stability : experimental
Portability : non-portable (GHC only)
-}
{-# LANGUAGE AutoDeriveTypeable #-}
module Diplomacy.Occupation (
Occupation
, emptyOccupation
, occupy
, occupier
, provinceOccupier
, occupies
, unitOccupies
, occupied
, zoneOccupied
, allSubjects
) where
import qualified Data.Map as M
import Data.MapUtil
import Data.Maybe (isJust)
import Diplomacy.Aligned
import Diplomacy.Unit
import Diplomacy.Province
import Diplomacy.Zone
import Diplomacy.Subject
import Diplomacy.GreatPower
-- | Each Zone is occupied by at most one Aligned Unit, but the functions on
-- Occupation work with ProvinceTarget; the use of Zone as a key here is just
-- to guarantee that we don't have, for instance, units on both of Spain's
-- coasts simultaneously.
type Occupation = M.Map Zone (Aligned Unit)
emptyOccupation :: Occupation
emptyOccupation = M.empty
occupy :: ProvinceTarget -> Maybe (Aligned Unit) -> Occupation -> Occupation
occupy pt maunit = M.alter (const maunit) (Zone pt)
-- | Must be careful with this one! We can't just lookup the Zone corresponding
-- to the ProvinceTarget; we must also check that the key matching that Zone,
-- if there is one in the map, is also ProvinceTarget-equal.
occupier :: ProvinceTarget -> Occupation -> Maybe (Aligned Unit)
occupier pt occupation = case lookupWithKey (Zone pt) occupation of
Just (zone, value) ->
if zoneProvinceTarget zone == pt
then Just value
else Nothing
_ -> Nothing
provinceOccupier :: Province -> Occupation -> Maybe (Aligned Unit)
provinceOccupier pr occupation = case lookupWithKey (Zone (Normal pr)) occupation of
Just (zone, value) ->
if zoneProvinceTarget zone == Normal pr
then Just value
else Nothing
_ -> Nothing
occupies :: Aligned Unit -> ProvinceTarget -> Occupation -> Bool
occupies aunit pt = (==) (Just aunit) . occupier pt
unitOccupies :: Unit -> ProvinceTarget -> Occupation -> Bool
unitOccupies unit pt = (==) (Just unit) . fmap alignedThing . occupier pt
occupied :: ProvinceTarget -> Occupation -> Bool
occupied pt = isJust . occupier pt
zoneOccupied :: Zone -> Occupation -> Bool
zoneOccupied zone = isJust . M.lookup zone
allSubjects :: Maybe GreatPower -> Occupation -> [Subject]
allSubjects maybeGreatPower = M.foldWithKey f []
where
f zone aunit =
let subject = (alignedThing aunit, zoneProvinceTarget zone)
in if maybeGreatPower == Nothing || Just (alignedGreatPower aunit) == maybeGreatPower
then (:) subject
else id
|
avieth/diplomacy
|
Diplomacy/Occupation.hs
|
Haskell
|
bsd-3-clause
| 2,765
|
{-- snippet modifyMVar --}
import Control.Concurrent (MVar, putMVar, takeMVar)
import Control.Exception (block, catch, throw, unblock)
import Prelude hiding (catch) -- use Control.Exception's version
modifyMVar :: MVar a -> (a -> IO (a,b)) -> IO b
modifyMVar m io =
block $ do
a <- takeMVar m
(b,r) <- unblock (io a) `catch` \e ->
putMVar m a >> throw e
putMVar m b
return r
{-- /snippet modifyMVar --}
|
binesiyu/ifl
|
examples/ch24/ModifyMVar.hs
|
Haskell
|
mit
| 436
|
<?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="ja-JP">
<title>TLS デバッグ | ZAP拡張</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>コンテンツ</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>インデックス</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>検索</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>お気に入り</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/tlsdebug/src/main/javahelp/org/zaproxy/zap/extension/tlsdebug/resources/help_ja_JP/helpset_ja_JP.hs
|
Haskell
|
apache-2.0
| 1,000
|
module VarPtr where
import Data.Var
data Record = Record Int
main = do
v <- newVar $ Record 5
subscribeAndRead v $ \y -> case y of
Record a -> putStrLn . show $ a
set v $ Record 10
|
beni55/fay
|
tests/VarPtr.hs
|
Haskell
|
bsd-3-clause
| 195
|
-- (c) The University of Glasgow 2006
{-# LANGUAGE CPP, DeriveFunctor #-}
module Unify (
-- Matching of types:
-- the "tc" prefix indicates that matching always
-- respects newtypes (rather than looking through them)
tcMatchTy, tcUnifyTyWithTFs, tcMatchTys, tcMatchTyX, tcMatchTysX,
ruleMatchTyX, tcMatchPreds,
MatchEnv(..), matchList,
typesCantMatch,
-- Side-effect free unification
tcUnifyTy, tcUnifyTys, BindFlag(..),
UnifyResultM(..), UnifyResult, tcUnifyTysFG
) where
#include "HsVersions.h"
import Var
import VarEnv
import VarSet
import Kind
import Type
import TyCon
import TypeRep
import Util ( filterByList )
import Outputable
import FastString (sLit)
import Control.Monad (liftM, foldM, ap)
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative (Applicative(..))
#endif
{-
************************************************************************
* *
Matching
* *
************************************************************************
Matching is much tricker than you might think.
1. The substitution we generate binds the *template type variables*
which are given to us explicitly.
2. We want to match in the presence of foralls;
e.g (forall a. t1) ~ (forall b. t2)
That is what the RnEnv2 is for; it does the alpha-renaming
that makes it as if a and b were the same variable.
Initialising the RnEnv2, so that it can generate a fresh
binder when necessary, entails knowing the free variables of
both types.
3. We must be careful not to bind a template type variable to a
locally bound variable. E.g.
(forall a. x) ~ (forall b. b)
where x is the template type variable. Then we do not want to
bind x to a/b! This is a kind of occurs check.
The necessary locals accumulate in the RnEnv2.
-}
data MatchEnv
= ME { me_tmpls :: VarSet -- Template variables
, me_env :: RnEnv2 -- Renaming envt for nested foralls
} -- In-scope set includes template variables
-- Nota Bene: MatchEnv isn't specific to Types. It is used
-- for matching terms and coercions as well as types
tcMatchTy :: TyVarSet -- Template tyvars
-> Type -- Template
-> Type -- Target
-> Maybe TvSubst -- One-shot; in principle the template
-- variables could be free in the target
tcMatchTy tmpls ty1 ty2
= tcMatchTyX tmpls init_subst ty1 ty2
where
init_subst = mkTvSubst in_scope emptyTvSubstEnv
in_scope = mkInScopeSet (tmpls `unionVarSet` tyVarsOfType ty2)
-- We're assuming that all the interesting
-- tyvars in ty1 are in tmpls
tcMatchTys :: TyVarSet -- Template tyvars
-> [Type] -- Template
-> [Type] -- Target
-> Maybe TvSubst -- One-shot; in principle the template
-- variables could be free in the target
tcMatchTys tmpls tys1 tys2
= tcMatchTysX tmpls init_subst tys1 tys2
where
init_subst = mkTvSubst in_scope emptyTvSubstEnv
in_scope = mkInScopeSet (tmpls `unionVarSet` tyVarsOfTypes tys2)
tcMatchTyX :: TyVarSet -- Template tyvars
-> TvSubst -- Substitution to extend
-> Type -- Template
-> Type -- Target
-> Maybe TvSubst
tcMatchTyX tmpls (TvSubst in_scope subst_env) ty1 ty2
= case match menv subst_env ty1 ty2 of
Just subst_env' -> Just (TvSubst in_scope subst_env')
Nothing -> Nothing
where
menv = ME {me_tmpls = tmpls, me_env = mkRnEnv2 in_scope}
tcMatchTysX :: TyVarSet -- Template tyvars
-> TvSubst -- Substitution to extend
-> [Type] -- Template
-> [Type] -- Target
-> Maybe TvSubst -- One-shot; in principle the template
-- variables could be free in the target
tcMatchTysX tmpls (TvSubst in_scope subst_env) tys1 tys2
= case match_tys menv subst_env tys1 tys2 of
Just subst_env' -> Just (TvSubst in_scope subst_env')
Nothing -> Nothing
where
menv = ME { me_tmpls = tmpls, me_env = mkRnEnv2 in_scope }
tcMatchPreds
:: [TyVar] -- Bind these
-> [PredType] -> [PredType]
-> Maybe TvSubstEnv
tcMatchPreds tmpls ps1 ps2
= matchList (match menv) emptyTvSubstEnv ps1 ps2
where
menv = ME { me_tmpls = mkVarSet tmpls, me_env = mkRnEnv2 in_scope_tyvars }
in_scope_tyvars = mkInScopeSet (tyVarsOfTypes ps1 `unionVarSet` tyVarsOfTypes ps2)
-- This one is called from the expression matcher, which already has a MatchEnv in hand
ruleMatchTyX :: MatchEnv
-> TvSubstEnv -- Substitution to extend
-> Type -- Template
-> Type -- Target
-> Maybe TvSubstEnv
ruleMatchTyX menv subst ty1 ty2 = match menv subst ty1 ty2 -- Rename for export
-- Now the internals of matching
-- | Workhorse matching function. Our goal is to find a substitution
-- on all of the template variables (specified by @me_tmpls menv@) such
-- that @ty1@ and @ty2@ unify. This substitution is accumulated in @subst@.
-- If a variable is not a template variable, we don't attempt to find a
-- substitution for it; it must match exactly on both sides. Furthermore,
-- only @ty1@ can have template variables.
--
-- This function handles binders, see 'RnEnv2' for more details on
-- how that works.
match :: MatchEnv -- For the most part this is pushed downwards
-> TvSubstEnv -- Substitution so far:
-- Domain is subset of template tyvars
-- Free vars of range is subset of
-- in-scope set of the RnEnv2
-> Type -> Type -- Template and target respectively
-> Maybe TvSubstEnv
match menv subst ty1 ty2 | Just ty1' <- coreView ty1 = match menv subst ty1' ty2
| Just ty2' <- coreView ty2 = match menv subst ty1 ty2'
match menv subst (TyVarTy tv1) ty2
| Just ty1' <- lookupVarEnv subst tv1' -- tv1' is already bound
= if eqTypeX (nukeRnEnvL rn_env) ty1' ty2
-- ty1 has no locally-bound variables, hence nukeRnEnvL
then Just subst
else Nothing -- ty2 doesn't match
| tv1' `elemVarSet` me_tmpls menv
= if any (inRnEnvR rn_env) (varSetElems (tyVarsOfType ty2))
then Nothing -- Occurs check
-- ezyang: Is this really an occurs check? It seems
-- to just reject matching \x. A against \x. x (maintaining
-- the invariant that the free vars of the range of @subst@
-- are a subset of the in-scope set in @me_env menv@.)
else do { subst1 <- match_kind menv subst (tyVarKind tv1) (typeKind ty2)
-- Note [Matching kinds]
; return (extendVarEnv subst1 tv1' ty2) }
| otherwise -- tv1 is not a template tyvar
= case ty2 of
TyVarTy tv2 | tv1' == rnOccR rn_env tv2 -> Just subst
_ -> Nothing
where
rn_env = me_env menv
tv1' = rnOccL rn_env tv1
match menv subst (ForAllTy tv1 ty1) (ForAllTy tv2 ty2)
= do { subst' <- match_kind menv subst (tyVarKind tv1) (tyVarKind tv2)
; match menv' subst' ty1 ty2 }
where -- Use the magic of rnBndr2 to go under the binders
menv' = menv { me_env = rnBndr2 (me_env menv) tv1 tv2 }
match menv subst (TyConApp tc1 tys1) (TyConApp tc2 tys2)
| tc1 == tc2 = match_tys menv subst tys1 tys2
match menv subst (FunTy ty1a ty1b) (FunTy ty2a ty2b)
= do { subst' <- match menv subst ty1a ty2a
; match menv subst' ty1b ty2b }
match menv subst (AppTy ty1a ty1b) ty2
| Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
-- 'repSplit' used because the tcView stuff is done above
= do { subst' <- match menv subst ty1a ty2a
; match menv subst' ty1b ty2b }
match _ subst (LitTy x) (LitTy y) | x == y = return subst
match _ _ _ _
= Nothing
--------------
match_kind :: MatchEnv -> TvSubstEnv -> Kind -> Kind -> Maybe TvSubstEnv
-- Match the kind of the template tyvar with the kind of Type
-- Note [Matching kinds]
match_kind menv subst k1 k2
| k2 `isSubKind` k1
= return subst
| otherwise
= match menv subst k1 k2
-- Note [Matching kinds]
-- ~~~~~~~~~~~~~~~~~~~~~
-- For ordinary type variables, we don't want (m a) to match (n b)
-- if say (a::*) and (b::*->*). This is just a yes/no issue.
--
-- For coercion kinds matters are more complicated. If we have a
-- coercion template variable co::a~[b], where a,b are presumably also
-- template type variables, then we must match co's kind against the
-- kind of the actual argument, so as to give bindings to a,b.
--
-- In fact I have no example in mind that *requires* this kind-matching
-- to instantiate template type variables, but it seems like the right
-- thing to do. C.f. Note [Matching variable types] in Rules.hs
--------------
match_tys :: MatchEnv -> TvSubstEnv -> [Type] -> [Type] -> Maybe TvSubstEnv
match_tys menv subst tys1 tys2 = matchList (match menv) subst tys1 tys2
--------------
matchList :: (env -> a -> b -> Maybe env)
-> env -> [a] -> [b] -> Maybe env
matchList _ subst [] [] = Just subst
matchList fn subst (a:as) (b:bs) = do { subst' <- fn subst a b
; matchList fn subst' as bs }
matchList _ _ _ _ = Nothing
{-
************************************************************************
* *
GADTs
* *
************************************************************************
Note [Pruning dead case alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider data T a where
T1 :: T Int
T2 :: T a
newtype X = MkX Int
newtype Y = MkY Char
type family F a
type instance F Bool = Int
Now consider case x of { T1 -> e1; T2 -> e2 }
The question before the house is this: if I know something about the type
of x, can I prune away the T1 alternative?
Suppose x::T Char. It's impossible to construct a (T Char) using T1,
Answer = YES we can prune the T1 branch (clearly)
Suppose x::T (F a), where 'a' is in scope. Then 'a' might be instantiated
to 'Bool', in which case x::T Int, so
ANSWER = NO (clearly)
We see here that we want precisely the apartness check implemented within
tcUnifyTysFG. So that's what we do! Two types cannot match if they are surely
apart. Note that since we are simply dropping dead code, a conservative test
suffices.
-}
-- | Given a list of pairs of types, are any two members of a pair surely
-- apart, even after arbitrary type function evaluation and substitution?
typesCantMatch :: [(Type,Type)] -> Bool
-- See Note [Pruning dead case alternatives]
typesCantMatch prs = any (\(s,t) -> cant_match s t) prs
where
cant_match :: Type -> Type -> Bool
cant_match t1 t2 = case tcUnifyTysFG (const BindMe) [t1] [t2] of
SurelyApart -> True
_ -> False
{-
************************************************************************
* *
Unification
* *
************************************************************************
Note [Fine-grained unification]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Do the types (x, x) and ([y], y) unify? The answer is seemingly "no" --
no substitution to finite types makes these match. But, a substitution to
*infinite* types can unify these two types: [x |-> [[[...]]], y |-> [[[...]]] ].
Why do we care? Consider these two type family instances:
type instance F x x = Int
type instance F [y] y = Bool
If we also have
type instance Looper = [Looper]
then the instances potentially overlap. The solution is to use unification
over infinite terms. This is possible (see [1] for lots of gory details), but
a full algorithm is a little more power than we need. Instead, we make a
conservative approximation and just omit the occurs check.
[1]: http://research.microsoft.com/en-us/um/people/simonpj/papers/ext-f/axioms-extended.pdf
tcUnifyTys considers an occurs-check problem as the same as general unification
failure.
tcUnifyTysFG ("fine-grained") returns one of three results: success, occurs-check
failure ("MaybeApart"), or general failure ("SurelyApart").
See also Trac #8162.
It's worth noting that unification in the presence of infinite types is not
complete. This means that, sometimes, a closed type family does not reduce
when it should. See test case indexed-types/should_fail/Overlap15 for an
example.
Note [The substitution in MaybeApart]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The constructor MaybeApart carries data with it, typically a TvSubstEnv. Why?
Because consider unifying these:
(a, a, Int) ~ (b, [b], Bool)
If we go left-to-right, we start with [a |-> b]. Then, on the middle terms, we
apply the subst we have so far and discover that we need [b |-> [b]]. Because
this fails the occurs check, we say that the types are MaybeApart (see above
Note [Fine-grained unification]). But, we can't stop there! Because if we
continue, we discover that Int is SurelyApart from Bool, and therefore the
types are apart. This has practical consequences for the ability for closed
type family applications to reduce. See test case
indexed-types/should_compile/Overlap14.
Note [Unifying with skolems]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we discover that two types unify if and only if a skolem variable is
substituted, we can't properly unify the types. But, that skolem variable
may later be instantiated with a unifyable type. So, we return maybeApart
in these cases.
Note [Lists of different lengths are MaybeApart]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is unusual to call tcUnifyTys or tcUnifyTysFG with lists of different
lengths. The place where we know this can happen is from compatibleBranches in
FamInstEnv, when checking data family instances. Data family instances may be
eta-reduced; see Note [Eta reduction for data family axioms] in TcInstDcls.
We wish to say that
D :: * -> * -> *
axDF1 :: D Int ~ DFInst1
axDF2 :: D Int Bool ~ DFInst2
overlap. If we conclude that lists of different lengths are SurelyApart, then
it will look like these do *not* overlap, causing disaster. See Trac #9371.
In usages of tcUnifyTys outside of family instances, we always use tcUnifyTys,
which can't tell the difference between MaybeApart and SurelyApart, so those
usages won't notice this design choice.
-}
tcUnifyTy :: Type -> Type -- All tyvars are bindable
-> Maybe TvSubst -- A regular one-shot (idempotent) substitution
-- Simple unification of two types; all type variables are bindable
tcUnifyTy ty1 ty2
= case initUM (const BindMe) (unify ty1 ty2) of
Unifiable subst -> Just subst
_other -> Nothing
-- | Unify two types, treating type family applications as possibly unifying
-- with anything and looking through injective type family applications.
tcUnifyTyWithTFs :: Bool -> Type -> Type -> Maybe TvSubst
-- This algorithm is a direct implementation of the "Algorithm U" presented in
-- the paper "Injective type families for Haskell", Figures 2 and 3. Equation
-- numbers in the comments refer to equations from the paper.
tcUnifyTyWithTFs twoWay t1 t2 = niFixTvSubst `fmap` go t1 t2 emptyTvSubstEnv
where
go :: Type -> Type -> TvSubstEnv -> Maybe TvSubstEnv
-- look through type synonyms
go t1 t2 theta | Just t1' <- tcView t1 = go t1' t2 theta
go t1 t2 theta | Just t2' <- tcView t2 = go t1 t2' theta
-- proper unification
go (TyVarTy tv) t2 theta
-- Equation (1)
| Just t1' <- lookupVarEnv theta tv
= go t1' t2 theta
| otherwise = let t2' = Type.substTy (niFixTvSubst theta) t2
in if tv `elemVarEnv` tyVarsOfType t2'
-- Equation (2)
then Just theta
-- Equation (3)
else Just $ extendVarEnv theta tv t2'
-- Equation (4)
go t1 t2@(TyVarTy _) theta | twoWay = go t2 t1 theta
-- Equation (5)
go (AppTy s1 s2) ty theta | Just(t1, t2) <- splitAppTy_maybe ty =
go s1 t1 theta >>= go s2 t2
go ty (AppTy s1 s2) theta | Just(t1, t2) <- splitAppTy_maybe ty =
go s1 t1 theta >>= go s2 t2
go (TyConApp tc1 tys1) (TyConApp tc2 tys2) theta
-- Equation (6)
| isAlgTyCon tc1 && isAlgTyCon tc2 && tc1 == tc2
= let tys = zip tys1 tys2
in foldM (\theta' (t1,t2) -> go t1 t2 theta') theta tys
-- Equation (7)
| isTypeFamilyTyCon tc1 && isTypeFamilyTyCon tc2 && tc1 == tc2
, Injective inj <- familyTyConInjectivityInfo tc1
= let tys1' = filterByList inj tys1
tys2' = filterByList inj tys2
injTys = zip tys1' tys2'
in foldM (\theta' (t1,t2) -> go t1 t2 theta') theta injTys
-- Equations (8)
| isTypeFamilyTyCon tc1
= Just theta
-- Equations (9)
| isTypeFamilyTyCon tc2, twoWay
= Just theta
-- Equation (10)
go _ _ _ = Nothing
-----------------
tcUnifyTys :: (TyVar -> BindFlag)
-> [Type] -> [Type]
-> Maybe TvSubst -- A regular one-shot (idempotent) substitution
-- The two types may have common type variables, and indeed do so in the
-- second call to tcUnifyTys in FunDeps.checkClsFD
tcUnifyTys bind_fn tys1 tys2
= case tcUnifyTysFG bind_fn tys1 tys2 of
Unifiable subst -> Just subst
_ -> Nothing
-- This type does double-duty. It is used in the UM (unifier monad) and to
-- return the final result. See Note [Fine-grained unification]
type UnifyResult = UnifyResultM TvSubst
data UnifyResultM a = Unifiable a -- the subst that unifies the types
| MaybeApart a -- the subst has as much as we know
-- it must be part of an most general unifier
-- See Note [The substitution in MaybeApart]
| SurelyApart
deriving Functor
-- See Note [Fine-grained unification]
tcUnifyTysFG :: (TyVar -> BindFlag)
-> [Type] -> [Type]
-> UnifyResult
tcUnifyTysFG bind_fn tys1 tys2
= initUM bind_fn (unify_tys tys1 tys2)
instance Outputable a => Outputable (UnifyResultM a) where
ppr SurelyApart = ptext (sLit "SurelyApart")
ppr (Unifiable x) = ptext (sLit "Unifiable") <+> ppr x
ppr (MaybeApart x) = ptext (sLit "MaybeApart") <+> ppr x
{-
************************************************************************
* *
Non-idempotent substitution
* *
************************************************************************
Note [Non-idempotent substitution]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
During unification we use a TvSubstEnv that is
(a) non-idempotent
(b) loop-free; ie repeatedly applying it yields a fixed point
Note [Finding the substitution fixpoint]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Finding the fixpoint of a non-idempotent substitution arising from a
unification is harder than it looks, because of kinds. Consider
T k (H k (f:k)) ~ T * (g:*)
If we unify, we get the substitution
[ k -> *
, g -> H k (f:k) ]
To make it idempotent we don't want to get just
[ k -> *
, g -> H * (f:k) ]
We also want to substitute inside f's kind, to get
[ k -> *
, g -> H k (f:*) ]
If we don't do this, we may apply the substitition to something,
and get an ill-formed type, i.e. one where typeKind will fail.
This happened, for example, in Trac #9106.
This is the reason for extending env with [f:k -> f:*], in the
definition of env' in niFixTvSubst
-}
niFixTvSubst :: TvSubstEnv -> TvSubst
-- Find the idempotent fixed point of the non-idempotent substitution
-- See Note [Finding the substitution fixpoint]
-- ToDo: use laziness instead of iteration?
niFixTvSubst env = f env
where
f env | not_fixpoint = f (mapVarEnv (substTy subst') env)
| otherwise = subst
where
not_fixpoint = foldVarSet ((||) . in_domain) False all_range_tvs
in_domain tv = tv `elemVarEnv` env
range_tvs = foldVarEnv (unionVarSet . tyVarsOfType) emptyVarSet env
all_range_tvs = closeOverKinds range_tvs
subst = mkTvSubst (mkInScopeSet all_range_tvs) env
-- env' extends env by replacing any free type with
-- that same tyvar with a substituted kind
-- See note [Finding the substitution fixpoint]
env' = extendVarEnvList env [ (rtv, mkTyVarTy $ setTyVarKind rtv $
substTy subst $ tyVarKind rtv)
| rtv <- varSetElems range_tvs
, not (in_domain rtv) ]
subst' = mkTvSubst (mkInScopeSet all_range_tvs) env'
niSubstTvSet :: TvSubstEnv -> TyVarSet -> TyVarSet
-- Apply the non-idempotent substitution to a set of type variables,
-- remembering that the substitution isn't necessarily idempotent
-- This is used in the occurs check, before extending the substitution
niSubstTvSet subst tvs
= foldVarSet (unionVarSet . get) emptyVarSet tvs
where
get tv = case lookupVarEnv subst tv of
Nothing -> unitVarSet tv
Just ty -> niSubstTvSet subst (tyVarsOfType ty)
{-
************************************************************************
* *
The workhorse
* *
************************************************************************
-}
unify :: Type -> Type -> UM ()
-- Respects newtypes, PredTypes
-- in unify, any NewTcApps/Preds should be taken at face value
unify (TyVarTy tv1) ty2 = uVar tv1 ty2
unify ty1 (TyVarTy tv2) = uVar tv2 ty1
unify ty1 ty2 | Just ty1' <- tcView ty1 = unify ty1' ty2
unify ty1 ty2 | Just ty2' <- tcView ty2 = unify ty1 ty2'
unify ty1 ty2
| Just (tc1, tys1) <- splitTyConApp_maybe ty1
, Just (tc2, tys2) <- splitTyConApp_maybe ty2
= if tc1 == tc2
then if isInjectiveTyCon tc1 Nominal
then unify_tys tys1 tys2
else don'tBeSoSure $ unify_tys tys1 tys2
else -- tc1 /= tc2
if isGenerativeTyCon tc1 Nominal && isGenerativeTyCon tc2 Nominal
then surelyApart
else maybeApart
-- Applications need a bit of care!
-- They can match FunTy and TyConApp, so use splitAppTy_maybe
-- NB: we've already dealt with type variables and Notes,
-- so if one type is an App the other one jolly well better be too
unify (AppTy ty1a ty1b) ty2
| Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
= do { unify ty1a ty2a
; unify ty1b ty2b }
unify ty1 (AppTy ty2a ty2b)
| Just (ty1a, ty1b) <- repSplitAppTy_maybe ty1
= do { unify ty1a ty2a
; unify ty1b ty2b }
unify (LitTy x) (LitTy y) | x == y = return ()
unify _ _ = surelyApart
-- ForAlls??
------------------------------
unify_tys :: [Type] -> [Type] -> UM ()
unify_tys orig_xs orig_ys
= go orig_xs orig_ys
where
go [] [] = return ()
go (x:xs) (y:ys) = do { unify x y
; go xs ys }
go _ _ = maybeApart -- See Note [Lists of different lengths are MaybeApart]
---------------------------------
uVar :: TyVar -- Type variable to be unified
-> Type -- with this type
-> UM ()
uVar tv1 ty
= do { subst <- umGetTvSubstEnv
-- Check to see whether tv1 is refined by the substitution
; case (lookupVarEnv subst tv1) of
Just ty' -> unify ty' ty -- Yes, call back into unify'
Nothing -> uUnrefined subst tv1 ty ty } -- No, continue
uUnrefined :: TvSubstEnv -- environment to extend (from the UM monad)
-> TyVar -- Type variable to be unified
-> Type -- with this type
-> Type -- (version w/ expanded synonyms)
-> UM ()
-- We know that tv1 isn't refined
uUnrefined subst tv1 ty2 ty2'
| Just ty2'' <- tcView ty2'
= uUnrefined subst tv1 ty2 ty2'' -- Unwrap synonyms
-- This is essential, in case we have
-- type Foo a = a
-- and then unify a ~ Foo a
uUnrefined subst tv1 ty2 (TyVarTy tv2)
| tv1 == tv2 -- Same type variable
= return ()
-- Check to see whether tv2 is refined
| Just ty' <- lookupVarEnv subst tv2
= uUnrefined subst tv1 ty' ty'
| otherwise
= do { -- So both are unrefined; unify the kinds
; unify (tyVarKind tv1) (tyVarKind tv2)
-- And then bind one or the other,
-- depending on which is bindable
-- NB: unlike TcUnify we do not have an elaborate sub-kinding
-- story. That is relevant only during type inference, and
-- (I very much hope) is not relevant here.
; b1 <- tvBindFlag tv1
; b2 <- tvBindFlag tv2
; let ty1 = TyVarTy tv1
; case (b1, b2) of
(Skolem, Skolem) -> maybeApart -- See Note [Unification with skolems]
(BindMe, _) -> extendSubst tv1 ty2
(_, BindMe) -> extendSubst tv2 ty1 }
uUnrefined subst tv1 ty2 ty2' -- ty2 is not a type variable
| tv1 `elemVarSet` niSubstTvSet subst (tyVarsOfType ty2')
= maybeApart -- Occurs check
-- See Note [Fine-grained unification]
| otherwise
= do { unify k1 k2
-- Note [Kinds Containing Only Literals]
; bindTv tv1 ty2 } -- Bind tyvar to the synonym if poss
where
k1 = tyVarKind tv1
k2 = typeKind ty2'
bindTv :: TyVar -> Type -> UM ()
bindTv tv ty -- ty is not a type variable
= do { b <- tvBindFlag tv
; case b of
Skolem -> maybeApart -- See Note [Unification with skolems]
BindMe -> extendSubst tv ty
}
{-
************************************************************************
* *
Binding decisions
* *
************************************************************************
-}
data BindFlag
= BindMe -- A regular type variable
| Skolem -- This type variable is a skolem constant
-- Don't bind it; it only matches itself
{-
************************************************************************
* *
Unification monad
* *
************************************************************************
-}
newtype UM a = UM { unUM :: (TyVar -> BindFlag)
-> TvSubstEnv
-> UnifyResultM (a, TvSubstEnv) }
instance Functor UM where
fmap = liftM
instance Applicative UM where
pure a = UM (\_tvs subst -> Unifiable (a, subst))
(<*>) = ap
instance Monad UM where
return = pure
fail _ = UM (\_tvs _subst -> SurelyApart) -- failed pattern match
m >>= k = UM (\tvs subst -> case unUM m tvs subst of
Unifiable (v, subst') -> unUM (k v) tvs subst'
MaybeApart (v, subst') ->
case unUM (k v) tvs subst' of
Unifiable (v', subst'') -> MaybeApart (v', subst'')
other -> other
SurelyApart -> SurelyApart)
-- returns an idempotent substitution
initUM :: (TyVar -> BindFlag) -> UM () -> UnifyResult
initUM badtvs um = fmap (niFixTvSubst . snd) $ unUM um badtvs emptyTvSubstEnv
tvBindFlag :: TyVar -> UM BindFlag
tvBindFlag tv = UM (\tv_fn subst -> Unifiable (tv_fn tv, subst))
-- | Extend the TvSubstEnv in the UM monad
extendSubst :: TyVar -> Type -> UM ()
extendSubst tv ty = UM (\_tv_fn subst -> Unifiable ((), extendVarEnv subst tv ty))
-- | Retrive the TvSubstEnv from the UM monad
umGetTvSubstEnv :: UM TvSubstEnv
umGetTvSubstEnv = UM $ \_tv_fn subst -> Unifiable (subst, subst)
-- | Converts any SurelyApart to a MaybeApart
don'tBeSoSure :: UM () -> UM ()
don'tBeSoSure um = UM $ \tv_fn subst -> case unUM um tv_fn subst of
SurelyApart -> MaybeApart ((), subst)
other -> other
maybeApart :: UM ()
maybeApart = UM (\_tv_fn subst -> MaybeApart ((), subst))
surelyApart :: UM a
surelyApart = UM (\_tv_fn _subst -> SurelyApart)
|
AlexanderPankiv/ghc
|
compiler/types/Unify.hs
|
Haskell
|
bsd-3-clause
| 29,646
|
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.Texturing.Specification
-- Copyright : (c) Sven Panne 2002-2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- This module corresponds to section 3.8.1 (Texture Image Specification),
-- section 3.8.2 (Alternate Texture Image Specification Commands), and section
-- 3.8.3 (Compressed Texture Images) of the OpenGL 2.1 specs.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.Texturing.Specification (
-- * Texture Targets
-- ** One-Dimensional Texture Targets
TextureTarget1D(..),
-- ** Two-Dimensional Texture Targets
TextureTarget2D(..),
TextureTarget2DMultisample(..),
TextureTargetCubeMap(..),
TextureTargetCubeMapFace(..),
-- ** Three-Dimensional Texture Targets
TextureTarget3D(..),
TextureTarget2DMultisampleArray(..),
-- ** Texture Buffer Target
TextureTargetBuffer(..),
-- ** Texture Target Classification
BindableTextureTarget,
ParameterizedTextureTarget,
OneDimensionalTextureTarget,
TwoDimensionalTextureTarget,
ThreeDimensionalTextureTarget,
QueryableTextureTarget,
GettableTextureTarget,
-- * Texture-related Data Types
Level, Border,
TexturePosition1D(..), TexturePosition2D(..), TexturePosition3D(..),
TextureSize1D(..), TextureSize2D(..), TextureSize3D(..),
-- * Texture Image Specification
texImage1D, texImage2D, texImage3D,
copyTexImage1D, copyTexImage2D,
texSubImage1D, texSubImage2D, texSubImage3D,
getTexImage,
-- * Alternate Texture Image Specification Commands
copyTexSubImage1D, copyTexSubImage2D, copyTexSubImage3D,
-- * Compressed Texture Images
CompressedTextureFormat(..), compressedTextureFormats,
CompressedPixelData(..),
compressedTexImage1D, compressedTexImage2D, compressedTexImage3D,
compressedTexSubImage1D, compressedTexSubImage2D, compressedTexSubImage3D,
getCompressedTexImage,
-- * Multisample Texture Images
SampleLocations(..), texImage2DMultisample, texImage3DMultisample,
-- * Implementation-Dependent Limits
maxTextureSize, maxCubeMapTextureSize, maxRectangleTextureSize,
max3DTextureSize, maxArrayTextureLayers, maxSampleMaskWords,
maxColorTextureSamples, maxDepthTextureSamples, maxIntegerSamples
) where
import Foreign.Ptr
import Graphics.Rendering.OpenGL.GL.CoordTrans
import Graphics.Rendering.OpenGL.GL.FramebufferObjects.RenderbufferTarget
import Graphics.Rendering.OpenGL.GL.GLboolean
import Graphics.Rendering.OpenGL.GL.PixelData
import Graphics.Rendering.OpenGL.GL.PixelRectangles
import Graphics.Rendering.OpenGL.GL.QueryUtils
import Graphics.Rendering.OpenGL.GL.StateVar
import Graphics.Rendering.OpenGL.GL.Texturing.PixelInternalFormat
import Graphics.Rendering.OpenGL.GL.Texturing.TextureTarget
import Graphics.Rendering.OpenGL.Raw
--------------------------------------------------------------------------------
type Level = GLint
type Border = GLint
newtype TexturePosition1D = TexturePosition1D GLint
deriving ( Eq, Ord, Show )
data TexturePosition2D = TexturePosition2D !GLint !GLint
deriving ( Eq, Ord, Show )
data TexturePosition3D = TexturePosition3D !GLint !GLint !GLint
deriving ( Eq, Ord, Show )
newtype TextureSize1D = TextureSize1D GLsizei
deriving ( Eq, Ord, Show )
data TextureSize2D = TextureSize2D !GLsizei !GLsizei
deriving ( Eq, Ord, Show )
data TextureSize3D = TextureSize3D !GLsizei !GLsizei !GLsizei
deriving ( Eq, Ord, Show )
--------------------------------------------------------------------------------
texImage1D :: OneDimensionalTextureTarget t => t -> Proxy -> Level -> PixelInternalFormat -> TextureSize1D -> Border -> PixelData a -> IO ()
texImage1D target proxy level int (TextureSize1D w) border pd =
withPixelData pd $
glTexImage1D
(marshalOneDimensionalTextureTarget proxy target)
level (marshalPixelInternalFormat int) w border
--------------------------------------------------------------------------------
texImage2D :: TwoDimensionalTextureTarget t => t -> Proxy -> Level -> PixelInternalFormat -> TextureSize2D -> Border -> PixelData a -> IO ()
texImage2D target proxy level int (TextureSize2D w h) border pd =
withPixelData pd $
glTexImage2D (marshalTwoDimensionalTextureTarget proxy target) level (marshalPixelInternalFormat int) w h border
--------------------------------------------------------------------------------
texImage3D :: ThreeDimensionalTextureTarget t => t -> Proxy -> Level -> PixelInternalFormat -> TextureSize3D -> Border -> PixelData a -> IO ()
texImage3D target proxy level int (TextureSize3D w h d) border pd =
withPixelData pd $
glTexImage3D
(marshalThreeDimensionalTextureTarget proxy target)
level (marshalPixelInternalFormat int) w h d border
--------------------------------------------------------------------------------
getTexImage :: GettableTextureTarget t => t -> Level -> PixelData a -> IO ()
getTexImage target level pd =
withPixelData pd $
glGetTexImage (marshalGettableTextureTarget target) level
--------------------------------------------------------------------------------
copyTexImage1D :: OneDimensionalTextureTarget t => t -> Level -> PixelInternalFormat -> Position -> TextureSize1D -> Border -> IO ()
copyTexImage1D target level int (Position x y) (TextureSize1D w) border =
glCopyTexImage1D
(marshalOneDimensionalTextureTarget NoProxy target) level
(marshalPixelInternalFormat' int) x y w border
--------------------------------------------------------------------------------
copyTexImage2D :: TwoDimensionalTextureTarget t => t -> Level -> PixelInternalFormat -> Position -> TextureSize2D -> Border -> IO ()
copyTexImage2D target level int (Position x y) (TextureSize2D w h) border =
glCopyTexImage2D
(marshalTwoDimensionalTextureTarget NoProxy target) level
(marshalPixelInternalFormat' int) x y w h border
--------------------------------------------------------------------------------
texSubImage1D :: OneDimensionalTextureTarget t => t -> Level -> TexturePosition1D -> TextureSize1D -> PixelData a -> IO ()
texSubImage1D target level (TexturePosition1D xOff) (TextureSize1D w) pd =
withPixelData pd $
glTexSubImage1D (marshalOneDimensionalTextureTarget NoProxy target) level xOff w
--------------------------------------------------------------------------------
texSubImage2D :: TwoDimensionalTextureTarget t => t -> Level -> TexturePosition2D -> TextureSize2D -> PixelData a -> IO ()
texSubImage2D target level (TexturePosition2D xOff yOff) (TextureSize2D w h) pd =
withPixelData pd $
glTexSubImage2D (marshalTwoDimensionalTextureTarget NoProxy target) level xOff yOff w h
--------------------------------------------------------------------------------
texSubImage3D :: ThreeDimensionalTextureTarget t => t -> Level -> TexturePosition3D -> TextureSize3D -> PixelData a -> IO ()
texSubImage3D target level (TexturePosition3D xOff yOff zOff) (TextureSize3D w h d) pd =
withPixelData pd $
glTexSubImage3D (marshalThreeDimensionalTextureTarget NoProxy target) level xOff yOff zOff w h d
--------------------------------------------------------------------------------
copyTexSubImage1D :: OneDimensionalTextureTarget t => t -> Level -> TexturePosition1D -> Position -> TextureSize1D -> IO ()
copyTexSubImage1D target level (TexturePosition1D xOff) (Position x y) (TextureSize1D w) =
glCopyTexSubImage1D (marshalOneDimensionalTextureTarget NoProxy target) level xOff x y w
--------------------------------------------------------------------------------
copyTexSubImage2D :: TwoDimensionalTextureTarget t => t -> Level -> TexturePosition2D -> Position -> TextureSize2D -> IO ()
copyTexSubImage2D target level (TexturePosition2D xOff yOff) (Position x y) (TextureSize2D w h) =
glCopyTexSubImage2D (marshalTwoDimensionalTextureTarget NoProxy target) level xOff yOff x y w h
--------------------------------------------------------------------------------
copyTexSubImage3D :: ThreeDimensionalTextureTarget t => t -> Level -> TexturePosition3D -> Position -> TextureSize2D -> IO ()
copyTexSubImage3D target level (TexturePosition3D xOff yOff zOff) (Position x y) (TextureSize2D w h) =
glCopyTexSubImage3D (marshalThreeDimensionalTextureTarget NoProxy target) level xOff yOff zOff x y w h
--------------------------------------------------------------------------------
newtype CompressedTextureFormat = CompressedTextureFormat GLenum
deriving ( Eq, Ord, Show )
compressedTextureFormats :: GettableStateVar [CompressedTextureFormat]
compressedTextureFormats =
makeGettableStateVar $ do
n <- getInteger1 fromIntegral GetNumCompressedTextureFormats
getEnumN CompressedTextureFormat GetCompressedTextureFormats n
--------------------------------------------------------------------------------
data CompressedPixelData a =
CompressedPixelData !CompressedTextureFormat GLsizei (Ptr a)
deriving ( Eq, Ord, Show )
withCompressedPixelData ::
CompressedPixelData a -> (GLenum -> GLsizei -> Ptr a -> b) -> b
withCompressedPixelData
(CompressedPixelData (CompressedTextureFormat fmt) size ptr) f =
f fmt size ptr
--------------------------------------------------------------------------------
compressedTexImage1D :: OneDimensionalTextureTarget t => t -> Proxy -> Level -> TextureSize1D -> Border -> CompressedPixelData a -> IO ()
compressedTexImage1D target proxy level (TextureSize1D w) border cpd =
withCompressedPixelData cpd $ \fmt ->
glCompressedTexImage1D
(marshalOneDimensionalTextureTarget proxy target) level fmt w border
--------------------------------------------------------------------------------
-- Note that the spec currently disallows TextureRectangle, but then again the
-- extension specification explicitly allows a relaxation in the future.
compressedTexImage2D :: TwoDimensionalTextureTarget t => t -> Proxy -> Level -> TextureSize2D -> Border -> CompressedPixelData a -> IO ()
compressedTexImage2D target proxy level (TextureSize2D w h) border cpd =
withCompressedPixelData cpd $ \fmt ->
glCompressedTexImage2D (marshalTwoDimensionalTextureTarget proxy target) level fmt w h border
--------------------------------------------------------------------------------
compressedTexImage3D :: ThreeDimensionalTextureTarget t => t -> Proxy -> Level -> TextureSize3D -> Border -> CompressedPixelData a -> IO ()
compressedTexImage3D target proxy level (TextureSize3D w h d) border cpd =
withCompressedPixelData cpd $ \fmt ->
glCompressedTexImage3D
(marshalThreeDimensionalTextureTarget proxy target) level fmt w h d border
--------------------------------------------------------------------------------
getCompressedTexImage :: GettableTextureTarget t => t -> Level -> Ptr a -> IO ()
getCompressedTexImage = glGetCompressedTexImage . marshalGettableTextureTarget
--------------------------------------------------------------------------------
compressedTexSubImage1D :: OneDimensionalTextureTarget t => t -> Level -> TexturePosition1D -> TextureSize1D -> CompressedPixelData a -> IO ()
compressedTexSubImage1D target level (TexturePosition1D xOff) (TextureSize1D w) cpd =
withCompressedPixelData cpd $
glCompressedTexSubImage1D (marshalOneDimensionalTextureTarget NoProxy target) level xOff w
--------------------------------------------------------------------------------
compressedTexSubImage2D :: TwoDimensionalTextureTarget t => t -> Level -> TexturePosition2D -> TextureSize2D -> CompressedPixelData a -> IO ()
compressedTexSubImage2D target level (TexturePosition2D xOff yOff) (TextureSize2D w h) cpd =
withCompressedPixelData cpd $
glCompressedTexSubImage2D (marshalTwoDimensionalTextureTarget NoProxy target) level xOff yOff w h
--------------------------------------------------------------------------------
-- see texImage3D, but no proxies
compressedTexSubImage3D :: ThreeDimensionalTextureTarget t => t -> Level -> TexturePosition3D -> TextureSize3D -> CompressedPixelData a -> IO ()
compressedTexSubImage3D target level (TexturePosition3D xOff yOff zOff) (TextureSize3D w h d) cpd =
withCompressedPixelData cpd $
glCompressedTexSubImage3D (marshalThreeDimensionalTextureTarget NoProxy target) level xOff yOff zOff w h d
--------------------------------------------------------------------------------
data SampleLocations =
FlexibleSampleLocations
| FixedSampleLocations
deriving ( Eq, Ord, Show )
marshalSampleLocations :: SampleLocations -> GLboolean
marshalSampleLocations = marshalGLboolean . (FixedSampleLocations ==)
{-
unmarshalSampleLocations :: GLboolean -> SampleLocations
unmarshalSampleLocations x =
if unmarshalGLboolean x
then FixedSampleLocations
else FlexibleSampleLocations
-}
--------------------------------------------------------------------------------
texImage2DMultisample :: TextureTarget2DMultisample
-> Proxy
-> Samples
-> PixelInternalFormat
-> TextureSize2D
-> SampleLocations
-> IO ()
texImage2DMultisample target proxy (Samples s) int (TextureSize2D w h) loc =
glTexImage2DMultisample
(marshalMultisample proxy target) s (marshalPixelInternalFormat int)
w h (marshalSampleLocations loc)
marshalMultisample :: ParameterizedTextureTarget t => Proxy -> t -> GLenum
marshalMultisample proxy = case proxy of
NoProxy -> marshalParameterizedTextureTarget
Proxy -> marshalParameterizedTextureTargetProxy
texImage3DMultisample :: TextureTarget2DMultisampleArray
-> Proxy
-> Samples
-> PixelInternalFormat
-> TextureSize3D
-> SampleLocations
-> IO ()
texImage3DMultisample target proxy (Samples s) int (TextureSize3D w h d) loc =
glTexImage3DMultisample
(marshalMultisample proxy target) s (marshalPixelInternalFormat int)
w h d (marshalSampleLocations loc)
--------------------------------------------------------------------------------
maxTextureSize :: GettableStateVar GLsizei
maxTextureSize = maxTextureSizeWith GetMaxTextureSize
maxCubeMapTextureSize :: GettableStateVar GLsizei
maxCubeMapTextureSize = maxTextureSizeWith GetMaxCubeMapTextureSize
maxRectangleTextureSize :: GettableStateVar GLsizei
maxRectangleTextureSize = maxTextureSizeWith GetMaxRectangleTextureSize
max3DTextureSize :: GettableStateVar GLsizei
max3DTextureSize = maxTextureSizeWith GetMax3DTextureSize
maxArrayTextureLayers :: GettableStateVar GLsizei
maxArrayTextureLayers = maxTextureSizeWith GetMaxArrayTextureLayers
maxSampleMaskWords :: GettableStateVar GLsizei
maxSampleMaskWords = maxTextureSizeWith GetMaxSampleMaskWords
maxColorTextureSamples :: GettableStateVar GLsizei
maxColorTextureSamples = maxTextureSizeWith GetMaxColorTextureSamples
maxDepthTextureSamples :: GettableStateVar GLsizei
maxDepthTextureSamples = maxTextureSizeWith GetMaxDepthTextureSamples
maxIntegerSamples :: GettableStateVar GLsizei
maxIntegerSamples = maxTextureSizeWith GetMaxIntegerSamples
maxTextureSizeWith :: PName1I -> GettableStateVar GLsizei
maxTextureSizeWith = makeGettableStateVar . getInteger1 fromIntegral
|
IreneKnapp/direct-opengl
|
Graphics/Rendering/OpenGL/GL/Texturing/Specification.hs
|
Haskell
|
bsd-3-clause
| 15,581
|
{- data size display and parsing
-
- Copyright 2011 Joey Hess <id@joeyh.name>
-
- License: BSD-2-clause
-
-
- And now a rant:
-
- In the beginning, we had powers of two, and they were good.
-
- Disk drive manufacturers noticed that some powers of two were
- sorta close to some powers of ten, and that rounding down to the nearest
- power of ten allowed them to advertise their drives were bigger. This
- was sorta annoying.
-
- Then drives got big. Really, really big. This was good.
-
- Except that the small rounding error perpretrated by the drive
- manufacturers suffered the fate of a small error, and became a large
- error. This was bad.
-
- So, a committee was formed. And it arrived at a committee-like decision,
- which satisfied noone, confused everyone, and made the world an uglier
- place. As with all committees, this was meh.
-
- And the drive manufacturers happily continued selling drives that are
- increasingly smaller than you'd expect, if you don't count on your
- fingers. But that are increasingly too big for anyone to much notice.
- This caused me to need git-annex.
-
- Thus, I use units here that I loathe. Because if I didn't, people would
- be confused that their drives seem the wrong size, and other people would
- complain at me for not being standards compliant. And we call this
- progress?
-}
module Utility.DataUnits (
dataUnits,
storageUnits,
memoryUnits,
bandwidthUnits,
oldSchoolUnits,
Unit(..),
roughSize,
compareSizes,
readSize
) where
import Data.List
import Data.Char
import Utility.HumanNumber
type ByteSize = Integer
type Name = String
type Abbrev = String
data Unit = Unit ByteSize Abbrev Name
deriving (Ord, Show, Eq)
dataUnits :: [Unit]
dataUnits = storageUnits ++ memoryUnits
{- Storage units are (stupidly) powers of ten. -}
storageUnits :: [Unit]
storageUnits =
[ Unit (p 8) "YB" "yottabyte"
, Unit (p 7) "ZB" "zettabyte"
, Unit (p 6) "EB" "exabyte"
, Unit (p 5) "PB" "petabyte"
, Unit (p 4) "TB" "terabyte"
, Unit (p 3) "GB" "gigabyte"
, Unit (p 2) "MB" "megabyte"
, Unit (p 1) "kB" "kilobyte" -- weird capitalization thanks to committe
, Unit (p 0) "B" "byte"
]
where
p :: Integer -> Integer
p n = 1000^n
{- Memory units are (stupidly named) powers of 2. -}
memoryUnits :: [Unit]
memoryUnits =
[ Unit (p 8) "YiB" "yobibyte"
, Unit (p 7) "ZiB" "zebibyte"
, Unit (p 6) "EiB" "exbibyte"
, Unit (p 5) "PiB" "pebibyte"
, Unit (p 4) "TiB" "tebibyte"
, Unit (p 3) "GiB" "gibibyte"
, Unit (p 2) "MiB" "mebibyte"
, Unit (p 1) "KiB" "kibibyte"
, Unit (p 0) "B" "byte"
]
where
p :: Integer -> Integer
p n = 2^(n*10)
{- Bandwidth units are only measured in bits if you're some crazy telco. -}
bandwidthUnits :: [Unit]
bandwidthUnits = error "stop trying to rip people off"
{- Do you yearn for the days when men were men and megabytes were megabytes? -}
oldSchoolUnits :: [Unit]
oldSchoolUnits = zipWith (curry mingle) storageUnits memoryUnits
where
mingle (Unit _ a n, Unit s' _ _) = Unit s' a n
{- approximate display of a particular number of bytes -}
roughSize :: [Unit] -> Bool -> ByteSize -> String
roughSize units short i
| i < 0 = '-' : findUnit units' (negate i)
| otherwise = findUnit units' i
where
units' = sortBy (flip compare) units -- largest first
findUnit (u@(Unit s _ _):us) i'
| i' >= s = showUnit i' u
| otherwise = findUnit us i'
findUnit [] i' = showUnit i' (last units') -- bytes
showUnit x (Unit size abbrev name) = s ++ " " ++ unit
where
v = (fromInteger x :: Double) / fromInteger size
s = showImprecise 2 v
unit
| short = abbrev
| s == "1" = name
| otherwise = name ++ "s"
{- displays comparison of two sizes -}
compareSizes :: [Unit] -> Bool -> ByteSize -> ByteSize -> String
compareSizes units abbrev old new
| old > new = roughSize units abbrev (old - new) ++ " smaller"
| old < new = roughSize units abbrev (new - old) ++ " larger"
| otherwise = "same"
{- Parses strings like "10 kilobytes" or "0.5tb". -}
readSize :: [Unit] -> String -> Maybe ByteSize
readSize units input
| null parsednum || null parsedunit = Nothing
| otherwise = Just $ round $ number * fromIntegral multiplier
where
(number, rest) = head parsednum
multiplier = head parsedunit
unitname = takeWhile isAlpha $ dropWhile isSpace rest
parsednum = reads input :: [(Double, String)]
parsedunit = lookupUnit units unitname
lookupUnit _ [] = [1] -- no unit given, assume bytes
lookupUnit [] _ = []
lookupUnit (Unit s a n:us) v
| a ~~ v || n ~~ v = [s]
| plural n ~~ v || a ~~ byteabbrev v = [s]
| otherwise = lookupUnit us v
a ~~ b = map toLower a == map toLower b
plural n = n ++ "s"
byteabbrev a = a ++ "b"
|
avengerpenguin/propellor
|
src/Utility/DataUnits.hs
|
Haskell
|
bsd-2-clause
| 4,700
|
{-# LANGUAGE LambdaCase, RankNTypes, ScopedTypeVariables #-}
module Stream.Folding.Prelude (
break
, concats
, cons
, drop
, lenumFrom
, lenumFromStepN
, lenumFromTo
, lenumFromToStep
, filter
, filterM
, foldl
, iterate
, iterateM
, joinFold
, map
, mapM
, maps
, repeat
, repeatM
, replicate
, replicateM
, scanr
, span
, splitAt
, splitAt_
, sum
, take
, takeWhile
, yield ) where
import Stream.Types
import Control.Monad hiding (filterM, mapM, replicateM)
import Data.Functor.Identity
import Control.Monad.Trans
import qualified System.IO as IO
import Prelude hiding (map, filter, drop, take, sum
, iterate, repeat, replicate, splitAt
, takeWhile, enumFrom, enumFromTo
, mapM, scanr, span, break, foldl)
-- ---------------
-- ---------------
-- Prelude
-- ---------------
-- ---------------
-- ---------------
-- yield
-- ---------------
yield :: Monad m => a -> Folding (Of a) m ()
yield r = Folding (\construct wrap done -> construct (r :> done ()))
{-# INLINE yield #-}
-- ---------------
-- sum
-- ---------------
sum :: (Monad m, Num a) => Folding (Of a) m () -> m a
sum = \(Folding phi) -> phi (\(n :> mm) -> mm >>= \m -> return (m+n))
join
(\_ -> return 0)
{-# INLINE sum #-}
-- ---------------
-- replicate
-- ---------------
replicate :: Monad m => Int -> a -> Folding (Of a) m ()
replicate n a = Folding (take_ (repeat_ a) n)
{-# INLINE replicate #-}
replicateM :: Monad m => Int -> m a -> Folding (Of a) m ()
replicateM n a = Folding (take_ (repeatM_ a) n)
{-# INLINE replicateM #-}
-- ---------------
-- iterate
-- ---------------
-- this can clearly be made non-recursive with eg numbers
iterate_ :: (a -> a) -> a -> Folding_ (Of a) m r
iterate_ f a = \construct wrap done ->
construct (a :> iterate_ f (f a) construct wrap done)
{-# INLINE iterate_ #-}
iterate :: (a -> a) -> a -> Folding (Of a) m r
iterate f a = Folding (iterate_ f a)
{-# INLINE iterate #-}
iterateM_ :: Monad m => (a -> m a) -> m a -> Folding_ (Of a) m r
iterateM_ f ma = \construct wrap done ->
let loop mx = wrap $ liftM (\x -> construct (x :> loop (f x))) mx
in loop ma
{-# INLINE iterateM_ #-}
iterateM :: Monad m => (a -> m a) -> m a -> Folding (Of a) m r
iterateM f a = Folding (iterateM_ f a)
{-# INLINE iterateM #-}
-- ---------------
-- repeat
-- ---------------
repeat_ :: a -> Folding_ (Of a) m r
repeat_ = \a construct wrap done ->
let loop = construct (a :> loop) in loop
{-# INLINE repeat_ #-}
repeat :: a -> Folding (Of a) m r
repeat a = Folding (repeat_ a)
{-# INLINE repeat #-}
repeatM_ :: Monad m => m a -> Folding_ (Of a) m r
repeatM_ ma = \construct wrap done ->
let loop = liftM (\a -> construct (a :> wrap loop)) ma in wrap loop
{-# INLINE repeatM_ #-}
repeatM :: Monad m => m a -> Folding (Of a) m r
repeatM ma = Folding (repeatM_ ma)
{-# INLINE repeatM #-}
-- ---------------
-- filter
-- ---------------
filter :: Monad m => (a -> Bool) -> Folding (Of a) m r -> Folding (Of a) m r
filter pred = \(Folding phi) -> Folding (filter_ phi pred)
{-# INLINE filter #-}
filter_ :: (Monad m) => Folding_ (Of a) m r -> (a -> Bool) -> Folding_ (Of a) m r
filter_ phi pred0 = \construct wrap done ->
phi (\aa@(a :> x) pred-> if pred a then construct (a :> x pred) else x pred)
(\mp pred -> wrap $ liftM ($pred) mp)
(\r pred -> done r)
pred0
{-# INLINE filter_ #-}
filterM_ :: (Monad m) => Folding_ (Of a) m r -> (a -> m Bool) -> Folding_ (Of a) m r
filterM_ phi pred0 = \construct wrap done ->
phi ( \aa@(a :> x) pred -> wrap $ do p <- pred a
return $ if p then construct (a :> x pred)
else x pred )
( \mp pred -> wrap $ liftM ($pred) mp )
( \r pred -> done r )
pred0
{-# INLINE filterM_ #-}
filterM :: Monad m => (a -> m Bool) -> Folding (Of a) m r -> Folding (Of a) m r
filterM pred = \(Folding phi) -> Folding (filterM_ phi pred)
-- ---------------
-- drop
-- ---------------
drop :: Monad m => Int -> Folding (Of a) m r -> Folding (Of a) m r
drop n = \(Folding phi) -> Folding (drop_ phi n)
{-# INLINE drop #-}
jdrop :: Monad m => Int -> Folding_ (Of a) m r -> Folding_ (Of a) m r
jdrop = \m phi construct wrap done ->
phi
(\(a :> fn) n -> if n <= m then fn (n+1) else construct (a :> (fn (n+1))))
(\m n -> wrap (m >>= \fn -> return (fn n)))
(\r _ -> done r)
1
{-# INLINE jdrop #-}
drop_ :: Monad m => Folding_ (Of a) m r -> Int -> Folding_ (Of a) m r
drop_ phi n0 = \construct wrap done ->
phi
(\(a :> fn) n -> if n >= 0 then fn (n-1) else construct (a :> (fn (n-1))))
(\m n -> wrap (m >>= \fn -> return (fn n)))
(\r _ -> done r)
n0
{-# INLINE drop_ #-}
-- ---------------
-- concats concat/join
-- ---------------
concats :: Monad m => Folding (Folding (Of a) m) m r -> Folding (Of a) m r
concats (Folding phi) = Folding $ \construct wrap done ->
phi (\(Folding phi') -> phi' construct wrap id)
wrap
done
{-# INLINE concats #-}
concats1 :: Monad m => Folding_ (Folding (Of a) m) m r -> Folding_ (Of a) m r
concats1 phi = \construct wrap done ->
phi (\(Folding phi') -> phi' construct wrap id)
wrap
done
{-# INLINE concats1 #-}
concats0 :: Monad m => Folding_ (Folding_ (Of a) m) m r -> Folding_ (Of a) m r
concats0 phi = \construct wrap done ->
phi (\phi' -> phi' construct wrap id)
wrap
done
{-# INLINE concats0 #-}
joinFold_ :: (Monad m, Functor f) => Folding_ f m (Folding_ f m r) -> Folding_ f m r
joinFold_ phi = \c w d -> phi c w (\folding -> folding c w d)
{-# INLINE joinFold_ #-}
joinFold (Folding phi) = Folding $ \c w d ->
phi c w (\folding -> getFolding folding c w d)
{-# INLINE joinFold #-}
-- ---------------
-- map
-- ---------------
map :: Monad m => (a -> b) -> Folding (Of a) m r -> Folding (Of b) m r
map f = \(Folding phi) -> Folding (map_ phi f)
{-# INLINE map #-}
map_ :: Monad m => Folding_ (Of a) m r -> (a -> b) -> Folding_ (Of b) m r
map_ phi f0 = \construct wrap done ->
phi (\(a :> x) f -> construct (f a :> x f))
(\mf f -> wrap (liftM ($f) mf))
(\r f -> done r)
f0
{-# INLINE map_ #-}
mapM :: Monad m => (a -> m b) -> Folding (Of a) m r -> Folding (Of b) m r
mapM f = \(Folding phi) -> Folding (mapM__ phi f)
where
mapM__ :: Monad m => Folding_ (Of a) m r -> (a -> m b) -> Folding_ (Of b) m r
mapM__ phi f0 = \construct wrap done ->
phi (\(a :> x) f -> wrap $ liftM (\z -> construct (z :> x f)) (f a) )
(\mff f -> wrap (liftM ($f) mff))
(\r _ -> done r)
f0
{-# INLINE mapM__ #-}
{-# INLINE mapM #-}
maps :: (Monad m, Functor g) => (forall x . f x -> g x) -> Folding f m r -> Folding g m r
maps morph (Folding phi) = Folding $ \construct wrap done ->
phi (construct . morph)
wrap
done
-- ---------------
-- take
-- ---------------
take_ :: (Monad m, Functor f) => Folding_ f m r -> Int -> Folding_ f m ()
take_ phi n = \construct wrap done -> phi
(\fx n -> if n <= 0 then done () else construct (fmap ($(n-1)) fx))
(\mx n -> if n <= 0 then done () else wrap (liftM ($n) mx))
(\r n -> done ())
n
{-# INLINE take_ #-}
take :: (Monad m, Functor f) => Int -> Folding f m r -> Folding f m ()
take n = \(Folding phi) -> Folding (take_ phi n)
{-# INLINE take #-}
takeWhile :: Monad m => (a -> Bool) -> Folding (Of a) m r -> Folding (Of a) m ()
takeWhile pred = \(Folding fold) -> Folding (takeWhile_ fold pred)
{-# INLINE takeWhile #-}
takeWhile_ :: Monad m => Folding_ (Of a) m r -> (a -> Bool) -> Folding_ (Of a) m ()
takeWhile_ phi pred0 = \construct wrap done ->
phi (\(a :> fn) p pred_ -> if not (pred_ a)
then done ()
else construct (a :> (fn True pred_)))
(\m p pred_ -> if not p then done () else wrap (liftM (\fn -> fn p pred_) m))
(\r p pred_ -> done ())
True
pred0
{-# INLINE takeWhile_ #-}
-- -------
lenumFrom n = \construct wrap done ->
let loop m = construct (m :> loop (succ m)) in loop n
lenumFromTo n m = \construct wrap done ->
let loop k = if k <= m then construct (k :> loop (succ k))
else done ()
in loop n
lenumFromToStep n m k = \construct wrap done ->
let loop p = if p <= k then construct (p :> loop (p + m))
else done ()
in loop n
lenumFromStepN start step n = \construct wrap done ->
let loop p 0 = done ()
loop p now = construct (p :> loop (p + step) (now-1))
in loop start n
foldl_ :: Monad m => Folding_ (Of a) m r -> (b -> a -> b) -> b -> m b
foldl_ phi = \ op b0 ->
phi (\(a :> fn) b -> fn $! flip op a $! b)
(\mf b -> mf >>= \f -> f b)
(\_ b -> return $! b)
b0
{-# INLINE foldl_ #-}
--
foldl :: Monad m => (b -> a -> b) -> b -> Folding (Of a) m r -> m b
foldl op b = \(Folding phi) -> foldl_ phi op b
{-# INLINE foldl #-}
jscanr :: Monad m => (a -> b -> b) -> b
-> Folding_ (Of a) m r -> Folding_ (Of b) m r
jscanr op b phi = phi
(\(a :> fx) b c w d -> c (b :> fx (op a b) c w d))
(\mfx b c w d -> w (liftM (\fx -> c (b :> fx b c w d)) mfx))
(\r b c w d -> c (b :> d r))
b
{-# INLINE jscanr #-}
scanr :: Monad m => (a -> b -> b) -> b
-> Folding (Of a) m r -> Folding (Of b) m r
scanr op b = \(Folding phi) -> Folding (lscanr_ phi op b)
lscanr_ :: Monad m => Folding_ (Of a) m r
-> (a -> b -> b) -> b -> Folding_ (Of b) m r
lscanr_ phi = phi
(\(a :> fx) op b c w d -> c (b :> fx op (op a b) c w d))
(\mfx op b c w d -> w (liftM (\fx -> c (b :> fx op b c w d)) mfx))
(\r op b c w d -> c (b :> d r))
{-# INLINE lscanr_ #-}
-----
chunksOf :: Monad m
=> Int
-> Folding (Of a) m r
-> Folding (Folding (Of a) m) m r
chunksOf = undefined
{-# INLINE chunksOf #-}
chunksOf_ :: Monad m
=> Folding_ (Of a) m r
-> Int
-> Folding_ (Folding_ (Of a) m) m r
chunksOf_ phi n = \construct wrap done -> undefined
-- --------
-- cons
-- --------
cons :: Monad m => a -> Folding (Of a) m r -> Folding (Of a) m r
cons a_ (Folding phi) = Folding $ \construct wrap done ->
phi (\(a :> a2p) a0 -> construct (a0 :> a2p a)
)
(\m a0 -> wrap $ liftM ($ a0) m
)
(\r a0 -> construct (a0 :> done r)
)
a_
-- --------
-- span
-- --------
span :: Monad m => (a -> Bool) -> Folding (Of a) m r
-> Folding (Of a) m (Folding (Of a) m r)
span pred0 (Folding phi) =
phi
(\ (a :> folding) ->
\pred ->
if pred a
then Folding $ \construct wrap done ->
construct (a :> getFolding (folding pred) construct wrap done)
else Folding $ \construct wrap done ->
done $ a `cons` joinFold (folding pred)
)
(\m ->
\pred ->
Folding $ \c w r ->
w (m >>= \folding -> return $ getFolding (folding pred) c w r)
)
(\r ->
\pred ->
Folding $ \construct wrap done ->
done (Folding $ \c w d -> d r)
)
pred0
{-# INLINE span #-}
-- --------
-- break
-- --------
break
:: Monad m =>
(a -> Bool)
-> Folding (Of a) m r -> Folding (Of a) m (Folding (Of a) m r)
break predicate = span (not . predicate)
-- --------
-- splitAt
-- --------
splitAt_ :: Monad m => Int -> Folding (Of a) m r
-> Folding (Of a) m (Folding (Of a) m r)
splitAt_ m (Folding phi) =
phi
(\ (a :> n2prod) n ->
if n > (0 :: Int)
then Folding $ \construct wrap done ->
construct (a :> getFolding (n2prod (n-1)) construct wrap done)
else Folding $ \construct wrap done ->
done $ a `cons` joinFold (n2prod (n))
)
(\m n -> Folding $ \c w r -> w (m >>= \n2fold -> return $ getFolding (n2fold n) c w r)
)
(\r n -> Folding $ \construct wrap done -> done (Folding $ \c w d -> d r)
)
m
{-# INLINE splitAt_ #-}
splitAt :: (Monad m, Functor f) => Int -> Folding f m r
-> Folding f m (Folding f m r)
splitAt m (Folding phi) =
phi
(\ fold n -> -- fold :: f (Int -> Folding f m (Folding f m r))
if n > (0 :: Int)
then Folding $ \construct wrap done ->
construct $ fmap (\f -> getFolding (f (n-1))
construct
wrap
done)
fold
else Folding $ \construct wrap done ->
done $ Folding $ \c w d ->
c $ fmap (\f -> getFolding (f n)
c
w
(\(Folding psi) -> psi c w d))
fold
)
(\m n -> Folding $ \c w r -> w (m >>= \n2fold -> return $ getFolding (n2fold n) c w r)
)
(\r n -> Folding $ \construct wrap done -> done (Folding $ \c w d -> d r)
)
m
{-# INLINE splitAt #-}
j :: (Monad m, Functor f) =>
f (Folding f m (Folding f m r)) -> Folding f m r
j ffolding =
Folding $ \cons w nil ->
cons $ fmap (\f -> getFolding f cons w (\(Folding psi) -> psi cons w nil))
ffolding
|
haskell-streaming/streaming
|
benchmarks/old/Stream/Folding/Prelude.hs
|
Haskell
|
bsd-3-clause
| 13,598
|
{-# LANGUAGE PackageImports #-}
import "devel-example" DevelExample (develMain)
main :: IO ()
main = develMain
|
s9gf4ult/yesod
|
yesod-bin/devel-example/app/devel.hs
|
Haskell
|
mit
| 112
|
<?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="sq-AL">
<title>Script Console</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
kingthorin/zap-extensions
|
addOns/scripts/src/main/javahelp/org/zaproxy/zap/extension/scripts/resources/help_sq_AL/helpset_sq_AL.hs
|
Haskell
|
apache-2.0
| 959
|
module X (x, D1(..), D2(..))
where
data D1 = D { f :: D2 } -- deriving Show
data D2 = A | B -- deriving Show
x :: D1
x = D { f = A }
|
olsner/ghc
|
testsuite/tests/driver/recomp010/X1.hs
|
Haskell
|
bsd-3-clause
| 137
|
-- Test for trac #2956
module TH_sections where
two :: Int
two = $( [| (1 +) 1 |] )
three :: Int
three = $( [| (+ 2) 1 |] )
|
urbanslug/ghc
|
testsuite/tests/th/TH_sections.hs
|
Haskell
|
bsd-3-clause
| 129
|
module Oczor.CodeGen.CodeGenJs where
import Oczor.CodeGen.Utl
codeGen :: Ast -> Doc
codeGen = x
where
x = cata $ \case
NoneF -> empty
UniqObjectF {} -> text "{}"
CodeF x -> text x
NotEqualF x y -> sep [x, text "!=", y]
EqualF x y -> sep [x, text "==", y]
LitF value -> lit value
IdentF name -> ident name
VarF name ast -> stmt [text "var", text name, equals, ast]
SetF astl astr -> stmt [astl, equals, astr]
ThrowF error -> stmt [text "throw", dquotes $ text error]
IfF p l r -> hcat [text "if", parens p] <> bracesNest l <> if onull r then empty else text "else" <> bracesNest r
ReturnF ast -> stmt [text "return", ast]
FieldF ast name -> field ast name
HasFieldF ast name -> sep [field ast name, text "!==", text "undefined"]
ObjectF list -> bracesNest $ punctuate comma (list <&> (\(name,ast) -> hsep [ident name, text ":", ast]))
FunctionF params body -> func params body
ScopeF list y -> parens (func [] (list ++ [text "return" <+> y]) ) <> parens empty
CallF name args -> name <> parens (hcat $ punctuate comma args)
OperatorF name param -> (hsep $ case param of {[x] -> [text name, x]; [x,y] -> [x,text name, y]} )
ArrayF list -> jsArray list
ConditionOperatorF astb astl astr -> parens $ hsep [astb, text "?", astl, text ":", astr]
BoolAndsF list -> parens $ hcat $ punctuate (text " && ") list
StmtListF list -> vcat list
ParensF x -> parens x
LabelF x y -> stmt [text "var", text x, equals, y]
func params body = hcat [text "function", parens $ hcat $ punctuate comma (params <&> text) ] <> bracesNest body
lit = createLit show "null" ("true", "false")
keywords = setFromList ["false", "true", "null", "abstract", "arguments", "boolean", "break", "byte case", "catch", "char", "class", "const continue", "debugger", "default", "delete", "do double", "else", "enum", "eval", "export extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements import", "in", "instanceof", "int", "interface let", "long", "native", "new", "null package", "private", "protected", "public", "return short", "static", "super", "switch", "synchronized this", "throw", "throws", "transient", "true try", "typeof", "var", "void", "volatile while", "with", "yield"]
ident = createIdent keywords
stmt x = hsep x <> text ";"
field ast name = ast <> dot <> ident name
|
ptol/oczor
|
src/Oczor/CodeGen/CodeGenJs.hs
|
Haskell
|
mit
| 2,395
|
import Test.HUnit
import Q11
import Q12
assertEqualIntList :: String -> [Int] -> [Int] -> Assertion
assertEqualIntList = assertEqual
test1 = TestCase (assertEqualIntList "decodeModified [] should be [] ." ([] ) (decodeModified [] ))
test2 = TestCase (assertEqualIntList "decodeModified [(Single 1)] should be [1] ." ([1] ) (decodeModified [(Single 1)] ))
test3 = TestCase (assertEqualIntList "decodeModified [(Single 1),(Single 2)] should be [1,2] ." ([1,2] ) (decodeModified [(Single 1),(Single 2)] ))
test4 = TestCase (assertEqualIntList "decodeModified [(Single 1),(Single 2),(Single 1)] should be [1,2,1]." ([1,2,1]) (decodeModified [(Single 1),(Single 2),(Single 1)]))
test5 = TestCase (assertEqualIntList "decodeModified [(Multiple 2 1),(Single 2)] should be [1,1,2]." ([1,1,2]) (decodeModified [(Multiple 2 1),(Single 2)] ))
test6 = TestCase (assertEqualIntList "decodeModified [(Single 1),(Multiple 2 2)] should be [1,2,2]." ([1,2,2]) (decodeModified [(Single 1),(Multiple 2 2)] ))
main = runTestTT $ TestList [test1,test2,test3,test4,test5,test6]
|
cshung/MiscLab
|
Haskell99/q12.test.hs
|
Haskell
|
mit
| 1,227
|
------------------------------------------------------------------------------
-- | This module is where all the routes and handlers are defined for your
-- site. The 'app' function is the initializer that combines everything
-- together and is exported by this module.
module Site (app) where
------------------------------------------------------------------------------
import Api.Core
import Data.ByteString (ByteString)
import Snap.Snaplet
------------------------------------------------------------------------------
import Application
------------------------------------------------------------------------------
-- | The application's routes.
routes :: [(ByteString, Handler App App ())]
routes = []
------------------------------------------------------------------------------
-- | The application initializer.
app :: SnapletInit App App
app = makeSnaplet "app" "An snaplet example application." Nothing $ do
api <- nestSnaplet "" api apiInit
addRoutes routes
return $ App api
|
thorinii/oldtoby-server
|
main/src/Site.hs
|
Haskell
|
mit
| 1,005
|
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, PatternGuards #-}
-- Copyright (c) 2004-6 Donald Bruce Stewart - http://www.cse.unsw.edu.au/~dons
-- GPL version 2 or later (see http://www.gnu.org/copyleft/gpl.html)
-- | A Haskell evaluator for the pure part, using plugs
module Plugin.Eval where
import File (findFile)
import Plugin
import Lambdabot.Parser
import Language.Haskell.Exts.Parser
import qualified Language.Haskell.Exts.Syntax as Hs
import qualified Text.Regex as R
import System.Directory
import System.Exit
import Codec.Binary.UTF8.String (decodeString)
import qualified Data.ByteString.Char8 as P
import Control.OldException (try)
$(plugin "Plugs")
instance Module PlugsModule () where
moduleCmds _ = ["run","let","undefine"]
moduleHelp _ "let" = "let <x> = <e>. Add a binding"
moduleHelp _ "undefine" = "undefine. Reset evaluator local bindings"
moduleHelp _ _ = "run <expr>. You have Haskell, 3 seconds and no IO. Go nuts!"
process _ _ to "run" s = ios80 to (plugs s)
process _ _ to "let" s = ios80 to (define s)
process _ _ _ "undefine" _ = do l <- io $ findFile "L.hs"
p <- io $ findFile "Pristine.hs"
io $ copyFile p l
-- x <- io $ comp Nothing
-- return [x]
return []
contextual _ _ to txt
| isEval txt = ios80 to . plugs . dropPrefix $ txt
| otherwise = return []
binary :: String
binary = "mueval"
isEval :: String -> Bool
isEval = ((evalPrefixes config) `arePrefixesWithSpaceOf`)
dropPrefix :: String -> String
dropPrefix = dropWhile (' ' ==) . drop 2
plugs :: String -> IO String
plugs src = do
load <- findFile "L.hs"
-- let args = ["-E", "-XBangPatterns", "-XNoMonomorphismRestriction", "-XViewPatterns", "--no-imports", "-l", load, "--expression=" ++ src, "+RTS", "-N2", "-RTS"]
let args = ["-E", "-XBangPatterns", "-XNoMonomorphismRestriction", "-XViewPatterns", "--no-imports", "-l", load, "--expression=" ++ src, "+RTS", "-N2", "-RTS"]
print args
(out,err,_) <- popen binary args Nothing
case (out,err) of
([],[]) -> return "Terminated\n"
_ -> do
let o = munge out
e = munge err
return $ case () of {_
| null o && null e -> "Terminated\n"
| null o -> " " ++ e
| otherwise -> " " ++ o
}
------------------------------------------------------------------------
-- define a new binding
define :: String -> IO String
define src = case parseModule (decodeString src ++ "\n") of -- extra \n so comments are parsed correctly
(ParseOk (Hs.Module _ _ _ _ (Just [Hs.EVar (Hs.UnQual (Hs.Ident "main"))]) [] ds))
| all okay ds -> comp (Just src)
(ParseFailed _ e) -> return $ " " ++ e
_ -> return "Invalid declaration"
where
okay (Hs.TypeSig {}) = True
okay (Hs.FunBind {}) = True
okay (Hs.PatBind {}) = True
okay (Hs.InfixDecl {}) = True
okay _ = False
-- It parses. then add it to a temporary L.hs and typecheck
comp :: Maybe String -> IO String
comp src = do
l <- findFile "L.hs"
-- Note we copy to .L.hs, not L.hs. This hides the temporary files as dot-files
copyFile l ".L.hs"
case src of
Nothing -> return () -- just reset from Pristine
Just s -> P.appendFile ".L.hs" (P.pack (s ++ "\n"))
-- and compile .L.hs
-- careful with timeouts here. need a wrapper.
(o',e',c) <- popen "ghc" ["-O","-v0","-c"
,"-Werror"
-- ,"-odir", "State/"
-- ,"-hidir","State/"
,".L.hs"] Nothing
-- cleanup, in case of error the files are not generated
try $ removeFile ".L.hi"
try $ removeFile ".L.o"
case (munge o', munge e') of
([],[]) | c /= ExitSuccess -> return "Error."
| otherwise -> do
renameFile ".L.hs" l
return (maybe "Undefined." (const "Defined.") src)
(ee,[]) -> return ee
(_ ,ee) -> return ee
-- test cases
-- lambdabot> undefine
-- Undefined.
--
-- lambdabot> let x = 1
-- Defined.
-- lambdabot> let y = L.x
-- Defined.
-- lambdabot> > L.x + L.y
-- 2
-- lambdabot> let type Z = Int
-- Defined.
-- lambdabot> let newtype P = P Int
-- Defined.
-- lambdabot> > L.P 1 :: L.P
-- add an instance declaration for (Show L.P)
-- lambdabot> let instance Show L.P where show _ = "P"
-- Defined.
-- lambdabot> > L.P 1 :: L.P
-- P
--
munge :: String -> String
munge = expandTab . dropWhile (=='\n') . dropNL . clean_
--
-- Clean up runplugs' output
--
clean_ :: String -> String
clean_ = id
{-
clean_ s| no_io `matches'` s = "No IO allowed\n"
| type_sig `matches'` s = "Add a type signature\n"
| enomem `matches'` s = "Tried to use too much memory\n"
| Just (_,m,_,_) <- ambiguous `R.matchRegexAll` s = m
| Just (_,_,b,_) <- inaninst `R.matchRegexAll` s = clean_ b
| Just (_,_,b,_) <- irc `R.matchRegexAll` s = clean_ b
| Just (_,m,_,_) <- nomatch `R.matchRegexAll` s = m
| Just (_,m,_,_) <- notinscope `R.matchRegexAll` s = m
| Just (_,m,_,_) <- hsplugins `R.matchRegexAll` s = m
| Just (a,_,_,_) <- columnnum `R.matchRegexAll` s = a
| Just (a,_,_,_) <- extraargs `R.matchRegexAll` s = a
| Just (_,_,b,_) <- filename' `R.matchRegexAll` s = clean_ b
| Just (a,_,b,_) <- filename `R.matchRegexAll` s = a ++ clean_ b
| Just (a,_,b,_) <- filepath `R.matchRegexAll` s = a ++ clean_ b
| Just (a,_,b,_) <- runplugs `R.matchRegexAll` s = a ++ clean_ b
| otherwise = s
where
-- s/<[^>]*>:[^:]: //
type_sig = regex' "add a type signature that fixes these type"
no_io = regex' "No instance for \\(Show \\(IO"
irc = regex' "\n*<irc>:[^:]*:[^:]*:\n*"
filename = regex' "\n*<[^>]*>:[^:]*:\\?[^:]*:\\?\n* *"
filename' = regex' "/tmp/.*\\.hs[^\n]*\n"
filepath = regex' "\n*/[^\\.]*.hs:[^:]*:\n* *"
ambiguous = regex' "Ambiguous type variable `a\' in the constraints"
runplugs = regex' "runplugs: "
notinscope = regex' "Variable not in scope:[^\n]*"
hsplugins = regex' "Compiled, but didn't create object"
extraargs = regex' "[ \t\n]*In the [^ ]* argument"
columnnum = regex' " at <[^\\.]*\\.[^\\.]*>:[^ ]*"
nomatch = regex' "Couldn't match[^\n]*\n"
inaninst = regex' "^[ \t]*In a.*$"
enomem = regex' "^Heap exhausted"
-}
------------------------------------------------------------------------
--
-- Plugs tests:
-- * too long, should be terminated.
-- @plugs last [ 1 .. 100000000 ]
-- @plugs last [ 1 .. ]
-- @plugs product [1..]
-- @plugs let loop () = loop () in loop () :: ()
--
-- * stack oflow
-- @plugs scanr (*) 1 [1..]
--
-- * type errors, or module scope errors
-- @plugs unsafePerformIO (return 42)
-- @plugs GHC.Exts.I# 1#
-- @plugs $( Language.Haskell.THSyntax.Q (putStr "heya") >> [| 3 |] )
-- @plugs Data.Array.listArray (minBound::Int,maxBound) (repeat 0)
--
-- * syntax errors
-- @plugs map foo bar
-- @plugs $( [| 1 |] )
--
-- * success
-- @plugs head [ 1 .. ]
-- @plugs [1..]
-- @plugs last $ sort [1..100000 ]
-- @plugs let fibs = 1:1:zipWith (+) fibs (tail fibs) in take 20 fibs
-- @plugs sort [1..10000]
-- @plugs ((error "throw me") :: ())
-- @plugs Random.randomRs (0,747737437443734::Integer) (Random.mkStdGen 1122)
--
-- More at http://www.scannedinavian.org/~shae/joyXlogs.txt
--
|
zeekay/lambdabot
|
Plugin/Eval.hs
|
Haskell
|
mit
| 8,059
|
module Assembler.Types where
import Data.Word
-- Constant is either an int or a label which resolves to an int
type Label = String
type Constant = Either Int Label
type RegId = Word8
data Instr = Halt
| Nop
| Rrmovl RegId RegId
| Irmovl RegId Constant
| Rmmovl RegId RegId Int
| Mrmovl RegId RegId Int
| Addl RegId RegId
| Subl RegId RegId
| Andl RegId RegId
| Xorl RegId RegId
| Jmp Label
| Jle Label
| Jl Label
| Je Label
| Jne Label
| Jge Label
| Jg Label
| Cmovle RegId RegId
| Cmovl RegId RegId
| Cmove RegId RegId
| Cmovne RegId RegId
| Cmovge RegId RegId
| Cmovg RegId RegId
| Call Label
| Ret
| Pushl RegId
| Popl RegId
deriving Show
data Entity = Instr (Instr, Int)
| Directive (String, Int)
| Label Label
deriving Show
|
aufheben/Y86
|
Assembler/src/Assembler/Types.hs
|
Haskell
|
mit
| 1,097
|
module Vector2D where
type Vector2D = (Double, Double)
zero :: Vector2D
zero = (0, 0)
unit :: Vector2D
unit = (1, 1)
fromScalar :: Double -> Vector2D
fromScalar scalar = (scalar, scalar)
fromAngle :: Double -> Vector2D
fromAngle angle = (cos angle, sin angle)
magnitude :: Vector2D -> Double
magnitude vector = sqrt(magnitudeSquared vector)
magnitudeSquared :: Vector2D -> Double
magnitudeSquared (x, y) = (x*x + y*y)
addVector :: Vector2D -> Vector2D -> Vector2D
addVector (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
subtractVector :: Vector2D -> Vector2D -> Vector2D
subtractVector (x1, y1) (x2, y2) = (x1 - x2, y1 - y2)
multiplyVector :: Vector2D -> Vector2D -> Vector2D
multiplyVector (x1, y1) (x2, y2) = (x1 * x2, y1 * y2)
multiplyScalar :: Vector2D -> Double -> Vector2D
multiplyScalar vector scalar = multiplyVector vector $ fromScalar scalar
divideVector :: Vector2D -> Vector2D -> Vector2D
divideVector (x1, y1) (x2, y2) = (x1 / x2, y1 / y2)
divideScalar :: Vector2D -> Double -> Vector2D
divideScalar vector scalar = divideVector vector $ fromScalar scalar
distance :: Vector2D -> Vector2D -> Double
distance (x1, y1) (x2, y2) = sqrt $ dx * dx + dy * dx
where dx = x1 - x2
dy = y1 - y2
dot :: Vector2D -> Vector2D -> Double
dot (x1, y1) (x2, y2) = x1*x2 + y1+y2
reflect :: Vector2D -> Vector2D -> Vector2D
reflect vector1@(vectorX, vectorY) vector2@(normalX, normalY) = (vectorX - (2 * dotProduct * normalX), vectorY - (2 * dotProduct * normalY))
where dotProduct = dot vector1 vector2
normalize :: Vector2D -> Vector2D
normalize vector
| vectorMagnitude == 0 || vectorMagnitude == 1 = vector
| otherwise = vector `divideVector` (fromScalar vectorMagnitude)
where vectorMagnitude = magnitude vector
limit :: Vector2D -> Double -> Vector2D
limit vector maximum
| magnitudeSquared vector <= maximum * maximum = vector
| otherwise = (normalize vector) `multiplyScalar` maximum
getAngle :: Vector2D -> Double
getAngle (x, y) = (-1) * (atan2 (-y) x)
rotate :: Vector2D -> Double -> Vector2D
rotate (x, y) angle = (x * (cos angle) - y * (sin angle),
x * (sin angle) - y * (cos angle))
lerp :: Double -> Double -> Double -> Double
lerp start end amount = start + (end - start) * amount
lerpVector :: Vector2D -> Vector2D -> Double -> Vector2D
lerpVector (startX, startY) (endX, endY) amount = (lerp startX endX amount,
lerp startY endY amount)
remap :: Double -> Double -> Double -> Double -> Double -> Double
remap value oldMin oldMax newMin newMax = newMin + (newMax - newMin) * ((value - oldMin) / (oldMax - oldMin))
remapVectorToScalar :: Vector2D -> Double -> Double -> Double -> Double -> Vector2D
remapVectorToScalar (x, y) oldMin oldMax newMin newMax = (remap x oldMin oldMax newMin newMax,
remap y oldMin oldMax newMin newMax)
remapVectorToVectors :: Vector2D -> Vector2D -> Vector2D -> Vector2D -> Vector2D -> Vector2D
remapVectorToVectors (x, y) (oldMinX, oldMinY) (oldMaxX, oldMaxY) (newMinX, newMinY) (newMaxX, newMaxY) = (remap x oldMinX oldMaxX newMinX newMaxX,
remap y oldMinY oldMaxY newMinY newMaxY)
angleBetween :: Vector2D -> Vector2D -> Double
angleBetween vector1 vector2 = acos (enforceAngleConstraints tempValue)
where tempValue = (vector1 `dot` vector2) / (magnitude vector1 * magnitude vector2)
enforceAngleConstraints value
| value <= -1 = pi
| value >= 1 = 0
| otherwise = value
degreesToRadians :: Double -> Double
degreesToRadians degrees = degrees * (pi / 180)
radiansToDegrees :: Double -> Double
radiansToDegrees radians = radians * (180 / pi)
clamp :: Double -> Double -> Double -> Double
clamp input min max
| input < min = min
| input > max = max
| otherwise = input
clampToScalar :: Vector2D -> Double -> Double -> Vector2D
clampToScalar (x, y) min max = (clamp x min max, clamp y min max)
clampToVectors :: Vector2D -> Vector2D -> Vector2D -> Vector2D
clampToVectors (x, y) (minX, minY) (maxX, maxY) = (clamp x minX maxX,
clamp y minY maxY)
negate :: Vector2D -> Vector2D
negate vector = vector `multiplyScalar` (-1)
|
jlturner/vector2d-haskell
|
Vector2D.hs
|
Haskell
|
mit
| 4,542
|
{-# LANGUAGE CPP, MultiParamTypeClasses, FlexibleInstances, FlexibleContexts #-}
-----------------------------------------------------------------------------
-- |
-- Module : Crypto.Nettle.Ciphers
-- Copyright : (c) 2013 Stefan Bühler
-- License : MIT-style (see the file COPYING)
--
-- Maintainer : stbuehler@web.de
-- Stability : experimental
-- Portability : portable
--
-- This module exports ciphers supported by nettle:
-- <http://www.lysator.liu.se/~nisse/nettle/>
--
-----------------------------------------------------------------------------
module Crypto.Nettle.Ciphers (
-- * Block ciphers
-- | Only block ciphers with a 128-bit 'blockSize' (16 bytes) support the XTS cipher mode.
--
-- For 'aeadInit' only 'AEAD_GCM' and 'AEAD_CCM' (with 'ccmInitTLS') is supported, and only if the the 'blockSize' is 16 bytes.
-- In all other cases 'aeadInit' just returns 'Nothing'.
-- ** AES
AES
, AES128
, AES192
, AES256
-- ** ARCTWO
, ARCTWO
, arctwoInitEKB
, arctwoInitGutmann
-- ** BLOWFISH
, BLOWFISH
-- ** Camellia
, Camellia
, Camellia128
, Camellia192
, Camellia256
-- ** CAST-128
, CAST128
-- ** DES
, DES
-- ** DES3 (EDE)
, DES_EDE3
-- ** TWOFISH
, TWOFISH
-- ** SERPENT
, SERPENT
-- * Stream ciphers
-- ** Nonce ciphers
, StreamNonceCipher(..)
, streamSetNonceWord64
-- ** ARCFOUR
, ARCFOUR
-- ** ChaCha
, CHACHA
-- ** Salsa20
, SALSA20
, ESTREAM_SALSA20
) where
import Crypto.Cipher.Types
import Crypto.Nettle.CCM
import Data.SecureMem
import qualified Data.ByteString as B
import Data.Word (Word64)
import Data.Bits
import Data.Tagged
import Crypto.Nettle.Ciphers.Internal
import Crypto.Nettle.Ciphers.ForeignImports
import Nettle.Utils
-- internal functions are not camelCase on purpose
{-# ANN module "HLint: ignore Use camelCase" #-}
#define INSTANCE_CIPHER(Typ) \
instance Cipher Typ where \
{ cipherInit = nettle_cipherInit \
; cipherName = witness nc_cipherName \
; cipherKeySize = witness nc_cipherKeySize \
}
#define INSTANCE_BLOCKCIPHER(Typ) \
INSTANCE_CIPHER(Typ); \
instance BlockCipher Typ where \
{ blockSize = witness nbc_blockSize \
; ecbEncrypt = nettle_ecbEncrypt \
; ecbDecrypt = nettle_ecbDecrypt \
; cbcEncrypt = nettle_cbcEncrypt \
; cbcDecrypt = nettle_cbcDecrypt \
; cfbEncrypt = nettle_cfbEncrypt \
; cfbDecrypt = nettle_cfbDecrypt \
; ctrCombine = nettle_ctrCombine \
; aeadInit AEAD_GCM = nettle_gcm_aeadInit \
; aeadInit AEAD_CCM = ccmInitTLS \
; aeadInit _ = \_ _ -> Nothing \
} ; \
instance AEADModeImpl Typ NettleGCM where \
{ aeadStateAppendHeader = nettle_gcm_aeadStateAppendHeader \
; aeadStateEncrypt = nettle_gcm_aeadStateEncrypt \
; aeadStateDecrypt = nettle_gcm_aeadStateDecrypt \
; aeadStateFinalize = nettle_gcm_aeadStateFinalize \
}
#define INSTANCE_STREAMCIPHER(Typ) \
INSTANCE_CIPHER(Typ); \
instance StreamCipher Typ where \
{ streamCombine = nettle_streamCombine \
}
#define INSTANCE_STREAMNONCECIPHER(Typ) \
INSTANCE_STREAMCIPHER(Typ); \
instance StreamNonceCipher Typ where \
{ streamSetNonce = nettle_streamSetNonce \
; streamNonceSize = witness nsc_nonceSize \
}
#define INSTANCE_BLOCKEDSTREAMCIPHER(Typ) \
INSTANCE_CIPHER(Typ); \
instance StreamCipher Typ where \
{ streamCombine = nettle_blockedStreamCombine \
}
#define INSTANCE_BLOCKEDSTREAMNONCECIPHER(Typ) \
INSTANCE_BLOCKEDSTREAMCIPHER(Typ); \
instance StreamNonceCipher Typ where \
{ streamSetNonce = nettle_blockedStreamSetNonce \
; streamNonceSize = witness nbsc_nonceSize \
}
{-|
'AES' is the generic cipher context for the AES cipher, supporting key sizes
of 128, 196 and 256 bits (16, 24 and 32 bytes). The 'blockSize' is always 128 bits (16 bytes).
'aeadInit' only supports the 'AEAD_GCM' mode for now.
-}
newtype AES = AES SecureMem
instance NettleCipher AES where
nc_cipherInit = Tagged c_hs_aes_init
nc_cipherName = Tagged "AES"
nc_cipherKeySize = Tagged $ KeySizeEnum [16,24,32]
nc_ctx_size = Tagged c_hs_aes_ctx_size
nc_ctx (AES c) = c
nc_Ctx = AES
instance NettleBlockCipher AES where
nbc_blockSize = Tagged 16
nbc_ecb_encrypt = Tagged c_hs_aes_encrypt
nbc_ecb_decrypt = Tagged c_hs_aes_decrypt
nbc_fun_encrypt = Tagged p_hs_aes_encrypt
nbc_fun_decrypt = Tagged p_hs_aes_decrypt
INSTANCE_BLOCKCIPHER(AES)
{-|
'AES128' provides the same interface as 'AES', but is restricted to 128-bit keys.
-}
newtype AES128 = AES128 SecureMem
instance NettleCipher AES128 where
nc_cipherInit = Tagged (\ctx _ key -> c_hs_aes128_init ctx key)
nc_cipherName = Tagged "AES-128"
nc_cipherKeySize = Tagged $ KeySizeFixed 16
nc_ctx_size = Tagged c_hs_aes128_ctx_size
nc_ctx (AES128 c) = c
nc_Ctx = AES128
instance NettleBlockCipher AES128 where
nbc_blockSize = Tagged 16
nbc_encrypt_ctx_offset = Tagged c_hs_aes128_ctx_encrypt
nbc_decrypt_ctx_offset = Tagged c_hs_aes128_ctx_decrypt
nbc_ecb_encrypt = Tagged c_aes128_encrypt
nbc_ecb_decrypt = Tagged c_aes128_decrypt
nbc_fun_encrypt = Tagged p_aes128_encrypt
nbc_fun_decrypt = Tagged p_aes128_decrypt
INSTANCE_BLOCKCIPHER(AES128)
{-|
'AES192' provides the same interface as 'AES', but is restricted to 192-bit keys.
-}
newtype AES192 = AES192 SecureMem
instance NettleCipher AES192 where
nc_cipherInit = Tagged (\ctx _ key -> c_hs_aes192_init ctx key)
nc_cipherName = Tagged "AES-192"
nc_cipherKeySize = Tagged $ KeySizeFixed 24
nc_ctx_size = Tagged c_hs_aes192_ctx_size
nc_ctx (AES192 c) = c
nc_Ctx = AES192
instance NettleBlockCipher AES192 where
nbc_blockSize = Tagged 16
nbc_encrypt_ctx_offset = Tagged c_hs_aes192_ctx_encrypt
nbc_decrypt_ctx_offset = Tagged c_hs_aes192_ctx_decrypt
nbc_ecb_encrypt = Tagged c_aes192_encrypt
nbc_ecb_decrypt = Tagged c_aes192_decrypt
nbc_fun_encrypt = Tagged p_aes192_encrypt
nbc_fun_decrypt = Tagged p_aes192_decrypt
INSTANCE_BLOCKCIPHER(AES192)
{-|
'AES256' provides the same interface as 'AES', but is restricted to 256-bit keys.
-}
newtype AES256 = AES256 SecureMem
instance NettleCipher AES256 where
nc_cipherInit = Tagged (\ctx _ key -> c_hs_aes256_init ctx key)
nc_cipherName = Tagged "AES-256"
nc_cipherKeySize = Tagged $ KeySizeFixed 32
nc_ctx_size = Tagged c_hs_aes256_ctx_size
nc_ctx (AES256 c) = c
nc_Ctx = AES256
instance NettleBlockCipher AES256 where
nbc_blockSize = Tagged 16
nbc_encrypt_ctx_offset = Tagged c_hs_aes256_ctx_encrypt
nbc_decrypt_ctx_offset = Tagged c_hs_aes256_ctx_decrypt
nbc_ecb_encrypt = Tagged c_aes256_encrypt
nbc_ecb_decrypt = Tagged c_aes256_decrypt
nbc_fun_encrypt = Tagged p_aes256_encrypt
nbc_fun_decrypt = Tagged p_aes256_decrypt
INSTANCE_BLOCKCIPHER(AES256)
{-|
'ARCTWO' (also known as the trade marked name RC2) is a block cipher specified in RFC 2268.
The default 'cipherInit' uses @ekb = bit-length of the key@; 'arctwoInitEKB' allows to specify ekb manually.
'arctwoInitGutmann' uses @ekb = 1024@ (the maximum).
'ARCTWO' uses keysizes from 1 to 128 bytes, and uses a 'blockSize' of 64 bits (8 bytes).
-}
newtype ARCTWO = ARCTWO SecureMem
instance NettleCipher ARCTWO where
nc_cipherInit = Tagged c_arctwo_set_key
nc_cipherName = Tagged "ARCTWO"
nc_cipherKeySize = Tagged $ KeySizeRange 1 128
nc_ctx_size = Tagged c_arctwo_ctx_size
nc_ctx (ARCTWO c) = c
nc_Ctx = ARCTWO
instance NettleBlockCipher ARCTWO where
nbc_blockSize = Tagged 8
nbc_ecb_encrypt = Tagged c_arctwo_encrypt
nbc_ecb_decrypt = Tagged c_arctwo_decrypt
nbc_fun_encrypt = Tagged p_arctwo_encrypt
nbc_fun_decrypt = Tagged p_arctwo_decrypt
INSTANCE_BLOCKCIPHER(ARCTWO)
{-|
Initialize cipher with an explicit @ekb@ value (valid values from 1 to 1024, 0 meaning the same as 1024).
-}
arctwoInitEKB :: Key ARCTWO -> Word -> ARCTWO
arctwoInitEKB k ekb = nettle_cipherInit' initfun k where
initfun ctxptr ksize ptr = c_arctwo_set_key_ekb ctxptr ksize ptr ekb
{-|
Initialize cipher with @ekb = 1024@.
-}
arctwoInitGutmann :: Key ARCTWO -> ARCTWO
arctwoInitGutmann = nettle_cipherInit' c_arctwo_set_key_gutmann
{-|
'BLOWFISH' is a block cipher designed by Bruce Schneier.
It uses a 'blockSize' of 64 bits (8 bytes), and a variable key size from 64 to 448 bits (8 to 56 bytes).
-}
newtype BLOWFISH = BLOWFISH SecureMem
instance NettleCipher BLOWFISH where
nc_cipherInit = Tagged c_blowfish_set_key
nc_cipherName = Tagged "BLOWFISH"
nc_cipherKeySize = Tagged $ KeySizeRange 1 128
nc_ctx_size = Tagged c_blowfish_ctx_size
nc_ctx (BLOWFISH c) = c
nc_Ctx = BLOWFISH
instance NettleBlockCipher BLOWFISH where
nbc_blockSize = Tagged 8
nbc_ecb_encrypt = Tagged c_blowfish_encrypt
nbc_ecb_decrypt = Tagged c_blowfish_decrypt
nbc_fun_encrypt = Tagged p_blowfish_encrypt
nbc_fun_decrypt = Tagged p_blowfish_decrypt
INSTANCE_BLOCKCIPHER(BLOWFISH)
{-|
Camellia is a block cipher developed by Mitsubishi and Nippon Telegraph and Telephone Corporation,
described in RFC3713, and recommended by some Japanese and European authorities as an alternative to AES.
The algorithm is patented (details see <http://www.lysator.liu.se/~nisse/nettle/nettle.html>).
Camellia uses a the same 'blockSize' and key sizes as 'AES'.
'aeadInit' only supports the 'AEAD_GCM' mode for now.
-}
newtype Camellia = Camellia SecureMem
instance NettleCipher Camellia where
nc_cipherInit = Tagged c_hs_camellia_init
nc_cipherName = Tagged "Camellia"
nc_cipherKeySize = Tagged $ KeySizeEnum [16,24,32]
nc_ctx_size = Tagged c_hs_camellia_ctx_size
nc_ctx (Camellia c) = c
nc_Ctx = Camellia
instance NettleBlockCipher Camellia where
nbc_blockSize = Tagged 16
nbc_ecb_encrypt = Tagged c_hs_camellia_encrypt
nbc_ecb_decrypt = Tagged c_hs_camellia_decrypt
nbc_fun_encrypt = Tagged p_hs_camellia_encrypt
nbc_fun_decrypt = Tagged p_hs_camellia_decrypt
INSTANCE_BLOCKCIPHER(Camellia)
{-|
'Camellia128' provides the same interface as 'Camellia', but is restricted to 128-bit keys.
-}
newtype Camellia128 = Camellia128 SecureMem
instance NettleCipher Camellia128 where
nc_cipherInit = Tagged (\ctx _ key -> c_hs_camellia128_init ctx key)
nc_cipherName = Tagged "Camellia-128"
nc_cipherKeySize = Tagged $ KeySizeFixed 16
nc_ctx_size = Tagged c_hs_camellia128_ctx_size
nc_ctx (Camellia128 c) = c
nc_Ctx = Camellia128
instance NettleBlockCipher Camellia128 where
nbc_blockSize = Tagged 16
nbc_encrypt_ctx_offset = Tagged c_hs_camellia128_ctx_encrypt
nbc_decrypt_ctx_offset = Tagged c_hs_camellia128_ctx_decrypt
nbc_ecb_encrypt = Tagged c_camellia128_crypt
nbc_ecb_decrypt = Tagged c_camellia128_crypt
nbc_fun_encrypt = Tagged p_camellia128_crypt
nbc_fun_decrypt = Tagged p_camellia128_crypt
INSTANCE_BLOCKCIPHER(Camellia128)
{-|
'Camellia192' provides the same interface as 'Camellia', but is restricted to 192-bit keys.
-}
newtype Camellia192 = Camellia192 SecureMem
instance NettleCipher Camellia192 where
nc_cipherInit = Tagged (\ctx _ key -> c_hs_camellia192_init ctx key)
nc_cipherName = Tagged "Camellia-192"
nc_cipherKeySize = Tagged $ KeySizeFixed 24
nc_ctx_size = Tagged c_hs_camellia192_ctx_size
nc_ctx (Camellia192 c) = c
nc_Ctx = Camellia192
instance NettleBlockCipher Camellia192 where
nbc_blockSize = Tagged 16
nbc_encrypt_ctx_offset = Tagged c_hs_camellia192_ctx_encrypt
nbc_decrypt_ctx_offset = Tagged c_hs_camellia192_ctx_decrypt
nbc_ecb_encrypt = Tagged c_camellia192_crypt
nbc_ecb_decrypt = Tagged c_camellia192_crypt
nbc_fun_encrypt = Tagged p_camellia192_crypt
nbc_fun_decrypt = Tagged p_camellia192_crypt
INSTANCE_BLOCKCIPHER(Camellia192)
{-|
'Camellia256' provides the same interface as 'Camellia', but is restricted to 256-bit keys.
-}
newtype Camellia256 = Camellia256 SecureMem
instance NettleCipher Camellia256 where
nc_cipherInit = Tagged (\ctx _ key -> c_hs_camellia256_init ctx key)
nc_cipherName = Tagged "Camellia-256"
nc_cipherKeySize = Tagged $ KeySizeFixed 32
nc_ctx_size = Tagged c_hs_camellia256_ctx_size
nc_ctx (Camellia256 c) = c
nc_Ctx = Camellia256
instance NettleBlockCipher Camellia256 where
nbc_blockSize = Tagged 16
nbc_encrypt_ctx_offset = Tagged c_hs_camellia256_ctx_encrypt
nbc_decrypt_ctx_offset = Tagged c_hs_camellia256_ctx_decrypt
nbc_ecb_encrypt = Tagged c_camellia256_crypt
nbc_ecb_decrypt = Tagged c_camellia256_crypt
nbc_fun_encrypt = Tagged p_camellia256_crypt
nbc_fun_decrypt = Tagged p_camellia256_crypt
INSTANCE_BLOCKCIPHER(Camellia256)
{-|
'CAST128' is a block cipher specified in RFC 2144. It uses a 64 bit (8 bytes) 'blockSize',
and a variable key size of 40 up to 128 bits (5 to 16 bytes).
-}
newtype CAST128 = CAST128 SecureMem
instance NettleCipher CAST128 where
nc_cipherInit = Tagged c_cast5_set_key
nc_cipherName = Tagged "CAST-128"
nc_cipherKeySize = Tagged $ KeySizeRange 5 16
nc_ctx_size = Tagged c_cast128_ctx_size
nc_ctx (CAST128 c) = c
nc_Ctx = CAST128
instance NettleBlockCipher CAST128 where
nbc_blockSize = Tagged 8
nbc_ecb_encrypt = Tagged c_cast128_encrypt
nbc_ecb_decrypt = Tagged c_cast128_decrypt
nbc_fun_encrypt = Tagged p_cast128_encrypt
nbc_fun_decrypt = Tagged p_cast128_decrypt
INSTANCE_BLOCKCIPHER(CAST128)
{-|
'DES' is the old Data Encryption Standard, specified by NIST.
It uses a 'blockSize' of 64 bits (8 bytes), and a key size of 56 bits.
The key is given as 8 bytes, as one bit per byte is used as a parity bit.
The parity bit is ignored by this implementation.
-}
newtype DES = DES SecureMem
instance NettleCipher DES where
nc_cipherInit = Tagged $ \ctxptr _ -> c_des_set_key ctxptr
nc_cipherName = Tagged "DES"
nc_cipherKeySize = Tagged $ KeySizeFixed 8
nc_ctx_size = Tagged c_des_ctx_size
nc_ctx (DES c) = c
nc_Ctx = DES
instance NettleBlockCipher DES where
nbc_blockSize = Tagged 8
nbc_ecb_encrypt = Tagged c_des_encrypt
nbc_ecb_decrypt = Tagged c_des_decrypt
nbc_fun_encrypt = Tagged p_des_encrypt
nbc_fun_decrypt = Tagged p_des_decrypt
INSTANCE_BLOCKCIPHER(DES)
{-|
'DES_EDE3' uses 3 'DES' keys @k1 || k2 || k3@.
Encryption first encrypts with k1, then decrypts with k2, then encrypts with k3.
The 'blockSize' is the same as for 'DES': 64 bits (8 bytes),
and the keys are simply concatenated, forming a 24 byte key string (with 168 bits actually getting used).
-}
newtype DES_EDE3 = DES_EDE3 SecureMem
instance NettleCipher DES_EDE3 where
nc_cipherInit = Tagged $ \ctxptr _ -> c_des3_set_key ctxptr
nc_cipherName = Tagged "DES-EDE3"
nc_cipherKeySize = Tagged $ KeySizeFixed 24
nc_ctx_size = Tagged c_des3_ctx_size
nc_ctx (DES_EDE3 c) = c
nc_Ctx = DES_EDE3
instance NettleBlockCipher DES_EDE3 where
nbc_blockSize = Tagged 8
nbc_ecb_encrypt = Tagged c_des3_encrypt
nbc_ecb_decrypt = Tagged c_des3_decrypt
nbc_fun_encrypt = Tagged p_des3_encrypt
nbc_fun_decrypt = Tagged p_des3_decrypt
INSTANCE_BLOCKCIPHER(DES_EDE3)
{-|
'SERPENT' is one of the AES finalists, designed by Ross Anderson, Eli Biham and Lars Knudsen.
The 'blockSize' is 128 bits (16 bytes), and the valid key sizes are from 128 bits to 256 bits (16 to 32 bytes),
although smaller bits are just padded with zeroes.
'aeadInit' only supports the 'AEAD_GCM' mode for now.
-}
newtype SERPENT = SERPENT SecureMem
instance NettleCipher SERPENT where
nc_cipherInit = Tagged c_serpent_set_key
nc_cipherName = Tagged "SERPENT"
nc_cipherKeySize = Tagged $ KeySizeRange 16 32
nc_ctx_size = Tagged c_serpent_ctx_size
nc_ctx (SERPENT c) = c
nc_Ctx = SERPENT
instance NettleBlockCipher SERPENT where
nbc_blockSize = Tagged 16
nbc_ecb_encrypt = Tagged c_serpent_encrypt
nbc_ecb_decrypt = Tagged c_serpent_decrypt
nbc_fun_encrypt = Tagged p_serpent_encrypt
nbc_fun_decrypt = Tagged p_serpent_decrypt
INSTANCE_BLOCKCIPHER(SERPENT)
{-|
'TWOFISH' is another AES finalist, designed by Bruce Schneier and others.
'TWOFISH' uses a the same 'blockSize' and key sizes as 'AES'.
'aeadInit' only supports the 'AEAD_GCM' mode for now.
-}
newtype TWOFISH = TWOFISH SecureMem
instance NettleCipher TWOFISH where
nc_cipherInit = Tagged c_twofish_set_key
nc_cipherName = Tagged "TWOFISH"
nc_cipherKeySize = Tagged $ KeySizeEnum [16,24,32]
nc_ctx_size = Tagged c_twofish_ctx_size
nc_ctx (TWOFISH c) = c
nc_Ctx = TWOFISH
instance NettleBlockCipher TWOFISH where
nbc_blockSize = Tagged 16
nbc_ecb_encrypt = Tagged c_twofish_encrypt
nbc_ecb_decrypt = Tagged c_twofish_decrypt
nbc_fun_encrypt = Tagged p_twofish_encrypt
nbc_fun_decrypt = Tagged p_twofish_decrypt
INSTANCE_BLOCKCIPHER(TWOFISH)
{-|
'ARCFOUR' is a stream cipher, also known under the trade marked name RC4.
Valid key sizes are from 1 to 256 bytes.
-}
newtype ARCFOUR = ARCFOUR SecureMem
instance NettleCipher ARCFOUR where
nc_cipherInit = Tagged c_arcfour_set_key
nc_cipherName = Tagged "ARCFOUR"
nc_cipherKeySize = Tagged $ KeySizeEnum [16,24,32]
nc_ctx_size = Tagged c_arcfour_ctx_size
nc_ctx (ARCFOUR c) = c
nc_Ctx = ARCFOUR
instance NettleStreamCipher ARCFOUR where
nsc_streamCombine = Tagged c_arcfour_crypt
INSTANCE_STREAMCIPHER(ARCFOUR)
{-|
'StreamNonceCipher' are special stream ciphers that can encrypt many messages with the same key;
setting a nonce restarts the cipher.
A good value for the nonce is a message/packet counter. Usually a nonce should not be reused with the same key.
-}
class StreamCipher cipher => StreamNonceCipher cipher where
streamNonceSize :: cipher -> KeySizeSpecifier
streamSetNonce :: cipher -> B.ByteString -> Maybe cipher
word64BE :: Word64 -> B.ByteString
word64BE value = B.pack $ _work (8::Int) [] value where
_work 0 r _ = r
_work n r v = let d = v `shiftR` 8; m = fromIntegral v :: Word8 in _work (n-1) (m:r) d
{-|
Sets a 'Word64' as 8-byte nonce (bigendian encoded)
-}
streamSetNonceWord64 :: StreamNonceCipher cipher => cipher -> Word64 -> Maybe cipher
streamSetNonceWord64 c nonce = streamSetNonce c $ word64BE nonce
-- set nonce to 0 on init
wrap_chacha_set_key :: Ptr Word8 -> Word -> Ptr Word8 -> IO ()
wrap_chacha_set_key ctxptr _ keyptr = do
c_chacha_set_key ctxptr keyptr
withByteStringPtr (B.replicate 8 0) $ \_ nonceptr ->
c_chacha_set_nonce ctxptr nonceptr
-- check nonce length
wrap_chacha_set_nonce :: Ptr Word8 -> Word -> Ptr Word8 -> IO ()
wrap_chacha_set_nonce ctxptr ivlen ivptr = if ivlen == 8 then c_chacha_set_nonce ctxptr ivptr else fail "Invalid nonce length"
{-|
'CHACHA' is a variant of the 'SALSA20' stream cipher, both designed by D. J. Bernstein.
Key size is 256 bits (32 bytes).
'CHACHA' works similar to 'SALSA20'; it could theoretically also support 128-bit keys, but there is no need for it as they share the same performance.
ChaCha uses a blocksize of 64 bytes internally; if crpyted input isn't aligned to 64 bytes it will
pad it with 0 and store the encrypted padding to xor with future input data.
Each message also requires a 8-byte ('Word64') nonce (which is initialized to 0; you can use a message sequence number).
Don't reuse a nonce with the same key.
Setting a nonce also resets the remaining padding data.
-}
newtype CHACHA = CHACHA (SecureMem, B.ByteString)
instance NettleCipher CHACHA where
nc_cipherInit = Tagged wrap_chacha_set_key
nc_cipherName = Tagged "ChaCha"
nc_cipherKeySize = Tagged $ KeySizeFixed 32
nc_ctx_size = Tagged c_chacha_ctx_size
nc_ctx (CHACHA (c, _)) = c
nc_Ctx c = CHACHA (c, B.empty)
instance NettleBlockedStreamCipher CHACHA where
nbsc_blockSize = Tagged 64
nbsc_IncompleteState (CHACHA (c, _)) inc = CHACHA (c, inc)
nbsc_incompleteState (CHACHA (_, inc)) = inc
nbsc_streamCombine = Tagged c_chacha_crypt
nbsc_nonceSize = Tagged $ KeySizeFixed 8
nbsc_setNonce = Tagged $ Just wrap_chacha_set_nonce
INSTANCE_BLOCKEDSTREAMNONCECIPHER(CHACHA)
-- set nonce to 0 on init
wrap_salsa20_set_key :: Ptr Word8 -> Word -> Ptr Word8 -> IO ()
wrap_salsa20_set_key ctxptr keylen keyptr = do
c_salsa20_set_key ctxptr keylen keyptr
withByteStringPtr (B.replicate 8 0) $ \_ nonceptr ->
c_salsa20_set_nonce ctxptr nonceptr
-- check nonce length
wrap_salsa20_set_nonce :: Ptr Word8 -> Word -> Ptr Word8 -> IO ()
wrap_salsa20_set_nonce ctxptr ivlen ivptr = if ivlen == 8 then c_salsa20_set_nonce ctxptr ivptr else fail "Invalid nonce length"
{-|
'SALSA20' is a fairly recent stream cipher designed by D. J. Bernstein.
Valid key sizes are 128 and 256 bits (16 and 32 bytes).
Salsa20 uses a blocksize of 64 bytes internally; if crpyted input isn't aligned to 64 bytes it will
pad it with 0 and store the encrypted padding to xor with future input data.
Each message also requires a 8-byte ('Word64') nonce (which is initialized to 0; you can use a message sequence number).
Don't reuse a nonce with the same key.
Setting a nonce also resets the remaining padding data.
-}
newtype SALSA20 = SALSA20 (SecureMem, B.ByteString)
instance NettleCipher SALSA20 where
nc_cipherInit = Tagged wrap_salsa20_set_key
nc_cipherName = Tagged "Salsa20"
nc_cipherKeySize = Tagged $ KeySizeEnum [16,32]
nc_ctx_size = Tagged c_salsa20_ctx_size
nc_ctx (SALSA20 (c, _)) = c
nc_Ctx c = SALSA20 (c, B.empty)
instance NettleBlockedStreamCipher SALSA20 where
nbsc_blockSize = Tagged 64
nbsc_IncompleteState (SALSA20 (c, _)) inc = SALSA20 (c, inc)
nbsc_incompleteState (SALSA20 (_, inc)) = inc
nbsc_streamCombine = Tagged c_salsa20_crypt
nbsc_nonceSize = Tagged $ KeySizeFixed 8
nbsc_setNonce = Tagged $ Just wrap_salsa20_set_nonce
INSTANCE_BLOCKEDSTREAMNONCECIPHER(SALSA20)
{-|
'ESTREAM_SALSA20' is the same as 'SALSA20', but uses only 12 instead of 20 rounds in mixing.
-}
newtype ESTREAM_SALSA20 = ESTREAM_SALSA20 (SecureMem, B.ByteString)
instance NettleCipher ESTREAM_SALSA20 where
nc_cipherInit = Tagged wrap_salsa20_set_key
nc_cipherName = Tagged "eSTREAM-Salsa20"
nc_cipherKeySize = Tagged $ KeySizeEnum [16,32]
nc_ctx_size = Tagged c_salsa20_ctx_size
nc_ctx (ESTREAM_SALSA20 (c, _)) = c
nc_Ctx c = ESTREAM_SALSA20 (c, B.empty)
instance NettleBlockedStreamCipher ESTREAM_SALSA20 where
nbsc_blockSize = Tagged 64
nbsc_IncompleteState (ESTREAM_SALSA20 (c, _)) inc = ESTREAM_SALSA20 (c, inc)
nbsc_incompleteState (ESTREAM_SALSA20 (_, inc)) = inc
nbsc_streamCombine = Tagged c_salsa20r12_crypt
nbsc_nonceSize = Tagged $ KeySizeFixed 8
nbsc_setNonce = Tagged $ Just wrap_salsa20_set_nonce
INSTANCE_BLOCKEDSTREAMNONCECIPHER(ESTREAM_SALSA20)
|
stbuehler/haskell-nettle
|
src/Crypto/Nettle/Ciphers.hs
|
Haskell
|
mit
| 23,016
|
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
module Lib
( someFunc
) where
import Reflex.Dom
import Data.JSString ()
import GHCJS.Types
import GUI.ChannelDrawer
import GUI.Player
import Data.Monoid
someFunc :: IO ()
someFunc = mainWidget mainUI
-- Needed until Reflex.Dom version 0.4 is released
foreign import javascript unsafe
"$1.withCredentials = true;"
setRequestWithCredentials :: JSVal -> IO ()
tvhBaseUrl :: String
tvhBaseUrl = "http://localhost:9981/"
navBar :: MonadWidget t m => m ()
navBar = do
elClass "nav" "navbar navbar-default navbar-static-top" $ do
divClass "container-fluid" $ do
divClass "navbar-header" $ do
divClass "navbar-brand" $ do
text "Tvheadend frontend"
mainUI :: MonadWidget t m => m ()
mainUI = do
navBar
divClass "container-fluid" $ do
divClass "row" $ do
curChannel <- elAttr "div"
("class" =: "col-lg-2" <>
-- height:90vh to fit the list inside the viewport
-- overflow-y:auto to get vertical scrollbar
-- padding-right:0px to pull scrollbar closer to the list
"style" =: "height:90vh;overflow-y:auto;padding-right:0px") $ do
-- create the channel drawer and react to events fired when a channel is selected
channelDrawer tvhBaseUrl
divClass "col-lg-10" $ do
player tvhBaseUrl curChannel
|
simonvandel/tvheadend-frontend
|
src/Lib.hs
|
Haskell
|
mit
| 1,429
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.