code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{- | Graphics.Gnewplot.Style contain constructors that wrap plottable things to modify their display style in individual panels. Example: @ import Graphics.Gnewplot.Instances import Graphics.Gnewplot.Exec someData :: [(Double,Double)] somedata = [(0.0, 1.0),(0.1, 2.0),(0.2, 1.4),(0.3, 1.7),(0.4, 1.0), (0.5, 1.8),(0.6, 1.1),(0.7, 1.5),(0.8, 1.2),(0.9, 1.9)] main = do gnuplotOnScreen $ Lines [LineWidth 1.5, LineColor \"blue\"] someData gnuplotOnScreen $ XScaleBar (0.1, 1.1) (0.1,\"100 nm\") 0.2 $ NoAxes $ someData @ -} {-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleInstances, ExistentialQuantification #-} {-# LANGUAGE TypeOperators, FlexibleContexts, GADTs, ScopedTypeVariables, DeriveDataTypeable #-} module Graphics.Gnewplot.Style where --import Math.Probably.FoldingStats hiding (F) import Control.Monad import Data.List import Graphics.Gnewplot.Types --newtype Lines a = Lines {unLines :: a } --newtype Dashed a = Dashed {unDashed :: a } -- | Options for modifying styles. Plot GnuplotTest to see styles for markers and lines. data StyleOpt = LineWidth Double | LineType Int | LineStyle Int | LineColor String | PointType Int | PointSize Double styleOptsToString :: [StyleOpt] -> String styleOptsToString = intercalate " " . map g where g (LineType lt) = "lt "++show lt g (LineWidth lt) = "lw "++show lt g (LineStyle lt) = "ls "++show lt g (LineColor lc) = "lc rgb "++show lc g (PointType lt) = "pt "++show lt g (PointSize lt) = "ps "++show lt -- | Place the vertical axis on the right newtype RightAxis a = RightAxis a instance PlotWithGnuplot a => PlotWithGnuplot (RightAxis a) where multiPlot r (RightAxis x) = do px <- multiPlot r x return $ map (\(r', pls) -> (r', addData (" axis x1y2") pls)) px -- | Plot with boxes newtype Boxes a = Boxes {unBoxes :: a } -- | Plot with boxes newtype HiSteps a = HiSteps {unHiSteps :: a } -- | Plot with lines data Lines a = Lines [StyleOpt] a -- | Plot with markers data Points a = Points [StyleOpt] a -- | Plot with lines and markers data LinesPoints a = LinesPoints [StyleOpt] a data LogScale a = LogScaleX a | LogScaleY a instance PlotWithGnuplot a => PlotWithGnuplot (Lines a) where multiPlot r (Lines sos x) = do px <- multiPlot r x let wstr = styleOptsToString sos return $ map (\(r', pls) -> (r', setWith ("lines "++wstr) pls)) px instance PlotWithGnuplot a => PlotWithGnuplot (LinesPoints a) where multiPlot r (LinesPoints sos x) = do px <- multiPlot r x let wstr = styleOptsToString sos return $ map (\(r', pls) -> (r', setWith ("linespoints "++wstr) pls)) px instance PlotWithGnuplot a => PlotWithGnuplot (Points a) where multiPlot r (Points sos x) = do px <- multiPlot r x let wstr = styleOptsToString sos return $ map (\(r', pls) -> (r', setWith ("points "++wstr) pls)) px instance PlotWithGnuplot a => PlotWithGnuplot (Boxes a) where multiPlot r (Boxes x) = do px <- multiPlot r x return $ map (\(r', pls) -> (r', setWith "boxes" pls)) px instance PlotWithGnuplot a => PlotWithGnuplot (HiSteps a) where multiPlot r (HiSteps x) = do px <- multiPlot r x return $ map (\(r', pls) -> (r', setWith "histeps" pls)) px -- | Set the horizontal range data XRange a = XRange Double Double a -- | Set the vertical range data YRange a = YRange Double Double a | YFromZero a -- | Place horizontal ticks manually data XTics a = XTics [Double] a | XTicLabel [(String, Double)] a -- | Place vertical ticks manually data YTics a = YTics [Double] a | YTicLabel [(String, Double)] a data TicFormat a = TicFormat XY String a data XY = X | Y | XY data Noaxis a = Noaxis a | NoXaxis a | NoYaxis a | NoTRaxis a -- | Locate the key (legend) somewhere else than the default location data Key a = KeyTopLeft Bool a | KeyTopRight Bool a instance PlotWithGnuplot a => PlotWithGnuplot (XRange a) where multiPlot r m@(XRange lo hi x) = do px <- multiPlot r x let setit = "set xrange ["++show lo++":"++show hi++"]\n" return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set xrange [*:*]"):pls)) px instance PlotWithGnuplot a => PlotWithGnuplot (TicFormat a) where multiPlot r m@(TicFormat xy s x) = do px <- multiPlot r x let whereStr X = "x" whereStr Y = "y" whereStr XY = "xy" let setit = "set format "++whereStr xy++" "++show s++"\n" return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "unset format"):pls)) px instance PlotWithGnuplot a => PlotWithGnuplot (Key a) where multiPlot r m@(KeyTopLeft box x) = do px <- multiPlot r x let boxs = if box then "box" else "" let setit = "set key top left "++boxs++"\n" return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set key default"):pls)) px instance PlotWithGnuplot a => PlotWithGnuplot (LogScale a) where multiPlot r m@(LogScaleX x) = do px <- multiPlot r x let cmd = TopLevelGnuplotCmd "set logscale x;" "set nologscale x" return $ map (\(r', pls) -> (r', cmd:pls)) px multiPlot r m@(LogScaleY x) = do px <- multiPlot r x let cmd = TopLevelGnuplotCmd "set logscale y;" "set nologscale y" return $ map (\(r', pls) -> (r', cmd:pls)) px instance PlotWithGnuplot a => PlotWithGnuplot (Noaxis a) where multiPlot r m@(Noaxis x) = do px <- multiPlot r x let cmd = TopLevelGnuplotCmd "unset border; unset tics;" "set border; set tics" return $ map (\(r', pls) -> (r', cmd:pls)) px multiPlot r m@(NoYaxis x) = do px <- multiPlot r x let cmd = TopLevelGnuplotCmd "set border 1; set tics; set ytics nomirror; unset ytics; set xtics nomirror;" "set border; set tics;" return $ map (\(r', pls) -> (r', cmd:pls)) px multiPlot r m@(NoXaxis x) = do px <- multiPlot r x let cmd = TopLevelGnuplotCmd "set border 2; set tics; set xtics nomirror; unset xtics; set ytics nomirror;" "set border; set tics;" return $ map (\(r', pls) -> (r', cmd:pls)) px multiPlot r m@(NoTRaxis x) = do px <- multiPlot r x let cmd = TopLevelGnuplotCmd "set border 3; set tics; set xtics nomirror; set ytics nomirror;" "set border; set tics;" return $ map (\(r', pls) -> (r', cmd:pls)) px instance PlotWithGnuplot a => PlotWithGnuplot (XTics a) where multiPlot r m@(XTics tics x) = do px <- multiPlot r x let setit = "set xtics "++ (intercalate ", " $ map show tics) ++";" return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set xtics autofreq;"):pls)) px multiPlot r m@(XTicLabel tics x) = do px <- multiPlot r x let showTic (lab, loc) = show lab++" "++show loc let setit = "set xtics ("++ (intercalate ", " $ map showTic tics) ++");" return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set xtics autofreq;"):pls)) px instance PlotWithGnuplot a => PlotWithGnuplot (YTics a) where multiPlot r m@(YTics tics x) = do px <- multiPlot r x let setit = "set ytics "++ (intercalate ", " $ map show tics) ++";" return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set ytics autofreq"):pls)) px multiPlot r m@(YTicLabel tics x) = do px <- multiPlot r x let showTic (lab, loc) = show lab++" "++show loc let setit = "set ytics ("++ (intercalate ", " $ map showTic tics) ++");" return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set ytics autofreq;"):pls)) px instance PlotWithGnuplot a => PlotWithGnuplot (YRange a) where multiPlot r m@(YRange lo hi x) = do px <- multiPlot r x let setit = "set yrange ["++show lo++":"++show hi++"]\n" return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set yrange [*:*]"):pls)) px multiPlot r m@(YFromZero x) = do px <- multiPlot r x let setit = "set yrange [0:*]\n" return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set yrange [*:*]"):pls)) px lineWidth w = Lines [LineWidth w] lineType t = Lines [LineType t] pointSize t = Points [PointSize t] pointType t = Points [PointType t] data CustAxis = CustAxis { caOrigin :: (Double,Double), caLength :: Double, caVertical :: Bool, caTicLen :: Double, caTicOffset :: Double, caTics :: [(Double, String)] } data WithAxis a = WithAxis CustAxis a instance PlotWithGnuplot a => PlotWithGnuplot (WithAxis a) where multiPlot r (WithAxis (CustAxis (x0,y0) len True tlen toff tics) x) = do let ticCmds (y,txt) = [TopLevelGnuplotCmd ("set arrow from first "++show x0++","++show (y0+y)++ " to first "++show (x0-tlen)++","++show (y0+y)++" nohead front") "unset arrow", TopLevelGnuplotCmd ("set label "++show txt++" at first "++ show (x0-toff)++","++show (y0+y)++" right front") "unset label" ] let cmds = TopLevelGnuplotCmd ("set arrow from first "++show x0++","++show y0++ " to first "++show x0++","++show (y0+len)++" nohead front") "unset arrow" : concatMap ticCmds tics px <- multiPlot r $ x return $ map (\(r', pls) -> (r', cmds++pls)) px -- | draw a scale bar with custom location, length, text and separation between the bar and the text data ScaleBars a = ScaleBars (Double, Double) (Double,String) (Double,String) a | XScaleBar (Double, Double) (Double,String) Double a | YScaleBar (Double, Double) (Double,String) Double a -- | Draw a line somewhere on the graph data LineAt a = LineAt (Double, Double) (Double, Double) a -- | Draw an arrow somewhere on the graph data ArrowAt a = ArrowAt (Double, Double) (Double, Double) a -- | place some text somewhere on the graph data TextAt a = TextAt (Double, Double) String a | TextAtLeft (Double, Double) String a | TextAtRot (Double,Double) String a instance PlotWithGnuplot a => PlotWithGnuplot (TextAt a) where multiPlot r (TextAt (x0,y0) s x) = do let mklab = TopLevelGnuplotCmd ("set label "++show s++" at first "++show x0++","++show y0++" center front") "unset label" px <- multiPlot r x return $ map (\(r', pls) -> (r', mklab:pls)) px multiPlot r (TextAtRot (x0,y0) s x) = do let mklab = TopLevelGnuplotCmd ("set label "++show s++" at first "++show x0++","++show y0++" center front rotate") "unset label" px <- multiPlot r x return $ map (\(r', pls) -> (r', mklab:pls)) px multiPlot r (TextAtLeft (x0,y0) s x) = do let mklab = TopLevelGnuplotCmd ("set label "++show s++" at first "++show x0++","++show y0++" left front") "unset label" px <- multiPlot r x return $ map (\(r', pls) -> (r', mklab:pls)) px instance PlotWithGnuplot a => PlotWithGnuplot (LineAt a) where multiPlot r (LineAt (x0,y0) (x1, y1) x) = do let mklab = TopLevelGnuplotCmd ("set arrow from first "++show x0++","++show y0++" to first "++show x1++","++show y1++" nohead front") "unset arrow" px <- multiPlot r x return $ map (\(r', pls) -> (r', mklab:pls)) px instance PlotWithGnuplot a => PlotWithGnuplot (ArrowAt a) where multiPlot r (ArrowAt (x0,y0) (x1, y1) x) = do let mklab = TopLevelGnuplotCmd ("set arrow from first "++show x0++","++show y0++" to first "++show x1++","++show y1++" heads front") "unset arrow" px <- multiPlot r x return $ map (\(r', pls) -> (r', mklab:pls)) px instance PlotWithGnuplot a => PlotWithGnuplot (ScaleBars a) where multiPlot r (ScaleBars p0 (xsz, xtxt) (ysz, ytxt) x) = do multiPlot r $ XScaleBar p0 (xsz, xtxt) (ysz/4) $ YScaleBar p0 (ysz, ytxt) (xsz/2) x multiPlot r (XScaleBar (x0,y0) (xsz, xtxt) yo x) = do let xtxtpos = (x0+xsz/2, y0 - yo) multiPlot r $ LineAt (x0, y0) (x0+xsz, y0) $ TextAt xtxtpos xtxt x multiPlot r (YScaleBar (x0,y0) (ysz, ytxt) yo x) = do let ytxtpos = (x0+yo, y0 + ysz/2) multiPlot r $ LineAt (x0, y0) (x0, y0+ysz) $ TextAt ytxtpos ytxt x data TicFont a = TicFont String a instance PlotWithGnuplot a => PlotWithGnuplot (TicFont a) where multiPlot r (TicFont str x) = do let mklab = TopLevelGnuplotCmd ("set tics font "++show str) "" px <- multiPlot r x return $ map (\(r', pls) -> (r', mklab:pls)) px -- | place a piece of text in the middle of the graph data CentreLabel = CentreLabel String instance PlotWithGnuplot CentreLabel where multiPlot r (CentreLabel str) = do let mklab = TopLevelGnuplotCmd ("set label "++show str++" at graph 0.5,0.5 center front") "unset label" nop::[GnuplotCmd] <- fmap (map snd) $ multiPlot r Noplot return [(r, mklab:concat nop)] -- | set axis labels data AxisLabels a = AxisLabels String String a | XLabel String a | YLabel String a instance PlotWithGnuplot a => PlotWithGnuplot (AxisLabels a) where multiPlot r (AxisLabels xlab ylab x) = do let mklabs = [TopLevelGnuplotCmd ("set xlabel "++show xlab) "unset xlabel", TopLevelGnuplotCmd ("set ylabel "++show ylab) "unset ylabel"] px <- multiPlot r x return $ map (\(r', pls) -> (r', mklabs++pls)) px multiPlot r (XLabel xlab x) = do let mklabs = [TopLevelGnuplotCmd ("set xlabel "++show xlab) "unset xlabel"] px <- multiPlot r x return $ map (\(r', pls) -> (r', mklabs++pls)) px multiPlot r (YLabel xlab x) = do let mklabs = [TopLevelGnuplotCmd ("set ylabel "++show xlab) "unset ylabel"] px <- multiPlot r x return $ map (\(r', pls) -> (r', mklabs++pls)) px -- | set the title of a plot instance PlotWithGnuplot a => PlotWithGnuplot (String, a) where multiPlot r (title, x) = do pls <- multiPlot r x return $ map (\(r', plines) -> (r' ,map (addTitle title) plines)) pls where addTitle title (PL x _ y clean) = PL x title y clean addTitle _ x = x
glutamate/gnewplot
Graphics/Gnewplot/Style.hs
bsd-3-clause
14,562
0
22
3,996
5,206
2,686
2,520
250
6
{- (c) Bartosz Nitka, Facebook, 2015 UniqDFM: Specialised deterministic finite maps, for things with @Uniques@. Basically, the things need to be in class @Uniquable@, and we use the @getUnique@ method to grab their @Uniques@. This is very similar to @UniqFM@, the major difference being that the order of folding is not dependent on @Unique@ ordering, giving determinism. Currently the ordering is determined by insertion order. See Note [Unique Determinism] in Unique for explanation why @Unique@ ordering is not deterministic. -} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-} {-# OPTIONS_GHC -Wall #-} module UniqDFM ( -- * Unique-keyed deterministic mappings UniqDFM, -- abstract type -- ** Manipulating those mappings emptyUDFM, unitUDFM, addToUDFM, addToUDFM_C, delFromUDFM, delListFromUDFM, adjustUDFM, alterUDFM, mapUDFM, plusUDFM, plusUDFM_C, lookupUDFM, elemUDFM, foldUDFM, eltsUDFM, filterUDFM, isNullUDFM, sizeUDFM, intersectUDFM, udfmIntersectUFM, intersectsUDFM, disjointUDFM, disjointUdfmUfm, minusUDFM, udfmMinusUFM, partitionUDFM, anyUDFM, udfmToList, udfmToUfm, nonDetFoldUDFM, alwaysUnsafeUfmToUdfm, ) where import Unique ( Uniquable(..), Unique, getKey ) import Outputable import qualified Data.IntMap as M import Data.Data import Data.List (sortBy) import Data.Function (on) import UniqFM (UniqFM, listToUFM_Directly, ufmToList, ufmToIntMap) -- Note [Deterministic UniqFM] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- A @UniqDFM@ is just like @UniqFM@ with the following additional -- property: the function `udfmToList` returns the elements in some -- deterministic order not depending on the Unique key for those elements. -- -- If the client of the map performs operations on the map in deterministic -- order then `udfmToList` returns them in deterministic order. -- -- There is an implementation cost: each element is given a serial number -- as it is added, and `udfmToList` sorts it's result by this serial -- number. So you should only use `UniqDFM` if you need the deterministic -- property. -- -- `foldUDFM` also preserves determinism. -- -- Normal @UniqFM@ when you turn it into a list will use -- Data.IntMap.toList function that returns the elements in the order of -- the keys. The keys in @UniqFM@ are always @Uniques@, so you end up with -- with a list ordered by @Uniques@. -- The order of @Uniques@ is known to be not stable across rebuilds. -- See Note [Unique Determinism] in Unique. -- -- -- There's more than one way to implement this. The implementation here tags -- every value with the insertion time that can later be used to sort the -- values when asked to convert to a list. -- -- An alternative would be to have -- -- data UniqDFM ele = UDFM (M.IntMap ele) [ele] -- -- where the list determines the order. This makes deletion tricky as we'd -- only accumulate elements in that list, but makes merging easier as you -- can just merge both structures independently. -- Deletion can probably be done in amortized fashion when the size of the -- list is twice the size of the set. -- | A type of values tagged with insertion time data TaggedVal val = TaggedVal val {-# UNPACK #-} !Int -- ^ insertion time deriving Data taggedFst :: TaggedVal val -> val taggedFst (TaggedVal v _) = v taggedSnd :: TaggedVal val -> Int taggedSnd (TaggedVal _ i) = i instance Eq val => Eq (TaggedVal val) where (TaggedVal v1 _) == (TaggedVal v2 _) = v1 == v2 instance Functor TaggedVal where fmap f (TaggedVal val i) = TaggedVal (f val) i -- | Type of unique deterministic finite maps data UniqDFM ele = UDFM !(M.IntMap (TaggedVal ele)) -- A map where keys are Unique's values and -- values are tagged with insertion time. -- The invariant is that all the tags will -- be distinct within a single map {-# UNPACK #-} !Int -- Upper bound on the values' insertion -- time. See Note [Overflow on plusUDFM] deriving (Data, Functor) emptyUDFM :: UniqDFM elt emptyUDFM = UDFM M.empty 0 unitUDFM :: Uniquable key => key -> elt -> UniqDFM elt unitUDFM k v = UDFM (M.singleton (getKey $ getUnique k) (TaggedVal v 0)) 1 addToUDFM :: Uniquable key => UniqDFM elt -> key -> elt -> UniqDFM elt addToUDFM (UDFM m i) k v = UDFM (M.insert (getKey $ getUnique k) (TaggedVal v i) m) (i + 1) addToUDFM_Directly :: UniqDFM elt -> Unique -> elt -> UniqDFM elt addToUDFM_Directly (UDFM m i) u v = UDFM (M.insert (getKey u) (TaggedVal v i) m) (i + 1) addToUDFM_Directly_C :: (elt -> elt -> elt) -> UniqDFM elt -> Unique -> elt -> UniqDFM elt addToUDFM_Directly_C f (UDFM m i) u v = UDFM (M.insertWith tf (getKey u) (TaggedVal v i) m) (i + 1) where tf (TaggedVal a j) (TaggedVal b _) = TaggedVal (f a b) j addToUDFM_C :: Uniquable key => (elt -> elt -> elt) -- old -> new -> result -> UniqDFM elt -- old -> key -> elt -- new -> UniqDFM elt -- result addToUDFM_C f (UDFM m i) k v = UDFM (M.insertWith tf (getKey $ getUnique k) (TaggedVal v i) m) (i + 1) where tf (TaggedVal a j) (TaggedVal b _) = TaggedVal (f b a) j -- Flip the arguments, just like -- addToUFM_C does. addListToUDFM_Directly :: UniqDFM elt -> [(Unique,elt)] -> UniqDFM elt addListToUDFM_Directly = foldl (\m (k, v) -> addToUDFM_Directly m k v) addListToUDFM_Directly_C :: (elt -> elt -> elt) -> UniqDFM elt -> [(Unique,elt)] -> UniqDFM elt addListToUDFM_Directly_C f = foldl (\m (k, v) -> addToUDFM_Directly_C f m k v) delFromUDFM :: Uniquable key => UniqDFM elt -> key -> UniqDFM elt delFromUDFM (UDFM m i) k = UDFM (M.delete (getKey $ getUnique k) m) i plusUDFM_C :: (elt -> elt -> elt) -> UniqDFM elt -> UniqDFM elt -> UniqDFM elt plusUDFM_C f udfml@(UDFM _ i) udfmr@(UDFM _ j) -- we will use the upper bound on the tag as a proxy for the set size, -- to insert the smaller one into the bigger one | i > j = insertUDFMIntoLeft_C f udfml udfmr | otherwise = insertUDFMIntoLeft_C f udfmr udfml -- Note [Overflow on plusUDFM] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- There are multiple ways of implementing plusUDFM. -- The main problem that needs to be solved is overlap on times of -- insertion between different keys in two maps. -- Consider: -- -- A = fromList [(a, (x, 1))] -- B = fromList [(b, (y, 1))] -- -- If you merge them naively you end up with: -- -- C = fromList [(a, (x, 1)), (b, (y, 1))] -- -- Which loses information about ordering and brings us back into -- non-deterministic world. -- -- The solution I considered before would increment the tags on one of the -- sets by the upper bound of the other set. The problem with this approach -- is that you'll run out of tags for some merge patterns. -- Say you start with A with upper bound 1, you merge A with A to get A' and -- the upper bound becomes 2. You merge A' with A' and the upper bound -- doubles again. After 64 merges you overflow. -- This solution would have the same time complexity as plusUFM, namely O(n+m). -- -- The solution I ended up with has time complexity of -- O(m log m + m * min (n+m, W)) where m is the smaller set. -- It simply inserts the elements of the smaller set into the larger -- set in the order that they were inserted into the smaller set. That's -- O(m log m) for extracting the elements from the smaller set in the -- insertion order and O(m * min(n+m, W)) to insert them into the bigger -- set. plusUDFM :: UniqDFM elt -> UniqDFM elt -> UniqDFM elt plusUDFM udfml@(UDFM _ i) udfmr@(UDFM _ j) -- we will use the upper bound on the tag as a proxy for the set size, -- to insert the smaller one into the bigger one | i > j = insertUDFMIntoLeft udfml udfmr | otherwise = insertUDFMIntoLeft udfmr udfml insertUDFMIntoLeft :: UniqDFM elt -> UniqDFM elt -> UniqDFM elt insertUDFMIntoLeft udfml udfmr = addListToUDFM_Directly udfml $ udfmToList udfmr insertUDFMIntoLeft_C :: (elt -> elt -> elt) -> UniqDFM elt -> UniqDFM elt -> UniqDFM elt insertUDFMIntoLeft_C f udfml udfmr = addListToUDFM_Directly_C f udfml $ udfmToList udfmr lookupUDFM :: Uniquable key => UniqDFM elt -> key -> Maybe elt lookupUDFM (UDFM m _i) k = taggedFst `fmap` M.lookup (getKey $ getUnique k) m elemUDFM :: Uniquable key => key -> UniqDFM elt -> Bool elemUDFM k (UDFM m _i) = M.member (getKey $ getUnique k) m -- | Performs a deterministic fold over the UniqDFM. -- It's O(n log n) while the corresponding function on `UniqFM` is O(n). foldUDFM :: (elt -> a -> a) -> a -> UniqDFM elt -> a foldUDFM k z m = foldr k z (eltsUDFM m) -- | Performs a nondeterministic fold over the UniqDFM. -- It's O(n), same as the corresponding function on `UniqFM`. -- If you use this please provide a justification why it doesn't introduce -- nondeterminism. nonDetFoldUDFM :: (elt -> a -> a) -> a -> UniqDFM elt -> a nonDetFoldUDFM k z (UDFM m _i) = foldr k z $ map taggedFst $ M.elems m eltsUDFM :: UniqDFM elt -> [elt] eltsUDFM (UDFM m _i) = map taggedFst $ sortBy (compare `on` taggedSnd) $ M.elems m filterUDFM :: (elt -> Bool) -> UniqDFM elt -> UniqDFM elt filterUDFM p (UDFM m i) = UDFM (M.filter (\(TaggedVal v _) -> p v) m) i -- | Converts `UniqDFM` to a list, with elements in deterministic order. -- It's O(n log n) while the corresponding function on `UniqFM` is O(n). udfmToList :: UniqDFM elt -> [(Unique, elt)] udfmToList (UDFM m _i) = [ (getUnique k, taggedFst v) | (k, v) <- sortBy (compare `on` (taggedSnd . snd)) $ M.toList m ] isNullUDFM :: UniqDFM elt -> Bool isNullUDFM (UDFM m _) = M.null m sizeUDFM :: UniqDFM elt -> Int sizeUDFM (UDFM m _i) = M.size m intersectUDFM :: UniqDFM elt -> UniqDFM elt -> UniqDFM elt intersectUDFM (UDFM x i) (UDFM y _j) = UDFM (M.intersection x y) i -- M.intersection is left biased, that means the result will only have -- a subset of elements from the left set, so `i` is a good upper bound. udfmIntersectUFM :: UniqDFM elt -> UniqFM elt -> UniqDFM elt udfmIntersectUFM (UDFM x i) y = UDFM (M.intersection x (ufmToIntMap y)) i -- M.intersection is left biased, that means the result will only have -- a subset of elements from the left set, so `i` is a good upper bound. intersectsUDFM :: UniqDFM elt -> UniqDFM elt -> Bool intersectsUDFM x y = isNullUDFM (x `intersectUDFM` y) disjointUDFM :: UniqDFM elt -> UniqDFM elt -> Bool disjointUDFM (UDFM x _i) (UDFM y _j) = M.null (M.intersection x y) disjointUdfmUfm :: UniqDFM elt -> UniqFM elt2 -> Bool disjointUdfmUfm (UDFM x _i) y = M.null (M.intersection x (ufmToIntMap y)) minusUDFM :: UniqDFM elt1 -> UniqDFM elt2 -> UniqDFM elt1 minusUDFM (UDFM x i) (UDFM y _j) = UDFM (M.difference x y) i -- M.difference returns a subset of a left set, so `i` is a good upper -- bound. udfmMinusUFM :: UniqDFM elt1 -> UniqFM elt2 -> UniqDFM elt1 udfmMinusUFM (UDFM x i) y = UDFM (M.difference x (ufmToIntMap y)) i -- M.difference returns a subset of a left set, so `i` is a good upper -- bound. -- | Partition UniqDFM into two UniqDFMs according to the predicate partitionUDFM :: (elt -> Bool) -> UniqDFM elt -> (UniqDFM elt, UniqDFM elt) partitionUDFM p (UDFM m i) = case M.partition (p . taggedFst) m of (left, right) -> (UDFM left i, UDFM right i) -- | Delete a list of elements from a UniqDFM delListFromUDFM :: Uniquable key => UniqDFM elt -> [key] -> UniqDFM elt delListFromUDFM = foldl delFromUDFM -- | This allows for lossy conversion from UniqDFM to UniqFM udfmToUfm :: UniqDFM elt -> UniqFM elt udfmToUfm (UDFM m _i) = listToUFM_Directly [(getUnique k, taggedFst tv) | (k, tv) <- M.toList m] listToUDFM_Directly :: [(Unique, elt)] -> UniqDFM elt listToUDFM_Directly = foldl (\m (u, v) -> addToUDFM_Directly m u v) emptyUDFM -- | Apply a function to a particular element adjustUDFM :: Uniquable key => (elt -> elt) -> UniqDFM elt -> key -> UniqDFM elt adjustUDFM f (UDFM m i) k = UDFM (M.adjust (fmap f) (getKey $ getUnique k) m) i -- | The expression (alterUDFM f k map) alters value x at k, or absence -- thereof. alterUDFM can be used to insert, delete, or update a value in -- UniqDFM. Use addToUDFM, delFromUDFM or adjustUDFM when possible, they are -- more efficient. alterUDFM :: Uniquable key => (Maybe elt -> Maybe elt) -- How to adjust -> UniqDFM elt -- old -> key -- new -> UniqDFM elt -- result alterUDFM f (UDFM m i) k = UDFM (M.alter alterf (getKey $ getUnique k) m) (i + 1) where alterf Nothing = inject $ f Nothing alterf (Just (TaggedVal v _)) = inject $ f (Just v) inject Nothing = Nothing inject (Just v) = Just $ TaggedVal v i -- | Map a function over every value in a UniqDFM mapUDFM :: (elt1 -> elt2) -> UniqDFM elt1 -> UniqDFM elt2 mapUDFM f (UDFM m i) = UDFM (M.map (fmap f) m) i anyUDFM :: (elt -> Bool) -> UniqDFM elt -> Bool anyUDFM p (UDFM m _i) = M.fold ((||) . p . taggedFst) False m instance Monoid (UniqDFM a) where mempty = emptyUDFM mappend = plusUDFM -- This should not be used in commited code, provided for convenience to -- make ad-hoc conversions when developing alwaysUnsafeUfmToUdfm :: UniqFM elt -> UniqDFM elt alwaysUnsafeUfmToUdfm = listToUDFM_Directly . ufmToList -- Output-ery instance Outputable a => Outputable (UniqDFM a) where ppr ufm = pprUniqDFM ppr ufm pprUniqDFM :: (a -> SDoc) -> UniqDFM a -> SDoc pprUniqDFM ppr_elt ufm = brackets $ fsep $ punctuate comma $ [ ppr uq <+> text ":->" <+> ppr_elt elt | (uq, elt) <- udfmToList ufm ]
vikraman/ghc
compiler/utils/UniqDFM.hs
bsd-3-clause
13,800
0
13
3,079
3,333
1,745
1,588
182
3
module MasterSlave where import Control.Monad import Control.Distributed.Process import Control.Distributed.Process.Closure import PrimeFactors slave :: (ProcessId, Integer) -> Process () slave (pid, n) = send pid (numPrimeFactors n) remotable ['slave] -- | Wait for n integers and sum them all up sumIntegers :: Int -> Process Integer sumIntegers = go 0 where go :: Integer -> Int -> Process Integer go !acc 0 = return acc go !acc n = do m <- expect go (acc + m) (n - 1) data SpawnStrategy = SpawnSyncWithReconnect | SpawnSyncNoReconnect | SpawnAsync deriving (Show, Read) master :: Integer -> SpawnStrategy -> [NodeId] -> Process Integer master n spawnStrategy slaves = do us <- getSelfPid -- Distribute 1 .. n amongst the slave processes spawnLocal $ case spawnStrategy of SpawnSyncWithReconnect -> forM_ (zip [1 .. n] (cycle slaves)) $ \(m, there) -> do them <- spawn there ($(mkClosure 'slave) (us, m)) reconnect them SpawnSyncNoReconnect -> forM_ (zip [1 .. n] (cycle slaves)) $ \(m, there) -> do _them <- spawn there ($(mkClosure 'slave) (us, m)) return () SpawnAsync -> forM_ (zip [1 .. n] (cycle slaves)) $ \(m, there) -> do spawnAsync there ($(mkClosure 'slave) (us, m)) _ <- expectTimeout 0 :: Process (Maybe DidSpawn) return () -- Wait for the result sumIntegers (fromIntegral n)
haskell-distributed/distributed-process-demos
src/MasterSlave/MasterSlave.hs
bsd-3-clause
1,462
0
21
379
532
274
258
-1
-1
module Types where import Data.Map import Data.Word -------------------------------------------------------------------------------- data Colour = Colour { red :: Word8, green :: Word8, blue :: Word8 } deriving (Show) data Config = Config { borderColour :: Colour, wraparound :: Bool, nations :: Map String Colour, provinces :: Map Int String } deriving (Show)
Ornedan/dom3conquestmaptool
Types.hs
bsd-3-clause
518
0
9
206
99
60
39
12
0
{-# OPTIONS_GHC -Wall #-} module Elm.Internal.Paths where import Build.Utils (getDataFile) import System.IO.Unsafe (unsafePerformIO) -- |Name of directory for all of a project's dependencies. dependencyDirectory :: FilePath dependencyDirectory = "elm_dependencies" -- |Name of the dependency file, specifying dependencies and -- other metadata for building and sharing projects. dependencyFile :: FilePath dependencyFile = "elm_dependencies.json" {-# NOINLINE runtime #-} -- |The absolute path to Elm's runtime system. runtime :: FilePath runtime = unsafePerformIO $ getDataFile "elm-runtime.js" {-# NOINLINE docs #-} -- |The absolute path to Elm's core library documentation. docs :: FilePath docs = unsafePerformIO $ getDataFile "docs.json"
deadfoxygrandpa/Elm
compiler/Elm/Internal/Paths.hs
bsd-3-clause
749
0
6
101
90
56
34
14
1
{-| Module : Manifest.SQLite Description : An SQLite-backed Manifest. copyright : (c) Alexander Vieth, 2015 Licence : BSD3 Maintainer : aovieth@gmail.com Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Manifest.SQLite ( SQLiteManifestSingle , sqliteSingle , SQLiteManifestMultiple , sqliteMultiple , TextSerializable(..) ) where import qualified Data.DependentMap as DM import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as B8 import qualified Data.Text as T import Data.String import Data.Typeable import Control.Applicative import Control.Monad import Control.Monad.Trans.State import Control.Monad.IO.Class import Control.Exception import Database.SQLite.Simple import Manifest.Manifest import Manifest.ManifestException import Manifest.Resource -- | A database file name describes the SQLite manifest. -- Empty string or ":memory:" gives an in-memory database which is lost -- once the associated resource is closed. You probably don't want that. data SQLiteDescriptor = SQLD String deriving (Eq, Ord, Typeable) instance ResourceDescriptor SQLiteDescriptor where type ResourceType SQLiteDescriptor = Connection acquireResource (SQLD str) = do conn <- open str beginTransaction conn return $ Resource conn commit rollback release where beginTransaction conn = execute_ conn "BEGIN TRANSACTION" rollback conn = execute_ conn "ROLLBACK TRANSACTION" commit conn = execute_ conn "COMMIT TRANSACTION" release = close -- | An SQLiteManifest. Assumes the provided SQLiteDescriptor picks out a -- database which has a table of the specified name, with two columns as -- specified. data SQLiteManifestSingle :: Access -> * -> * -> * where SQLiteManifestSingle :: SQLiteDescriptor -> B8.ByteString -- ^ Name of the table to use. -> B8.ByteString -- ^ Column name for domain -> B8.ByteString -- ^ Column name for range -> SQLiteManifestSingle access domain range data SQLiteManifestMultiple :: Access -> * -> * -> * where SQLiteManifestMultiple :: SQLiteDescriptor -> B8.ByteString -> B8.ByteString -> B8.ByteString -> SQLiteManifestMultiple access domain range sqliteSingle :: String -> B8.ByteString -> B8.ByteString -> B8.ByteString -> SQLiteManifestSingle access domain range sqliteSingle file = SQLiteManifestSingle (SQLD file) sqliteMultiple :: String -> B8.ByteString -> B8.ByteString -> B8.ByteString -> SQLiteManifestMultiple access domain range sqliteMultiple file = SQLiteManifestMultiple (SQLD file) class TextSerializable a where textSerialize :: a -> T.Text textDeserialize :: T.Text -> Maybe a instance TextSerializable () where textSerialize = const "" textDeserialize = const (Just ()) instance TextSerializable Int where textSerialize = T.pack . show textDeserialize t = case reads (T.unpack t) :: [(Int, [Char])] of [(i, [])] -> Just i _ -> Nothing instance TextSerializable T.Text where textSerialize = id textDeserialize = Just instance Manifest SQLiteManifestSingle where type ManifestResourceDescriptor SQLiteManifestSingle access domain range = SQLiteDescriptor resourceDescriptor (SQLiteManifestSingle sqld _ _ _) = sqld type ManifestDomainType SQLiteManifestSingle domain range = T.Text type ManifestRangeType SQLiteManifestSingle domain range = T.Text type ManifestDomainConstraint SQLiteManifestSingle domain range = TextSerializable domain type ManifestRangeConstraint SQLiteManifestSingle domain range = TextSerializable range type ManifestFunctor SQLiteManifestSingle domain range = Maybe mdomainDump _ = textSerialize mrangePull _ = textDeserialize instance ManifestRead SQLiteManifestSingle where mget (SQLiteManifestSingle _ tableName domainName rangeName) conn key = do let statement = [ "SELECT \"" , rangeName , "\" FROM " , tableName , " WHERE \"" , domainName , "\"=?" ] let queryString = fromString . B8.unpack . BS.concat $ statement -- ^ SQLite simple doesn't allow query substitution for table name and -- where clause simultaneously :( y <- query conn queryString (Only key) return $ case y :: [Only T.Text] of [] -> Nothing (y' : _) -> Just (fromOnly y') -- ^ TBD should we warn in case more than one row is found? instance ManifestWrite SQLiteManifestSingle where mrangeDump _ = textSerialize mset (SQLiteManifestSingle _ tableName domainName rangeName) conn key value = case value of Nothing -> do let statement = [ "DELETE FROM " , tableName , " WHERE \"" , domainName , "\"=?" ] let queryString = fromString . B8.unpack . BS.concat $ statement execute conn queryString (Only key) Just value -> do let statement = [ "INSERT OR REPLACE INTO " , tableName , " (\"" , domainName , "\", \"" , rangeName , "\") VALUES (?, ?)" ] let queryString = fromString . B8.unpack . BS.concat $ statement liftIO $ execute conn queryString (key, value) instance Manifest SQLiteManifestMultiple where type ManifestResourceDescriptor SQLiteManifestMultiple access domain range = SQLiteDescriptor resourceDescriptor (SQLiteManifestMultiple sqld _ _ _) = sqld type ManifestDomainType SQLiteManifestMultiple domain range = T.Text type ManifestRangeType SQLiteManifestMultiple domain range = T.Text type ManifestDomainConstraint SQLiteManifestMultiple domain range = TextSerializable domain type ManifestRangeConstraint SQLiteManifestMultiple domain range = TextSerializable range type ManifestFunctor SQLiteManifestMultiple domain range = [] mdomainDump _ = textSerialize mrangePull _ x = case textDeserialize x of Nothing -> [] Just x' -> [x'] instance ManifestRead SQLiteManifestMultiple where mget (SQLiteManifestMultiple _ tableName domainName rangeName) conn key = do let statement = [ "SELECT \"" , rangeName , "\" FROM " , tableName , " WHERE \"" , domainName , "\"=?" ] let queryString = fromString . B8.unpack . BS.concat $ statement -- ^ SQLite simple doesn't allow query substitution for table name and -- where clause simultaneously :( y <- query conn queryString (Only key) return $ case y :: [Only T.Text] of ys -> fromOnly <$> ys instance ManifestWrite SQLiteManifestMultiple where mrangeDump _ = textSerialize mset (SQLiteManifestMultiple _ tableName domainName rangeName) conn key value = do -- Delete every record with the key. let deleteStatement = [ "DELETE FROM " , tableName , " WHERE \"" , domainName , "\"=?" ] let queryString = fromString . B8.unpack . BS.concat $ deleteStatement execute conn queryString (Only key) -- Now insert everything in the value list. let insertStatement = [ "INSERT INTO " , tableName , " (\"" , domainName , "\", \"" , rangeName , "\") VALUES (?, ?)" ] let queryString = fromString . B8.unpack . BS.concat $ insertStatement forM_ value (\v -> liftIO $ execute conn queryString (key, v))
avieth/Manifest
Manifest/SQLite.hs
bsd-3-clause
8,338
5
17
2,405
1,537
831
706
163
1
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE DataKinds, FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} -- FIXME {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module ArrayAggTest where import Control.Monad.IO.Class (MonadIO) import Data.Aeson import Data.List (sort) import qualified Data.Text as T import Test.Hspec.Expectations () import PersistentTestModels import PgInit share [mkPersist persistSettings, mkMigrate "jsonTestMigrate"] [persistLowerCase| TestValue json Value |] cleanDB :: (BaseBackend backend ~ SqlBackend, PersistQueryWrite backend, MonadIO m) => ReaderT backend m () cleanDB = deleteWhere ([] :: [Filter TestValue]) emptyArr :: Value emptyArr = toJSON ([] :: [Value]) specs :: Spec specs = do describe "rawSql/array_agg" $ do let runArrayAggTest :: (PersistField [a], Ord a, Show a) => Text -> [a] -> Assertion runArrayAggTest dbField expected = runConnAssert $ do void $ insertMany [ UserPT "a" $ Just "b" , UserPT "c" $ Just "d" , UserPT "e" Nothing , UserPT "g" $ Just "h" ] escape <- getEscapeRawNameFunction let query = T.concat [ "SELECT array_agg(", escape dbField, ") " , "FROM ", escape "UserPT" ] [Single xs] <- rawSql query [] liftIO $ sort xs @?= expected it "works for [Text]" $ do runArrayAggTest "ident" ["a", "c", "e", "g" :: Text] it "works for [Maybe Text]" $ do runArrayAggTest "password" [Nothing, Just "b", Just "d", Just "h" :: Maybe Text]
yesodweb/persistent
persistent-postgresql/test/ArrayAggTest.hs
mit
1,901
0
21
462
466
248
218
44
1
main = 3 'div' 4
roberth/uu-helium
test/thompson/Thompson01.hs
gpl-3.0
17
0
5
5
12
6
6
-1
-1
{-# LANGUAGE TypeOperators, BangPatterns, Rank2Types, PatternGuards , ExistentialQuantification, ScopedTypeVariables, GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- temp {-# OPTIONS_GHC -Wall #-} ---------------------------------------------------------------------- -- | -- Module : Data.PolyStableMemo -- Copyright : (c) Conal Elliott 2009 -- License : AGPLv3 -- -- Maintainer : conal@conal.net -- Stability : experimental -- -- Polymorphic memoization based using stable names. ---------------------------------------------------------------------- module Data.PolyStableMemo ((:-->),memo) where -- ,memo2,memo3 import System.IO.Unsafe (unsafePerformIO) import Control.Concurrent.MVar import System.Mem.StableName import qualified Data.IntMap as I -- import Shady.Language.Graph -- import Shady.Language.Operator -- import Shady.Language.Exp -- import Shady.Language.Graph import Shady.Language.Type -- Stable names have EQ but not Ord, so they're not convenient for fast -- maps. On the other hand, there's 'hashStableName', which generates an -- 'Int', with rare collisions. So represent the memo table as an IntMap -- whose entries are lists of StableName/value pairs. -- @(k a, v a)@ pair data StableBind k v = forall a. HasType a => SB (StableName (k a)) (v a) -- Polymorphic function type k :--> v = forall a. (HasType a, Show a) => k a -> v a -- Sorry about the 'Show' constraint. Turns out to be needed indirectly, -- due to constant folding. -- Stable map type SM k v = I.IntMap [StableBind k v] -- | Pointer-based memoization. Evaluates keys to WHNF to improve hit rate. memo :: (k :--> v) -> (k :--> v) -- memo :: (forall a. HasType a => k a -> v a) -> (forall a. HasType a => k a -> v a) -- memo :: HasType a => (k a -> v a) -> (k a -> v a) memo f = fetch f (unsafePerformIO (newMVar I.empty)) {- -- polymorphic function newtype Pfun p q a = Pfun { unPfun :: p a -> q a } -- | Memoized binary function -- memo2 :: HasType a => -- (k a -> l a -> v a) -> (k a -> l a -> v a) memo2 :: (forall a. HasType a => k a -> l a -> v a) -> (forall a. HasType a => k a -> l a -> v a) memo2 h = unPfun . memo (Pfun . memo . h) -- h :: k a -> l a -> v a -- memo . h :: k a -> l a -> v a -- Pfun . memo . h :: k a -> Pfun l v a -- memo (Pfun . memo . h) :: k a -> Pfun l v a -- unPfun . memo (Pfun . memo . h) :: k a -> l a -> v a -- | Memoized binary function memo3 :: HasType a => (k a -> l a -> m a -> v a) -> (k a -> l a -> m a -> v a) memo3 h = unPfun . memo (Pfun . memo2 . h) pfun2 :: (l a -> m a -> v a) -> Pfun l (Pfun m v) a pfun2 = Pfun . fmap Pfun unPfun2 :: Pfun l (Pfun m v) a -> (l a -> m a -> v a) unPfun2 = fmap unPfun . unPfun -- h :: k a -> l a -> m a -> v a -- memo2 . h :: k a -> l a -> m a -> v a -- pfun2 . memo2 . h :: k a -> Pfun l (Pfun m v) a -- memo (pfun2 . memo2 . h) :: k a -> Pfun l (Pfun m v) a -- unPfun2 . memo (pfun2 . memo2 . h) :: k a -> l a -> m a -> v a -- I worry that the function compositions will lose sharing. -- -- | Memoized ternary function -- memo3 :: HasType a => -- (k a -> l a -> m a -> v a) -> (k a -> l a -> m a -> v a) -- memo3 h = unPfun2 . memo (pfun2 . memo2 . h) -} -- TODO: Make lazy and strict versions. -- fetch :: (k :--> v) -> MVar (SM k v) -> (k :--> v) fetch :: HasType a => (k a -> v a) -> MVar (SM k v) -> (k a -> v a) fetch f smv !k = unsafePerformIO $ do st <- makeStableName k modifyMVar smv $ \ sm -> return $ let h = hashStableName st in maybe (let v = f k in (I.insertWith (++) h [SB st v] sm, v)) -- new ((,) sm) -- found (I.lookup h sm >>= blookup st) -- look blookup :: forall k v a. HasType a => StableName (k a) -> [StableBind k v] -> Maybe (v a) blookup stk = look where look :: [StableBind k v] -> Maybe (v a) look [] = Nothing look (SB stk' v : binds') | Just Refl <- tya `tyEq` typeOf2 stk', stk == stk' = Just v | otherwise = look binds' tya :: Type a tya = typeT
sseefried/shady-gen
src/Data/PolyStableMemo.hs
agpl-3.0
4,275
0
20
1,255
615
336
279
34
2
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Model.Markdown.Diff where import Prelude import Data.Algorithm.Diff import Yesod.Markdown import Database.Persist.TH import Data.Maybe import qualified Data.Text as T data DiffInfo = S | B | F deriving (Eq, Ord, Read, Show) data MarkdownDiff = MarkdownDiff [(DiffInfo, T.Text)] deriving (Show, Read, Eq, Ord) derivePersistField "MarkdownDiff" diffSecond :: [(DiffInfo, a)] -> [a] diffSecond = let not_first (B, s) = Just s not_first (S, s) = Just s not_first _ = Nothing in mapMaybe not_first markdownDiffSecond :: MarkdownDiff -> Markdown markdownDiffSecond (MarkdownDiff diff) = Markdown . T.concat . diffSecond $ diff diffToDiffInfo :: Diff a -> (DiffInfo, a) diffToDiffInfo (First x) = (F, x) diffToDiffInfo (Both _ x) = (B, x) diffToDiffInfo (Second x) = (S, x) diffMarkdown :: Markdown -> Markdown -> MarkdownDiff diffMarkdown (Markdown m1) (Markdown m2) = MarkdownDiff $ map diffToDiffInfo $ getDiff (T.lines m1) (T.lines m2)
chreekat/snowdrift
Model/Markdown/Diff.hs
agpl-3.0
1,031
0
10
188
379
207
172
-1
-1
{- Each project can generate invitation codes to give users special roles such as Moderator or Team Member or Admin. Invitation.hs is where invited users go to actually redeem invitations they receive. -} module Handler.Invitation where import Import import qualified Data.Text as T -- import Model.Role getInvitationR :: Text -> Text -> Handler Html getInvitationR project_handle code = do (Entity _ project, Entity _ invite) <- runYDB $ (,) <$> getBy404 (UniqueProjectHandle project_handle) <*> getBy404 (UniqueInvite code) maybe_user_id <- maybeAuthId unless (isJust maybe_user_id) setUltDestCurrent alreadyExpired let redeemed = inviteRedeemed invite || isJust (inviteRedeemedBy invite) defaultLayout $ do snowdriftDashTitle (projectName project <> " Invitation") (T.pack . show $ inviteRole invite) $(widgetFile "invitation") postInvitationR :: Text -> Text -> Handler Html postInvitationR _ code = do viewer_id :: UserId <- requireAuthId now <- liftIO getCurrentTime _ <- runYDB $ do Entity invite_id invite <- getBy404 $ UniqueInvite code if inviteRedeemed invite then return Nothing else do -- TODO make sure project handle matches invite update $ \i -> do set i [ InviteRedeemed =. val True , InviteRedeemedTs =. val (Just now) , InviteRedeemedBy =. val (Just viewer_id) ] where_ ( i ^. InviteId ==. val invite_id ) _ <- insertUnique $ ProjectUserRole (inviteProject invite) viewer_id (inviteRole invite) -- TODO: update return $ Just $ inviteRole invite redirectUltDest HomeR
chreekat/snowdrift
Handler/Invitation.hs
agpl-3.0
1,794
0
23
525
429
204
225
-1
-1
module HplAssets.DTMC ( transformDtmc, emptyDtmc ) where import BasicTypes import HplAssets.DTMC.Types import FeatureModel.Types import Data.Generics import Data.List import Data.Maybe import Data.FDTMC (FeatureSelection, resolve, append, compose) emptyDtmc :: DtmcModel -> DtmcModel emptyDtmc dtmcmodel = dtmcmodel { dtmcs = [] } transformDtmc :: DtmcTransformation -> DtmcModel -> FeatureConfiguration -> DtmcModel -> DtmcModel transformDtmc (SelectDTMC ids) model features product = product { dtmcs = selected } where selected = (dtmcs product) ++ map (resolve' features) chosenDtmcs chosenDtmcs = filter ((`elem` ids) . dtmcId) $ dtmcs model transformDtmc (AppendDTMC id point) model features product = product { dtmcs = appended } where appended = map (append' chosenDtmc point ) (dtmcs product) chosenDtmc = fromMaybe (error "No fdtmc to append") $ find (\dtmc -> dtmcId dtmc == id) $ dtmcs model transformDtmc (ComposeDTMC id startpoint endpoint) model features product = product { dtmcs = composed } where composed = map (compose' chosenDtmc startpoint endpoint) (dtmcs product) chosenDtmc = fromMaybe (error "No fdtmc to append") $ find (\dtmc -> dtmcId dtmc == id) $ dtmcs model resolve' :: FeatureConfiguration -> Dtmc -> Dtmc resolve' features dtmc = dtmc { chain = resolve (chain dtmc) featureVars } where featureVars = translateFeatureConfiguration features append' :: Dtmc -> Pointcut -> Dtmc -> Dtmc append' fragment pointcut base = Dtmc { dtmcId = (dtmcId base), chain = append (chain base) (chain fragment) pointcut } compose' :: Dtmc -> Pointcut -> Pointcut -> Dtmc -> Dtmc compose' fragment startpoint endpoint base = Dtmc { dtmcId = (dtmcId base), chain = compose (chain base) (chain fragment) startpoint endpoint } translateFeatureConfiguration :: FeatureConfiguration -> FeatureSelection translateFeatureConfiguration config = map (head . fId) flatFeatures where flatFeatures = map fnode (flatten $ fcTree config)
rbonifacio/hephaestus-pl
src/meta-hephaestus/HplAssets/DTMC.hs
lgpl-3.0
2,099
0
13
441
643
341
302
35
1
{- Copyright 2016 Markus Ongyerth This file is part of Monky. Monky is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Monky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Monky. If not, see <http://www.gnu.org/licenses/>. -} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-| Module : Monky.Outputs.Guess Description : Guess the output that should be used based on pipe Maintainer : ongy Stability : testing Portability : Linux -} module Monky.Outputs.Guess ( guessOutput , GuessOut , guessOutputDiv ) where import Data.Text (Text) import Control.Exception (try) import Data.Char (isDigit) import Data.List (isPrefixOf) import Data.Maybe (catMaybes) import System.Directory (getDirectoryContents) import System.IO (hIsTerminalDevice, stdout) import System.Posix.Files (readSymbolicLink) import Monky.Modules import Monky.Outputs.Fallback (chooseTerminalOut) import Monky.Outputs.Show (getShowOut) import Monky.Outputs.Dzen2 (getDzenOutDiv) import Monky.Outputs.I3 (getI3Output) import Monky.Outputs.Serialize (getSerializeOut) #if MIN_VERSION_base(4,8,0) #else import Control.Applicative ((<$>)) #endif data Output = Terminal | Process String | Other deriving (Eq, Ord, Show) -- | Type wrapper for this to work data GuessOut = forall a . MonkyOutput a => GO a instance MonkyOutput GuessOut where doLine (GO o) = doLine o networkOuts :: [String] networkOuts = ["netcat", "nc", "socat"] fdToPath :: String -> Int -> IO String fdToPath proc fd = readSymbolicLink ("/proc/" ++ proc ++ "/fd/" ++ show fd) getProcFds :: String -> IO (Maybe (String, [(Int, String)])) getProcFds proc = do ret <- try $ do fds <- map read . filter (not . isPrefixOf ".") <$> getDirectoryContents ("/proc/" ++ proc ++ "/fd/") paths <- mapM (fdToPath proc) fds exe <- readSymbolicLink ("/proc/" ++ proc ++ "/exe") return (reverse . takeWhile (/= '/') . reverse $ exe, zip fds paths) return $ case ret of (Left (_ :: IOError)) -> Nothing (Right x) -> Just x hasPipe :: String -> (String, [(Int, String)]) -> Bool hasPipe pipe (_, xs) = any (\(fd, path) -> path == pipe && fd /= 1) xs pickCandidate :: String -> [(String, [(Int, String)])] -> Maybe String pickCandidate _ [] = Nothing pickCandidate _ [(x, _)] = Just x pickCandidate pipe xs = let std = filter (\(_, ys) -> any (\(i, path) -> i == 1 && path == pipe) ys) xs in Just . fst $ if null std then head xs else head std getOutputType :: IO Output getOutputType = do term <- hIsTerminalDevice stdout if term then return Terminal else do procs <- filter (all isDigit) <$> getDirectoryContents "/proc" fds <- catMaybes <$> mapM getProcFds procs own <- readSymbolicLink ("/proc/self/fd/1") let candidates = filter (hasPipe own) fds let candidate = pickCandidate own candidates return $ case candidate of Nothing -> Other (Just x) -> Process x -- Same inputs as 'gessOutput' chooseProcessOut :: Int -> Text -> MonkyOut -> String -> IO GuessOut chooseProcessOut height path divider x | x == "dzen2" = GO <$> getDzenOutDiv height path divider | x == "i3bar" = GO <$> getI3Output | x `elem`networkOuts = GO <$> getSerializeOut | otherwise = GO <$> getShowOut -- | Guess output based on isatty and other side of the stdout fd guessOutput :: Int -- ^Dzen height -> Text -- ^Dzen xbm path -> IO GuessOut guessOutput height path = guessOutputDiv height path $ MonkyPlain " | " -- | Guess output based on isatty and other side of the stdout fd guessOutputDiv :: Int -- ^Dzen height -> Text -- ^Dzen xbm path -> MonkyOut -- ^The Divider to use -> IO GuessOut guessOutputDiv height path divider = do out <- getOutputType case out of Terminal -> GO <$> chooseTerminalOut Other -> {- for other we just use show -} GO <$> getShowOut (Process x) -> chooseProcessOut height path divider x
monky-hs/monky
Monky/Outputs/Guess.hs
lgpl-3.0
4,499
8
20
943
1,139
607
532
96
3
module Network.Haskoin.Test.Util where import qualified Data.ByteString as BS import Data.Time.Clock (UTCTime (..)) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import Data.Word (Word32) import Test.QuickCheck -- | Arbitrary strict ByteString arbitraryBS :: Gen BS.ByteString arbitraryBS = BS.pack `fmap` arbitrary -- | Arbitrary strict ByteString that is not empty arbitraryBS1 :: Gen BS.ByteString arbitraryBS1 = BS.pack `fmap` listOf1 arbitrary -- | Arbitrary strict ByteString of a given length arbitraryBSn :: Int -> Gen BS.ByteString arbitraryBSn n = BS.pack `fmap` vectorOf n arbitrary -- | Arbitrary UTCTime that generates dates after 01 Jan 1970 01:00:00 CET arbitraryUTCTime :: Gen UTCTime arbitraryUTCTime = do w <- arbitrary :: Gen Word32 return $ posixSecondsToUTCTime $ realToFrac w -- | Generate a Maybe from a Gen a arbitraryMaybe :: Gen a -> Gen (Maybe a) arbitraryMaybe g = frequency [ (1, return Nothing) , (5, Just <$> g) ]
xenog/haskoin
src/Network/Haskoin/Test/Util.hs
unlicense
1,089
0
8
276
244
138
106
19
1
{- misc utility functions - - Copyright 2010-2011 Joey Hess <id@joeyh.name> - - License: BSD-2-clause -} {-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-tabs #-} module Utility.Misc where import Utility.FileSystemEncoding import Utility.Monad import System.IO import Control.Monad import Foreign import Data.Char import Data.List import System.Exit #ifndef mingw32_HOST_OS import System.Posix.Process (getAnyProcessStatus) import Utility.Exception #endif import Control.Applicative import Prelude {- A version of hgetContents that is not lazy. Ensures file is - all read before it gets closed. -} hGetContentsStrict :: Handle -> IO String hGetContentsStrict = hGetContents >=> \s -> length s `seq` return s {- A version of readFile that is not lazy. -} readFileStrict :: FilePath -> IO String readFileStrict = readFile >=> \s -> length s `seq` return s {- Reads a file strictly, and using the FileSystemEncoding, so it will - never crash on a badly encoded file. -} readFileStrictAnyEncoding :: FilePath -> IO String readFileStrictAnyEncoding f = withFile f ReadMode $ \h -> do fileEncoding h hClose h `after` hGetContentsStrict h {- Writes a file, using the FileSystemEncoding so it will never crash - on a badly encoded content string. -} writeFileAnyEncoding :: FilePath -> String -> IO () writeFileAnyEncoding f content = withFile f WriteMode $ \h -> do fileEncoding h hPutStr h content {- Like break, but the item matching the condition is not included - in the second result list. - - separate (== ':') "foo:bar" = ("foo", "bar") - separate (== ':') "foobar" = ("foobar", "") -} separate :: (a -> Bool) -> [a] -> ([a], [a]) separate c l = unbreak $ break c l where unbreak r@(a, b) | null b = r | otherwise = (a, tail b) {- Breaks out the first line. -} firstLine :: String -> String firstLine = takeWhile (/= '\n') {- Splits a list into segments that are delimited by items matching - a predicate. (The delimiters are not included in the segments.) - Segments may be empty. -} segment :: (a -> Bool) -> [a] -> [[a]] segment p l = map reverse $ go [] [] l where go c r [] = reverse $ c:r go c r (i:is) | p i = go [] (c:r) is | otherwise = go (i:c) r is prop_segment_regressionTest :: Bool prop_segment_regressionTest = all id -- Even an empty list is a segment. [ segment (== "--") [] == [[]] -- There are two segements in this list, even though the first is empty. , segment (== "--") ["--", "foo", "bar"] == [[],["foo","bar"]] ] {- Includes the delimiters as segments of their own. -} segmentDelim :: (a -> Bool) -> [a] -> [[a]] segmentDelim p l = map reverse $ go [] [] l where go c r [] = reverse $ c:r go c r (i:is) | p i = go [] ([i]:c:r) is | otherwise = go (i:c) r is {- Replaces multiple values in a string. - - Takes care to skip over just-replaced values, so that they are not - mangled. For example, massReplace [("foo", "new foo")] does not - replace the "new foo" with "new new foo". -} massReplace :: [(String, String)] -> String -> String massReplace vs = go [] vs where go acc _ [] = concat $ reverse acc go acc [] (c:cs) = go ([c]:acc) vs cs go acc ((val, replacement):rest) s | val `isPrefixOf` s = go (replacement:acc) vs (drop (length val) s) | otherwise = go acc rest s {- Wrapper around hGetBufSome that returns a String. - - The null string is returned on eof, otherwise returns whatever - data is currently available to read from the handle, or waits for - data to be written to it if none is currently available. - - Note on encodings: The normal encoding of the Handle is ignored; - each byte is converted to a Char. Not unicode clean! -} hGetSomeString :: Handle -> Int -> IO String hGetSomeString h sz = do fp <- mallocForeignPtrBytes sz len <- withForeignPtr fp $ \buf -> hGetBufSome h buf sz map (chr . fromIntegral) <$> withForeignPtr fp (peekbytes len) where peekbytes :: Int -> Ptr Word8 -> IO [Word8] peekbytes len buf = mapM (peekElemOff buf) [0..pred len] {- Reaps any zombie git processes. - - Warning: Not thread safe. Anything that was expecting to wait - on a process and get back an exit status is going to be confused - if this reap gets there first. -} reapZombies :: IO () #ifndef mingw32_HOST_OS reapZombies = do -- throws an exception when there are no child processes catchDefaultIO Nothing (getAnyProcessStatus False True) >>= maybe (return ()) (const reapZombies) #else reapZombies = return () #endif exitBool :: Bool -> IO a exitBool False = exitFailure exitBool True = exitSuccess
sjfloat/propellor
src/Utility/Misc.hs
bsd-2-clause
4,549
6
12
901
1,188
621
567
72
3
-- | -- Module : Crypto.Hash.Blake2s -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : unknown -- -- Module containing the binding functions to work with the -- Blake2s cryptographic hash. -- {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} module Crypto.Hash.Blake2s ( Blake2s_160 (..), Blake2s_224 (..), Blake2s_256 (..) ) where import Crypto.Hash.Types import Foreign.Ptr (Ptr) import Data.Data import Data.Word (Word8, Word32) -- | Blake2s (160 bits) cryptographic hash algorithm data Blake2s_160 = Blake2s_160 deriving (Show,Data) instance HashAlgorithm Blake2s_160 where type HashBlockSize Blake2s_160 = 64 type HashDigestSize Blake2s_160 = 20 type HashInternalContextSize Blake2s_160 = 136 hashBlockSize _ = 64 hashDigestSize _ = 20 hashInternalContextSize _ = 136 hashInternalInit p = c_blake2s_init p 160 hashInternalUpdate = c_blake2s_update hashInternalFinalize p = c_blake2s_finalize p 160 -- | Blake2s (224 bits) cryptographic hash algorithm data Blake2s_224 = Blake2s_224 deriving (Show,Data) instance HashAlgorithm Blake2s_224 where type HashBlockSize Blake2s_224 = 64 type HashDigestSize Blake2s_224 = 28 type HashInternalContextSize Blake2s_224 = 136 hashBlockSize _ = 64 hashDigestSize _ = 28 hashInternalContextSize _ = 136 hashInternalInit p = c_blake2s_init p 224 hashInternalUpdate = c_blake2s_update hashInternalFinalize p = c_blake2s_finalize p 224 -- | Blake2s (256 bits) cryptographic hash algorithm data Blake2s_256 = Blake2s_256 deriving (Show,Data) instance HashAlgorithm Blake2s_256 where type HashBlockSize Blake2s_256 = 64 type HashDigestSize Blake2s_256 = 32 type HashInternalContextSize Blake2s_256 = 136 hashBlockSize _ = 64 hashDigestSize _ = 32 hashInternalContextSize _ = 136 hashInternalInit p = c_blake2s_init p 256 hashInternalUpdate = c_blake2s_update hashInternalFinalize p = c_blake2s_finalize p 256 foreign import ccall unsafe "cryptonite_blake2s_init" c_blake2s_init :: Ptr (Context a) -> Word32 -> IO () foreign import ccall "cryptonite_blake2s_update" c_blake2s_update :: Ptr (Context a) -> Ptr Word8 -> Word32 -> IO () foreign import ccall unsafe "cryptonite_blake2s_finalize" c_blake2s_finalize :: Ptr (Context a) -> Word32 -> Ptr (Digest a) -> IO ()
vincenthz/cryptonite
Crypto/Hash/Blake2s.hs
bsd-3-clause
2,727
0
11
679
531
289
242
52
0
{-# LANGUAGE CPP, NamedFieldPuns, NondecreasingIndentation #-} {-# OPTIONS_GHC -fno-cse #-} -- -fno-cse is needed for GLOBAL_VAR's to behave properly ----------------------------------------------------------------------------- -- -- GHC Driver -- -- (c) The University of Glasgow 2005 -- ----------------------------------------------------------------------------- module Compiler.DriverPipeline ( -- Run a series of compilation steps in a pipeline, for a -- collection of source files. oneShot, compileFile, -- Interfaces for the batch-mode driver linkBinary, -- Interfaces for the compilation manager (interpreted/batch-mode) preprocess, compileOne, compileOne', link, -- Exports for hooks to override runPhase and link PhasePlus(..), CompPipeline(..), PipeEnv(..), PipeState(..), phaseOutputFilename, getPipeState, getPipeEnv, hscPostBackendPhase, getLocation, setModLocation, setDynFlags, runPhase, exeFileName, mkExtraObjToLinkIntoBinary, mkNoteObjsToLinkIntoBinary, maybeCreateManifest, runPhase_MoveBinary, linkingNeeded, checkLinkInfo, writeInterfaceOnlyMode ) where -- #include "HsVersions.h" import PipelineMonad import Packages import HeaderInfo import DriverPhases import SysTools import HscMain import Finder import HscTypes hiding ( Hsc ) import Outputable import Module import UniqFM ( eltsUFM ) import ErrUtils import DynFlags import Config import Panic import Util import StringBuffer ( hGetStringBuffer ) import BasicTypes ( SuccessFlag(..) ) import Maybes ( expectJust ) import SrcLoc import FastString import LlvmCodeGen ( llvmFixupAsm ) import MonadUtils import Platform import TcRnTypes import Hooks import Exception import Data.IORef ( readIORef ) import System.Directory import System.FilePath import System.IO import Control.Monad import Data.List ( isSuffixOf ) import Data.Maybe import System.Environment import Data.Char -- --------------------------------------------------------------------------- -- Pre-process -- | Just preprocess a file, put the result in a temp. file (used by the -- compilation manager during the summary phase). -- -- We return the augmented DynFlags, because they contain the result -- of slurping in the OPTIONS pragmas preprocess :: HscEnv -> (FilePath, Maybe Phase) -- ^ filename and starting phase -> IO (DynFlags, FilePath) preprocess hsc_env (filename, mb_phase) = runPipeline anyHsc hsc_env (filename, fmap RealPhase mb_phase) Nothing Temporary Nothing{-no ModLocation-} Nothing{-no stub-} -- --------------------------------------------------------------------------- -- | Compile -- -- Compile a single module, under the control of the compilation manager. -- -- This is the interface between the compilation manager and the -- compiler proper (hsc), where we deal with tedious details like -- reading the OPTIONS pragma from the source file, converting the -- C or assembly that GHC produces into an object file, and compiling -- FFI stub files. -- -- NB. No old interface can also mean that the source has changed. compileOne :: HscEnv -> ModSummary -- ^ summary for module being compiled -> Int -- ^ module N ... -> Int -- ^ ... of M -> Maybe ModIface -- ^ old interface, if we have one -> Maybe Linkable -- ^ old linkable, if we have one -> SourceModified -> IO HomeModInfo -- ^ the complete HomeModInfo, if successful compileOne = compileOne' Nothing (Just batchMsg) compileOne' :: Maybe TcGblEnv -> Maybe Messager -> HscEnv -> ModSummary -- ^ summary for module being compiled -> Int -- ^ module N ... -> Int -- ^ ... of M -> Maybe ModIface -- ^ old interface, if we have one -> Maybe Linkable -- ^ old linkable, if we have one -> SourceModified -> IO HomeModInfo -- ^ the complete HomeModInfo, if successful compileOne' m_tc_result mHscMessage hsc_env0 summary mod_index nmods mb_old_iface maybe_old_linkable source_modified0 = do let dflags0 = ms_hspp_opts summary this_mod = ms_mod summary src_flavour = ms_hsc_src summary location = ms_location summary input_fn = expectJust "compile:hs" (ml_hs_file location) input_fnpp = ms_hspp_file summary mod_graph = hsc_mod_graph hsc_env0 needsTH = any (xopt Opt_TemplateHaskell . ms_hspp_opts) mod_graph needsQQ = any (xopt Opt_QuasiQuotes . ms_hspp_opts) mod_graph needsLinker = needsTH || needsQQ isDynWay = any (== WayDyn) (ways dflags0) isProfWay = any (== WayProf) (ways dflags0) -- #8180 - when using TemplateHaskell, switch on -dynamic-too so -- the linker can correctly load the object files. let dflags1 = if needsLinker && dynamicGhc && not isDynWay && not isProfWay then gopt_set dflags0 Opt_BuildDynamicToo else dflags0 debugTraceMsg dflags1 2 (text "compile: input file" <+> text input_fnpp) let basename = dropExtension input_fn -- We add the directory in which the .hs files resides) to the import path. -- This is needed when we try to compile the .hc file later, if it -- imports a _stub.h file that we created here. let current_dir = takeDirectory basename old_paths = includePaths dflags1 dflags = dflags1 { includePaths = current_dir : old_paths } hsc_env = hsc_env0 {hsc_dflags = dflags} -- Figure out what lang we're generating let hsc_lang = hscTarget dflags -- ... and what the next phase should be let next_phase = hscPostBackendPhase dflags src_flavour hsc_lang -- ... and what file to generate the output into output_fn <- getOutputFilename next_phase Temporary basename dflags next_phase (Just location) -- -fforce-recomp should also work with --make let force_recomp = gopt Opt_ForceRecomp dflags source_modified | force_recomp = SourceModified | otherwise = source_modified0 object_filename = ml_obj_file location let always_do_basic_recompilation_check = case hsc_lang of HscInterpreted -> True _ -> False hsc_lang' = if hsc_lang == HscInterpreted then HscAsm else hsc_lang e <- genericHscCompileGetFrontendResult always_do_basic_recompilation_check m_tc_result mHscMessage hsc_env summary source_modified mb_old_iface (mod_index, nmods) case e of Left iface -> do details <- genModDetails hsc_env iface return (HomeModInfo{ hm_details = details, hm_iface = iface, hm_linkable = maybe_old_linkable }) Right (tc_result, mb_old_hash) -> -- run the compiler case hsc_lang' of HscInterpreted -> case ms_hsc_src summary of t | isHsBootOrSig t -> do (iface, _changed, details) <- hscSimpleIface hsc_env tc_result mb_old_hash return (HomeModInfo{ hm_details = details, hm_iface = iface, hm_linkable = maybe_old_linkable }) _ -> do guts0 <- hscDesugar hsc_env summary tc_result guts <- hscSimplify hsc_env guts0 (iface, _changed, details, cgguts) <- hscNormalIface hsc_env guts mb_old_hash (hasStub, comp_bc, modBreaks) <- hscInteractive hsc_env cgguts summary stub_o <- case hasStub of Nothing -> return [] Just stub_c -> do stub_o <- compileStub hsc_env stub_c return [DotO stub_o] let hs_unlinked = [BCOs comp_bc modBreaks] unlinked_time = ms_hs_date summary -- Why do we use the timestamp of the source file here, -- rather than the current time? This works better in -- the case where the local clock is out of sync -- with the filesystem's clock. It's just as accurate: -- if the source is modified, then the linkable will -- be out of date. let linkable = LM unlinked_time this_mod (hs_unlinked ++ stub_o) return (HomeModInfo{ hm_details = details, hm_iface = iface, hm_linkable = Just linkable }) HscNothing -> do (iface, changed, details) <- hscSimpleIface hsc_env tc_result mb_old_hash when (gopt Opt_WriteInterface dflags) $ hscWriteIface dflags iface changed summary let linkable = if isHsBootOrSig src_flavour then maybe_old_linkable else Just (LM (ms_hs_date summary) this_mod []) return (HomeModInfo{ hm_details = details, hm_iface = iface, hm_linkable = linkable }) _ -> case ms_hsc_src summary of HsBootFile -> do (iface, changed, details) <- hscSimpleIface hsc_env tc_result mb_old_hash hscWriteIface dflags iface changed summary touchObjectFile dflags object_filename return (HomeModInfo{ hm_details = details, hm_iface = iface, hm_linkable = maybe_old_linkable }) HsigFile -> do (iface, changed, details) <- hscSimpleIface hsc_env tc_result mb_old_hash hscWriteIface dflags iface changed summary compileEmptyStub dflags hsc_env basename location -- Same as Hs o_time <- getModificationUTCTime object_filename let linkable = LM o_time this_mod [DotO object_filename] return (HomeModInfo{ hm_details = details, hm_iface = iface, hm_linkable = Just linkable }) HsSrcFile -> do guts0 <- hscDesugar hsc_env summary tc_result guts <- hscSimplify hsc_env guts0 (iface, changed, details, cgguts) <- hscNormalIface hsc_env guts mb_old_hash hscWriteIface dflags iface changed summary -- We're in --make mode: finish the compilation pipeline. let mod_name = ms_mod_name summary _ <- runPipeline StopLn hsc_env (output_fn, Just (HscOut src_flavour mod_name (HscRecomp cgguts summary))) (Just basename) Persistent (Just location) Nothing -- The object filename comes from the ModLocation o_time <- getModificationUTCTime object_filename let linkable = LM o_time this_mod [DotO object_filename] return (HomeModInfo{ hm_details = details, hm_iface = iface, hm_linkable = Just linkable }) ----------------------------------------------------------------------------- -- stub .h and .c files (for foreign export support) -- The _stub.c file is derived from the haskell source file, possibly taking -- into account the -stubdir option. -- -- The object file created by compiling the _stub.c file is put into a -- temporary file, which will be later combined with the main .o file -- (see the MergeStubs phase). compileStub :: HscEnv -> FilePath -> IO FilePath compileStub hsc_env stub_c = do (_, stub_o) <- runPipeline StopLn hsc_env (stub_c,Nothing) Nothing Temporary Nothing{-no ModLocation-} Nothing return stub_o compileEmptyStub :: DynFlags -> HscEnv -> FilePath -> ModLocation -> IO () compileEmptyStub dflags hsc_env basename location = do -- To maintain the invariant that every Haskell file -- compiles to object code, we make an empty (but -- valid) stub object file for signatures empty_stub <- newTempName dflags "c" writeFile empty_stub "" _ <- runPipeline StopLn hsc_env (empty_stub, Nothing) (Just basename) Persistent (Just location) Nothing return () -- --------------------------------------------------------------------------- -- Link link :: GhcLink -- interactive or batch -> DynFlags -- dynamic flags -> Bool -- attempt linking in batch mode? -> HomePackageTable -- what to link -> IO SuccessFlag -- For the moment, in the batch linker, we don't bother to tell doLink -- which packages to link -- it just tries all that are available. -- batch_attempt_linking should only be *looked at* in batch mode. It -- should only be True if the upsweep was successful and someone -- exports main, i.e., we have good reason to believe that linking -- will succeed. link ghcLink dflags = lookupHook linkHook l dflags ghcLink dflags where l LinkInMemory _ _ _ = if cGhcWithInterpreter == "YES" then -- Not Linking...(demand linker will do the job) return Succeeded else panicBadLink LinkInMemory l NoLink _ _ _ = return Succeeded l LinkBinary dflags batch_attempt_linking hpt = link' dflags batch_attempt_linking hpt l LinkStaticLib dflags batch_attempt_linking hpt = link' dflags batch_attempt_linking hpt l LinkDynLib dflags batch_attempt_linking hpt = link' dflags batch_attempt_linking hpt panicBadLink :: GhcLink -> a panicBadLink other = panic ("link: GHC not built to link this way: " ++ show other) link' :: DynFlags -- dynamic flags -> Bool -- attempt linking in batch mode? -> HomePackageTable -- what to link -> IO SuccessFlag link' dflags batch_attempt_linking hpt | batch_attempt_linking = do let staticLink = case ghcLink dflags of LinkStaticLib -> True _ -> platformBinariesAreStaticLibs (targetPlatform dflags) home_mod_infos = eltsUFM hpt -- the packages we depend on pkg_deps = concatMap (map fst . dep_pkgs . mi_deps . hm_iface) home_mod_infos -- the linkables to link linkables = map (expectJust "link".hm_linkable) home_mod_infos debugTraceMsg dflags 3 (text "link: linkables are ..." $$ vcat (map ppr linkables)) -- check for the -no-link flag if isNoLink (ghcLink dflags) then do debugTraceMsg dflags 3 (text "link(batch): linking omitted (-c flag given).") return Succeeded else do let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us) obj_files = concatMap getOfiles linkables exe_file = exeFileName staticLink dflags linking_needed <- linkingNeeded dflags staticLink linkables pkg_deps if not (gopt Opt_ForceRecomp dflags) && not linking_needed then do debugTraceMsg dflags 2 (text exe_file <+> ptext (sLit "is up to date, linking not required.")) return Succeeded else do compilationProgressMsg dflags ("Linking " ++ exe_file ++ " ...") -- Don't showPass in Batch mode; doLink will do that for us. let link = case ghcLink dflags of LinkBinary -> linkBinary LinkStaticLib -> linkStaticLibCheck LinkDynLib -> linkDynLibCheck other -> panicBadLink other link dflags obj_files pkg_deps debugTraceMsg dflags 3 (text "link: done") -- linkBinary only returns if it succeeds return Succeeded | otherwise = do debugTraceMsg dflags 3 (text "link(batch): upsweep (partially) failed OR" $$ text " Main.main not exported; not linking.") return Succeeded linkingNeeded :: DynFlags -> Bool -> [Linkable] -> [PackageKey] -> IO Bool linkingNeeded dflags staticLink linkables pkg_deps = do -- if the modification time on the executable is later than the -- modification times on all of the objects and libraries, then omit -- linking (unless the -fforce-recomp flag was given). let exe_file = exeFileName staticLink dflags e_exe_time <- tryIO $ getModificationUTCTime exe_file case e_exe_time of Left _ -> return True Right t -> do -- first check object files and extra_ld_inputs let extra_ld_inputs = [ f | FileOption _ f <- ldInputs dflags ] e_extra_times <- mapM (tryIO . getModificationUTCTime) extra_ld_inputs let (errs,extra_times) = splitEithers e_extra_times let obj_times = map linkableTime linkables ++ extra_times if not (null errs) || any (t <) obj_times then return True else do -- next, check libraries. XXX this only checks Haskell libraries, -- not extra_libraries or -l things from the command line. let pkg_hslibs = [ (libraryDirs c, lib) | Just c <- map (lookupPackage dflags) pkg_deps, lib <- packageHsLibs dflags c ] pkg_libfiles <- mapM (uncurry (findHSLib dflags)) pkg_hslibs if any isNothing pkg_libfiles then return True else do e_lib_times <- mapM (tryIO . getModificationUTCTime) (catMaybes pkg_libfiles) let (lib_errs,lib_times) = splitEithers e_lib_times if not (null lib_errs) || any (t <) lib_times then return True else checkLinkInfo dflags pkg_deps exe_file -- Returns 'False' if it was, and we can avoid linking, because the -- previous binary was linked with "the same options". checkLinkInfo :: DynFlags -> [PackageKey] -> FilePath -> IO Bool checkLinkInfo dflags pkg_deps exe_file | not (platformSupportsSavingLinkOpts (platformOS (targetPlatform dflags))) -- ToDo: Windows and OS X do not use the ELF binary format, so -- readelf does not work there. We need to find another way to do -- this. = return False -- conservatively we should return True, but not -- linking in this case was the behaviour for a long -- time so we leave it as-is. | otherwise = do link_info <- getLinkInfo dflags pkg_deps debugTraceMsg dflags 3 $ text ("Link info: " ++ link_info) m_exe_link_info <- readElfSection dflags ghcLinkInfoSectionName exe_file debugTraceMsg dflags 3 $ text ("Exe link info: " ++ show m_exe_link_info) return (Just link_info /= m_exe_link_info) platformSupportsSavingLinkOpts :: OS -> Bool platformSupportsSavingLinkOpts os | os == OSSolaris2 = False -- see #5382 | otherwise = osElfTarget os ghcLinkInfoSectionName :: String ghcLinkInfoSectionName = ".debug-ghc-link-info" -- if we use the ".debug" prefix, then strip will strip it by default findHSLib :: DynFlags -> [String] -> String -> IO (Maybe FilePath) findHSLib dflags dirs lib = do let batch_lib_file = if gopt Opt_Static dflags then "lib" ++ lib <.> "a" else mkSOName (targetPlatform dflags) lib found <- filterM doesFileExist (map (</> batch_lib_file) dirs) case found of [] -> return Nothing (x:_) -> return (Just x) -- ----------------------------------------------------------------------------- -- Compile files in one-shot mode. oneShot :: HscEnv -> Phase -> [(String, Maybe Phase)] -> IO () oneShot hsc_env stop_phase srcs = do o_files <- mapM (compileFile hsc_env stop_phase) srcs doLink (hsc_dflags hsc_env) stop_phase o_files compileFile :: HscEnv -> Phase -> (FilePath, Maybe Phase) -> IO FilePath compileFile hsc_env stop_phase (src, mb_phase) = do exists <- doesFileExist src when (not exists) $ throwGhcExceptionIO (CmdLineError ("does not exist: " ++ src)) let dflags = hsc_dflags hsc_env split = gopt Opt_SplitObjs dflags mb_o_file = outputFile dflags ghc_link = ghcLink dflags -- Set by -c or -no-link -- When linking, the -o argument refers to the linker's output. -- otherwise, we use it as the name for the pipeline's output. output -- If we are dong -fno-code, then act as if the output is -- 'Temporary'. This stops GHC trying to copy files to their -- final location. | HscNothing <- hscTarget dflags = Temporary | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent -- -o foo applies to linker | isJust mb_o_file = SpecificFile -- -o foo applies to the file we are compiling now | otherwise = Persistent stop_phase' = case stop_phase of As _ | split -> SplitAs _ -> stop_phase ( _, out_file) <- runPipeline stop_phase' hsc_env (src, fmap RealPhase mb_phase) Nothing output Nothing{-no ModLocation-} Nothing return out_file doLink :: DynFlags -> Phase -> [FilePath] -> IO () doLink dflags stop_phase o_files | not (isStopLn stop_phase) = return () -- We stopped before the linking phase | otherwise = case ghcLink dflags of NoLink -> return () LinkBinary -> linkBinary dflags o_files [] LinkStaticLib -> linkStaticLibCheck dflags o_files [] LinkDynLib -> linkDynLibCheck dflags o_files [] other -> panicBadLink other -- --------------------------------------------------------------------------- -- | Run a compilation pipeline, consisting of multiple phases. -- -- This is the interface to the compilation pipeline, which runs -- a series of compilation steps on a single source file, specifying -- at which stage to stop. -- -- The DynFlags can be modified by phases in the pipeline (eg. by -- OPTIONS_GHC pragmas), and the changes affect later phases in the -- pipeline. runPipeline :: Phase -- ^ When to stop -> HscEnv -- ^ Compilation environment -> (FilePath,Maybe PhasePlus) -- ^ Input filename (and maybe -x suffix) -> Maybe FilePath -- ^ original basename (if different from ^^^) -> PipelineOutput -- ^ Output filename -> Maybe ModLocation -- ^ A ModLocation, if this is a Haskell module -> Maybe FilePath -- ^ stub object, if we have one -> IO (DynFlags, FilePath) -- ^ (final flags, output filename) runPipeline stop_phase hsc_env0 (input_fn, mb_phase) mb_basename output maybe_loc maybe_stub_o = do let dflags0 = hsc_dflags hsc_env0 -- Decide where dump files should go based on the pipeline output dflags = dflags0 { dumpPrefix = Just (basename ++ ".") } hsc_env = hsc_env0 {hsc_dflags = dflags} (input_basename, suffix) = splitExtension input_fn suffix' = drop 1 suffix -- strip off the . basename | Just b <- mb_basename = b | otherwise = input_basename -- If we were given a -x flag, then use that phase to start from start_phase = fromMaybe (RealPhase (startPhase suffix')) mb_phase isHaskell (RealPhase (Unlit _)) = True isHaskell (RealPhase (Cpp _)) = True isHaskell (RealPhase (HsPp _)) = True isHaskell (RealPhase (Hsc _)) = True isHaskell (HscOut {}) = True isHaskell _ = False isHaskellishFile = isHaskell start_phase env = PipeEnv{ pe_isHaskellishFile = isHaskellishFile, stop_phase, src_filename = input_fn, src_basename = basename, src_suffix = suffix', output_spec = output } -- We want to catch cases of "you can't get there from here" before -- we start the pipeline, because otherwise it will just run off the -- end. -- -- There is a partial ordering on phases, where A < B iff A occurs -- before B in a normal compilation pipeline. let happensBefore' = happensBefore dflags case start_phase of RealPhase start_phase' -> when (not (start_phase' `happensBefore'` stop_phase)) $ throwGhcExceptionIO (UsageError ("cannot compile this file to desired target: " ++ input_fn)) HscOut {} -> return () debugTraceMsg dflags 4 (text "Running the pipeline") r <- runPipeline' start_phase hsc_env env input_fn maybe_loc maybe_stub_o -- If we are compiling a Haskell module, and doing -- -dynamic-too, but couldn't do the -dynamic-too fast -- path, then rerun the pipeline for the dyn way let dflags = extractDynFlags hsc_env -- NB: Currently disabled on Windows (ref #7134, #8228, and #5987) when (not $ platformOS (targetPlatform dflags) == OSMinGW32) $ do when isHaskellishFile $ whenCannotGenerateDynamicToo dflags $ do debugTraceMsg dflags 4 (text "Running the pipeline again for -dynamic-too") let dflags' = dynamicTooMkDynamicDynFlags dflags hsc_env' <- newHscEnv dflags' _ <- runPipeline' start_phase hsc_env' env input_fn maybe_loc maybe_stub_o return () return r runPipeline' :: PhasePlus -- ^ When to start -> HscEnv -- ^ Compilation environment -> PipeEnv -> FilePath -- ^ Input filename -> Maybe ModLocation -- ^ A ModLocation, if this is a Haskell module -> Maybe FilePath -- ^ stub object, if we have one -> IO (DynFlags, FilePath) -- ^ (final flags, output filename) runPipeline' start_phase hsc_env env input_fn maybe_loc maybe_stub_o = do -- Execute the pipeline... let state = PipeState{ hsc_env, maybe_loc, maybe_stub_o = maybe_stub_o } evalP (pipeLoop start_phase input_fn) env state -- --------------------------------------------------------------------------- -- outer pipeline loop -- | pipeLoop runs phases until we reach the stop phase pipeLoop :: PhasePlus -> FilePath -> CompPipeline (DynFlags, FilePath) pipeLoop phase input_fn = do env <- getPipeEnv dflags <- getDynFlags let happensBefore' = happensBefore dflags stopPhase = stop_phase env case phase of RealPhase realPhase | realPhase `eqPhase` stopPhase -- All done -> -- Sometimes, a compilation phase doesn't actually generate any output -- (eg. the CPP phase when -fcpp is not turned on). If we end on this -- stage, but we wanted to keep the output, then we have to explicitly -- copy the file, remembering to prepend a {-# LINE #-} pragma so that -- further compilation stages can tell what the original filename was. case output_spec env of Temporary -> return (dflags, input_fn) output -> do pst <- getPipeState final_fn <- liftIO $ getOutputFilename stopPhase output (src_basename env) dflags stopPhase (maybe_loc pst) when (final_fn /= input_fn) $ do let msg = ("Copying `" ++ input_fn ++"' to `" ++ final_fn ++ "'") line_prag = Just ("{-# LINE 1 \"" ++ src_filename env ++ "\" #-}\n") liftIO $ copyWithHeader dflags msg line_prag input_fn final_fn return (dflags, final_fn) | not (realPhase `happensBefore'` stopPhase) -- Something has gone wrong. We'll try to cover all the cases when -- this could happen, so if we reach here it is a panic. -- eg. it might happen if the -C flag is used on a source file that -- has {-# OPTIONS -fasm #-}. -> panic ("pipeLoop: at phase " ++ show realPhase ++ " but I wanted to stop at phase " ++ show stopPhase) _ -> do liftIO $ debugTraceMsg dflags 4 (ptext (sLit "Running phase") <+> ppr phase) (next_phase, output_fn) <- runHookedPhase phase input_fn dflags r <- pipeLoop next_phase output_fn case phase of HscOut {} -> whenGeneratingDynamicToo dflags $ do setDynFlags $ dynamicTooMkDynamicDynFlags dflags -- TODO shouldn't ignore result: _ <- pipeLoop phase input_fn return () _ -> return () return r runHookedPhase :: PhasePlus -> FilePath -> DynFlags -> CompPipeline (PhasePlus, FilePath) runHookedPhase pp input dflags = lookupHook runPhaseHook runPhase dflags pp input dflags -- ----------------------------------------------------------------------------- -- In each phase, we need to know into what filename to generate the -- output. All the logic about which filenames we generate output -- into is embodied in the following function. phaseOutputFilename :: Phase{-next phase-} -> CompPipeline FilePath phaseOutputFilename next_phase = do PipeEnv{stop_phase, src_basename, output_spec} <- getPipeEnv PipeState{maybe_loc, hsc_env} <- getPipeState let dflags = hsc_dflags hsc_env liftIO $ getOutputFilename stop_phase output_spec src_basename dflags next_phase maybe_loc getOutputFilename :: Phase -> PipelineOutput -> String -> DynFlags -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath getOutputFilename stop_phase output basename dflags next_phase maybe_location | is_last_phase, Persistent <- output = persistent_fn | is_last_phase, SpecificFile <- output = case outputFile dflags of Just f -> return f Nothing -> panic "SpecificFile: No filename" | keep_this_output = persistent_fn | otherwise = newTempName dflags suffix where hcsuf = hcSuf dflags odir = objectDir dflags osuf = objectSuf dflags keep_hc = gopt Opt_KeepHcFiles dflags keep_s = gopt Opt_KeepSFiles dflags keep_bc = gopt Opt_KeepLlvmFiles dflags myPhaseInputExt HCc = hcsuf myPhaseInputExt MergeStub = osuf myPhaseInputExt StopLn = osuf myPhaseInputExt other = phaseInputExt other is_last_phase = next_phase `eqPhase` stop_phase -- sometimes, we keep output from intermediate stages keep_this_output = case next_phase of As _ | keep_s -> True LlvmOpt | keep_bc -> True HCc | keep_hc -> True _other -> False suffix = myPhaseInputExt next_phase -- persistent object files get put in odir persistent_fn | StopLn <- next_phase = return odir_persistent | otherwise = return persistent persistent = basename <.> suffix odir_persistent | Just loc <- maybe_location = ml_obj_file loc | Just d <- odir = d </> persistent | otherwise = persistent -- ----------------------------------------------------------------------------- -- | Each phase in the pipeline returns the next phase to execute, and the -- name of the file in which the output was placed. -- -- We must do things dynamically this way, because we often don't know -- what the rest of the phases will be until part-way through the -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning -- of a source file can change the latter stages of the pipeline from -- taking the LLVM route to using the native code generator. -- runPhase :: PhasePlus -- ^ Run this phase -> FilePath -- ^ name of the input file -> DynFlags -- ^ for convenience, we pass the current dflags in -> CompPipeline (PhasePlus, -- next phase to run FilePath) -- output filename -- Invariant: the output filename always contains the output -- Interesting case: Hsc when there is no recompilation to do -- Then the output filename is still a .o file ------------------------------------------------------------------------------- -- Unlit phase runPhase (RealPhase (Unlit sf)) input_fn dflags = do output_fn <- phaseOutputFilename (Cpp sf) let flags = [ -- The -h option passes the file name for unlit to -- put in a #line directive SysTools.Option "-h" , SysTools.Option $ escape $ normalise input_fn , SysTools.FileOption "" input_fn , SysTools.FileOption "" output_fn ] liftIO $ SysTools.runUnlit dflags flags return (RealPhase (Cpp sf), output_fn) where -- escape the characters \, ", and ', but don't try to escape -- Unicode or anything else (so we don't use Util.charToC -- here). If we get this wrong, then in -- Coverage.addTicksToBinds where we check that the filename in -- a SrcLoc is the same as the source filenaame, the two will -- look bogusly different. See test: -- libraries/hpc/tests/function/subdir/tough2.lhs escape ('\\':cs) = '\\':'\\': escape cs escape ('\"':cs) = '\\':'\"': escape cs escape ('\'':cs) = '\\':'\'': escape cs escape (c:cs) = c : escape cs escape [] = [] ------------------------------------------------------------------------------- -- Cpp phase : (a) gets OPTIONS out of file -- (b) runs cpp if necessary runPhase (RealPhase (Cpp sf)) input_fn dflags0 = do src_opts <- liftIO $ getOptionsFromFile dflags0 input_fn (dflags1, unhandled_flags, warns) <- liftIO $ parseDynamicFilePragma dflags0 src_opts setDynFlags dflags1 liftIO $ checkProcessArgsResult dflags1 unhandled_flags if not (xopt Opt_Cpp dflags1) then do -- we have to be careful to emit warnings only once. unless (gopt Opt_Pp dflags1) $ liftIO $ handleFlagWarnings dflags1 warns -- no need to preprocess CPP, just pass input file along -- to the next phase of the pipeline. return (RealPhase (HsPp sf), input_fn) else do output_fn <- phaseOutputFilename (HsPp sf) liftIO $ doCpp dflags1 True{-raw-} input_fn output_fn -- re-read the pragmas now that we've preprocessed the file -- See #2464,#3457 src_opts <- liftIO $ getOptionsFromFile dflags0 output_fn (dflags2, unhandled_flags, warns) <- liftIO $ parseDynamicFilePragma dflags0 src_opts liftIO $ checkProcessArgsResult dflags2 unhandled_flags unless (gopt Opt_Pp dflags2) $ liftIO $ handleFlagWarnings dflags2 warns -- the HsPp pass below will emit warnings setDynFlags dflags2 return (RealPhase (HsPp sf), output_fn) ------------------------------------------------------------------------------- -- HsPp phase runPhase (RealPhase (HsPp sf)) input_fn dflags = do if not (gopt Opt_Pp dflags) then -- no need to preprocess, just pass input file along -- to the next phase of the pipeline. return (RealPhase (Hsc sf), input_fn) else do PipeEnv{src_basename, src_suffix} <- getPipeEnv let orig_fn = src_basename <.> src_suffix output_fn <- phaseOutputFilename (Hsc sf) liftIO $ SysTools.runPp dflags ( [ SysTools.Option orig_fn , SysTools.Option input_fn , SysTools.FileOption "" output_fn ] ) -- re-read pragmas now that we've parsed the file (see #3674) src_opts <- liftIO $ getOptionsFromFile dflags output_fn (dflags1, unhandled_flags, warns) <- liftIO $ parseDynamicFilePragma dflags src_opts setDynFlags dflags1 liftIO $ checkProcessArgsResult dflags1 unhandled_flags liftIO $ handleFlagWarnings dflags1 warns return (RealPhase (Hsc sf), output_fn) ----------------------------------------------------------------------------- -- Hsc phase -- Compilation of a single module, in "legacy" mode (_not_ under -- the direction of the compilation manager). runPhase (RealPhase (Hsc src_flavour)) input_fn dflags0 = do -- normal Hsc mode, not mkdependHS PipeEnv{ stop_phase=stop, src_basename=basename, src_suffix=suff } <- getPipeEnv -- we add the current directory (i.e. the directory in which -- the .hs files resides) to the include path, since this is -- what gcc does, and it's probably what you want. let current_dir = takeDirectory basename paths = includePaths dflags0 dflags = dflags0 { includePaths = current_dir : paths } setDynFlags dflags -- gather the imports and module name (hspp_buf,mod_name,imps,src_imps) <- liftIO $ do do buf <- hGetStringBuffer input_fn (src_imps,imps,L _ mod_name) <- getImports dflags buf input_fn (basename <.> suff) return (Just buf, mod_name, imps, src_imps) -- Take -o into account if present -- Very like -ohi, but we must *only* do this if we aren't linking -- (If we're linking then the -o applies to the linked thing, not to -- the object file for one module.) -- Note the nasty duplication with the same computation in compileFile above location <- getLocation src_flavour mod_name let o_file = ml_obj_file location -- The real object file hi_file = ml_hi_file location dest_file | writeInterfaceOnlyMode dflags = hi_file | otherwise = o_file -- Figure out if the source has changed, for recompilation avoidance. -- -- Setting source_unchanged to True means that M.o seems -- to be up to date wrt M.hs; so no need to recompile unless imports have -- changed (which the compiler itself figures out). -- Setting source_unchanged to False tells the compiler that M.o is out of -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless. src_timestamp <- liftIO $ getModificationUTCTime (basename <.> suff) source_unchanged <- liftIO $ if not (isStopLn stop) -- SourceModified unconditionally if -- (a) recompilation checker is off, or -- (b) we aren't going all the way to .o file (e.g. ghc -S) then return SourceModified -- Otherwise look at file modification dates else do dest_file_exists <- doesFileExist dest_file if not dest_file_exists then return SourceModified -- Need to recompile else do t2 <- getModificationUTCTime dest_file if t2 > src_timestamp then return SourceUnmodified else return SourceModified PipeState{hsc_env=hsc_env'} <- getPipeState -- Tell the finder cache about this module mod <- liftIO $ addHomeModuleToFinder hsc_env' mod_name location -- Make the ModSummary to hand to hscMain let mod_summary = ModSummary { ms_mod = mod, ms_hsc_src = src_flavour, ms_hspp_file = input_fn, ms_hspp_opts = dflags, ms_hspp_buf = hspp_buf, ms_location = location, ms_hs_date = src_timestamp, ms_obj_date = Nothing, ms_iface_date = Nothing, ms_textual_imps = imps, ms_srcimps = src_imps } -- run the compiler! result <- liftIO $ hscCompileOneShot hsc_env' mod_summary source_unchanged return (HscOut src_flavour mod_name result, panic "HscOut doesn't have an input filename") runPhase (HscOut src_flavour mod_name result) _ dflags = do location <- getLocation src_flavour mod_name setModLocation location let o_file = ml_obj_file location -- The real object file hsc_lang = hscTarget dflags next_phase = hscPostBackendPhase dflags src_flavour hsc_lang case result of HscNotGeneratingCode -> return (RealPhase next_phase, panic "No output filename from Hsc when no-code") HscUpToDate -> do liftIO $ touchObjectFile dflags o_file -- The .o file must have a later modification date -- than the source file (else we wouldn't get Nothing) -- but we touch it anyway, to keep 'make' happy (we think). return (RealPhase StopLn, o_file) HscUpdateBoot -> do -- In the case of hs-boot files, generate a dummy .o-boot -- stamp file for the benefit of Make liftIO $ touchObjectFile dflags o_file return (RealPhase next_phase, o_file) HscUpdateSig -> do -- We need to create a REAL but empty .o file -- because we are going to attempt to put it in a library PipeState{hsc_env=hsc_env'} <- getPipeState let input_fn = expectJust "runPhase" (ml_hs_file location) basename = dropExtension input_fn liftIO $ compileEmptyStub dflags hsc_env' basename location return (RealPhase next_phase, o_file) HscRecomp cgguts mod_summary -> do output_fn <- phaseOutputFilename next_phase PipeState{hsc_env=hsc_env'} <- getPipeState (outputFilename, mStub) <- liftIO $ hscGenHardCode hsc_env' cgguts mod_summary output_fn case mStub of Nothing -> return () Just stub_c -> do stub_o <- liftIO $ compileStub hsc_env' stub_c setStubO stub_o return (RealPhase next_phase, outputFilename) ----------------------------------------------------------------------------- -- Cmm phase runPhase (RealPhase CmmCpp) input_fn dflags = do output_fn <- phaseOutputFilename Cmm liftIO $ doCpp dflags False{-not raw-} input_fn output_fn return (RealPhase Cmm, output_fn) runPhase (RealPhase Cmm) input_fn dflags = do let hsc_lang = hscTarget dflags let next_phase = hscPostBackendPhase dflags HsSrcFile hsc_lang output_fn <- phaseOutputFilename next_phase PipeState{hsc_env} <- getPipeState liftIO $ hscCompileCmmFile hsc_env input_fn output_fn return (RealPhase next_phase, output_fn) ----------------------------------------------------------------------------- -- Cc phase -- we don't support preprocessing .c files (with -E) now. Doing so introduces -- way too many hacks, and I can't say I've ever used it anyway. runPhase (RealPhase cc_phase) input_fn dflags | any (cc_phase `eqPhase`) [Cc, Ccpp, HCc, Cobjc, Cobjcpp] = do let platform = targetPlatform dflags hcc = cc_phase `eqPhase` HCc let cmdline_include_paths = includePaths dflags -- HC files have the dependent packages stamped into them pkgs <- if hcc then liftIO $ getHCFilePackages input_fn else return [] -- add package include paths even if we're just compiling .c -- files; this is the Value Add(TM) that using ghc instead of -- gcc gives you :) pkg_include_dirs <- liftIO $ getPackageIncludePath dflags pkgs let include_paths = foldr (\ x xs -> ("-I" ++ x) : xs) [] (cmdline_include_paths ++ pkg_include_dirs) let gcc_extra_viac_flags = extraGccViaCFlags dflags let pic_c_flags = picCCOpts dflags let verbFlags = getVerbFlags dflags -- cc-options are not passed when compiling .hc files. Our -- hc code doesn't not #include any header files anyway, so these -- options aren't necessary. pkg_extra_cc_opts <- liftIO $ if cc_phase `eqPhase` HCc then return [] else getPackageExtraCcOpts dflags pkgs framework_paths <- if platformUsesFrameworks platform then do pkgFrameworkPaths <- liftIO $ getPackageFrameworkPath dflags pkgs let cmdlineFrameworkPaths = frameworkPaths dflags return $ map ("-F"++) (cmdlineFrameworkPaths ++ pkgFrameworkPaths) else return [] let split_objs = gopt Opt_SplitObjs dflags split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ] | otherwise = [ ] let cc_opt | optLevel dflags >= 2 = [ "-O2" ] | optLevel dflags >= 1 = [ "-O" ] | otherwise = [] -- Decide next phase let next_phase = As False output_fn <- phaseOutputFilename next_phase let more_hcc_opts = -- on x86 the floating point regs have greater precision -- than a double, which leads to unpredictable results. -- By default, we turn this off with -ffloat-store unless -- the user specified -fexcess-precision. (if platformArch platform == ArchX86 && not (gopt Opt_ExcessPrecision dflags) then [ "-ffloat-store" ] else []) ++ -- gcc's -fstrict-aliasing allows two accesses to memory -- to be considered non-aliasing if they have different types. -- This interacts badly with the C code we generate, which is -- very weakly typed, being derived from C--. ["-fno-strict-aliasing"] ghcVersionH <- liftIO $ getGhcVersionPathName dflags let gcc_lang_opt | cc_phase `eqPhase` Ccpp = "c++" | cc_phase `eqPhase` Cobjc = "objective-c" | cc_phase `eqPhase` Cobjcpp = "objective-c++" | otherwise = "c" liftIO $ SysTools.runCc dflags ( -- force the C compiler to interpret this file as C when -- compiling .hc files, by adding the -x c option. -- Also useful for plain .c files, just in case GHC saw a -- -x c option. [ SysTools.Option "-x", SysTools.Option gcc_lang_opt , SysTools.FileOption "" input_fn , SysTools.Option "-o" , SysTools.FileOption "" output_fn ] ++ map SysTools.Option ( pic_c_flags -- Stub files generated for foreign exports references the runIO_closure -- and runNonIO_closure symbols, which are defined in the base package. -- These symbols are imported into the stub.c file via RtsAPI.h, and the -- way we do the import depends on whether we're currently compiling -- the base package or not. ++ (if platformOS platform == OSMinGW32 && thisPackage dflags == basePackageKey then [ "-DCOMPILING_BASE_PACKAGE" ] else []) -- We only support SparcV9 and better because V8 lacks an atomic CAS -- instruction. Note that the user can still override this -- (e.g., -mcpu=ultrasparc) as GCC picks the "best" -mcpu flag -- regardless of the ordering. -- -- This is a temporary hack. See #2872, commit -- 5bd3072ac30216a505151601884ac88bf404c9f2 ++ (if platformArch platform == ArchSPARC then ["-mcpu=v9"] else []) -- GCC 4.6+ doesn't like -Wimplicit when compiling C++. ++ (if (cc_phase /= Ccpp && cc_phase /= Cobjcpp) then ["-Wimplicit"] else []) ++ (if hcc then gcc_extra_viac_flags ++ more_hcc_opts else []) ++ verbFlags ++ [ "-S" ] ++ cc_opt ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt , "-include", ghcVersionH ] ++ framework_paths ++ split_opt ++ include_paths ++ pkg_extra_cc_opts )) return (RealPhase next_phase, output_fn) ----------------------------------------------------------------------------- -- Splitting phase runPhase (RealPhase Splitter) input_fn dflags = do -- tmp_pfx is the prefix used for the split .s files split_s_prefix <- liftIO $ SysTools.newTempName dflags "split" let n_files_fn = split_s_prefix liftIO $ SysTools.runSplit dflags [ SysTools.FileOption "" input_fn , SysTools.FileOption "" split_s_prefix , SysTools.FileOption "" n_files_fn ] -- Save the number of split files for future references s <- liftIO $ readFile n_files_fn let n_files = read s :: Int dflags' = dflags { splitInfo = Just (split_s_prefix, n_files) } setDynFlags dflags' -- Remember to delete all these files liftIO $ addFilesToClean dflags' [ split_s_prefix ++ "__" ++ show n ++ ".s" | n <- [1..n_files]] return (RealPhase SplitAs, "**splitter**") -- we don't use the filename in SplitAs ----------------------------------------------------------------------------- -- As, SpitAs phase : Assembler -- This is for calling the assembler on a regular assembly file (not split). runPhase (RealPhase (As with_cpp)) input_fn dflags = do -- LLVM from version 3.0 onwards doesn't support the OS X system -- assembler, so we use clang as the assembler instead. (#5636) let whichAsProg | hscTarget dflags == HscLlvm && platformOS (targetPlatform dflags) == OSDarwin = do -- be careful what options we call clang with -- see #5903 and #7617 for bugs caused by this. llvmVer <- liftIO $ figureLlvmVersion dflags return $ case llvmVer of Just n | n >= 30 -> SysTools.runClang _ -> SysTools.runAs | otherwise = return SysTools.runAs as_prog <- whichAsProg let cmdline_include_paths = includePaths dflags let pic_c_flags = picCCOpts dflags next_phase <- maybeMergeStub output_fn <- phaseOutputFilename next_phase -- we create directories for the object file, because it -- might be a hierarchical module. liftIO $ createDirectoryIfMissing True (takeDirectory output_fn) ccInfo <- liftIO $ getCompilerInfo dflags let runAssembler inputFilename outputFilename = liftIO $ as_prog dflags ([ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ] -- See Note [-fPIC for assembler] ++ map SysTools.Option pic_c_flags -- We only support SparcV9 and better because V8 lacks an atomic CAS -- instruction so we have to make sure that the assembler accepts the -- instruction set. Note that the user can still override this -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag -- regardless of the ordering. -- -- This is a temporary hack. ++ (if platformArch (targetPlatform dflags) == ArchSPARC then [SysTools.Option "-mcpu=v9"] else []) ++ (if any (ccInfo ==) [Clang, AppleClang, AppleClang51] then [SysTools.Option "-Qunused-arguments"] else []) ++ [ SysTools.Option "-x" , if with_cpp then SysTools.Option "assembler-with-cpp" else SysTools.Option "assembler" , SysTools.Option "-c" , SysTools.FileOption "" inputFilename , SysTools.Option "-o" , SysTools.FileOption "" outputFilename ]) liftIO $ debugTraceMsg dflags 4 (text "Running the assembler") runAssembler input_fn output_fn return (RealPhase next_phase, output_fn) -- This is for calling the assembler on a split assembly file (so a collection -- of assembly files) runPhase (RealPhase SplitAs) _input_fn dflags = do -- we'll handle the stub_o file in this phase, so don't MergeStub, -- just jump straight to StopLn afterwards. let next_phase = StopLn output_fn <- phaseOutputFilename next_phase let base_o = dropExtension output_fn osuf = objectSuf dflags split_odir = base_o ++ "_" ++ osuf ++ "_split" let pic_c_flags = picCCOpts dflags -- this also creates the hierarchy liftIO $ createDirectoryIfMissing True split_odir -- remove M_split/ *.o, because we're going to archive M_split/ *.o -- later and we don't want to pick up any old objects. fs <- liftIO $ getDirectoryContents split_odir liftIO $ mapM_ removeFile $ map (split_odir </>) $ filter (osuf `isSuffixOf`) fs let (split_s_prefix, n) = case splitInfo dflags of Nothing -> panic "No split info" Just x -> x let split_s n = split_s_prefix ++ "__" ++ show n <.> "s" split_obj :: Int -> FilePath split_obj n = split_odir </> takeFileName base_o ++ "__" ++ show n <.> osuf let assemble_file n = SysTools.runAs dflags ( -- We only support SparcV9 and better because V8 lacks an atomic CAS -- instruction so we have to make sure that the assembler accepts the -- instruction set. Note that the user can still override this -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag -- regardless of the ordering. -- -- This is a temporary hack. (if platformArch (targetPlatform dflags) == ArchSPARC then [SysTools.Option "-mcpu=v9"] else []) ++ -- See Note [-fPIC for assembler] map SysTools.Option pic_c_flags ++ [ SysTools.Option "-c" , SysTools.Option "-o" , SysTools.FileOption "" (split_obj n) , SysTools.FileOption "" (split_s n) ]) liftIO $ mapM_ assemble_file [1..n] -- Note [pipeline-split-init] -- If we have a stub file, it may contain constructor -- functions for initialisation of this module. We can't -- simply leave the stub as a separate object file, because it -- will never be linked in: nothing refers to it. We need to -- ensure that if we ever refer to the data in this module -- that needs initialisation, then we also pull in the -- initialisation routine. -- -- To that end, we make a DANGEROUS ASSUMPTION here: the data -- that needs to be initialised is all in the FIRST split -- object. See Note [codegen-split-init]. PipeState{maybe_stub_o} <- getPipeState case maybe_stub_o of Nothing -> return () Just stub_o -> liftIO $ do tmp_split_1 <- newTempName dflags osuf let split_1 = split_obj 1 copyFile split_1 tmp_split_1 removeFile split_1 joinObjectFiles dflags [tmp_split_1, stub_o] split_1 -- join them into a single .o file liftIO $ joinObjectFiles dflags (map split_obj [1..n]) output_fn return (RealPhase next_phase, output_fn) ----------------------------------------------------------------------------- -- LlvmOpt phase runPhase (RealPhase LlvmOpt) input_fn dflags = do ver <- liftIO $ readIORef (llvmVersion dflags) let opt_lvl = max 0 (min 2 $ optLevel dflags) -- don't specify anything if user has specified commands. We do this -- for opt but not llc since opt is very specifically for optimisation -- passes only, so if the user is passing us extra options we assume -- they know what they are doing and don't get in the way. optFlag = if null (getOpts dflags opt_lo) then map SysTools.Option $ words (llvmOpts ver !! opt_lvl) else [] tbaa | ver < 29 = "" -- no tbaa in 2.8 and earlier | gopt Opt_LlvmTBAA dflags = "--enable-tbaa=true" | otherwise = "--enable-tbaa=false" output_fn <- phaseOutputFilename LlvmLlc liftIO $ SysTools.runLlvmOpt dflags ([ SysTools.FileOption "" input_fn, SysTools.Option "-o", SysTools.FileOption "" output_fn] ++ optFlag ++ [SysTools.Option tbaa]) return (RealPhase LlvmLlc, output_fn) where -- we always (unless -optlo specified) run Opt since we rely on it to -- fix up some pretty big deficiencies in the code we generate llvmOpts ver = [ "-mem2reg -globalopt" , if ver >= 34 then "-O1 -globalopt" else "-O1" -- LLVM 3.4 -O1 doesn't eliminate aliases reliably (bug #8855) , "-O2" ] ----------------------------------------------------------------------------- -- LlvmLlc phase runPhase (RealPhase LlvmLlc) input_fn dflags = do ver <- liftIO $ readIORef (llvmVersion dflags) let opt_lvl = max 0 (min 2 $ optLevel dflags) -- iOS requires external references to be loaded indirectly from the -- DATA segment or dyld traps at runtime writing into TEXT: see #7722 rmodel | platformOS (targetPlatform dflags) == OSiOS = "dynamic-no-pic" | gopt Opt_PIC dflags = "pic" | not (gopt Opt_Static dflags) = "dynamic-no-pic" | otherwise = "static" tbaa | ver < 29 = "" -- no tbaa in 2.8 and earlier | gopt Opt_LlvmTBAA dflags = "--enable-tbaa=true" | otherwise = "--enable-tbaa=false" -- hidden debugging flag '-dno-llvm-mangler' to skip mangling let next_phase = case gopt Opt_NoLlvmMangler dflags of False -> LlvmMangle True | gopt Opt_SplitObjs dflags -> Splitter True -> As False output_fn <- phaseOutputFilename next_phase -- AVX can cause LLVM 3.2 to generate a C-like frame pointer -- prelude, see #9391 when (ver == 32 && isAvxEnabled dflags) $ liftIO $ errorMsg dflags $ text "Note: LLVM 3.2 has known problems with AVX instructions (see trac #9391)" liftIO $ SysTools.runLlvmLlc dflags ([ SysTools.Option (llvmOpts !! opt_lvl), SysTools.Option $ "-relocation-model=" ++ rmodel, SysTools.FileOption "" input_fn, SysTools.Option "-o", SysTools.FileOption "" output_fn] ++ [SysTools.Option tbaa] ++ map SysTools.Option fpOpts ++ map SysTools.Option abiOpts ++ map SysTools.Option sseOpts ++ map SysTools.Option (avxOpts ver) ++ map SysTools.Option avx512Opts ++ map SysTools.Option stackAlignOpts) return (RealPhase next_phase, output_fn) where -- Bug in LLVM at O3 on OSX. llvmOpts = if platformOS (targetPlatform dflags) == OSDarwin then ["-O1", "-O2", "-O2"] else ["-O1", "-O2", "-O3"] -- On ARMv7 using LLVM, LLVM fails to allocate floating point registers -- while compiling GHC source code. It's probably due to fact that it -- does not enable VFP by default. Let's do this manually here fpOpts = case platformArch (targetPlatform dflags) of ArchARM ARMv7 ext _ -> if (elem VFPv3 ext) then ["-mattr=+v7,+vfp3"] else if (elem VFPv3D16 ext) then ["-mattr=+v7,+vfp3,+d16"] else [] ArchARM ARMv6 ext _ -> if (elem VFPv2 ext) then ["-mattr=+v6,+vfp2"] else ["-mattr=+v6"] _ -> [] -- On Ubuntu/Debian with ARM hard float ABI, LLVM's llc still -- compiles into soft-float ABI. We need to explicitly set abi -- to hard abiOpts = case platformArch (targetPlatform dflags) of ArchARM _ _ HARD -> ["-float-abi=hard"] ArchARM _ _ _ -> [] _ -> [] sseOpts | isSse4_2Enabled dflags = ["-mattr=+sse42"] | isSse2Enabled dflags = ["-mattr=+sse2"] | isSseEnabled dflags = ["-mattr=+sse"] | otherwise = [] avxOpts ver | isAvx512fEnabled dflags = ["-mattr=+avx512f"] | isAvx2Enabled dflags = ["-mattr=+avx2"] | isAvxEnabled dflags = ["-mattr=+avx"] | ver == 32 = ["-mattr=-avx"] -- see #9391 | otherwise = [] avx512Opts = [ "-mattr=+avx512cd" | isAvx512cdEnabled dflags ] ++ [ "-mattr=+avx512er" | isAvx512erEnabled dflags ] ++ [ "-mattr=+avx512pf" | isAvx512pfEnabled dflags ] stackAlignOpts = case platformArch (targetPlatform dflags) of ArchX86_64 | isAvxEnabled dflags -> ["-stack-alignment=32"] _ -> [] ----------------------------------------------------------------------------- -- LlvmMangle phase runPhase (RealPhase LlvmMangle) input_fn dflags = do let next_phase = if gopt Opt_SplitObjs dflags then Splitter else As False output_fn <- phaseOutputFilename next_phase liftIO $ llvmFixupAsm dflags input_fn output_fn return (RealPhase next_phase, output_fn) ----------------------------------------------------------------------------- -- merge in stub objects runPhase (RealPhase MergeStub) input_fn dflags = do PipeState{maybe_stub_o} <- getPipeState output_fn <- phaseOutputFilename StopLn liftIO $ createDirectoryIfMissing True (takeDirectory output_fn) case maybe_stub_o of Nothing -> panic "runPhase(MergeStub): no stub" Just stub_o -> do liftIO $ joinObjectFiles dflags [input_fn, stub_o] output_fn return (RealPhase StopLn, output_fn) -- warning suppression runPhase (RealPhase other) _input_fn _dflags = panic ("runPhase: don't know how to run phase " ++ show other) maybeMergeStub :: CompPipeline Phase maybeMergeStub = do PipeState{maybe_stub_o} <- getPipeState if isJust maybe_stub_o then return MergeStub else return StopLn getLocation :: HscSource -> ModuleName -> CompPipeline ModLocation getLocation src_flavour mod_name = do dflags <- getDynFlags PipeEnv{ src_basename=basename, src_suffix=suff } <- getPipeEnv -- Build a ModLocation to pass to hscMain. -- The source filename is rather irrelevant by now, but it's used -- by hscMain for messages. hscMain also needs -- the .hi and .o filenames, and this is as good a way -- as any to generate them, and better than most. (e.g. takes -- into account the -osuf flags) location1 <- liftIO $ mkHomeModLocation2 dflags mod_name basename suff -- Boot-ify it if necessary let location2 | HsBootFile <- src_flavour = addBootSuffixLocn location1 | otherwise = location1 -- Take -ohi into account if present -- This can't be done in mkHomeModuleLocation because -- it only applies to the module being compiles let ohi = outputHi dflags location3 | Just fn <- ohi = location2{ ml_hi_file = fn } | otherwise = location2 -- Take -o into account if present -- Very like -ohi, but we must *only* do this if we aren't linking -- (If we're linking then the -o applies to the linked thing, not to -- the object file for one module.) -- Note the nasty duplication with the same computation in compileFile above let expl_o_file = outputFile dflags location4 | Just ofile <- expl_o_file , isNoLink (ghcLink dflags) = location3 { ml_obj_file = ofile } | otherwise = location3 return location4 ----------------------------------------------------------------------------- -- MoveBinary sort-of-phase -- After having produced a binary, move it somewhere else and generate a -- wrapper script calling the binary. Currently, we need this only in -- a parallel way (i.e. in GUM), because PVM expects the binary in a -- central directory. -- This is called from linkBinary below, after linking. I haven't made it -- a separate phase to minimise interfering with other modules, and -- we don't need the generality of a phase (MoveBinary is always -- done after linking and makes only sense in a parallel setup) -- HWL runPhase_MoveBinary :: DynFlags -> FilePath -> IO Bool runPhase_MoveBinary dflags input_fn | WayPar `elem` ways dflags && not (gopt Opt_Static dflags) = panic ("Don't know how to combine PVM wrapper and dynamic wrapper") | WayPar `elem` ways dflags = do let sysMan = pgm_sysman dflags pvm_root <- getEnv "PVM_ROOT" pvm_arch <- getEnv "PVM_ARCH" let pvm_executable_base = "=" ++ input_fn pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base -- nuke old binary; maybe use configur'ed names for cp and rm? _ <- tryIO (removeFile pvm_executable) -- move the newly created binary into PVM land copy dflags "copying PVM executable" input_fn pvm_executable -- generate a wrapper script for running a parallel prg under PVM writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan) return True | otherwise = return True mkExtraObj :: DynFlags -> Suffix -> String -> IO FilePath mkExtraObj dflags extn xs = do cFile <- newTempName dflags extn oFile <- newTempName dflags "o" writeFile cFile xs let rtsDetails = getPackageDetails dflags rtsPackageKey SysTools.runCc dflags ([Option "-c", FileOption "" cFile, Option "-o", FileOption "" oFile] ++ map (FileOption "-I") (includeDirs rtsDetails)) return oFile -- When linking a binary, we need to create a C main() function that -- starts everything off. This used to be compiled statically as part -- of the RTS, but that made it hard to change the -rtsopts setting, -- so now we generate and compile a main() stub as part of every -- binary and pass the -rtsopts setting directly to the RTS (#5373) -- mkExtraObjToLinkIntoBinary :: DynFlags -> IO FilePath mkExtraObjToLinkIntoBinary dflags = do when (gopt Opt_NoHsMain dflags && haveRtsOptsFlags dflags) $ do log_action dflags dflags SevInfo noSrcSpan defaultUserStyle (text "Warning: -rtsopts and -with-rtsopts have no effect with -no-hs-main." $$ text " Call hs_init_ghc() from your main() function to set these options.") mkExtraObj dflags "c" (showSDoc dflags main) where main | gopt Opt_NoHsMain dflags = Outputable.empty | otherwise = vcat [ text "#include \"Rts.h\"", text "extern StgClosure ZCMain_main_closure;", text "int main(int argc, char *argv[])", char '{', text " RtsConfig __conf = defaultRtsConfig;", text " __conf.rts_opts_enabled = " <> text (show (rtsOptsEnabled dflags)) <> semi, case rtsOpts dflags of Nothing -> Outputable.empty Just opts -> ptext (sLit " __conf.rts_opts= ") <> text (show opts) <> semi, text " __conf.rts_hs_main = rtsTrue;", text " return hs_main(argc,argv,&ZCMain_main_closure,__conf);", char '}', char '\n' -- final newline, to keep gcc happy ] -- Write out the link info section into a new assembly file. Previously -- this was included as inline assembly in the main.c file but this -- is pretty fragile. gas gets upset trying to calculate relative offsets -- that span the .note section (notably .text) when debug info is present mkNoteObjsToLinkIntoBinary :: DynFlags -> [PackageKey] -> IO [FilePath] mkNoteObjsToLinkIntoBinary dflags dep_packages = do link_info <- getLinkInfo dflags dep_packages if (platformSupportsSavingLinkOpts (platformOS (targetPlatform dflags))) then fmap (:[]) $ mkExtraObj dflags "s" (showSDoc dflags (link_opts link_info)) else return [] where link_opts info = hcat [ text "\t.section ", text ghcLinkInfoSectionName, text ",\"\",", text elfSectionNote, text "\n", text "\t.ascii \"", info', text "\"\n", -- ALL generated assembly must have this section to disable -- executable stacks. See also -- compiler/nativeGen/AsmCodeGen.lhs for another instance -- where we need to do this. (if platformHasGnuNonexecStack (targetPlatform dflags) then text ".section .note.GNU-stack,\"\",@progbits\n" else Outputable.empty) ] where info' = text $ escape info escape :: String -> String escape = concatMap (charToC.fromIntegral.ord) elfSectionNote :: String elfSectionNote = case platformArch (targetPlatform dflags) of ArchARM _ _ _ -> "%note" _ -> "@note" -- The "link info" is a string representing the parameters of the -- link. We save this information in the binary, and the next time we -- link, if nothing else has changed, we use the link info stored in -- the existing binary to decide whether to re-link or not. getLinkInfo :: DynFlags -> [PackageKey] -> IO String getLinkInfo dflags dep_packages = do package_link_opts <- getPackageLinkOpts dflags dep_packages pkg_frameworks <- if platformUsesFrameworks (targetPlatform dflags) then getPackageFrameworks dflags dep_packages else return [] let extra_ld_inputs = ldInputs dflags let link_info = (package_link_opts, pkg_frameworks, rtsOpts dflags, rtsOptsEnabled dflags, gopt Opt_NoHsMain dflags, map showOpt extra_ld_inputs, getOpts dflags opt_l) -- return (show link_info) -- generates a Perl skript starting a parallel prg under PVM mk_pvm_wrapper_script :: String -> String -> String -> String mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $ [ "eval 'exec perl -S $0 ${1+\"$@\"}'", " if $running_under_some_shell;", "# =!=!=!=!=!=!=!=!=!=!=!", "# This script is automatically generated: DO NOT EDIT!!!", "# Generated by Glasgow Haskell Compiler", "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!", "#", "$pvm_executable = '" ++ pvm_executable ++ "';", "$pvm_executable_base = '" ++ pvm_executable_base ++ "';", "$SysMan = '" ++ sysMan ++ "';", "", {- ToDo: add the magical shortcuts again iff we actually use them -- HWL "# first, some magical shortcuts to run "commands" on the binary", "# (which is hidden)", "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {", " local($cmd) = $1;", " system("$cmd $pvm_executable");", " exit(0); # all done", "}", -} "", "# Now, run the real binary; process the args first", "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base, "$debug = '';", "$nprocessors = 0; # the default: as many PEs as machines in PVM config", "@nonPVM_args = ();", "$in_RTS_args = 0;", "", "args: while ($a = shift(@ARGV)) {", " if ( $a eq '+RTS' ) {", " $in_RTS_args = 1;", " } elsif ( $a eq '-RTS' ) {", " $in_RTS_args = 0;", " }", " if ( $a eq '-d' && $in_RTS_args ) {", " $debug = '-';", " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {", " $nprocessors = $1;", " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {", " $nprocessors = $1;", " } else {", " push(@nonPVM_args, $a);", " }", "}", "", "local($return_val) = 0;", "# Start the parallel execution by calling SysMan", "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");", "$return_val = $?;", "# ToDo: fix race condition moving files and flushing them!!", "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";", "exit($return_val);" ] ----------------------------------------------------------------------------- -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file getHCFilePackages :: FilePath -> IO [PackageKey] getHCFilePackages filename = Exception.bracket (openFile filename ReadMode) hClose $ \h -> do l <- hGetLine h case l of '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest -> return (map stringToPackageKey (words rest)) _other -> return [] ----------------------------------------------------------------------------- -- Static linking, of .o files -- The list of packages passed to link is the list of packages on -- which this program depends, as discovered by the compilation -- manager. It is combined with the list of packages that the user -- specifies on the command line with -package flags. -- -- In one-shot linking mode, we can't discover the package -- dependencies (because we haven't actually done any compilation or -- read any interface files), so the user must explicitly specify all -- the packages. linkBinary :: DynFlags -> [FilePath] -> [PackageKey] -> IO () linkBinary = linkBinary' False linkBinary' :: Bool -> DynFlags -> [FilePath] -> [PackageKey] -> IO () linkBinary' staticLink dflags o_files dep_packages = do let platform = targetPlatform dflags mySettings = settings dflags verbFlags = getVerbFlags dflags output_fn = exeFileName staticLink dflags -- get the full list of packages to link with, by combining the -- explicit packages with the auto packages and all of their -- dependencies, and eliminating duplicates. full_output_fn <- if isAbsolute output_fn then return output_fn else do d <- getCurrentDirectory return $ normalise (d </> output_fn) pkg_lib_paths <- getPackageLibraryPath dflags dep_packages let pkg_lib_path_opts = concatMap get_pkg_lib_path_opts pkg_lib_paths get_pkg_lib_path_opts l | osElfTarget (platformOS platform) && dynLibLoader dflags == SystemDependent && not (gopt Opt_Static dflags) = let libpath = if gopt Opt_RelativeDynlibPaths dflags then "$ORIGIN" </> (l `makeRelativeTo` full_output_fn) else l rpath = if gopt Opt_RPath dflags then ["-Wl,-rpath", "-Wl," ++ libpath] else [] -- Solaris 11's linker does not support -rpath-link option. It silently -- ignores it and then complains about next option which is -l<some -- dir> as being a directory and not expected object file, E.g -- ld: elf error: file -- /tmp/ghc-src/libraries/base/dist-install/build: -- elf_begin: I/O error: region read: Is a directory rpathlink = if (platformOS platform) == OSSolaris2 then [] else ["-Wl,-rpath-link", "-Wl," ++ l] in ["-L" ++ l] ++ rpathlink ++ rpath | osMachOTarget (platformOS platform) && dynLibLoader dflags == SystemDependent && not (gopt Opt_Static dflags) && gopt Opt_RPath dflags = let libpath = if gopt Opt_RelativeDynlibPaths dflags then "@loader_path" </> (l `makeRelativeTo` full_output_fn) else l in ["-L" ++ l] ++ ["-Wl,-rpath", "-Wl," ++ libpath] | otherwise = ["-L" ++ l] let lib_paths = libraryPaths dflags let lib_path_opts = map ("-L"++) lib_paths extraLinkObj <- mkExtraObjToLinkIntoBinary dflags noteLinkObjs <- mkNoteObjsToLinkIntoBinary dflags dep_packages pkg_link_opts <- do (package_hs_libs, extra_libs, other_flags) <- getPackageLinkOpts dflags dep_packages return $ if staticLink then package_hs_libs -- If building an executable really means making a static -- library (e.g. iOS), then we only keep the -l options for -- HS packages, because libtool doesn't accept other options. -- In the case of iOS these need to be added by hand to the -- final link in Xcode. else other_flags ++ package_hs_libs ++ extra_libs -- -Wl,-u,<sym> contained in other_flags -- needs to be put before -l<package>, -- otherwise Solaris linker fails linking -- a binary with unresolved symbols in RTS -- which are defined in base package -- the reason for this is a note in ld(1) about -- '-u' option: "The placement of this option -- on the command line is significant. -- This option must be placed before the library -- that defines the symbol." pkg_framework_path_opts <- if platformUsesFrameworks platform then do pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages return $ map ("-F" ++) pkg_framework_paths else return [] framework_path_opts <- if platformUsesFrameworks platform then do let framework_paths = frameworkPaths dflags return $ map ("-F" ++) framework_paths else return [] pkg_framework_opts <- if platformUsesFrameworks platform then do pkg_frameworks <- getPackageFrameworks dflags dep_packages return $ concat [ ["-framework", fw] | fw <- pkg_frameworks ] else return [] framework_opts <- if platformUsesFrameworks platform then do let frameworks = cmdlineFrameworks dflags -- reverse because they're added in reverse order from -- the cmd line: return $ concat [ ["-framework", fw] | fw <- reverse frameworks ] else return [] -- probably _stub.o files let extra_ld_inputs = ldInputs dflags -- Here are some libs that need to be linked at the *end* of -- the command line, because they contain symbols that are referred to -- by the RTS. We can't therefore use the ordinary way opts for these. let debug_opts | WayDebug `elem` ways dflags = [ #if defined(HAVE_LIBBFD) "-lbfd", "-liberty" #endif ] | otherwise = [] let thread_opts | WayThreaded `elem` ways dflags = let os = platformOS (targetPlatform dflags) in if os == OSOsf3 then ["-lpthread", "-lexc"] else if os `elem` [OSMinGW32, OSFreeBSD, OSOpenBSD, OSNetBSD, OSHaiku, OSQNXNTO, OSiOS, OSDarwin] then [] else ["-lpthread"] | otherwise = [] rc_objs <- maybeCreateManifest dflags output_fn let link = if staticLink then SysTools.runLibtool else SysTools.runLink link dflags ( map SysTools.Option verbFlags ++ [ SysTools.Option "-o" , SysTools.FileOption "" output_fn ] ++ map SysTools.Option ( [] -- Permit the linker to auto link _symbol to _imp_symbol. -- This lets us link against DLLs without needing an "import library". ++ (if platformOS platform == OSMinGW32 then ["-Wl,--enable-auto-import"] else []) -- '-no_compact_unwind' -- C++/Objective-C exceptions cannot use optimised -- stack unwinding code. The optimised form is the -- default in Xcode 4 on at least x86_64, and -- without this flag we're also seeing warnings -- like -- ld: warning: could not create compact unwind for .LFB3: non-standard register 5 being saved in prolog -- on x86. ++ (if sLdSupportsCompactUnwind mySettings && not staticLink && (platformOS platform == OSDarwin || platformOS platform == OSiOS) && case platformArch platform of ArchX86 -> True ArchX86_64 -> True ArchARM {} -> True ArchARM64 -> True _ -> False then ["-Wl,-no_compact_unwind"] else []) -- '-no_pie' -- iOS uses 'dynamic-no-pic', so we must pass this to ld to suppress a warning; see #7722 ++ (if platformOS platform == OSiOS && not staticLink then ["-Wl,-no_pie"] else []) -- '-Wl,-read_only_relocs,suppress' -- ld gives loads of warnings like: -- ld: warning: text reloc in _base_GHCziArr_unsafeArray_info to _base_GHCziArr_unsafeArray_closure -- when linking any program. We're not sure -- whether this is something we ought to fix, but -- for now this flags silences them. ++ (if platformOS platform == OSDarwin && platformArch platform == ArchX86 && not staticLink then ["-Wl,-read_only_relocs,suppress"] else []) ++ o_files ++ lib_path_opts) ++ extra_ld_inputs ++ map SysTools.Option ( rc_objs ++ framework_path_opts ++ framework_opts ++ pkg_lib_path_opts ++ extraLinkObj:noteLinkObjs ++ pkg_link_opts ++ pkg_framework_path_opts ++ pkg_framework_opts ++ debug_opts ++ thread_opts )) -- parallel only: move binary to another dir -- HWL success <- runPhase_MoveBinary dflags output_fn unless success $ throwGhcExceptionIO (InstallationError ("cannot move binary")) exeFileName :: Bool -> DynFlags -> FilePath exeFileName staticLink dflags | Just s <- outputFile dflags = case platformOS (targetPlatform dflags) of OSMinGW32 -> s <?.> "exe" _ -> if staticLink then s <?.> "a" else s | otherwise = if platformOS (targetPlatform dflags) == OSMinGW32 then "main.exe" else if staticLink then "liba.a" else "a.out" where s <?.> ext | null (takeExtension s) = s <.> ext | otherwise = s maybeCreateManifest :: DynFlags -> FilePath -- filename of executable -> IO [FilePath] -- extra objects to embed, maybe maybeCreateManifest dflags exe_filename | platformOS (targetPlatform dflags) == OSMinGW32 && gopt Opt_GenManifest dflags = do let manifest_filename = exe_filename <.> "manifest" writeFile manifest_filename $ "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"++ " <assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n"++ " <assemblyIdentity version=\"1.0.0.0\"\n"++ " processorArchitecture=\"X86\"\n"++ " name=\"" ++ dropExtension exe_filename ++ "\"\n"++ " type=\"win32\"/>\n\n"++ " <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n"++ " <security>\n"++ " <requestedPrivileges>\n"++ " <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n"++ " </requestedPrivileges>\n"++ " </security>\n"++ " </trustInfo>\n"++ "</assembly>\n" -- Windows will find the manifest file if it is named -- foo.exe.manifest. However, for extra robustness, and so that -- we can move the binary around, we can embed the manifest in -- the binary itself using windres: if not (gopt Opt_EmbedManifest dflags) then return [] else do rc_filename <- newTempName dflags "rc" rc_obj_filename <- newTempName dflags (objectSuf dflags) writeFile rc_filename $ "1 24 MOVEABLE PURE " ++ show manifest_filename ++ "\n" -- magic numbers :-) -- show is a bit hackish above, but we need to escape the -- backslashes in the path. runWindres dflags $ map SysTools.Option $ ["--input="++rc_filename, "--output="++rc_obj_filename, "--output-format=coff"] -- no FileOptions here: windres doesn't like seeing -- backslashes, apparently removeFile manifest_filename return [rc_obj_filename] | otherwise = return [] linkDynLibCheck :: DynFlags -> [String] -> [PackageKey] -> IO () linkDynLibCheck dflags o_files dep_packages = do when (haveRtsOptsFlags dflags) $ do log_action dflags dflags SevInfo noSrcSpan defaultUserStyle (text "Warning: -rtsopts and -with-rtsopts have no effect with -shared." $$ text " Call hs_init_ghc() from your main() function to set these options.") linkDynLib dflags o_files dep_packages linkStaticLibCheck :: DynFlags -> [String] -> [PackageKey] -> IO () linkStaticLibCheck dflags o_files dep_packages = do when (platformOS (targetPlatform dflags) `notElem` [OSiOS, OSDarwin]) $ throwGhcExceptionIO (ProgramError "Static archive creation only supported on Darwin/OS X/iOS") linkBinary' True dflags o_files dep_packages -- ----------------------------------------------------------------------------- -- Running CPP doCpp :: DynFlags -> Bool -> FilePath -> FilePath -> IO () doCpp dflags raw input_fn output_fn = do let hscpp_opts = picPOpts dflags let cmdline_include_paths = includePaths dflags pkg_include_dirs <- getPackageIncludePath dflags [] let include_paths = foldr (\ x xs -> "-I" : x : xs) [] (cmdline_include_paths ++ pkg_include_dirs) let verbFlags = getVerbFlags dflags let cpp_prog args | raw = SysTools.runCpp dflags args | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args) let target_defs = [ "-DGHCJS_BUILD_OS=1", "-DGHCJS_BUILD_ARCH=1", "-DGHCJS_HOST_OS=1", "-DGHCJS_HOST_ARCH=1" ] -- remember, in code we *compile*, the HOST is the same our TARGET, -- and BUILD is the same as our HOST. let sse_defs = [ "-D__SSE__=1" | isSseEnabled dflags ] ++ [ "-D__SSE2__=1" | isSse2Enabled dflags ] ++ [ "-D__SSE4_2__=1" | isSse4_2Enabled dflags ] let avx_defs = [ "-D__AVX__=1" | isAvxEnabled dflags ] ++ [ "-D__AVX2__=1" | isAvx2Enabled dflags ] ++ [ "-D__AVX512CD__=1" | isAvx512cdEnabled dflags ] ++ [ "-D__AVX512ER__=1" | isAvx512erEnabled dflags ] ++ [ "-D__AVX512F__=1" | isAvx512fEnabled dflags ] ++ [ "-D__AVX512PF__=1" | isAvx512pfEnabled dflags ] backend_defs <- getBackendDefs dflags #ifdef GHCI let th_defs = [ "-D__GLASGOW_HASKELL_TH__=YES" ] #else let th_defs = [ "-D__GLASGOW_HASKELL_TH__=NO" ] #endif -- Default CPP defines in Haskell source ghcVersionH <- getGhcVersionPathName dflags let hsSourceCppOpts = [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt , "-include", ghcVersionH ] cpp_prog ( map SysTools.Option verbFlags ++ map SysTools.Option include_paths ++ map SysTools.Option hsSourceCppOpts ++ map SysTools.Option target_defs ++ map SysTools.Option backend_defs ++ map SysTools.Option th_defs ++ map SysTools.Option hscpp_opts ++ map SysTools.Option sse_defs ++ map SysTools.Option avx_defs -- Set the language mode to assembler-with-cpp when preprocessing. This -- alleviates some of the C99 macro rules relating to whitespace and the hash -- operator, which we tend to abuse. Clang in particular is not very happy -- about this. ++ [ SysTools.Option "-x" , SysTools.Option "assembler-with-cpp" , SysTools.Option input_fn -- We hackily use Option instead of FileOption here, so that the file -- name is not back-slashed on Windows. cpp is capable of -- dealing with / in filenames, so it works fine. Furthermore -- if we put in backslashes, cpp outputs #line directives -- with *double* backslashes. And that in turn means that -- our error messages get double backslashes in them. -- In due course we should arrange that the lexer deals -- with these \\ escapes properly. , SysTools.Option "-o" , SysTools.FileOption "" output_fn ]) getBackendDefs :: DynFlags -> IO [String] getBackendDefs dflags | hscTarget dflags == HscLlvm = do llvmVer <- figureLlvmVersion dflags return $ case llvmVer of Just n -> [ "-D__GLASGOW_HASKELL_LLVM__="++show n ] _ -> [] getBackendDefs _ = return [] -- --------------------------------------------------------------------------- -- join object files into a single relocatable object file, using ld -r joinObjectFiles :: DynFlags -> [FilePath] -> FilePath -> IO () joinObjectFiles dflags o_files output_fn = do let mySettings = settings dflags ldIsGnuLd = sLdIsGnuLd mySettings osInfo = platformOS (targetPlatform dflags) ld_r args cc = SysTools.runLink dflags ([ SysTools.Option "-nostdlib", SysTools.Option "-Wl,-r" ] ++ (if any (cc ==) [Clang, AppleClang, AppleClang51] then [] else [SysTools.Option "-nodefaultlibs"]) ++ (if osInfo == OSFreeBSD then [SysTools.Option "-L/usr/lib"] else []) -- gcc on sparc sets -Wl,--relax implicitly, but -- -r and --relax are incompatible for ld, so -- disable --relax explicitly. ++ (if platformArch (targetPlatform dflags) == ArchSPARC && ldIsGnuLd then [SysTools.Option "-Wl,-no-relax"] else []) ++ map SysTools.Option ld_build_id ++ [ SysTools.Option "-o", SysTools.FileOption "" output_fn ] ++ args) -- suppress the generation of the .note.gnu.build-id section, -- which we don't need and sometimes causes ld to emit a -- warning: ld_build_id | sLdSupportsBuildId mySettings = ["-Wl,--build-id=none"] | otherwise = [] ccInfo <- getCompilerInfo dflags if ldIsGnuLd then do script <- newTempName dflags "ldscript" cwd <- getCurrentDirectory let o_files_abs = map (cwd </>) o_files writeFile script $ "INPUT(" ++ unwords o_files_abs ++ ")" ld_r [SysTools.FileOption "" script] ccInfo else if sLdSupportsFilelist mySettings then do filelist <- newTempName dflags "filelist" writeFile filelist $ unlines o_files ld_r [SysTools.Option "-Wl,-filelist", SysTools.FileOption "-Wl," filelist] ccInfo else do ld_r (map (SysTools.FileOption "") o_files) ccInfo -- ----------------------------------------------------------------------------- -- Misc. writeInterfaceOnlyMode :: DynFlags -> Bool writeInterfaceOnlyMode dflags = gopt Opt_WriteInterface dflags && HscNothing == hscTarget dflags -- | What phase to run after one of the backend code generators has run hscPostBackendPhase :: DynFlags -> HscSource -> HscTarget -> Phase hscPostBackendPhase _ HsBootFile _ = StopLn hscPostBackendPhase _ HsigFile _ = StopLn hscPostBackendPhase dflags _ hsc_lang = case hsc_lang of HscC -> HCc HscAsm | gopt Opt_SplitObjs dflags -> Splitter | otherwise -> As False HscLlvm -> LlvmOpt HscNothing -> StopLn HscInterpreted -> StopLn touchObjectFile :: DynFlags -> FilePath -> IO () touchObjectFile dflags path = do createDirectoryIfMissing True $ takeDirectory path SysTools.touch dflags "Touching object file" path haveRtsOptsFlags :: DynFlags -> Bool haveRtsOptsFlags dflags = isJust (rtsOpts dflags) || case rtsOptsEnabled dflags of RtsOptsSafeOnly -> False _ -> True -- | Find out path to @ghcversion.h@ file getGhcVersionPathName :: DynFlags -> IO FilePath getGhcVersionPathName dflags = do dirs <- getPackageIncludePath dflags [rtsPackageKey] found <- filterM doesFileExist (map (</> "ghcversion.h") dirs) case found of [] -> throwGhcExceptionIO (InstallationError ("ghcversion.h missing")) (x:_) -> return x -- Note [-fPIC for assembler] -- When compiling .c source file GHC's driver pipeline basically -- does the following two things: -- 1. ${CC} -S 'PIC_CFLAGS' source.c -- 2. ${CC} -x assembler -c 'PIC_CFLAGS' source.S -- -- Why do we need to pass 'PIC_CFLAGS' both to C compiler and assembler? -- Because on some architectures (at least sparc32) assembler also chooses -- the relocation type! -- Consider the following C module: -- -- /* pic-sample.c */ -- int v; -- void set_v (int n) { v = n; } -- int get_v (void) { return v; } -- -- $ gcc -S -fPIC pic-sample.c -- $ gcc -c pic-sample.s -o pic-sample.no-pic.o # incorrect binary -- $ gcc -c -fPIC pic-sample.s -o pic-sample.pic.o # correct binary -- -- $ objdump -r -d pic-sample.pic.o > pic-sample.pic.o.od -- $ objdump -r -d pic-sample.no-pic.o > pic-sample.no-pic.o.od -- $ diff -u pic-sample.pic.o.od pic-sample.no-pic.o.od -- -- Most of architectures won't show any difference in this test, but on sparc32 -- the following assembly snippet: -- -- sethi %hi(_GLOBAL_OFFSET_TABLE_-8), %l7 -- -- generates two kinds or relocations, only 'R_SPARC_PC22' is correct: -- -- 3c: 2f 00 00 00 sethi %hi(0), %l7 -- - 3c: R_SPARC_PC22 _GLOBAL_OFFSET_TABLE_-0x8 -- + 3c: R_SPARC_HI22 _GLOBAL_OFFSET_TABLE_-0x8
seereason/ghcjs
src/Compiler/DriverPipeline.hs
mit
102,016
0
31
35,638
16,564
8,368
8,196
1,443
45
module GameEngine.Data.BSP where import Data.Word import Data.Vector (Vector) import Data.Vect hiding (Vector) import Data.ByteString {- Information: http://graphics.stanford.edu/~kekoa/q3/ http://www.mralligator.com/q3/ -} data Model = Model { mdMins :: !Vec3 , mdMaxs :: !Vec3 , mdFirstSurface :: !Int , mdNumSurfaces :: !Int , mdFirstBrush :: !Int , mdNumBrushes :: !Int } data Shader = Shader { shName :: !ByteString , shSurfaceFlags :: !Int , shContentFlags :: !Int } data Plane = Plane { plNormal :: !Vec3 , plDist :: !Float } data Node = Node { ndPlaneNum :: !Int , ndChildren :: !(Int,Int) , ndMins :: !Vec3 , ndMaxs :: !Vec3 } data Leaf = Leaf { lfCluster :: !Int , lfArea :: !Int , lfMins :: !Vec3 , lfMaxs :: !Vec3 , lfFirstLeafSurface :: !Int , lfNumLeafSurfaces :: !Int , lfFirstLeafBrush :: !Int , lfNumLeafBrushes :: !Int } data BrushSide = BrushSide { bsPlaneNum :: !Int , bsShaderNum :: !Int } data Brush = Brush { brFirstSide :: !Int , brNumSides :: !Int , brShaderNum :: !Int } data Fog = Fog { fgName :: !ByteString , fgBrushNum :: !Int , fgVisibleSide :: !Int } data DrawVertex = DrawVertex { dvPosition :: !Vec3 , dvDiffuseUV :: !Vec2 , dvLightmaptUV :: !Vec2 , dvNormal :: !Vec3 , dvColor :: !Vec4 } data SurfaceType = Planar | Patch | TriangleSoup | Flare data Surface = Surface { srShaderNum :: !Int , srFogNum :: !Int , srSurfaceType :: !SurfaceType , srFirstVertex :: !Int , srNumVertices :: !Int , srFirstIndex :: !Int , srNumIndices :: !Int , srLightmapNum :: !Int , srLightmapPos :: !Vec2 , srLightmapSize :: !Vec2 , srLightmapOrigin :: !Vec3 , srLightmapVec1 :: !Vec3 , srLightmapVec2 :: !Vec3 , srLightmapVec3 :: !Vec3 , srPatchSize :: !(Int,Int) } data Lightmap = Lightmap { lmMap :: !ByteString } data LightGrid = LightGrid data Visibility = Visibility { vsNumVecs :: !Int , vsSizeVecs :: !Int , vsVecs :: !(Vector Word8) } data BSPLevel = BSPLevel { blEntities :: !ByteString , blShaders :: !(Vector Shader) , blPlanes :: !(Vector Plane) , blNodes :: !(Vector Node) , blLeaves :: !(Vector Leaf) , blLeafSurfaces :: !(Vector Int) , blLeafBrushes :: !(Vector Int) , blModels :: !(Vector Model) , blBrushes :: !(Vector Brush) , blBrushSides :: !(Vector BrushSide) , blDrawVertices :: !(Vector DrawVertex) , blDrawIndices :: !(Vector Int) , blFogs :: !(Vector Fog) , blSurfaces :: !(Vector Surface) , blLightmaps :: !(Vector Lightmap) , blLightgrid :: !(Vector LightGrid) , blVisibility :: !Visibility }
csabahruska/quake3
game-engine/GameEngine/Data/BSP.hs
bsd-3-clause
3,111
0
11
1,078
791
448
343
254
0
{-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Machine.Pipe -- Copyright : (C) 2015 Yorick Laupa, Gabriel Gonzalez -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Yorick Laupa <yo.eight@gmail.com> -- Stability : provisional -- Portability : Rank-2 Types, GADTs -- -- Allows bidirectional communication between two MachineT. Exposed the -- same interface of Pipes library. ---------------------------------------------------------------------------- module Data.Machine.Pipe where import Control.Monad import Data.Void import Data.Machine.Plan import Data.Machine.Type infixl 8 >~> infixl 7 >+> infixl 7 >>~ infixr 6 +>> data Exchange a' a b' b c where Request :: a' -> Exchange a' a b' b a Respond :: b -> Exchange a' a b' b b' type Proxy a' a b' b m c = MachineT m (Exchange a' a b' b) c -- | 'Effect's neither 'request' nor 'respond' type Effect m r = Proxy Void () () Void m r -- | @Client a' a@ sends requests of type @a'@ and receives responses of -- type @a@. 'Client's only 'request' and never 'respond'. type Client a' a m r = Proxy a' a () Void m r -- | @Server b' b@ receives requests of type @b'@ and sends responses of type -- @b@. 'Server's only 'respond' and never 'request'. type Server b' b m r = Proxy Void () b' b m r -- | Like 'Effect', but with a polymorphic type type Effect' m r = forall x' x y' y . Proxy x' x y' y m r -- | Like 'Server', but with a polymorphic type type Server' b' b m r = forall x' x . Proxy x' x b' b m r -- | Like 'Client', but with a polymorphic type type Client' a' a m r = forall y' y . Proxy a' a y' y m r -- | Send a value of type a' upstream and block waiting for a reply of type a. -- 'request' is the identity of the request category. request :: a' -> PlanT (Exchange a' a y' y) o m a request a = awaits (Request a) -- | Send a value of type a downstream and block waiting for a reply of type a' -- 'respond' is the identity of the respond category. respond :: a -> PlanT (Exchange x' x a' a) o m a' respond a = awaits (Respond a) -- | Forward responses followed by requests. -- 'push' is the identity of the push category. push :: Monad m => a -> Proxy a' a a' a m r push = construct . go where go = respond >=> request >=> go -- | Compose two proxies blocked while 'request'ing data, creating a new proxy -- blocked while 'request'ing data. -- ('>~>') is the composition operator of the push category. (>~>) :: Monad m => (_a -> Proxy a' a b' b m r) -> (b -> Proxy b' b c' c m r) -> _a -> Proxy a' a c' c m r (fa >~> fb) a = fa a >>~ fb -- | (p >>~ f) pairs each 'respond' in p with an 'request' in f. (>>~) :: Monad m => Proxy a' a b' b m r -> (b -> Proxy b' b c' c m r) -> Proxy a' a c' c m r pm >>~ fb = MachineT $ runMachineT pm >>= \p -> case p of Stop -> return Stop Yield r n -> return $ Yield r (n >>~ fb) Await k (Request a') ff -> return $ Await (\a -> k a >>~ fb) (Request a') (ff >>~ fb) Await k (Respond b) _ -> runMachineT (k +>> fb b) -- | Forward requests followed by responses. -- 'pull' is the identity of the pull category. pull :: Monad m => a' -> Proxy a' a a' a m r pull = construct . go where go = request >=> respond >=> go -- | Compose two proxies blocked in the middle of 'respond'ing, creating a new -- proxy blocked in the middle of 'respond'ing. -- ('>+>') is the composition operator of the pull category. (>+>) :: Monad m => (b' -> Proxy a' a b' b m r) -> (_c' -> Proxy b' b c' c m r) -> _c' -> Proxy a' a c' c m r (fb' >+> fc') c' = fb' +>> fc' c' -- | (f +>> p) pairs each 'request' in p with a 'respond' in f. (+>>) :: Monad m => (b' -> Proxy a' a b' b m r) -> Proxy b' b c' c m r -> Proxy a' a c' c m r fb' +>> pm = MachineT $ runMachineT pm >>= \p -> case p of Stop -> return Stop Yield r n -> return $ Yield r (fb' +>> n) Await k (Request b') _ -> runMachineT (fb' b' >>~ k) Await k (Respond c) ff -> return $ Await (\c' -> fb' +>> k c') (Respond c) (fb' +>> ff) -- | It is impossible for an `Exchange` to hold a `Void` value. absurdExchange :: Exchange Void a b Void t -> c absurdExchange (Request z) = absurd z absurdExchange (Respond z) = absurd z -- | Run a self-contained 'Effect', converting it back to the base monad. runEffect :: Monad m => Effect m o -> m [o] runEffect (MachineT m) = m >>= \v -> case v of Stop -> return [] Yield o n -> liftM (o:) (runEffect n) Await _ y _ -> absurdExchange y -- | Like 'runEffect' but discarding any produced value. runEffect_ :: Monad m => Effect m o -> m () runEffect_ (MachineT m) = m >>= \v -> case v of Stop -> return () Yield _ n -> runEffect_ n Await _ y _ -> absurdExchange y
fumieval/machines
src/Data/Machine/Pipe.hs
bsd-3-clause
4,970
0
15
1,307
1,442
762
680
76
4
module System.Info.ShortPathName ( getShortPathName ) where import System.Win32.Info (getShortPathName)
juhp/stack
src/windows/System/Info/ShortPathName.hs
bsd-3-clause
109
0
5
14
23
15
8
3
0
{- ****************************************************************************** * H M T C * * * * Module: ScopeLevel * * Purpose: Definition of and operation on scope level. * * Authors: Henrik Nilsson * * * * Copyright (c) Henrik Nilsson, 2013 * * * ****************************************************************************** -} -- | ScopeLevel: Definition of and operation on scope level module ScopeLevel ( ScopeLvl, -- Scope level topMajScopeLvl, -- :: Int topScopeLvl, -- :: ScopeLvl majScopeLvl, -- :: ScopeLvl -> Int minScopeLvl, -- :: ScopeLvl -> Int incMajScopeLvl, -- :: ScopeLvl -> ScopeLvl incMinScopeLvl -- :: ScopeLvl -> ScopeLvl ) where ------------------------------------------------------------------------------ -- Scope level ------------------------------------------------------------------------------ -- | Scope level. -- Pair of major (depth of procedure/function) nesting -- and minor (depth of let-command nesting) levels. type ScopeLvl = (Int, Int) topMajScopeLvl :: Int topMajScopeLvl = 0 topScopeLvl :: ScopeLvl topScopeLvl = (topMajScopeLvl, 0) majScopeLvl :: ScopeLvl -> Int majScopeLvl = fst minScopeLvl :: ScopeLvl -> Int minScopeLvl = fst incMajScopeLvl :: ScopeLvl -> ScopeLvl incMajScopeLvl (majl, _) = (majl + 1, 0) incMinScopeLvl :: ScopeLvl -> ScopeLvl incMinScopeLvl (majl, minl) = (majl, minl + 1)
jbracker/supermonad-plugin
examples/monad/hmtc/original/ScopeLevel.hs
bsd-3-clause
1,896
0
6
729
174
111
63
21
1
{-# LANGUAGE Arrows #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE FlexibleInstances #-} {- Copyright (C) 2015 Martin Linnemann <theCodingMarlin@googlemail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Readers.Odt.Arrows.State Copyright : Copyright (C) 2015 Martin Linnemann License : GNU GPL, version 2 or above Maintainer : Martin Linnemann <theCodingMarlin@googlemail.com> Stability : alpha Portability : portable An arrow that transports a state. It is in essence a more powerful version of the standard state monad. As it is such a simple extension, there are other version out there that do exactly the same. The implementation is duplicated, though, to add some useful features. Most of these might be implemented without access to innards, but it's much faster and easier to implement this way. -} module Text.Pandoc.Readers.Odt.Arrows.State where import Prelude hiding ( foldr, foldl ) import qualified Control.Category as Cat import Control.Arrow import Control.Monad import Data.Foldable import Text.Pandoc.Compat.Monoid import Text.Pandoc.Readers.Odt.Arrows.Utils import Text.Pandoc.Readers.Odt.Generic.Fallible newtype ArrowState state a b = ArrowState { runArrowState :: (state, a) -> (state, b) } -- | Constructor withState :: (state -> a -> (state, b)) -> ArrowState state a b withState = ArrowState . uncurry -- | Constructor withState' :: ((state, a) -> (state, b)) -> ArrowState state a b withState' = ArrowState -- | Constructor modifyState :: (state -> state ) -> ArrowState state a a modifyState = ArrowState . first -- | Constructor ignoringState :: ( a -> b ) -> ArrowState state a b ignoringState = ArrowState . second -- | Constructor fromState :: (state -> (state, b)) -> ArrowState state a b fromState = ArrowState . (.fst) -- | Constructor extractFromState :: (state -> b ) -> ArrowState state x b extractFromState f = ArrowState $ \(state,_) -> (state, f state) -- | Constructor withUnchangedState :: (state -> a -> b ) -> ArrowState state a b withUnchangedState f = ArrowState $ \(state,a) -> (state, f state a) -- | Constructor tryModifyState :: (state -> Either f state) -> ArrowState state a (Either f a) tryModifyState f = ArrowState $ \(state,a) -> (state,).Left ||| (,Right a) $ f state instance Cat.Category (ArrowState s) where id = ArrowState id arrow2 . arrow1 = ArrowState $ (runArrowState arrow2).(runArrowState arrow1) instance Arrow (ArrowState state) where arr = ignoringState first a = ArrowState $ \(s,(aF,aS)) -> second (,aS) $ runArrowState a (s,aF) second a = ArrowState $ \(s,(aF,aS)) -> second (aF,) $ runArrowState a (s,aS) instance ArrowChoice (ArrowState state) where left a = ArrowState $ \(s,e) -> case e of Left l -> second Left $ runArrowState a (s,l) Right r -> (s, Right r) right a = ArrowState $ \(s,e) -> case e of Left l -> (s, Left l) Right r -> second Right $ runArrowState a (s,r) instance ArrowLoop (ArrowState state) where loop a = ArrowState $ \(s, x) -> let (s', (x', _d)) = runArrowState a (s, (x, _d)) in (s', x') instance ArrowApply (ArrowState state) where app = ArrowState $ \(s, (f,b)) -> runArrowState f (s,b) -- | Embedding of a state arrow in a state arrow with a different state type. switchState :: (s -> s') -> (s' -> s) -> ArrowState s' x y -> ArrowState s x y switchState there back a = ArrowState $ first there >>> runArrowState a >>> first back -- | Lift a state arrow to modify the state of an arrow -- with a different state type. liftToState :: (s -> s') -> ArrowState s' s s -> ArrowState s x x liftToState unlift a = modifyState $ unlift &&& id >>> runArrowState a >>> snd -- | Switches the type of the state temporarily. -- Drops the intermediate result state, behaving like the identity arrow, -- save for side effects in the state. withSubState :: ArrowState s x s2 -> ArrowState s2 s s -> ArrowState s x x withSubState unlift a = keepingTheValue (withSubState unlift a) >>^ fst -- | Switches the type of the state temporarily. -- Returns the resulting sub-state. withSubState' :: ArrowState s x s' -> ArrowState s' s s -> ArrowState s x s' withSubState' unlift a = ArrowState $ runArrowState unlift >>> switch >>> runArrowState a >>> switch where switch (x,y) = (y,x) -- | Switches the type of the state temporarily. -- Drops the intermediate result state, behaving like a fallible -- identity arrow, save for side effects in the state. withSubStateF :: ArrowState s x (Either f s') -> ArrowState s' s (Either f s ) -> ArrowState s x (Either f x ) withSubStateF unlift a = keepingTheValue (withSubStateF' unlift a) >>^ spreadChoice >>^ fmap fst -- | Switches the type of the state temporarily. -- Returns the resulting sub-state. withSubStateF' :: ArrowState s x (Either f s') -> ArrowState s' s (Either f s ) -> ArrowState s x (Either f s') withSubStateF' unlift a = ArrowState go where go p@(s,_) = tryRunning unlift ( tryRunning a (second Right) ) p where tryRunning a' b v = case runArrowState a' v of (_ , Left f) -> (s, Left f) (x , Right y) -> b (y,x) -- | Fold a state arrow through something 'Foldable'. Collect the results -- in a 'Monoid'. -- Intermediate form of a fold between one with "only" a 'Monoid' -- and one with any function. foldS :: (Foldable f, Monoid m) => ArrowState s x m -> ArrowState s (f x) m foldS a = ArrowState $ \(s,f) -> foldr a' (s,mempty) f where a' x (s',m) = second (m <>) $ runArrowState a (s',x) -- | Fold a state arrow through something 'Foldable'. Collect the results -- in a 'Monoid'. -- Intermediate form of a fold between one with "only" a 'Monoid' -- and one with any function. foldSL :: (Foldable f, Monoid m) => ArrowState s x m -> ArrowState s (f x) m foldSL a = ArrowState $ \(s,f) -> foldl a' (s,mempty) f where a' (s',m) x = second (m <>) $ runArrowState a (s',x) -- | Fold a fallible state arrow through something 'Foldable'. Collect the -- results in a 'Monoid'. -- Intermediate form of a fold between one with "only" a 'Monoid' -- and one with any function. -- If the iteration fails, the state will be reset to the initial one. foldS' :: (Foldable f, Monoid m) => ArrowState s x (Either e m) -> ArrowState s (f x) (Either e m) foldS' a = ArrowState $ \(s,f) -> foldr (a' s) (s,Right mempty) f where a' s x (s',Right m) = case runArrowState a (s',x) of (s'',Right m') -> (s'', Right (m <> m')) (_ ,Left e ) -> (s , Left e) a' _ _ e = e -- | Fold a fallible state arrow through something 'Foldable'. Collect the -- results in a 'Monoid'. -- Intermediate form of a fold between one with "only" a 'Monoid' -- and one with any function. -- If the iteration fails, the state will be reset to the initial one. foldSL' :: (Foldable f, Monoid m) => ArrowState s x (Either e m) -> ArrowState s (f x) (Either e m) foldSL' a = ArrowState $ \(s,f) -> foldl (a' s) (s,Right mempty) f where a' s (s',Right m) x = case runArrowState a (s',x) of (s'',Right m') -> (s'', Right (m <> m')) (_ ,Left e ) -> (s , Left e) a' _ e _ = e -- | Fold a state arrow through something 'Foldable'. Collect the results in a -- 'MonadPlus'. iterateS :: (Foldable f, MonadPlus m) => ArrowState s x y -> ArrowState s (f x) (m y) iterateS a = ArrowState $ \(s,f) -> foldr a' (s,mzero) f where a' x (s',m) = second ((mplus m).return) $ runArrowState a (s',x) -- | Fold a state arrow through something 'Foldable'. Collect the results in a -- 'MonadPlus'. iterateSL :: (Foldable f, MonadPlus m) => ArrowState s x y -> ArrowState s (f x) (m y) iterateSL a = ArrowState $ \(s,f) -> foldl a' (s,mzero) f where a' (s',m) x = second ((mplus m).return) $ runArrowState a (s',x) -- | Fold a fallible state arrow through something 'Foldable'. -- Collect the results in a 'MonadPlus'. -- If the iteration fails, the state will be reset to the initial one. iterateS' :: (Foldable f, MonadPlus m) => ArrowState s x (Either e y ) -> ArrowState s (f x) (Either e (m y)) iterateS' a = ArrowState $ \(s,f) -> foldr (a' s) (s,Right mzero) f where a' s x (s',Right m) = case runArrowState a (s',x) of (s'',Right m') -> (s'',Right $ mplus m $ return m') (_ ,Left e ) -> (s ,Left e ) a' _ _ e = e -- | Fold a fallible state arrow through something 'Foldable'. -- Collect the results in a 'MonadPlus'. -- If the iteration fails, the state will be reset to the initial one. iterateSL' :: (Foldable f, MonadPlus m) => ArrowState s x (Either e y ) -> ArrowState s (f x) (Either e (m y)) iterateSL' a = ArrowState $ \(s,f) -> foldl (a' s) (s,Right mzero) f where a' s (s',Right m) x = case runArrowState a (s',x) of (s'',Right m') -> (s'',Right $ mplus m $ return m') (_ ,Left e ) -> (s ,Left e ) a' _ e _ = e
janschulz/pandoc
src/Text/Pandoc/Readers/Odt/Arrows/State.hs
gpl-2.0
10,991
2
14
3,489
2,939
1,582
1,357
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="sr-CS"> <title>Form Handler | 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>
kingthorin/zap-extensions
addOns/formhandler/src/main/javahelp/org/zaproxy/zap/extension/formhandler/resources/help_sr_CS/helpset_sr_CS.hs
apache-2.0
973
78
66
159
413
209
204
-1
-1
{-# LANGUAGE TupleSections, UnboxedTuples #-} module Main where a :: Bool -> (Int, Bool) a = ( , True) b :: Int -> Bool -> (Int, Bool) b = (1, ) c :: a -> (a, Bool) c = (True || False, ) d :: Bool -> (#Int, Bool#) d = (# , True#) e :: Int -> Bool -> (#Int, Bool#) e = (#1, #) f :: a -> (#a, Bool#) f = (#True || False, #) main = return ()
hvr/jhc
regress/tests/1_typecheck/4_fail/ghc/tcfail206.hs
mit
345
8
9
88
186
111
75
15
1
-- -- Adapted from the program "infer", believed to have been originally -- authored by Philip Wadler, and used in the nofib benchmark suite -- since at least the late 90s. -- module StateX (StateX, returnSX, eachSX, thenSX, toSX, putSX, getSX, useSX) where data StateX s a = MkSX (s -> a) rep (MkSX f) = f returnSX returnX x = MkSX (\s -> returnX (x, s)) eachSX eachX xSX f = MkSX (\s -> rep xSX s `eachX` (\(x,s') -> (f x, s'))) thenSX thenX xSX kSX = MkSX (\s -> rep xSX s `thenX` (\(x,s') -> rep (kSX x) s')) toSX eachX xX = MkSX (\s -> xX `eachX` (\x -> (x,s))) putSX returnX s' = MkSX (\s -> returnX ((), s')) getSX returnX = MkSX (\s -> returnX (s,s)) useSX eachX s xSX = rep xSX s `eachX` (\(x,s') -> x)
jasonzoladz/parconc-examples
parinfer/StateX.hs
bsd-3-clause
779
0
13
211
351
200
151
10
1
import qualified Data.Vector as U main = print . head . U.toList . U.fromList $ replicate 1 (7::Int)
dolio/vector
old-testsuite/microsuite/from-to.hs
bsd-3-clause
101
0
8
18
45
25
20
2
1
module WhereIn3 where f y = g y where g x@(Left a) = case x of (Right b) -> b (Left a) -> a
RefactoringTools/HaRe
old/testing/simplifyExpr/WhereIn3_TokOut.hs
bsd-3-clause
156
0
11
88
62
32
30
5
2
-- !!! ds016 -- case expressions -- module ShouldCompile where f x y z = case ( x ++ x ++ x ++ x ++ x ) of [] -> [] [a] -> error "2" [a,b,c] -> case ( (y,z,y,z) ) of -- (True, _, False, _) | True == False -> z -- (True, _, False, _) | True == False -> z _ -> z (a:bs) -> error "4"
ezyang/ghc
testsuite/tests/deSugar/should_compile/ds016.hs
bsd-3-clause
409
0
10
199
121
68
53
9
4
-- Copyright (c) 2000 Galois Connections, Inc. -- All rights reserved. This software is distributed as -- free software under the license in the file "LICENSE", -- which is included in the distribution. module Parse where import Data.Char import Text.ParserCombinators.Parsec hiding (token) import Data program :: Parser Code program = do { whiteSpace ; ts <- tokenList ; eof ; return ts } tokenList :: Parser Code tokenList = many token <?> "list of tokens" token :: Parser GMLToken token = do { ts <- braces tokenList ; return (TBody ts) } <|> do { ts <- brackets tokenList ; return (TArray ts) } <|> (do { s <- gmlString ; return (TString s) } <?> "string") <|> (do { t <- pident False ; return t } <?> "identifier") <|> (do { char '/' -- No whitespace after slash ; t <- pident True ; return t } <?> "binding identifier") <|> (do { n <- number ; return n } <?> "number") pident :: Bool -> Parser GMLToken pident rebind = do { id <- ident ; case (lookup id opTable) of Nothing -> if rebind then return (TBind id) else return (TId id) Just t -> if rebind then error ("Attempted rebinding of identifier " ++ id) else return t } ident :: Parser String ident = lexeme $ do { l <- letter ; ls <- many (satisfy (\x -> isAlphaNum x || x == '-' || x == '_')) ; return (l:ls) } gmlString :: Parser String gmlString = lexeme $ between (char '"') (char '"') (many (satisfy (\x -> isPrint x && x /= '"'))) -- Tests for numbers -- Hugs breaks on big exponents (> ~40) test_number = "1234 -1234 1 -0 0" ++ " 1234.5678 -1234.5678 1234.5678e12 1234.5678e-12 -1234.5678e-12" ++ " -1234.5678e12 -1234.5678E-12 -1234.5678E12" ++ " 1234e11 1234E33 -1234e33 1234e-33" ++ " 123e 123.4e 123ee 123.4ee 123E 123.4E 123EE 123.4EE" -- Always int or real number :: Parser GMLToken number = lexeme $ do { s <- optSign ; n <- decimal ; do { string "." ; m <- decimal ; e <- option "" exponent' ; return (TReal (read (s ++ n ++ "." ++ m ++ e))) -- FIXME: Handle error conditions } <|> do { e <- exponent' ; return (TReal (read (s ++ n ++ ".0" ++ e))) } <|> do { return (TInt (read (s ++ n))) } } exponent' :: Parser String exponent' = try $ do { e <- oneOf "eE" ; s <- optSign ; n <- decimal ; return (e:s ++ n) } decimal = many1 digit optSign :: Parser String optSign = option "" (string "-") ------------------------------------------------------ -- Library for tokenizing. braces p = between (symbol "{") (symbol "}") p brackets p = between (symbol "[") (symbol "]") p symbol name = lexeme (string name) lexeme p = do{ x <- p; whiteSpace; return x } whiteSpace = skipMany (simpleSpace <|> oneLineComment <?> "") where simpleSpace = skipMany1 (oneOf " \t\n\r\v") oneLineComment = do{ string "%" ; skipMany (noneOf "\n\r\v") ; return () } ------------------------------------------------------------------------------ rayParse :: String -> Code rayParse is = case (parse program "<stdin>" is) of Left err -> error (show err) Right x -> x rayParseF :: String -> IO Code rayParseF file = do { r <- parseFromFile program file ; case r of Left err -> error (show err) Right x -> return x } run :: String -> IO () run is = case (parse program "" is) of Left err -> print err Right x -> print x runF :: IO () runF = do { r <- parseFromFile program "simple.gml" ; case r of Left err -> print err Right x -> print x }
urbanslug/ghc
testsuite/tests/programs/galois_raytrace/Parse.hs
bsd-3-clause
3,880
0
21
1,220
1,264
639
625
89
4
-- Copyright (c) 2000 Galois Connections, Inc. -- All rights reserved. This software is distributed as -- free software under the license in the file "LICENSE", -- which is included in the distribution. module Primitives where rad2deg :: Double -> Double rad2deg r = r * 180 / pi deg2rad :: Double -> Double deg2rad d = d * pi / 180 addi :: Int -> Int -> Int addi = (+) addf :: Double -> Double -> Double addf = (+) acosD :: Double -> Double acosD x = acos x * 180 / pi asinD :: Double -> Double asinD x = asin x * 180 / pi
ryantm/ghc
testsuite/tests/programs/galois_raytrace/Primitives.hs
bsd-3-clause
532
0
7
118
154
85
69
13
1
module ViewTranslation where import qualified Matrix4f import qualified Vector3f import qualified Vector4f import Vector3f (x, y, z) translation :: Vector3f.T -> Matrix4f.T translation p = let np_x = -(x p) np_y = -(y p) np_z = -(z p) in Matrix4f.T { Matrix4f.column_3 = Vector4f.V4 np_x np_y np_z 1.0, Matrix4f.column_2 = Vector4f.V4 0.0 0.0 1.0 0.0, Matrix4f.column_1 = Vector4f.V4 0.0 1.0 0.0 0.0, Matrix4f.column_0 = Vector4f.V4 1.0 0.0 0.0 0.0 }
io7m/jcamera
com.io7m.jcamera.documentation/src/main/resources/com/io7m/jcamera/documentation/haskell/ViewTranslation.hs
isc
510
0
11
129
176
97
79
15
1
module WebPage where import Profile import Conf import TokenCSFR import OAuth import API import Lucid import Protolude import Control.Lens import Data.Aeson import Orphan.UUID import Network.URL -- to use import Synchro urlToLog :: OAuthCred -> TokenCSFR -> Text urlToLog OAuthCred{..} t = toSL $ exportURL URL { url_type = Absolute $ Host (HTTP True) (toSL _authDomain) Nothing , url_path = toSL _authPath , url_params = [ ("redirect_uri" , toSL _uriRedirect ) , ("response_type" , "code" ) , ("client_id" , toSL _clientId ) , ("state" , show t ) , ("prompt" , "consent" ) -- only while debugging , ("scope" , toSL _scope ) , ("access_type" , "offline" ) ] } -------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------- instance ToHtml WebPage where toHtmlRaw = toHtml toHtml WebPage{..} = doctype_ >> html where html = html_ $ do head_ $ do meta_ [name_ "google-site-verification", content_ verification] meta_ [charset_ "UTF-8"] meta_ [title_ "Kinda Might Work" ] case innerPage of Nothing -> "" Just InnerPage{..} -> do script_ [src_ "https://code.jquery.com/jquery-1.7.1.min.js"] (""::Text) script_ [src_$ "https://api.trello.com/1/client.js?key="<> _clientId trello_conf] (""::Text) script_ [src_ "/trelloAuth.js"] (""::Text) body_ body urlToAction :: (Monad m) => Text -> HtmlT m () -> HtmlT m () urlToAction path = a_ [href_ $ path ] urlToAction' path = urlToAction (path <> "/" <> show csrf_token) urlTolog' cred = a_ [href_ $ urlToLog cred csrf_token] body = case innerPage of Nothing -> do h3_ "Kinda Might Work:" p_ "Get your Trello and WunderList accounts on sync!" urlTolog' google_conf "log with google to continue" Just InnerPage{..} -> do h3_ $ "Welcome " <> toHtml userName <> " !!" p_ $ do "Using accounts for email: " strong_ (toHtml userEmail) "( "<> urlToAction "/go-out" "log out" <> " )" br_ [] if trelloAccount then p_ [] $ do "Your trello acount is linked (" urlToAction' "/tr-out" "unlink" ") " else a_ [ onclick_ $ "authenticateTrello('"<> show csrf_token <>"')" , href_ "#" ] "link your trello account" br_ [] if wuListAccount then p_ [] $ do "Your WunderList acount is linked (" urlToAction' "/wl-out" "unlink" ") " else urlTolog' wuList_conf"link your wunderlist account" br_ [] let ready = wuListAccount && trelloAccount h4_ "Click to Sync!" if not ready then p_ [] $ do "You need to link your Trello and " "Wunderlist account to sync." else toSyncForm outOfSync toSyncForm :: (Monad m) => [(Text,SyncOptions)] -> HtmlT m () toSyncForm fields = form_ [action_ $"/sync/"<>show csrf_token, method_ "post"] $ do fieldset_ $ do legend_ "Boards to syncrhonize" let toRetrieve = [ (name,ref) | (name,ToRetrieve ref _) <- fields ] ul_ $ sequence_ [ li_ [] $ do input_ [type_ "checkbox", name_"board", value_ ref] toHtml (show name :: Text) | (name,ref) <- toRetrieve ] br_ [] if null toRetrieve then h4_ "Everything sync'ed, press F5 to check again." else input_ [type_ "submit",value_ "sync selected boards"] br_ [] fieldset_ $ do legend_ "Already sync'ed:" ul_ $ sequence_ [ li_ [] $ do p_ $ toHtml (show name :: Text) br_ [] | (name,AlreadySync) <- fields ]
mreider/kinda-might-work
src/WebPage.hs
mit
7,057
0
23
4,287
1,105
542
563
-1
-1
module Hafer.Data.GenericGraph ( module Hafer.Data.GenericGraph -- TODO: proper interface ) where import Data.List (find) -- Data declarations data Graph v e = MathGraph [Vertex v] [Edge v e] | ElemSetGraph [GraphElem v e] deriving (Show, Eq) data Vertex v = Vertex v deriving (Show, Eq) data Edge v e = Edge e Direction (Vertex v) (Vertex v) deriving (Show, Eq) data GraphElem v e = GVertex (Vertex v) | GEdge (Edge v e) deriving (Show, Eq) data Direction = None | L2R | R2L | Both deriving (Show, Eq) -- | Typeclass for converting vertex/edge types to labels that can be -- shown in a generic graph rendering. -- Reduced version of Text.Show typeclass -- (which should rather be used for debugging purposes) class Format a where format :: a -> String -- Graph properties vertices :: Graph v e -> [Vertex v] vertices g = case g of MathGraph vs es -> vs ElemSetGraph elems -> foldr (++) [] $ map (\e -> case e of GVertex v -> [v] _ -> []) elems edges :: Graph v e -> [Edge v e] edges g = case g of MathGraph vs es -> es ElemSetGraph elems -> foldr (++) [] $ map (\e -> case e of GEdge e -> [e] _ -> []) elems elements :: Graph v e -> [GraphElem v e] elements g = case g of ElemSetGraph elems -> elems MathGraph vs es -> map (\v -> GVertex v) vs ++ map (\e -> GEdge e) es edgesFor :: Eq v => Graph v e -> Vertex v -> [Edge v e] edgesFor g v = let es = edges g in filter (isConnectedVia v) es isConnectedVia :: Eq v => Vertex v -> Edge v e -> Bool isConnectedVia v (Edge e dir a b) = if (v == a) || (v == b) then True else False adjacents :: Eq v => Graph v e -> Vertex v -> [Vertex v] adjacents g v = let es = edgesFor g v vs = vertices g adjaRefs = map ( \e -> case e of Edge e' dir a b -> if a == v then b else a ) es in map (\ref -> case (find (\v -> v == ref) vs) of Just v -> v Nothing -> ref ) adjaRefs -- ########################################################################## -- # Graph properties -- ########################################################################## degree :: Eq v => Graph v e -> [(Vertex v, Int)] degree g = let vs = vertices g in map (\v -> let adjas = adjacents g v in (v, length adjas) ) vs maxDegree :: Eq v => Graph v e -> Int maxDegree g = maximum $ map (\(v, d) -> d) $ degree g
ooz/Hafer
src/Hafer/Data/GenericGraph.hs
mit
3,237
0
16
1,469
996
516
480
68
3
britishDenominations = [ 1, 2, 5, 10, 20, 50, 100, 200 ] countSplits :: (Integral a) => a -> [a] -> a countSplits n dens = countSplits' n remaining where remaining = takeWhile (<=n) dens countSplits' n [] | n>0 = 0 countSplits' 0 _ = 1 countSplits' _ [x] = 1 countSplits' n rem = sum $ map (\d -> countSplits (n-d) $ filter (<=d) rem) rem answer = countSplits 200 britishDenominations
arekfu/project_euler
p0031/p0031.hs
mit
392
0
12
80
191
102
89
9
1
{-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Yesod.Paginator.Pages ( -- * Type safe @'Natural'@s -- | -- -- N.B. @'PageNumber'@ and @'PerPage'@ will currently allow @0@, but it's -- unclear if that's correct and may not be the case in the future. -- PageNumber , PerPage , ItemsCount , pageOffset -- * Page , Page , pageItems , pageNumber , toPage -- * Pages , Pages , pagesCurrent , pagesLast , toPages -- * Safely accessing Pages data , takePreviousPages , takeNextPages , getPreviousPage , getNextPage ) where import Yesod.Paginator.Prelude import Text.Blaze (ToMarkup) import Web.PathPieces newtype PageNumber = PageNumber Natural deriving newtype (Enum, Eq, Integral, Num, Ord, Real, Show, ToMarkup) newtype PerPage = PerPage Natural deriving newtype (Enum, Eq, Integral, Num, Ord, Real, Read, Show, PathPiece) newtype ItemsCount = ItemsCount Natural deriving newtype (Enum, Eq, Integral, Num, Ord, Real, Read, Show, PathPiece) data Page a = Page { pageItems :: [a] , pageNumber :: PageNumber } deriving stock (Eq, Show) setPageItems :: Page a -> [b] -> Page b setPageItems page items = page { pageItems = items } overPageItems :: ([a] -> [b]) -> Page a -> Page b overPageItems f page = setPageItems page $ f $ pageItems page instance Functor Page where fmap f = overPageItems $ fmap f instance Foldable Page where foldMap f = foldMap f . pageItems instance Traversable Page where traverse f page = setPageItems page <$> traverse f (pageItems page) -- | @'Page'@ constructor toPage :: [a] -> PageNumber -> Page a toPage = Page data Pages a = Pages { pagesCurrent :: Page a , pagesPrevious :: [PageNumber] , pagesNext :: [PageNumber] , pagesLast :: PageNumber } deriving stock (Eq, Show) setPagesCurrent :: Pages a -> Page b -> Pages b setPagesCurrent pages current = pages { pagesCurrent = current } overPagesCurrent :: (Page a -> Page b) -> Pages a -> Pages b overPagesCurrent f pages = setPagesCurrent pages $ f $ pagesCurrent pages instance Functor Pages where fmap f = overPagesCurrent $ fmap f instance Foldable Pages where foldMap f = foldMap f . pagesCurrent instance Traversable Pages where traverse f pages = setPagesCurrent pages <$> traverse f (pagesCurrent pages) -- | Take previous pages, going back from current -- -- >>> takePreviousPages 3 $ Pages (Page [] 5) [1,2,3,4] [6] 6 -- [2,3,4] -- takePreviousPages :: Natural -> Pages a -> [PageNumber] takePreviousPages n = reverse . genericTake n . reverse . pagesPrevious -- | Take next pages, going forward from current -- -- >>> takeNextPages 3 $ Pages (Page [] 2) [1] [3,4,5,6] 6 -- [3,4,5] -- takeNextPages :: Natural -> Pages a -> [PageNumber] takeNextPages n = genericTake n . pagesNext -- | The previous page number, if it exists -- -- >>> getPreviousPage $ Pages (Page [] 1) [] [2,3,4] 4 -- Nothing -- -- >>> getPreviousPage $ Pages (Page [] 2) [1] [3,4] 4 -- Just 1 -- getPreviousPage :: Pages a -> Maybe PageNumber getPreviousPage pages = do let prevPage = pageNumber (pagesCurrent pages) - 1 firstPage <- headMay $ pagesPrevious pages prevPage <$ guard (prevPage >= firstPage) -- | The next page number, if it exists -- -- >>> getNextPage $ Pages (Page [] 4) [1,2,3] [] 4 -- Nothing -- -- >>> getNextPage $ Pages (Page [] 3) [1,2] [4] 4 -- Just 4 -- getNextPage :: Pages a -> Maybe PageNumber getNextPage pages = do let nextPage = pageNumber (pagesCurrent pages) + 1 lastPage <- lastMay $ pagesNext pages nextPage <$ guard (nextPage <= lastPage) -- | Construct a @'Pages' a@ from paginated data -- -- >>> toPages 4 3 10 [] -- Pages {pagesCurrent = Page {pageItems = [], pageNumber = 4}, pagesPrevious = [1,2,3], pagesNext = [], pagesLast = 4} -- toPages :: PageNumber -> PerPage -> ItemsCount -> [a] -> Pages a toPages number per total items = Pages { pagesCurrent = toPage items number , pagesPrevious = [1 .. (number - 1)] , pagesNext = [(number + 1) .. lastPage] , pagesLast = lastPage } where lastPage = getLastPage total per -- | Calculate the last page of some paginated data -- -- >>> getLastPage 10 3 -- 4 -- -- >>> getLastPage 10 5 -- 2 -- getLastPage :: ItemsCount -> PerPage -> PageNumber getLastPage total = fromIntegral . carry . (total `divMod`) . fromIntegral where carry :: (Eq a, Num a) => (a, a) -> a carry (q, 0) = q carry (q, _) = q + 1 -- | Calculate a page's zero-based offset in the overall items -- -- >>> pageOffset 4 3 -- 9 -- pageOffset :: PageNumber -> PerPage -> ItemsCount pageOffset p per = fromIntegral $ (fromIntegral p - 1) * per
pbrisbin/yesod-paginator
src/Yesod/Paginator/Pages.hs
mit
4,769
0
13
1,070
1,233
675
558
90
2
module SqlTypes where import qualified CsvTypes as Mcsv import Data.Text import Database.Persist.TH (mkPersist, mkMigrate, persistLowerCase, share, sqlSettings) share [mkPersist sqlSettings, mkMigrate "migrateTables"] [persistLowerCase| District sid Int name Text Primary sid MEAPScore meapDistrict DistrictId year Text grade Int subject Mcsv.Subject subgroup Mcsv.Subgroup numTested Int level1Proficient Double level2Proficient Double level3Proficient Double level4Proficient Double totalProficient Double avgScore Double stdDev Double deriving Show SchoolStaff staffDistrict DistrictId teachers Double librarians Double librarySupport Double |]
rdlester/meap-analysis
Src/SqlTypes.hs
mit
852
0
7
274
62
39
23
-1
-1
{-# LANGUAGE CPP #-} module GHCJS.DOM.SVGAnimatedAngle ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.SVGAnimatedAngle #else #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.SVGAnimatedAngle #else #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/SVGAnimatedAngle.hs
mit
361
0
5
33
33
26
7
4
0
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.CharacterData (js_substringData, substringData, js_appendData, appendData, js_insertData, insertData, js_deleteData, deleteData, js_replaceData, replaceData, js_setData, setData, js_getData, getData, js_getLength, getLength, CharacterData, castToCharacterData, gTypeCharacterData, IsCharacterData, toCharacterData) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"substringData\"]($2, $3)" js_substringData :: JSRef CharacterData -> Word -> Word -> IO (JSRef (Maybe JSString)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/CharacterData.substringData Mozilla CharacterData.substringData documentation> substringData :: (MonadIO m, IsCharacterData self, FromJSString result) => self -> Word -> Word -> m (Maybe result) substringData self offset length = liftIO (fromMaybeJSString <$> (js_substringData (unCharacterData (toCharacterData self)) offset length)) foreign import javascript unsafe "$1[\"appendData\"]($2)" js_appendData :: JSRef CharacterData -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/CharacterData.appendData Mozilla CharacterData.appendData documentation> appendData :: (MonadIO m, IsCharacterData self, ToJSString data') => self -> data' -> m () appendData self data' = liftIO (js_appendData (unCharacterData (toCharacterData self)) (toJSString data')) foreign import javascript unsafe "$1[\"insertData\"]($2, $3)" js_insertData :: JSRef CharacterData -> Word -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/CharacterData.insertData Mozilla CharacterData.insertData documentation> insertData :: (MonadIO m, IsCharacterData self, ToJSString data') => self -> Word -> data' -> m () insertData self offset data' = liftIO (js_insertData (unCharacterData (toCharacterData self)) offset (toJSString data')) foreign import javascript unsafe "$1[\"deleteData\"]($2, $3)" js_deleteData :: JSRef CharacterData -> Word -> Word -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/CharacterData.deleteData Mozilla CharacterData.deleteData documentation> deleteData :: (MonadIO m, IsCharacterData self) => self -> Word -> Word -> m () deleteData self offset length = liftIO (js_deleteData (unCharacterData (toCharacterData self)) offset length) foreign import javascript unsafe "$1[\"replaceData\"]($2, $3, $4)" js_replaceData :: JSRef CharacterData -> Word -> Word -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/CharacterData.replaceData Mozilla CharacterData.replaceData documentation> replaceData :: (MonadIO m, IsCharacterData self, ToJSString data') => self -> Word -> Word -> data' -> m () replaceData self offset length data' = liftIO (js_replaceData (unCharacterData (toCharacterData self)) offset length (toJSString data')) foreign import javascript unsafe "$1[\"data\"] = $2;" js_setData :: JSRef CharacterData -> JSRef (Maybe JSString) -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/CharacterData.data Mozilla CharacterData.data documentation> setData :: (MonadIO m, IsCharacterData self, ToJSString val) => self -> Maybe val -> m () setData self val = liftIO (js_setData (unCharacterData (toCharacterData self)) (toMaybeJSString val)) foreign import javascript unsafe "$1[\"data\"]" js_getData :: JSRef CharacterData -> IO (JSRef (Maybe JSString)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/CharacterData.data Mozilla CharacterData.data documentation> getData :: (MonadIO m, IsCharacterData self, FromJSString result) => self -> m (Maybe result) getData self = liftIO (fromMaybeJSString <$> (js_getData (unCharacterData (toCharacterData self)))) foreign import javascript unsafe "$1[\"length\"]" js_getLength :: JSRef CharacterData -> IO Word -- | <https://developer.mozilla.org/en-US/docs/Web/API/CharacterData.length Mozilla CharacterData.length documentation> getLength :: (MonadIO m, IsCharacterData self) => self -> m Word getLength self = liftIO (js_getLength (unCharacterData (toCharacterData self)))
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/CharacterData.hs
mit
5,262
70
13
955
1,257
690
567
93
1
-- | Interpreter for the DSL to generate `PromptScript`'s. module Interp where import AST import Control.Monad import Data.Foldable (foldlM) import Data.Map.Strict (Map, filterWithKey, findWithDefault, mapAccum, mapAccumWithKey) import qualified Data.Map.Strict as Map import Data.Set (Set, difference, elems, empty, insert, notMember) import Data.Traversable (mapM) import Errors import qualified Text.Parsec as Parsec import qualified Utils -- | Compile a `CueSheet` into a `PromptScript` safely. transpile :: CueSheet -> Either Error PromptScript transpile cs = do declChars <- safeListToSet DuplicateCharacterDeclaration (characters cs) declDepts <- safeListToSet DuplicateDepartmentDeclaration (departments cs) foldlM insertAct (PromptScript "Untitled" declChars declDepts Map.empty) (acts cs) -- | Inserts a `CueAct` into the appropriately place in a PromptScript. insertAct :: PromptScript -> CueAct -> Either Error PromptScript insertAct ps ca@(CueAct i scs) = do ensureStrictGtInsert (\_ -> OutOfOrderOrDuplicateActError ca) i (pActs ps) foldlM (insertScene i) ps scs -- | Inserts a `CueScene` into a `PromptScript`. insertScene :: Int -- ^ Act index of target. -> PromptScript -- ^ Full `PromptScript` to be updated. -> CueScene -- ^ CueScene to be inserted. -> Either Error PromptScript -- ^ Updated `PromptScript` or `Error`. insertScene aIdx ps sc@(CueScene i cgs) = do ensureStrictGtInsert (\_ -> OutOfOrderOrDuplicateSceneError sc) i (pActScenes $ findWithDefault (PromptAct Map.empty) aIdx (pActs ps)) foldlM (insertCueGroups aIdx i) ps cgs -- | Check unkown characters. checkUnkownCharacters :: PromptScript -- ^ Script -> PromptScript -- ^ Cue Sheet -> Either [Error] () -- ^ Result checkUnkownCharacters s p = do declChars <- return $ pCharacters p knownChars <- return $ pCharacters s errs <- return $ foldr (\l errs -> Errors.UnkownTargetCharacterError l:errs) [] (difference declChars knownChars) if null errs then return () else Left errs -- | Merge a prompt script with a cuesheet. eval :: PromptScript -- ^ The prompt script, possibly already marked up. -> PromptScript -- ^ The compiled cuesheet. -> Either [Error] PromptScript -- ^ A list of `Error`s, or the updated prompt script. eval prompt cuesheet = let (errs, prompt') = mapAccumWithKey (processAct cuesheet) [] (pActs prompt) in if null errs then Right $ prompt { pActs = prompt' } else Left errs -- | Merge `PromptAct`s scenes into `PromptScript`. processAct :: PromptScript -- ^ The prompt script to be updated. -> [Error] -- ^ Accumulating errors. -> Int -- ^ Act index. -> PromptAct -- ^ Act from cue sheet to be merged in. -> ([Error], PromptAct) -- ^ Any errors and updated act. processAct cuesheet errs0 actIdx (PromptAct scenes) = let (errs, scenes') = mapAccumWithKey (processScene cuesheet actIdx) [] scenes in if null errs then (errs0, PromptAct scenes') else (errs0 ++ errs, PromptAct scenes') -- | Merge `PromptScenes`s cue groups into `PromptScript`. processScene :: PromptScript -- ^ The cuehseet -> Int -- ^ Act index -> [Error] -- ^ Accumulating errors -> Int -- ^ Scene index -> PromptScene -- ^ Original scene -> ([Error], PromptScene) -- ^ Results processScene cuesheet actIdx errs0 scIdx (PromptScene markers) = -- `cms` are any relevant markers from cuesheet. let scenes = pActScenes $ findWithDefault (PromptAct Map.empty) actIdx (pActs cuesheet) in let cms = pMarkers $ findWithDefault (PromptScene Map.empty) scIdx scenes in let (errs, markers') = fst $ mapAccum resolveMarker ([], markers) cms in (errs0 ++ errs, PromptScene markers') -- | Attempt to place a PromptMarker into a PromptScript. resolveMarker :: ([Error], Map.Map Int PromptMarker) -- ^ Any errors and the "script". -> PromptMarker -- ^ PromptMarker to be placed. -> (([Error], Map.Map Int PromptMarker), Map.Map Int PromptMarker) -- ^ First is -- updated, IGNORE -- snd. resolveMarker (errs0, m0) mFromCueSheet@(PromptMarker _ cues) = let res = filterWithKey (fuzzyMatch mFromCueSheet) m0 in if null res then ((errs0 ++ [NoMatchError mFromCueSheet], m0), m0) -- TODO: check return: it is ignored else if Map.size res == 1 then ((errs0, Map.adjust (\p@(PromptMarker _ cs) -> p { pCues = cs ++ cues }) (head $ Map.keys res) m0), m0) else ((errs0 ++ [AmbiguousError mFromCueSheet $ Map.elems res], m0), m0) -- | Attempt to insert a CueGroup into a script. insertCueGroups :: Int -- ^ Act index. -> Int -- ^ Scene index. -> PromptScript -- ^ Prompt script to be updated. -> CueGroup -- ^ CueGroup to place -> Either Error PromptScript -- ^ Updated `PromptScript` or `Error`. insertCueGroups aIdx scIdx ps (CueGroup m cues) = do -- check character well-scoped (let char = mChar m in if char `notMember` pCharacters ps then Left (UndeclaredCharacterError char) else Right ()) -- check department all well scoped foldM_ (\() (Cue d _ _ _) -> if d `notMember` pDepartments ps then Left (UndeclaredDepartmentError d) else Right ()) () cues -- all checks pass, let's add it! insertPromptMarker aIdx scIdx (PromptMarker m cues) ps -- | Insert a PromptMarker into the script UNSAFELY. insertPromptMarker :: Int -- ^ Act index. -> Int -- ^ Scene index. -> PromptMarker -- ^ Marker to be inserted. -> PromptScript -- ^ Prompt script to be updated. -> Either e PromptScript -- ^ Updated prompt script. insertPromptMarker aIdx scIdx m ps = -- TODO: self explanatory... let theScenes = (pActScenes $ findWithDefault (PromptAct Map.empty) aIdx (pActs ps)) in let theScenes = (pActScenes $ findWithDefault (PromptAct Map.empty) aIdx (pActs ps)) in let theMarkrs = (pMarkers $ findWithDefault (PromptScene Map.empty) scIdx theScenes) in let theMarkrs' = Map.insert (genKey theMarkrs) m theMarkrs in let theScene' = PromptScene theMarkrs' in let theAct' = PromptAct $ Map.insert scIdx theScene' theScenes in let theActs' = Map.insert aIdx theAct' (pActs ps) in Right $ ps { pActs = theActs' } -- | Generator a fresh key to be used in a Map based on the highest index. genKey :: (Enum k, Bounded k) => Map.Map k v -> k genKey m | null m = minBound | otherwise = succ $ fst (Map.findMax m) -- | Safely convert a list of elements to a set, complaining if there are any -- duplicates. safeListToSet :: (Ord a, Traversable t) => (a -> e) -> t a -> Either e (Set a) safeListToSet eF = foldlM (flip handlePossibleDup) empty where handlePossibleDup e es = if e `elem` es then Left (eF e) else Right (e `insert` es) -- | Check to see if the item attempting to be inserted, is strictly greater -- than the highest element in the map. ensureStrictGtInsert :: Ord k => (k -> e) -> k -> Map k v -> Either e (Map k v) ensureStrictGtInsert eF i m | null m = Right m | otherwise = if i > fst (Map.findMax m) then Right m else Left (eF i) -- | Fuzzy check if two `PromptMarker`s match. -- -- fuzzyMatch :: PromptMarker -- ^ Search Criteria -> Int -- ^ Marker Index -> PromptMarker -- ^ Possible match -> Bool -- ^ True if fuzzy match, False otherwise. fuzzyMatch (PromptMarker (Visual _ _ _) _) _ (PromptMarker (Line _ _ _) _) = False fuzzyMatch (PromptMarker (Line _ _ _) _) _ (PromptMarker (Visual _ _ _) _) = False fuzzyMatch (PromptMarker (Line c1 l1 Nothing) _) _ (PromptMarker (Line c0 l0 _) _) = c0 == c1 && Utils.substring l1 l0 fuzzyMatch (PromptMarker (Line c1 l1 (Just i1)) _) i0 (PromptMarker (Line c0 l0 _) _) = c0 == c1 && i0 == i1 && Utils.substring l1 l0 fuzzyMatch (PromptMarker (Visual c1 a1 Nothing) _) _ (PromptMarker (Visual c0 a0 _) _) = c0 == c1 && a0 == a1 fuzzyMatch (PromptMarker v1@(Visual _ _ (Just _)) _) i0 (PromptMarker (Visual c0 a0 _) _) = (Visual c0 a0 $ Just i0) == v1
rwoll-hmc/project
src/Interp.hs
mit
9,241
0
23
2,941
2,357
1,229
1,128
140
3
module GCC where import Data.Maybe import Data.List import Data.Char trim :: String -> String trim = f . f where f = reverse . dropWhile isSpace type Int32 = Int type Addr = Int data AddrOrLabel = AbsAddr Addr | RefAddr String instance Show AddrOrLabel where show (AbsAddr n) = show n show (RefAddr label) = label instance Read AddrOrLabel where readsPrec _ value = let v = dropWhile isSpace value in let ds = takeWhile isDigit v in if null ds then [(RefAddr (takeWhile (not . isSpace) v), dropWhile (not . isSpace) v)] else [(AbsAddr (read ds), dropWhile isDigit v)] data Instruction = LDC Int32 | LD Int Int | ST Int Int | ADD | SUB | MUL | DIV | CEQ | CGT | CGTE | ATOM | CONS | CAR | CDR | SEL AddrOrLabel AddrOrLabel | JOIN | LDF AddrOrLabel | AP Int | RTN | DUM Int | RAP Int | STOP | TSEL AddrOrLabel AddrOrLabel | TAP Int | TRAP Int | DBUG | BRK instance Show Instruction where show (LDC n) = "LDC " ++ show n show (LD i j) = "LD " ++ show i ++ " " ++ show j show (ST i j) = "ST " ++ show i ++ " " ++ show j show (ADD) = "ADD" show (SUB) = "SUB" show (MUL) = "MUL" show (DIV) = "DIV" show (CEQ) = "CEQ" show (CGT) = "CGT" show (CGTE) = "CGTE" show (ATOM) = "ATOM" show (CONS) = "CONS" show (CAR) = "CAR" show (CDR) = "CDR" show (SEL a1 a2) = "SEL " ++ show a1 ++ " " ++ show a2 show (JOIN) = "JOIN" show (LDF a) = "LDF " ++ show a show (AP n) = "AP " ++ show n show (RTN) = "RTN" show (DUM n) = "DUM " ++ show n show (RAP n) = "RAP " ++ show n show (STOP) = "STOP" show (TSEL a1 a2) = "TSEL " ++ show a1 ++ " " ++ show a2 show (TAP n) = "TAP " ++ show n show (TRAP n) = "TRAP " ++ show n show (DBUG) = "DBUG" show (BRK) = "BRK" parseInstruction :: String -> [String] -> Instruction parseInstruction "LDC" [n] = LDC (read n) parseInstruction "LD" [i, j] = LD (read i) (read j) parseInstruction "ST" [i, j] = ST (read i) (read j) parseInstruction "ADD" [] = ADD parseInstruction "SUB" [] = SUB parseInstruction "MUL" [] = MUL parseInstruction "DIV" [] = DIV parseInstruction "CEQ" [] = CEQ parseInstruction "CGT" [] = CGT parseInstruction "CGTE" [] = CGTE parseInstruction "ATOM" [] = ATOM parseInstruction "CONS" [] = CONS parseInstruction "CAR" [] = CAR parseInstruction "CDR" [] = CDR parseInstruction "SEL" [a1, a2] = SEL (read a1) (read a2) parseInstruction "JOIN" [] = JOIN parseInstruction "LDF" [a] = LDF (read a) parseInstruction "AP" [n] = AP (read n) parseInstruction "RTN" [] = RTN parseInstruction "DUM" [n] = DUM (read n) parseInstruction "RAP" [n] = RAP (read n) parseInstruction "STOP" [] = STOP parseInstruction "TSEL" [a1, a2] = TSEL (read a1) (read a2) parseInstruction "TAP" [n] = TAP (read n) parseInstruction "TRAP" [n] = TRAP (read n) parseInstruction "DBUG" [] = DBUG parseInstruction "BRK" [] = BRK parseInstruction s args = error $ "bad instruction: " ++ s ++ " " ++ intercalate " " args data InstructionOrLabel = Instruction Instruction | Label String type Program = [Instruction] type ProgramWithLabels = [InstructionOrLabel] writeAsm :: FilePath -> Program -> IO () writeAsm filename = writeFile filename . unlines . map show assemble :: ProgramWithLabels -> Program assemble p = assemble' (buildSymtab 0 p) p where buildSymtab n p = case p of [] -> [] (Instruction _):p' -> buildSymtab (n + 1) p' (Label label):p' -> (label, n) : buildSymtab n p' assemble' symtab p = case p of [] -> [] (Instruction i):p' -> assembleInstruction symtab i : assemble' symtab p' (Label _):p' -> assemble' symtab p' assembleInstruction symtab i = case i of SEL a1 a2 -> SEL (lookupLabel symtab a1) (lookupLabel symtab a2) LDF a -> LDF (lookupLabel symtab a) TSEL a1 a2 -> TSEL (lookupLabel symtab a1) (lookupLabel symtab a2) _ -> i lookupLabel symtab a = case a of RefAddr label -> AbsAddr $ fromJust $ lookup label symtab AbsAddr _ -> a -- The following are not currently used. instance Show InstructionOrLabel where show (Instruction i) = " " ++ show i show (Label label) = label ++ ":" readAsmWithLabels :: FilePath -> IO ProgramWithLabels readAsmWithLabels filename = do s <- readFile filename return $ (catMaybes . map lineToMaybeInstructionOrLabel . map stripComment . lines) s where lineToMaybeInstructionOrLabel :: String -> Maybe InstructionOrLabel lineToMaybeInstructionOrLabel s = let ws = words s in case ws of [] -> Nothing w:ws -> if (last w == ':') && (ws == []) then Just $ Label $ init w else Just $ Instruction $ parseInstruction w ws stripComment :: String -> String stripComment = takeWhile (/= ';') writeAsmWithLabels :: FilePath -> ProgramWithLabels -> IO () writeAsmWithLabels filename = writeFile filename . unlines . map show
jchl/icfp2014
src/GCC.hs
mit
5,271
0
17
1,556
2,040
1,038
1,002
143
9
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-} module Y2017.M11.D10.Exercise where {-- So we've got keywords and recommended article sets as files we're reading from. El-great-o. Now, let's create a scheme and upload these data to our data store. --} import Data.Map (Map) import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.SqlQQ import Database.PostgreSQL.Simple.ToRow -- below imports available via 1HaskellADay git repository import Data.MemoizingTable import Store.SQL.Connection import Store.SQL.Util.Indexed import Store.SQL.Util.Inserts import Store.SQL.Util.Pivots import Y2017.M11.D03.Exercise -- Keyphrase import Y2017.M11.D06.Exercise -- Score, etc import Y2017.M11.D07.Exercise -- Recommend -- We will read in our keyphrases and scores/recommendations and store them in -- the database -- step 1. read in the keyphrases -- step 2. read in the scores {-- -- Now we have to provide ToRow instances of these things instance ToRow Keyphrase where toRow kw = undefined On second thought, is that the way to go? Storing a keyphrase requires the below --v keyphrase kind, so a toRow instance of Keyphrase doesn't make sense, as a row's information comes from multiple sources. --} -- each time we save a keyphrase set, we provide versioning/typing information -- on how we got our keywords. Was it Maui, TFIDF, word-frequency? Let's add a -- row to say that. keyphraseKindStmt :: Query keyphraseKindStmt = [sql|INSERT INTO keyphrase_algorithm (algorithm) VALUES (?) RETURNING id|] keyphraseKind :: Connection -> String -> IO [Index] keyphraseKind conn kind = undefined -- hint: how do we pass kind in the format Simple SQL expects? -- So, we have the keyphrases, their strengths, and an index for kind, let's put -- these together and insert each keyphrase into the keyword database, linking -- the keyphrase to the article_id ... which, of course, is linked via -- article_analysis -- so we do need to know what articles are analyzed already, and which articles -- are not ... enter the memoizing table -- first, load article_analysis into the memoizing table by getting its values articlesStmt :: Query articlesStmt = [sql|SELECT id,article_id FROM article_analysis|] article :: Connection -> IO [(Integer, Integer)] article conn = undefined -- query_ conn articlesStmt {-- >>> arts <- article conn >>> arts [] ... which is fine, as we haven't done any analysis (that we've stored in the database) on our article set. So let's do that. We do that by inserting the keyphrase with its article index into the database, then checked to make sure we have the article id, or, if not, add it to our memoizing table. Goodness this is a lot of housekeeping! --} insertKWsStmt :: Query insertKWsStmt = [sql|INSERT INTO keyphrase (strength,keyphrase,kind) VALUES (?,?,?) returning id|] data KWInserter = KWI Strength String Integer instance ToRow KWInserter where toRow kwi = undefined kws2Kwi :: Index -> KeyphraseMap -> [KWInserter] kws2Kwi idx kphmap = undefined insertKW :: Connection -> Index -> KeyphraseMap -> IO [Index] insertKW conn idx kphrmap = undefined -- And now we have the keyphrase indices to insert into the join table which -- must (and this is where the memoizing table comes in) refer to the article id-- in the article_analysis table. If an article id isn't in the analysis table, -- we add it. insertKWjoinsStmt :: Query insertKWjoinsStmt = [sql|INSERT INTO article_keyphrase (keyphrase_id,article_id) VALUES (?,?)|] -- but since we have the article ids in the keyphrase map already, and we know -- what the article ids already stored in the memoizing table, we can treat -- this problem at another time. -- but what we do have to do is convert the map indices (one article_id for many -- keyphrases) to be in one-for-one correspondence to the returned indices of -- the keyphrases just inserted. keys2indices :: KeyphraseMap -> [Index] keys2indices kphrmap = undefined insertKWjoins :: Connection -> [Index] -> KeyphraseMap -> IO () insertKWjoins conn idxn kphrmap = undefined -- RECOMMENDATIONS ------------------------------------------------------- -- Now we do the same with the recommendation set. Also memoizing article ids -- from the recommendation data structure... {-- We can't have a single ToRow instance because the recommendations are divided amongst two tables: QRY goes to article_recommendation and VAL x goes to recommendation instance ToRow Recommend where toRow r = undefinek --} insertStudiedStmt :: Query insertStudiedStmt = [sql|INSERT INTO article_recommendation (article_id) VALUES (?)|] insertRecsStmt :: Query insertRecsStmt = [sql|INSERT INTO recommendation (recommended_article_id,article_id,hindsight_score) VALUES (?,?,?)|] insertStudied :: Connection -> Score -> IO () insertStudied conn (Row i _ QRY) = inserter conn insertStudiedStmt [Idx i] insertRecs :: Connection -> Index -> [Score] -> IO () insertRecs conn idx = inserter conn insertRecsStmt . map (\(Row i _ (VAL f)) -> (idx,i,f)) -- which means we need to partition the scores by type. -- ANALYSES ----------------------------------------------------------------- -- Now we can wrap it up by collating all article ids and inserting the new ones -- into the article_analysis table type MTII = MemoizingTable Integer Integer insertAnalyzedStmt :: Query insertAnalyzedStmt = [sql|INSERT INTO article_analysis (article_id) VALUES (?)|] insertAnalyses :: Connection -> MTII -> IO () insertAnalyses conn = undefined -- which, of course, we need to collate these values to insert -- So we take all the scored recommendations, and all the keywords, and we diff -- them -- which means we need to make scored indexed by article id instance Indexed Score where idx (Row i _ _) = i analyzed :: Map Integer Score -> KeyphraseMap -> MTII -> MTII analyzed scrs kphrmap mtii = undefined -- but we need a memoizing table to start from ... startMT :: [(Integer, Integer)] -> MTII startMT pairs = undefined -- with that, insert the analyses.
geophf/1HaskellADay
exercises/HAD/Y2017/M11/D10/Exercise.hs
mit
6,179
0
12
1,133
693
417
276
59
1
{-# LANGUAGE TemplateHaskell #-} import Luck.Template import Test.QuickCheck gen :: Gen (Maybe [Bool]) gen = $(mkGenQ defFlags{_fileName="examples/Combination.luck",_maxUnroll=14}) tProxy1 main = sample $ (fmap . fmap . fmap) fromEnum gen
QuickChick/Luck
luck/examples-template/combination.hs
mit
241
0
10
31
83
45
38
6
1
module Language.F2.Eval (eval, getInt, getBool, getTuple, applyValue, getValue) where import Language.F2.DataType import Control.Monad.Error import Control.Monad.State getInt :: Value -> Either String Integer getInt v = do v' <- getValue v case v' of VInt x -> return x _ -> throwError "exec error : type miss..." getBool :: Value -> Either String Bool getBool v = do v' <- getValue v case v' of VBool x -> return x _ -> throwError "exec error : type miss..." getTuple :: Value -> Either String (Value, Value) getTuple v = do v' <- getValue v case v' of VTuple x -> return x _ -> throwError "exec error : type miss..." applyValue :: Value -> Value -> Either String Value applyValue v x = do v' <- getValue v case v' of VFun env (Fun s ast) -> eval ((s, x):env) ast VFFI f -> f v getValue :: Value -> Either String Value getValue (VLazy env ast) = eval env ast getValue x = return x eval' :: AST -> StateT VEnv (Either String) Value eval' (Let s e1 e2) = do v1 <- eval' e1 modify ((s,v1):) v2 <- eval' e2 modify tail return v2 eval' (LetRec s e1 e2) = do v1 <- eval' e1 case v1 of VFun env e -> do let fn = VFun ((s, fn):env) e modify ((s,fn):) _ -> modify ((s, v1):) v2 <- eval' e2 modify tail return v2 eval' fn@(Fun s e) = do env <- get return $ VFun env fn eval' fn@(App e1 e2) = do v1 <- eval' e1 >>= lift . getValue v2 <- eval' e2 case v1 of VFun env (Fun s f) -> do envs <- get put $ (s, v2):env v3 <- eval' f put envs return v3 VFFI f -> lift $ f v2 eval' (If c e1 e2) = do vc <- eval' c >>= lift . getBool if vc then eval' e1 else eval' e2 eval' (Tuple (e1, e2)) = do v1 <- eval' e1 v2 <- eval' e2 return (VTuple (v1,v2)) eval' (Var s) = do env <- get case lookup s env of Just v -> return v eval' (IntLit x) = return $ VInt x eval' (BoolLit x) = return $ VBool x eval' (Sig ast _) = eval' ast eval' (Lazy ast) = do env <- get return $ VLazy env ast eval :: VEnv -> AST -> Either String Value eval env ast = evalStateT (eval' ast) env
kagamilove0707/F2
src/Language/F2/Eval.hs
mit
2,117
0
18
585
1,051
501
550
83
4
module Hasql.Postgres.Options where import BasePrelude import Options.Applicative import qualified Hasql.Postgres as HP -- | -- Given a prefix for long names produce a parser of 'HP.Settings'. settings :: Maybe String -> Parser HP.Settings settings prefix = HP.ParamSettings <$> host <*> port <*> user <*> password <*> database where host = fmap fromString $ strOption $ long (applyPrefix "host") <> value "127.0.0.1" <> showDefault <> help "Server host" port = option auto $ long (applyPrefix "port") <> value 5432 <> showDefault <> help "Server port" user = fmap fromString $ strOption $ long (applyPrefix "user") <> value "postgres" <> showDefault <> help "Username" password = fmap fromString $ strOption $ long (applyPrefix "password") <> value "" <> showDefault <> help "Password" database = fmap fromString $ strOption $ long (applyPrefix "database") <> value "" <> showDefault <> help "Default database name" applyPrefix s = maybe s (<> ("-" <> s)) prefix
nikita-volkov/hasql-postgres-options
library/Hasql/Postgres/Options.hs
mit
1,193
0
13
379
311
154
157
39
1
{- | Module : $Header$ Copyright : Heng Jiang, Uni Bremen 2007 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : portable OWL 2 signature and sentences -} module OWL2.Sign where import OWL2.AS import qualified Data.Set as Set import qualified Data.Map as Map data Sign = Sign { concepts :: Set.Set Class -- classes , datatypes :: Set.Set Datatype -- datatypes , objectProperties :: Set.Set Individual -- object properties , dataProperties :: Set.Set DataProperty -- data properties , annotationRoles :: Set.Set AnnotationProperty -- annotation properties , individuals :: Set.Set NamedIndividual -- named individuals , prefixMap :: PrefixMap } deriving (Show, Eq, Ord) data SignAxiom = Subconcept ClassExpression ClassExpression -- subclass, superclass | Role (DomainOrRangeOrFunc (RoleKind, RoleType)) ObjectPropertyExpression | Data (DomainOrRangeOrFunc ()) DataPropertyExpression | Conceptmembership NamedIndividual ClassExpression deriving (Show, Eq, Ord) data RoleKind = FuncRole | RefRole deriving (Show, Eq, Ord) data RoleType = IRole | DRole deriving (Show, Eq, Ord) data DesKind = RDomain | DDomain | RIRange deriving (Show, Eq, Ord) data DomainOrRangeOrFunc a = DomainOrRange DesKind ClassExpression | RDRange DataRange | FuncProp a deriving (Show, Eq, Ord) emptySign :: Sign emptySign = Sign { concepts = Set.empty , datatypes = Set.empty , objectProperties = Set.empty , dataProperties = Set.empty , annotationRoles = Set.empty , individuals = Set.empty , prefixMap = Map.empty } diffSig :: Sign -> Sign -> Sign diffSig a b = a { concepts = concepts a `Set.difference` concepts b , datatypes = datatypes a `Set.difference` datatypes b , objectProperties = objectProperties a `Set.difference` objectProperties b , dataProperties = dataProperties a `Set.difference` dataProperties b , annotationRoles = annotationRoles a `Set.difference` annotationRoles b , individuals = individuals a `Set.difference` individuals b } addSign :: Sign -> Sign -> Sign addSign toIns totalSign = totalSign { concepts = Set.union (concepts totalSign) (concepts toIns), datatypes = Set.union (datatypes totalSign) (datatypes toIns), objectProperties = Set.union (objectProperties totalSign) (objectProperties toIns), dataProperties = Set.union (dataProperties totalSign) (dataProperties toIns), annotationRoles = Set.union (annotationRoles totalSign) (annotationRoles toIns), individuals = Set.union (individuals totalSign) (individuals toIns) } isSubSign :: Sign -> Sign -> Bool isSubSign a b = Set.isSubsetOf (concepts a) (concepts b) && Set.isSubsetOf (datatypes a) (datatypes b) && Set.isSubsetOf (objectProperties a) (objectProperties b) && Set.isSubsetOf (dataProperties a) (dataProperties b) && Set.isSubsetOf (annotationRoles a) (annotationRoles b) && Set.isSubsetOf (individuals a) (individuals b) symOf :: Sign -> Set.Set Entity symOf s = Set.unions [ Set.map (Entity Class) $ concepts s , Set.map (Entity Datatype) $ datatypes s , Set.map (Entity ObjectProperty) $ objectProperties s , Set.map (Entity DataProperty) $ dataProperties s , Set.map (Entity NamedIndividual) $ individuals s , Set.map (Entity AnnotationProperty) $ annotationRoles s ]
nevrenato/Hets_Fork
OWL2/Sign.hs
gpl-2.0
3,910
0
12
1,131
1,011
543
468
76
1
{-| A ledger-compatible @balance@ command, with additional support for multi-column reports. Here is a description/specification for the balance command. See also "Hledger.Reports" -> \"Balance reports\". /Basic balance report/ With no reporting interval (@--monthly@ etc.), hledger's balance command emulates ledger's, showing accounts indented according to hierarchy, along with their total amount posted (including subaccounts). Here's an example. With @data/sample.journal@, which defines the following account tree: @ assets bank checking saving cash expenses food supplies income gifts salary liabilities debts @ the basic @balance@ command gives this output: @ $ hledger -f sample.journal balance $-1 assets $1 bank:saving $-2 cash $2 expenses $1 food $1 supplies $-2 income $-1 gifts $-1 salary $1 liabilities:debts -------------------- 0 @ Subaccounts are displayed indented below their parent. Only the account leaf name (the final part) is shown. (With @--flat@, account names are shown in full and unindented.) Each account's \"balance\" is the sum of postings in that account and any subaccounts during the report period. When the report period includes all transactions, this is equivalent to the account's current balance. The overall total of the highest-level displayed accounts is shown below the line. (The @--no-total/-N@ flag prevents this.) /Eliding and omitting/ Accounts which have a zero balance, and no non-zero subaccount balances, are normally omitted from the report. (The @--empty/-E@ flag forces such accounts to be displayed.) Eg, above @checking@ is omitted because it has a zero balance and no subaccounts. Accounts which have a single subaccount also being displayed, with the same balance, are normally elided into the subaccount's line. (The @--no-elide@ flag prevents this.) Eg, above @bank@ is elided to @bank:saving@ because it has only a single displayed subaccount (@saving@) and their balance is the same ($1). Similarly, @liabilities@ is elided to @liabilities:debts@. /Date limiting/ The default report period is that of the whole journal, including all known transactions. The @--begin\/-b@, @--end\/-e@, @--period\/-p@ options or @date:@/@date2:@ patterns can be used to report only on transactions before and/or after specified dates. /Depth limiting/ The @--depth@ option can be used to limit the depth of the balance report. Eg, to see just the top level accounts (still including their subaccount balances): @ $ hledger -f sample.journal balance --depth 1 $-1 assets $2 expenses $-2 income $1 liabilities -------------------- 0 @ /Account limiting/ With one or more account pattern arguments, the report is restricted to accounts whose name matches one of the patterns, plus their parents and subaccounts. Eg, adding the pattern @o@ to the first example gives: @ $ hledger -f sample.journal balance o $1 expenses:food $-2 income $-1 gifts $-1 salary -------------------- $-1 @ * The @o@ pattern matched @food@ and @income@, so they are shown. * @food@'s parent (@expenses@) is shown even though the pattern didn't match it, to clarify the hierarchy. The usual eliding rules cause it to be elided here. * @income@'s subaccounts are also shown. /Multi-column balance report/ hledger's balance command will show multiple columns when a reporting interval is specified (eg with @--monthly@), one column for each sub-period. There are three kinds of multi-column balance report, indicated by the heading: * A \"period balance\" (or \"flow\") report (the default) shows the change of account balance in each period, which is equivalent to the sum of postings in each period. Here, checking's balance increased by 10 in Feb: > Change of balance (flow): > > Jan Feb Mar > assets:checking 20 10 -5 * A \"cumulative balance\" report (with @--cumulative@) shows the accumulated ending balance across periods, starting from zero at the report's start date. Here, 30 is the sum of checking postings during Jan and Feb: > Ending balance (cumulative): > > Jan Feb Mar > assets:checking 20 30 25 * A \"historical balance\" report (with @--historical/-H@) also shows ending balances, but it includes the starting balance from any postings before the report start date. Here, 130 is the balance from all checking postings at the end of Feb, including pre-Jan postings which created a starting balance of 100: > Ending balance (historical): > > Jan Feb Mar > assets:checking 120 130 125 /Eliding and omitting, 2/ Here's a (imperfect?) specification for the eliding/omitting behaviour: * Each account is normally displayed on its own line. * An account less deep than the report's max depth, with just one interesting subaccount, and the same balance as the subaccount, is non-interesting, and prefixed to the subaccount's line, unless @--no-elide@ is in effect. * An account with a zero inclusive balance and less than two interesting subaccounts is not displayed at all, unless @--empty@ is in effect. * Multi-column balance reports show full account names with no eliding (like @--flat@). Accounts (and periods) are omitted as described below. /Which accounts to show in balance reports/ By default: * single-column: accounts with non-zero balance in report period. (With @--flat@: accounts with non-zero balance and postings.) * periodic: accounts with postings and non-zero period balance in any period * cumulative: accounts with non-zero cumulative balance in any period * historical: accounts with non-zero historical balance in any period With @-E/--empty@: * single-column: accounts with postings in report period * periodic: accounts with postings in report period * cumulative: accounts with postings in report period * historical: accounts with non-zero starting balance + accounts with postings in report period /Which periods (columns) to show in balance reports/ An empty period/column is one where no report account has any postings. A zero period/column is one where no report account has a non-zero period balance. Currently, by default: * single-column: N/A * periodic: all periods within the overall report period, except for leading and trailing empty periods * cumulative: all periods within the overall report period, except for leading and trailing empty periods * historical: all periods within the overall report period, except for leading and trailing empty periods With @-E/--empty@: * single-column: N/A * periodic: all periods within the overall report period * cumulative: all periods within the overall report period * historical: all periods within the overall report period /What to show in empty cells/ An empty periodic balance report cell is one which has no corresponding postings. An empty cumulative/historical balance report cell is one which has no correponding or prior postings, ie the account doesn't exist yet. Currently, empty cells show 0. -} module Hledger.Cli.Balance ( balancemode ,balance ,balanceReportAsText ,periodBalanceReportAsText ,cumulativeBalanceReportAsText ,historicalBalanceReportAsText ,tests_Hledger_Cli_Balance ) where import System.Console.CmdArgs.Explicit as C import Text.CSV import Test.HUnit import Text.Printf (printf) import Text.Tabular as T import Text.Tabular.AsciiArt import Hledger import Hledger.Data.OutputFormat import Hledger.Cli.Options import Hledger.Cli.Utils -- | Command line options for this command. balancemode = (defCommandMode $ ["balance"] ++ aliases) { -- also accept but don't show the common bal alias modeHelp = "show accounts and balances" `withAliases` aliases ,modeGroupFlags = C.Group { groupUnnamed = [ flagNone ["tree"] (\opts -> setboolopt "tree" opts) "show accounts as a tree (default in simple reports)" ,flagNone ["flat"] (\opts -> setboolopt "flat" opts) "show accounts as a list (default in multicolumn mode)" ,flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "flat mode: omit N leading account name parts" ,flagReq ["format"] (\s opts -> Right $ setopt "format" s opts) "FORMATSTR" "tree mode: use this custom line format" ,flagNone ["no-elide"] (\opts -> setboolopt "no-elide" opts) "tree mode: don't squash boring parent accounts" ,flagNone ["historical","H"] (\opts -> setboolopt "historical" opts) "multicolumn mode: show historical ending balances" ,flagNone ["cumulative"] (\opts -> setboolopt "cumulative" opts) "multicolumn mode: show accumulated ending balances" ,flagNone ["average","A"] (\opts -> setboolopt "average" opts) "multicolumn mode: show a row average column" ,flagNone ["row-total","T"] (\opts -> setboolopt "row-total" opts) "multicolumn mode: show a row total column" ,flagNone ["no-total","N"] (\opts -> setboolopt "no-total" opts) "don't show the final total row" ] ++ outputflags ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } where aliases = ["bal"] -- | The balance command, prints a balance report. balance :: CliOpts -> Journal -> IO () balance opts@CliOpts{reportopts_=ropts} j = do d <- getCurrentDay case lineFormatFromOpts ropts of Left err -> error' $ unlines [err] Right _ -> do let format = outputFormatFromOpts opts interval = intervalFromOpts ropts baltype = balancetype_ ropts case interval of NoInterval -> do let report = balanceReport ropts (queryFromOpts d ropts) j render = case format of "csv" -> \ropts r -> (++ "\n") $ printCSV $ balanceReportAsCsv ropts r _ -> balanceReportAsText writeOutput opts $ render ropts report _ -> do let report = multiBalanceReport ropts (queryFromOpts d ropts) j render = case format of "csv" -> \ropts r -> (++ "\n") $ printCSV $ multiBalanceReportAsCsv ropts r _ -> case baltype of PeriodBalance -> periodBalanceReportAsText CumulativeBalance -> cumulativeBalanceReportAsText HistoricalBalance -> historicalBalanceReportAsText writeOutput opts $ render ropts report -- single-column balance reports -- | Render a single-column balance report as CSV. balanceReportAsCsv :: ReportOpts -> BalanceReport -> CSV balanceReportAsCsv opts (items, total) = ["account","balance"] : [[a, showMixedAmountWithoutPrice b] | ((a, _, _), b) <- items] ++ if no_total_ opts then [] else [["total", showMixedAmountOneLineWithoutPrice total]] -- | Render a single-column balance report as plain text. balanceReportAsText :: ReportOpts -> BalanceReport -> String balanceReportAsText opts ((items, total)) = unlines $ concat lines ++ t where lines = case lineFormatFromOpts opts of Right f -> map (balanceReportItemAsText opts f) items Left err -> [[err]] t = if no_total_ opts then [] else ["--------------------" -- TODO: This must use the format somehow ,padleft 20 $ showMixedAmountWithoutPrice total ] tests_balanceReportAsText = [ "balanceReportAsText" ~: do -- "unicode in balance layout" ~: do j <- readJournal' "2009/01/01 * медвежья шкура\n расходы:покупки 100\n актив:наличные\n" let opts = defreportopts balanceReportAsText opts (balanceReport opts (queryFromOpts (parsedate "2008/11/26") opts) j) `is` unlines [" -100 актив:наличные" ," 100 расходы:покупки" ,"--------------------" ," 0" ] ] {- This implementation turned out to be a bit convoluted but implements the following algorithm for formatting: - If there is a single amount, print it with the account name directly: - Otherwise, only print the account name on the last line. a USD 1 ; Account 'a' has a single amount EUR -1 b USD -1 ; Account 'b' has two amounts. The account name is printed on the last line. -} -- | Render one balance report line item as plain text suitable for console output. balanceReportItemAsText :: ReportOpts -> [OutputFormat] -> BalanceReportItem -> [String] balanceReportItemAsText opts format ((_, accountName, depth), Mixed amounts) = -- 'amounts' could contain several quantities of the same commodity with different price. -- In order to combine them into single value (which is expected) we take the first price and -- use it for the whole mixed amount. This could be suboptimal. XXX let Mixed normAmounts = normaliseMixedAmountSquashPricesForDisplay (Mixed amounts) in case normAmounts of [] -> [] [a] -> [formatBalanceReportItem opts (Just accountName) depth a format] (as) -> multiline as where multiline :: [Amount] -> [String] multiline [] = [] multiline [a] = [formatBalanceReportItem opts (Just accountName) depth a format] multiline (a:as) = (formatBalanceReportItem opts Nothing depth a format) : multiline as formatBalanceReportItem :: ReportOpts -> Maybe AccountName -> Int -> Amount -> [OutputFormat] -> String formatBalanceReportItem _ _ _ _ [] = "" formatBalanceReportItem opts accountName depth amount (fmt:fmts) = s ++ (formatBalanceReportItem opts accountName depth amount fmts) where s = case fmt of FormatLiteral l -> l FormatField ljust min max field -> formatField opts accountName depth amount ljust min max field formatField :: ReportOpts -> Maybe AccountName -> Int -> Amount -> Bool -> Maybe Int -> Maybe Int -> HledgerFormatField -> String formatField opts accountName depth total ljust min max field = case field of AccountField -> formatValue ljust min max $ maybe "" (maybeAccountNameDrop opts) accountName DepthSpacerField -> case min of Just m -> formatValue ljust Nothing max $ replicate (depth * m) ' ' Nothing -> formatValue ljust Nothing max $ replicate depth ' ' TotalField -> formatValue ljust min max $ showAmountWithoutPrice total _ -> "" -- multi-column balance reports -- | Render a multi-column balance report as CSV. multiBalanceReportAsCsv :: ReportOpts -> MultiBalanceReport -> CSV multiBalanceReportAsCsv opts (MultiBalanceReport (colspans, items, (coltotals,tot,avg))) = ("account" : "short account" : "indent" : map showDateSpan colspans ++ (if row_total_ opts then ["total"] else []) ++ (if average_ opts then ["average"] else []) ) : [a : a' : show i : map showMixedAmountOneLineWithoutPrice (amts ++ (if row_total_ opts then [rowtot] else []) ++ (if average_ opts then [rowavg] else [])) | ((a,a',i), amts, rowtot, rowavg) <- items] ++ if no_total_ opts then [] else [["totals", "", ""] ++ map showMixedAmountOneLineWithoutPrice ( coltotals ++ (if row_total_ opts then [tot] else []) ++ (if average_ opts then [avg] else []) )] -- | Render a multi-column period balance report as plain text suitable for console output. periodBalanceReportAsText :: ReportOpts -> MultiBalanceReport -> String periodBalanceReportAsText opts r@(MultiBalanceReport (colspans, items, (coltotals,tot,avg))) = unlines $ ([printf "Balance changes in %s:" (showDateSpan $ multiBalanceReportSpan r)] ++) $ trimborder $ lines $ render id (" "++) showMixedAmountOneLineWithoutPrice $ addtotalrow $ Table (T.Group NoLine $ map (Header . padright acctswidth) accts) (T.Group NoLine $ map Header colheadings) (map rowvals items') where trimborder = ("":) . (++[""]) . drop 1 . init . map (drop 1 . init) colheadings = map showDateSpan colspans ++ (if row_total_ opts then [" Total"] else []) ++ (if average_ opts then ["Average"] else []) items' | empty_ opts = items | otherwise = items -- dbg1 "2" $ filter (any (not . isZeroMixedAmount) . snd) $ dbg1 "1" items accts = map renderacct items' renderacct ((a,a',i),_,_,_) | tree_ opts = replicate ((i-1)*2) ' ' ++ a' | otherwise = maybeAccountNameDrop opts a acctswidth = maximum $ map length $ accts rowvals (_,as,rowtot,rowavg) = as ++ (if row_total_ opts then [rowtot] else []) ++ (if average_ opts then [rowavg] else []) addtotalrow | no_total_ opts = id | otherwise = (+----+ (row "" $ coltotals ++ (if row_total_ opts then [tot] else []) ++ (if average_ opts then [avg] else []) )) -- | Render a multi-column cumulative balance report as plain text suitable for console output. cumulativeBalanceReportAsText :: ReportOpts -> MultiBalanceReport -> String cumulativeBalanceReportAsText opts r@(MultiBalanceReport (colspans, items, (coltotals,tot,avg))) = unlines $ ([printf "Ending balances (cumulative) in %s:" (showDateSpan $ multiBalanceReportSpan r)] ++) $ trimborder $ lines $ render id (" "++) showMixedAmountOneLineWithoutPrice $ addtotalrow $ Table (T.Group NoLine $ map (Header . padright acctswidth) accts) (T.Group NoLine $ map Header colheadings) (map rowvals items) where trimborder = ("":) . (++[""]) . drop 1 . init . map (drop 1 . init) colheadings = map (maybe "" (showDate . prevday) . spanEnd) colspans ++ (if row_total_ opts then [" Total"] else []) ++ (if average_ opts then ["Average"] else []) accts = map renderacct items renderacct ((a,a',i),_,_,_) | tree_ opts = replicate ((i-1)*2) ' ' ++ a' | otherwise = maybeAccountNameDrop opts a acctswidth = maximum $ map length $ accts rowvals (_,as,rowtot,rowavg) = as ++ (if row_total_ opts then [rowtot] else []) ++ (if average_ opts then [rowavg] else []) addtotalrow | no_total_ opts = id | otherwise = (+----+ (row "" $ coltotals ++ (if row_total_ opts then [tot] else []) ++ (if average_ opts then [avg] else []) )) -- | Render a multi-column historical balance report as plain text suitable for console output. historicalBalanceReportAsText :: ReportOpts -> MultiBalanceReport -> String historicalBalanceReportAsText opts r@(MultiBalanceReport (colspans, items, (coltotals,tot,avg))) = unlines $ ([printf "Ending balances (historical) in %s:" (showDateSpan $ multiBalanceReportSpan r)] ++) $ trimborder $ lines $ render id (" "++) showMixedAmountOneLineWithoutPrice $ addtotalrow $ Table (T.Group NoLine $ map (Header . padright acctswidth) accts) (T.Group NoLine $ map Header colheadings) (map rowvals items) where trimborder = ("":) . (++[""]) . drop 1 . init . map (drop 1 . init) colheadings = map (maybe "" (showDate . prevday) . spanEnd) colspans ++ (if row_total_ opts then [" Total"] else []) ++ (if average_ opts then ["Average"] else []) accts = map renderacct items renderacct ((a,a',i),_,_,_) | tree_ opts = replicate ((i-1)*2) ' ' ++ a' | otherwise = maybeAccountNameDrop opts a acctswidth = maximum $ map length $ accts rowvals (_,as,rowtot,rowavg) = as ++ (if row_total_ opts then [rowtot] else []) ++ (if average_ opts then [rowavg] else []) addtotalrow | no_total_ opts = id | otherwise = (+----+ (row "" $ coltotals ++ (if row_total_ opts then [tot] else []) ++ (if average_ opts then [avg] else []) )) -- | Figure out the overall date span of a multicolumn balance report. multiBalanceReportSpan :: MultiBalanceReport -> DateSpan multiBalanceReportSpan (MultiBalanceReport ([], _, _)) = DateSpan Nothing Nothing multiBalanceReportSpan (MultiBalanceReport (colspans, _, _)) = DateSpan (spanStart $ head colspans) (spanEnd $ last colspans) tests_Hledger_Cli_Balance = TestList tests_balanceReportAsText
kmels/hledger
hledger/Hledger/Cli/Balance.hs
gpl-3.0
21,273
0
26
5,547
3,712
1,982
1,730
226
8
{-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE OverloadedStrings #-} module Game.Osu.OszLoader.OsuParser.DifficultySpec (spec) where import Data.Attoparsec.Text import Data.Text hiding (map, filter, null) import Game.Osu.OszLoader.OsuParser.Difficulty import Game.Osu.OszLoader.Types import Test.Hspec import Test.QuickCheck difficultySample ∷ Text difficultySample = Data.Text.concat [ "[Difficulty]\n" , "HPDrainRate:8\n" , "CircleSize:4\n" , "OverallDifficulty:8\n" , "ApproachRate:8\n" , "SliderMultiplier:1.8\n" , "SliderTickRate:0.5\n" ] numProp ∷ (Show a, Eq a) ⇒ Parser a → Text → Positive a → Expectation numProp p t (Positive x) = parseOnly p tx `shouldBe` Right x where tx = t `append` pack (show x) spec ∷ Spec spec = do describe "Difficulty section" $ do it "can parse the provided sample" $ do parseOnly difficultySection difficultySample `shouldBe` Right (Difficulty { _hpDrainRate = 8 , _circleSize = 4 , _overallDifficulty = 8 , _approachRate = Just 8 , _sliderMultiplier = 1.8 , _sliderTickRate = 0.5}) context "subparsers" $ do it "hpDrainRateP" . property $ numProp hpDrainRateP "HPDrainRate:" it "circleSizeP" . property $ numProp circleSizeP "CircleSize:" it "overallDifficultyP" . property $ numProp overallDifficultyP "OverallDifficulty:" it "approachRateP" . property $ numProp approachRateP "ApproachRate:" it "sliderMultiplierP" . property $ numProp sliderMultiplierP "SliderMultiplier:" it "sliderTickRateP" . property $ numProp sliderTickRateP "SliderTickRate:"
Fuuzetsu/osz-loader
test/Game/Osu/OszLoader/OsuParser/DifficultySpec.hs
gpl-3.0
1,745
0
18
430
408
216
192
42
1
module Parser (Line(..), LineType(..), Expr(..), NumType(..), getOp, parseFile, regNum, symbolString) where import Register (lookupRegisterName) import Util (readBin) import Control.Arrow ((>>>)) import Control.Applicative ((<$>), (<*>)) import Data.Bits ((.|.), (.&.), shiftL, shiftR, xor) import Data.Char(isSpace) import Data.Maybe (fromJust, maybeToList) import Numeric (readHex) import Text.Parsec.Error (Message(SysUnExpect, UnExpect, Expect, Message), errorPos, errorMessages) import Text.ParserCombinators.Parsec (Parser, ParseError, sourceLine) import Text.ParserCombinators.Parsec.Char (alphaNum, char, digit, hexDigit, letter, newline, oneOf, satisfy, string) import Text.ParserCombinators.Parsec.Combinator (between, many1, option, optionMaybe, sepBy) import Text.ParserCombinators.Parsec.Prim ((<|>), getPosition, many, parse, try) ------ types ------------------------------------------------- data Line = Line LineType Int deriving (Show, Eq) data LineType = Label String | CmdLine String [Expr] deriving (Show, Eq) data Expr = Str String | Symbol String | Register Integer | Num NumType Integer | OffsetBase Expr Integer | Negate Expr | Comp Expr | BinOp Expr Expr BinOpType deriving (Show, Eq) data NumType = Hex | Dec | Bin deriving (Show, Eq) data BinOpType = Add | Sub | Mul | Div | And | Or | Xor | Lsh | Rsh deriving (Show, Eq) ------ public ------------------------------------------------- parseFile f str = parse asmsrc f (removeComments str) >>= return . concat ------ utility ------------------------------------------------- removeComments :: String -> String removeComments = lines >>> map stripComment >>> unlines -- comments begin with a #, carry on to end of line stripComment :: String -> String stripComment = takeWhile (/='#') regNum (Register n) = Just n regNum _ = Nothing symbolString (Symbol s) = return s symbolString _ = fail $ "not a symbol" getOp :: BinOpType -> (Integer -> Integer -> Integer) getOp Add = (+) getOp Sub = (-) getOp Mul = (*) getOp Div = div getOp Lsh = \x y -> x `shiftL` (fromIntegral y) getOp Rsh = \x y -> x `shiftR` (fromIntegral y) getOp And = (.&.) getOp Or = (.|.) getOp Xor = xor ------ parsers ------------------------------------------------- asmsrc = many asmline asmline = do whitespaces l <- optionMaybe (try label) whitespaces cmd <- optionMaybe (try cmdline) whitespaces newline return $ (maybeToList l) ++ (maybeToList cmd) whitespace = satisfy (\c -> isSpace c && c /= '\n') whitespaces = many whitespace label :: Parser Line label = do first <- letter <|> char '_' restLabel <- many (alphaNum <|> char '_') char ':' lineNum <- sourceLine <$> getPosition return $ Line (Label (first:restLabel)) lineNum cmdline :: Parser Line cmdline = do cmd <- symbol whitespaces args <- argList lineNum <- sourceLine <$> getPosition return $ Line (CmdLine (fromJust $ symbolString cmd) args) lineNum argList :: Parser [Expr] argList = arg `sepBy` (char ',' >> whitespaces) arg = do a <- try offsetBase <|> register <|> stringLiteral <|> expr whitespaces return a expr = l7 l0 = paren atom = num <|> symbol <|> l0 l1 = negcomp <|> atom l2 = try muldivExpr <|> l1 l3 = try addsubExpr <|> l2 l4 = try shiftExpr <|> l3 l5 = try andExpr <|> l4 l6 = try xorExpr <|> l5 l7 = try orExpr <|> l6 paren = between (char '(' >> whitespaces) (whitespaces >> char ')') expr negcomp = do op <- char '-' <|> char '~' e <- atom case op of '-' -> return $ Negate e '~' -> return $ Comp e muldivExpr = do e1 <- l1 whitespaces op <- char '*' <|> char '/' whitespaces e2 <- l2 case op of '*' -> return $ BinOp e1 e2 Mul '/' -> return $ BinOp e1 e2 Div addsubExpr = do e1 <- l2 whitespaces op <- char '+' <|> char '-' whitespaces e2 <- l3 case op of '+' -> return $ BinOp e1 e2 Add '-' -> return $ BinOp e1 e2 Sub shiftExpr = do e1 <- l3 whitespaces op <- string "<<" <|> string ">>" whitespaces e2 <- l4 case op of "<<" -> return $ BinOp e1 e2 Lsh ">>" -> return $ BinOp e1 e2 Rsh andExpr = do e1 <- l4 whitespaces char '&' whitespaces e2 <- l5 return $ BinOp e1 e2 And xorExpr = do e1 <- l5 whitespaces char '^' whitespaces e2 <- l6 return $ BinOp e1 e2 Xor orExpr = do e1 <- l6 whitespaces char '|' whitespaces e2 <- l7 return $ BinOp e1 e2 Or offsetBase :: Parser Expr offsetBase = do n <- option (Num Dec 0) (try expr) char '(' whitespaces r <- register whitespaces char ')' return $ OffsetBase n (fromJust (regNum r)) num :: Parser Expr num = (try hex) <|> bin <|> dec hex = do char '0' char 'X' <|> char 'x' ds <- many1 hexDigit return $ Num Hex (fst $ head (readHex ds)) dec = do ds <- many1 digit return $ Num Dec (read ds) bin = do char '%' ds <- many1 (oneOf "01") return $ Num Bin (fst $ head (readBin ds)) symbol :: Parser Expr symbol = do first <- letter <|> char '_' <|> char '.' rest <- many (alphaNum <|> char '_') return $ Symbol (first:rest) -- taken from Text.Parsec.Token, with modifications stringLiteral :: Parser Expr stringLiteral = do s <- between (char '"') (char '"') (many stringChar) return $ Str s stringChar = stringLetter <|> stringEscape stringLetter = satisfy (\c -> (c /= '"') && (c /= '\\') && (c > '\026')) stringEscape = char '\\' >> char '"' register = char '$' >> many1 alphaNum >>= lookupRegisterName >>= return . Register -- parses is a utility that tests only if a String can be parsed by a parser parses p str = case parse p "" str of Left _ -> False Right _ -> True prettyParseError :: String -> ParseError -> String prettyParseError msg err = let pos = errorPos err msgs = filter (not . null) $ map errorMsgString (errorMessages err) in (unlines msgs) ++ msg errorMsgString :: Message -> String errorMsgString (SysUnExpect "") = "" errorMsgString (SysUnExpect s) = "unexpected " ++ s errorMsgString (UnExpect "") = "" errorMsgString (UnExpect s) = "unexpected " ++ s errorMsgString (Expect "") = "" errorMsgString (Expect s) = "expected " ++ s errorMsgString (Message s) = s
adamsmasher/EMA
Parser.hs
gpl-3.0
7,254
0
13
2,400
2,384
1,218
1,166
187
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.DirectConnect.DescribeVirtualInterfaces -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Displays all virtual interfaces for an AWS account. Virtual interfaces -- deleted fewer than 15 minutes before DescribeVirtualInterfaces is called are -- also returned. If a connection ID is included then only virtual interfaces -- associated with this connection will be returned. If a virtual interface ID -- is included then only a single virtual interface will be returned. -- -- A virtual interface (VLAN) transmits the traffic between the AWS Direct -- Connect location and the customer. -- -- If a connection ID is provided, only virtual interfaces provisioned on the -- specified connection will be returned. If a virtual interface ID is provided, -- only this particular virtual interface will be returned. -- -- <http://docs.aws.amazon.com/directconnect/latest/APIReference/API_DescribeVirtualInterfaces.html> module Network.AWS.DirectConnect.DescribeVirtualInterfaces ( -- * Request DescribeVirtualInterfaces -- ** Request constructor , describeVirtualInterfaces -- ** Request lenses , dviConnectionId , dviVirtualInterfaceId -- * Response , DescribeVirtualInterfacesResponse -- ** Response constructor , describeVirtualInterfacesResponse -- ** Response lenses , dvirVirtualInterfaces ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.DirectConnect.Types import qualified GHC.Exts data DescribeVirtualInterfaces = DescribeVirtualInterfaces { _dviConnectionId :: Maybe Text , _dviVirtualInterfaceId :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'DescribeVirtualInterfaces' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dviConnectionId' @::@ 'Maybe' 'Text' -- -- * 'dviVirtualInterfaceId' @::@ 'Maybe' 'Text' -- describeVirtualInterfaces :: DescribeVirtualInterfaces describeVirtualInterfaces = DescribeVirtualInterfaces { _dviConnectionId = Nothing , _dviVirtualInterfaceId = Nothing } dviConnectionId :: Lens' DescribeVirtualInterfaces (Maybe Text) dviConnectionId = lens _dviConnectionId (\s a -> s { _dviConnectionId = a }) dviVirtualInterfaceId :: Lens' DescribeVirtualInterfaces (Maybe Text) dviVirtualInterfaceId = lens _dviVirtualInterfaceId (\s a -> s { _dviVirtualInterfaceId = a }) newtype DescribeVirtualInterfacesResponse = DescribeVirtualInterfacesResponse { _dvirVirtualInterfaces :: List "virtualInterfaces" VirtualInterface } deriving (Eq, Read, Show, Monoid, Semigroup) instance GHC.Exts.IsList DescribeVirtualInterfacesResponse where type Item DescribeVirtualInterfacesResponse = VirtualInterface fromList = DescribeVirtualInterfacesResponse . GHC.Exts.fromList toList = GHC.Exts.toList . _dvirVirtualInterfaces -- | 'DescribeVirtualInterfacesResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dvirVirtualInterfaces' @::@ ['VirtualInterface'] -- describeVirtualInterfacesResponse :: DescribeVirtualInterfacesResponse describeVirtualInterfacesResponse = DescribeVirtualInterfacesResponse { _dvirVirtualInterfaces = mempty } -- | A list of virtual interfaces. dvirVirtualInterfaces :: Lens' DescribeVirtualInterfacesResponse [VirtualInterface] dvirVirtualInterfaces = lens _dvirVirtualInterfaces (\s a -> s { _dvirVirtualInterfaces = a }) . _List instance ToPath DescribeVirtualInterfaces where toPath = const "/" instance ToQuery DescribeVirtualInterfaces where toQuery = const mempty instance ToHeaders DescribeVirtualInterfaces instance ToJSON DescribeVirtualInterfaces where toJSON DescribeVirtualInterfaces{..} = object [ "connectionId" .= _dviConnectionId , "virtualInterfaceId" .= _dviVirtualInterfaceId ] instance AWSRequest DescribeVirtualInterfaces where type Sv DescribeVirtualInterfaces = DirectConnect type Rs DescribeVirtualInterfaces = DescribeVirtualInterfacesResponse request = post "DescribeVirtualInterfaces" response = jsonResponse instance FromJSON DescribeVirtualInterfacesResponse where parseJSON = withObject "DescribeVirtualInterfacesResponse" $ \o -> DescribeVirtualInterfacesResponse <$> o .:? "virtualInterfaces" .!= mempty
dysinger/amazonka
amazonka-directconnect/gen/Network/AWS/DirectConnect/DescribeVirtualInterfaces.hs
mpl-2.0
5,291
0
10
957
573
346
227
67
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.TagManager.Accounts.Containers.Versions.SetLatest -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Sets the latest version used for synchronization of workspaces when -- detecting conflicts and errors. -- -- /See:/ <https://developers.google.com/tag-manager Tag Manager API Reference> for @tagmanager.accounts.containers.versions.set_latest@. module Network.Google.Resource.TagManager.Accounts.Containers.Versions.SetLatest ( -- * REST Resource AccountsContainersVersionsSetLatestResource -- * Creating a Request , accountsContainersVersionsSetLatest , AccountsContainersVersionsSetLatest -- * Request Lenses , acvslXgafv , acvslUploadProtocol , acvslPath , acvslAccessToken , acvslUploadType , acvslCallback ) where import Network.Google.Prelude import Network.Google.TagManager.Types -- | A resource alias for @tagmanager.accounts.containers.versions.set_latest@ method which the -- 'AccountsContainersVersionsSetLatest' request conforms to. type AccountsContainersVersionsSetLatestResource = "tagmanager" :> "v2" :> CaptureMode "path" "set_latest" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Post '[JSON] ContainerVersion -- | Sets the latest version used for synchronization of workspaces when -- detecting conflicts and errors. -- -- /See:/ 'accountsContainersVersionsSetLatest' smart constructor. data AccountsContainersVersionsSetLatest = AccountsContainersVersionsSetLatest' { _acvslXgafv :: !(Maybe Xgafv) , _acvslUploadProtocol :: !(Maybe Text) , _acvslPath :: !Text , _acvslAccessToken :: !(Maybe Text) , _acvslUploadType :: !(Maybe Text) , _acvslCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AccountsContainersVersionsSetLatest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acvslXgafv' -- -- * 'acvslUploadProtocol' -- -- * 'acvslPath' -- -- * 'acvslAccessToken' -- -- * 'acvslUploadType' -- -- * 'acvslCallback' accountsContainersVersionsSetLatest :: Text -- ^ 'acvslPath' -> AccountsContainersVersionsSetLatest accountsContainersVersionsSetLatest pAcvslPath_ = AccountsContainersVersionsSetLatest' { _acvslXgafv = Nothing , _acvslUploadProtocol = Nothing , _acvslPath = pAcvslPath_ , _acvslAccessToken = Nothing , _acvslUploadType = Nothing , _acvslCallback = Nothing } -- | V1 error format. acvslXgafv :: Lens' AccountsContainersVersionsSetLatest (Maybe Xgafv) acvslXgafv = lens _acvslXgafv (\ s a -> s{_acvslXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). acvslUploadProtocol :: Lens' AccountsContainersVersionsSetLatest (Maybe Text) acvslUploadProtocol = lens _acvslUploadProtocol (\ s a -> s{_acvslUploadProtocol = a}) -- | GTM ContainerVersion\'s API relative path. Example: -- accounts\/{account_id}\/containers\/{container_id}\/versions\/{version_id} acvslPath :: Lens' AccountsContainersVersionsSetLatest Text acvslPath = lens _acvslPath (\ s a -> s{_acvslPath = a}) -- | OAuth access token. acvslAccessToken :: Lens' AccountsContainersVersionsSetLatest (Maybe Text) acvslAccessToken = lens _acvslAccessToken (\ s a -> s{_acvslAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). acvslUploadType :: Lens' AccountsContainersVersionsSetLatest (Maybe Text) acvslUploadType = lens _acvslUploadType (\ s a -> s{_acvslUploadType = a}) -- | JSONP acvslCallback :: Lens' AccountsContainersVersionsSetLatest (Maybe Text) acvslCallback = lens _acvslCallback (\ s a -> s{_acvslCallback = a}) instance GoogleRequest AccountsContainersVersionsSetLatest where type Rs AccountsContainersVersionsSetLatest = ContainerVersion type Scopes AccountsContainersVersionsSetLatest = '["https://www.googleapis.com/auth/tagmanager.edit.containers"] requestClient AccountsContainersVersionsSetLatest'{..} = go _acvslPath _acvslXgafv _acvslUploadProtocol _acvslAccessToken _acvslUploadType _acvslCallback (Just AltJSON) tagManagerService where go = buildClient (Proxy :: Proxy AccountsContainersVersionsSetLatestResource) mempty
brendanhay/gogol
gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Versions/SetLatest.hs
mpl-2.0
5,456
0
16
1,169
705
413
292
109
1
{- ORMOLU_DISABLE -} -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca) -- Copyright 2014 2015 2016, Julia Longtin (julial@turinglace.com) -- Copyright 2015 2016, Mike MacHenry (mike.machenry@gmail.com) -- Released under the GNU AGPLV3+, see LICENSE module Graphics.Implicit.ObjectUtil.GetBox3 (getBox3) where import Prelude(uncurry, pure, Bool(False), Either (Left, Right), (==), max, (/), (-), (+), fmap, unzip, ($), (<$>), (.), minimum, maximum, min, (>), (*), (<), abs, either, const, otherwise, take, fst, snd) import Graphics.Implicit.Definitions ( Fastℕ, fromFastℕ, ExtrudeMScale(C2, C1), SymbolicObj3(Shared3, Cube, Sphere, Cylinder, Rotate3, Extrude, ExtrudeOnEdgeOf, ExtrudeM, RotateExtrude), Box3, ℝ, fromFastℕtoℝ, toScaleFn ) import Graphics.Implicit.ObjectUtil.GetBox2 (getBox2, getBox2R) import qualified Linear.Quaternion as Q import Graphics.Implicit.ObjectUtil.GetBoxShared (corners, pointsBox, getBoxShared) import Linear (V2(V2), V3(V3)) -- FIXME: many variables are being ignored here. no rounding for intersect, or difference.. etc. -- Get a Box3 around the given object. getBox3 :: SymbolicObj3 -> Box3 -- Primitives getBox3 (Shared3 obj) = getBoxShared obj getBox3 (Cube size) = (pure 0, size) getBox3 (Sphere r) = (pure (-r), pure r) getBox3 (Cylinder h r1 r2) = (V3 (-r) (-r) 0, V3 r r h ) where r = max r1 r2 -- (Rounded) CSG -- Simple transforms getBox3 (Rotate3 q symbObj) = let box = getBox3 symbObj in pointsBox $ Q.rotate q <$> corners box -- Misc -- 2D Based getBox3 (Extrude symbObj h) = (V3 x1 y1 0, V3 x2 y2 h) where (V2 x1 y1, V2 x2 y2) = getBox2 symbObj getBox3 (ExtrudeOnEdgeOf symbObj1 symbObj2) = let (V2 ax1 ay1, V2 ax2 ay2) = getBox2 symbObj1 (V2 bx1 by1, V2 bx2 by2) = getBox2 symbObj2 in (V3 (bx1+ax1) (by1+ax1) ay1, V3 (bx2+ax2) (by2+ax2) ay2) -- FIXME: magic numbers: 0.2 and 11. -- FIXME: this may use an approximation, based on sampling functions. generate a warning if the approximation part of this function is used. -- FIXME: re-implement the expression system, so this can recieve a function, and determine class (constant, linear)... and implement better forms of this function. getBox3 (ExtrudeM twist scale translate symbObj height) = let (V2 x1 y1, V2 x2 y2) = getBox2 symbObj (dx, dy) = (x2 - x1, y2 - y1) samples :: Fastℕ samples = 11 range :: [Fastℕ] range = [0, 1 .. (samples-1)] (xrange, yrange) = ( fmap ((\s -> x1+s*dx/fromFastℕtoℝ (samples-1)) . fromFastℕtoℝ) range, fmap ((\s -> y1+s*dy/fromFastℕtoℝ (samples-1)) . fromFastℕtoℝ) range) hfuzz :: ℝ hfuzz = 0.2 h = case height of Left hval -> hval Right hfun -> hmax + hfuzz*(hmax-hmin) where hs = [hfun $ V2 x y | x <- xrange, y <- yrange] (hmin, hmax) = (minimum hs, maximum hs) hrange = fmap ((/ fromFastℕtoℝ (samples-1)) . (h*) . fromFastℕtoℝ) range (twistXmin, twistYmin, twistXmax, twistYmax) = let both f (a, b) = (f a, f b) (V2 scalex' scaley') = case scale of C1 s -> V2 s s C2 s -> s s -> pack $ both maximum . unzip $ fmap unpack $ fmap abs . toScaleFn s <$> hrange smin s v = min v (s * v) smax s v = max v (s * v) -- FIXME: assumes minimums are negative, and maximums are positive. scaleEach (V2 d1 d2, V2 d3 d4) = (scalex' * d1, scaley' * d2, scalex' * d3, scaley' * d4) in case twist of Left twval -> if twval == 0 then (smin scalex' x1, smin scaley' y1, smax scalex' x2, smax scaley' y2) else scaleEach $ getBox2R symbObj twval Right _ -> scaleEach $ getBox2R symbObj 360 -- we can't range functions yet, so assume a full circle. (tminx, tmaxx, tminy, tmaxy) = let tvalsx :: (ℝ -> V2 ℝ) -> [ℝ] tvalsx tfun = fmap (fst . unpack . tfun) hrange tvalsy :: (ℝ -> V2 ℝ) -> [ℝ] tvalsy tfun = fmap (snd . unpack . tfun) hrange in case translate of Left (V2 tvalx tvaly) -> (tvalx, tvalx, tvaly, tvaly) Right tfun -> ( minimum $ tvalsx tfun , maximum $ tvalsx tfun , minimum $ tvalsy tfun , maximum $ tvalsy tfun ) in (V3 (twistXmin + tminx) (twistYmin + tminy) 0, V3 (twistXmax + tmaxx) (twistYmax + tmaxy) h) -- Note: Assumes x2 is always greater than x1. -- FIXME: Insert the above assumption as an assertion in the type system? getBox3 (RotateExtrude _ (Left (V2 xshift yshift)) _ symbObj) = let (V2 _ y1, V2 x2 y2) = getBox2 symbObj r = max x2 (x2 + xshift) in (V3 (-r) (-r) $ min y1 (y1 + yshift), V3 r r $ max y2 (y2 + yshift)) -- FIXME: magic numbers: 0.1, 1.1, and 11. -- FIXME: this may use an approximation, based on sampling functions. generate a warning if the approximation part of this function is used. -- FIXME: re-implement the expression system, so this can recieve a function, and determine class (constant, linear)... and implement better forms of this function. getBox3 (RotateExtrude rot (Right f) rotate symbObj) = let samples :: Fastℕ samples = 11 xfuzz :: ℝ xfuzz = 1.1 yfuzz :: ℝ yfuzz=0.1 range :: [Fastℕ] range = [0, 1 .. (samples-1)] step = rot/fromFastℕtoℝ (samples-1) (V2 x1 y1, V2 x2 y2) = getBox2 symbObj (xrange, yrange) = unzip $ fmap unpack $ take (fromFastℕ samples) $ fmap (f . (step*) . fromFastℕtoℝ) range xmax = maximum xrange ymax = maximum yrange ymin = minimum yrange xmax' | xmax > 0 = xmax * xfuzz | xmax < - x1 = 0 | otherwise = xmax ymax' = ymax + yfuzz * (ymax - ymin) ymin' = ymin - yfuzz * (ymax - ymin) (r, _, _) = if either (==0) (const False) rotate then let s = maximum $ fmap abs [x2, y1, y2] in (s + xmax', s + ymin', y2 + ymax') else (x2 + xmax', y1 + ymin', y2 + ymax') in (V3 (-r) (-r) $ y1 + ymin', V3 r r $ y2 + ymax') unpack :: V2 a -> (a, a) unpack (V2 a b) = (a, b) pack :: (a, a) -> V2 a pack = uncurry V2
colah/ImplicitCAD
Graphics/Implicit/ObjectUtil/GetBox3.hs
agpl-3.0
6,583
5
22
1,999
2,279
1,239
1,040
111
8
-- using || && and or -- || && 与 and or的定义是不一样的,要注意 usingandorinfixr = True || (False && True) usingandor = or [False, and [True, False]] ----------------------------------------------- firstOrEmpty :: [[Char]] -> [Char] firstOrEmpty lst = if not (null lst) then head lst else "empty" (+++) :: [a] -> [a] -> [a] lst1 +++ lst2 = if null lst1 then lst2 else head lst1 : tail lst1 +++ lst2 list1 ++++ list2 = case list1 of [] -> list2 x:xs -> x: xs ++++ list2 --addv3 :: [a] -> [a] -> [a] addv3 [] list2 = list2 addv3 (x:xs) list2 = x:(addv3 xs list2) reverse2 :: [a] -> [a] reverse2 lst = if null lst then lst else reverse2 (tail lst) +++ (head lst:[]) ----------------------------------------------- yxmaxmin :: Ord a => [a] -> (a, a) yxmaxmin list = let h = head list in if null (tail list) then (h, h) else if h > h_max then (h, h_min) else if h < h_min then (h_max, h) else (h_max, h_min) where t = yxmaxmin (tail list) h_max = fst t h_min = snd t maxmin :: Ord a => [a] -> (a, a) maxmin list = let h = head list in if null (tail list) then (h, h) else ( if h > t_max then h else t_max, if h < t_min then h else t_min ) where t = maxmin (tail list); t_max = fst t; t_min = snd t --yxversion fibonacci 0 = 0 fibonacci 1 = 1 fibonacci n = fibonacci ( n - 1) + (fibonacci ( n - 2)) --pattern marching and guard mfibonacci 0 = 0 mfibonacci 1 = 1 mfibonacci n | otherwise = let (f1, f2) = ( mfibonacci (n-1), mfibonacci (n-2)) in (f1 + f2) --just guard mmfib n | n == 0 = 0 | n == 1 = 1 | otherwise = mmfib(n-2) + (mmfib(n-1))
wangyixiang/beginninghaskell
chapter2/src/Chapter2/SimpleFunctions.hs
unlicense
1,605
20
13
370
792
420
372
39
4
{-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE JavaScriptFFI #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {- Copyright 2020 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 Blocks.CodeGen (workspaceToCode) where import Blockly.Block import Blockly.Workspace hiding (workspaceToCode) import Blocks.Parser import qualified Blocks.Printer as PR import Control.Monad import Control.Monad.State.Lazy (get, put) import qualified Control.Monad.State.Lazy as S import Data.JSString.Text import qualified Data.Map as M import Data.Monoid ((<>)) import qualified Data.Text as T import qualified Prelude as P import Prelude hiding ((<>), show) pack = textToJSString unpack = textFromJSString show :: Show a => a -> T.Text show = T.pack . P.show errc :: T.Text -> Block -> SaveErr Expr errc msg block = SE Comment $ Just $ Error msg block type Code = T.Text class Pretty a where pretty :: a -> PR.Printer -- instance Pretty Product where -- pretty (Product s tps) = s <> " " <> T.concat (map pretty tps) instance Pretty Type where pretty (Type s) = PR.write_ s pretty (Sum typeName []) = PR.write_ $ "data " <> typeName -- Empty data declaration pretty (Sum typeName (tp : tps)) = do PR.write_ $ "data " <> typeName <> " =" c <- PR.getCol PR.write_ " " pretty tp mapM_ (\t -> PR.setCol (c -1) >> PR.writeLine "" >> PR.write "|" >> pretty t) tps pretty (Product s tps) = do PR.write_ s when (length tps > 0) $ do PR.write_ "(" PR.intercalation "," tps pretty PR.write_ ")" PR.write_ " " pretty (ListType t) = do PR.write_ "[" pretty t PR.write_ "]" instance Pretty Expr where pretty (LiteralS s) = PR.write_ s pretty (LiteralN d) = PR.write_ $ if d == fromInteger (truncate d) then show $ truncate d else show d pretty (LocalVar name) = PR.write_ $ name pretty (CallFunc name vars_) = do PR.write_ name case vars_ of [] -> return () _ -> do PR.write_ "(" PR.intercalation "," vars_ pretty PR.write_ ")" pretty (CallConstr name vars_) = do PR.write name case vars_ of [] -> return () _ -> do PR.write_ "(" PR.intercalation "," vars_ pretty PR.write_ ")" pretty (CallFuncInfix name left right) = do shouldParenth left PR.makeSpace PR.write name -- SPACES between? PR.makeSpace shouldParenth right where getPrec (CallFuncInfix name _ _) = infixP name getPrec _ = 9 cur = infixP name shouldParenth expr = let prec = getPrec expr in if prec < cur then parenthesize expr else pretty expr parenthesize expr = do PR.write_ "(" pretty expr PR.write_ ")" pretty (FuncDef name vars expr) = do let varCode = if not $ null vars then "(" <> T.intercalate "," vars <> ")" else "" PR.write_ name if null vars then return () else PR.write_ varCode PR.write_ " = " pretty expr pretty (If cond th el) = do PR.push PR.write "if" pretty cond PR.reset PR.write "then" pretty th PR.reset PR.write "else" pretty el PR.pop pretty (Case expr rows) = do col <- PR.getCol PR.write "case" PR.makeSpace pretty expr PR.makeSpace PR.write "of" mapM_ ( \(con, vars, expr) -> do PR.setCol (col + 4) PR.writeLine "" PR.write con PR.makeSpace when (length vars > 0) $ do PR.write_ "(" PR.write_ $ T.intercalate "," vars PR.write_ ")" PR.write "->" pretty expr ) rows PR.pop pretty (UserType tp) = pretty tp pretty (Tuple exprs) = do PR.write_ "(" PR.intercalation "," exprs pretty PR.write_ ")" pretty (ListCreate exprs) = do PR.write_ "[" PR.intercalation "," exprs pretty PR.write_ "]" pretty (ListSpec left right) = do PR.write_ "[" pretty left PR.write_ " .. " pretty right PR.write_ "]" pretty (ListSpecStep left next right) = do PR.write_ "[" pretty left PR.write_ ", " pretty next PR.write_ " .. " pretty right PR.write_ "]" pretty (ListComp act vars_ guards) = do PR.write_ "[" pretty act PR.write_ " | " PR.intercalation ", " vars_ (\(var, expr) -> PR.write_ var >> PR.write_ " <- " >> pretty expr) when (length guards > 0) $ do PR.write_ "," PR.makeSpace PR.intercalation ", " guards pretty PR.write_ "]" pretty Comment = PR.write_ "" infixP "-" = 6 infixP "+" = 6 infixP "*" = 7 infixP "/" = 7 infixP "^" = 8 infixP "&" = 8 infixP "<>" = 8 infixP _ = 9 workspaceToCode :: Workspace -> IO (Code, [Error]) workspaceToCode workspace = do topBlocks <- getTopBlocksTrue workspace >>= return . filter (not . isDisabled) let exprs = map blockToCode topBlocks let errors = map (\(SE code (Just e)) -> e) $ filter (\c -> case c of SE code Nothing -> False; _ -> True) exprs let code = T.intercalate "\n\n" $ map (\(SE expr _) -> PR.run $ pretty expr) exprs return (code, errors) where blockToCode :: Block -> SaveErr Expr blockToCode block = do let blockType = getBlockType block case M.lookup blockType blockCodeMap of Just func -> let (SE code err) = func block in SE code err Nothing -> errc "No such block in CodeGen" block
google/codeworld
funblocks-client/src/Blocks/CodeGen.hs
apache-2.0
6,050
0
18
1,690
2,054
966
1,088
187
3
module Reverse where bang :: String -> String bang = (++ "!") why :: String -> Char why = (!! 4) awesome = dropWhile (/= 'a') thirdLetter = (!! 2) letterIndex :: Int -> Char letterIndex = ("Curry is awesome!" !!) -- You’re expected -- only to slice and dice this particular string with take and drop. -- Curry is awesome -- awesome is Curry rvrs :: String -> String rvrs curryIsAwesome = (drop 9 curryIsAwesome) ++ " " ++ (take 2 . drop 6) curryIsAwesome ++ " " ++ (take 5 curryIsAwesome) main :: IO () main = print $ rvrs "Curry is awesome" -- concat [[1, 2, 3], [4, 5 , 6]] -- [1,2,3,4,5,6] -- *Main> ++ [1, 2, 3] [4, 5, 6] -- <interactive>:4:1: error: parse error on input ‘++’ -- *Main> (++) [1, 2, 3] [4, 5, 6] -- [1,2,3,4,5,6] -- *Main> (++) "hello" " world" -- "hello world" -- *Main> ["hello" ++ " world"] -- ["hello world"] -- *Main> 4 !! "hello" -- <interactive>:9:6: error: -- • Couldn't match expected type ‘Int’ with actual type ‘[Char]’ -- • In the second argument of ‘(!!)’, namely ‘"hello"’ -- In the expression: 4 !! "hello" -- In an equation for ‘it’: it = 4 !! "hello" -- *Main> (!!) "hello" 4 -- 'o' -- *Main> "hello" !! 4 -- 'o' -- *Main> take "4 lovely" -- <interactive>:12:6: error: -- • Couldn't match expected type ‘Int’ with actual type ‘[Char]’ -- • In the first argument of ‘take’, namely ‘"4 lovely"’ -- In the expression: take "4 lovely" -- In an equation for ‘it’: it = take "4 lovely" -- *Main> take 3 "awesome" -- "awe" -- concat [[1 * 6], [2 * 6], [3 * 6]] -- [6,12,18] -- *Main> "rain" ++ drop 2 "elbow" -- "rainbow" -- *Main> 10 * head [1, 2, 3] -- 10 -- *Main> (take 3 "Julie") ++ (tail "yes") -- "Jules" -- *Main> concat [tail [1, 2, 3], tail [4, 5, 6], tail [7, 8, 9]] -- [2,3,5,6,8,9]
prt2121/haskell-practice
hb-chap03/src/Main.hs
apache-2.0
1,842
0
11
400
208
134
74
18
1
{-# LANGUAGE OverloadedStrings #-} module Persistence.Book where import Data.Text (Text, unpack) import qualified Database.PostgreSQL.Simple as PG import Model.Book getBookByShortUID :: Text -> PG.Connection -> IO (Maybe Book) getBookByShortUID shortuid conn = do results <- PG.query conn "SELECT \ \ id, \ \ chapter, \ \ contents, \ \ shortuid \ \FROM \"Book\" WHERE \ \ shortuid = ?" (PG.Only shortuid) let r = results :: [Book] if null r then return Nothing else return $ Just $ head r
DataStewardshipPortal/ds-wizard
DSServer/app/Persistence/Book.hs
apache-2.0
659
0
11
249
135
72
63
14
2
module Network.Eureka.Version.Cabal ( fromVersions , fromVersion , fromString , showVersion , versionInRangeP ) where import Data.Maybe (listToMaybe) import qualified Data.Version as DV (Version, Version (Version), parseVersion, showVersion) import Network.Eureka.Version.Types (Version, Predicate) import Text.ParserCombinators.ReadP (readP_to_S) versionInRangeP :: [Int] -> [Int] -> Predicate versionInRangeP lower upper ver = ver >= fromVersions lower && ver < fromVersions upper fromVersions :: [Int] -> Version fromVersions vs = fromVersion $ DV.Version vs [] fromVersion :: DV.Version -> Version fromVersion = id fromString :: String -> Maybe Version fromString = fmap fst . listToMaybe . filter (null . snd) . readP_to_S DV.parseVersion showVersion :: Version -> String showVersion = DV.showVersion
SumAll/haskell-eureka-semver
src/Network/Eureka/Version/Cabal.hs
apache-2.0
847
0
9
145
248
141
107
27
1
-- Copyright 2020 Google LLC -- -- 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 FfiUser2 (quadruple) where import FfiUser1 (triple) quadruple x = x + triple x
google/hrepl
hrepl/tests/FfiUser2.hs
apache-2.0
677
0
6
117
45
31
14
3
1
module Bintree where -- Binary tree data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq) instance Show a => Show (Tree a) where show (Leaf a) = show a show (Branch x y) = "<" ++ show x ++ " | " ++ show y ++ ">" -- instance Eq Data where func = treeFoldr :: (b -> a -> a) -> a -> Tree b -> a treeFoldr f acc EmptyTree = acc treeFoldr f acc (Node b left right) = treeFoldr f (f b (treeFoldr f acc right)) left instance (Eq t) => Eq (Tree t) where Empty == Empty = True Leaf a == Leaf b = a == b Node x y == Node a b = (x == a) && (y == b) _ == _ = False -- foldable btfoldr f z Empty = z btfoldr f z (Leaf x) = f x z btfoldr f z (Node x y) = btfoldr f (btfoldr f z y) x -- i can use foldr normally now -- data Maybe a = Nothing | Just a -- instance Foldable Maybe where -- foldr _ z Nothing = z -- foldr f z (Just x) = f x z -- instance Functor Maybe where -- fmap _ Nothing = Nothing -- fmap f (Just x) = f x tmap _ Empty = Empty tmap f (Leaf x) = Leaf $ f x tmap f (Node x y) = Node (tmap f x) (tmap f y)
riccardotommasini/plp16
haskell/prepared/ESE20181120/Bintree.hs
apache-2.0
1,086
0
10
312
485
245
240
-1
-1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} module Test.Delorean.Local.Date where import Data.Text (Text, pack) import Delorean.Local import P import System.IO import Test.Delorean.Arbitrary () import Test.Delorean.ParserCheck import Test.QuickCheck import Text.Printf prop_roundTripYear :: Year -> Property prop_roundTripYear y = (yearFromInt . yearToInt) y === pure y prop_roundTripMonth :: Month -> Property prop_roundTripMonth m = (monthFromInt . monthToInt) m === pure m prop_roundTripWeekOfMonth :: WeekOfMonth -> Property prop_roundTripWeekOfMonth w = (weekOfMonthFromInt . weekOfMonthToInt) w === pure w prop_roundTripDayOfMonth :: DayOfMonth -> Property prop_roundTripDayOfMonth d = (dayOfMonthFromInt . dayOfMonthToInt) d === pure d prop_roundTripDayOfWeek :: DayOfWeek -> Property prop_roundTripDayOfWeek d = (dayOfWeekFromInt . dayOfWeekToInt) d === pure d prop_roundTripNextMonth :: Date -> Bool prop_roundTripNextMonth m = (prevMonth . nextMonth) m == m && (nextMonth . prevMonth) m == m prop_roundTripNextDay :: Date -> Bool prop_roundTripNextDay d = (nextDay . prevDay) d == d && (prevDay . nextDay) d == d prop_toDayOfMonth :: Bool prop_toDayOfMonth = let match (y, m, w, d, e) = fromMaybe False $ do y' <- yearFromInt y m' <- monthFromInt m e' <- dayOfMonthFromInt e pure $ toDayOfMonth y' m' w d == e' in all match [ (2015, 2, FirstWeek, Thursday, 5) , (2015, 2, SecondWeek, Wednesday, 11) , (2015, 1, SecondWeek, Wednesday, 14) ] prop_roundTripGregorianDay :: Date -> Property prop_roundTripGregorianDay d = (gregorianDayToDate . dateToGregorianDay) d === d prop_symmetricDayOfWeek :: DayOfWeek -> Property prop_symmetricDayOfWeek = symmetric dayOfWeekParser renderDayOfWeek prop_symmetricWeekOfMonth :: WeekOfMonth -> Property prop_symmetricWeekOfMonth = symmetric weekOfMonthParser renderWeekOfMonth prop_symmetricDayOfMonth :: DayOfMonth -> Property prop_symmetricDayOfMonth = symmetric dayOfMonthParser renderDayOfMonth prop_symmetricDate :: Date -> Property prop_symmetricDate = symmetric dateParser renderDate prop_parseDayOfWeek :: DayOfWeek -> Property prop_parseDayOfWeek = parserAlias dayOfWeekParser renderDayOfWeek parseDayOfWeek prop_parseWeekOfMonth :: WeekOfMonth -> Property prop_parseWeekOfMonth = parserAlias weekOfMonthParser renderWeekOfMonth parseWeekOfMonth prop_parseDayOfMonth :: DayOfMonth -> Property prop_parseDayOfMonth = parserAlias dayOfMonthParser renderDayOfMonth parseDayOfMonth prop_parseDate :: Date -> Property prop_parseDate = parserAlias dateParser renderDate parseDate prop_symmetricYear :: Year -> Property prop_symmetricYear = symmetric yearParser (p 4 . yearToInt) prop_symmetricMonth :: Month -> Property prop_symmetricMonth = symmetric monthParser (p 2 . monthToInt) prop_symmetricDay :: DayOfMonth -> Property prop_symmetricDay = symmetric dayOfMonthParser' (p 2 . dayOfMonthToInt) prop_symmetricPlusDaysMinusDays n date = conjoin [ minusDays n (plusDays n date) === date , plusDays n (minusDays n date) === date] prop_nextDayPlusDays1 date = nextDay date === plusDays 1 date prop_prevDayMinusDays1 date = prevDay date === minusDays 1 date p :: Int -> Int -> Text p n a = pack $ printf ("%0" <> show n <> "d") a return [] tests :: IO Bool tests = $quickCheckAll
ambiata/delorean
test/Test/Delorean/Local/Date.hs
bsd-3-clause
3,566
0
14
652
925
483
442
97
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS -Wall #-} -- | -- Module : Network.Mail.Client.Gmail -- License : BSD3 -- Maintainer : Enzo Haussecker -- Stability : Experimental -- Portability : Unknown -- -- A dead simple SMTP Client for sending Gmail. module Network.Mail.Client.Gmail ( -- ** Sending sendGmail -- ** Exceptions , GmailException(..) ) where import Control.Monad (forever, forM) import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Trans.Resource (ResourceT, runResourceT) import Control.Exception (Exception, bracket, throw) import Data.Attoparsec.ByteString.Char8 as P import Data.ByteString.Char8 as B (ByteString, pack) import Data.ByteString.Base64.Lazy (encode) import Data.ByteString.Lazy.Char8 as L (ByteString, hPutStrLn, readFile) import Data.ByteString.Lazy.Search (replace) import Data.Conduit import Data.Conduit.Attoparsec (sinkParser) import Data.Default (def) import Data.Monoid ((<>)) import Data.Text as S (Text, pack) import Data.Text.Lazy as L (Text, fromChunks) import Data.Text.Lazy.Encoding (encodeUtf8) import Data.Typeable (Typeable) import Network (PortID(PortNumber), connectTo) import Network.Mail.Mime hiding (renderMail) import Network.TLS import Network.TLS.Extra (ciphersuite_all) import Prelude hiding (any, readFile) import System.FilePath (takeExtension, takeFileName) import System.IO hiding (readFile) import System.Timeout (timeout) data GmailException = ParseError String | Timeout deriving (Show, Typeable) instance Exception GmailException -- | -- Send an email from your Gmail account using the -- simple message transfer protocol with transport -- layer security. If you have 2-step verification -- enabled on your account, then you will need to -- retrieve an application specific password before -- using this function. Below is an example using -- ghci, where Alice sends an Excel spreadsheet to -- Bob. -- -- > >>> :set -XOverloadedStrings -- > >>> :module Network.Mail.Mime Network.Mail.Client.Gmail -- > >>> sendGmail "alice" "password" (Address (Just "Alice") "alice@gmail.com") [Address (Just "Bob") "bob@example.com"] [] [] "Excel Spreadsheet" "Hi Bob,\n\nThe Excel spreadsheet is attached.\n\nRegards,\n\nAlice" ["Spreadsheet.xls"] 10000000 -- sendGmail :: L.Text -- ^ username -> L.Text -- ^ password -> Address -- ^ from -> [Address] -- ^ to -> [Address] -- ^ cc -> [Address] -- ^ bcc -> S.Text -- ^ subject -> L.Text -- ^ body -> [FilePath] -- ^ attachments -> Int -- ^ timeout (in microseconds) -> IO () sendGmail user pass from to cc bcc subject body attachments micros = do let handle = connectTo "smtp.gmail.com" $ PortNumber 587 bracket handle hClose $ \ hdl -> do recvSMTP hdl micros "220" sendSMTP hdl "EHLO" recvSMTP hdl micros "250" sendSMTP hdl "STARTTLS" recvSMTP hdl micros "220" let context = contextNew hdl params bracket context cClose $ \ ctx -> do handshake ctx sendSMTPS ctx "EHLO" recvSMTPS ctx micros "250" sendSMTPS ctx "AUTH LOGIN" recvSMTPS ctx micros "334" sendSMTPS ctx username recvSMTPS ctx micros "334" sendSMTPS ctx password recvSMTPS ctx micros "235" sendSMTPS ctx sender recvSMTPS ctx micros "250" sendSMTPS ctx recipient recvSMTPS ctx micros "250" sendSMTPS ctx "DATA" recvSMTPS ctx micros "354" sendSMTPS ctx =<< mail recvSMTPS ctx micros "250" sendSMTPS ctx "QUIT" recvSMTPS ctx micros "221" where username = encode $ encodeUtf8 user password = encode $ encodeUtf8 pass sender = "MAIL FROM: " <> angleBracket [from] recipient = "RCPT TO: " <> angleBracket (to ++ cc ++ bcc) mail = renderMail from to cc bcc subject body attachments -- | -- Consume the SMTP packet stream. sink :: B.ByteString -> Sink (Maybe B.ByteString) (ResourceT IO) () sink code = (awaitForever $ maybe (throw Timeout) yield) =$= sinkParser (parser code) -- | -- Parse the SMTP packet stream. parser :: B.ByteString -> P.Parser () parser code = do reply <- P.take 3 if code /= reply then throw . ParseError $ "Expected SMTP reply code " ++ show code ++ ", but recieved SMTP reply code " ++ show reply ++ "." else anyChar >>= \ case ' ' -> return () '-' -> manyTill anyChar endOfLine >> parser code _ -> throw $ ParseError "Unexpected character." -- | -- Define the TLS client parameters. params :: ClientParams params = (defaultParamsClient "smtp.gmail.com" "587") { clientSupported = def { supportedCiphers = ciphersuite_all } , clientShared = def { sharedValidationCache = noValidate } } where noValidate = ValidationCache (\_ _ _ -> return ValidationCachePass) -- This is not secure! (\_ _ _ -> return ()) -- | -- Terminate the TLS connection. cClose :: Context -> IO () cClose ctx = bye ctx >> contextClose ctx -- | -- Display the first email address in the -- given list using angle bracket formatting. angleBracket :: [Address] -> L.ByteString angleBracket = \ case [] -> ""; (Address _ email:_) -> "<" <> encodeUtf8 (fromChunks [email]) <> ">" -- | -- Send an unencrypted. sendSMTP :: Handle -> L.ByteString -> IO () sendSMTP = L.hPutStrLn -- | -- Send an encrypted message. sendSMTPS :: Context -> L.ByteString -> IO () sendSMTPS ctx msg = sendData ctx $ msg <> "\r\n" -- | -- Receive an unencrypted. recvSMTP :: Handle -> Int -> B.ByteString -> IO () recvSMTP hdl micros code = runResourceT $ source $$ sink code where source = forever $ liftIO chunk >>= yield chunk = timeout micros $ append <$> hGetLine hdl append = flip (<>) "\n" . B.pack -- | -- Receive an encrypted message. recvSMTPS :: Context -> Int -> B.ByteString -> IO () recvSMTPS ctx micros code = runResourceT $ source $$ sink code where source = forever $ liftIO chunk >>= yield chunk = timeout micros $ recvData ctx -- | -- Render an email using the RFC 2822 message format. renderMail :: Address -- ^ from -> [Address] -- ^ to -> [Address] -- ^ cc -> [Address] -- ^ bcc -> S.Text -- ^ subject -> L.Text -- ^ body -> [FilePath] -- ^ attachments -> IO L.ByteString renderMail from to cc bcc subject body attach = do parts <- forM attach $ \ path -> do content <- readFile path let mime = getMime $ takeExtension path file = Just . S.pack $ takeFileName path return $! [Part mime Base64 file [] content] let plain = [Part "text/plain; charset=utf-8" QuotedPrintableText Nothing [] $ encodeUtf8 body] mail <- renderMail' . Mail from to cc bcc headers $ plain : parts return $! replace "\n." ("\n.." :: L.ByteString) mail <> "\r\n.\r\n" where headers = [("Subject", subject)] -- | -- Get the mime type for the given file extension. getMime :: String -> S.Text getMime = \ case ".3dm" -> "x-world/x-3dmf" ".3dmf" -> "x-world/x-3dmf" ".a" -> "application/octet-stream" ".aab" -> "application/x-authorware-bin" ".aam" -> "application/x-authorware-map" ".aas" -> "application/x-authorware-seg" ".abc" -> "text/vnd.abc" ".acgi" -> "text/html" ".afl" -> "video/animaflex" ".ai" -> "application/postscript" ".aif" -> "audio/aiff" ".aifc" -> "audio/aiff" ".aiff" -> "audio/aiff" ".aim" -> "application/x-aim" ".aip" -> "text/x-audiosoft-intra" ".ani" -> "application/x-navi-animation" ".aos" -> "application/x-nokia-9000-communicator-add-on-software" ".aps" -> "application/mime" ".arc" -> "application/octet-stream" ".arj" -> "application/arj" ".art" -> "image/x-jg" ".asf" -> "video/x-ms-asf" ".asm" -> "text/x-asm" ".asp" -> "text/asp" ".asx" -> "application/x-mplayer2" ".au" -> "audio/basic" ".avi" -> "application/x-troff-msvideo" ".avs" -> "video/avs-video" ".bcpio" -> "application/x-bcpio" ".bin" -> "application/mac-binary" ".bm" -> "image/bmp" ".bmp" -> "image/bmp" ".boo" -> "application/book" ".book" -> "application/book" ".boz" -> "application/x-bzip2" ".bsh" -> "application/x-bsh" ".bz" -> "application/x-bzip" ".bz2" -> "application/x-bzip2" ".c" -> "text/plain" ".c++" -> "text/plain" ".cat" -> "application/vnd.ms-pki.seccat" ".cc" -> "text/plain" ".ccad" -> "application/clariscad" ".cco" -> "application/x-cocoa" ".cdf" -> "application/cdf" ".cer" -> "application/pkix-cert" ".cha" -> "application/x-chat" ".chat" -> "application/x-chat" ".class" -> "application/java" ".com" -> "application/octet-stream" ".conf" -> "text/plain" ".cpio" -> "application/x-cpio" ".cpp" -> "text/x-c" ".cpt" -> "application/mac-compactpro" ".crl" -> "application/pkcs-crl" ".crt" -> "application/pkix-cert" ".csh" -> "application/x-csh" ".css" -> "application/x-pointplus" ".cxx" -> "text/plain" ".dcr" -> "application/x-director" ".deepv" -> "application/x-deepv" ".def" -> "text/plain" ".der" -> "application/x-x509-ca-cert" ".dif" -> "video/x-dv" ".dir" -> "application/x-director" ".dl" -> "video/dl" ".doc" -> "application/msword" ".dot" -> "application/msword" ".dp" -> "application/commonground" ".drw" -> "application/drafting" ".dump" -> "application/octet-stream" ".dv" -> "video/x-dv" ".dvi" -> "application/x-dvi" ".dwf" -> "drawing/x-dwf (old)" ".dwg" -> "application/acad" ".dxf" -> "application/dxf" ".dxr" -> "application/x-director" ".el" -> "text/x-script.elisp" ".elc" -> "application/x-bytecode.elisp (compiled elisp)" ".env" -> "application/x-envoy" ".eps" -> "application/postscript" ".es" -> "application/x-esrehber" ".etx" -> "text/x-setext" ".evy" -> "application/envoy" ".exe" -> "application/octet-stream" ".f" -> "text/plain" ".f77" -> "text/x-fortran" ".f90" -> "text/plain" ".fdf" -> "application/vnd.fdf" ".fif" -> "application/fractals" ".fli" -> "video/fli" ".flo" -> "image/florian" ".flx" -> "text/vnd.fmi.flexstor" ".fmf" -> "video/x-atomic3d-feature" ".for" -> "text/plain" ".fpx" -> "image/vnd.fpx" ".frl" -> "application/freeloader" ".funk" -> "audio/make" ".g" -> "text/plain" ".g3" -> "image/g3fax" ".gif" -> "image/gif" ".gl" -> "video/gl" ".gsd" -> "audio/x-gsm" ".gsm" -> "audio/x-gsm" ".gsp" -> "application/x-gsp" ".gss" -> "application/x-gss" ".gtar" -> "application/x-gtar" ".gz" -> "application/x-compressed" ".gzip" -> "application/x-gzip" ".h" -> "text/plain" ".hdf" -> "application/x-hdf" ".help" -> "application/x-helpfile" ".hgl" -> "application/vnd.hp-hpgl" ".hh" -> "text/plain" ".hlb" -> "text/x-script" ".hlp" -> "application/hlp" ".hpg" -> "application/vnd.hp-hpgl" ".hpgl" -> "application/vnd.hp-hpgl" ".hqx" -> "application/binhex" ".hs" -> "text/x-haskell" ".hta" -> "application/hta" ".htc" -> "text/x-component" ".htm" -> "text/html" ".html" -> "text/html" ".htmls" -> "text/html" ".htt" -> "text/webviewhtml" ".htx" -> "text/html" ".ice" -> "x-conference/x-cooltalk" ".ico" -> "image/x-icon" ".idc" -> "text/plain" ".ief" -> "image/ief" ".iefs" -> "image/ief" ".iges" -> "application/iges" ".igs" -> "application/iges" ".ima" -> "application/x-ima" ".imap" -> "application/x-httpd-imap" ".inf" -> "application/inf" ".ins" -> "application/x-internett-signup" ".ip" -> "application/x-ip2" ".isu" -> "video/x-isvideo" ".it" -> "audio/it" ".iv" -> "application/x-inventor" ".ivr" -> "i-world/i-vrml" ".ivy" -> "application/x-livescreen" ".jam" -> "audio/x-jam" ".jav" -> "text/plain" ".java" -> "text/plain" ".jcm" -> "application/x-java-commerce" ".jfif" -> "image/jpeg" ".jfif-tbnl" -> "image/jpeg" ".jpe" -> "image/jpeg" ".jpeg" -> "image/jpeg" ".jpg" -> "image/jpeg" ".jps" -> "image/x-jps" ".js" -> "application/x-javascript" ".jut" -> "image/jutvision" ".kar" -> "audio/midi" ".ksh" -> "application/x-ksh" ".la" -> "audio/nspaudio" ".lam" -> "audio/x-liveaudio" ".latex" -> "application/x-latex" ".lha" -> "application/lha" ".lhx" -> "application/octet-stream" ".list" -> "text/plain" ".lma" -> "audio/nspaudio" ".log" -> "text/plain" ".lsp" -> "application/x-lisp" ".lst" -> "text/plain" ".lsx" -> "text/x-la-asf" ".ltx" -> "application/x-latex" ".lzh" -> "application/octet-stream" ".lzx" -> "application/lzx" ".m" -> "text/plain" ".m1v" -> "video/mpeg" ".m2a" -> "audio/mpeg" ".m2v" -> "video/mpeg" ".m3u" -> "audio/x-mpequrl" ".man" -> "application/x-troff-man" ".map" -> "application/x-navimap" ".mar" -> "text/plain" ".mbd" -> "application/mbedlet" ".mc$" -> "application/x-magic-cap-package-1.0" ".mcd" -> "application/mcad" ".mcf" -> "image/vasa" ".mcp" -> "application/netmc" ".me" -> "application/x-troff-me" ".mht" -> "message/rfc822" ".mhtml" -> "message/rfc822" ".mid" -> "application/x-midi" ".midi" -> "application/x-midi" ".mif" -> "application/x-frame" ".mime" -> "message/rfc822" ".mjf" -> "audio/x-vnd.audioexplosion.mjuicemediafile" ".mjpg" -> "video/x-motion-jpeg" ".mm" -> "application/base64" ".mme" -> "application/base64" ".mod" -> "audio/mod" ".moov" -> "video/quicktime" ".mov" -> "video/quicktime" ".movie" -> "video/x-sgi-movie" ".mp2" -> "audio/mpeg" ".mp3" -> "audio/mpeg3" ".mpa" -> "audio/mpeg" ".mpc" -> "application/x-project" ".mpe" -> "video/mpeg" ".mpeg" -> "video/mpeg" ".mpg" -> "audio/mpeg" ".mpga" -> "audio/mpeg" ".mpp" -> "application/vnd.ms-project" ".mpt" -> "application/x-project" ".mpv" -> "application/x-project" ".mpx" -> "application/x-project" ".mrc" -> "application/marc" ".ms" -> "application/x-troff-ms" ".mv" -> "video/x-sgi-movie" ".my" -> "audio/make" ".mzz" -> "application/x-vnd.audioexplosion.mzz" ".nap" -> "image/naplps" ".naplps" -> "image/naplps" ".nc" -> "application/x-netcdf" ".ncm" -> "application/vnd.nokia.configuration-message" ".nif" -> "image/x-niff" ".niff" -> "image/x-niff" ".nix" -> "application/x-mix-transfer" ".nsc" -> "application/x-conference" ".nvd" -> "application/x-navidoc" ".o" -> "application/octet-stream" ".oda" -> "application/oda" ".omc" -> "application/x-omc" ".omcd" -> "application/x-omcdatamaker" ".omcr" -> "application/x-omcregerator" ".p" -> "text/x-pascal" ".p10" -> "application/pkcs10" ".p12" -> "application/pkcs-12" ".p7a" -> "application/x-pkcs7-signature" ".p7c" -> "application/pkcs7-mime" ".p7m" -> "application/pkcs7-mime" ".p7r" -> "application/x-pkcs7-certreqresp" ".p7s" -> "application/pkcs7-signature" ".part" -> "application/pro_eng" ".pas" -> "text/pascal" ".pbm" -> "image/x-portable-bitmap" ".pcl" -> "application/vnd.hp-pcl" ".pct" -> "image/x-pict" ".pcx" -> "image/x-pcx" ".pdb" -> "chemical/x-pdb" ".pdf" -> "application/pdf" ".pfunk" -> "audio/make" ".pgm" -> "image/x-portable-graymap" ".pic" -> "image/pict" ".pict" -> "image/pict" ".pkg" -> "application/x-newton-compatible-pkg" ".pko" -> "application/vnd.ms-pki.pko" ".pl" -> "text/plain" ".plx" -> "application/x-pixclscript" ".pm" -> "image/x-xpixmap" ".pm4" -> "application/x-pagemaker" ".pm5" -> "application/x-pagemaker" ".png" -> "image/png" ".pnm" -> "application/x-portable-anymap" ".pot" -> "application/mspowerpoint" ".pov" -> "model/x-pov" ".ppa" -> "application/vnd.ms-powerpoint" ".ppm" -> "image/x-portable-pixmap" ".pps" -> "application/mspowerpoint" ".ppt" -> "application/mspowerpoint" ".ppz" -> "application/mspowerpoint" ".pre" -> "application/x-freelance" ".prt" -> "application/pro_eng" ".ps" -> "application/postscript" ".psd" -> "application/octet-stream" ".pvu" -> "paleovu/x-pv" ".pwz" -> "application/vnd.ms-powerpoint" ".py" -> "text/x-script.phyton" ".pyc" -> "applicaiton/x-bytecode.python" ".qcp" -> "audio/vnd.qcelp" ".qd3" -> "x-world/x-3dmf" ".qd3d" -> "x-world/x-3dmf" ".qif" -> "image/x-quicktime" ".qt" -> "video/quicktime" ".qtc" -> "video/x-qtc" ".qti" -> "image/x-quicktime" ".qtif" -> "image/x-quicktime" ".ra" -> "audio/x-pn-realaudio" ".ram" -> "audio/x-pn-realaudio" ".ras" -> "application/x-cmu-raster" ".rast" -> "image/cmu-raster" ".rexx" -> "text/x-script.rexx" ".rf" -> "image/vnd.rn-realflash" ".rgb" -> "image/x-rgb" ".rm" -> "application/vnd.rn-realmedia" ".rmi" -> "audio/mid" ".rmm" -> "audio/x-pn-realaudio" ".rmp" -> "audio/x-pn-realaudio" ".rng" -> "application/ringing-tones" ".rnx" -> "application/vnd.rn-realplayer" ".roff" -> "application/x-troff" ".rp" -> "image/vnd.rn-realpix" ".rpm" -> "audio/x-pn-realaudio-plugin" ".rt" -> "text/richtext" ".rtf" -> "application/rtf" ".rtx" -> "application/rtf" ".rv" -> "video/vnd.rn-realvideo" ".s" -> "text/x-asm" ".s3m" -> "audio/s3m" ".saveme" -> "application/octet-stream" ".sbk" -> "application/x-tbook" ".scm" -> "application/x-lotusscreencam" ".sdml" -> "text/plain" ".sdp" -> "application/sdp" ".sdr" -> "application/sounder" ".sea" -> "application/sea" ".set" -> "application/set" ".sgm" -> "text/sgml" ".sgml" -> "text/sgml" ".sh" -> "application/x-bsh" ".shar" -> "application/x-bsh" ".shtml" -> "text/html" ".sid" -> "audio/x-psid" ".sit" -> "application/x-sit" ".skd" -> "application/x-koan" ".skm" -> "application/x-koan" ".skp" -> "application/x-koan" ".skt" -> "application/x-koan" ".sl" -> "application/x-seelogo" ".smi" -> "application/smil" ".smil" -> "application/smil" ".snd" -> "audio/basic" ".sol" -> "application/solids" ".spc" -> "application/x-pkcs7-certificates" ".spl" -> "application/futuresplash" ".spr" -> "application/x-sprite" ".sprite" -> "application/x-sprite" ".src" -> "application/x-wais-source" ".ssi" -> "text/x-server-parsed-html" ".ssm" -> "application/streamingmedia" ".sst" -> "application/vnd.ms-pki.certstore" ".step" -> "application/step" ".stl" -> "application/sla" ".stp" -> "application/step" ".sv4cpio" -> "application/x-sv4cpio" ".sv4crc" -> "application/x-sv4crc" ".svf" -> "image/vnd.dwg" ".svr" -> "application/x-world" ".swf" -> "application/x-shockwave-flash" ".t" -> "application/x-troff" ".talk" -> "text/x-speech" ".tar" -> "application/x-tar" ".tbk" -> "application/toolbook" ".tcl" -> "application/x-tcl" ".tcsh" -> "text/x-script.tcsh" ".tex" -> "application/x-tex" ".texi" -> "application/x-texinfo" ".texinfo" -> "application/x-texinfo" ".text" -> "application/plain" ".tgz" -> "application/gnutar" ".tif" -> "image/tiff" ".tiff" -> "image/tiff" ".tr" -> "application/x-troff" ".tsi" -> "audio/tsp-audio" ".tsp" -> "application/dsptype" ".tsv" -> "text/tab-separated-values" ".turbot" -> "image/florian" ".txt" -> "text/plain" ".uil" -> "text/x-uil" ".uni" -> "text/uri-list" ".unis" -> "text/uri-list" ".unv" -> "application/i-deas" ".uri" -> "text/uri-list" ".uris" -> "text/uri-list" ".ustar" -> "application/x-ustar" ".uu" -> "application/octet-stream" ".uue" -> "text/x-uuencode" ".vcd" -> "application/x-cdlink" ".vcs" -> "text/x-vcalendar" ".vda" -> "application/vda" ".vdo" -> "video/vdo" ".vew" -> "application/groupwise" ".viv" -> "video/vivo" ".vivo" -> "video/vivo" ".vmd" -> "application/vocaltec-media-desc" ".vmf" -> "application/vocaltec-media-file" ".voc" -> "audio/voc" ".vos" -> "video/vosaic" ".vox" -> "audio/voxware" ".vqe" -> "audio/x-twinvq-plugin" ".vqf" -> "audio/x-twinvq" ".vql" -> "audio/x-twinvq-plugin" ".vrml" -> "application/x-vrml" ".vrt" -> "x-world/x-vrt" ".vsd" -> "application/x-visio" ".vst" -> "application/x-visio" ".vsw" -> "application/x-visio" ".w60" -> "application/wordperfect6.0" ".w61" -> "application/wordperfect6.1" ".w6w" -> "application/msword" ".wav" -> "audio/wav" ".wb1" -> "application/x-qpro" ".wbmp" -> "image/vnd.wap.wbmp" ".web" -> "application/vnd.xara" ".wiz" -> "application/msword" ".wk1" -> "application/x-123" ".wmf" -> "windows/metafile" ".wml" -> "text/vnd.wap.wml" ".wmlc" -> "application/vnd.wap.wmlc" ".wmls" -> "text/vnd.wap.wmlscript" ".wmlsc" -> "application/vnd.wap.wmlscriptc" ".word" -> "application/msword" ".wp" -> "application/wordperfect" ".wp5" -> "application/wordperfect" ".wp6" -> "application/wordperfect" ".wpd" -> "application/wordperfect" ".wq1" -> "application/x-lotus" ".wri" -> "application/mswrite" ".wrl" -> "application/x-world" ".wrz" -> "model/vrml" ".wsc" -> "text/scriplet" ".wsrc" -> "application/x-wais-source" ".wtk" -> "application/x-wintalk" ".xbm" -> "image/x-xbitmap" ".xdr" -> "video/x-amt-demorun" ".xgz" -> "xgl/drawing" ".xif" -> "image/vnd.xiff" ".xl" -> "application/excel" ".xla" -> "application/excel" ".xlb" -> "application/excel" ".xlc" -> "application/excel" ".xld" -> "application/excel" ".xlk" -> "application/excel" ".xll" -> "application/excel" ".xlm" -> "application/excel" ".xls" -> "application/excel" ".xlt" -> "application/excel" ".xlv" -> "application/excel" ".xlw" -> "application/excel" ".xm" -> "audio/xm" ".xml" -> "application/xml" ".xmz" -> "xgl/movie" ".xpix" -> "application/x-vnd.ls-xpix" ".xpm" -> "image/x-xpixmap" ".x-png" -> "image/png" ".xsr" -> "video/x-amt-showrun" ".xwd" -> "image/x-xwd" ".xyz" -> "chemical/x-pdb" ".z" -> "application/x-compress" ".zip" -> "application/x-compressed" ".zoo" -> "application/octet-stream" ".zsh" -> "text/x-script.zsh" _ -> "application/octet-stream"
brokendata/smtps-gmail
Network/Mail/Client/Gmail.hs
bsd-3-clause
24,808
0
17
6,920
4,511
2,321
2,190
589
449
{-# LANGUAGE OverloadedStrings #-} module CommonMark.Renderer.Html ( def , renderBlock , renderDoc , dummyDoc , HtmlOptions ) where import Data.Default import Data.Monoid ( (<>), mconcat) import Data.Sequence import Data.Foldable ( toList ) import Data.Text ( Text ) import Text.Blaze.Html5 ( Html ) import qualified Text.Blaze.Html5 as H import CommonMark.Types data HtmlOptions = HtmlOptions { blocksep :: Text , itemsep :: Text , endofline :: Text } deriving (Show) instance Default HtmlOptions where def = let nl = "\n" in HtmlOptions nl nl nl renderDoc :: HtmlOptions -> Doc -> Html renderDoc opts (Doc _ blocks) = renderBlocks opts blocks <> eol where eol = H.toHtml $ endofline opts renderBlocks :: HtmlOptions -> Blocks -> Html renderBlocks opts = mconcat . map (renderBlock opts) . toList renderBlock :: HtmlOptions -> Block -> Html renderBlock opts block = case block of Hrule -> H.hr Header n t | 1 <= n && n <= 6 -> headers !! (n - 1) $ H.toHtml t | otherwise -> error "illegal header level" -- header parsers should be implemented in such a way that only -- legal level values (1 to 6) find their way into the doc's AST CodeBlock info t -> H.pre . H.code . H.toHtml . (<> eol) $ t -- HtmlBlock t -> undefined -- Paragraph t -> undefined -- Blockquote blocks -> undefined -- List tight ltype items -> undefined _ -> error "invalid block" where headers = [H.h1, H.h2, H.h3, H.h4, H.h5, H.h6] bsep = blocksep opts isep = itemsep opts eol = endofline opts -- for testing purposes dummyDoc :: Doc dummyDoc = Doc def (fromList [Hrule])
Jubobs/CommonMark-WIP
src/CommonMark/Renderer/Html.hs
bsd-3-clause
1,796
0
13
523
488
268
220
42
4
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeOperators #-} module VCS.Apply where import Data.Type.Equality hiding (apply) import VCS.Multirec import Language.Clojure.Lang import Language.Common import Debug.Trace applyS :: IsRecEl r => (forall a . at a -> Usingl a -> Maybe (Usingl a)) -> (forall p1 p2 . al p1 p2 -> All Usingl p1 -> Maybe (All Usingl p2)) -> Spine at al r -> Usingl r -> Maybe (Usingl r) applyS appAt appAl Scp x = pure x applyS appAt appAl (Schg i j p) x = case view x of Tag c d -> do Refl <- testEquality c i inj j <$> appAl p d applyS appAt appAl (Scns i p) x = case view x of Tag c d -> do Refl <- testEquality c i inj i <$> sAll appAt p d where sAll :: (forall a . at a -> Usingl a -> Maybe (Usingl a)) -> All at p -> All Usingl p -> Maybe (All Usingl p) sAll appAt An An = pure An sAll appAt (at `Ac` ats) (a `Ac` as) = Ac <$> appAt at a <*> sAll appAt ats as applyAl :: (forall a . at a -> Usingl a -> Maybe (Usingl a)) -> Al at p1 p2 -> All Usingl p1 -> Maybe (All Usingl p2) applyAl appAt A0 An = pure An applyAl appAt (Amod p a) (Ac x xs) = Ac <$> appAt p x <*> applyAl appAt a xs applyAl appAt (Ains k a) xs = Ac <$> pure k <*> applyAl appAt a xs applyAl appAt (Adel k a) (Ac x xs) = do Refl <- testEquality x k applyAl appAt a xs applyAt :: (IsRecEl a => rec a -> Usingl a -> Maybe (Usingl a)) -> At rec a -> Usingl a -> Maybe (Usingl a) applyAt appRec (Ai r) x = appRec r x applyAt appRec (As c) x = if old == new then pure x else if old == x then pure new else trace "applyAt failing" Nothing where (old, new) = unContract c applyAtAlmuH :: At AlmuH a -> Usingl a -> Maybe (Usingl a) applyAtAlmuH = applyAt (unH applyAlmu) where unH f (AlmuH al) x = f al x ctxIns :: IsRecEl u => Ctx (AtmuPos u) l -> Usingl u -> Maybe (All Usingl l) ctxIns (Here (FixPos almu) xs) u = Ac <$> applyAlmu almu u <*> pure xs ctxIns (There x xs) u = Ac <$> pure x <*> ctxIns xs u ctxDel :: IsRecEl v => Ctx (AtmuNeg v) l -> All Usingl l -> Maybe (Usingl v) ctxDel (Here (FixNeg almu) _) (x `Ac` _) = applyAlmu almu x ctxDel (There _ xs) (_ `Ac` xss) = ctxDel xs xss applyAlmu :: (IsRecEl u, IsRecEl v) => Almu u v -> Usingl u -> Maybe (Usingl v) applyAlmu (Alspn s) x = applyS applyAtAlmuH (applyAl applyAtAlmuH) s x applyAlmu (Alins constr ctx) x = inj constr <$> ctxIns ctx x applyAlmu (Aldel constr ctx) x = case view x of (Tag c1 p1) -> do Refl <- testEquality constr c1 ctxDel ctx p1
nazrhom/vcs-clojure
src/VCS/Apply.hs
bsd-3-clause
2,716
0
14
741
1,302
633
669
64
3
{-# LANGUAGE CPP , DataKinds , GADTs , TypeOperators , PolyKinds , FlexibleContexts , ScopedTypeVariables , UndecidableInstances #-} -- TODO: all the instances here are orphans. To ensure that we don't -- have issues about orphan instances, we should give them all -- newtypes and only provide the instance for those newtypes! -- (and\/or: for the various op types, it's okay to move them to -- AST.hs to avoid orphanage. It's just the instances for 'Term' -- itself which are morally suspect outside of testing.) {-# OPTIONS_GHC -Wall -fwarn-tabs -fno-warn-orphans #-} ---------------------------------------------------------------- -- 2016.05.24 -- | -- Module : Language.Hakaru.Syntax.ABT.Eq -- Copyright : Copyright (c) 2016 the Hakaru team -- License : BSD3 -- Maintainer : wren@community.haskell.org -- Stability : experimental -- Portability : GHC-only -- -- Warning: The following module is for testing purposes only. Using -- the 'JmEq1' instance for 'Term' is inefficient and should not -- be done accidentally. To implement that (orphan) instance we -- also provide the following (orphan) instances: -- -- > SArgs : JmEq1 -- > Term : JmEq1, Eq1, Eq -- > TrivialABT : JmEq2, JmEq1, Eq2, Eq1, Eq -- -- TODO: because this is only for testing, everything else should -- move to the @Tests@ directory. ---------------------------------------------------------------- module Language.Hakaru.Syntax.AST.Eq where import Language.Hakaru.Types.DataKind import Language.Hakaru.Types.Sing import Language.Hakaru.Types.Coercion import Language.Hakaru.Types.HClasses import Language.Hakaru.Syntax.IClasses import Language.Hakaru.Syntax.ABT import Language.Hakaru.Syntax.AST import Language.Hakaru.Syntax.Datum import Language.Hakaru.Syntax.TypeOf import Language.Hakaru.Syntax.Reducer import Control.Monad.Reader import qualified Data.Foldable as F import qualified Data.List.NonEmpty as L import qualified Data.Sequence as S import qualified Data.Traversable as T #if __GLASGOW_HASKELL__ < 710 import Data.Functor ((<$>)) import Data.Traversable #endif import Data.Maybe -- import Data.Number.Nat import Unsafe.Coerce --------------------------------------------------------------------- -- | This function performs 'jmEq' on a @(:$)@ node of the AST. -- It's necessary to break it out like this since we can't just -- give a 'JmEq1' instance for 'SCon' due to polymorphism issues -- (e.g., we can't just say that 'Lam_' is John Major equal to -- 'Lam_', since they may be at different types). However, once the -- 'SArgs' associated with the 'SCon' is given, that resolves the -- polymorphism. jmEq_S :: (ABT Term abt, JmEq2 abt) => SCon args a -> SArgs abt args -> SCon args' a' -> SArgs abt args' -> Maybe (TypeEq a a', TypeEq args args') jmEq_S Lam_ es Lam_ es' = jmEq1 es es' >>= \Refl -> Just (Refl, Refl) jmEq_S App_ es App_ es' = jmEq1 es es' >>= \Refl -> Just (Refl, Refl) jmEq_S Let_ es Let_ es' = jmEq1 es es' >>= \Refl -> Just (Refl, Refl) jmEq_S (CoerceTo_ c) (es :* End) (CoerceTo_ c') (es' :* End) = do (Refl, Refl) <- jmEq2 es es' let t1 = coerceTo c (typeOf es) let t2 = coerceTo c' (typeOf es') Refl <- jmEq1 t1 t2 return (Refl, Refl) jmEq_S (UnsafeFrom_ c) (es :* End) (UnsafeFrom_ c') (es' :* End) = do (Refl, Refl) <- jmEq2 es es' let t1 = coerceFrom c (typeOf es) let t2 = coerceFrom c' (typeOf es') Refl <- jmEq1 t1 t2 return (Refl, Refl) jmEq_S (PrimOp_ op) es (PrimOp_ op') es' = do Refl <- jmEq1 es es' (Refl, Refl) <- jmEq2 op op' return (Refl, Refl) jmEq_S (ArrayOp_ op) es (ArrayOp_ op') es' = do Refl <- jmEq1 es es' (Refl, Refl) <- jmEq2 op op' return (Refl, Refl) jmEq_S (MeasureOp_ op) es (MeasureOp_ op') es' = do Refl <- jmEq1 es es' (Refl, Refl) <- jmEq2 op op' return (Refl, Refl) jmEq_S Dirac es Dirac es' = jmEq1 es es' >>= \Refl -> Just (Refl, Refl) jmEq_S MBind es MBind es' = jmEq1 es es' >>= \Refl -> Just (Refl, Refl) jmEq_S Integrate es Integrate es' = jmEq1 es es' >>= \Refl -> Just (Refl, Refl) jmEq_S (Summate h1 h2) es (Summate h1' h2') es' = do Refl <- jmEq1 (sing_HDiscrete h1) (sing_HDiscrete h1') Refl <- jmEq1 (sing_HSemiring h2) (sing_HSemiring h2') Refl <- jmEq1 es es' Just (Refl, Refl) jmEq_S (Product h1 h2) es (Product h1' h2') es' = do Refl <- jmEq1 (sing_HDiscrete h1) (sing_HDiscrete h1') Refl <- jmEq1 (sing_HSemiring h2) (sing_HSemiring h2') Refl <- jmEq1 es es' Just (Refl, Refl) jmEq_S (Product h1 h2) es (Product h1' h2') es' = do Refl <- jmEq1 (sing_HDiscrete h1) (sing_HDiscrete h1') Refl <- jmEq1 (sing_HSemiring h2) (sing_HSemiring h2') Refl <- jmEq1 es es' Just (Refl, Refl) jmEq_S Expect es Expect es' = jmEq1 es es' >>= \Refl -> Just (Refl, Refl) jmEq_S _ _ _ _ = Nothing -- TODO: Handle jmEq2 of pat and pat' jmEq_Branch :: (ABT Term abt, JmEq2 abt) => [(Branch a abt b, Branch a abt b')] -> Maybe (TypeEq b b') jmEq_Branch [] = Nothing jmEq_Branch [(Branch pat e, Branch pat' e')] = do (Refl, Refl) <- jmEq2 e e' return Refl jmEq_Branch ((Branch pat e, Branch pat' e'):es) = do (Refl, Refl) <- jmEq2 e e' jmEq_Branch es instance JmEq2 abt => JmEq1 (SArgs abt) where jmEq1 End End = Just Refl jmEq1 (x :* xs) (y :* ys) = jmEq2 x y >>= \(Refl, Refl) -> jmEq1 xs ys >>= \Refl -> Just Refl jmEq1 _ _ = Nothing instance (ABT Term abt, JmEq2 abt) => JmEq1 (Term abt) where jmEq1 (o :$ es) (o' :$ es') = do (Refl, Refl) <- jmEq_S o es o' es' return Refl jmEq1 (NaryOp_ o es) (NaryOp_ o' es') = do Refl <- jmEq1 o o' () <- all_jmEq2 es es' return Refl jmEq1 (Literal_ v) (Literal_ w) = jmEq1 v w jmEq1 (Empty_ a) (Empty_ b) = jmEq1 a b jmEq1 (Array_ i f) (Array_ j g) = do (Refl, Refl) <- jmEq2 i j (Refl, Refl) <- jmEq2 f g Just Refl -- Assumes nonempty literal arrays. The hope is that Empty_ covers that case. -- TODO handle empty literal arrays. jmEq1 (ArrayLiteral_ (e:es)) (ArrayLiteral_ (e':es')) = do (Refl, Refl) <- jmEq2 e e' () <- all_jmEq2 (S.fromList es) (S.fromList es') return Refl jmEq1 (Bucket a b r) (Bucket a' b' r') = do (Refl, Refl) <- jmEq2 a a' (Refl, Refl) <- jmEq2 b b' Refl <- jmEq1 r r' return Refl jmEq1 (Datum_ (Datum hint _ _)) (Datum_ (Datum hint' _ _)) -- BUG: We need to compare structurally rather than using the hint | hint == hint' = unsafeCoerce (Just Refl) | otherwise = Nothing jmEq1 (Case_ a bs) (Case_ a' bs') = do (Refl, Refl) <- jmEq2 a a' jmEq_Branch (zip bs bs') jmEq1 (Superpose_ pms) (Superpose_ pms') = do (Refl,Refl) L.:| _ <- T.sequence $ fmap jmEq_Tuple (L.zip pms pms') return Refl jmEq1 _ _ = Nothing all_jmEq2 :: (ABT Term abt, JmEq2 abt) => S.Seq (abt '[] a) -> S.Seq (abt '[] a) -> Maybe () all_jmEq2 xs ys = let eq x y = isJust (jmEq2 x y) in if F.and (S.zipWith eq xs ys) then Just () else Nothing jmEq_Tuple :: (ABT Term abt, JmEq2 abt) => ((abt '[] a , abt '[] b), (abt '[] a', abt '[] b')) -> Maybe (TypeEq a a', TypeEq b b') jmEq_Tuple ((a,b), (a',b')) = do a'' <- jmEq2 a a' >>= (\(Refl, Refl) -> Just Refl) b'' <- jmEq2 b b' >>= (\(Refl, Refl) -> Just Refl) return (a'', b'') -- TODO: a more general function of type: -- (JmEq2 abt) => Term abt a -> Term abt b -> Maybe (Sing a, TypeEq a b) -- This can then be used to define typeOf and instance JmEq2 Term instance (ABT Term abt, JmEq2 abt) => Eq1 (Term abt) where eq1 x y = isJust (jmEq1 x y) instance (ABT Term abt, JmEq2 abt) => Eq (Term abt a) where (==) = eq1 instance ( Show1 (Sing :: k -> *) , JmEq1 (Sing :: k -> *) , JmEq1 (syn (TrivialABT syn)) , Foldable21 syn ) => JmEq2 (TrivialABT (syn :: ([k] -> k -> *) -> k -> *)) where jmEq2 x y = case (viewABT x, viewABT y) of (Syn t1, Syn t2) -> jmEq1 t1 t2 >>= \Refl -> Just (Refl, Refl) (Var (Variable _ _ t1), Var (Variable _ _ t2)) -> jmEq1 t1 t2 >>= \Refl -> Just (Refl, Refl) (Bind (Variable _ _ x1) v1, Bind (Variable _ _ x2) v2) -> do Refl <- jmEq1 x1 x2 (Refl,Refl) <- jmEq2 (unviewABT v1) (unviewABT v2) return (Refl, Refl) _ -> Nothing instance ( Show1 (Sing :: k -> *) , JmEq1 (Sing :: k -> *) , JmEq1 (syn (TrivialABT syn)) , Foldable21 syn ) => JmEq1 (TrivialABT (syn :: ([k] -> k -> *) -> k -> *) xs) where jmEq1 x y = jmEq2 x y >>= \(Refl, Refl) -> Just Refl instance ( Show1 (Sing :: k -> *) , JmEq1 (Sing :: k -> *) , Foldable21 syn , JmEq1 (syn (TrivialABT syn)) ) => Eq2 (TrivialABT (syn :: ([k] -> k -> *) -> k -> *)) where eq2 x y = isJust (jmEq2 x y) instance ( Show1 (Sing :: k -> *) , JmEq1 (Sing :: k -> *) , Foldable21 syn , JmEq1 (syn (TrivialABT syn)) ) => Eq1 (TrivialABT (syn :: ([k] -> k -> *) -> k -> *) xs) where eq1 = eq2 instance ( Show1 (Sing :: k -> *) , JmEq1 (Sing :: k -> *) , Foldable21 syn , JmEq1 (syn (TrivialABT syn)) ) => Eq (TrivialABT (syn :: ([k] -> k -> *) -> k -> *) xs a) where (==) = eq1 type Varmap = Assocs (Variable :: Hakaru -> *) void_jmEq1 :: Sing (a :: Hakaru) -> Sing (b :: Hakaru) -> ReaderT Varmap Maybe () void_jmEq1 x y = lift (jmEq1 x y) >> return () void_varEq :: Variable (a :: Hakaru) -> Variable (b :: Hakaru) -> ReaderT Varmap Maybe () void_varEq x y = lift (varEq x y) >> return () try_bool :: Bool -> ReaderT Varmap Maybe () try_bool b = lift $ if b then Just () else Nothing alphaEq :: forall abt a . (ABT Term abt) => abt '[] a -> abt '[] a -> Bool alphaEq e1 e2 = maybe False (const True) $ runReaderT (go (viewABT e1) (viewABT e2)) emptyAssocs where -- Don't compare @x@ to @y@ directly; instead, -- look up whatever @x@ renames to (i.e., @y'@) -- and then see whether that is equal to @y@. go :: forall xs1 xs2 a . View (Term abt) xs1 a -> View (Term abt) xs2 a -> ReaderT Varmap Maybe () go (Var x) (Var y) = do s <- ask case lookupAssoc x s of Nothing -> void_varEq x y -- free variables Just y' -> void_varEq y' y -- remember that @x@ renames to @y@ and recurse go (Bind x e1) (Bind y e2) = do Refl <- lift $ jmEq1 (varType x) (varType y) local (insertAssoc (Assoc x y)) (go e1 e2) -- perform the core comparison for syntactic equality go (Syn t1) (Syn t2) = termEq t1 t2 -- if the views don't match, then clearly they are not equal. go _ _ = lift Nothing termEq :: forall a . Term abt a -> Term abt a -> ReaderT Varmap Maybe () termEq e1 e2 = case (e1, e2) of (o1 :$ es1, o2 :$ es2) -> sConEq o1 es1 o2 es2 (NaryOp_ op1 es1, NaryOp_ op2 es2) -> do try_bool (op1 == op2) F.sequence_ $ S.zipWith go (viewABT <$> es1) (viewABT <$> es2) (Literal_ x, Literal_ y) -> try_bool (x == y) (Empty_ x, Empty_ y) -> void_jmEq1 x y (Datum_ d1, Datum_ d2) -> datumEq d1 d2 (Array_ n1 e1, Array_ n2 e2) -> do go (viewABT n1) (viewABT n2) go (viewABT e1) (viewABT e2) (ArrayLiteral_ es, ArrayLiteral_ es') -> F.sequence_ $ zipWith go (viewABT <$> es) (viewABT <$> es') (Bucket a b r, Bucket a' b' r') -> do go (viewABT a) (viewABT a') go (viewABT b) (viewABT b') reducerEq r r' (Case_ e1 bs1, Case_ e2 bs2) -> do Refl <- lift $ jmEq1 (typeOf e1) (typeOf e2) go (viewABT e1) (viewABT e2) zipWithM_ sBranch bs1 bs2 (Superpose_ pms1, Superpose_ pms2) -> F.sequence_ $ L.zipWith pairEq pms1 pms2 (Reject_ x, Reject_ y) -> void_jmEq1 x y (_, _) -> lift Nothing sArgsEq :: forall args . SArgs abt args -> SArgs abt args -> ReaderT Varmap Maybe () sArgsEq End End = return () sArgsEq (e1 :* es1) (e2 :* es2) = do go (viewABT e1) (viewABT e2) sArgsEq es1 es2 sArgsEq _ _ = lift Nothing sConEq :: forall a args1 args2 . SCon args1 a -> SArgs abt args1 -> SCon args2 a -> SArgs abt args2 -> ReaderT Varmap Maybe () sConEq Lam_ e1 Lam_ e2 = sArgsEq e1 e2 sConEq App_ (e1 :* e2 :* End) App_ (e1' :* e2' :* End) = do Refl <- lift $ jmEq1 (typeOf e2) (typeOf e2') go (viewABT e1) (viewABT e1') go (viewABT e2) (viewABT e2') sConEq Let_ (e1 :* e2 :* End) Let_ (e1' :* e2' :* End) = do Refl <- lift $ jmEq1 (typeOf e1) (typeOf e1') go (viewABT e1) (viewABT e1') go (viewABT e2) (viewABT e2') sConEq (CoerceTo_ _) (e1 :* End) (CoerceTo_ _) (e2 :* End) = do Refl <- lift $ jmEq1 (typeOf e1) (typeOf e2) go (viewABT e1) (viewABT e2) sConEq (UnsafeFrom_ _) (e1 :* End) (UnsafeFrom_ _) (e2 :* End) = do Refl <- lift $ jmEq1 (typeOf e1) (typeOf e2) go (viewABT e1) (viewABT e2) sConEq (PrimOp_ o1) es1 (PrimOp_ o2) es2 = primOpEq o1 es1 o2 es2 sConEq (ArrayOp_ o1) es1 (ArrayOp_ o2) es2 = arrayOpEq o1 es1 o2 es2 sConEq (MeasureOp_ o1) es1 (MeasureOp_ o2) es2 = measureOpEq o1 es1 o2 es2 sConEq Dirac e1 Dirac e2 = sArgsEq e1 e2 sConEq MBind (e1 :* e2 :* End) MBind (e1' :* e2' :* End) = do Refl <- lift $ jmEq1 (typeOf e1) (typeOf e1') go (viewABT e1) (viewABT e1') go (viewABT e2) (viewABT e2') sConEq Plate e1 Plate e2 = sArgsEq e1 e2 sConEq Chain e1 Chain e2 = sArgsEq e1 e2 sConEq Integrate e1 Integrate e2 = sArgsEq e1 e2 sConEq (Summate h1 h2) e1 (Summate h1' h2') e2 = do Refl <- lift $ jmEq1 (sing_HDiscrete h1) (sing_HDiscrete h1') Refl <- lift $ jmEq1 (sing_HSemiring h2) (sing_HSemiring h2') sArgsEq e1 e2 sConEq (Product h1 h2) e1 (Product h1' h2') e2 = do Refl <- lift $ jmEq1 (sing_HDiscrete h1) (sing_HDiscrete h1') Refl <- lift $ jmEq1 (sing_HSemiring h2) (sing_HSemiring h2') sArgsEq e1 e2 sConEq (Product h1 h2) e1 (Product h1' h2') e2 = do Refl <- lift $ jmEq1 (sing_HDiscrete h1) (sing_HDiscrete h1') Refl <- lift $ jmEq1 (sing_HSemiring h2) (sing_HSemiring h2') sArgsEq e1 e2 sConEq Expect (e1 :* e2 :* End) Expect (e1' :* e2' :* End) = do Refl <- lift $ jmEq1 (typeOf e1) (typeOf e1') go (viewABT e1) (viewABT e1') go (viewABT e2) (viewABT e2') sConEq _ _ _ _ = lift Nothing primOpEq :: forall a typs1 typs2 args1 args2 . (typs1 ~ UnLCs args1, args1 ~ LCs typs1, typs2 ~ UnLCs args2, args2 ~ LCs typs2) => PrimOp typs1 a -> SArgs abt args1 -> PrimOp typs2 a -> SArgs abt args2 -> ReaderT Varmap Maybe () primOpEq p1 e1 p2 e2 = do (Refl, Refl) <- lift $ jmEq2 p1 p2 sArgsEq e1 e2 arrayOpEq :: forall a typs1 typs2 args1 args2 . (typs1 ~ UnLCs args1, args1 ~ LCs typs1, typs2 ~ UnLCs args2, args2 ~ LCs typs2) => ArrayOp typs1 a -> SArgs abt args1 -> ArrayOp typs2 a -> SArgs abt args2 -> ReaderT Varmap Maybe () arrayOpEq p1 e1 p2 e2 = do (Refl, Refl) <- lift $ jmEq2 p1 p2 sArgsEq e1 e2 measureOpEq :: forall a typs1 typs2 args1 args2 . (typs1 ~ UnLCs args1, args1 ~ LCs typs1, typs2 ~ UnLCs args2, args2 ~ LCs typs2) => MeasureOp typs1 a -> SArgs abt args1 -> MeasureOp typs2 a -> SArgs abt args2 -> ReaderT Varmap Maybe () measureOpEq m1 e1 m2 e2 = do (Refl,Refl) <- lift $ jmEq2 m1 m2 sArgsEq e1 e2 datumEq :: forall a . Datum (abt '[]) a -> Datum (abt '[]) a -> ReaderT Varmap Maybe () datumEq (Datum _ _ d1) (Datum _ _ d2) = datumCodeEq d1 d2 datumCodeEq :: forall xss a . DatumCode xss (abt '[]) a -> DatumCode xss (abt '[]) a -> ReaderT Varmap Maybe () datumCodeEq (Inr c) (Inr d) = datumCodeEq c d datumCodeEq (Inl c) (Inl d) = datumStructEq c d datumCodeEq _ _ = lift Nothing datumStructEq :: forall xs a . DatumStruct xs (abt '[]) a -> DatumStruct xs (abt '[]) a -> ReaderT Varmap Maybe () datumStructEq (Et c1 c2) (Et d1 d2) = do datumFunEq c1 d1 datumStructEq c2 d2 datumStructEq Done Done = return () datumStructEq _ _ = lift Nothing datumFunEq :: forall x a . DatumFun x (abt '[]) a -> DatumFun x (abt '[]) a -> ReaderT Varmap Maybe () datumFunEq (Konst e) (Konst f) = go (viewABT e) (viewABT f) datumFunEq (Ident e) (Ident f) = go (viewABT e) (viewABT f) datumFunEq _ _ = lift Nothing pairEq :: forall a b . (abt '[] a, abt '[] b) -> (abt '[] a, abt '[] b) -> ReaderT Varmap Maybe () pairEq (x1, y1) (x2, y2) = do go (viewABT x1) (viewABT x2) go (viewABT y1) (viewABT y2) sBranch :: forall a b . Branch a abt b -> Branch a abt b -> ReaderT Varmap Maybe () sBranch (Branch _ e1) (Branch _ e2) = go (viewABT e1) (viewABT e2) reducerEq :: forall xs a . Reducer abt xs a -> Reducer abt xs a -> ReaderT Varmap Maybe () reducerEq (Red_Fanout r s) (Red_Fanout r' s') = do reducerEq r r' reducerEq s s' reducerEq (Red_Index s i r) (Red_Index s' i' r') = do go (viewABT s) (viewABT s') go (viewABT i) (viewABT i') reducerEq r r' reducerEq (Red_Split i r s) (Red_Split i' r' s') = do go (viewABT i) (viewABT i') reducerEq r r' reducerEq s s' reducerEq Red_Nop Red_Nop = return () reducerEq (Red_Add _ x) (Red_Add _ x') = go (viewABT x) (viewABT x') reducerEq _ _ = lift Nothing
zaxtax/hakaru
haskell/Language/Hakaru/Syntax/AST/Eq.hs
bsd-3-clause
19,170
11
16
6,307
7,339
3,661
3,678
430
46
module Main(main) where import PolyPaver.Invocation import Data.Ratio ((%)) main = defaultMain Problem { box = [(0,(409018325532672 % 579004697502343,9015995347763200 % 6369051672525773)),(1,(1 % 2,2 % 1))] ,theorem = thm } thm = Implies (Geq (Var 0) (Over (Over (Lit (1023 % 1)) (Lit (1024 % 1))) (Sqrt (Var 1)))) (Implies (Leq (Var 0) (Over (Over (Lit (1025 % 1)) (Lit (1024 % 1))) (Sqrt (Var 1)))) (Implies (Geq (Var 1) (Neg (Lit (340282000000000000000000000000000000000 % 1)))) (Implies (Geq (Var 1) (Over (Lit (1 % 1)) (Lit (2 % 1)))) (Implies (Leq (Var 1) (Lit (2 % 1))) (Implies (Geq (Var 0) (Neg (Lit (340282000000000000000000000000000000000 % 1)))) (Implies (Leq (Var 0) (Lit (340282000000000000000000000000000000000 % 1))) (Implies (Geq (FTimes (Over (Lit (1 % 1)) (Lit (2 % 1))) (Var 0)) (Neg (Lit (340282000000000000000000000000000000000 % 1)))) (Implies (Leq (FTimes (Over (Lit (1 % 1)) (Lit (2 % 1))) (Var 0)) (Lit (340282000000000000000000000000000000000 % 1))) (And (Geq (FTimes (Var 0) (Var 0)) (Neg (Lit (340282000000000000000000000000000000000 % 1)))) (Leq (FTimes (Var 0) (Var 0)) (Lit (340282000000000000000000000000000000000 % 1))))))))))))
michalkonecny/polypaver
examples/old/their_sqrt/their_sqrt_12.hs
bsd-3-clause
1,210
0
31
217
712
376
336
9
1
{-# LANGUAGE TypeFamilies #-} import Music.Prelude import qualified Music.Score as Score markIf :: (HasColor a, HasPitches' a, Score.Pitch a ~ Pitch) => (Interval -> Bool) -> Score a -> Score a markIf p = mapIf (\x -> p $ withOrigin c $ x ^?! pitches) mark where mark = colorRed mapIf p f = uncurry mplus . over _1 f . mpartition p withOrigin x = (.-. x) markPerfect = text "Perfect consonances" . markIf isPerfectConsonance markImperfect = text "Imperfect consonances" . markIf isImperfectConsonance markDiss = text "Dissonances" . markIf isDissonance -- Try different subjects: subject = [c..c'] -- subject = [c,d,cs,gs,f,fs,g_,gs_,fs,f,e,ds',c] main = openLilypond $ asScore $ rcat [ markPerfect $ scat subject, markImperfect $ scat subject, markDiss $ scat subject ]
music-suite/music-preludes
examples/analysis.hs
bsd-3-clause
850
0
11
202
257
131
126
16
1
-- |This library simplifies the task of securely connecting two -- servers to each other. It closely mimicks the regular socket API, -- and adds the concept of identity: each communicating server has an -- identity, and connections can only be established between two -- servers who know each other and expect to be communicating. -- -- Under the hood, the library takes care of strongly authenticating -- the connection, and of encrypting all traffic. If you successfully -- establish a connection using this library, you have the guarantee -- that the connection is secure. {-# LANGUAGE NoImplicitPrelude #-} module Network.Secure ( -- * Tutorial -- $tutorial -- * Internals and caveats -- $internals -- * Managing identities Identity(..) , PeerIdentity , LocalIdentity , toPeerIdentity , newLocalIdentity -- * Communicating -- ** Connecting to peers , connect -- ** Accepting connections from peers , Socket , newServer , accept -- ** Talking to connected peers , Connection , peer , read , readPtr , write , writePtr , close -- ** Misc reexports from 'Network.Socket' , HostName , ServiceName ) where import Network.Secure.Connection import Network.Secure.Identity -- $tutorial -- -- First, each host needs to generate a local identity for itself. A -- local identity allows a server to authenticate itself to remote -- peers. -- -- > do -- > id <- newLocalIdentity "server1.domain.com" 365 -- > writeIdentity id >>= writeFile "server.key" -- -- The name is not used at all by the library, it just allows you to -- identify the key later on if you need to. -- -- This identity contains secret key material that only the generating -- host should have. From this, we need to generate a public identity -- that can be given to other hosts. -- -- > do -- > id <- readFile "server.key" >>= readIdentity -- > writeIdentity (toPeerIdentity id) >>= writeFile "server.pub" -- -- This public file should be distributed to the servers with whom you -- want to communicate. Once everyone has the public identities of -- their peers, we can start connecting. First, one host needs to -- start listening for connections. -- -- > do -- > me <- readFile "a.key" >>= readIdentity -- > you <- readFile "b.pub" >>= readIdentity -- > server <- newServer (Nothing, "4242") -- > conn <- accept me [you] server -- -- Then, another host needs to connect. -- -- > do -- > me <- readFile "b.key" >>= readIdentity -- > you <- readFile "a.pub" >>= readIdentity -- > conn <- connect me [you] ("a.com", "4242") -- -- Et voila! From there on, you can communicate using the usual -- socket-ish API: -- -- > do -- > write conn "hello?" -- > read conn 128 >>= putStrLn -- > close conn -- -- N.B. The program should start with 'withOpenSSL' in order to initialize SSL -- (@main = withOpenSSL $ do@). -- $internals -- -- Note that this section gives out internal implementation details -- which are subject to change! Compatibility breakages will be -- indicated by appropriate version number bumps for the package, and -- the internal details of new versions may bear no resemblance -- whatsoever to the old version. -- -- The current implementation uses OpenSSL (via HsOpenSSL) for -- transport security, with the @AES256-SHA@ ciphersuite and 4096 bit -- RSA keys. -- -- Due to a current limitation of the HsOpenSSL API, we do not use a -- ciphersuite that makes use of ephemeral keys for encryption. The -- consequence is that connections established with this library do -- not provide perfect forward secrecy. -- -- That is, if an attacker can compromise the private keys of the -- communicating servers, she can decrypt all past communications that -- she has recorded. -- -- This shortcoming will be fixed at some point, either by adding -- Diffie-Hellman keying support to HsOpenSSL, or by switching to a -- different underlying implementation.
GaloisInc/secure-sockets
Network/Secure.hs
bsd-3-clause
4,019
0
5
852
172
146
26
23
0
module Main where import Data.List import System.Environment import qualified Semantics import Tests.Frenetic.Slices.TestCompile import Tests.Frenetic.Slices.TestEndToEnd import Tests.Frenetic.Slices.TestSlice import Tests.Frenetic.Slices.TestVerification import Tests.Frenetic.Slices.TestVlanAssignment import Tests.Frenetic.TestSat import Test.HUnit import Test.Framework main = do args <- getArgs let sat = elem "sat" args let ourTests = if sat then satTestGroup : mainTests else mainTests let args' = if sat then delete "sat" args else args defaultMainWithArgs ourTests args' mainTests = [ Semantics.tests , testGroup "Slice tests" [ sliceCompileTests , sliceTests , sliceVerificationTests , vlanAssignmentTests ] ] satTestGroup = testGroup "SAT tests" [ satTests , endToEndTests ]
frenetic-lang/netcore-1.0
testsuite/Main.hs
bsd-3-clause
1,031
0
11
336
192
111
81
27
3
{-# LANGUAGE TypeSynonymInstances #-} module Types where import Protolude type App a = ReaderT AppConfig (ExceptT AppError IO) a data AppError = LoginError Text | TagNotFound Text | TagHasNoText Text | UsageNotParsable Text | BalanceNotParsable Text | UsageNotExtractable | EndDateNotFound | EndDateNotParsable Text | PublisherError Text deriving Show data AppArgs = ShowVersion | Run AppConfig deriving Show type ProviderBaseUrl = Text data AppConfig = AppConfig { acQuiet :: Bool , acProviderLogin :: ProviderLogin , acPersistPath :: Maybe FilePath , acPublishEndpoints :: Endpoints , acAvailableThreshold :: AvailableThreshold , acBalanceThreshold :: BalanceThreshold , acProviderBaseUrl :: ProviderBaseUrl } deriving Show data ProviderLogin = ProviderLogin { plUser :: Text , plPass :: Text } deriving Show type Endpoints = [Endpoint] data Endpoint = EndpointQuota Text | EndpointUsed Text | EndpointAvailable Text | EndpointBalance Text | EndpointDaysLeft Text deriving Show data AvailableThreshold = AvailableThreshold { atWarning :: Maybe Int , atCritical :: Maybe Int } deriving Show data BalanceThreshold = BalanceThreshold { btWarning :: Maybe Float , btCritical :: Maybe Float } deriving Show data Tariff = Tariff { tBalance :: Balance , tUsage :: Usage , tDaysLeft :: Integer } deriving Show data Balance = BalanceNotAvailable | Balance Float deriving Show data Usage = UsageNotAvailable | Usage { uQuota :: Int , uUsed :: Int , uAvailable :: Int } deriving Show class IsBelowThreshold a where isBelowWarning :: a -> ReaderT AppConfig IO Bool isBelowCritical :: a -> ReaderT AppConfig IO Bool instance IsBelowThreshold Usage where isBelowWarning UsageNotAvailable = pure False isBelowWarning (Usage _ _ a) = do n <- atWarning <$> asks acAvailableThreshold pure $ maybe False (> a) n isBelowCritical UsageNotAvailable = pure False isBelowCritical (Usage _ _ a) = do w <- atCritical <$> asks acAvailableThreshold pure $ maybe False (> a) w instance IsBelowThreshold Balance where isBelowWarning BalanceNotAvailable = pure False isBelowWarning (Balance b) = do n <- btWarning <$> asks acBalanceThreshold pure $ maybe False (> b) n isBelowCritical BalanceNotAvailable = pure False isBelowCritical (Balance b) = do w <- btCritical <$> asks acBalanceThreshold pure $ maybe False (> b) w
section77/datenverbrauch
src/Types.hs
bsd-3-clause
3,101
0
10
1,150
652
359
293
80
0
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} module Network.Conduits where import Network import Util import Conduit import Static import Network.Runners import Control.Applicative trainC :: forall m i ls. ( MonadIO m , Creatable (Network i ls) ) => LearningParameters -> Conduit ( SArray U i , SArray U (NOutput (Network i ls)) ) m (Network i ls) trainC params = go (seeded 9 :: Network i ls) where go net = do mxy <- await case mxy of Just (x, y) -> do (net', (pct, dtl)) <- trainOnce net params x y liftIO . putStrLn$ show pct ++ '\t':show dtl yield net' go net' Nothing -> return () combineXY :: Monad m => Source m x -> Source m y -> Source m (x, y) combineXY sx sy = getZipSource $ liftA2 (,) (ZipSource sx) (ZipSource sy)
jonascarpay/convoluted
src/Network/Conduits.hs
bsd-3-clause
1,055
0
17
438
331
168
163
29
2
{-# LANGUAGE CPP, OverloadedStrings, DataKinds, GADTs #-} module Main where import Language.Hakaru.Pretty.SExpression import Language.Hakaru.Syntax.AST.Transforms import Language.Hakaru.Syntax.TypeCheck import Language.Hakaru.Command import Language.Hakaru.Summary #if __GLASGOW_HASKELL__ < 710 import Control.Applicative (Applicative(..), (<$>)) #endif import Data.Monoid import Data.Text import qualified Data.Text.IO as IO import System.IO (stderr) import qualified Options.Applicative as O import System.Environment data Options = Options { opt :: Bool , program :: String} options :: O.Parser Options options = Options <$> O.switch ( O.long "opt" <> O.help "enables summary optimization for sexpr printer" ) <*> O.strArgument ( O.metavar "PROGRAM" <> O.help "Program to be pretty printed") parseOpts :: IO Options parseOpts = O.execParser $ O.info (O.helper <*> options) (O.fullDesc <> O.progDesc "Pretty print a hakaru program in S-expression") main :: IO () main = do args <- parseOpts case args of Options opt program -> do IO.readFile program >>= runPretty opt runPretty :: Bool -> Text-> IO () runPretty opt prog = case parseAndInfer prog of Left err -> IO.hPutStrLn stderr err Right (TypedAST _ ast) -> do ast' <- summary . expandTransformations $ ast print . pretty $ ast'
zachsully/hakaru
commands/PrettySExpression.hs
bsd-3-clause
1,489
0
14
381
388
210
178
41
2
{-# LANGUAGE OverloadedStrings #-} import qualified Data.Text.IO as TO import Text.Parsec import Data.Cauterize.Parser import Data.Cauterize.Generators.C main :: IO () main = do d <- TO.readFile fname case parse parseCauterize fname d of Left e -> print e Right v -> print $ gen v where fname = "example.scm"
sw17ch/Z-ARCHIVED-hscauterize
hscauterize.hs
bsd-3-clause
331
0
11
70
106
55
51
12
2
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE PolyKinds #-} module Data.LnFunctor.Coapply where import Data.LnFunctor class LnFunctor f => LnCoapply f where type Unlink f h m k l i j :: Constraint lcoap :: Unlink f h m k l i j => f h m (a -> b) -> f k l a -> f i j b (<@@>) :: (LnCoapply f, Unlink f h m k l i j) => f h m (a -> b) -> f k l a -> f i j b (<@@>) = lcoap infixl 4 <@@> (<@@) :: (LnCoapply f, Unlink f h m k l i j) => f h m a -> f k l b -> f i j a (<@@) = lcothenL infixl 4 <@@ (@@>) :: (LnCoapply f, Unlink f h m k l i j) => f h m a -> f k l b -> f i j b (@@>) = lcothenR infixl 4 @@> lcothenL :: (LnCoapply f, Unlink f h m k l i j) => f h m a -> f k l b -> f i j a lcothenL = lliftCA2 const lcothenR :: (LnCoapply f, Unlink f h m k l i j) => f h m a -> f k l b -> f i j b lcothenR = lliftCA2 (const id) lliftCA :: (LnCoapply f,LinkPar f i j k l) => (a -> b) -> f i j a -> f k l b lliftCA = (<$$>) lliftCA2 :: (LnCoapply f, Unlink f h m k l i j) => (a -> b -> c) -> f h m a -> f k l b -> f i j c lliftCA2 f a b = f <$> a <@@> b lliftCA3 :: forall f a b c d h i j k l m n o p q. (LnCoapply f, Unlink f h m k l i j, Unlink f p q n o h m) => (a -> b -> c -> d) -> f p q a -> f n o b -> f k l c -> f i j d lliftCA3 f a b c = fab <@@> c where fa :: f p q (b -> c -> d) fa = f <$> a fab :: f h m (c -> d) fab = fa <@@> b
kylcarte/lnfunctors
src/Data/LnFunctor/Coapply.hs
bsd-3-clause
1,467
0
11
440
850
450
400
37
1
module P025 where import Data.Maybe (fromJust) import Data.List (find) import Fibonacci (fibonacci) run :: IO () run = print (fst found) where found = fromJust . find (\(i, f) -> (length . show) f == 1000) . zip [1..] $ fibonacci
tyehle/euler-haskell
src/P025.hs
bsd-3-clause
238
0
16
49
112
62
50
7
1
module LibSpec where import Test.Hspec import Del.Lib import Del.Syntax main :: IO () main = hspec spec spec :: Spec spec = do describe "simplifyExp" $ do let a = Sym "a" mempty mempty it "checks a+a=2a" $ simplifyExp (Add a a) `shouldBe` (Mul (Num 2.0) a) it "checks a-a=0" $ simplifyExp (Sub a a) `shouldBe` Num 0 it "checks a*a=a**2" $ simplifyExp (Mul a a) `shouldBe` (Pow a (Num 2.0)) it "checks a/a=1" $ simplifyExp (Div a a) `shouldBe` Num 1 it "checks a/(a*a)=a**(-1)" $ simplifyExp (Div a (Mul a a)) `shouldBe` (Pow a (Neg (Num 1.0))) it "checks a/(a/a)=a" $ simplifyExp (Div a (Div a a)) `shouldBe` a
ishiy1993/mk-sode1
test/LibSpec.hs
bsd-3-clause
681
0
16
180
305
150
155
22
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE ScopedTypeVariables #-} module Rumpus.TestScene where import Rumpus -- | For profiling (where we can't run code) -- and for other prototyping. loadTestScene :: ECSMonad () loadTestScene = do -- testEntity <- spawnEntity $ return () -- addCodeExpr testEntity "CollisionBegan" "collisionStart" myCollisionBeganExpr myCollisionBegan -- selectEntity testEntity -- Spawn objects forM_ [room, city, fountain] $ \onStart -> do --forM_ [room] $ \onStart -> do spawnEntity $ do myStart ==> onStart mySize ==> 0.3 myShape ==> Cube setWorldPlaying True return () ------------------------------------------------------------------------------ -- Room roomCube, roomW, roomH, roomD, wallD, shelfH, roomOffset :: GLfloat roomCube = 4 (roomW, roomH, roomD) = (roomCube,roomCube,roomCube) wallD = 1 shelfH = 0.15 roomOffset = (roomH/2 - wallD/2) room :: Start room = do setPose (identity & translation .~ V3 0 roomOffset (-roomD/2 + 0.4)) removeChildren builderID <- ask let makeWall pos size hue = spawnEntity_ $ do myParent ==> builderID myPose ==> position (pos & _y +~ roomOffset) myShape ==> Cube myBody ==> Animated myBodyFlags ==> [Ungrabbable] mySize ==> size myColor ==> colorHSL hue 0.8 0.6 myMass ==> 0 --makeWall (V3 0 0 (-roomD/2)) (V3 roomW roomH wallD) 0.1 -- back --makeWall (V3 0 0 (roomD/2)) (V3 roomW roomH wallD) 0.2 -- front --makeWall (V3 (-roomW/2) 0 0) (V3 wallD roomH roomD) 0.3 -- left --makeWall (V3 (roomW/2) 0 0) (V3 wallD roomH roomD) 0.4 -- right makeWall (V3 0 (-roomH/2) 0) (V3 roomW wallD roomD) 0.5 -- floor makeWall (V3 0 (roomH/2) 0) (V3 roomW wallD roomD) 0.6 -- ceiling let numShelves = 4 forM_ [1..(numShelves - 1)] $ \n -> do let shelfY = (roomH/realToFrac numShelves) * n - (roomH/2) makeWall (V3 0 shelfY (roomD/2)) (V3 roomW shelfH (wallD*2)) 0.7 -- shelf ------------------------------------------------------------------------------- -- City -- Golden Section Spiral -- (via http://www.softimageblog.com/archives/115) pointsOnSphere :: Int -> [V3 GLfloat] pointsOnSphere (fromIntegral -> n) = let inc = pi * (3 - sqrt 5) off = 2 / n in flip map [0..n] $ \k -> let y = k * off - 1 + (off / 2) r = sqrt (1 - y*y) phi = k * inc in V3 (cos phi * r) y (sin phi * r) city :: Start city = do removeChildren createBuildings createStars createBuildings :: EntityMonad () createBuildings = do rootEntityID <- ask let n = 8 dim = 200 height = dim * 5 buildSites = [V3 (x * dim * 2) (-height) (z * dim * 2) | x <- [-n..n], z <- [-n..n]] forM_ (zip [0..] buildSites) $ \(_i::Int, V3 x y z) -> do hue <- liftIO randomIO when (x /= 0 && z /= 0) $ spawnEntity_ $ do myParent ==> rootEntityID myPose ==> position (V3 x y z) myShape ==> Cube --myUpdate ==> do -- now <- getNow -- let newHeight = ((sin (now+_i) + 1) + 1) * height -- setSize (V3 dim newHeight dim) mySize ==> V3 dim height dim myColor ==> colorHSL hue 0.8 0.8 createStars :: EntityMonad () createStars = do rootEntityID <- ask let numPoints = 300 :: Int sphere = pointsOnSphere numPoints hues = map ((/ fromIntegral numPoints) . fromIntegral) [0..numPoints] forM_ (zip sphere hues) $ \(pos, hue) -> spawnEntity_ $ do myParent ==> rootEntityID myPose ==> position (pos * 1000) myShape ==> Sphere mySize ==> 5 myColor ==> colorHSL hue 0.8 0.8 ------------------------- -- Fountain rate :: Float rate = 10 majorScale :: [GLfloat] majorScale = map (+60) [0,2,4,7,9] fountain :: Start fountain = do removeChildren myUpdate ==> do withState $ \timer -> do shouldSpawn <- checkTimer timer when shouldSpawn $ do -- Play a note note <- randomFrom majorScale sendSynth "note" (Atom $ realToFrac note) -- Spawn a ball pose <- getPose _ <- spawnEntity $ do myPose ==> pose & translation +~ (pose ^. _m33) !* (V3 0 0.3 0) myShape ==> Sphere mySize ==> 0.03 myMass ==> 0.1 myColor ==> colorHSL (note / 12) 0.9 0.8 myStart ==> do setLifetime 10 applyForce $ (pose ^. _m33) !* (V3 0 0.3 0) -- Create a new timer newTimer <- createNewTimer rate setState newTimer -- Create the initial timer newTimer <- createNewTimer rate setState newTimer
lukexi/rumpus
src/Rumpus/TestScene.hs
bsd-3-clause
5,408
0
28
1,963
1,449
738
711
113
1
{-# LANGUAGE NoMonomorphismRestriction, OverloadedStrings, ScopedTypeVariables #-} module Utils.Spoty ( module Utils.Spoty.Types, getAlbum, getAlbumTracks, getArtist, getArtistAlbums, CountryID, getArtistTop, getArtistRelated, SearchCategory(..), search, searchArtist, searchAlbum, searchTrack, getTrack, getUser, fetchOne, fetchAll ) where import Control.Applicative ((<$>)) import Control.Exception (throw) import Control.Lens import Control.Monad (when) import Data.Aeson import Data.Aeson.Lens (key) import Data.Aeson.Types (parseMaybe) import qualified Data.ByteString.Lazy.Char8 as BL import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) import qualified Data.Text as T import qualified Network.Wreq as W import qualified Pipes as P import qualified Pipes.Prelude as P import Utils.Spoty.Types baseURL, versionURL :: String baseURL = "https://api.spotify.com/" versionURL = "v1/" -- | Country identifier e.g. \"SE\". type CountryID = T.Text -- | Categories being used in a search. data SearchCategory = SearchAlbum -- ^ Search for albums. | SearchArtist -- ^ Search for artists. | SearchTrack -- ^ Search for tracks. deriving (Eq, Ord) instance Show SearchCategory where show SearchAlbum = "album" show SearchArtist = "artist" show SearchTrack = "track" -- | Construct a URL from an endpoint and an identifier. build :: T.Text -> SpotID -> T.Text build e = build2 e "" -- | Construct a URL from endpoint / spotify id / subdir. build2 :: T.Text -> T.Text -> SpotID -> T.Text build2 endpoint dir arg = T.intercalate "/" [endpoint, arg, dir] -- | Retrieve an album. getAlbum :: SpotID -> IO Album getAlbum = fetch . build "albums" -- | Retrieve the tracks of an album. getAlbumTracks :: SpotID -> P.Producer Track IO () getAlbumTracks = makeProducer Nothing W.defaults . build2 "albums" "tracks" -- | Retrieve an artist. getArtist :: SpotID -> IO Artist getArtist = fetch . build "artists" -- | Retrieve the albums of an artist. getArtistAlbums :: SpotID -> P.Producer Album IO () getArtistAlbums = makeProducer Nothing W.defaults . build2 "artists" "albums" type Predicate a = W.Response BL.ByteString -> IO a -- | Construct producer (source) from URL generating a paging object. -- Optionally accepts a predicate applied on the retrieved JSON object. makeProducer :: FromJSON a => Maybe (Predicate (Paging a)) -> W.Options -> T.Text -> P.Producer a IO () makeProducer predicate opts url = go 0 where go off = do let opts' = opts & W.param "offset" .~ [T.pack $ show off] reply <- P.liftIO $ grab opts' url let f = fromMaybe (fmap (^. W.responseBody) . W.asJSON) predicate (chunk :: Paging b) <- P.liftIO $ f reply mapM_ P.yield $ chunk ^. items let delta = length $ chunk ^. items off' = off + delta when (off' < chunk ^. total) (go off') -- | Extract the value associated with the given key from a response. extractInner :: (FromJSON a) => W.Response BL.ByteString -> T.Text -> Maybe a extractInner raw tag = locate >>= parseMaybe parseJSON where locate = raw ^? W.responseBody . key tag -- | Retrieve the most popular tracks of an artist. getArtistTop :: SpotID -> CountryID -> IO [Track] getArtistTop artist country = do let opts = W.defaults & W.param "country" .~ [country] reply <- grab opts $ build2 "artists" "top-tracks" artist return . fromMaybe [] $ extractInner reply "tracks" -- | Retrieve a few related artists. getArtistRelated :: SpotID -> IO [Artist] getArtistRelated artist = do reply <- grab W.defaults $ build2 "artists" "related-artists" artist return . fromMaybe [] $ extractInner reply "artists" -- | Retrieve a track. getTrack :: SpotID -> IO Track getTrack = fetch . build "tracks" -- | Retrieve an user. getUser :: T.Text -> IO User getUser = fetch . build "users" -- | Search for some string in the given categories. search :: [SearchCategory] -> T.Text -> (P.Producer Artist IO (), P.Producer Album IO (), P.Producer Track IO ()) search cats term = (extract SearchArtist, extract SearchAlbum, extract SearchTrack) where opts = W.defaults & W.param "q" .~ [term] & W.param "type" .~ [T.intercalate "," $ map (T.pack . show) cats] pluralize = T.pack . (<> "s") . show extract tag = when (tag `elem` cats) (makeProducer (Just $ predicate tag) opts url) url = build "search" "" predicate tag reply = case extractInner reply (pluralize tag) of Just val -> return val Nothing -> throw . W.JSONError $ "Unexpected search result, got: " <> show reply -- | Search for artists. searchArtist :: T.Text -> P.Producer Artist IO () searchArtist = (^. _1) . search [SearchArtist] -- | Search for albums. searchAlbum :: T.Text -> P.Producer Album IO () searchAlbum = (^. _2) . search [SearchAlbum] -- | Search for tracks. searchTrack :: T.Text -> P.Producer Track IO () searchTrack = (^. _3) . search [SearchTrack] -- | Fetch one element from the producer and discard the rest. fetchOne :: Monad m => P.Producer a m () -> m (Maybe a) fetchOne = P.head -- | Fetch all elements from the producer (NOTE: not constant space). fetchAll :: Monad m => P.Producer a m () -> m [a] fetchAll = P.toListM -- | Fetch a path and decode the corresponding object. fetch :: FromJSON a => T.Text -> IO a fetch = fetchWith W.defaults -- | Fetch a path with the given HTTP options and decode the corresponding object. fetchWith :: FromJSON a => W.Options -> T.Text -> IO a fetchWith opts path' = (^. W.responseBody) <$> (grab opts path' >>= W.asJSON) -- | Fetch a path with the given HTTP options and return the raw response. grab :: W.Options -> T.Text -> IO (W.Response BL.ByteString) grab opts path' = W.getWith opts $ baseURL <> versionURL <> T.unpack path'
davnils/spoty
src/Utils/Spoty.hs
bsd-3-clause
5,834
11
17
1,154
1,724
910
814
-1
-1
module CalculatorKata.Day1Spec (spec) where import Test.Hspec import CalculatorKata.Day1 (calculate) spec :: Spec spec = do it "calculates one digit" (calculate "2" == 2.0) it "calculates many digits" (calculate "234" == 234.0) it "calculates addition" (calculate "54+6" == 54.0+6.0) it "calculates subtraction" (calculate "54-8" == 54.0-8.0) it "calculates multiplication" (calculate "54*2" == 54.0*2) it "calculates division" (calculate "54/6" == 54.0/6.0)
Alex-Diez/haskell-tdd-kata
old-katas/test/CalculatorKata/Day1Spec.hs
bsd-3-clause
602
0
11
202
160
78
82
17
1
-- | Helper functions to make it easy to start messing around module System.MIDI.Utility ( selectMidiDevice , selectInputDevice , selectOutputDevice ) where -------------------------------------------------------------------------------- import Data.List import Control.Monad import Control.Concurrent import System.IO import System.MIDI import System.MIDI.Base -------------------------------------------------------------------------------- maybeRead :: Read a => String -> Maybe a maybeRead s = case reads s of [(x,"")] -> Just x _ -> Nothing -- | Utility function to help choosing a midi device. -- If there is only a single device, we select that. -- You can also set a default device (by its name), which -- will be automatically selected if present. selectMidiDevice :: MIDIHasName a => String -- ^ prompt -> Maybe String -- ^ default device name -> [a] -- ^ list of devices -> IO a selectMidiDevice prompt mbdefault srclist = do names <- mapM getName srclist let nsrc = length srclist putStrLn prompt src <- case srclist of [] -> do putStrLn "no midi devices found" fail "no midi devices found" [x] -> do putStrLn $ "device #1 (" ++ head names ++ ") selected." return x _ -> do k <- case findIndex (==mbdefault) (map Just names) of Just i -> return (i+1) Nothing -> do forM_ (zip [1..] names) $ \(i,name) -> putStrLn $ show i ++ ": " ++ name putStr "please select a midi device: " hFlush stdout l <- getLine putStrLn "" let k = case maybeRead l of Nothing -> nsrc Just m -> if m<1 || m>nsrc then nsrc else m return k putStrLn $ "device #" ++ show k ++ " (" ++ names!!(k-1) ++ ") selected." return $ srclist!!(k-1) return src -- | Select a MIDI input device (source) selectInputDevice :: String -> Maybe String -> IO Source selectInputDevice prompt mbdefault = do srclist <- enumerateSources src <- selectMidiDevice prompt mbdefault srclist return src -- | Select a MIDI output device (destination) selectOutputDevice :: String -> Maybe String -> IO Destination selectOutputDevice prompt mbdefault = do dstlist <- enumerateDestinations dst <- selectMidiDevice prompt mbdefault dstlist return dst --------------------------------------------------------------------------------
chpatrick/hmidi
System/MIDI/Utility.hs
bsd-3-clause
2,472
0
28
625
620
303
317
57
6
module Monad( ServerEnv(..) , ServerM , newServerEnv , runServerM , runServerMIO , AuthM(..) , runAuth ) where import Control.Monad.Base import Control.Monad.Catch (MonadCatch, MonadThrow) import Control.Monad.Except import Control.Monad.Logger import Control.Monad.Reader import Control.Monad.Trans.Control import Data.Monoid import Database.Persist.Sql import Servant.Server import Servant.Server.Auth.Token.Config import Servant.Server.Auth.Token.Model import Servant.Server.Auth.Token.Persistent import qualified Servant.Server.Auth.Token.Persistent.Schema as S import Config -- | Server private environment data ServerEnv = ServerEnv { -- | Configuration used to create the server envConfig :: !ServerConfig -- | Configuration of auth server , envAuthConfig :: !AuthConfig -- | DB pool , envPool :: !ConnectionPool } -- | Create new server environment newServerEnv :: MonadIO m => ServerConfig -> m ServerEnv newServerEnv cfg = do let authConfig = defaultAuthConfig pool <- liftIO $ do pool <- createPool cfg -- run migrations flip runSqlPool pool $ runMigration S.migrateAllAuth -- create default admin if missing one _ <- runPersistentBackendT authConfig pool $ ensureAdmin 17 "admin" "123456" "admin@localhost" return pool let env = ServerEnv { envConfig = cfg , envAuthConfig = authConfig , envPool = pool } return env -- | Server monad that holds internal environment newtype ServerM a = ServerM { unServerM :: ReaderT ServerEnv (LoggingT Handler) a } deriving (Functor, Applicative, Monad, MonadIO, MonadBase IO, MonadReader ServerEnv , MonadLogger, MonadLoggerIO, MonadThrow, MonadCatch, MonadError ServantErr) newtype StMServerM a = StMServerM { unStMServerM :: StM (ReaderT ServerEnv (LoggingT Handler)) a } instance MonadBaseControl IO ServerM where type StM ServerM a = StMServerM a liftBaseWith f = ServerM $ liftBaseWith $ \q -> f (fmap StMServerM . q . unServerM) restoreM = ServerM . restoreM . unStMServerM -- | Lift servant monad to server monad liftHandler :: Handler a -> ServerM a liftHandler = ServerM . lift . lift -- | Execution of 'ServerM' runServerM :: ServerEnv -> ServerM a -> Handler a runServerM e = runStdoutLoggingT . flip runReaderT e . unServerM -- | Execution of 'ServerM' in IO monad runServerMIO :: ServerEnv -> ServerM a -> IO a runServerMIO env m = do ea <- runHandler $ runServerM env m case ea of Left e -> fail $ "runServerMIO: " <> show e Right a -> return a -- | Special monad for authorisation actions newtype AuthM a = AuthM { unAuthM :: PersistentBackendT IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadError ServantErr, HasStorage, HasAuthConfig) -- | Execution of authorisation actions that require 'AuthHandler' context runAuth :: AuthM a -> ServerM a runAuth m = do cfg <- asks envAuthConfig pool <- asks envPool liftHandler $ Handler . ExceptT $ runPersistentBackendT cfg pool $ unAuthM m
NCrashed/servant-auth-token
example/persistent/src/Monad.hs
bsd-3-clause
3,007
0
13
568
780
420
360
-1
-1
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, PatternGuards, TypeSynonymInstances #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.Tabbed -- Copyright : (c) 2007 David Roundy, Andrea Rossato -- License : BSD-style (see xmonad/LICENSE) -- -- Maintainer : andrea.rossato@unibz.it -- Stability : unstable -- Portability : unportable -- -- A tabbed layout for the Xmonad Window Manager -- ----------------------------------------------------------------------------- module XMonad.Layout.Tabbed ( -- * Usage: -- $usage simpleTabbed, tabbed, addTabs , simpleTabbedAlways, tabbedAlways, addTabsAlways , simpleTabbedBottom, tabbedBottom, addTabsBottom , simpleTabbedBottomAlways, tabbedBottomAlways, addTabsBottomAlways , Theme (..) , def , defaultTheme , TabbedDecoration (..) , shrinkText, CustomShrink(CustomShrink) , Shrinker(..) , TabbarShown, TabbarLocation ) where import Data.List import XMonad import qualified XMonad.StackSet as S import XMonad.Layout.Decoration import XMonad.Layout.Simplest ( Simplest(Simplest) ) -- $usage -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Layout.Tabbed -- -- Then edit your @layoutHook@ by adding the Tabbed layout: -- -- > myLayout = simpleTabbed ||| Full ||| etc.. -- -- or, if you want a specific theme for you tabbed layout: -- -- > myLayout = tabbed shrinkText def ||| Full ||| etc.. -- -- and then: -- -- > main = xmonad def { layoutHook = myLayout } -- -- This layout has hardcoded behaviour for mouse clicks on tab decorations: -- Left click on the tab switches focus to that window. -- Middle click on the tab closes the window. -- -- The default Tabbar behaviour is to hide it when only one window is open -- on the workspace. To have it always shown, use one of the layouts or -- modifiers ending in @Always@. -- -- For more detailed instructions on editing the layoutHook see: -- -- "XMonad.Doc.Extending#Editing_the_layout_hook" -- -- You can also edit the default configuration options. -- -- > myTabConfig = def { inactiveBorderColor = "#FF0000" -- > , activeTextColor = "#00FF00"} -- -- and -- -- > mylayout = tabbed shrinkText myTabConfig ||| Full ||| etc.. -- Layouts -- | A tabbed layout with the default xmonad Theme. -- -- This is a minimal working configuration: -- -- > import XMonad -- > import XMonad.Layout.Tabbed -- > main = xmonad def { layoutHook = simpleTabbed } simpleTabbed :: ModifiedLayout (Decoration TabbedDecoration DefaultShrinker) Simplest Window simpleTabbed = tabbed shrinkText def simpleTabbedAlways :: ModifiedLayout (Decoration TabbedDecoration DefaultShrinker) Simplest Window simpleTabbedAlways = tabbedAlways shrinkText def -- | A bottom-tabbed layout with the default xmonad Theme. simpleTabbedBottom :: ModifiedLayout (Decoration TabbedDecoration DefaultShrinker) Simplest Window simpleTabbedBottom = tabbedBottom shrinkText def -- | A bottom-tabbed layout with the default xmonad Theme. simpleTabbedBottomAlways :: ModifiedLayout (Decoration TabbedDecoration DefaultShrinker) Simplest Window simpleTabbedBottomAlways = tabbedBottomAlways shrinkText def -- | A layout decorated with tabs and the possibility to set a custom -- shrinker and theme. tabbed :: (Eq a, Shrinker s) => s -> Theme -> ModifiedLayout (Decoration TabbedDecoration s) Simplest a tabbed s c = addTabs s c Simplest tabbedAlways :: (Eq a, Shrinker s) => s -> Theme -> ModifiedLayout (Decoration TabbedDecoration s) Simplest a tabbedAlways s c = addTabsAlways s c Simplest -- | A layout decorated with tabs at the bottom and the possibility to set a custom -- shrinker and theme. tabbedBottom :: (Eq a, Shrinker s) => s -> Theme -> ModifiedLayout (Decoration TabbedDecoration s) Simplest a tabbedBottom s c = addTabsBottom s c Simplest tabbedBottomAlways :: (Eq a, Shrinker s) => s -> Theme -> ModifiedLayout (Decoration TabbedDecoration s) Simplest a tabbedBottomAlways s c = addTabsBottomAlways s c Simplest -- Layout Modifiers -- | A layout modifier that uses the provided shrinker and theme to add tabs to any layout. addTabs :: (Eq a, LayoutClass l a, Shrinker s) => s -> Theme -> l a -> ModifiedLayout (Decoration TabbedDecoration s) l a addTabs = createTabs WhenPlural Top addTabsAlways :: (Eq a, LayoutClass l a, Shrinker s) => s -> Theme -> l a -> ModifiedLayout (Decoration TabbedDecoration s) l a addTabsAlways = createTabs Always Top -- | A layout modifier that uses the provided shrinker and theme to add tabs to the bottom of any layout. addTabsBottom :: (Eq a, LayoutClass l a, Shrinker s) => s -> Theme -> l a -> ModifiedLayout (Decoration TabbedDecoration s) l a addTabsBottom = createTabs WhenPlural Bottom addTabsBottomAlways :: (Eq a, LayoutClass l a, Shrinker s) => s -> Theme -> l a -> ModifiedLayout (Decoration TabbedDecoration s) l a addTabsBottomAlways = createTabs Always Bottom -- Tab creation abstractions. Internal use only. -- Create tabbar when required at the given location with the given -- shrinker and theme to the supplied layout. createTabs ::(Eq a, LayoutClass l a, Shrinker s) => TabbarShown -> TabbarLocation -> s -> Theme -> l a -> ModifiedLayout (Decoration TabbedDecoration s) l a createTabs sh loc tx th l = decoration tx th (Tabbed loc sh) l data TabbarLocation = Top | Bottom deriving (Read,Show) data TabbarShown = Always | WhenPlural deriving (Read, Show, Eq) data TabbedDecoration a = Tabbed TabbarLocation TabbarShown deriving (Read, Show) instance Eq a => DecorationStyle TabbedDecoration a where describeDeco (Tabbed Top _ ) = "Tabbed" describeDeco (Tabbed Bottom _ ) = "Tabbed Bottom" decorationEventHook _ ds ButtonEvent { ev_window = ew , ev_event_type = et , ev_button = eb } | et == buttonPress , Just ((w,_),_) <-findWindowByDecoration ew ds = if eb == button2 then killWindow w else focus w decorationEventHook _ _ _ = return () pureDecoration (Tabbed lc sh) _ ht _ s wrs (w,r@(Rectangle x y wh hh)) = if ((sh == Always && numWindows > 0) || numWindows > 1) then Just $ case lc of Top -> upperTab Bottom -> lowerTab else Nothing where ws = filter (`elem` map fst (filter ((==r) . snd) wrs)) (S.integrate s) loc i = x + fi ((wh * fi i) `div` max 1 (fi $ length ws)) wid = fi $ maybe x (\i -> loc (i+1) - loc i) $ w `elemIndex` ws nx = maybe x loc $ w `elemIndex` ws upperTab = Rectangle nx y wid (fi ht) lowerTab = Rectangle nx (y+fi(hh-ht)) wid (fi ht) numWindows = length ws shrink (Tabbed loc _ ) (Rectangle _ _ _ dh) (Rectangle x y w h) = case loc of Top -> Rectangle x (y + fi dh) w (h - dh) Bottom -> Rectangle x y w (h - dh)
eb-gh-cr/XMonadContrib1
XMonad/Layout/Tabbed.hs
bsd-3-clause
7,253
0
17
1,724
1,591
870
721
89
1
module LAuREL.Lib (stdlib) where import Data.Functor import Data.String.Utils import LAuREL.Types import System.Random (getStdRandom, randomR) o_add :: Lib -> [Expr] -> IO Evaluated o_add lib [Type (Integer a), Type (Integer b)] = return $ Evaluated lib $ return $ Type $ Integer $ a + b o_sub :: Lib -> [Expr] -> IO Evaluated o_sub lib [Type (Integer a), Type (Integer b)] = return $ Evaluated lib $ return $ Type $ Integer $ a - b o_mul :: Lib -> [Expr] -> IO Evaluated o_mul lib [Type (Integer a), Type (Integer b)] = return $ Evaluated lib $ return $ Type $ Integer $ a * b o_forget :: Lib -> [Expr] -> IO Evaluated o_forget lib [a,b] = return $ Evaluated lib $ return b o_at :: Lib -> [Expr] -> IO Evaluated o_at lib [Type (List a), Type (Integer s)] = return $ Evaluated lib $ return $ Type (a !! s) o_pass :: Lib -> [Expr] -> IO Evaluated o_pass lib [a] = return $ Evaluated lib $ return a b_eq :: Lib -> [Expr] -> IO Evaluated b_eq lib [Type (Integer a), Type (Integer b)] = return $ Evaluated lib $ return $ Type $ Bool $ a == b b_eq lib [Type (String a), Type (String b)] = return $ Evaluated lib $ return $ Type $ Bool $ a == b b_sup :: Lib -> [Expr] -> IO Evaluated b_sup lib [Type (Integer a), Type (Integer b)] = return $ Evaluated lib $ return $ Type $ Bool $ a > b b_inf :: Lib -> [Expr] -> IO Evaluated b_inf lib [Type (Integer a), Type (Integer b)] = return $ Evaluated lib $ return $ Type $ Bool $ a < b f_print :: Lib -> [Expr] -> IO Evaluated f_print lib [Type _tg] = do { putStrLn $ show _tg; return $ Evaluated lib $ return $ Type $ None } f_input :: Lib -> [Expr] -> IO Evaluated f_input lib _ = return $ Evaluated lib $ (getLine >>= return . Type . String ) f_str_to_int :: Lib -> [Expr] -> IO Evaluated f_str_to_int lib [Type (String a)] = return $ Evaluated lib $ return $ Type $ Integer $ read a f_str_to_float :: Lib -> [Expr] -> IO Evaluated f_str_to_float lib [Type (String a)] = return $ Evaluated lib $ return $ Type $ Float $ read a f_error :: Lib -> [Expr] -> IO Evaluated f_error lib [Type (String a)] = return $ Evaluated lib $ error a f_split :: Lib -> [Expr] -> IO Evaluated f_split lib [Type (String del), Type (String str)] = return $ Evaluated lib $ return $ Type (List (map (String) sp)) where sp = split del str f_readfile :: Lib -> [Expr] -> IO Evaluated f_readfile lib [Type (String a)] = return $ Evaluated lib (readFile a >>= return . Type . String) f_random :: Lib -> [Expr] -> IO Evaluated f_random lib [Type (Integer a), Type (Integer b)] = do rand <- getStdRandom (randomR (a,b)) return $ Evaluated lib $ return $ Type $ Integer rand -- |The standard library stdlib :: Lib stdlib = Lib [ LibFunction "+" ["Integer", "Integer", "Integer"] ["a", "b"] o_add $ Just "Adds a to b", LibFunction "-" ["Integer", "Integer", "Integer"] ["a", "b"] o_sub $ Just "Sub b to a", LibFunction "*" ["Integer", "Integer", "Integer"] ["a", "b"] o_mul $ Just "Multiplies a by b", LibFunction "@" ["[String]", "Integer", "String"] ["a", "b"] o_at $ Just "Gets element b of a", LibFunction ";" ["*", "*", "*"] ["a", "b"] o_forget $ Just "Removes the previous functions value", LibFunction "==" ["Integer", "Integer", "Bool"] ["a", "b"] b_eq $ Just "Checks the equallity", LibFunction ">" ["Integer", "Integer", "Bool"] ["a", "b"] b_sup $ Just "Checks the superiority", LibFunction "<" ["Integer", "Integer", "Bool"] ["a", "b"] b_inf $ Just "Checks the superiority", LibFunction "$" ["*", "*", "*"] ["a", "b"] o_pass $ Nothing, LibFunction "str_to_int" ["String", "Integer"] ["a"] f_str_to_int $ Just "Converts string to integer", LibFunction "str_to_float" ["String", "Float"] ["a"] f_str_to_float $ Just "Converts string to float", LibFunction "split" ["*", "*", "*"] ["a", "b"] f_split $ Just "Splits b at deliminators a", LibFunction "print" ["String", "None"] ["a"] f_print $ Just "Prints a", LibFunction "input" ["String"] [] f_input $ Just "Asks for input", LibFunction "error" ["String", "*"] ["a"] f_error $ Just "Stops the program and shows the message", LibFunction "readfile" ["String", "String"] ["a"] f_readfile $ Just "Reads the givent file", LibFunction "random" ["Integer", "Integer"] ["a", "b"] f_random $ Just "Generates a random number between a and b" ]
davbaumgartner/LAuREL
LAuREL/Lib.hs
bsd-3-clause
4,398
77
11
944
1,959
1,011
948
80
1
{-# LANGUAGE OverloadedStrings #-} module Text.InjectSpec (main, spec) where import Test.Hspec import Test.Hspec.Expectations.Contrib import Text.Inject import Data.Attoparsec.Text main :: IO () main = hspec spec spec :: Spec spec = do describe "inject" $ do it "expands shell commands" $ do inject "{{echo foobar}}" `shouldReturn` "foobar\n" describe "pBraces (an internal function)" $ do it "returns content in between braces" $ do parseOnly pBraces "{{foo}bar}}" `shouldBe` Right (Braces "foo}bar") it "fails on unterminated braces" $ do parseOnly pBraces "{{foo}bar}" `shouldSatisfy` isLeft
beni55/inject
test/Text/InjectSpec.hs
mit
675
0
16
160
165
84
81
18
1
{-# LANGUAGE FlexibleContexts #-} module TW.Check where import TW.Ast import TW.BuiltIn import Control.Monad.Except import qualified Data.Map as M data DefinedType = DefinedType { dt_name :: QualTypeName , dt_args :: [TypeVar] } deriving (Show, Eq) builtInToDefTy :: BuiltIn -> DefinedType builtInToDefTy bi = DefinedType { dt_name = bi_name bi , dt_args = bi_args bi } typeDefToDefTy :: Maybe ModuleName -> TypeDef -> DefinedType typeDefToDefTy qualOwner td = let mkTy = case qualOwner of Nothing -> QualTypeName (ModuleName []) Just qt -> QualTypeName qt in case td of TypeDefEnum ed -> DefinedType (mkTy (ed_name ed)) (ed_args ed) TypeDefStruct sd -> DefinedType (mkTy (sd_name sd)) (sd_args sd) checkModules :: [Module] -> Either String [Module] checkModules modules = runExcept $ forM modules $ \m -> do let currentMStr = printModuleNameS $ m_name m defTypes <- M.fromList . map (\dt -> (dt_name dt, dt_args dt)) <$> getDefinedTypes m let isValidType args t = case t of TyVar tv -> unless (tv `elem` args) $ throwError $ "Undefined type variable " ++ show tv ++ " in " ++ currentMStr TyCon qt qtArgs -> case M.lookup qt defTypes of Nothing -> throwError $ "Undefined type variable " ++ show qt ++ " in " ++ currentMStr Just tvars -> do forM_ qtArgs (isValidType args) when (length tvars /= length qtArgs) $ throwError $ "Type " ++ show qt ++ " got applied wrong number of arguments in " ++ currentMStr checkRoute r = case r of ApiRouteDynamic t -> unless (isPathPiece t) $ throwError $ "Invalid route parameter " ++ show t ++ ". Route parameters can only be primitive types!" _ -> return () forM_ (m_typeDefs m) $ \td -> case td of TypeDefEnum ed -> forM_ (ed_choices ed) $ \ch -> forM_ (ec_arg ch) (isValidType (ed_args ed)) TypeDefStruct sd -> forM_ (sd_fields sd) $ \fld -> isValidType (sd_args sd) (sf_type fld) forM_ (m_apis m) $ \api -> forM_ (ad_endpoints api) $ \ep -> do mapM_ (isValidType []) (aed_req ep) isValidType [] (aed_resp ep) mapM_ checkRoute (aed_route ep) return m where getDefinedTypes m = do importedTypes <- forM (m_imports m) $ \im -> case M.lookup im moduleMap of Nothing -> throwError $ "Unknown module " ++ printModuleNameS im ++ " referenced from " ++ (printModuleNameS $ m_name m) Just imModel -> return $ map (typeDefToDefTy (Just im)) $ m_typeDefs imModel return $ concat importedTypes ++ (map (typeDefToDefTy Nothing) $ m_typeDefs m) ++ map builtInToDefTy allBuiltIns moduleMap = M.fromList $ map (\m -> (m_name m, m)) modules
agrafix/typed-wire
src/TW/Check.hs
mit
3,511
0
28
1,457
985
480
505
86
6
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.ECS.DeleteService -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes a specified service within a cluster. -- -- /See:/ <http://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DeleteService.html AWS API Reference> for DeleteService. module Network.AWS.ECS.DeleteService ( -- * Creating a Request deleteService , DeleteService -- * Request Lenses , dsCluster , dsService -- * Destructuring the Response , deleteServiceResponse , DeleteServiceResponse -- * Response Lenses , dsrsService , dsrsResponseStatus ) where import Network.AWS.ECS.Types import Network.AWS.ECS.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'deleteService' smart constructor. data DeleteService = DeleteService' { _dsCluster :: !(Maybe Text) , _dsService :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteService' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dsCluster' -- -- * 'dsService' deleteService :: Text -- ^ 'dsService' -> DeleteService deleteService pService_ = DeleteService' { _dsCluster = Nothing , _dsService = pService_ } -- | The name of the cluster that hosts the service you want to delete. dsCluster :: Lens' DeleteService (Maybe Text) dsCluster = lens _dsCluster (\ s a -> s{_dsCluster = a}); -- | The name of the service you want to delete. dsService :: Lens' DeleteService Text dsService = lens _dsService (\ s a -> s{_dsService = a}); instance AWSRequest DeleteService where type Rs DeleteService = DeleteServiceResponse request = postJSON eCS response = receiveJSON (\ s h x -> DeleteServiceResponse' <$> (x .?> "service") <*> (pure (fromEnum s))) instance ToHeaders DeleteService where toHeaders = const (mconcat ["X-Amz-Target" =# ("AmazonEC2ContainerServiceV20141113.DeleteService" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON DeleteService where toJSON DeleteService'{..} = object (catMaybes [("cluster" .=) <$> _dsCluster, Just ("service" .= _dsService)]) instance ToPath DeleteService where toPath = const "/" instance ToQuery DeleteService where toQuery = const mempty -- | /See:/ 'deleteServiceResponse' smart constructor. data DeleteServiceResponse = DeleteServiceResponse' { _dsrsService :: !(Maybe ContainerService) , _dsrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteServiceResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dsrsService' -- -- * 'dsrsResponseStatus' deleteServiceResponse :: Int -- ^ 'dsrsResponseStatus' -> DeleteServiceResponse deleteServiceResponse pResponseStatus_ = DeleteServiceResponse' { _dsrsService = Nothing , _dsrsResponseStatus = pResponseStatus_ } -- | Undocumented member. dsrsService :: Lens' DeleteServiceResponse (Maybe ContainerService) dsrsService = lens _dsrsService (\ s a -> s{_dsrsService = a}); -- | The response status code. dsrsResponseStatus :: Lens' DeleteServiceResponse Int dsrsResponseStatus = lens _dsrsResponseStatus (\ s a -> s{_dsrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-ecs/gen/Network/AWS/ECS/DeleteService.hs
mpl-2.0
4,320
0
13
1,023
662
392
270
88
1
{-# LANGUAGE OverloadedStrings #-} -- | Parse Składnica in the CONLL format and output lemma sentences -- which can be potentially parsed by the plTAG grammar. -- -- (The CONLL parser used below is borrowed from the Grzegorz -- Chrupala's `colada` library) import qualified Data.Text.Lazy as L import qualified Data.Text.Lazy.IO as L import Data.List.Split import qualified Data.Vector as V import Control.Monad (forM_) import System.Environment (getArgs) -- | @Token@ is a representation of a word, which consists of a number of fields. type Token = V.Vector L.Text -- | @Field@ is a part of a word token, such as word form, lemma or POS tag type Field = L.Text -- | @Sentence@ is a vector of tokens. type Sentence = V.Vector Token -- | @parse text@ returns a lazy list of sentences. parse :: L.Text -> [Sentence] parse = map V.fromList . splitWhen V.null . map (V.fromList . L.words) . L.lines ------------------------------------------------- -- Conversion ------------------------------------------------- -- | Dummy terminal type. data Term x = Term x deriving (Show) -- | Process the list (custom scanning function). process :: ([a] -> Maybe (b, [a])) -> [a] -> [b] process f xs = case f xs of Nothing -> [] Just (y, xs') -> y : process f xs' -- | Convert lemma to a grammar-consistent form . -- -- TODO: -- -- * ... -> "dots" convertWord :: [L.Text] -> Maybe (L.Text, [L.Text]) convertWord l = case l of [] -> Nothing "." : "." : "." : t -> Just ("dots", t) "." : t -> Just ("fullstop", t) "," : t -> Just ("comma", t) "?" : t -> Just ("qmark", t) "!" : t -> Just ("excl", t) ";" : t -> Just ("semicol", t) "-" : t -> Just ("hyph", t) x : t -> Just (x, t) -- convertWord :: L.Text -> L.Text -- convertWord "," = "comma" -- convertWord "." = "fullstop" -- convertWord "?" = "qmark" -- convertWord "!" = "excl" -- convertWord ";" = "semicol" -- convertWord "-" = "hyph" -- convertWord x = x -- | Convert the sentence to a form appropriate for parsing. convert :: Sentence -> [Term L.Text] convert -- = map (\x -> Term (convertWord x)) = map Term . process convertWord . map (V.! 2) . V.toList ------------------------------------------------- -- Main ------------------------------------------------- main :: IO () main = do [path] <- getArgs conts <- L.readFile path forM_ (parse conts) $ \sent -> do print $ convert sent
kawu/french-tag
tools/parse-skladnica-conll.hs
bsd-2-clause
2,436
0
12
515
612
344
268
43
9
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TupleSections #-} -- | Names for packages. module Stack.Types.PackageName (PackageName ,PackageNameParseFail(..) ,packageNameParser ,parsePackageName ,parsePackageNameFromString ,packageNameString ,packageNameText ,fromCabalPackageName ,toCabalPackageName ,parsePackageNameFromFilePath ,mkPackageName ,packageNameArgument) where import Control.Applicative import Control.DeepSeq import Control.Monad import Control.Monad.Catch import Data.Aeson.Extended import Data.Attoparsec.Combinators import Data.Attoparsec.Text import Data.Data import Data.Hashable import Data.List (intercalate) import Data.Store (Store) import Data.Text (Text) import qualified Data.Text as T import Data.Text.Binary () import qualified Distribution.Package as Cabal import GHC.Generics import Language.Haskell.TH import Language.Haskell.TH.Syntax import qualified Options.Applicative as O import Path import Stack.Types.StringError -- | A parse fail. data PackageNameParseFail = PackageNameParseFail Text | CabalFileNameParseFail FilePath | CabalFileNameInvalidPackageName FilePath deriving (Typeable) instance Exception PackageNameParseFail instance Show PackageNameParseFail where show (PackageNameParseFail bs) = "Invalid package name: " ++ show bs show (CabalFileNameParseFail fp) = "Invalid file path for cabal file, must have a .cabal extension: " ++ fp show (CabalFileNameInvalidPackageName fp) = "cabal file names must use valid package names followed by a .cabal extension, the following is invalid: " ++ fp -- | A package name. newtype PackageName = PackageName Text deriving (Eq,Ord,Typeable,Data,Generic,Hashable,NFData,Store,ToJSON,ToJSONKey) instance Lift PackageName where lift (PackageName n) = appE (conE 'PackageName) (stringE (T.unpack n)) instance Show PackageName where show (PackageName n) = T.unpack n instance FromJSON PackageName where parseJSON j = do s <- parseJSON j case parsePackageNameFromString s of Nothing -> fail ("Couldn't parse package name: " ++ s) Just ver -> return ver instance FromJSONKey PackageName where fromJSONKey = FromJSONKeyTextParser $ \k -> either (fail . show) return $ parsePackageName k -- | Attoparsec parser for a package name packageNameParser :: Parser PackageName packageNameParser = fmap (PackageName . T.pack . intercalate "-") (sepBy1 word (char '-')) where word = concat <$> sequence [many digit, pured letter, many (alternating letter digit)] -- | Make a package name. mkPackageName :: String -> Q Exp mkPackageName s = case parsePackageNameFromString s of Nothing -> errorString ("Invalid package name: " ++ show s) Just pn -> [|pn|] -- | Parse a package name from a 'Text'. parsePackageName :: MonadThrow m => Text -> m PackageName parsePackageName x = go x where go = either (const (throwM (PackageNameParseFail x))) return . parseOnly (packageNameParser <* endOfInput) -- | Parse a package name from a 'String'. parsePackageNameFromString :: MonadThrow m => String -> m PackageName parsePackageNameFromString = parsePackageName . T.pack -- | Produce a string representation of a package name. packageNameString :: PackageName -> String packageNameString (PackageName n) = T.unpack n -- | Produce a string representation of a package name. packageNameText :: PackageName -> Text packageNameText (PackageName n) = n -- | Convert from a Cabal package name. fromCabalPackageName :: Cabal.PackageName -> PackageName fromCabalPackageName (Cabal.PackageName name) = let !x = T.pack name in PackageName x -- | Convert to a Cabal package name. toCabalPackageName :: PackageName -> Cabal.PackageName toCabalPackageName (PackageName name) = let !x = T.unpack name in Cabal.PackageName x -- | Parse a package name from a file path. parsePackageNameFromFilePath :: MonadThrow m => Path a File -> m PackageName parsePackageNameFromFilePath fp = do base <- clean $ toFilePath $ filename fp case parsePackageNameFromString base of Nothing -> throwM $ CabalFileNameInvalidPackageName $ toFilePath fp Just x -> return x where clean = liftM reverse . strip . reverse strip ('l':'a':'b':'a':'c':'.':xs) = return xs strip _ = throwM (CabalFileNameParseFail (toFilePath fp)) -- | An argument which accepts a template name of the format -- @foo.hsfiles@. packageNameArgument :: O.Mod O.ArgumentFields PackageName -> O.Parser PackageName packageNameArgument = O.argument (do s <- O.str either O.readerError return (p s)) where p s = case parsePackageNameFromString s of Just x -> Right x Nothing -> Left $ unlines [ "Expected valid package name, but got: " ++ s , "Package names consist of one or more alphanumeric words separated by hyphens." , "To avoid ambiguity with version numbers, each of these words must contain at least one letter." ]
mrkkrp/stack
src/Stack/Types/PackageName.hs
bsd-3-clause
5,511
0
14
1,276
1,221
639
582
124
3
{-# LANGUAGE DeriveGeneric #-} module System.Console.GetOpt.Generics.ModifierSpec where import qualified GHC.Generics import Generics.SOP import Test.Hspec import System.Console.GetOpt.Generics.Modifier import Util spec :: Spec spec = do describe "insertWith" $ do it "combines existing values with the given function" $ do insertWith (++) (1 :: Integer) "bar" [(1, "foo")] `shouldBe` [(1, "foobar")] describe "getVersion" $ do it "returns the version" $ do let modifiers = unsafeModifiers [AddVersionFlag "1.0.0"] getVersion modifiers `shouldBe` Just "1.0.0" data Foo = Foo { bar :: String } deriving (GHC.Generics.Generic) instance Generic Foo instance HasDatatypeInfo Foo data Overlap = Overlap { foo :: String, fooo :: String } deriving (GHC.Generics.Generic) instance Generic Overlap instance HasDatatypeInfo Overlap
kosmikus/getopt-generics
test/System/Console/GetOpt/Generics/ModifierSpec.hs
bsd-3-clause
933
0
18
218
248
136
112
30
1
{- | Module : $Header$ Copyright : (c) Till Mossakowski, Wiebke Herding, C. Maeder, Uni Bremen 2004 License : GPLv2 or higher, see LICENSE.txt Maintainer : luecke@informatik.uni-bremen.de Stability : provisional Portability : portable Parser for modal logic extension of CASL -} module Hybrid.Parse_AS where import CASL.Formula import CASL.OpItem import Common.AS_Annotation import Common.AnnoState import Common.Id import Common.Keywords import Common.Lexer import Common.Token import Hybrid.AS_Hybrid import Hybrid.Keywords import Text.ParserCombinators.Parsec hybrid_reserved_words :: [String] hybrid_reserved_words = [ diamondS, termS, rigidS, flexibleS, modalityS, modalitiesS, nominalS, nominalsS] hybridFormula :: AParser st H_FORMULA hybridFormula = do a <- asKey hereP n <- nominal return (Here n $ toRange a [] a) <|> do a <- asKey asP n <- nominal f <- primFormula hybrid_reserved_words return (At n f $ toRange a [] a) <|> do a <- asKey exMark n <- nominal f <- primFormula hybrid_reserved_words return (Univ n f $ toRange a [] a) <|> do a <- asKey "?" n <- nominal f <- primFormula hybrid_reserved_words return (Exist n f $ toRange a [] a) <|> do o <- oBracketT m <- modality [] c <- cBracketT f <- primFormula hybrid_reserved_words return (BoxOrDiamond True m f $ toRange o [] c) <|> do o <- asKey lessS m <- modality [greaterS] -- do not consume matching ">"! c <- asKey greaterS f <- primFormula hybrid_reserved_words return (BoxOrDiamond False m f $ toRange o [] c) nominal :: AParser st NOMINAL nominal = do n <- simpleId return (Simple_nom n) modality :: [String] -> AParser st MODALITY modality ks = do t <- term (ks ++ hybrid_reserved_words) return $ Term_mod t instance TermParser H_FORMULA where termParser = aToTermParser hybridFormula rigor :: AParser st RIGOR rigor = (asKey rigidS >> return Rigid) <|> (asKey flexibleS >> return Flexible) rigidSigItems :: AParser st H_SIG_ITEM rigidSigItems = do r <- rigor itemList hybrid_reserved_words opS opItem (Rigid_op_items r) <|> itemList hybrid_reserved_words predS predItem (Rigid_pred_items r) instance AParsable H_SIG_ITEM where aparser = rigidSigItems hKey :: AParser st Token hKey = asKey modalityS <|> asKey modalitiesS hKey' :: AParser st Token hKey' = asKey nominalS <|> asKey nominalsS hBasic :: AParser st H_BASIC_ITEM hBasic = do (as, fs, ps) <- hItem'' hKey simpleId return (Simple_mod_decl as fs ps) <|> do (as, fs, ps) <- hItem'' hKey' simpleId return (Simple_nom_decl as fs ps) hItem'' :: AParser st Token -> AParser st a -> AParser st ([Annoted a], [AnHybFORM], Range) hItem'' k pr = do c <- k (as, cs) <- separatedBy (annoParser pr) anSemiOrComma let ps = catRange $ c : cs return (as, [], ps) instance AParsable H_BASIC_ITEM where aparser = hBasic
mariefarrell/Hets
Hybrid/Parse_AS.hs
gpl-2.0
3,268
0
16
960
973
472
501
101
1
-- Refactoring: move myFringe to module D6. This refactoring test the adding of hiding -- in the import declaration (see module B6), and the adding the import decl and the change -- of qualifiers. module C6(Tree(..), SameOrNot(..)) where data Tree a = Leaf a | Branch (Tree a) (Tree a) sumTree:: (Num a) => Tree a -> a sumTree (Leaf x ) = x sumTree (Branch left right) = sumTree left + sumTree right class SameOrNot a where isSame :: a -> a -> Bool isNotSame :: a -> a -> Bool instance SameOrNot Int where isSame a b = a == b isNotSame a b = a /= b
SAdams601/HaRe
old/testing/moveDefBtwMods/C6_TokOut.hs
bsd-3-clause
577
0
8
137
184
99
85
11
1
{-# LANGUAGE TypeApplications, ScopedTypeVariables, PolyKinds, TypeFamilies, RankNTypes, FlexibleContexts #-} -- tests about visible type application module Vta1 where quad :: a -> b -> c -> d -> (a, b, c, d) quad = (,,,) silly = quad @_ @Bool @Char @_ 5 True 'a' "Hello" pairup_nosig x y = (x, y) pairup_sig :: a -> b -> (a,b) pairup_sig u w = (u, w) answer_sig = pairup_sig @Bool @Int False 7 -- -- (False, 7) :: (Bool, Int) answer_read = show (read @Int "3") -- "3" :: String answer_show = show @Integer (read "5") -- "5" :: String answer_showread = show @Int (read @Int "7") -- "7" :: String intcons a = (:) @Int a intpair x y = pairup_sig @Int x y answer_pairup = pairup_sig @Int 5 True -- (5, True) :: (Int, Bool) answer_intpair = intpair 1 "hello" -- (1, "hello") :: (Int, String) answer_intcons = intcons 7 [] -- [7] :: [Int] type family F a type instance F Char = Bool g :: F a -> a g _ = undefined f :: Char f = g True answer = g @Char False mapSame :: forall b. (forall a. a -> a) -> [b] -> [b] mapSame _ [] = [] mapSame fun (x:xs) = fun @b x : (mapSame @b fun xs) pair :: forall a. a-> (forall b. b -> (a, b)) pair x y = (x, y) b = pair @Int 3 @Bool True c = mapSame id [1,2,3] d = pair 3 @Bool True pairnum :: forall a. Num a => forall b. b -> (a, b) pairnum = pair 3 e = (pair 3 :: forall a. Num a => forall b. b -> (a, b)) @Int @Bool True h = pairnum @Int @Bool True data First (a :: * -> *) = F data Proxy (a :: k) = P -- This expands to P (kind variable) (type variable) data Three (a :: * -> k -> *) = T foo :: Proxy a -> Int foo _ = 0 first :: First a -> Int first _ = 0 fTest = first F fMaybe = first @Maybe F test = foo P bar = foo @Bool P -- should work too :: Three a -> Int too _ = 3 threeBase = too T threeOk = too @Either T blah = Nothing @Int newtype N = MkN { unMkN :: forall a. Show a => a -> String } n = MkN show boo = unMkN n @Bool boo2 :: forall (a :: * -> *) . Proxy a -> Bool boo2 _ = False base = boo2 P bar'= boo2 @Maybe P -- should work
olsner/ghc
testsuite/tests/typecheck/should_compile/Vta1.hs
bsd-3-clause
2,038
0
11
511
935
508
427
61
1
module Test where import Test2 hiding (main) main = doit
wxwxwwxxx/ghc
testsuite/tests/driver/T437/Test.hs
bsd-3-clause
60
0
5
13
18
12
6
3
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ConstraintKinds #-} module Futhark.Representation.SOACS.SOAC ( SOAC(..) , StreamForm(..) , typeCheckSOAC -- * Utility , getStreamOrder , getStreamAccums -- * Generic traversal , SOACMapper(..) , identitySOACMapper , mapSOACM ) where import Control.Applicative import Control.Monad.Writer import Control.Monad.Identity import qualified Data.Map.Strict as M import qualified Data.Set as S import Data.Maybe import Data.List import Prelude import Futhark.Representation.AST import qualified Futhark.Analysis.Alias as Alias import qualified Futhark.Util.Pretty as PP import Futhark.Util.Pretty ((</>), ppr, comma, commasep, Doc, Pretty, parens, text) import Futhark.Representation.AST.Attributes.Aliases import Futhark.Transform.Substitute import Futhark.Transform.Rename import Futhark.Optimise.Simplifier.Lore import Futhark.Representation.Ranges (Ranges, removeLambdaRanges, removeExtLambdaRanges) import Futhark.Representation.AST.Attributes.Ranges import Futhark.Representation.Aliases (Aliases, removeLambdaAliases, removeExtLambdaAliases) import Futhark.Analysis.Usage import qualified Futhark.Analysis.SymbolTable as ST import Futhark.Analysis.PrimExp.Convert import qualified Futhark.TypeCheck as TC import Futhark.Analysis.Metrics import qualified Futhark.Analysis.Range as Range import Futhark.Util (maybeNth) data SOAC lore = Map SubExp (LambdaT lore) [VName] | Reduce SubExp Commutativity (LambdaT lore) [(SubExp, VName)] | Scan SubExp (LambdaT lore) [(SubExp, VName)] -- ^ @Scan cs w lam input@ where @(nes, arrs) = unzip input@. -- -- Performs an inclusive scan on the input arrays @arrs@ (that must all have -- outer length @w@), using the binary operator defined in @lam@ and the -- neutral elements @nes@. -- -- Inclusive scan means the result from scanning array @xs@ with operator @op@ -- will be @[xs[0], xs[0] op xs[1], ..., x0 op x1 op ... op x[w-1] ]@ | Redomap SubExp Commutativity (LambdaT lore) (LambdaT lore) [SubExp] [VName] | Scanomap SubExp (LambdaT lore) (LambdaT lore) [SubExp] [VName] | Stream SubExp (StreamForm lore) (ExtLambdaT lore) [VName] | Scatter SubExp (LambdaT lore) [VName] [(SubExp, VName)] -- Scatter <cs> <length> <lambda> <original index and value arrays> -- <input/output arrays along with their sizes> -- -- <length> is the length of each index array and value array, since they -- all must be the same length for any fusion to make sense. If you have a -- list of index-value array pairs of different sizes, you need to use -- multiple writes instead. -- -- The lambda body returns the output in this manner: -- -- [index_0, index_1, ..., index_n, value_0, value_1, ..., value_n] -- -- This must be consistent along all Scatter-related optimisations. -- -- The original index arrays and value arrays are concatenated. deriving (Eq, Ord, Show) data StreamForm lore = Parallel StreamOrd Commutativity (LambdaT lore) [SubExp] | Sequential [SubExp] deriving (Eq, Ord, Show) -- | Like 'Mapper', but just for 'SOAC's. data SOACMapper flore tlore m = SOACMapper { mapOnSOACSubExp :: SubExp -> m SubExp , mapOnSOACLambda :: Lambda flore -> m (Lambda tlore) , mapOnSOACExtLambda :: ExtLambda flore -> m (ExtLambda tlore) , mapOnSOACVName :: VName -> m VName } -- | A mapper that simply returns the SOAC verbatim. identitySOACMapper :: Monad m => SOACMapper lore lore m identitySOACMapper = SOACMapper { mapOnSOACSubExp = return , mapOnSOACLambda = return , mapOnSOACExtLambda = return , mapOnSOACVName = return } -- | Map a monadic action across the immediate children of a -- SOAC. The mapping does not descend recursively into subexpressions -- and is done left-to-right. mapSOACM :: (Applicative m, Monad m) => SOACMapper flore tlore m -> SOAC flore -> m (SOAC tlore) mapSOACM tv (Map w lam arrs) = Map <$> mapOnSOACSubExp tv w <*> mapOnSOACLambda tv lam <*> mapM (mapOnSOACVName tv) arrs mapSOACM tv (Reduce w comm lam input) = Reduce <$> mapOnSOACSubExp tv w <*> pure comm <*> mapOnSOACLambda tv lam <*> (zip <$> mapM (mapOnSOACSubExp tv) nes <*> mapM (mapOnSOACVName tv) arrs) where (nes, arrs) = unzip input mapSOACM tv (Scan w lam input) = Scan <$> mapOnSOACSubExp tv w <*> mapOnSOACLambda tv lam <*> (zip <$> mapM (mapOnSOACSubExp tv) nes <*> mapM (mapOnSOACVName tv) arrs) where (nes, arrs) = unzip input mapSOACM tv (Redomap w comm lam0 lam1 nes arrs) = Redomap <$> mapOnSOACSubExp tv w <*> pure comm <*> mapOnSOACLambda tv lam0 <*> mapOnSOACLambda tv lam1 <*> mapM (mapOnSOACSubExp tv) nes <*> mapM (mapOnSOACVName tv) arrs mapSOACM tv (Scanomap w lam0 lam1 nes arrs) = Scanomap <$> mapOnSOACSubExp tv w <*> mapOnSOACLambda tv lam0 <*> mapOnSOACLambda tv lam1 <*> mapM (mapOnSOACSubExp tv) nes <*> mapM (mapOnSOACVName tv) arrs mapSOACM tv (Stream size form lam arrs) = Stream <$> mapOnSOACSubExp tv size <*> mapOnStreamForm form <*> mapOnSOACExtLambda tv lam <*> mapM (mapOnSOACVName tv) arrs where mapOnStreamForm (Parallel o comm lam0 acc) = Parallel <$> pure o <*> pure comm <*> mapOnSOACLambda tv lam0 <*> mapM (mapOnSOACSubExp tv) acc mapOnStreamForm (Sequential acc) = Sequential <$> mapM (mapOnSOACSubExp tv) acc mapSOACM tv (Scatter len lam ivs as) = Scatter <$> mapOnSOACSubExp tv len <*> mapOnSOACLambda tv lam <*> mapM (mapOnSOACVName tv) ivs <*> mapM (\(aw,a) -> (,) <$> mapOnSOACSubExp tv aw <*> mapOnSOACVName tv a) as instance Attributes lore => FreeIn (SOAC lore) where freeIn = execWriter . mapSOACM free where walk f x = tell (f x) >> return x free = SOACMapper { mapOnSOACSubExp = walk freeIn , mapOnSOACLambda = walk freeInLambda , mapOnSOACExtLambda = walk freeInExtLambda , mapOnSOACVName = walk freeIn } instance Attributes lore => Substitute (SOAC lore) where substituteNames subst = runIdentity . mapSOACM substitute where substitute = SOACMapper { mapOnSOACSubExp = return . substituteNames subst , mapOnSOACLambda = return . substituteNames subst , mapOnSOACExtLambda = return . substituteNames subst , mapOnSOACVName = return . substituteNames subst } instance Attributes lore => Rename (SOAC lore) where rename = mapSOACM renamer where renamer = SOACMapper rename rename rename rename soacType :: SOAC lore -> [ExtType] soacType (Map size f _) = staticShapes $ mapType size f soacType (Reduce _ _ fun _) = staticShapes $ lambdaReturnType fun soacType (Scan width lam _) = staticShapes $ map (`arrayOfRow` width) $ lambdaReturnType lam soacType (Redomap outersize _ outerfun innerfun _ _) = staticShapes $ let acc_tp = lambdaReturnType outerfun acc_el_tp = lambdaReturnType innerfun res_el_tp = drop (length acc_tp) acc_el_tp in case res_el_tp of [] -> acc_tp _ -> acc_tp ++ map (`arrayOfRow` outersize) res_el_tp soacType (Scanomap outersize outerfun innerfun _ _) = staticShapes $ let acc_tp = map (`arrayOfRow` outersize) $ lambdaReturnType outerfun acc_el_tp = lambdaReturnType innerfun res_el_tp = drop (length acc_tp) acc_el_tp in case res_el_tp of [] -> acc_tp _ -> acc_tp ++ map (`arrayOfRow` outersize) res_el_tp soacType (Stream outersize form lam _) = map (substNamesInExtType substs) rtp where nms = map paramName $ take (1 + length accs) params substs = M.fromList $ zip nms (outersize:accs) ExtLambda params _ rtp = lam accs = case form of Parallel _ _ _ acc -> acc Sequential acc -> acc soacType (Scatter _w lam _ivs as) = staticShapes $ zipWith arrayOfRow (snd $ splitAt (n `div` 2) lam_ts) ws where lam_ts = lambdaReturnType lam n = length lam_ts ws = map fst as instance TypedOp (SOAC lore) where opType = pure . soacType instance (Attributes lore, Aliased lore) => AliasedOp (SOAC lore) where opAliases (Map _ f _) = map (const mempty) $ lambdaReturnType f opAliases (Reduce _ _ f _) = map (const mempty) $ lambdaReturnType f opAliases (Scan _ f _) = map (const mempty) $ lambdaReturnType f opAliases (Redomap _ _ _ innerfun _ _) = map (const mempty) $ lambdaReturnType innerfun opAliases (Scanomap _ _ innerfun _ _) = map (const mempty) $ lambdaReturnType innerfun opAliases (Stream _ form lam _) = let a1 = case form of Parallel _ _ lam0 _ -> map (const mempty) $ lambdaReturnType lam0 Sequential _ -> [] in a1 ++ map (const mempty) (extLambdaReturnType lam) opAliases (Scatter _len lam _ivs _as) = map (const mempty) $ lambdaReturnType lam -- Only Map, Redomap and Stream can consume anything. The operands -- to Scan and Reduce functions are always considered "fresh". consumedInOp (Map _ lam arrs) = S.map consumedArray $ consumedByLambda lam where consumedArray v = fromMaybe v $ lookup v params_to_arrs params_to_arrs = zip (map paramName (lambdaParams lam)) arrs consumedInOp (Redomap _ _ foldlam _ nes arrs) = S.map consumedArray $ consumedByLambda foldlam where consumedArray v = fromMaybe v $ lookup v params_to_arrs params_to_arrs = zip (map paramName $ drop (length nes) (lambdaParams foldlam)) arrs consumedInOp (Stream _ form lam arrs) = S.fromList $ subExpVars $ case form of Sequential accs -> map (consumedArray accs) $ S.toList $ consumedByExtLambda lam Parallel _ _ _ accs -> map (consumedArray accs) $ S.toList $ consumedByExtLambda lam where consumedArray accs v = fromMaybe (Var v) $ lookup v $ paramsToInput accs -- Drop the chunk parameter, which cannot alias anything. paramsToInput accs = zip (map paramName $ drop 1 $ extLambdaParams lam) (accs++map Var arrs) consumedInOp (Scatter _ _ _ as) = S.fromList $ map snd as consumedInOp _ = mempty instance (Attributes lore, Attributes (Aliases lore), CanBeAliased (Op lore)) => CanBeAliased (SOAC lore) where type OpWithAliases (SOAC lore) = SOAC (Aliases lore) addOpAliases (Map size lam args) = Map size (Alias.analyseLambda lam) args addOpAliases (Reduce size comm lam input) = Reduce size comm (Alias.analyseLambda lam) input addOpAliases (Scan size lam input) = Scan size (Alias.analyseLambda lam) input addOpAliases (Redomap size comm outerlam innerlam acc arr) = Redomap size comm (Alias.analyseLambda outerlam) (Alias.analyseLambda innerlam) acc arr addOpAliases (Scanomap size outerlam innerlam acc arr) = Scanomap size (Alias.analyseLambda outerlam) (Alias.analyseLambda innerlam) acc arr addOpAliases (Stream size form lam arr) = Stream size (analyseStreamForm form) (Alias.analyseExtLambda lam) arr where analyseStreamForm (Parallel o comm lam0 acc) = Parallel o comm (Alias.analyseLambda lam0) acc analyseStreamForm (Sequential acc) = Sequential acc addOpAliases (Scatter len lam ivs as) = Scatter len (Alias.analyseLambda lam) ivs as removeOpAliases = runIdentity . mapSOACM remove where remove = SOACMapper return (return . removeLambdaAliases) (return . removeExtLambdaAliases) return instance Attributes lore => IsOp (SOAC lore) where safeOp _ = False cheapOp _ = True substNamesInExtType :: M.Map VName SubExp -> ExtType -> ExtType substNamesInExtType _ tp@(Prim _) = tp substNamesInExtType subs (Mem se space) = Mem (substNamesInSubExp subs se) space substNamesInExtType subs (Array btp shp u) = let shp' = Shape $ map (substNamesInExtSize subs) (shapeDims shp) in Array btp shp' u substNamesInSubExp :: M.Map VName SubExp -> SubExp -> SubExp substNamesInSubExp _ e@(Constant _) = e substNamesInSubExp subs (Var idd) = M.findWithDefault (Var idd) idd subs substNamesInExtSize :: M.Map VName SubExp -> ExtSize -> ExtSize substNamesInExtSize _ (Ext o) = Ext o substNamesInExtSize subs (Free o) = Free $ substNamesInSubExp subs o instance (Ranged inner) => RangedOp (SOAC inner) where opRanges op = replicate (length $ soacType op) unknownRange instance (Attributes lore, CanBeRanged (Op lore)) => CanBeRanged (SOAC lore) where type OpWithRanges (SOAC lore) = SOAC (Ranges lore) removeOpRanges = runIdentity . mapSOACM remove where remove = SOACMapper return (return . removeLambdaRanges) (return . removeExtLambdaRanges) return addOpRanges (Map w lam args) = Map w (Range.runRangeM $ Range.analyseLambda lam) args addOpRanges (Reduce w comm lam input) = Reduce w comm (Range.runRangeM $ Range.analyseLambda lam) input addOpRanges (Scan w lam input) = Scan w (Range.runRangeM $ Range.analyseLambda lam) input addOpRanges (Redomap w comm outerlam innerlam acc arr) = Redomap w comm (Range.runRangeM $ Range.analyseLambda outerlam) (Range.runRangeM $ Range.analyseLambda innerlam) acc arr addOpRanges (Scanomap w outerlam innerlam acc arr) = Scanomap w (Range.runRangeM $ Range.analyseLambda outerlam) (Range.runRangeM $ Range.analyseLambda innerlam) acc arr addOpRanges (Stream w form lam arr) = Stream w (Range.runRangeM $ analyseStreamForm form) (Range.runRangeM $ Range.analyseExtLambda lam) arr where analyseStreamForm (Sequential acc) = return $ Sequential acc analyseStreamForm (Parallel o comm lam0 acc) = do lam0' <- Range.analyseLambda lam0 return $ Parallel o comm lam0' acc addOpRanges (Scatter len lam ivs as) = Scatter len (Range.runRangeM $ Range.analyseLambda lam) ivs as instance (Attributes lore, CanBeWise (Op lore)) => CanBeWise (SOAC lore) where type OpWithWisdom (SOAC lore) = SOAC (Wise lore) removeOpWisdom = runIdentity . mapSOACM remove where remove = SOACMapper return (return . removeLambdaWisdom) (return . removeExtLambdaWisdom) return instance Annotations lore => ST.IndexOp (SOAC lore) where indexOp vtable k soac [i] = do (lam,se,arr_params,arrs) <- lambdaAndSubExp soac let arr_indexes = M.fromList $ catMaybes $ zipWith arrIndex arr_params arrs arr_indexes' = foldl expandPrimExpTable arr_indexes $ bodyStms $ lambdaBody lam case se of Var v -> M.lookup v arr_indexes' _ -> Nothing where lambdaAndSubExp (Map _ lam arrs) = nthMapOut 0 lam arrs lambdaAndSubExp (Redomap _ _ _ lam nes arrs) = nthMapOut (length nes) lam arrs lambdaAndSubExp _ = Nothing nthMapOut num_accs lam arrs = do se <- maybeNth (num_accs+k) $ bodyResult $ lambdaBody lam return (lam, se, drop num_accs $ lambdaParams lam, arrs) arrIndex p arr = do (pe,cs) <- ST.index' arr [i] vtable return (paramName p, (pe,cs)) expandPrimExpTable table stm | [v] <- patternNames $ stmPattern stm, Just (pe,cs) <- runWriterT $ primExpFromExp (asPrimExp table) $ stmExp stm, all (`ST.elem` vtable) (unCertificates $ stmCerts stm) = M.insert v (pe, stmCerts stm <> cs) table | otherwise = table asPrimExp table (BasicOp (SubExp (Var v))) | Just (e,cs) <- M.lookup v table = tell cs >> return e | Just (Prim pt) <- ST.lookupType v vtable = return $ LeafExp v pt asPrimExp _ (BasicOp (SubExp (Constant v))) = return $ ValueExp v asPrimExp _ _ = lift Nothing indexOp _ _ _ _ = Nothing instance Aliased lore => UsageInOp (SOAC lore) where usageInOp (Map _ f arrs) = usageInLambda f arrs usageInOp (Redomap _ _ _ f _ arrs) = usageInLambda f arrs usageInOp _ = mempty typeCheckSOAC :: TC.Checkable lore => SOAC (Aliases lore) -> TC.TypeM lore () typeCheckSOAC (Map size fun arrexps) = do TC.require [Prim int32] size arrargs <- TC.checkSOACArrayArgs size arrexps TC.checkLambda fun arrargs typeCheckSOAC (Redomap size _ outerfun innerfun accexps arrexps) = typeCheckScanomapRedomap size outerfun innerfun accexps arrexps typeCheckSOAC (Scanomap size outerfun innerfun accexps arrexps) = typeCheckScanomapRedomap size outerfun innerfun accexps arrexps typeCheckSOAC (Stream size form lam arrexps) = do let accexps = getStreamAccums form TC.require [Prim int32] size accargs <- mapM TC.checkArg accexps arrargs <- mapM lookupType arrexps _ <- TC.checkSOACArrayArgs size arrexps let chunk = head $ extLambdaParams lam let asArg t = (t, mempty) inttp = Prim int32 lamarrs'= map (`setOuterSize` Var (paramName chunk)) arrargs let acc_len= length accexps let lamrtp = take acc_len $ extLambdaReturnType lam unless (staticShapes (map TC.argType accargs) == lamrtp) $ TC.bad $ TC.TypeError "Stream with inconsistent accumulator type in lambda." -- check reduce's lambda, if any _ <- case form of Parallel _ _ lam0 _ -> do let acct = map TC.argType accargs outerRetType = lambdaReturnType lam0 TC.checkLambda lam0 $ map TC.noArgAliases $ accargs ++ accargs unless (acct == outerRetType) $ TC.bad $ TC.TypeError $ "Initial value is of type " ++ prettyTuple acct ++ ", but stream's reduce lambda returns type " ++ prettyTuple outerRetType ++ "." _ -> return () -- just get the dflow of lambda on the fakearg, which does not alias -- arr, so we can later check that aliases of arr are not used inside lam. let fake_lamarrs' = map asArg lamarrs' TC.checkExtLambda lam $ asArg inttp : accargs ++ fake_lamarrs' -- check outerdim of Lambda's streamed-in array params are NOT specified, -- and that return type inner dimens are all specified but not as other -- lambda parameters! let lamarr_rtp = drop acc_len $ extLambdaReturnType lam lamarr_ptp = map paramType $ drop (acc_len+1) $ extLambdaParams lam names_lamparams = S.fromList $ map paramName $ extLambdaParams lam _ <- mapM (checkOuterDim (paramName chunk) . head . shapeDims . arrayShape) lamarr_ptp _ <- mapM (checkInnerDim names_lamparams . tail . shapeDims . arrayShape) lamarr_rtp return () where checkOuterDim chunknm outdim = do let chunk_str = pretty chunknm case outdim of Constant _ -> TC.bad $ TC.TypeError ("Stream: outer dimension of stream should NOT"++ " be specified since it is "++chunk_str++"by default.") Var idd -> unless (idd == chunknm) $ TC.bad $ TC.TypeError ("Stream: outer dimension of stream should NOT"++ " be specified since it is "++chunk_str++"by default.") boundDim (Free (Var idd)) = return $ Just idd boundDim (Free _ ) = return Nothing boundDim (Ext _ ) = TC.bad $ TC.TypeError $ "Stream's lambda: inner dimensions of the"++ " streamed-out arrays MUST be specified!" checkInnerDim lamparnms innerdims = do rtp_iner_syms <- catMaybes <$> mapM boundDim innerdims case find (`S.member` lamparnms) rtp_iner_syms of Just name -> TC.bad $ TC.TypeError $ "Stream's lambda: " ++ pretty name ++ " cannot specify an inner result shape" _ -> return True typeCheckSOAC (Scatter w lam ivs as) = do -- Requirements: -- -- 0. @lambdaReturnType@ of @lam@ must be a list -- [index types..., value types]. -- -- 1. The number of index types must be equal to the number of value types -- and the number of arrays in @as@. -- -- 2. Each index type must have the type i32. -- -- 3. Each array pair in @as@ and the value types must have the same type -- -- 4. Each array in @as@ is consumed. This is not really a check, but more -- of a requirement, so that e.g. the source is not hoisted out of a -- loop, which will mean it cannot be consumed. -- -- 5. Each of ivs must be an array matching a corresponding lambda -- parameters. -- -- Code: -- First check the input size. TC.require [Prim int32] w -- 0. let rts = lambdaReturnType lam rtsLen = length rts `div` 2 rtsI = take rtsLen rts rtsV = drop rtsLen rts -- 1. unless (rtsLen == length as) $ TC.bad $ TC.TypeError "Scatter: Uneven number of index types, value types, and I/O arrays." -- 2. forM_ rtsI $ \rtI -> unless (Prim int32 == rtI) $ TC.bad $ TC.TypeError "Scatter: Index return type must be i32." forM_ (zip rtsV as) $ \(rtV, (aw, a)) -> do -- All lengths must have type i32. TC.require [Prim int32] aw -- 3. TC.requireI [rtV `arrayOfRow` aw] a -- 4. TC.consume =<< TC.lookupAliases a -- 5. arrargs <- TC.checkSOACArrayArgs w ivs TC.checkLambda lam arrargs typeCheckSOAC (Reduce size _ fun inputs) = typeCheckScanReduce size fun inputs typeCheckSOAC (Scan size fun inputs) = typeCheckScanReduce size fun inputs typeCheckScanReduce :: TC.Checkable lore => SubExp -> Lambda (Aliases lore) -> [(SubExp, VName)] -> TC.TypeM lore () typeCheckScanReduce size fun inputs = do let (startexps, arrexps) = unzip inputs TC.require [Prim int32] size startargs <- mapM TC.checkArg startexps arrargs <- TC.checkSOACArrayArgs size arrexps TC.checkLambda fun $ map TC.noArgAliases $ startargs ++ arrargs let startt = map TC.argType startargs intupletype = map TC.argType arrargs funret = lambdaReturnType fun unless (startt == funret) $ TC.bad $ TC.TypeError $ "Initial value is of type " ++ prettyTuple startt ++ ", but function returns type " ++ prettyTuple funret ++ "." unless (intupletype == funret) $ TC.bad $ TC.TypeError $ "Array element value is of type " ++ prettyTuple intupletype ++ ", but function returns type " ++ prettyTuple funret ++ "." typeCheckScanomapRedomap :: TC.Checkable lore => SubExp -> Lambda (Aliases lore) -> Lambda (Aliases lore) -> [SubExp] -> [VName] -> TC.TypeM lore () typeCheckScanomapRedomap size outerfun innerfun accexps arrexps = do TC.require [Prim int32] size arrargs <- TC.checkSOACArrayArgs size arrexps accargs <- mapM TC.checkArg accexps TC.checkLambda innerfun $ map TC.noArgAliases accargs ++ arrargs let innerRetType = lambdaReturnType innerfun innerAccType = take (length accexps) innerRetType asArg t = (t, mempty) TC.checkLambda outerfun $ map asArg $ innerAccType ++ innerAccType let acct = map TC.argType accargs outerRetType = lambdaReturnType outerfun unless (acct == innerAccType ) $ TC.bad $ TC.TypeError $ "Initial value is of type " ++ prettyTuple acct ++ ", but reduction function returns type " ++ prettyTuple innerRetType ++ "." unless (acct == outerRetType) $ TC.bad $ TC.TypeError $ "Initial value is of type " ++ prettyTuple acct ++ ", but fold function returns type " ++ prettyTuple outerRetType ++ "." -- | Get Stream's accumulators as a sub-expression list getStreamAccums :: StreamForm lore -> [SubExp] getStreamAccums (Parallel _ _ _ accs) = accs getStreamAccums (Sequential accs) = accs getStreamOrder :: StreamForm lore -> StreamOrd getStreamOrder (Parallel o _ _ _) = o getStreamOrder (Sequential _) = InOrder instance OpMetrics (Op lore) => OpMetrics (SOAC lore) where opMetrics (Map _ fun _) = inside "Map" $ lambdaMetrics fun opMetrics (Reduce _ _ fun _) = inside "Reduce" $ lambdaMetrics fun opMetrics (Scan _ fun _) = inside "Scan" $ lambdaMetrics fun opMetrics (Redomap _ _ fun1 fun2 _ _) = inside "Redomap" $ lambdaMetrics fun1 >> lambdaMetrics fun2 opMetrics (Scanomap _ fun1 fun2 _ _) = inside "Scanomap" $ lambdaMetrics fun1 >> lambdaMetrics fun2 opMetrics (Stream _ _ lam _) = inside "Stream" $ extLambdaMetrics lam opMetrics (Scatter _len lam _ivs _as) = inside "Scatter" $ lambdaMetrics lam extLambdaMetrics :: OpMetrics (Op lore) => ExtLambda lore -> MetricsM () extLambdaMetrics = bodyMetrics . extLambdaBody instance PrettyLore lore => PP.Pretty (SOAC lore) where ppr (Map size lam as) = ppSOAC "map" size [lam] Nothing as ppr (Reduce size comm lam inputs) = ppSOAC s size [lam] (Just es) as where (es, as) = unzip inputs s = case comm of Noncommutative -> "reduce" Commutative -> "reduceComm" ppr (Redomap size comm outer inner es as) = text s <> parens (ppr size <> comma </> ppr outer <> comma </> ppr inner <> comma </> commasep (PP.braces (commasep $ map ppr es) : map ppr as)) where s = case comm of Noncommutative -> "redomap" Commutative -> "redomapComm" ppr (Stream size form lam arrs) = case form of Parallel o comm lam0 acc -> let ord_str = if o == Disorder then "Per" else "" comm_str = case comm of Commutative -> "Comm" Noncommutative -> "" in text ("streamPar"++ord_str++comm_str) <> parens (ppr size <> comma </> ppr lam0 </> comma </> ppr lam </> commasep ( PP.braces (commasep $ map ppr acc) : map ppr arrs )) Sequential acc -> text "streamSeq" <> parens (ppr size <> comma </> ppr lam <> comma </> commasep ( PP.braces (commasep $ map ppr acc) : map ppr arrs )) ppr (Scan size lam inputs) = ppSOAC "scan" size [lam] (Just es) as where (es, as) = unzip inputs ppr (Scanomap size outer inner es as) = text "scanomap" <> parens (ppr size <> comma </> ppr outer <> comma </> ppr inner <> comma </> commasep (PP.braces (commasep $ map ppr es) : map ppr as)) ppr (Scatter len lam ivs as) = ppSOAC "write" len [lam] (Just (map Var ivs)) (map snd as) ppSOAC :: Pretty fn => String -> SubExp -> [fn] -> Maybe [SubExp] -> [VName] -> Doc ppSOAC name size funs es as = text name <> parens (ppr size <> comma </> ppList funs </> commasep (es' ++ map ppr as)) where es' = maybe [] ((:[]) . ppTuple') es ppList :: Pretty a => [a] -> Doc ppList as = case map ppr as of [] -> mempty a':as' -> foldl (</>) (a' <> comma) $ map (<> comma) as'
ihc/futhark
src/Futhark/Representation/SOACS/SOAC.hs
isc
27,710
24
25
7,481
8,349
4,166
4,183
535
6
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.VTTRegionList (js_item, item, js_getRegionById, getRegionById, js_getLength, getLength, VTTRegionList, castToVTTRegionList, gTypeVTTRegionList) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"item\"]($2)" js_item :: JSRef VTTRegionList -> Word -> IO (JSRef VTTRegion) -- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTRegionList.item Mozilla VTTRegionList.item documentation> item :: (MonadIO m) => VTTRegionList -> Word -> m (Maybe VTTRegion) item self index = liftIO ((js_item (unVTTRegionList self) index) >>= fromJSRef) foreign import javascript unsafe "$1[\"getRegionById\"]($2)" js_getRegionById :: JSRef VTTRegionList -> JSString -> IO (JSRef VTTRegion) -- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTRegionList.getRegionById Mozilla VTTRegionList.getRegionById documentation> getRegionById :: (MonadIO m, ToJSString id) => VTTRegionList -> id -> m (Maybe VTTRegion) getRegionById self id = liftIO ((js_getRegionById (unVTTRegionList self) (toJSString id)) >>= fromJSRef) foreign import javascript unsafe "$1[\"length\"]" js_getLength :: JSRef VTTRegionList -> IO Word -- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTRegionList.length Mozilla VTTRegionList.length documentation> getLength :: (MonadIO m) => VTTRegionList -> m Word getLength self = liftIO (js_getLength (unVTTRegionList self))
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/VTTRegionList.hs
mit
2,288
22
11
326
582
344
238
37
1
module Battleship where import Data.Maybe import Data.List import Haste.Random import DataTypes {- Lab Assignment 4 Anna Averianova & Tobias Deekens, 2013 -} -- Returns the size of a given boat model sizeOfModel :: Model -> Int sizeOfModel AircraftCarrier = 5 sizeOfModel Battleship = 4 sizeOfModel Submarine = 3 sizeOfModel Destroyer = 3 sizeOfModel PatrolBoat = 2 -- Returns a new boat with provided starting coordinates, alignment and -- a list of occupied coordinates {- This is wrong now -} craftBoat :: Coord -> Alignment -> [Cell] -> Boat craftBoat c a s | s' == 5 = Boat AircraftCarrier c a | s' == 4 = Boat Battleship c a | s' == 3 = Boat Destroyer c a | s' == 2 = Boat PatrolBoat c a where s' = length s -- Flips a boat's alignment flipAlignment :: Boat -> Boat flipAlignment (Boat m s a) = Boat m s fa where fa = if a == Horizontal then Vertical else Horizontal setStart :: Boat -> Coord -> Boat setStart (Boat m s a) s' = Boat m s' a -- Returns an empty battlefield (untouched cells only) emptyField :: Field emptyField = Field (replicate 10 (replicate 10 Nothing)) -- Returns an empty fleet emptyFleet :: Fleet emptyFleet = Fleet ([]) -- Checks if all boats on a field have been hit allShipsSunken :: Field -> Bool allShipsSunken f = length (concat (map (filter (==Just True)) r)) == sizeOfFleet where r = rows f -- Returns a list of coordinates occupied by a boat on a field boatCoord :: Boat -> [Coord] boatCoord (Boat m (x,y) Horizontal) = [(x,y + fromIntegral(i)) | i <- [0..(sizeOfModel m -1)]] boatCoord (Boat m (x,y) Vertical) = [(x + fromIntegral(i),y) | i <- [0..(sizeOfModel m -1)]] -- Checks if coordinates of a boat do not go out the field borders areBoatCoordOkay :: Boat -> Bool areBoatCoordOkay b = and [(x `elem` [0..9]) && (y `elem` [0..9]) | (x,y) <- bc] where bc = boatCoord b -- Checks if the boat can be added to the fleet -- Returns true when a new boat does not overlap with the boats in the fleet -- and has valid field coordinates. canBeInFleet :: Fleet -> Boat -> Bool canBeInFleet f b = (fc `intersect` bc == []) && (areBoatCoordOkay b) && (spaceLeftForModel f b) where fc = fleetCoord f bc = boatCoord b -- Checks if a boat of a given type can be added to the fleet -- Returns false when the fleet already has an upper limit of models spaceLeftForModel :: Fleet -> Boat -> Bool spaceLeftForModel f b | (m == PatrolBoat) = length (elemIndices m fleetModels) < 2 | otherwise = not (m `elem` fleetModels) where m = model b fleetModels = [model b | b <- (boats f)] -- Checks if a boat can be added to a fleet -- and returns (updated fleet, True) if it is -- (old fleet, False) otherwise addToFleet :: Fleet -> Boat -> (Fleet, Bool) addToFleet f b | canBeInFleet f b = (newFleet, True) | otherwise = (f, False) where newFleet = Fleet ((boats f) ++ [b]) -- Returns a list of coordinates occupied by a fleet on a field fleetCoord :: Fleet -> [Coord] fleetCoord (Fleet []) = [] fleetCoord (Fleet (x:xs)) = (boatCoord x) ++ (fleetCoord (Fleet xs)) -- Returns True only when a fleet consists of 6 non overlapping boats -- of which one is AircraftCarrier, one is Battleship, one is Submarine, -- one is Destroyer and two are PatrolBoat isValidFleet :: Fleet -> Bool isValidFleet f = (size == 6) && noIntersect && length (elemIndices AircraftCarrier models) == 1 && length (elemIndices Battleship models) == 1 && length (elemIndices Submarine models) == 1 && length (elemIndices Destroyer models) == 1 && length (elemIndices PatrolBoat models) == 2 where bs = boats f size = length bs boatsCoord = concat [ boatCoord b| b <- bs] models = [ model b| b <- bs] noIntersect = (nub boatsCoord) == boatsCoord -- Updates a field at a given set of coordinates with -- the provided value updateField :: Field -> [Coord] -> Maybe Bool -> Field updateField f [] _ = f updateField f (x:xs) b = let newField = updateCell f x b in updateField newField xs b -- Updates a Field at given coordinates with a provided value updateCell :: Field -> Coord -> Maybe Bool -> Field updateCell f x b = Field ( r !!= (rw, r!!rw !!= (cl, b)) ) where r = rows f rw = fst x cl = snd x -- Given a list, and a tuple containing an index in the list and a new value -- updates the given list with the new value at the given index (!!=) :: [a] -> (Int,a) -> [a] (!!=) l (idx, t) | ( (length l) - 1 ) == idx = (fst $ splitAt idx l) ++ [t] | otherwise = (fst chopped) ++ [t] ++ (tail $ snd chopped) where chopped = splitAt idx l -- Shoots at a position on a field with provided coordinates -- 0 == miss -- 1 == hit -- 2 == sink shootAtCoordinate :: Field -> Coord -> Fleet -> (Field, Int) shootAtCoordinate field c fleet | isNothing bh = (updateField field [c] (Just False), 0) | otherwise = case isBoatSunk field (bc \\ [c]) of False -> (updateField field [c] (Just True), 1) True -> (updateField field [c] (Just True), 2) where cell = (rows field)!!rIdx!!cIdx rIdx = fst c cIdx = snd c bh = whichBoatHit c fleet bc = boatCoord (fromJust bh) -- Checks which boat in the fleet has a given coordinate -- returns Nothing if no boat with such coordinate are in the fleet whichBoatHit :: Coord -> Fleet -> Maybe Boat whichBoatHit c f | b == Nothing = Nothing | otherwise = Just ((boats f)!!(fromJust b)) where fcl = map boatCoord $ boats f b = findIndex (isJust) $ map (elemIndex c) fcl -- Checks if a hit sinks the boat isBoatSunk :: Field -> [Coord] -> Bool isBoatSunk f c = all (\x -> isJust (r!!(fst x)!!(snd x))) c where r = rows f ------------------------------------------------------------------------- -- All possible shots fullShots :: [(Coord)] fullShots = [(i,j) | i <- [0..9], j <- [0..9]] -- Shuffles the shots to be in random order shuffleShots :: Seed -> [(Coord)] -> [(Coord)] shuffleShots _ [] = [] shuffleShots g s = item : shuffleShots g' rest where (pos, g') = randomR (0, length s - 1) g item = s!!pos rest = delete item s -- Takes a current number of shots, a field, a fleet and a coord where -- the ship has been hit at sinkShip :: [Direction] -> Field -> Fleet -> Coord -> [Coord] -> (Field, [Coord]) sinkShip dirs fd ft c shs | (trd' try) = sinkShip ds (snd' try) ft c shs' | otherwise = ( (snd' try), shs') where d = head dirs ds = tail dirs try = walkSide d fd ft c [] shs' = shs\\(fst' try) -- Shoots the filed in a given direction. -- Returns a list of shots (empty when a shot in given direction is impossibe, -- updated field and -- True if the ship not sunk and another direction walk needed -- False if the ship has been sunk walkSide :: Direction -> Field -> Fleet -> Coord -> [Coord] -> ([Coord], Field, Bool) walkSide d fd ft c sh | t == Nothing = ([], fd, True) | (snd res) == 1 = walkSide d (fst res) ft t' (t':sh) | (snd res) == 2 = (t':sh, (fst res), False) | (snd res) == 0 = (t':sh, (fst res), True) where t = nextTarget d c t' = fromJust t res = shootAtCoordinate fd (fromJust t) ft -- Returns a next coordinate in a given direction -- Returns Nothing if next cell does not exist nextTarget :: Direction -> Coord -> Maybe Coord nextTarget North (0,_) = Nothing nextTarget North (x,y) = Just (x-1,y) nextTarget South (9,_) = Nothing nextTarget South (x,y) = Just (x+1,y) nextTarget East (_,9) = Nothing nextTarget East (x,y) = Just (x,y+1) nextTarget West (_,0) = Nothing nextTarget West (x,y) = Just (x,y-1) fst':: (a,b,c) -> a fst' (a,_,_) = a snd':: (a,b,c) -> b snd' (_,b,_) = b trd':: (a,b,c) -> c trd' (_,_,c) = c ------------------------------------------------------------------------- -- Example Field example::Field example = Field [ [Nothing, Just True, Just True, Just True, Just True, Just True, Nothing, Nothing, Nothing, Nothing] , [Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing] , [Nothing, Nothing, Nothing, Nothing, Just True, Just True, Just True, Just True, Nothing, Nothing] , [Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing] , [Nothing, Just True, Just True, Just True, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing] , [Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing] , [Nothing, Nothing, Nothing, Nothing, Nothing, Just True, Just True, Just True, Nothing, Nothing] , [Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing] , [Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing] , [Just True, Just True, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Just True, Just True ] ] -- Example Fleet exampleFleet :: Fleet exampleFleet = Fleet {boats = [Boat {model = AircraftCarrier, start = (0,1), alignment = Horizontal}, Boat {model = Battleship, start = (2,4), alignment = Horizontal}, Boat {model = Submarine, start = (4,1), alignment = Horizontal}, Boat {model = Destroyer, start = (5,5), alignment = Vertical}, Boat {model = PatrolBoat, start = (9,0), alignment = Horizontal}, Boat {model = PatrolBoat, start = (9,8), alignment = Horizontal}]} ------------------------------------------------------------------------- -- Prints a field printField :: Field -> IO () printField f = putStr (unlines (map printRow rows')) where rows' = rows f -- Helper function printing a list of field cells on the screen printRow :: [Cell] -> String printRow = foldr ((++) . printCell) "" -- Helper function printing a field cell on the screen printCell :: Cell -> String printCell Nothing = "_" printCell (Just True) = "x" printCell (Just False) = "."
tdeekens/tda452-code
Lab-4/Battleship.hs
mit
10,493
0
17
2,781
3,479
1,912
1,567
174
2
import System.Random import System.Environment import qualified Data.List as List import qualified Data.Map as Map import Control.Monad import Control.Arrow import ML.Common import ML.DecisionTree import ML.RandomForest main = do args <- getArgs let reader = if (args !! 0 == "f") then reasSamplesClassIsLead else reasSamplesClassIsLast rawText <- readFile $ args !! 1 let trainDataSet = reader $ rawText print "reading train" rawText2 <- readFile $ args !! 2 let testDataSet = reader $ rawText2 -- let tree = buildNode trainDataSet --let tree = trainRandomForest (mkStdGen 2) trainDataSet --print tree --mapM_ (\sample -> print $ show (fst sample) ++ show (predictDecTree tree (snd sample))) testDataSet print $ (show $ testClassifier tree testDataSet) ++ "/" ++ (show $ length testDataSet)
Daiver/HRandomForest
main3.hs
mit
847
0
13
171
207
109
98
19
2
module Utils where import Data.Char elemAny :: (Eq a) => [a] -> [a] -> Bool elemAny l1 l2 = or $ map (\x -> elem x l2) l1 splitInto :: Int -> [a] -> [[a]] splitInto n list | length list <= n = [list] | otherwise = fst split : splitInto n (snd split) where split = splitAt n list allDigit :: String -> Bool allDigit s = and $ map (isDigit) s allLower :: String -> String allLower s = map (toLower) s
crockeo/ballgame
src/Utils.hs
mit
416
0
9
102
210
109
101
13
1
module Frequency where englishLetters = [ ('e',8269949) , ('t',6393831) , ('a',5618362) , ('i',5174648) , ('o',5156878) , ('n',4897495) , ('s',4548571) , ('r',4122762) , ('h',3313317) , ('l',2859703) , ('d',2541643) , ('c',2256826) , ('u',2084567) , ('m',1760271) , ('p',1479766) , ('f',1469526) , ('g',1392062) , ('y',1329083) , ('w',1177144) , ('b',1045301) , ('v', 727277) , ('k', 501687) , ('x', 168434) , ('j', 122815) , ('q', 86037) , ('z', 79034) ] englishInitials = [ ('t',2160301) , ('a',1634574) , ('i',1119695) , ('s', 924924) , ('o', 923945) , ('w', 775609) , ('c', 741166) , ('p', 607299) , ('b', 602109) , ('m', 540655) , ('f', 539828) , ('h', 499922) , ('d', 474965) , ('r', 436503) , ('e', 367725) , ('l', 340950) , ('n', 307899) , ('g', 283424) , ('u', 283403) , ('y', 234635) , ('k', 123042) , ('v', 102244) , ('j', 87335) , ('q', 29440) , ('z', 5977) , ('x', 4184) ] englishFinals = [ ('e',2631722) , ('s',1930725) , ('t',1390207) , ('d',1293522) , ('n',1180173) , ('y', 827186) , ('r', 754097) , ('o', 599275) , ('f', 518026) , ('l', 488554) , ('h', 483105) , ('g', 454625) , ('a', 452570) , ('m', 261725) , ('i', 187123) , ('w', 158618) , ('k', 139400) , ('u', 113835) , ('c', 107310) , ('p', 101494) , ('x', 27036) , ('b', 26955) , ('v', 11770) , ('z', 5917) , ('j', 3548) , ('q', 3235) ] englishBigrams = [ ("th",1784632) , ("he",1382681) , ("in",1337659) , ("an",1045521) , ("re",1036003) , ("er",1015739) , ("on", 901503) , ("at", 881937) , ("es", 763992) , ("en", 759950) , ("ti", 711888) , ("nd", 686855) , ("or", 675151) , ("te", 660775) , ("it", 618544) , ("nt", 613379) , ("al", 597097) , ("ed", 588553) , ("st", 576149) , ("to", 559634) , ("ha", 557425) , ("ar", 540733) , ("ng", 530427) , ("is", 522759) , ("ou", 516476) , ("se", 512379) , ("of", 485979) , ("as", 461772) , ("ve", 450998) , ("le", 436825) , ("me", 418281) , ("ea", 416547) , ("io", 406829) , ("ro", 398542) , ("co", 396944) , ("ne", 375901) , ("ri", 374734) , ("de", 370895) , ("ll", 360496) , ("ic", 359682) , ("ra", 359344) , ("li", 359138) , ("hi", 340206) , ("ce", 331611) , ("ca", 314378) , ("el", 310308) , ("si", 308879) , ("ta", 299052) , ("om", 297564) , ("ma", 285015) , ("la", 284664) , ("no", 284414) , ("ns", 280952) , ("us", 275241) , ("be", 271652) , ("di", 270383) , ("pr", 266421) , ("ch", 264195) , ("ur", 263746) , ("ec", 261395) , ("ts", 261295) , ("ho", 256773) , ("ly", 253542) , ("fo", 250195) , ("ot", 249091) , ("we", 244539) , ("ut", 242508) , ("et", 240950) , ("ge", 239911) , ("pe", 239619) , ("ct", 238376) , ("ac", 234735) , ("tr", 226727) , ("il", 224153) , ("so", 213252) , ("nc", 212480) , ("rs", 210658) , ("ow", 209770) , ("na", 207181) , ("ss", 202855) , ("lo", 197755) , ("ol", 196581) , ("un", 195309) , ("mo", 195026) , ("wa", 192960) , ("ie", 188775) , ("ee", 187911) , ("po", 184307) , ("ul", 183219) , ("id", 183167) , ("wi", 183010) , ("mi", 182929) , ("im", 179816) , ("ni", 179214) , ("pa", 178614) , ("rt", 178336) , ("wh", 175582) , ("os", 174600) , ("ad", 172752) , ("em", 172548) , ("fi", 165783) , ("ig", 163395) , ("su", 161882) , ("ai", 159534) , ("am", 157702) , ("iv", 156030) , ("yo", 155419) , ("ia", 150363) , ("vi", 147740) , ("do", 147342) , ("pl", 146808) , ("ev", 145534) , ("ay", 143867) , ("sh", 143597) , ("ke", 140908) , ("ir", 139064) , ("ci", 138080) , ("ab", 135129) , ("um", 129826) , ("mp", 125487) , ("gh", 124450) , ("ry", 123471) , ("ld", 123090) , ("bu", 122527) , ("tu", 121740) , ("fe", 121018) , ("if", 120855) , ("bo", 120754) , ("bl", 120378) , ("av", 119655) , ("op", 119402) , ("wo", 118039) , ("ex", 117766) , ("sa", 117713) , ("ty", 116134) , ("ag", 113431) , ("oo", 113325) , ("da", 108144) , ("sp", 107503) , ("ye", 104622) , ("ep", 103623) , ("cl", 103297) , ("od", 103240) , ("fr", 102858) , ("ap", 102142) , ("uh", 101619) , ("go", 99903) , ("ey", 99438) , ("ls", 97770) , ("cr", 97415) , ("ov", 96519) , ("ba", 96148) , ("gr", 94687) , ("uc", 94000) , ("ei", 90284) , ("ue", 89828) , ("tt", 89508) , ("sc", 86755) , ("oc", 86134) , ("ff", 86045) , ("ga", 85727) , ("rd", 84357) , ("rm", 83460) , ("cu", 82814) , ("bi", 82322) , ("lu", 80149) , ("qu", 79196) , ("fa", 78646) , ("by", 77932) , ("rn", 77655) , ("ef", 75326) , ("va", 75092) , ("ys", 74911) , ("ht", 73289) , ("ck", 71181) , ("du", 71162) , ("ew", 71061) , ("up", 70305) , ("ds", 70257) , ("au", 69331) , ("gi", 69028) , ("hu", 68586) , ("ki", 67742) , ("ru", 67425) , ("lt", 67318) , ("ug", 67185) , ("eg", 66735) , ("pp", 66516) , ("kn", 65879) , ("pi", 65587) , ("rr", 63973) , ("mu", 63342) , ("ua", 63259) , ("ob", 59215) , ("og", 58782) , ("ud", 58721) , ("ib", 58538) , ("ny", 57933) , ("ak", 57254) , ("pu", 57104) , ("br", 56418) , ("ph", 55918) , ("gu", 55461) , ("ah", 54981) , ("rc", 54764) , ("rk", 52536) , ("tl", 51953) , ("fu", 51766) , ("pt", 51270) , ("rg", 50918) , ("ub", 50909) , ("mm", 50327) , ("ju", 49983) , ("ik", 48934) , ("oi", 48877) , ("ui", 48512) , ("mb", 48458) , ("dr", 47744) , ("ip", 46432) , ("nk", 45917) , ("tw", 45540) , ("ms", 44839) , ("nu", 44442) , ("eo", 44389) , ("xp", 44354) , ("hr", 43544) , ("nn", 41588) , ("ok", 41579) , ("rv", 41513) , ("wn", 41204) , ("cc", 40699) , ("iz", 40609) , ("gn", 40189) , ("af", 39073) , ("ft", 38942) , ("rl", 38857) , ("sm", 38404) , ("nf", 38357) , ("my", 36684) , ("eq", 35028) , ("gs", 33704) , ("vo", 32763) , ("sl", 32759) , ("dy", 32364) , ("fl", 31547) , ("ze", 31213) , ("nl", 30766) , ("ps", 30678) , ("gl", 30595) , ("hy", 30586) , ("cy", 30232) , ("ks", 29994) , ("jo", 29808) , ("oa", 29275) , ("oh", 29197) , ("bs", 28662) , ("sy", 27814) , ("dd", 27458) , ("nv", 27312) , ("aw", 26131) , ("oe", 25023) , ("ws", 24016) , ("sk", 22976) , ("dn", 22769) , ("tc", 22005) , ("lf", 21871) , ("yt", 21753) , ("rp", 21255) , ("yp", 21069) , ("eb", 20978) , ("xt", 20092) , ("je", 19975) , ("xi", 19893) , ("yi", 19268) , ("gg", 18926) , ("rf", 18748) , ("eu", 18633) , ("dl", 18245) , ("xa", 17885) , ("ka", 17676) , ("nm", 17600) , ("tm", 17233) , ("hh", 17060) , ("za", 16763) , ("mh", 16623) , ("sn", 16440) , ("ox", 16297) , ("oy", 16147) , ("cs", 15797) , ("rb", 15447) , ("ym", 15167) , ("ek", 14689) , ("yl", 14616) , ("ja", 14367) , ("lv", 14051) , ("wr", 13935) , ("lm", 13599) , ("lk", 13274) , ("dg", 13217) , ("yr", 13111) , ("hn", 13058) , ("ix", 12720) , ("eh", 12529) , ("uf", 12283) , ("lp", 12209) , ("sw", 12097) , ("gt", 11698) , ("xc", 11649) , ("gy", 11548) , ("ax", 11279) , ("xe", 11266) , ("yc", 10614) , ("dm", 10587) , ("hs", 10575) , ("yb", 10503) , ("az", 10387) , ("ya", 10183) , ("yn", 9869) , ("lc", 9778) , ("ae", 9555) , ("zi", 9369) , ("iu", 9291) , ("sf", 9076) , ("ii", 9003) , ("dv", 8904) , ("nh", 8845) , ("pm", 8648) , ("hm", 8430) , ("rh", 8387) , ("cd", 8142) , ("hl", 8142) , ("bt", 7841) , ("gm", 7713) , ("uo", 7465) , ("tp", 7438) , ("bj", 7414) , ("nj", 7272) , ("sd", 7114) , ("aj", 7059) , ("bb", 6997) , ("lw", 6847) , ("tn", 6828) , ("kl", 6714) , ("py", 6612) , ("fy", 6542) , ("uy", 6423) , ("aa", 6276) , ("nr", 6275) , ("ko", 6263) , ("rw", 6181) , ("np", 6178) , ("sb", 5761) , ("pc", 5620) , ("ky", 5614) , ("iq", 5570) , ("ml", 5568) , ("ao", 5469) , ("mc", 5274) , ("mn", 5060) , ("sr", 5016) , ("wl", 4964) , ("lr", 4876) , ("mr", 4876) , ("wt", 4845) , ("nb", 4801) , ("fs", 4788) , ("lb", 4785) , ("sq", 4667) , ("yd", 4649) , ("yw", 4544) , ("gf", 4511) , ("dc", 4475) , ("hw", 4388) , ("lg", 4314) , ("bc", 4244) , ("tg", 4218) , ("dh", 4190) , ("xo", 4152) , ("hc", 4146) , ("tb", 4085) , ("zo", 4066) , ("zy", 4035) , ("bm", 3928) , ("dw", 3878) , ("dt", 3875) , ("tf", 3646) , ("nz", 3636) , ("oj", 3576) , ("hb", 3548) , ("gc", 3344) , ("oz", 3289) , ("bp", 3288) , ("uv", 3133) , ("dj", 3095) , ("aq", 2990) , ("nw", 2882) , ("yz", 2881) , ("uk", 2865) , ("ku", 2849) , ("pb", 2830) , ("kg", 2760) , ("xu", 2744) , ("db", 2699) , ("wy", 2659) , ("pd", 2658) , ("mg", 2641) , ("xh", 2640) , ("wp", 2629) , ("tv", 2627) , ("dp", 2607) , ("tz", 2585) , ("fb", 2566) , ("ji", 2565) , ("hd", 2513) , ("ln", 2498) , ("zz", 2469) , ("df", 2437) , ("ez", 2380) , ("cq", 2379) , ("xy", 2332) , ("ih", 2329) , ("fp", 2322) , ("cp", 2303) , ("cm", 2272) , ("yg", 2261) , ("ww", 2238) , ("sg", 2187) , ("td", 2180) , ("yv", 2162) , ("km", 2144) , ("gd", 2116) , ("bv", 2115) , ("cg", 2074) , ("mf", 2053) , ("kr", 2019) , ("ij", 2016) , ("nq", 1977) , ("vy", 1969) , ("kh", 1960) , ("wd", 1959) , ("ej", 1941) , ("pf", 1917) , ("pn", 1870) , ("vs", 1863) , ("hp", 1861) , ("md", 1783) , ("bd", 1765) , ("ux", 1722) , ("pk", 1721) , ("cn", 1718) , ("kb", 1701) , ("cf", 1698) , ("mt", 1688) , ("cb", 1685) , ("fd", 1539) , ("gp", 1475) , ("uz", 1474) , ("pg", 1465) , ("lh", 1387) , ("yu", 1347) , ("sv", 1346) , ("fg", 1325) , ("fc", 1321) , ("kt", 1230) , ("kp", 1216) , ("yf", 1205) , ("kd", 1189) , ("hf", 1165) , ("fn", 1138) , ("kw", 1108) , ("qa", 1091) , ("wf", 1068) , ("wb", 1059) , ("vu", 1018) , ("oq", 1011) , ("qi", 985) , ("bn", 966) , ("kc", 961) , ("tk", 945) , ("pw", 936) , ("kf", 931) , ("zl", 884) , ("mw", 877) , ("cv", 870) , ("wk", 860) , ("mv", 851) , ("wu", 841) , ("fm", 833) , ("bh", 831) , ("hg", 808) , ("vr", 762) , ("yk", 745) , ("nx", 738) , ("zs", 721) , ("zu", 721) , ("pv", 718) , ("xx", 703) , ("tx", 700) , ("fh", 699) , ("gb", 691) , ("bg", 678) , ("yh", 676) , ("gw", 675) , ("wc", 671) , ("wm", 650) , ("rj", 641) , ("zh", 641) , ("cz", 634) , ("jr", 618) , ("bf", 586) , ("iw", 582) , ("kk", 581) , ("rq", 575) , ("xs", 555) , ("zm", 547) , ("sj", 543) , ("fw", 531) , ("wg", 530) , ("dq", 518) , ("sz", 513) , ("dk", 512) , ("gk", 507) , ("vc", 501) , ("rz", 475) , ("xf", 461) , ("hq", 444) , ("fk", 441) , ("iy", 410) , ("rx", 410) , ("xl", 394) , ("lz", 387) , ("xr", 383) , ("hk", 376) , ("uj", 362) , ("vh", 354) , ("vp", 347) , ("kq", 341) , ("bw", 336) , ("uu", 334) , ("xv", 329) , ("cx", 324) , ("uw", 313) , ("xm", 295) , ("zt", 295) , ("zn", 292) , ("vl", 288) , ("qp", 285) , ("vd", 284) , ("xd", 282) , ("vv", 281) , ("jc", 276) , ("qt", 275) , ("kv", 273) , ("vb", 271) , ("vt", 266) , ("jn", 255) , ("mz", 255) , ("hv", 244) , ("qs", 243) , ("jf", 240) , ("xb", 240) , ("hz", 233) , ("pj", 231) , ("fx", 226) , ("fz", 225) , ("mk", 216) , ("dz", 213) , ("mj", 211) , ("bx", 210) , ("cw", 208) , ("xq", 208) , ("xw", 197) , ("bk", 191) , ("gz", 191) , ("cj", 190) , ("lj", 187) , ("tj", 187) , ("vn", 183) , ("zb", 183) , ("lx", 172) , ("uq", 171) , ("sx", 169) , ("lq", 167) , ("wv", 165) , ("jm", 162) , ("xn", 162) , ("dx", 151) , ("js", 150) , ("jp", 147) , ("mx", 144) , ("zd", 143) , ("yy", 139) , ("px", 137) , ("bz", 136) , ("gv", 131) , ("vm", 125) , ("kx", 123) , ("vg", 120) , ("zk", 120) , ("fv", 117) , ("jd", 116) , ("jk", 116) , ("qr", 109) , ("zc", 106) , ("qo", 105) , ("zv", 105) , ("zw", 104) , ("gj", 100) , ("kj", 97) , ("xg", 91) , ("hj", 90) , ("vf", 90) , ("gq", 86) , ("jb", 83) , ("zg", 76) , ("jt", 75) , ("zp", 74) , ("xk", 71) , ("gx", 70) , ("ql", 70) , ("tq", 69) , ("yx", 68) , ("vw", 66) , ("yj", 63) , ("zf", 63) , ("qe", 60) , ("wj", 60) , ("zr", 59) , ("jg", 58) , ("jh", 58) , ("qq", 57) , ("jl", 54) , ("qd", 53) , ("yq", 52) , ("pq", 49) , ("zq", 47) , ("fj", 44) , ("fq", 43) , ("hx", 41) , ("jq", 38) , ("mq", 38) , ("vx", 37) , ("jj", 36) , ("qm", 36) , ("qn", 33) , ("qc", 31) , ("qb", 30) , ("bq", 27) , ("jw", 27) , ("qv", 27) , ("qx", 25) , ("vj", 24) , ("vk", 24) , ("vq", 23) , ("wq", 22) , ("jv", 21) , ("jy", 20) , ("pz", 18) , ("qw", 18) , ("vz", 18) , ("jz", 16) , ("qg", 16) , ("qh", 15) , ("xj", 15) , ("kz", 14) , ("qf", 14) , ("qk", 14) , ("wz", 14) , ("qj", 13) , ("zj", 13) , ("zx", 8) , ("wx", 7) , ("xz", 5) , ("jx", 3) , ("qy", 1) ]
bhamrick/puzzlib
Frequency.hs
mit
14,337
0
6
4,931
6,801
4,533
2,268
758
1
module Listas ( unittest , primeiros , calculaSomaPA , calculaProdPA , mapeiaListaPA ) where primeiros 0 _ = [] primeiros n [] = [] primeiros n (a:x) = a : primeiros (n - 1) x fact = foldl (*) 1 . enumFromTo 1 -- a0 = 0 calculaSomaPA n razao = sum (map (\x -> razao + ((x - 1) * razao)) (take n [1..])) -- a0 = 0 mapeiaListaPA n razao = map (\x -> razao + ((x - 1) * razao)) (take n [1..]) -- a0 = 1 calculaProdPA n razao = product (map (\x -> razao + ((x - 1) * razao)) (take n [1..])) unittest = do putStrLn "Haskel::MiniTest" putStrLn "Test Primeiros" print (primeiros 0 [1897, 1014, 783, 952, 67, 1848, 468, 892, 833, 1439, 365, 115, 335]) print (primeiros 1 [1897, 1014, 783, 952, 67, 1848, 468, 892, 833, 1439, 365, 115, 335]) print (primeiros 2 [1897, 1014, 783, 952, 67, 1848, 468, 892, 833, 1439, 365, 115, 335]) print (primeiros 3 [1897, 1014, 783, 952, 67, 1848, 468, 892, 833, 1439, 365, 115, 335]) print (primeiros 4 [1897, 1014, 783, 952, 67, 1848, 468, 892, 833, 1439, 365, 115, 335]) print (primeiros 5 [1897, 1014, 783, 952, 67, 1848, 468, 892, 833, 1439, 365, 115, 335]) print (primeiros 6 [1897, 1014, 783, 952, 67, 1848, 468, 892, 833, 1439, 365, 115, 335]) print (primeiros 7 [1897, 1014, 783, 952, 67, 1848, 468, 892, 833, 1439, 365, 115, 335]) print (primeiros 8 [1897, 1014, 783, 952, 67, 1848, 468, 892, 833, 1439, 365, 115, 335]) putStrLn "Test Mapeamentos Somas Produtos" print (mapeiaListaPA 7 7) print (calculaSomaPA 7 7) print (calculaProdPA 7 7) print (mapeiaListaPA 4 7) print (calculaSomaPA 4 7) print (calculaProdPA 4 7) print (mapeiaListaPA 3 6) print (calculaSomaPA 3 6) print (calculaProdPA 3 6) print (mapeiaListaPA 3 12) print (calculaSomaPA 3 12) print (calculaProdPA 3 12)
tonussi/freezing-dubstep
pratica-10/Listas.hs
mit
1,801
0
14
400
938
516
422
38
1
import Data.Dates sumProperDivisors :: Int -> Int sumProperDivisors n = iter 2 1 where iter i acc | isDivisor && (i*i == n) = acc + i | isDivisor = iter (i+1) (acc + i + n `div` i) | i*i >= n = acc | otherwise = iter (i+1) acc where isDivisor = n `rem`i == 0 amicaleNumbers :: Int -> [Int] amicaleNumbers bound = filter predicate [1..bound] where predicate n = n /= conjugate && n == sumProperDivisors conjugate where conjugate = sumProperDivisors n main = print $ sum $ amicaleNumbers 9999
dpieroux/euler
0/0021.hs
mit
609
0
13
212
239
121
118
14
1
{-# LANGUAGE FlexibleContexts #-} module System.Tianbar.Plugin.Socket where -- Socket connectivity import Control.Concurrent import Control.Lens hiding (index) import Control.Monad import Control.Monad.IO.Class import Control.Monad.State import Control.Monad.Trans.Maybe import qualified Data.ByteString.UTF8 as U import qualified Data.Map as M import Network.Socket import qualified Network.Socket.ByteString as SB import System.Tianbar.Callbacks import System.Tianbar.Plugin type SocketMap = M.Map CallbackIndex Socket data SocketPlugin = SocketPlugin { _spSock :: SocketMap } spSock :: Lens' SocketPlugin SocketMap spSock inj (SocketPlugin m) = SocketPlugin <$> inj m instance Plugin SocketPlugin where initialize = return $ SocketPlugin M.empty destroy = mapM_ close . M.elems . view spSock handler = dir "socket" $ msum [connectHandler, sendHandler, closeHandler] connectHandler :: ServerPart SocketPlugin Response connectHandler = dir "connect" $ do nullDir socketPath <- look "path" sock <- liftIO $ do s <- socket AF_UNIX Stream defaultProtocol connect s $ SockAddrUnix socketPath return s (callback, index) <- newCallback _ <- liftIO $ forkIO $ void $ forever $ do sockData <- SB.recv sock 4096 liftIO $ callback [U.toString sockData] return () spSock . at index .= Just sock callbackResponse index sendHandler :: ServerPart SocketPlugin Response sendHandler = dir "send" $ do nullDir index <- fromData sock <- MaybeT $ getSocket index dataToSend <- lookBS "data" -- TODO: resend until done _ <- liftIO $ SB.send sock dataToSend callbackResponse index closeHandler :: ServerPart SocketPlugin Response closeHandler = dir "close" $ do nullDir index <- fromData sock <- getSocket index case sock of Nothing -> return () Just sock' -> do liftIO $ close sock' spSock . at index .= Nothing callbackResponse index getSocket :: MonadState SocketPlugin m => CallbackIndex -> m (Maybe Socket) getSocket callbackIndex = use $ spSock . at callbackIndex
koterpillar/tianbar
src/System/Tianbar/Plugin/Socket.hs
mit
2,174
0
16
497
626
311
315
-1
-1