code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module AsXYSpec where import Control.Exception (evaluate) import Test.Hspec import Data.Ratio import Data.Matrix import Data.Matrix.AsXYZ readTest str mat = do it ("read " ++ str) $ do fromXY str `shouldBe` mat readData = [ ("x,y+1", {- shouldBe -} fromLists [ [1,0,0], [0,1,1], [0,0,1]]), ("+x+y+2,+x+y+3", {- shouldBe -} fromLists [ [1,1,2], [1,1,3], [0,0,1]]) ] curryM f (a,b) = do f a b spec :: Spec spec = do describe "Data.Matrix.AsXY.fromXY" $ do it "read empty throws exception" $ do evaluate (fromXY "") `shouldThrow` anyException it "read a,b throws exception" $ do evaluate (fromXY "a,b") `shouldThrow` anyException it "read x,y throws exception" $ do evaluate (fromAB "x,y") `shouldThrow` anyException it "read x,y" $ do fromXY "x,y" `shouldBe` (identity 3) it "read X,Y" $ do fromXY "X,Y" `shouldBe` (identity 3) mapM_ (curryM readTest) readData it "read a,b" $ do fromAB "a,b" `shouldBe` (identity 3) it "read A,B" $ do fromAB "A,B" `shouldBe` (identity 3) it "row size" $ do (nrows . fromXY $ "x,y") `shouldBe` 3 it "col size" $ do (ncols . fromXY $ "x,y") `shouldBe` 3 describe "Data.Matrix.AsXYZ.prettyXYZ" $ do it "show 0 (2x2)" $ do prettyXY (zero 2 2) `shouldBe` "0,0" it "show 0 (3x3)" $ do prettyXY (zero 3 3) `shouldBe` "0,0" it "show 0 (3x4)" $ do prettyXY (zero 2 3) `shouldBe` "0,0" it "show 1 (2x2)" $ do prettyXY (identity 2) `shouldBe` "x,y" it "show 1 (2x3)" $ do prettyXY (submatrix 1 2 1 3 $ identity 3) `shouldBe` "x,y" it "show 1 (3x3)" $ do prettyXY (identity 3) `shouldBe` "x,y" it "positive first" $ do prettyXY (fromLists [[1,-1,-1],[-1,1,-1]]) `shouldBe` "x-y-1,y-x-1" it "number last" $ do prettyXY (fromLists [[-1,-1,-1],[-1,-1,1]]) `shouldBe` "-x-y-1,-x-y+1" describe "Data.Matrix.AsXYZ.prettyABC" $ do it "show 0" $ do prettyAB (zero 4 4) `shouldBe` "0,0" it "show 1" $ do prettyAB (identity 4) `shouldBe` "a,b"
narumij/matrix-as-xyz
test/AsXYSpec.hs
bsd-3-clause
2,193
0
31
636
882
446
436
66
1
{-# LANGUAGE TemplateHaskell, ConstraintKinds, ScopedTypeVariables, FlexibleInstances #-} module Templates where import qualified Classes as D import Prelude ( (=<<), String ) import Language.Haskell.InstanceTemplates import Language.Haskell.TH.Syntax -- This is just for prettier -ddump-splices -- The instance templates are defined in a separate module because they use new -- names -- TODO: use nested instantiations once they work. type Functor f = D.Functor f $(mkTemplate =<< [d| class Functor f where fmap :: (a -> b) -> f a -> f b instance D.Functor f where map = fmap |] ) {- Instance templates syntax deriving class Functor f where fmap :: (a -> b) -> f a -> f b instance D.Functor f where map = fmap -} type Applicative f = (D.Functor f, D.Applicative f) $(mkTemplate =<< [d| class Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b (*>) :: f a -> f b -> f b (<*) :: f a -> f b -> f a {- TODO a <* b = const id <$> a <*> b a *> b = const <$> a <*> b -} instance D.Functor f where map f x = pure f <*> x instance D.Applicative f where pure = pure (<*>) = (<*>) (*>) = (*>) (<*) = (<*) |] ) type Monad a = D.Monad a $(mkTemplate =<< [d| class Monad m where (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b return :: a -> m a {- TODO m >> k = m >>= \_ -> k fail = error -} -- This means that "fail" parameter is inherited form this instance. instance Inherit (Instance (D.MonadFail m)) where instance D.Functor m where map f x = D.pure f D.<*> x instance D.Applicative m where pure = return l <*> r = l >>= \f -> r >>= \x -> return (f x) instance D.Monad m where (>>=) = (>>=) (>>) = (>>) |] )
mgsloan/instance-templates
tests/monads/Templates.hs
bsd-3-clause
1,833
0
7
541
134
86
48
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Dalvik.Printer ( prettyInstruction , prettyHeader , prettyClassDef , protoDesc , methodStr , getStr' , getTypeName' ) where import qualified Control.Exception as E import Data.Bits import qualified Data.ByteString.Char8 as BS import qualified Data.Foldable as F import Data.Int import qualified Data.List as L import qualified Data.Map as Map import Data.Maybe ( mapMaybe ) import qualified Data.Monoid as M import Data.Serialize.Get ( runGet ) import Data.Serialize.Put ( runPut, putWord32le, putWord64le ) import Data.Serialize.IEEE754 ( getFloat32le, getFloat64le ) import Data.Word import Text.FShow.RealFloat import Text.PrettyPrint.HughesPJClass as PP import Text.Printf ( printf ) import Prelude import qualified Dalvik.AccessFlags as AF import qualified Dalvik.DebugInfo as DI import Dalvik.Instruction import Dalvik.Types methodComm :: MethodId -> PP.Doc methodComm mid = " // method@" <> word16HexFixed mid typeComm :: TypeId -> PP.Doc typeComm tid = " // type@" <> word16HexFixed tid fieldComm :: FieldId -> PP.Doc fieldComm fid = " // field@" <> word16HexFixed fid stringComm :: StringId -> PP.Doc stringComm sid = " // string@" <> word16HexFixed (fromIntegral sid) intComm8 :: Word8 -> PP.Doc intComm8 i = " // #" <> word8Hex i intComm8' :: Word8 -> PP.Doc intComm8' i = " // #" <> word8HexFixed i intComm16 :: Word16 -> PP.Doc intComm16 i = " // #" <> word16Hex i intComm16' :: Word16 -> PP.Doc intComm16' i = " // #" <> word16HexFixed i intComm32 :: Word32 -> PP.Doc intComm32 i = " // #" <> word32HexFixed i intComm64 :: Word64 -> PP.Doc intComm64 i = " // #" <> word64HexFixed i offComm :: Int16 -> PP.Doc offComm i = " // " <> sign <> int16HexFixed i' where (sign, i') | i < 0 = ("-", -i) | otherwise = ("+", i) offComm32 :: Int32 -> PP.Doc offComm32 i = " // " <> int32HexFixed i offComm' :: Word32 -> PP.Doc offComm' i = " // " <> sign <> word32HexFixed i' where (sign, i') | i < 0 = ("-", -i) | otherwise = ("+", i) regStr :: Reg -> PP.Doc regStr (R4 r) = iregStr8 r regStr (R8 r) = iregStr8 r regStr (R16 r) = iregStr16 r iregStr8 :: Word8 -> PP.Doc iregStr8 r = "v" <> word8Dec r iregStr16 :: Word16 -> PP.Doc iregStr16 r = "v" <> word16Dec r moveTypeString :: MoveType -> PP.Doc moveTypeString MNormal = "move" moveTypeString MWide = "move-wide" moveTypeString MObject = "move-object" moveSizeString :: Reg -> PP.Doc moveSizeString (R4 _) = "" moveSizeString (R8 _) = "/from16" moveSizeString (R16 _) = "/16" constStr :: DexFile -> PP.Doc -> Reg -> ConstArg -> PP.Doc constStr dex instr d c = mkInsn instr [regStr d, constString dex c] ifOpStr :: IfOp -> PP.Doc ifOpStr Eq = "eq" ifOpStr Ne = "ne" ifOpStr Lt = "lt" ifOpStr Ge = "ge" ifOpStr Gt = "gt" ifOpStr Le = "le" typeStr :: CType -> PP.Doc typeStr Byte = "byte" typeStr Char = "char" typeStr Short = "short" typeStr Int = "int" typeStr Long = "long" typeStr Float = "float" typeStr Double = "double" unopStr :: Unop -> PP.Doc unopStr NegInt = "neg-int" unopStr NotInt = "not-int" unopStr NegLong = "neg-long" unopStr NotLong = "not-long" unopStr NegFloat = "neg-float" unopStr NegDouble = "neg-double" unopStr (Convert ty1 ty2) = M.mconcat [typeStr ty1, "-to-", typeStr ty2] binopStr :: Binop -> PP.Doc binopStr Add = "add" binopStr Sub = "sub" binopStr Mul = "mul" binopStr Div = "div" binopStr Rem = "rem" binopStr And = "and" binopStr Or = "or" binopStr Xor = "xor" binopStr Shl = "shl" binopStr Shr = "shr" binopStr UShr = "ushr" binopStr RSub = "rsub" int32ToFloat :: Int32 -> Float int32ToFloat = either (const (0/0)) id . runGet getFloat32le . runPut . putWord32le . fromIntegral int64ToDouble :: Int64 -> Double int64ToDouble = either (const (0/0)) id . runGet getFloat64le . runPut . putWord64le . fromIntegral ffmt :: Float -> PP.Doc ffmt f | isNaN f = "nan" | otherwise = PP.text $ fshowFFloat (Just 6) (FF f) "" dfmt :: Double -> PP.Doc dfmt d | isNaN d = "nan" | otherwise = PP.text $ fshowFFloat (Just 6) (FD d) "" constString :: DexFile -> ConstArg -> PP.Doc constString _ (Const4 i) = "#int " <> int8Dec (fromIntegral i) <> intComm8 (fromIntegral i) constString _ (Const16 i) = "#int " <> int16Dec (fromIntegral i) <> intComm16 (fromIntegral i) constString _ (ConstHigh16 i) = "#int " <> int32Dec i <> intComm16 (fromIntegral (i `shiftR` 16) :: Word16) constString _ (ConstWide16 i) = "#int " <> int64Dec i <> intComm16 (fromIntegral i) constString _ (Const32 w) = -- dexdump always prints these as floats, even though they might not be. "#float " <> ffmt (int32ToFloat w) <> intComm32 (fromIntegral w :: Word32) constString _ (ConstWide32 i) = -- dexdump always prints these as floats, even though they might not be. "#float " <> ffmt (int32ToFloat (fromIntegral i)) <> intComm32 (fromIntegral i) constString _ (ConstWide w) = -- dexdump always prints these as doubles, even though they might not be. "#double " <> dfmt (int64ToDouble w) <> intComm64 (fromIntegral w) constString _ (ConstWideHigh16 i) = "#long " <> int64Dec i <> intComm16 (fromIntegral (i `shiftR` 48) :: Word16) constString dex (ConstString sid) = "\"" <> getStr' dex sid <> "\"" <> stringComm sid constString dex (ConstStringJumbo sid) = "\"" <> getStr' dex sid <> "\"" <> stringComm sid constString dex (ConstClass tid) = getTypeName' dex tid <> typeComm tid accessOpStr :: AccessOp -> PP.Doc accessOpStr (Get ty) = "get" <> accessTypeStr ty accessOpStr (Put ty) = "put" <> accessTypeStr ty accessTypeStr :: Maybe AccessType -> PP.Doc accessTypeStr Nothing = "" accessTypeStr (Just AWide) = "-wide" accessTypeStr (Just AObject) = "-object" accessTypeStr (Just ABoolean) = "-boolean" accessTypeStr (Just AByte) = "-byte" accessTypeStr (Just AChar) = "-char" accessTypeStr (Just AShort) = "-short" ikindStr :: InvokeKind -> PP.Doc ikindStr Virtual = "virtual" ikindStr Super = "super" ikindStr Direct = "direct" ikindStr Static = "static" ikindStr Interface = "interface" getStr' :: DexFile -> StringId -> PP.Doc getStr' _ sid | sid == -1 = "unknown" getStr' dex sid = maybe ("<unknown string ID: " <> word32HexFixed sid <> ">") pSDI $ getStr dex sid getTypeName' :: DexFile -> TypeId -> PP.Doc getTypeName' dex tid = maybe ("<unknown type ID: " <> word16HexFixed tid <> ">") pSDI $ getTypeName dex tid getTypeName'' :: DexFile -> TypeId -> PP.Doc getTypeName'' dex tid = maybe msg (pSDI . tailSDI) $ getTypeName dex tid where tailSDI = BS.map slashToDot . BS.init . BS.tail slashToDot '/' = '.' slashToDot '$' = '.' slashToDot c = c msg = "<unknown type ID: " <> word16HexFixed tid <> ">" fieldStr :: DexFile -> FieldId -> PP.Doc fieldStr dex fid = case getField dex fid of Nothing -> "<unknown field ID: " <> word16HexFixed fid <> ">" Just fld -> getTypeName' dex (fieldClassId fld) <> "." <> getStr' dex (fieldNameId fld) <> ":" <> getTypeName' dex (fieldTypeId fld) protoDesc' :: DexFile -> ProtoId -> PP.Doc protoDesc' dex pid = case getProto dex pid of Nothing -> "<unknown prototype ID: " <> word16HexFixed pid <> ">" Just proto -> protoDesc dex proto methodStr :: DexFile -> MethodId -> PP.Doc methodStr dex mid = case getMethod dex mid of Nothing -> "<unknown method ID: " <> word16HexFixed mid <> ">" Just meth -> getTypeName'' dex (methClassId meth) <> "." <> getStr' dex (methNameId meth) <> ":" <> protoDesc' dex (methProtoId meth) methodStr' :: DexFile -> MethodId -> PP.Doc methodStr' dex mid = case getMethod dex mid of Nothing -> "<unknown method ID: " <> word16HexFixed mid <> ">" Just meth -> getTypeName' dex (methClassId meth) <> "." <> getStr' dex (methNameId meth) <> ":" <> protoDesc' dex (methProtoId meth) protoDesc :: DexFile -> Proto -> PP.Doc protoDesc dex proto = M.mconcat [ "(", argStr, ")", retStr ] where argStr = M.mconcat $ map (getTypeName' dex) (protoParams proto) retStr = getTypeName' dex (protoRet proto) prettyField :: String -> PP.Doc -> PP.Doc prettyField str v = padRight 20 str <> ":" <+> v prettyField16 :: String -> Word16 -> PP.Doc prettyField16 str (-1) = prettyField str "-1" prettyField16 str v = prettyField str (word16Dec v) prettyField32 :: String -> Word32 -> PP.Doc prettyField32 str (-1) = prettyField str "-1" prettyField32 str v = prettyField str (word32Dec v) prettyFieldHex :: String -> Word32 -> PP.Doc prettyFieldHex str v = prettyField str (M.mconcat [word32Dec v, "(0x ", word24HexFixed v, ")"]) prettyFieldHex4 :: String -> Word32 -> PP.Doc prettyFieldHex4 str v = prettyField str (M.mconcat [word32Dec v, " (0x", word16HexFixed (fromIntegral v), ")"]) prettyFieldHexS :: String -> Word32 -> PP.Doc -> PP.Doc prettyFieldHexS n v s = prettyField n $ M.mconcat [ "0x", hp v, " (", s, ")" ] where hp = if v >= 0x10000 then word20HexFixed else (word16HexFixed . fromIntegral) escape :: String -> String escape [] = [] escape ('\0' : s) = '\\' : '0' : escape s escape ('\n' : s) = '\\' : 'n' : escape s escape (c : s) = c : escape s escapebs :: BS.ByteString -> BS.ByteString escapebs = BS.pack . escape . BS.unpack prettyHeader :: FilePath -> DexHeader -> PP.Doc prettyHeader fp hdr = vsep [ "Opened" <+> PP.quotes (PP.text fp) <> ", DEX version " <> PP.quotes (pSDI (dexVersion hdr)) , "DEX file header:" , prettyField "magic" (PP.quotes (pSDI (escapebs (BS.append (dexMagic hdr) (dexVersion hdr))))) , prettyField "checksum" (word32HexFixed (dexChecksum hdr)) , prettyField "signature" sig , prettyField32 "file_size" (dexFileLen hdr) , prettyField32 "header_size" (dexHdrLen hdr) , prettyField32 "link_size" (dexLinkSize hdr) , prettyFieldHex "link_off" (dexLinkOff hdr) , prettyField32 "string_ids_size" (dexNumStrings hdr) , prettyFieldHex "string_ids_off" (dexOffStrings hdr) , prettyField32 "type_ids_size" (dexNumTypes hdr) , prettyFieldHex "type_ids_off" (dexOffTypes hdr) , prettyField32 "field_ids_size" (dexNumFields hdr) , prettyFieldHex "field_ids_off" (dexOffFields hdr) , prettyField32 "method_ids_size" (dexNumMethods hdr) , prettyFieldHex "method_ids_off" (dexOffMethods hdr) , prettyField32 "class_defs_size" (dexNumClassDefs hdr) , prettyFieldHex "class_defs_off" (dexOffClassDefs hdr) , prettyField32 "data_size" (dexDataSize hdr) , prettyFieldHex "data_off" (dexDataOff hdr) ] where sig = M.mconcat [ M.mconcat (take 2 sigStrings), "...", M.mconcat (drop 18 sigStrings) ] sigStrings = map word8HexFixed (dexSHA1 hdr) prettyClassDef :: DexFile -> (TypeId, Class) -> PP.Doc prettyClassDef dex (i, cls) = vsep [ PP.hcat [ "Class #", word16Dec i, " header:" ] , prettyField16 "class_idx" (classId cls) , prettyFieldHex4 "access_flags" (classAccessFlags cls) , prettyField16 "superclass_idx" (classSuperId cls) , prettyFieldHex "interfaces_off" (classInterfacesOff cls) , prettyField32 "source_file_idx" (classSourceNameId cls) , prettyFieldHex "annotations_off" (classAnnotsOff cls) , prettyFieldHex "class_data_off" (classDataOff cls) , prettyField32 "static_fields_size" (fromIntegral (length (classStaticFields cls))) , prettyField32 "instance_fields_size" (fromIntegral (length (classInstanceFields cls))) , prettyField32 "direct_methods_size" (fromIntegral (length (classDirectMethods cls))) , prettyField32 "virtual_methods_size" (fromIntegral (length (classVirtualMethods cls))) , "" , PP.hcat ["Class #", word16Dec i, " -"] , prettyField " Class descriptor" (PP.quotes (getTypeName' dex (classId cls))) , prettyFieldHexS " Access flags" (classAccessFlags cls) (AF.flagsString AF.AClass (classAccessFlags cls)) , prettyField " Superclass" (PP.quotes (getTypeName' dex (classSuperId cls))) , " Annotations -" , PP.nest 4 $ vsep (map (prettyVisibleAnnotation dex) cannots) , " Interfaces -" , vsep (map (prettyInterface dex) (zip [0..] (classInterfaces cls))) , " Static fields -" , vsep (map (prettyEncodedField dex fannots) (zip [0..] (classStaticFields cls))) , " Instance fields -" , vsep (map (prettyEncodedField dex fannots) (zip [0..] (classInstanceFields cls))) , " Direct methods -" , vsep (map (prettyEncodedMethod dex mannots) (zip [0..] (classDirectMethods cls))) , " Virtual methods -" , vsep (map (prettyEncodedMethod dex mannots) (zip [0..] (classVirtualMethods cls))) ] where ClassAnnotations { classAnnotationsAnnot = cannots , classFieldAnnotations = fannots , classMethodAnnotations = mannots } = classAnnotations cls prettyAnnotationVisibility :: AnnotationVisibility -> PP.Doc prettyAnnotationVisibility v = case v of AVBuild -> "BUILD" AVRuntime -> "RUNTIME" AVSystem -> "SYSTEM" prettyVisibleAnnotation :: DexFile -> VisibleAnnotation -> PP.Doc prettyVisibleAnnotation dex va = PP.hcat [ "<" <> prettyAnnotationVisibility (vaVisibility va) <> ">" , " " , prettyAnnotation dex (vaAnnotation va) ] prettyAnnotation :: DexFile -> Annotation -> PP.Doc prettyAnnotation dex a = getTypeName' dex (annotTypeId a) <> PP.parens (PP.hcat (PP.punctuate ", " (map prettyElement (annotElements a)))) where prettyElement (enameIx, eval) = getStr' dex enameIx <> "=" <> prettyEncodedValue dex eval prettyEncodedValue :: DexFile -> EncodedValue -> PP.Doc prettyEncodedValue dex ev = case ev of EncodedByte i -> "(int8)" <> PP.int (fromIntegral i) EncodedShort i -> "(int16)" <> PP.int (fromIntegral i) EncodedChar c -> PP.quotes (PP.char c) EncodedInt i -> "(int32)" <> PP.int (fromIntegral i) EncodedLong i -> "(int64)" <> PP.integer (fromIntegral i) EncodedFloat f -> "(float)" <> PP.float f EncodedDouble d -> "(double)" <> PP.double d EncodedStringRef sid -> PP.doubleQuotes (getStr' dex sid) EncodedTypeRef tid -> getTypeName' dex tid EncodedFieldRef fid -> fieldStr dex fid EncodedMethodRef mid -> methodStr dex mid EncodedEnumRef fid -> fieldStr dex fid EncodedArray vs -> PP.brackets $ PP.hcat (PP.punctuate ", " (map (prettyEncodedValue dex) vs)) EncodedAnnotation a -> prettyAnnotation dex a EncodedNull -> "(null)" EncodedBool b -> PP.text (show b) prettyInterface :: DexFile -> (Word32, TypeId) -> PP.Doc prettyInterface dex (n, iface) = M.mconcat [ " #", PP.int (fromIntegral n), ": ", PP.quotes (getTypeName' dex iface) ] prettyEncodedField :: DexFile -> [(FieldId, [VisibleAnnotation])] -> (Word32, EncodedField) -> PP.Doc prettyEncodedField dex _annots (n, f) = case getField dex (fieldId f) of Nothing -> "<unknown field ID: " <> word16HexFixed (fieldId f) <> ">" Just fld -> vsep [ M.mconcat [" #", word32Dec n, " : (in ", getTypeName' dex (fieldClassId fld), ")"] , prettyField " name" (PP.quotes (getStr' dex (fieldNameId fld))) , prettyField " type" (PP.quotes (getTypeName' dex (fieldTypeId fld))) , prettyFieldHexS " access" (fieldAccessFlags f) (AF.flagsString AF.AField (fieldAccessFlags f)) ] prettyEncodedMethod :: DexFile -> [(MethodId, [VisibleAnnotation])] -> (Word32, EncodedMethod) -> PP.Doc prettyEncodedMethod dex annots (n, m) = case (mmeth, mmeth >>= (getProto dex . methProtoId)) of (Just method, Just proto) -> let flags = methAccessFlags m adoc | Just vannots <- lookup (methId m) annots = " annots" $+$ PP.nest 8 (vsep (map (prettyVisibleAnnotation dex) vannots)) | otherwise = PP.empty in vsep [ " #" <> word32Dec n <> " : (in" <+> getTypeName' dex (methClassId method) <> ")" , prettyField " name" (PP.quotes (getStr' dex (methNameId method))) , prettyField " type" (PP.quotes (protoDesc dex proto)) , prettyFieldHexS " access" flags (AF.flagsString AF.AMethod flags) , adoc , maybe (" code: (none)") (prettyCode dex flags (methId m)) (methCode m) ] (Nothing, _) -> "<unknown method ID: " <> word16HexFixed (methId m) <> ">" (Just method, Nothing) -> "<unknown prototype ID: " <> word16HexFixed (methProtoId method) <> ">" where mmeth = getMethod dex (methId m) -- | Like 'PP.vcat', except it never collapses overlapping lines vsep :: [PP.Doc] -> PP.Doc vsep = F.foldl' ($+$) M.mempty prettyCode :: DexFile -> AF.AccessFlags -> MethodId -> CodeItem -> PP.Doc prettyCode dex flags mid codeItem = vsep [ " code -" , prettyField16 " registers" (codeRegs codeItem) , prettyField16 " ins" (codeInSize codeItem) , prettyField16 " outs" (codeOutSize codeItem) , prettyField " insns size" (word32Dec (fromIntegral (length insnUnits)) <+> "16-bit code units") , word24HexFixed nameAddr <> ": |[" <> word24HexFixed nameAddr <> "] " <> methodStr dex mid , insnText , prettyField " catches" (if null tries then "(none)" else word32Dec (fromIntegral (length tries))) , vsep (map (prettyTryBlock dex codeItem) tries) , prettyField " positions" "" , vsep (map prettyPosition (reverse (dbgPositions debugState))) , prettyField " locals" "" , vsep (map (prettyLocal dex) locals) ] where tries = codeTryItems codeItem insnUnits = codeInsns codeItem debugState = either (const DI.emptyDebugState) id (DI.executeDebugInsns dex codeItem flags mid) addr = codeInsnOff codeItem nameAddr = addr - 16 decodeErrorMsg = maybe "Unknown error" decodeErrorAsString . E.fromException insnText = either (\msg -> "error parsing instructions: " <> PP.text (decodeErrorMsg msg)) (formatInstructions dex addr 0 insnUnits) (decodeInstructions insnUnits) locals = L.sortBy cmpLocal [ (r, l) | (r, ls) <- Map.toList (dbgLocals debugState) , l <- ls , hasLocal l ] cmpLocal (_, LocalInfo n _ e _ _ _) (_, LocalInfo n' _ e' _ _ _) = compare (e, n) (e', n') hasLocal (LocalInfo _ _ _ nid _ _) = nid /= (-1) prettyLocal :: DexFile -> (Word32, LocalInfo) -> PP.Doc prettyLocal dex (r, LocalInfo _ s e nid tid sid) = M.mconcat [ " 0x", word16HexFixed (fromIntegral s), " - 0x", word16HexFixed (fromIntegral e) , " reg=", word32Dec r, " ", getStr' dex (fromIntegral nid), " " , getTypeName' dex (fromIntegral tid), " ", if sid == -1 then "" else getStr' dex (fromIntegral sid) ] prettyPosition :: PositionInfo -> PP.Doc prettyPosition (PositionInfo a l) = " 0x" <> word16HexFixed (fromIntegral a) <> " line=" <> word32Dec l prettyTryBlock :: DexFile -> CodeItem -> TryItem -> PP.Doc prettyTryBlock dex codeItem tryItem = vsep [ M.mconcat [ " 0x", word16HexFixed (fromIntegral (tryStartAddr tryItem)), " - 0x", word16HexFixed (fromIntegral end) ] , vsep [ " " <> getTypeName' dex ty <> " -> 0x" <> word16HexFixed (fromIntegral addr) | (ty, addr) <- handlers ] , vsep [ " <any> -> 0x" <> word16HexFixed (fromIntegral addr) | addr <- mapMaybe chAllAddr catches ] ] where end = tryStartAddr tryItem + fromIntegral (tryInsnCount tryItem) catches = filter ((== tryHandlerOff tryItem) . fromIntegral . chHandlerOff) (codeHandlers codeItem) handlers = M.mconcat (map chHandlers catches) formatInstructions :: DexFile -> Word32 -> Word32 -> [Word16] -> [Instruction] -> PP.Doc formatInstructions _ _ _ [] [] = M.mempty formatInstructions _ _ _ [] is = "ERROR: No more code units (" <> PP.text (show is) <> " instructions left)" formatInstructions _ _ _ ws [] = "ERROR: No more instructions (" <> PP.int (length ws) <> " code units left)" formatInstructions dex addr off ws (i:is) = M.mconcat [ word24HexFixed addr , ": " , unitDoc , "|" , word16HexFixed (fromIntegral off) , ": " , idoc ] $+$ formatInstructions dex (addr + (l' * 2)) (off + l') ws' is where (iws, ws') = L.splitAt l ws istrs = [ word8HexFixed (fromIntegral (w .&. 0x00FF)) <> word8HexFixed (fromIntegral ((w .&. 0xFF00) `shiftR` 8)) | w <- iws ] istrs' | length istrs < 8 = take 8 (istrs ++ repeat " ") | otherwise = take 7 istrs ++ ["... "] l = insnUnitCount i l' = fromIntegral l unitDoc = M.mconcat (PP.punctuate " " istrs') idoc = prettyInstruction dex off i prettyInstruction :: DexFile -> Word32 -> Instruction -> PP.Doc prettyInstruction _ _ Nop = "nop" <> " // spacer" prettyInstruction _ _ (Move mty dst src) = M.mconcat [ moveTypeString mty , moveSizeString dst, " " , regStr dst, ", ", regStr src ] prettyInstruction _ _ (Move1 MResult r) = "move-result " <> regStr r prettyInstruction _ _ (Move1 MResultWide r) = "move-result-wide " <> regStr r prettyInstruction _ _ (Move1 MResultObject r) = "move-result-object " <> regStr r prettyInstruction _ _ (Move1 MException r) = "move-exception " <> regStr r prettyInstruction _ _ ReturnVoid = "return-void" prettyInstruction _ _ (Return MNormal r) = "return " <> regStr r prettyInstruction _ _ (Return MWide r) = "return-wide " <> regStr r prettyInstruction _ _ (Return MObject r) = "return-object " <> regStr r prettyInstruction dex _ (LoadConst d c@(Const4 _)) = constStr dex "const/4" d c prettyInstruction dex _ (LoadConst d c@(Const16 _)) = constStr dex "const/16" d c prettyInstruction dex _ (LoadConst d c@(ConstHigh16 _)) = constStr dex "const/high16" d c prettyInstruction dex _ (LoadConst d c@(ConstWide16 _)) = constStr dex "const-wide/16" d c prettyInstruction dex _ (LoadConst d c@(Const32 _)) = constStr dex "const" d c prettyInstruction dex _ (LoadConst d c@(ConstWide32 _)) = constStr dex "const-wide/32" d c prettyInstruction dex _ (LoadConst d c@(ConstWide _)) = constStr dex "const-wide" d c prettyInstruction dex _ (LoadConst d c@(ConstWideHigh16 _)) = constStr dex "const-wide/high16" d c prettyInstruction dex _ (LoadConst d c@(ConstString _)) = constStr dex "const-string" d c prettyInstruction dex _ (LoadConst d c@(ConstStringJumbo _)) = constStr dex "const-string/jumbo" d c prettyInstruction dex _ (LoadConst d c@(ConstClass _)) = constStr dex "const-class" d c prettyInstruction _ _ (MonitorEnter r) = "monitor-enter v" <> word8Dec r prettyInstruction _ _ (MonitorExit r) = "monitor-exit v" <> word8Dec r prettyInstruction dex _ (CheckCast r tid) = M.mconcat ["check-cast v", word8Dec r, ", ", getTypeName' dex tid] <> typeComm tid prettyInstruction dex _ (InstanceOf dst ref tid) = mkInsn "instance-of" [ iregStr8 dst, iregStr8 ref, getTypeName' dex tid ] <> typeComm tid prettyInstruction _ _ (ArrayLength dst ref) = mkInsn'8 "array-length" [ dst, ref ] prettyInstruction dex _ (NewInstance dst tid) = mkInsn "new-instance" [ iregStr8 dst, getTypeName' dex tid ] <> typeComm tid prettyInstruction dex _ (NewArray dst sz tid) = mkInsn "new-array" [ iregStr8 dst, iregStr8 sz, getTypeName' dex tid ] <> typeComm tid prettyInstruction dex _ (FilledNewArray tid rs) = mkInsnb "filled-new-array" (map iregStr8 rs) [ getTypeName' dex tid ] <> typeComm tid prettyInstruction dex _ (FilledNewArrayRange tid rs) = mkInsnb "filled-new-array/range" (map iregStr16 rs) [ getTypeName' dex tid ] <> typeComm tid prettyInstruction _ a (FillArrayData dst off) = mkInsn "fill-array-data" [ iregStr8 dst, word32HexFixed (a + fromIntegral off) ] <> offComm' off prettyInstruction _ _ (Throw r) = "throw v" <> word8Dec r prettyInstruction _ a (Goto off) = "goto " <> word16HexFixed (fromIntegral (a + fromIntegral off)) <> offComm (fromIntegral off :: Int16) prettyInstruction _ a (Goto16 off) = "goto/16 " <> word16HexFixed (fromIntegral (a + fromIntegral off)) <> offComm off prettyInstruction _ a (Goto32 off) = "goto/32 " <> word32HexFixed (fromIntegral (a + fromIntegral off)) <> offComm32 off prettyInstruction _ a (PackedSwitch r off) = mkInsn "packed-switch" [ iregStr8 r, word32HexFixed (a + fromIntegral off) ] <> offComm' off prettyInstruction _ a (SparseSwitch r off) = mkInsn "sparse-switch" [ iregStr8 r, word32HexFixed (a + fromIntegral off) ] <> offComm' off prettyInstruction _ _ (Cmp CLFloat dst r1 r2) = mkInsn'8 "cmpl-float" [dst, r1, r2] prettyInstruction _ _ (Cmp CGFloat dst r1 r2) = mkInsn'8 "cmpg-float" [dst, r1, r2] prettyInstruction _ _ (Cmp CLDouble dst r1 r2) = mkInsn'8 "cmpl-double" [dst, r1, r2] prettyInstruction _ _ (Cmp CGDouble dst r1 r2) = mkInsn'8 "cmpg-double" [dst, r1, r2] prettyInstruction _ _ (Cmp CLong dst r1 r2) = mkInsn'8 "cmp-long" [dst, r1, r2] prettyInstruction _ a (If op r1 r2 off) = mkInsn ("if-" <> ifOpStr op) [ iregStr8 r1, iregStr8 r2 , word16HexFixed (fromIntegral (a + fromIntegral off)) ] <> offComm off prettyInstruction _ a (IfZero op r off) = mkInsn ("if-" <> ifOpStr op <> "z") [ iregStr8 r, word16HexFixed (fromIntegral (a + fromIntegral off)) ] <> offComm off prettyInstruction _ _ (ArrayOp op val arr idx) = mkInsn'8 ("a" <> accessOpStr op) [ val, arr, idx ] prettyInstruction dex _ (InstanceFieldOp op val obj fid) = mkInsn ("i" <> accessOpStr op) [ iregStr8 val, iregStr8 obj, fieldStr dex fid ] <> fieldComm fid prettyInstruction dex _ (StaticFieldOp op val fid) = mkInsn ("s" <> accessOpStr op) [ iregStr8 val, fieldStr dex fid ] <> fieldComm fid prettyInstruction dex _ (Invoke kind range mid args) = mkInsn ("invoke-" <> ikindStr kind <> if range then "/range" else "") [ PP.brackets (M.mconcat (PP.punctuate ", " (map iregStr16 args))) , methodStr' dex mid ] <> methodComm mid prettyInstruction _ _ (Unop op r1 r2) = mkInsn'8 (unopStr op) [r1, r2] prettyInstruction _ _ (IBinop op False dst r1 r2) = mkInsn'8 (binopStr op <> "-int") [ dst, r1, r2 ] prettyInstruction _ _ (IBinop op True dst r1 r2) = mkInsn'8 (binopStr op <> "-long") [ dst, r1, r2 ] prettyInstruction _ _ (FBinop op False dst r1 r2) = mkInsn'8 (binopStr op <> "-float") [ dst, r1, r2 ] prettyInstruction _ _ (FBinop op True dst r1 r2) = mkInsn'8 (binopStr op <> "-double") [ dst, r1, r2 ] prettyInstruction _ _ (IBinopAssign op False dst src) = mkInsn'8 (binopStr op <> "-int/2addr") [ dst, src ] prettyInstruction _ _ (IBinopAssign op True dst src) = mkInsn'8 (binopStr op <> "-long/2addr") [ dst, src ] prettyInstruction _ _ (FBinopAssign op False dst src) = mkInsn'8 (binopStr op <> "-float/2addr") [ dst, src ] prettyInstruction _ _ (FBinopAssign op True dst src) = mkInsn'8 (binopStr op <> "-double/2addr") [ dst, src ] prettyInstruction _ _ (BinopLit16 RSub dst src i) = mkInsn "rsub-int" [iregStr8 dst, iregStr8 src, "#int " <> int16Dec i] <> intComm16' (fromIntegral i) prettyInstruction _ _ (BinopLit16 op dst src i) = mkInsn (binopStr op <> "-int/lit16") [iregStr8 dst, iregStr8 src, "#int " <> int16Dec i] <> intComm16' (fromIntegral i) prettyInstruction _ _ (BinopLit8 op dst src i) = mkInsn (binopStr op <> "-int/lit8") [iregStr8 dst, iregStr8 src, "#int " <> int8Dec i] <> intComm8' (fromIntegral i) prettyInstruction _ _ i@(PackedSwitchData{}) = "packed-switch-data (" <> int32Dec (fromIntegral size) <> " units)" where size = insnUnitCount i prettyInstruction _ _ i@(SparseSwitchData{}) = "sparse-switch-data (" <> int32Dec (fromIntegral size) <> " units)" where size = insnUnitCount i prettyInstruction _ _ i@(ArrayData{}) = "array-data (" <> int32Dec (fromIntegral size) <> " units)" where size = insnUnitCount i -- Helpers -- | Right pad a string with spaces until it is the specified width padRight :: Int -> String -> PP.Doc padRight n s = PP.text (s ++ replicate (n - length s) ' ') -- | Lift a bytestring into a 'Doc' unsafely pSDI :: BS.ByteString -> PP.Doc pSDI = PP.text . BS.unpack mkInsn :: PP.Doc -> [PP.Doc] -> PP.Doc mkInsn name args = name <+> M.mconcat (PP.punctuate ", " args) {-# INLINE mkInsn #-} mkInsn'8 :: PP.Doc -> [Word8] -> PP.Doc mkInsn'8 name args = mkInsn name (map iregStr8 args) {-# INLINE mkInsn'8 #-} mkInsnb :: PP.Doc -> [PP.Doc] -> [PP.Doc] -> PP.Doc mkInsnb name bargs args = name <+> PP.braces (M.mconcat (PP.punctuate ", " bargs)) <> "," <+> M.mconcat (PP.punctuate ", " args) {-# INLINE mkInsnb #-} word16Hex :: Word16 -> PP.Doc word16Hex w = PP.text (printf "%x" w) word16HexFixed :: Word16 -> PP.Doc word16HexFixed w = PP.text (printf "%0.4x" w) word8Hex :: Word8 -> PP.Doc word8Hex w = PP.text (printf "%x" w) word8HexFixed :: Word8 -> PP.Doc word8HexFixed w = PP.text (printf "%0.2x" w) word24HexFixed :: Word32 -> PP.Doc word24HexFixed w = M.mconcat [ word8HexFixed (fromIntegral (w .&. 0x00FF0000) `shiftR` 16) , word16HexFixed (fromIntegral (w .&. 0x0000FFFF)) ] word20HexFixed :: Word32 -> PP.Doc word20HexFixed w = M.mconcat [ word8Hex (fromIntegral (w .&. 0x00FF0000) `shiftR` 16) , word16HexFixed (fromIntegral (w .&. 0x0000FFFF)) ] word32HexFixed :: Word32 -> PP.Doc word32HexFixed w = PP.text (printf "%0.8x" w) word64HexFixed :: Word64 -> PP.Doc word64HexFixed w = PP.text (printf "%0.16x" w) int16HexFixed :: Int16 -> PP.Doc int16HexFixed w = PP.text (printf "%0.4x" w) int32HexFixed :: Int32 -> PP.Doc int32HexFixed w = PP.text (printf "%0.8x" w) word8Dec :: Word8 -> PP.Doc word8Dec w = PP.text (printf "%d" w) word16Dec :: Word16 -> PP.Doc word16Dec w = PP.text (printf "%d" w) word32Dec :: Word32 -> PP.Doc word32Dec w = PP.text (printf "%d" w) int8Dec :: Int8 -> PP.Doc int8Dec w = PP.text (printf "%d" w) int16Dec :: Int16 -> PP.Doc int16Dec w = PP.text (printf "%d" w) int32Dec :: Int32 -> PP.Doc int32Dec w = PP.text (printf "%d" w) int64Dec :: Int64 -> PP.Doc int64Dec w = PP.text (printf "%d" w)
travitch/dalvik
src/Dalvik/Printer.hs
bsd-3-clause
30,900
0
20
7,157
10,901
5,512
5,389
657
16
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DataKinds #-} module Main where import Numeric.HXSC import Numeric.HXSC.Internal import Text.Printf -- import qualified Data.Vector as V -- import qualified Data.Vector.Storable as V import qualified Data.Vector.Unboxed as V import System.Random.MWC import Control.DeepSeq (force) import Control.Exception (evaluate) import Criterion.Main lconst :: a -> b -> b lconst _ b = b main :: IO () main = do xs <- evaluate . force $ V.iterateN 1000000 (+0.1) 0 let x = 2.0 :: Double y = 0.3 :: Double n = 9007199254740993 :: Int putStrLn "" printf "%d \\in (%.20f, %.20f)\n" n (fromIntD n) (fromIntU n) printf "sqrt(%f) \\in (%.20f, %.20f)\n" x (sqrtD x) (sqrtU x) printf "%f + %f \\in (%.20f, %.20f)\n" x y (plusD x y) (plusU x y) printf "%f + %f \\in (%.20f, %.20f)\n" x y (plusD' x y) (plusU' x y) defaultMain [ -- bgroup "single" [ bench "nop" $ nf ( id ) (x, y) -- , bench "plusD" $ nf (uncurry plusD) (x, y) -- , bench "plusN" $ nf (uncurry plusN) (x, y) -- , bench "plus." $ nf (uncurry (+) ) (x, y) -- , bench "plusU" $ nf (uncurry plusU) (x, y) -- ] -- , bgroup "multiple" [ bench "nop" $ nf (V.foldl' const (0 :: Double)) xs , bench "plus." $ nf (V.foldl' (+) 0) xs , bench "plusN" $ nf (V.foldl' plusN 0) xs , bench "plusU" $ nf (V.foldl' plusU 0) xs , bench "plusU'" $ nf (V.foldl' plusU' 0) xs -- , bench "plusUV" $ nf vsumU xs , bench "plusD" $ nf (V.foldl' plusD 0) xs -- , bench "plusDV" $ nf vsumD xs , bench "plusD'" $ nf (V.foldl' plusD' 0) xs ]]
dlilja/hxsc
example/example.hs
bsd-3-clause
2,078
0
15
857
478
250
228
31
1
{- Baseclasses for Map-like and Set-like collections inspired by containers. -} {-# LANGUAGE TypeFamilies #-} module Compiler.Hoopl.Collections ( IsSet(..) , setInsertList, setDeleteList, setUnions , IsMap(..) , mapInsertList, mapDeleteList, mapUnions ) where import Data.List (foldl', foldl1') class IsSet set where type ElemOf set setNull :: set -> Bool setSize :: set -> Int setMember :: ElemOf set -> set -> Bool setEmpty :: set setSingleton :: ElemOf set -> set setInsert :: ElemOf set -> set -> set setDelete :: ElemOf set -> set -> set setUnion :: set -> set -> set setDifference :: set -> set -> set setIntersection :: set -> set -> set setIsSubsetOf :: set -> set -> Bool setFold :: (ElemOf set -> b -> b) -> b -> set -> b setElems :: set -> [ElemOf set] setFromList :: [ElemOf set] -> set -- Helper functions for IsSet class setInsertList :: IsSet set => [ElemOf set] -> set -> set setInsertList keys set = foldl' (flip setInsert) set keys setDeleteList :: IsSet set => [ElemOf set] -> set -> set setDeleteList keys set = foldl' (flip setDelete) set keys setUnions :: IsSet set => [set] -> set setUnions [] = setEmpty setUnions sets = foldl1' setUnion sets class IsMap map where type KeyOf map mapNull :: map a -> Bool mapSize :: map a -> Int mapMember :: KeyOf map -> map a -> Bool mapLookup :: KeyOf map -> map a -> Maybe a mapFindWithDefault :: a -> KeyOf map -> map a -> a mapEmpty :: map a mapSingleton :: KeyOf map -> a -> map a mapInsert :: KeyOf map -> a -> map a -> map a mapDelete :: KeyOf map -> map a -> map a mapUnion :: map a -> map a -> map a mapUnionWithKey :: (KeyOf map -> a -> a -> a) -> map a -> map a -> map a mapDifference :: map a -> map a -> map a mapIntersection :: map a -> map a -> map a mapIsSubmapOf :: Eq a => map a -> map a -> Bool mapMap :: (a -> b) -> map a -> map b mapMapWithKey :: (KeyOf map -> a -> b) -> map a -> map b mapFold :: (a -> b -> b) -> b -> map a -> b mapFoldWithKey :: (KeyOf map -> a -> b -> b) -> b -> map a -> b mapElems :: map a -> [a] mapKeys :: map a -> [KeyOf map] mapToList :: map a -> [(KeyOf map, a)] mapFromList :: [(KeyOf map, a)] -> map a -- Helper functions for IsMap class mapInsertList :: IsMap map => [(KeyOf map, a)] -> map a -> map a mapInsertList assocs map = foldl' (flip (uncurry mapInsert)) map assocs mapDeleteList :: IsMap map => [KeyOf map] -> map a -> map a mapDeleteList keys map = foldl' (flip mapDelete) map keys mapUnions :: IsMap map => [map a] -> map a mapUnions [] = mapEmpty mapUnions maps = foldl1' mapUnion maps
ezyang/hoopl
src/Compiler/Hoopl/Collections.hs
bsd-3-clause
2,742
0
11
738
1,098
555
543
60
1
{-# LANGUAGE Unsafe #-} -- | It defines main data structures for security, i.e., monad family 'MAC' and labeled resources 'Res'. module MAC.Core ( -- Resources definitions Res (MkRes,unRes) , labelOf -- Monad MAC , MAC (MkMAC) , runMAC -- IO actions into MAC , ioTCB ) where import Control.Applicative -- | Labeling expressions of type @a@ with label @l@. newtype Res l a = MkRes {unRes :: a} -- | Label of resources labelOf :: Res l a -> l labelOf _res = undefined {-| This monad labels the results of the computation (of type @a@) with label @l@. -} --newtype MAC l a = MkMAC {unMAC :: IO a} newtype MAC l a = MkMAC (IO a) instance Functor (MAC l) where fmap f (MkMAC io) = MkMAC (fmap f io) instance Applicative (MAC l) where pure = MkMAC . return (<*>) (MkMAC f) (MkMAC a) = MkMAC (f <*> a) instance Monad (MAC l) where return = pure MkMAC m >>= k = ioTCB (m >>= runMAC . k) -- | It lifts arbitrary 'IO'-actions. ioTCB :: IO a -> MAC l a ioTCB = MkMAC -- Should not be exported! -- | Execute secure computations. runMAC :: MAC l a -> IO a runMAC (MkMAC m) = m
alejandrorusso/mac-privacy
MAC/Core.hs
bsd-3-clause
1,148
0
9
296
301
169
132
30
1
module Problem38 where import Data.List (find) import Data.Maybe (mapMaybe) import Problem32 (digits, fromDigits, isPandigital) -- -- Problem 38: Pandigital multiples -- -- Take the number 192 and multiply it by each of 1, 2, and 3: -- -- 192 × 1 = 192 -- 192 × 2 = 384 -- 192 × 3 = 576 -- -- By concatenating each product we get the 1 to 9 pandigital, 192384576. We -- will call 192384576 the concatenated product of 192 and (1,2,3) -- -- The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, -- and 5, giving the pandigital, 918273645, which is the concatenated product of -- 9 and (1,2,3,4,5). -- -- What is the largest 1 to 9 pandigital 9-digit number that can be formed as -- the concatenated product of an integer with (1,2, ... , n) where n > 1? problem38 :: Int problem38 = maximum $ map (fromDigits . makePandigitalMultiple) searchAll where searchAll = mapMaybe (find isPandigitalMultiple . searchLength) [1..4] searchLength len = reverse [10^len..10^(len+1)-1] isPandigitalMultiple :: Int -> Bool isPandigitalMultiple x = length allDigits == 9 && isPandigital allDigits where allDigits = makePandigitalMultiple x makePandigitalMultiple :: Int -> [Int] makePandigitalMultiple x = concatMap digits products where xNumDigits = length (digits x) products = map (* x) [1..(9 `div` xNumDigits)]
c0deaddict/project-euler
src/Part1/Problem38.hs
bsd-3-clause
1,370
0
12
267
254
146
108
15
1
import Test.Framework (defaultMain) import qualified HStyle.Block.Tests (tests) main :: IO () main = defaultMain [ HStyle.Block.Tests.tests ]
mightybyte/hstyle
tests/TestSuite.hs
bsd-3-clause
152
0
7
27
48
28
20
5
1
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports#-} module Data.KeyStore.KS.Opt ( Opt , OptEnum(..) , opt_enum , getSettingsOpt , getSettingsOpt' , setSettingsOpt , opt__debug_enabled , opt__verify_enabled , opt__sections_fix , opt__backup_keys , opt__hash_comment , opt__hash_prf , opt__hash_iterations , opt__hash_width_octets , opt__hash_salt_octets , opt__crypt_cipher , opt__crypt_prf , opt__crypt_iterations , opt__crypt_salt_octets , Opt_(..) , opt_ , listSettingsOpts , optHelp , optName , parseOpt ) where import Data.KeyStore.Types import qualified Data.Vector as V import qualified Data.Map as Map import qualified Data.ByteString.Lazy.Char8 as LBS import qualified Data.HashMap.Strict as HM import Data.Aeson import qualified Data.Text as T import Data.Monoid import Data.Maybe import Data.Char import Text.Printf data Opt a = Opt { opt_enum :: OptEnum , opt_default :: a , opt_from :: Value -> a , opt_to :: a -> Value , opt_help :: Help } data Help = Help { hlp_text :: [T.Text] , hlp_type :: T.Text } deriving Show getSettingsOpt :: Opt a -> Settings -> a getSettingsOpt opt = maybe (opt_default opt) id . getSettingsOpt' opt getSettingsOpt' :: Opt a -> Settings -> Maybe a getSettingsOpt' Opt{..} (Settings hm) = opt_from <$> HM.lookup (optName opt_enum) hm setSettingsOpt :: Opt a -> a -> Settings -> Settings setSettingsOpt Opt{..} x (Settings hm) = Settings $ HM.insert (optName opt_enum) (opt_to x) hm opt__debug_enabled :: Opt Bool opt__debug_enabled = bool_opt dbg_help False Debug__enabled opt__verify_enabled :: Opt Bool opt__verify_enabled = bool_opt vfy_help False Verify__enabled opt__sections_fix :: Opt Bool opt__sections_fix = bool_opt sfx_help False Sections__fix opt__backup_keys :: Opt [Name] opt__backup_keys = backup_opt bku_help Backup__keys opt__hash_comment :: Opt Comment opt__hash_comment = text_opt hcm_help (Comment ,_Comment) "" Hash__comment opt__hash_prf :: Opt HashPRF opt__hash_prf = enum_opt hpr_help _text_HashPRF PRF_sha512 Hash__prf opt__hash_iterations :: Opt Iterations opt__hash_iterations = intg_opt hit_help (Iterations,_Iterations) 5000 Hash__iterations opt__hash_width_octets :: Opt Octets opt__hash_width_octets = intg_opt hwd_help (Octets ,_Octets ) 64 Hash__width_octets opt__hash_salt_octets :: Opt Octets opt__hash_salt_octets = intg_opt hna_help (Octets ,_Octets ) 16 Hash__salt_octets opt__crypt_cipher :: Opt Cipher opt__crypt_cipher = enum_opt ccy_help _text_Cipher CPH_aes256 Crypt__cipher opt__crypt_prf :: Opt HashPRF opt__crypt_prf = enum_opt cpr_help _text_HashPRF PRF_sha512 Crypt__prf opt__crypt_iterations :: Opt Iterations opt__crypt_iterations = intg_opt cit_help (Iterations,_Iterations) 5000 Crypt__iterations opt__crypt_salt_octets :: Opt Octets opt__crypt_salt_octets = intg_opt cna_help (Octets ,_Octets ) 16 Crypt__salt_octets data OptEnum = Debug__enabled | Verify__enabled | Sections__fix | Backup__keys | Hash__comment | Hash__prf | Hash__iterations | Hash__width_octets | Hash__salt_octets | Crypt__cipher | Crypt__prf | Crypt__iterations | Crypt__salt_octets deriving (Bounded,Enum,Eq,Ord,Show) data Opt_ = forall a. Opt_ (Opt a) opt_ :: OptEnum -> Opt_ opt_ enm = case enm of Debug__enabled -> Opt_ opt__debug_enabled Verify__enabled -> Opt_ opt__verify_enabled Sections__fix -> Opt_ opt__sections_fix Backup__keys -> Opt_ opt__backup_keys Hash__comment -> Opt_ opt__hash_comment Hash__prf -> Opt_ opt__hash_prf Hash__iterations -> Opt_ opt__hash_iterations Hash__width_octets -> Opt_ opt__hash_width_octets Hash__salt_octets -> Opt_ opt__hash_salt_octets Crypt__cipher -> Opt_ opt__crypt_cipher Crypt__prf -> Opt_ opt__crypt_prf Crypt__iterations -> Opt_ opt__crypt_iterations Crypt__salt_octets -> Opt_ opt__crypt_salt_octets listSettingsOpts :: Maybe OptEnum -> T.Text listSettingsOpts Nothing = T.unlines $ map optName [minBound..maxBound] listSettingsOpts (Just oe) = optHelp oe optHelp :: OptEnum -> T.Text optHelp = help . opt_ help :: Opt_ -> T.Text help (Opt_ Opt{..}) = T.unlines $ map f [ (,) pth "" , (,) " type:" hlp_type , (,) " default:" dflt , (,) "" "" ] <> map (" "<>) hlp_text where f (l,v) = T.pack $ printf "%-12s %s" (T.unpack l) (T.unpack v) pth = optName opt_enum dflt = T.pack $ LBS.unpack $ encode $ opt_to opt_default Help{..} = opt_help optName :: OptEnum -> T.Text optName opt = T.pack $ map toLower grp ++ "." ++ drop 2 __nme where (grp,__nme) = splitAt (f (-1) ' ' so) so where f i _ [] = i+1 f i '_' ('_':_) = i f i _ (h:t) = f (i+1) h t so = show opt parseOpt :: T.Text -> Maybe OptEnum parseOpt txt = listToMaybe [ oe | oe<-[minBound..maxBound], optName oe==txt ] backup_opt :: [T.Text] -> OptEnum -> Opt [Name] backup_opt hp ce = Opt { opt_enum = ce , opt_default = [] , opt_from = frm , opt_to = Array . V.fromList . map (String . T.pack . _name) , opt_help = Help hp "[<string>]" } where frm val = case val of Array v -> catMaybes $ map extr $ V.toList v _ -> [] extr val = case val of String t | Right nm <- name $ T.unpack t -> Just nm _ -> Nothing bool_opt :: [T.Text] -> Bool -> OptEnum -> Opt Bool bool_opt hp x0 ce = Opt { opt_enum = ce , opt_default = x0 , opt_from = frm , opt_to = Bool , opt_help = Help hp "<boolean>" } where frm v = case v of Bool b -> b _ -> x0 intg_opt :: [T.Text] -> (Int->a,a->Int) -> a -> OptEnum -> Opt a intg_opt hp (inj,prj) x0 ce = Opt { opt_enum = ce , opt_default = x0 , opt_from = frm , opt_to = toJSON . prj , opt_help = Help hp "<integer>" } where frm v = case fromJSON v of Success i -> inj i _ -> x0 text_opt :: [T.Text] -> (T.Text->a,a->T.Text) -> a -> OptEnum -> Opt a text_opt hp (inj,prj) x0 ce = Opt { opt_enum = ce , opt_default = x0 , opt_from = frm , opt_to = String . prj , opt_help = Help hp "<string>" } where frm v = case v of String t -> inj t _ -> x0 enum_opt :: (Bounded a,Enum a) => [T.Text] -> (a->T.Text) -> a -> OptEnum -> Opt a enum_opt hp shw x0 ce = Opt { opt_enum = ce , opt_default = x0 , opt_from = frm , opt_to = String . shw , opt_help = Help hp typ } where frm v = case v of String s | Just x <- Map.lookup s mp -> x _ -> x0 mp = Map.fromList [ (shw v,v) | v<-[minBound..maxBound] ] typ = T.intercalate "|" $ map shw [minBound..maxBound] dbg_help, vfy_help, sfx_help, bku_help, hcm_help, hpr_help, hit_help, hwd_help, hna_help, ccy_help, cpr_help, cit_help, cna_help :: [T.Text] dbg_help = ["Controls whether debug output is enabled or not." ] vfy_help = [ "Controls whether verification mode is enabled or not," , "in which the secret text loaded from environment" , "variables is checked against the stored MACs." , "These checks can consume a lot of compute time." ] sfx_help = [ "Set when a 'Sections' keystore has been fixed so that" , "section, key and host names no longer contrained to avoid" , "prefixes." ] bku_help = [ "Controls the default keys that will be used to make secret copies" , "(i.e., backup) each key. Each key may individually specify their" , "backup/save keys which will operate in addition to those specify here." , "This setting usually set to empty globally accross a keystore but" , "triggered to backup keys on a per-section basis with the section's" , "backup key." ] hcm_help = [ "Controls the default comment attribute for hashes." ] hpr_help = [ "Controls the default psuedo-random/hash function used in the PBKDF2" , "function used to generate the MACs." ] hit_help = [ "Controls the default number of iterations used in the PBKDF2" , "function used to generate the MACs." ] hwd_help = [ "Controls the default width (in bytes) of the output of the PBKDF2" , "function used to generate the MACs." ] hna_help = [ "Controls the default width (in bytes) of the salt generated for the PBKDF2" , "function used to generate the MACs." ] ccy_help = [ "Controls the default cipher used to encrypt the keys." ] cpr_help = [ "Controls the default psuedo-random/hash function used in the PBKDF2." , "function used to generate the cipher keys." ] cit_help = [ "Controls the default number of iterations used in the PBKDF2" , "function used to generate cipher keys." ] cna_help = [ "Controls the default width (in bytes) of the salt generated for the PBKDF2" , "function used to generate cipher keys." ]
cdornan/keystore
src/Data/KeyStore/KS/Opt.hs
bsd-3-clause
10,201
0
16
3,282
2,415
1,318
1,097
254
13
-- | Nelson-Oppen Procedure for Combining Theory Solvers module Language.Nano.SMT.NelsonOppen (theory_solver) where import Language.Nano.SMT.Types import Control.Monad.State import qualified Data.HashMap.Strict as M import qualified Data.HashSet as S import Control.Applicative ((<$>)) import qualified Language.Nano.SMT.CongClos as CC ------------------------------------------------------------------------------- -- | `theory_solver` returns the `k` belonging to the conflicting `Atom` -- or empty list if the conjunction of `[Atom]` is satisfiable theory_solver :: TheoryCube k -> [k] theory_solver kas = runState (theory_solver' kas) st0 where (ks, as) = unzip kas st0 = NOST M.empty M.empty S.empty M.empty solvers 0 theory_solver' ks atoms = do hatoms <- mapM hashConsAtom atoms let km = M.fromList $ zip (hid <$> hatoms) ks res <- crunch core <- resultHAtoms res return $ [km ! hid a | a <- core] solvers = [SS cc0] -- DiffBound.solver where cc0 = init :: CCState ------------------------------------------------------------------------------ -- | Transitively grind causes down into [HAtom] ----------------------------- ------------------------------------------------------------------------------ resultHAtoms :: Maybe Cause -> NO [HAtom] resultHAtoms Nothing = return [] resultHAtoms (Just is) = ((`grindCauses` is) . causes) <$> get grindCauses :: M.HashMap HId [HId] -> [HId] -> [HId] grindCauses cm = sortNub . goMany where go i = maybe [] goMany (M.lookup i cm) goMany = concatMap go ------------------------------------------------------------------------------ -- | State for Nelson-Oppen Engine ------------------------------------------- ------------------------------------------------------------------------------ data NelsonOppenState = NOST { exprs :: HashMap HId HExpr , atoms :: HashMap HId HAtom , equalities :: HashSet (HId, HId) , causes :: HashMap HId [HId] , solvers :: [Solver] , counter :: Int } ------------------------------------------------------------------------------- -- | crunch atoms == Nothing means atoms is SAT, Just c means CONTRA ------------------------------------------------------------------------------- crunch :: [HAtoms] -> NO (Maybe Cause) crunch [] = return Nothing crunch eqs = do ss <- solvers <$> get case crunchSolvers ss eqs of (_ , Contra c) -> return (Just c) (ss', Eqs xs ) -> updSolvers ss' >> updEqualities xs >>= crunch updSolvers :: [Solver] -> NO () updSolvers ss = modify $ \st -> st {solvers = ss } crunchSolvers :: [Solver] -> [HAtom] -> ([Solver], SolveResult) crunchSolvers solvers as = (solvers', mconcat result) where (solvers', results) = unzip $ map (`crunchSolver` as) solvers crunchSolver :: Solver -> [HAtom] -> (Solver, SolveResult) crunchSolver (SS state) as = (SS state', result) where (result, state') = upd as state ------------------------------------------------------------------------------ -- | Registering New Equalities ---------------------------------------------- ------------------------------------------------------------------------------ updEqualities :: [Equality] -> NO [HAtom] updEqualities eqs = do known <- equalities <$> get let eqs' = [e | e <- eqs, (lhs e, rhs e) `S.notElem` known] mapM addEq eqs' addEq :: (Eq x y c) -> NO HAtom addEq (Eq x y c) = do a <- hashConsAtom $ Rel Eq [x, y] modify $ \st -> { causes = H.insert (hid a) c (causes st) } { equalities = S.insert (x, y) (equalities st) } return a -------------------------------------------------------------------- -- | Hash Consing: Building the DAG -------------------------------- -------------------------------------------------------------------- fresh :: NO Int fresh = do st <- get let n = counter st put $ st { counter = n + 1 } return n -------------------------------------------------------------------- hashConsAtom :: Atom -> NO HAtom hashConsAtom = undefined hashConsExpr :: Expr -> NO HExpr hashConsExpr = undefined --------------------------------------------------------------------
UCSD-PL/nano-smt
Language/Nano/SMT/NelsonOppen.hs
bsd-3-clause
4,398
0
14
941
1,109
598
511
-1
-1
{-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 701 {-# LANGUAGE Safe #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Text.PrettyPrint.HughesPJClass -- Copyright : (c) Lennart Augustsson 2014 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : David Terei <[email protected]> -- Stability : stable -- Portability : portable -- -- Pretty printing class, simlar to 'Show' but nicer looking. -- -- Note that the precedence level is a 'Rational' so there is an unlimited -- number of levels. This module re-exports 'Text.PrettyPrint.HughesPJ'. -- ----------------------------------------------------------------------------- module Text.PrettyPrint.MarkedHughesPJClass ( -- * Pretty typeclass Pretty(..), PrettyLevel(..), prettyNormal, prettyShow, prettyParen, -- re-export HughesPJ module Text.PrettyPrint.MarkedHughesPJ ) where import Text.PrettyPrint.MarkedHughesPJ -- | Level of detail in the pretty printed output. -- Level 0 is the least detail. newtype PrettyLevel = PrettyLevel Int deriving (Eq, Ord, Show) -- | The "normal" (Level 0) of detail. prettyNormal :: PrettyLevel prettyNormal = PrettyLevel 0 -- | Pretty printing class. The precedence level is used in a similar way as in -- the 'Show' class. Minimal complete definition is either 'pPrintPrec' or -- 'pPrint'. class Pretty a where pPrintPrec :: PrettyLevel -> Rational -> a -> MDoc b pPrintPrec _ _ = pPrint pPrint :: a -> MDoc b pPrint = pPrintPrec prettyNormal 0 pPrintList :: PrettyLevel -> [a] -> MDoc b pPrintList l = brackets . fsep . punctuate comma . map (pPrintPrec l 0) #if __GLASGOW_HASKELL__ >= 708 {-# MINIMAL pPrintPrec | pPrint #-} #endif -- | Pretty print a value with the 'prettyNormal' level. prettyShow :: (Pretty a) => a -> String prettyShow = render . pPrint pPrint0 :: (Pretty a) => PrettyLevel -> a -> MDoc b pPrint0 l = pPrintPrec l 0 appPrec :: Rational appPrec = 10 -- | Parenthesize an value if the boolean is true. {-# DEPRECATED prettyParen "Please use 'maybeParens' instead" #-} prettyParen :: Bool -> MDoc a -> MDoc a prettyParen = maybeParens -- Various Pretty instances instance Pretty Int where pPrint = int instance Pretty Integer where pPrint = integer instance Pretty Float where pPrint = float instance Pretty Double where pPrint = double instance Pretty () where pPrint _ = text "()" instance Pretty Bool where pPrint = text . show instance Pretty Ordering where pPrint = text . show instance Pretty Char where pPrint = char pPrintList _ = text . show instance (Pretty a) => Pretty (Maybe a) where pPrintPrec _ _ Nothing = text "Nothing" pPrintPrec l p (Just x) = prettyParen (p > appPrec) $ text "Just" <+> pPrintPrec l (appPrec+1) x instance (Pretty a, Pretty b) => Pretty (Either a b) where pPrintPrec l p (Left x) = prettyParen (p > appPrec) $ text "Left" <+> pPrintPrec l (appPrec+1) x pPrintPrec l p (Right x) = prettyParen (p > appPrec) $ text "Right" <+> pPrintPrec l (appPrec+1) x instance (Pretty a) => Pretty [a] where pPrintPrec l _ = pPrintList l instance (Pretty a, Pretty b) => Pretty (a, b) where pPrintPrec l _ (a, b) = parens $ fsep $ punctuate comma [pPrint0 l a, pPrint0 l b] instance (Pretty a, Pretty b, Pretty c) => Pretty (a, b, c) where pPrintPrec l _ (a, b, c) = parens $ fsep $ punctuate comma [pPrint0 l a, pPrint0 l b, pPrint0 l c] instance (Pretty a, Pretty b, Pretty c, Pretty d) => Pretty (a, b, c, d) where pPrintPrec l _ (a, b, c, d) = parens $ fsep $ punctuate comma [pPrint0 l a, pPrint0 l b, pPrint0 l c, pPrint0 l d] instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e) => Pretty (a, b, c, d, e) where pPrintPrec l _ (a, b, c, d, e) = parens $ fsep $ punctuate comma [pPrint0 l a, pPrint0 l b, pPrint0 l c, pPrint0 l d, pPrint0 l e] instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e, Pretty f) => Pretty (a, b, c, d, e, f) where pPrintPrec l _ (a, b, c, d, e, f) = parens $ fsep $ punctuate comma [pPrint0 l a, pPrint0 l b, pPrint0 l c, pPrint0 l d, pPrint0 l e, pPrint0 l f] instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e, Pretty f, Pretty g) => Pretty (a, b, c, d, e, f, g) where pPrintPrec l _ (a, b, c, d, e, f, g) = parens $ fsep $ punctuate comma [pPrint0 l a, pPrint0 l b, pPrint0 l c, pPrint0 l d, pPrint0 l e, pPrint0 l f, pPrint0 l g] instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e, Pretty f, Pretty g, Pretty h) => Pretty (a, b, c, d, e, f, g, h) where pPrintPrec l _ (a, b, c, d, e, f, g, h) = parens $ fsep $ punctuate comma [pPrint0 l a, pPrint0 l b, pPrint0 l c, pPrint0 l d, pPrint0 l e, pPrint0 l f, pPrint0 l g, pPrint0 l h]
ku-fpg/marked-pretty
src/Text/PrettyPrint/MarkedHughesPJClass.hs
bsd-3-clause
4,833
0
10
1,059
1,674
904
770
79
1
module Matterhorn.State.ChannelListOverlay ( enterChannelListOverlayMode , channelListSelectDown , channelListSelectUp , channelListPageDown , channelListPageUp ) where import Prelude () import Matterhorn.Prelude import qualified Brick.Widgets.List as L import qualified Data.Vector as Vec import qualified Data.Sequence as Seq import Data.Function ( on ) import qualified Data.Text as T import Lens.Micro.Platform ( to ) import Network.Mattermost.Types import qualified Network.Mattermost.Endpoints as MM import Matterhorn.State.ListOverlay import Matterhorn.State.Channels import Matterhorn.Types enterChannelListOverlayMode :: MH () enterChannelListOverlayMode = do myTId <- use csCurrentTeamId myChannels <- use (csChannels.to (filteredChannelIds (const True))) enterListOverlayMode (csTeam(myTId).tsChannelListOverlay) ChannelListOverlay AllChannels enterHandler (fetchResults myTId myChannels) enterHandler :: Channel -> MH Bool enterHandler chan = do joinChannel (getId chan) return True fetchResults :: TeamId -> [ChannelId] -- ^ The channels to exclude from the results -> ChannelSearchScope -- ^ The scope to search -> Session -- ^ The connection session -> Text -- ^ The search string -> IO (Vec.Vector Channel) fetchResults myTId exclude AllChannels session searchString = do resultChans <- case T.null searchString of True -> MM.mmGetPublicChannels myTId (Just 0) (Just 200) session False -> MM.mmSearchChannels myTId searchString session let filteredChans = Seq.filter (\ c -> not (channelId c `elem` exclude)) resultChans sortedChans = Vec.fromList $ toList $ Seq.sortBy (compare `on` channelDisplayName) filteredChans return sortedChans -- | Move the selection up in the channel list overlay by one channel. channelListSelectUp :: MH () channelListSelectUp = channelListMove L.listMoveUp -- | Move the selection down in the channel list overlay by one channel. channelListSelectDown :: MH () channelListSelectDown = channelListMove L.listMoveDown -- | Move the selection up in the channel list overlay by a page of channels -- (channelListPageSize). channelListPageUp :: MH () channelListPageUp = channelListMove (L.listMoveBy (-1 * channelListPageSize)) -- | Move the selection down in the channel list overlay by a page of channels -- (channelListPageSize). channelListPageDown :: MH () channelListPageDown = channelListMove (L.listMoveBy channelListPageSize) -- | Transform the channel list results in some way, e.g. by moving the -- cursor, and then check to see whether the modification warrants a -- prefetch of more search results. channelListMove :: (L.List Name Channel -> L.List Name Channel) -> MH () channelListMove = listOverlayMove (csCurrentTeam.tsChannelListOverlay) -- | The number of channels in a "page" for cursor movement purposes. channelListPageSize :: Int channelListPageSize = 10
matterhorn-chat/matterhorn
src/Matterhorn/State/ChannelListOverlay.hs
bsd-3-clause
3,109
0
16
653
611
332
279
54
2
----------------------------------------------------------------------------- -- | -- Module : Distribution.Server.Util.ServeTarball -- Copyright : (c) 2008 David Himmelstrup -- (c) 2009 Antoine Latter -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- ----------------------------------------------------------------------------- module Distribution.Server.Util.ServeTarball ( serveTarball , serveTarEntry , constructTarIndexFromFile , constructTarIndex ) where import Happstack.Server.Types import Happstack.Server.Monads import Happstack.Server.Routing (method) import Happstack.Server.Response import Distribution.Server.Framework.HappstackUtils (mime, remainingPath) import Distribution.Server.Framework.CacheControl import Distribution.Server.Pages.Template (hackagePage) import Distribution.Server.Framework.ResponseContentTypes as Resource import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar import qualified Data.TarIndex as TarIndex import Data.TarIndex (TarIndex) import qualified Text.XHtml.Strict as XHtml import Text.XHtml.Strict ((<<), (!)) import qualified Data.ByteString.Lazy as BS import System.FilePath import Control.Monad.Trans (MonadIO, liftIO) import Control.Monad (msum, mzero, MonadPlus(..)) import System.IO -- | Serve the contents of a tar file -- file. TODO: This is not a sustainable implementation, -- but it gives us something to test with. serveTarball :: (MonadIO m, MonadPlus m) => String -- description for directory listings -> [FilePath] -- dir index file names (e.g. ["index.html"]) -> FilePath -- root dir in tar to serve -> FilePath -- the tarball -> TarIndex -- index for tarball -> [CacheControl] -> ETag -- the etag -> ServerPartT m Response serveTarball descr indices tarRoot tarball tarIndex cacheCtls etag = do rq <- askRq action GET $ remainingPath $ \paths -> do -- first we come up with the set of paths in the tarball that -- would match our request let validPaths :: [FilePath] validPaths = (joinPath $ tarRoot:paths) : [joinPath $ tarRoot:paths ++ [index] | index <- indices] msum $ concat [ serveFiles validPaths , serveDirs (rqUri rq) validPaths ] where serveFiles paths = flip map paths $ \path -> case TarIndex.lookup tarIndex path of Just (TarIndex.TarFileEntry off) -> do cacheControl cacheCtls etag tfe <- liftIO $ serveTarEntry tarball off path ok (toResponse tfe) _ -> mzero action act m = method act >> m serveDirs fullPath paths = flip map paths $ \path -> case TarIndex.lookup tarIndex path of Just (TarIndex.TarDir fs) | not (hasTrailingPathSeparator fullPath) -> seeOther (addTrailingPathSeparator fullPath) (toResponse ()) | otherwise -> do cacheControl cacheCtls etag ok $ toResponse $ Resource.XHtml $ renderDirIndex descr path fs _ -> mzero renderDirIndex :: String -> FilePath -> [(FilePath, TarIndex.TarIndexEntry)] -> XHtml.Html renderDirIndex descr topdir topentries = hackagePage title [ XHtml.h2 << title , XHtml.h3 << addTrailingPathSeparator topdir , renderForest "" topentries] where title = "Directory listing for " ++ descr renderForest _ [] = XHtml.noHtml renderForest dir ts = XHtml.ulist ! [ XHtml.theclass "directory-list" ] << map (uncurry (renderTree dir)) ts renderTree dir entryname (TarIndex.TarFileEntry _) = XHtml.li << XHtml.anchor ! [XHtml.href (dir </> entryname)] << entryname renderTree dir entryname (TarIndex.TarDir entries) = XHtml.li << [ XHtml.anchor ! [XHtml.href (dir </> entryname)] << addTrailingPathSeparator entryname , renderForest (dir </> entryname) entries ] serveTarEntry :: FilePath -> Int -> FilePath -> IO Response serveTarEntry tarfile off fname = do htar <- openFile tarfile ReadMode hSeek htar AbsoluteSeek (fromIntegral (off * 512)) header <- BS.hGet htar 512 case Tar.read header of (Tar.Next Tar.Entry{Tar.entryContent = Tar.NormalFile _ size} _) -> do body <- BS.hGet htar (fromIntegral size) let mimeType = mime fname response = ((setHeader "Content-Length" (show size)) . (setHeader "Content-Type" mimeType)) $ resultBS 200 body return response _ -> fail "oh noes!!" constructTarIndexFromFile :: FilePath -> IO TarIndex constructTarIndexFromFile file = do tar <- BS.readFile file case constructTarIndex tar of Left err -> fail err Right tarIndex -> return tarIndex -- | Forcing the Either will force the tar index constructTarIndex :: BS.ByteString -> Either String TarIndex constructTarIndex = either (\e -> Left ("bad tar file: " ++ show e)) Right . TarIndex.construct . Tar.read
snoyberg/hackage-server
Distribution/Server/Util/ServeTarball.hs
bsd-3-clause
5,422
0
21
1,512
1,288
682
606
104
3
{-# OPTIONS_HADDOCK hide #-} module Database.Edis.Helper where import Data.ByteString (ByteString) import Data.Maybe (fromJust) import Data.Proxy (Proxy) import Data.Serialize (Serialize, encode, decode) import Database.Redis as Redis hiding (decode) import GHC.TypeLits -------------------------------------------------------------------------------- -- Helper functions -------------------------------------------------------------------------------- encodeKey :: KnownSymbol s => Proxy s -> ByteString encodeKey = encode . symbolVal decodeAsAnything :: (Serialize x) => Either Reply ByteString -> Redis (Either Reply x) decodeAsAnything (Left replyErr) = return $ Left replyErr decodeAsAnything (Right str) = case decode str of Left decodeErr -> return $ Left (Error $ encode decodeErr) Right val -> return $ Right val decodeAsMaybe :: (Serialize x) => Either Reply (Maybe ByteString) -> Redis (Either Reply (Maybe x)) decodeAsMaybe (Left replyErr) = return $ Left replyErr decodeAsMaybe (Right Nothing) = return $ Right Nothing decodeAsMaybe (Right (Just str)) = case decode str of Left decodeErr -> return $ Left (Error $ encode decodeErr) Right val -> return $ Right (Just val) decodeBPOP :: Serialize x => Either Reply (Maybe (ByteString, ByteString)) -> Redis (Either Reply (Maybe (ByteString, x))) decodeBPOP (Left replyError) = return $ Left replyError decodeBPOP (Right Nothing) = return $ Right Nothing decodeBPOP (Right (Just (key, raw))) = case decode raw of Left decodeError -> return $ Left (Error $ encode decodeError) Right value -> return $ Right (Just (key, value)) decodeAsList :: (Serialize x) => Either Reply [ByteString] -> Redis (Either Reply [x]) decodeAsList (Left replyErr) = return $ Left replyErr decodeAsList (Right strs) = case mapM decode strs of Left decodeErr -> return $ Left (Error $ encode decodeErr) Right vals -> return $ Right vals decodeAsListWithScores :: (Serialize x) => Either Reply [(ByteString, Double)] -> Redis (Either Reply [(x, Double)]) decodeAsListWithScores (Left replyErr) = return $ Left replyErr decodeAsListWithScores (Right pairs) = let (strs, scores) = unzip pairs in case mapM decode strs of Left decodeErr -> return $ Left (Error $ encode decodeErr) Right vals -> return $ Right (zip vals scores) fromRight :: Either a b -> b fromRight (Left _) = error "Left val" fromRight (Right e) = e fromMaybeResult :: Either Reply (Maybe x) -> x fromMaybeResult = fromJust . fromRight
banacorn/tredis
src/Database/Edis/Helper.hs
mit
2,605
0
14
519
936
470
466
43
2
{- - Qoropa -- Love Your Mail! - Copyright © 2010 Ali Polatel - - This file is part of the Qoropa mail reader. Qoropa is free software; - you can redistribute it and/or modify it under the terms of the GNU General - Public License version 2, as published by the Free Software Foundation. - - Qoropa 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 - - Author: Ali Polatel <[email protected]> -} module Qoropa ( qoropa ) where import Qoropa.Config (QoropaConfig) import Qoropa.UI (start, mainLoop) qoropa :: QoropaConfig -> IO () qoropa cfg = do ui <- start cfg mainLoop ui -- vim: set ft=haskell et ts=4 sts=4 sw=4 fdm=marker :
beni55/qoropa
src/Qoropa.hs
gpl-2.0
1,036
0
8
207
72
39
33
8
1
{-# LANGUAGE CPP, RankNTypes #-} {- | Module :./CMDL/InfoCommands.hs Description : CMDL interface commands Copyright : uni-bremen and DFKI License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable CMDL.InfoCommands contains all commands that provides information about the state of the development graph and selected theories -} module CMDL.InfoCommands ( cNodes , cShowDgGoals , cShowNodeProvenGoals , cShowNodeUnprovenGoals , cRedoHistory , cCurrentComorphism , cShowTaxonomy , cShowTheory , cShowTheoryGoals , cUndoHistory , cEdges , cShowNodeAxioms , cInfo , cComorphismsTo , cInfoCurrent , cShowConcept , cNodeNumber , cHelp ) where #ifdef UNI_PACKAGE import GUI.Taxonomy #endif import CMDL.DataTypesUtils import CMDL.DataTypes import CMDL.Shell (nodeNames) import CMDL.Utils import Static.GTheory import Static.DevGraph import Static.PrintDevGraph (showLEdge) import Common.AS_Annotation (SenAttr (isAxiom)) import Common.DocUtils (showDoc) import Common.Taxonomy (TaxoGraphKind (..)) import Common.Utils (trim) import qualified Common.OrderedMap as OMap import Common.GraphAlgo (yen) import Proofs.AbstractState (isSubElemG, pathToComorphism) import Data.Graph.Inductive.Graph (LNode, LEdge, Node) import Data.List import Logic.Prover (SenStatus) import Logic.Comorphism (AnyComorphism) import Logic.Grothendieck (logicGraph2Graph) import Comorphisms.LogicGraph (logicGraph) import Interfaces.Command (cmdNameStr, describeCmd, showCmd) import Interfaces.DataTypes import Interfaces.Utils -- show list of all goals(i.e. prints their name) cShowDgGoals :: CmdlState -> IO CmdlState cShowDgGoals state = case i_state $ intState state of -- nothing to print Nothing -> return state Just dgState -> let -- list of all nodes ls = getAllNodes dgState -- compute list of node goals nodeGoals = nodeNames $ filter (hasOpenGoals . snd) ls -- list of all goal edge names edgeGoals = map fst $ filter (edgeContainsGoals . snd) $ createEdgeNames ls $ getAllEdges dgState -- print sorted version of the list in return $ genMessage [] (unlines $ sort (nodeGoals ++ edgeGoals)) state {- local function that computes the theory of a node but it keeps only the goal theory -} getGoalThS :: CmdlUseTranslation -> Int -> CmdlState -> [String] getGoalThS useTrans x state = case getTh useTrans x state of Nothing -> [] Just th -> let nwth = case th of G_theory x1 syn x2 x3 thSens x4 -> G_theory x1 syn x2 x3 (OMap.filter (\ s -> not (isAxiom s) && not (isProvenSenStatus s)) thSens) x4 in [showDoc nwth "\n"] {- local function that computes the theory of a node that takes into consideration translated theories in the selection too and returns the theory as a string -} getThS :: CmdlUseTranslation -> Int -> CmdlState -> [String] getThS useTrans x state = case getTh useTrans x state of Nothing -> ["Could not find a theory"] Just th -> [showDoc th "\n"] getInfoFromNodes :: String -> ([Node] -> [String]) -> CmdlState -> IO CmdlState getInfoFromNodes input f state = case i_state $ intState state of Nothing -> return state Just dgState -> let (errors, nodes) = getInputNodes input dgState in return (if null nodes then genMsgAndCode errors 1 state else genMessage errors (intercalate "\n" $ f nodes) state) cShowFromNode :: (forall a . SenStatus a (AnyComorphism, BasicProof) -> Bool) -- ^ what sentences to show -> String -- input string containing node-names -> CmdlState -- the state -> IO CmdlState cShowFromNode f input state = getInfoFromNodes input (concatMap (\ n -> case getTh Dont_translate n state of Nothing -> [] Just th -> case th of G_theory _ _ _ _ sens _ -> OMap.keys $ OMap.filter f sens)) state cShowNodeProvenGoals :: String -> CmdlState -> IO CmdlState cShowNodeProvenGoals = cShowFromNode (\ s -> not (isAxiom s) && isProvenSenStatus s) cShowNodeUnprovenGoals :: String -> CmdlState -> IO CmdlState cShowNodeUnprovenGoals = cShowFromNode (\ s -> not (isAxiom s) && not (isProvenSenStatus s)) cShowNodeAxioms :: String -> CmdlState -> IO CmdlState cShowNodeAxioms = cShowFromNode isAxiom -- show theory of input nodes cShowTheory :: CmdlUseTranslation -> String -> CmdlState -> IO CmdlState cShowTheory useTrans input state = getInfoFromNodes input (concatMap (\ n -> getThS useTrans n state)) state -- show theory of all goals cShowTheoryGoals :: String -> CmdlState -> IO CmdlState cShowTheoryGoals input st = getInfoFromNodes input (concatMap (\ n -> getGoalThS Do_translate n st)) st showNodeInfo :: LNode DGNodeLab -> String showNodeInfo (i, l) = (if isDGRef l then ("reference " ++) else if isInternalNode l then ("internal " ++) else id) "node " ++ getDGNodeName l ++ " " ++ show i ++ "\n" ++ showDoc l "" showEdgeInfo :: LEdge DGLinkLab -> String showEdgeInfo e@(_, _, l) = showLEdge e ++ "\n" ++ showDoc l "" -- show all information of selection cInfoCurrent :: CmdlState -> IO CmdlState cInfoCurrent state = case i_state $ intState state of -- nothing selected Nothing -> return state Just ps -> let (errors, nodes) = getSelectedDGNodes ps in if null nodes then return $ genMsgAndCode errors 1 state else cInfo (unwords $ nodeNames nodes) state cComorphismsTo :: String -> CmdlState -> IO CmdlState cComorphismsTo input state = case i_state $ intState state of -- nothing selected Nothing -> return state Just ps -> case getCurrentSublogic ps of Just start -> case parseSublogics input of Just end -> let cmors = yen 10 (start, Nothing) (\ (l, _) -> isSubElemG l end) (logicGraph2Graph logicGraph) cmor = map (show . pathToComorphism) cmors in return $ genMessage "" (unlines cmor) state Nothing -> return $ genMsgAndCode ("Invalid logic " ++ input) 1 state Nothing -> return $ genMsgAndCode "No node(s) selected!" 1 state -- show all information of input cInfo :: String -> CmdlState -> IO CmdlState cInfo input state = case i_state $ intState state of -- error message Nothing -> return $ genMsgAndCode "No library loaded" 1 state Just dgS -> let (nds, edg, nbEdg, errs) = decomposeIntoGoals input tmpErrs = prettyPrintErrList errs in case (nds, edg, nbEdg) of ([], [], []) -> return $ genMsgAndCode ("Nothing from the input " ++ "could be processed") 1 state (_, _, _) -> let lsNodes = getAllNodes dgS lsEdges = getAllEdges dgS (errs'', listEdges) = obtainEdgeList edg nbEdg lsNodes lsEdges (errs', listNodes) = obtainNodeList nds lsNodes strsNode = map showNodeInfo listNodes strsEdge = map showEdgeInfo listEdges tmpErrs' = tmpErrs ++ prettyPrintErrList errs' tmpErrs'' = tmpErrs' ++ prettyPrintErrList errs'' in return $ genMessage tmpErrs'' (intercalate "\n\n" (strsNode ++ strsEdge)) state taxoShowGeneric :: TaxoGraphKind -> CmdlState -> [LNode DGNodeLab] -> IO () #ifdef UNI_PACKAGE taxoShowGeneric kind state ls = case ls of (nb, nlab) : ll -> case i_state $ intState state of Nothing -> return () Just _ -> case getTh Do_translate nb state of -- the theory was computed Just th -> do -- display graph displayGraph kind (getDGNodeName nlab) th taxoShowGeneric kind state ll -- theory couldn't be computed so just go next _ -> taxoShowGeneric kind state ll _ -> return () #else taxoShowGeneric _ _ _ = return () #endif cShowTaxoGraph :: TaxoGraphKind -> String -> CmdlState -> IO CmdlState cShowTaxoGraph kind input state = case i_state $ intState state of Nothing -> return state Just dgState -> do let (errors, nodes) = getInputDGNodes input dgState taxoShowGeneric kind state nodes return $ genMessage errors [] state cShowTaxonomy :: String -> CmdlState -> IO CmdlState cShowTaxonomy = cShowTaxoGraph KSubsort cShowConcept :: String -> CmdlState -> IO CmdlState cShowConcept = cShowTaxoGraph KConcept -- show node number of input cNodeNumber :: String -> CmdlState -> IO CmdlState cNodeNumber input state = case i_state $ intState state of Nothing -> return state Just dgState -> let (errors, nodes) = getInputDGNodes input dgState ls = map (\ (i, n) -> getDGNodeName n ++ " is node number " ++ show i) nodes in return $ genMessage errors (intercalate "\n" ls) state -- print the name of all edges cEdges :: CmdlState -> IO CmdlState cEdges state = case i_state $ intState state of Nothing -> return state Just dgState -> do -- list of all nodes let lsNodes = getAllNodes dgState -- compute all edges names lsEdg = getAllEdges dgState lsEdges = map fst $ createEdgeNames lsNodes lsEdg -- print edge list in a sorted fashion return $ genMessage [] (intercalate "\n" $ sort lsEdges) state cUndoHistory :: CmdlState -> IO CmdlState cUndoHistory = return . cHistory True cRedoHistory :: CmdlState -> IO CmdlState cRedoHistory = return . cHistory False cCurrentComorphism :: CmdlState -> IO CmdlState cCurrentComorphism st = case i_state $ intState st of Nothing -> return $ genMessage "" "No comorphism!" st Just ist -> case cComorphism ist of Just cmor -> return $ genMessage "" (show cmor) st Nothing -> return $ genMessage "" "No comorphism!" st cHistory :: Bool -> CmdlState -> CmdlState cHistory isUndo state = genMessage [] (unlines $ ((if isUndo then "Un" else "Re") ++ "do history :") : map (showCmd . command) ((if isUndo then undoList else redoList) $ i_hist $ intState state) ) state -- print the name of all nodes cNodes :: CmdlState -> IO CmdlState cNodes state = case i_state $ intState state of -- no library loaded, so nothing to print Nothing -> return state Just dgState -> do -- compute the list of node names let ls = nodeNames $ getAllNodes dgState -- print a sorted version of it return $ genMessage [] (intercalate "\n" $ sort ls) state cHelp :: [CmdlCmdDescription] -> CmdlState -> IO CmdlState cHelp allcmds state = do putStrLn $ formatLine ("Command", "Parameter", "Description") putStrLn $ replicate maxLineWidth '-' mapM_ (\ cm -> do let cmd = cmdDescription cm name = cmdNameStr cmd req = formatRequirement $ cmdReq cm descL = formatDesc $ describeCmd cmd desc = head descL ++ concatMap (('\n' : replicate descStart ' ') ++) (tail descL) putStrLn $ formatLine (name, req, desc)) allcmds return state where maxLineWidth = 80 maxNameLen = maximum $ map (length . cmdNameStr . cmdDescription) allcmds maxParamLen = maximum $ map (length . formatRequirement . cmdReq ) allcmds descStart = maxNameLen + 1 + maxParamLen + 1 descWidth = maxLineWidth - descStart formatDesc :: String -> [String] formatDesc = reverse . filter (not . null) . map trim . foldl (\ l w -> if length (head l) + length w > descWidth then (w ++ " ") : l else (head l ++ w ++ " ") : tail l) [""] . words formatLine :: (String, String, String) -> String formatLine (c1, c2, c3) = c1 ++ replicate (maxNameLen - length c1 + 1) ' ' ++ c2 ++ replicate (maxParamLen - length c2 + 1) ' ' ++ c3
spechub/Hets
CMDL/InfoCommands.hs
gpl-2.0
12,900
0
23
4,005
3,362
1,720
1,642
246
4
{- | Module : ./CspCASLProver.hs Description : Interface to the CspCASLProver (Isabelle based) theorem prover Copyright : (c) Liam O'Reilly and Markus Roggenbach, Swansea University 2009 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable CspCASLProver allows interactive theorem proving on CspCASL specifications. See CspCASL.hs for details on the specification language CspCASL. "CspCASLProver.Consts" conatins constants and related fucntions for CspCASLProver. "CspCASLProver.CspCASLProver" is an interactive interface to the Isabelle prover (instanisated with CspProver). The encoding of CspCASL into IsabelleHOL requires the generation of several Isabelle theories where only the final theory requires user interaction. "CspCASLProver.CspProverConsts" contains Isabelle abstract syntax constants for CSP-Prover operations "CspCASLProver.IsabelleUtils" contains utilities for CspCASLProver related to Isabelle. The functions here typically manipulate Isabelle signatures. "CspCASLProver.TransProcesses" contains functions that implement CspCASLProver's translation of processes from CspCASL to CspProver. "CspCASLProver.Utils" contains utilities for CspCASLProver related to the actual construction of Isabelle theories. -} module CspCASLProver where
spechub/Hets
CspCASLProver.hs
gpl-2.0
1,356
0
2
183
5
4
1
1
0
#!/usr/bin/env stack {- stack runghc --verbosity info --package pandoc-types -} import Text.Pandoc.JSON main :: IO () main = toJSONFilter dropHtmlInlines dropHtmlInlines :: Inline -> Inline dropHtmlInlines (RawInline (Format "html") _) = Str "" dropHtmlInlines x = x
ony/hledger
tools/pandoc-drop-html-inlines.hs
gpl-3.0
271
0
9
41
69
36
33
6
1
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-} module Types where import Prelude hiding (FilePath, putStrLn) import Control.Lens import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State import Control.Monad.Trans.Resource import Data.Text (Text(), pack) import Data.Text.IO (putStrLn) import System.Directory import System.IO (hFlush, stdout) import System.FilePath import System.Process import Util data St = St { _stLessProcess :: Maybe ProcessHandle } makeLenses ''St emptySt :: St emptySt = St Nothing data Env = Env { _envRepoRoot :: FilePath , _envRobinRoot :: FilePath , _envStatusFile :: FilePath , _envOutputFile :: FilePath , _envLessFile :: FilePath , _envPidFile :: FilePath , _envLogFile :: FilePath } deriving (Show) makeLenses ''Env emptyEnv :: String -> Env emptyEnv rr = Env { _envRepoRoot = rr , _envRobinRoot = robinRoot , _envStatusFile = specialFile "status" , _envOutputFile = specialFile "output" , _envLessFile = specialFile "less" , _envPidFile = specialFile "pid" , _envLogFile = specialFile "log" } where robinRoot = rr </> ".robin" specialFile n = robinRoot </> n data Err = Err deriving (Show) type I = ReaderT Env (ExceptT Err (ResourceT IO)) type M = StateT St I runI :: I a -> IO (Either Err a) runI m = getRepoRoot >>= runResourceT . runExceptT . runReaderT m' . emptyEnv where m' = view envRobinRoot >>= ensureDir >> m ensureDir :: (MonadIO m) => FilePath -> m () ensureDir = liftIO . createDirectoryIfMissing False runM :: M a -> IO (Either Err a) runM = runI . flip evalStateT emptySt debug :: (MonadIO m) => Text -> m () debug text = liftIO $ putStrLn text >> hFlush stdout debugs :: (MonadIO m) => [Char] -> m () debugs = debug . pack
ktvoelker/HsTools
src/Types.hs
gpl-3.0
1,807
0
9
372
579
320
259
59
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.ElastiCache.Waiters -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.AWS.ElastiCache.Waiters where import Network.AWS.ElastiCache.DescribeCacheClusters import Network.AWS.ElastiCache.DescribeCacheClusters import Network.AWS.ElastiCache.DescribeReplicationGroups import Network.AWS.ElastiCache.DescribeReplicationGroups import Network.AWS.ElastiCache.Types import Network.AWS.Prelude import Network.AWS.Waiter -- | Polls 'Network.AWS.ElastiCache.DescribeCacheClusters' every 30 seconds until a -- successful state is reached. An error is returned after 60 failed checks. cacheClusterAvailable :: Wait DescribeCacheClusters cacheClusterAvailable = Wait { _waitName = "CacheClusterAvailable" , _waitAttempts = 60 , _waitDelay = 30 , _waitAcceptors = [ matchAll "available" AcceptSuccess (folding (concatOf drsCacheClusters) . ccCacheClusterStatus . _Just . to toTextCI) , matchAny "deleted" AcceptFailure (folding (concatOf drsCacheClusters) . ccCacheClusterStatus . _Just . to toTextCI) , matchAny "deleting" AcceptFailure (folding (concatOf drsCacheClusters) . ccCacheClusterStatus . _Just . to toTextCI) , matchAny "incompatible-network" AcceptFailure (folding (concatOf drsCacheClusters) . ccCacheClusterStatus . _Just . to toTextCI) , matchAny "restore-failed" AcceptFailure (folding (concatOf drsCacheClusters) . ccCacheClusterStatus . _Just . to toTextCI)] } -- | Polls 'Network.AWS.ElastiCache.DescribeCacheClusters' every 30 seconds until a -- successful state is reached. An error is returned after 60 failed checks. cacheClusterDeleted :: Wait DescribeCacheClusters cacheClusterDeleted = Wait { _waitName = "CacheClusterDeleted" , _waitAttempts = 60 , _waitDelay = 30 , _waitAcceptors = [ matchError "CacheClusterNotFound" AcceptSuccess , matchAny "creating" AcceptFailure (folding (concatOf drsCacheClusters) . ccCacheClusterStatus . _Just . to toTextCI) , matchAny "modifying" AcceptFailure (folding (concatOf drsCacheClusters) . ccCacheClusterStatus . _Just . to toTextCI) , matchAny "rebooting" AcceptFailure (folding (concatOf drsCacheClusters) . ccCacheClusterStatus . _Just . to toTextCI)] } -- | Polls 'Network.AWS.ElastiCache.DescribeReplicationGroups' every 30 seconds until a -- successful state is reached. An error is returned after 60 failed checks. replicationGroupDeleted :: Wait DescribeReplicationGroups replicationGroupDeleted = Wait { _waitName = "ReplicationGroupDeleted" , _waitAttempts = 60 , _waitDelay = 30 , _waitAcceptors = [ matchError "ReplicationGroupNotFoundFault" AcceptSuccess , matchAny "creating" AcceptFailure (folding (concatOf drgrsReplicationGroups) . rgStatus . _Just . to toTextCI) , matchAny "modifying" AcceptFailure (folding (concatOf drgrsReplicationGroups) . rgStatus . _Just . to toTextCI) , matchAny "rebooting" AcceptFailure (folding (concatOf drgrsReplicationGroups) . rgStatus . _Just . to toTextCI)] } -- | Polls 'Network.AWS.ElastiCache.DescribeReplicationGroups' every 30 seconds until a -- successful state is reached. An error is returned after 60 failed checks. replicationGroupAvailable :: Wait DescribeReplicationGroups replicationGroupAvailable = Wait { _waitName = "ReplicationGroupAvailable" , _waitAttempts = 60 , _waitDelay = 30 , _waitAcceptors = [ matchAll "available" AcceptSuccess (folding (concatOf drgrsReplicationGroups) . rgStatus . _Just . to toTextCI) , matchAny "deleted" AcceptFailure (folding (concatOf drgrsReplicationGroups) . rgStatus . _Just . to toTextCI) , matchAny "deleting" AcceptFailure (folding (concatOf drgrsReplicationGroups) . rgStatus . _Just . to toTextCI) , matchAny "incompatible-network" AcceptFailure (folding (concatOf drgrsReplicationGroups) . rgStatus . _Just . to toTextCI) , matchAny "restore-failed" AcceptFailure (folding (concatOf drgrsReplicationGroups) . rgStatus . _Just . to toTextCI)] }
fmapfmapfmap/amazonka
amazonka-elasticache/gen/Network/AWS/ElastiCache/Waiters.hs
mpl-2.0
6,645
0
15
2,934
839
451
388
119
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} -- run as: ./gen -o favicon.png -w 32 -h 32 import Diagrams.Prelude import Diagrams.Backend.Rasterific.CmdLine main = defaultMain icon icon :: Diagram B icon = lines_ `atop` canvas_ where line_ = rect 14 3 # fc white . lw none dot_ = circle 2 # fc white . lw none line1 = alignL $ hsep 2 [line_, dot_] line2 = alignL $ hsep 2 [dot_, line_] lines_ = centerXY $ vsep 3 [line1, line2, line1] canvas_ = roundedRect 32 32 4 # fc (sRGB24read "7868FF") . lw none
aelve/guide
favicon/gen.hs
bsd-3-clause
548
5
14
130
190
98
92
-1
-1
{-# LANGUAGE TupleSections #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module Stack.Dot (dot ,listDependencies ,DotOpts(..) ,resolveDependencies ,printGraph ,pruneGraph ) where import Control.Applicative import Control.Arrow ((&&&)) import Control.Monad (void) import Control.Monad.Catch (MonadCatch,MonadMask) import Control.Monad.IO.Class import Control.Monad.Logger (MonadLogger) import Control.Monad.Reader (MonadReader) import Control.Monad.Trans.Control (MonadBaseControl) import qualified Data.Foldable as F import qualified Data.HashSet as HashSet import Data.Map (Map) import qualified Data.Map as Map import Data.Monoid ((<>)) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.IO as Text import qualified Data.Traversable as T import Network.HTTP.Client.Conduit (HasHttpManager) import Stack.Build (withLoadPackage) import Stack.Build.Installed (getInstalled, GetInstalledOpts(..)) import Stack.Build.Source import Stack.Constants import Stack.Package import Stack.Types import Stack.Types.Internal (HasLogLevel) -- | Options record for @stack dot@ data DotOpts = DotOpts { dotIncludeExternal :: Bool -- ^ Include external dependencies , dotIncludeBase :: Bool -- ^ Include dependencies on base , dotDependencyDepth :: Maybe Int -- ^ Limit the depth of dependency resolution to (Just n) or continue until fixpoint , dotPrune :: Set String -- ^ Package names to prune from the graph } -- | Visualize the project's dependencies as a graphviz graph dot :: (HasEnvConfig env ,HasHttpManager env ,HasLogLevel env ,MonadBaseControl IO m ,MonadCatch m ,MonadLogger m ,MonadIO m ,MonadMask m ,MonadReader env m ) => DotOpts -> m () dot dotOpts = do (locals,_,_) <- loadLocals defaultBuildOpts Map.empty resultGraph <- createDependencyGraph dotOpts let pkgsToPrune = if dotIncludeBase dotOpts then dotPrune dotOpts else Set.insert "base" (dotPrune dotOpts) localNames = Set.fromList (map (packageName . lpPackageFinal) locals) prunedGraph = pruneGraph localNames pkgsToPrune resultGraph printGraph dotOpts locals prunedGraph -- | Create the dependency graph, the result is a map from a package -- name to a tuple of dependencies and a version if available. This -- function mainly gathers the required arguments for -- @resolveDependencies@. createDependencyGraph :: (HasEnvConfig env ,HasHttpManager env ,HasLogLevel env ,MonadLogger m ,MonadBaseControl IO m ,MonadCatch m ,MonadIO m ,MonadMask m ,MonadReader env m) => DotOpts -> m (Map PackageName (Set PackageName, Maybe Version)) createDependencyGraph dotOpts = do (_,locals,_,sourceMap) <- loadSourceMap defaultBuildOpts let graph = Map.fromList (localDependencies dotOpts locals) menv <- getMinimalEnvOverride installedMap <- fmap thrd . fst <$> getInstalled menv (GetInstalledOpts False False) sourceMap withLoadPackage menv (\loader -> do let depLoader = createDepLoader sourceMap installedMap (fmap3 (packageAllDeps &&& (Just . packageVersion)) loader) liftIO $ resolveDependencies (dotDependencyDepth dotOpts) graph depLoader) where -- fmap a function over the result of a function with 3 arguments fmap3 :: Functor f => (d -> e) -> (a -> b -> c -> f d) -> a -> b -> c -> f e fmap3 f g a b c = f <$> g a b c thrd :: (a,b,c) -> c thrd (_,_,x) = x -- Given an 'Installed' try to get the 'Version' libVersionFromInstalled :: Installed -> Maybe Version libVersionFromInstalled (Library ghcPkgId) = case ghcPkgIdPackageIdentifier ghcPkgId of PackageIdentifier _ v -> Just v libVersionFromInstalled (Executable _) = Nothing listDependencies :: (HasEnvConfig env ,HasHttpManager env ,HasLogLevel env ,MonadBaseControl IO m ,MonadCatch m ,MonadLogger m ,MonadMask m ,MonadIO m ,MonadReader env m ) => Text -> m () listDependencies sep = do let dotOpts = DotOpts True True Nothing Set.empty resultGraph <- createDependencyGraph dotOpts void (Map.traverseWithKey go (snd <$> resultGraph)) where go name v = liftIO (Text.putStrLn $ Text.pack (packageNameString name) <> sep <> maybe "<unknown>" (Text.pack . show) v) -- | @pruneGraph dontPrune toPrune graph@ prunes all packages in -- @graph@ with a name in @toPrune@ and removes resulting orphans -- unless they are in @dontPrune@ pruneGraph :: (F.Foldable f, F.Foldable g, Eq a) => f PackageName -> g String -> Map PackageName (Set PackageName, a) -> Map PackageName (Set PackageName, a) pruneGraph dontPrune names = pruneUnreachable dontPrune . Map.mapMaybeWithKey (\pkg (pkgDeps,x) -> if show pkg `F.elem` names then Nothing else let filtered = Set.filter (\n -> show n `F.notElem` names) pkgDeps in if Set.null filtered && not (Set.null pkgDeps) then Nothing else Just (filtered,x)) -- | Make sure that all unreachable nodes (orphans) are pruned pruneUnreachable :: (Eq a, F.Foldable f) => f PackageName -> Map PackageName (Set PackageName, a) -> Map PackageName (Set PackageName, a) pruneUnreachable dontPrune = fixpoint prune where fixpoint :: Eq a => (a -> a) -> a -> a fixpoint f v = if f v == v then v else fixpoint f (f v) prune graph' = Map.filterWithKey (\k _ -> reachable k) graph' where reachable k = k `F.elem` dontPrune || k `Set.member` reachables reachables = F.fold (fst <$> graph') -- | Resolve the dependency graph up to (Just depth) or until fixpoint is reached resolveDependencies :: (Applicative m, Monad m) => Maybe Int -> Map PackageName (Set PackageName,Maybe Version) -> (PackageName -> m (Set PackageName, Maybe Version)) -> m (Map PackageName (Set PackageName,Maybe Version)) resolveDependencies (Just 0) graph _ = return graph resolveDependencies limit graph loadPackageDeps = do let values = Set.unions (fst <$> Map.elems graph) keys = Map.keysSet graph next = Set.difference values keys if Set.null next then return graph else do x <- T.traverse (\name -> (name,) <$> loadPackageDeps name) (F.toList next) resolveDependencies (subtract 1 <$> limit) (Map.unionWith unifier graph (Map.fromList x)) loadPackageDeps where unifier (pkgs1,v1) (pkgs2,_) = (Set.union pkgs1 pkgs2, v1) -- | Given a SourceMap and a dependency loader, load the set of dependencies for a package createDepLoader :: Applicative m => Map PackageName PackageSource -> Map PackageName Installed -> (PackageName -> Version -> Map FlagName Bool -> m (Set PackageName,Maybe Version)) -> PackageName -> m (Set PackageName, Maybe Version) createDepLoader sourceMap installed loadPackageDeps pkgName = case Map.lookup pkgName sourceMap of Just (PSLocal lp) -> pure ((packageAllDeps &&& (Just . packageVersion)) (lpPackageFinal lp)) Just (PSUpstream version _ flags) -> loadPackageDeps pkgName version flags Nothing -> pure (Set.empty, do m' <- T.traverse libVersionFromInstalled installed Map.lookup pkgName m') -- | Resolve the direct (depth 0) external dependencies of the given local packages localDependencies :: DotOpts -> [LocalPackage] -> [(PackageName,(Set PackageName,Maybe Version))] localDependencies dotOpts locals = map (\lp -> (packageName (lpPackageFinal lp), (deps lp,Just (lpVersion lp)))) locals where deps lp = if dotIncludeExternal dotOpts then Set.delete (lpName lp) (packageAllDeps (lpPackageFinal lp)) else Set.intersection localNames (packageAllDeps (lpPackageFinal lp)) lpName lp = packageName (lpPackageFinal lp) localNames = Set.fromList $ map (packageName . lpPackageFinal) locals lpVersion lp = packageVersion (lpPackageFinal lp) -- | Print a graphviz graph of the edges in the Map and highlight the given local packages printGraph :: (Applicative m, MonadIO m) => DotOpts -> [LocalPackage] -> Map PackageName (Set PackageName, Maybe Version) -> m () printGraph dotOpts locals graph = do liftIO $ Text.putStrLn "strict digraph deps {" printLocalNodes dotOpts filteredLocals printLeaves graph void (Map.traverseWithKey printEdges (fst <$> graph)) liftIO $ Text.putStrLn "}" where filteredLocals = filter (\local -> show (packageName (lpPackageFinal local)) `Set.notMember` dotPrune dotOpts) locals -- | Print the local nodes with a different style depending on options printLocalNodes :: (F.Foldable t, MonadIO m) => DotOpts -> t LocalPackage -> m () printLocalNodes dotOpts locals = liftIO $ Text.putStrLn (Text.intercalate "\n" lpNodes) where applyStyle :: Text -> Text applyStyle n = if dotIncludeExternal dotOpts then n <> " [style=dashed];" else n <> " [style=solid];" lpNodes :: [Text] lpNodes = map (applyStyle . nodeName . packageName . lpPackageFinal) (F.toList locals) -- | Print nodes without dependencies printLeaves :: (Applicative m, MonadIO m) => Map PackageName (Set PackageName,Maybe Version) -> m () printLeaves = F.traverse_ printLeaf . Map.keysSet . Map.filter Set.null . fmap fst -- | @printDedges p ps@ prints an edge from p to every ps printEdges :: (Applicative m, MonadIO m) => PackageName -> Set PackageName -> m () printEdges package deps = F.for_ deps (printEdge package) -- | Print an edge between the two package names printEdge :: MonadIO m => PackageName -> PackageName -> m () printEdge from to = liftIO $ Text.putStrLn (Text.concat [ nodeName from, " -> ", nodeName to, ";"]) -- | Convert a package name to a graph node name. nodeName :: PackageName -> Text nodeName name = "\"" <> Text.pack (packageNameString name) <> "\"" -- | Print a node with no dependencies printLeaf :: MonadIO m => PackageName -> m () printLeaf package = liftIO . Text.putStrLn . Text.concat $ if isWiredIn package then ["{rank=max; ", nodeName package, " [shape=box]; };"] else ["{rank=max; ", nodeName package, "; };"] -- | Check if the package is wired in (shipped with) ghc isWiredIn :: PackageName -> Bool isWiredIn = (`HashSet.member` wiredInPackages)
duplode/stack
src/Stack/Dot.hs
bsd-3-clause
11,701
0
21
3,470
3,032
1,582
1,450
216
3
{-# LANGUAGE MultiParamTypeClasses #-} -- Test #3265 module T3265 where data a :+: b = Left a | Right b class a :*: b where {}
sdiehl/ghc
testsuite/tests/rename/should_fail/T3265.hs
bsd-3-clause
131
0
6
30
36
22
14
-1
-1
module Graphics.Blank.Events ( -- * Events Event(..) , NamedEvent(..) , EventName(..) -- * Event Queue , EventQueue -- not abstract , writeEventQueue , readEventQueue , tryReadEventQueue , newEventQueue ) where import Data.Aeson (FromJSON(..)) import qualified Data.Map as Map import Data.Map (Map) import Data.Char import Control.Monad import Control.Concurrent.STM -- | Basic Event from Browser, the code is event-type specific. data Event = Event { jsCode :: Int , jsMouse :: Maybe (Int,Int) } deriving (Show) -- | When an event is sent to the application, it always has a name. data NamedEvent = NamedEvent EventName Event deriving (Show) instance FromJSON NamedEvent where parseJSON o = do (str,code,x,y) <- parseJSON o case Map.lookup str namedEventDB of Just n -> return $ NamedEvent n (Event code (Just (x,y))) Nothing -> do (str',code',(),()) <- parseJSON o case Map.lookup str' namedEventDB of Just n -> return $ NamedEvent n (Event code' Nothing) Nothing -> fail "bad parse" namedEventDB :: Map String EventName namedEventDB = Map.fromList [ (map toLower (show n),n) | n <- [minBound..maxBound] ] -- | 'EventName' mirrors event names from jquery, where 'map toLower (show name)' gives -- the jquery event name. data EventName -- Keys = KeyPress | KeyDown | KeyUp -- Mouse | MouseDown | MouseEnter | MouseMove | MouseOut | MouseOver | MouseUp deriving (Eq, Ord, Show, Enum, Bounded) -- | EventQueue is a STM channel ('TChan') of 'Event's. -- Intentionally, 'EventQueue' is not abstract. type EventQueue = TChan Event writeEventQueue :: EventQueue -> Event -> IO () writeEventQueue q e = atomically $ writeTChan q e readEventQueue :: EventQueue -> IO Event readEventQueue q = atomically $ readTChan q tryReadEventQueue :: EventQueue -> IO (Maybe Event) tryReadEventQueue q = atomically $ do b <- isEmptyTChan q if b then return Nothing else liftM Just (readTChan q) newEventQueue :: IO EventQueue newEventQueue = atomically newTChan
sordina/blank-canvas
Graphics/Blank/Events.hs
bsd-3-clause
2,406
0
19
769
591
324
267
58
2
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, TypeFamilies #-} module PushedInAsGivens where type family F a bar y = let foo :: (F Int ~ [a]) => a -> Int foo x = length [x,y] in (y,foo y) -- This example demonstrates why we need to push in -- an unsolved wanted as a given and not a given/solved. -- [Wanted] F Int ~ [beta] --- forall a. F Int ~ [a] => a ~ beta -- We push in the [Wanted] as given, it will interact and solve the implication -- constraint, and finally we quantify over F Int ~ [beta]. If we push it in as -- Given/Solved, it will be discarded when we meet the given (F Int ~ [a]) and -- we will not be able to solve the implication constraint. -- Oct 14: actually this example is _really_ strange, and doesn't illustrate -- the real issue in #4935, for which there is a separate test -- -- The example here requires us to infer a type -- bar :: F Int ~ [a] => ... -- which is a strange type to quantify over; better to complain about -- having no instance for F Int.
sdiehl/ghc
testsuite/tests/indexed-types/should_compile/PushedInAsGivens.hs
bsd-3-clause
1,043
0
12
230
92
57
35
6
1
module Main where import Digraph main = mapM_ print [ test001 , test002 , test003 , test004 ] -- These check that the result of SCCs doesn't depend on the order of the key -- type (Int here). test001 = testSCC [("a", 1, []), ("b", 2, []), ("c", 3, [])] test002 = testSCC [("a", 2, []), ("b", 3, []), ("c", 1, [])] test003 = testSCC [("b", 1, []), ("c", 2, []), ("a", 3, [])] test004 = testSCC [("b", 2, []), ("c", 3, []), ("a", 1, [])] testSCC = flattenSCCs . stronglyConnCompFromEdgedVerticesOrd . map toNode where toNode (a, b, c) = DigraphNode a b c
ezyang/ghc
testsuite/tests/determinism/determ001/determinism001.hs
bsd-3-clause
577
0
8
128
273
166
107
13
1
{-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ViewPatterns #-} module T13098 where import Language.Haskell.TH $( sequence [ dataD (cxt []) (mkName "T") [PlainTV (mkName "a")] Nothing [normalC (mkName "T") []] [] , pragCompleteD [mkName "T"] Nothing ] ) $([d| class LL f where go :: f a -> () instance LL [] where go _ = () pattern T2 :: LL f => f a pattern T2 <- (go -> ()) {-# COMPLETE T2 :: [] #-} -- No warning foo :: [a] -> Int foo T2 = 5 |])
shlevy/ghc
testsuite/tests/th/T13098.hs
bsd-3-clause
581
0
13
194
108
58
50
17
0
module Completesig03A where data A = A | B {-# COMPLETE A #-}
shlevy/ghc
testsuite/tests/pmcheck/complete_sigs/Completesig03A.hs
bsd-3-clause
65
0
5
15
15
10
5
3
0
import Text.Printf main = do line <- getLine let f = read line :: Double putStrLn . printf "%.3f" $ 5*(f-32)/9
Voleking/ICPC
references/aoapc-book/BeginningAlgorithmContests/haskell/ch1/ex1-2.hs
mit
118
0
11
28
62
30
32
5
1
module Filter.Posterise where import Codec.Picture simplePosterise :: Int -> Image Pixel8 -> Image Pixel8 simplePosterise n = pixelMap f where width = 255 `div` fromIntegral n f gray = width * (gray `div` width)
lesguillemets/haskell-image-filters
Filter/Posterise.hs
mit
233
0
9
55
78
42
36
6
1
{-# LANGUAGE DataKinds #-} module App where import Network.Wai import Network.Wai.Handler.Warp import Servant import System.IO import Api.Main import qualified Database.PostgreSQL.Simple as PGS -- * run app run :: IO () run = do con <- PGS.connect PGS.defaultConnectInfo { PGS.connectUser = "ordermage" , PGS.connectPassword = "thisisatest" , PGS.connectDatabase = "ordermage" } let port = 3000 settings = setPort port $ setBeforeMainLoop (hPutStrLn stderr ("listening on port " ++ show port)) defaultSettings runSettings settings =<< mkApp con mkApp :: PGS.Connection -> IO Application mkApp con = return $ serve api (server con)
gigavinyl/ordermage
src/App.hs
mit
709
0
16
168
189
102
87
21
1
{-# LANGUAGE CPP, OverloadedStrings #-} module BasicTests (basicSpecs) where import Yesod.Test import Foundation redirectCode :: Int #if MIN_VERSION_yesod_test(1,4,0) redirectCode = 303 #else redirectCode = 302 #endif basicSpecs :: YesodSpec MyApp basicSpecs = ydescribe "Basic tests" $ do yit "checks the home page is not logged in" $ do get' "/" statusIs 200 bodyContains "Please visit the <a href=\"/auth/login\">Login page" yit "tests an invalid login" $ do get' "/auth/login" statusIs 200 post' "/auth/page/account/login" $ do byLabel "Username" "abc" byLabel "Password" "xxx" statusIs redirectCode get' "/auth/login" statusIs 200 bodyContains "Invalid username/password combination" yit "new account page looks ok" $ do get' "/auth/page/account/newaccount" statusIs 200 htmlAllContain "title" "Register a new account" bodyContains "Register" yit "reset password page looks ok" $ do get' "/auth/page/account/resetpassword" statusIs 200 bodyContains "Send password reset email" post' "/auth/page/account/resetpassword" $ do byLabel "Username" "abc" addNonce statusIs redirectCode get' "/" statusIs 200 bodyContains "Invalid username" yit "verify page returns an error" $ do get' "/auth/page/account/verify/abc/xxxxxx" statusIs redirectCode get' "/" statusIs 200 bodyContains "invalid verification key" yit "new password returns an error" $ do get' "/auth/page/account/newpassword/abc/xxxxxx" statusIs redirectCode get' "/" statusIs 200 bodyContains "invalid verification key" yit "set password returns an error" $ do post' "/auth/page/account/setpassword" $ do addPostParam "f1" "xxx" addPostParam "f2" "xxx" addPostParam "f3" "xxx" addPostParam "f4" "xxx" addPostParam "f5" "xxx" statusIs redirectCode get' "/" statusIs 200 bodyContains "As a protection against cross-site" yit "resend verify email returns an error" $ do post' "/auth/page/account/resendverifyemail" $ do addPostParam "f1" "xxx" addPostParam "f2" "xxx" statusIs 400 bodyContains "As a protection against cross-site"
jasonzoladz/yesod-auth-account-fork
tests/BasicTests.hs
mit
2,731
0
14
993
472
183
289
68
1
module Spacer where import Data.Foldable (maximum) import Data.List (transpose) import Rainbow --[ -- [0, 0, 0, 0, 0], [0, 0, 0, 0, 0] -- [1, 2, 6, 2, 1], [0, 0, 0, 0, 0] -- [3, 4, 8, 3, 7] [0, 0, 0, 0, 0h] --] -- -- fill :: Int -> a -> [a] fill n a = take n $ repeat a spaces n = fill n ' ' padAll :: Int -> [String] -> [String] padAll n = map $ pad n pad :: Int -> String -> String pad m s = s ++ (spaces n) where n = 3 + (max 0 (m - (length s))) printLines :: [[String]] -> IO () printLines lines = mapM_ (putStrLn) formatted' where formatted' :: [String] formatted' = map (concat) formatted formatted :: [[String]] formatted = formatLines lines formatLines :: [[String]] -> [[String]] formatLines = (transpose . formatLines' . transpose) formatLines' :: [[String]] -> [[String]] formatLines' = map formatLine formatLine :: [String] -> [String] formatLine xs = map p xs where p :: String -> String p s = pad m s m :: Int m = maximum $ map length xs printLinesPretty :: [[(String, Radiant)]] -> IO () printLinesPretty lines = mapM_ action formatted where action :: [Chunk String] -> IO () action line = (mapM_ (putChunk) line) >> (putStrLn "") formatted :: [[Chunk String]] formatted = formatLines2 lines formatLines2 :: [[(String, Radiant)]] -> [[Chunk String]] formatLines2 = (transpose . formatLines2' . transpose) formatLines2' :: [[(String, Radiant)]] -> [[Chunk String]] formatLines2' = map formatLine2 formatLine2 :: [(String, Radiant)] -> [Chunk String] formatLine2 values = map (fmap (pad m)) chunks2 where chunks2 :: [Chunk String] chunks2 = map fst chunks chunks :: [(Chunk String, Int)] chunks = map (\(s,rad) -> ((fore rad (chunk s)), length s)) values m :: Int m = maximum $ fmap snd chunks
nlim/portfolio-quote
src/Spacer.hs
mit
1,881
0
14
482
748
411
337
46
1
{-# htermination (ceilingRatio :: Ratio MyInt -> MyInt) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data Tup2 a b = Tup2 a b ; data Integer = Integer MyInt ; data MyInt = Pos Nat | Neg Nat ; data Nat = Succ Nat | Zero ; data Ordering = LT | EQ | GT ; data Ratio a = CnPc a a; ceilingN0 xv (Tup2 n vw) = n; fromIntegerMyInt :: Integer -> MyInt fromIntegerMyInt (Integer x) = x; pt :: (c -> b) -> (a -> c) -> a -> b; pt f g x = f (g x); toIntegerMyInt :: MyInt -> Integer toIntegerMyInt x = Integer x; fromIntegral = pt fromIntegerMyInt toIntegerMyInt; properFractionQ1 xw xx (Tup2 q vx) = q; stop :: MyBool -> a; stop MyFalse = stop MyFalse; error :: a; error = stop MyTrue; primMinusNatS :: Nat -> Nat -> Nat; primMinusNatS (Succ x) (Succ y) = primMinusNatS x y; primMinusNatS Zero (Succ y) = Zero; primMinusNatS x Zero = x; primDivNatS0 x y MyTrue = Succ (primDivNatS (primMinusNatS x y) (Succ y)); primDivNatS0 x y MyFalse = Zero; primGEqNatS :: Nat -> Nat -> MyBool; primGEqNatS (Succ x) Zero = MyTrue; primGEqNatS (Succ x) (Succ y) = primGEqNatS x y; primGEqNatS Zero (Succ x) = MyFalse; primGEqNatS Zero Zero = MyTrue; primDivNatS :: Nat -> Nat -> Nat; primDivNatS Zero Zero = error; primDivNatS (Succ x) Zero = error; primDivNatS (Succ x) (Succ y) = primDivNatS0 x y (primGEqNatS x y); primDivNatS Zero (Succ x) = Zero; primQuotInt :: MyInt -> MyInt -> MyInt; primQuotInt (Pos x) (Pos (Succ y)) = Pos (primDivNatS x (Succ y)); primQuotInt (Pos x) (Neg (Succ y)) = Neg (primDivNatS x (Succ y)); primQuotInt (Neg x) (Pos (Succ y)) = Neg (primDivNatS x (Succ y)); primQuotInt (Neg x) (Neg (Succ y)) = Pos (primDivNatS x (Succ y)); primQuotInt wx wy = error; primModNatS0 x y MyTrue = primModNatS (primMinusNatS x (Succ y)) (Succ (Succ y)); primModNatS0 x y MyFalse = Succ x; primModNatS :: Nat -> Nat -> Nat; primModNatS Zero Zero = error; primModNatS Zero (Succ x) = Zero; primModNatS (Succ x) Zero = error; primModNatS (Succ x) (Succ Zero) = Zero; primModNatS (Succ x) (Succ (Succ y)) = primModNatS0 x y (primGEqNatS x (Succ y)); primRemInt :: MyInt -> MyInt -> MyInt; primRemInt (Pos x) (Pos (Succ y)) = Pos (primModNatS x (Succ y)); primRemInt (Pos x) (Neg (Succ y)) = Pos (primModNatS x (Succ y)); primRemInt (Neg x) (Pos (Succ y)) = Neg (primModNatS x (Succ y)); primRemInt (Neg x) (Neg (Succ y)) = Neg (primModNatS x (Succ y)); primRemInt vz wu = error; primQrmInt :: MyInt -> MyInt -> Tup2 MyInt MyInt; primQrmInt x y = Tup2 (primQuotInt x y) (primRemInt x y); quotRemMyInt :: MyInt -> MyInt -> Tup2 MyInt MyInt quotRemMyInt = primQrmInt; properFractionVu30 xw xx = quotRemMyInt xw xx; properFractionQ xw xx = properFractionQ1 xw xx (properFractionVu30 xw xx); properFractionR1 xw xx (Tup2 vy r) = r; properFractionR xw xx = properFractionR1 xw xx (properFractionVu30 xw xx); properFractionRatio :: Ratio MyInt -> Tup2 MyInt (Ratio MyInt) properFractionRatio (CnPc x y) = Tup2 (fromIntegral (properFractionQ x y)) (CnPc (properFractionR x y) y); ceilingVu8 xv = properFractionRatio xv; ceilingN xv = ceilingN0 xv (ceilingVu8 xv); fromIntMyInt :: MyInt -> MyInt fromIntMyInt x = x; primMinusNat :: Nat -> Nat -> MyInt; primMinusNat Zero Zero = Pos Zero; primMinusNat Zero (Succ y) = Neg (Succ y); primMinusNat (Succ x) Zero = Pos (Succ x); primMinusNat (Succ x) (Succ y) = primMinusNat x y; primPlusNat :: Nat -> Nat -> Nat; primPlusNat Zero Zero = Zero; primPlusNat Zero (Succ y) = Succ y; primPlusNat (Succ x) Zero = Succ x; primPlusNat (Succ x) (Succ y) = Succ (Succ (primPlusNat x y)); primPlusInt :: MyInt -> MyInt -> MyInt; primPlusInt (Pos x) (Neg y) = primMinusNat x y; primPlusInt (Neg x) (Pos y) = primMinusNat y x; primPlusInt (Neg x) (Neg y) = Neg (primPlusNat x y); primPlusInt (Pos x) (Pos y) = Pos (primPlusNat x y); psMyInt :: MyInt -> MyInt -> MyInt psMyInt = primPlusInt; ceilingCeiling0 xv MyTrue = psMyInt (ceilingN xv) (fromIntMyInt (Pos (Succ Zero))); ceilingCeiling0 xv MyFalse = ceilingN xv; ceilingR0 xv (Tup2 vv r) = r; ceilingR xv = ceilingR0 xv (ceilingVu8 xv); intToRatio x = CnPc (fromIntMyInt x) (fromIntMyInt (Pos (Succ Zero))); fromIntRatio :: MyInt -> Ratio MyInt fromIntRatio = intToRatio; primCmpNat :: Nat -> Nat -> Ordering; primCmpNat Zero Zero = EQ; primCmpNat Zero (Succ y) = LT; primCmpNat (Succ x) Zero = GT; primCmpNat (Succ x) (Succ y) = primCmpNat x y; primCmpInt :: MyInt -> MyInt -> Ordering; primCmpInt (Pos Zero) (Pos Zero) = EQ; primCmpInt (Pos Zero) (Neg Zero) = EQ; primCmpInt (Neg Zero) (Pos Zero) = EQ; primCmpInt (Neg Zero) (Neg Zero) = EQ; primCmpInt (Pos x) (Pos y) = primCmpNat x y; primCmpInt (Pos x) (Neg y) = GT; primCmpInt (Neg x) (Pos y) = LT; primCmpInt (Neg x) (Neg y) = primCmpNat y x; compareMyInt :: MyInt -> MyInt -> Ordering compareMyInt = primCmpInt; primMulNat :: Nat -> Nat -> Nat; primMulNat Zero Zero = Zero; primMulNat Zero (Succ y) = Zero; primMulNat (Succ x) Zero = Zero; primMulNat (Succ x) (Succ y) = primPlusNat (primMulNat x (Succ y)) (Succ y); primMulInt :: MyInt -> MyInt -> MyInt; primMulInt (Pos x) (Pos y) = Pos (primMulNat x y); primMulInt (Pos x) (Neg y) = Neg (primMulNat x y); primMulInt (Neg x) (Pos y) = Neg (primMulNat x y); primMulInt (Neg x) (Neg y) = Pos (primMulNat x y); srMyInt :: MyInt -> MyInt -> MyInt srMyInt = primMulInt; compareRatio :: Ratio MyInt -> Ratio MyInt -> Ordering compareRatio (CnPc x y) (CnPc x' y') = compareMyInt (srMyInt x y') (srMyInt x' y); esEsOrdering :: Ordering -> Ordering -> MyBool esEsOrdering LT LT = MyTrue; esEsOrdering LT EQ = MyFalse; esEsOrdering LT GT = MyFalse; esEsOrdering EQ LT = MyFalse; esEsOrdering EQ EQ = MyTrue; esEsOrdering EQ GT = MyFalse; esEsOrdering GT LT = MyFalse; esEsOrdering GT EQ = MyFalse; esEsOrdering GT GT = MyTrue; gtRatio :: Ratio MyInt -> Ratio MyInt -> MyBool gtRatio x y = esEsOrdering (compareRatio x y) GT; ceilingRatio :: Ratio MyInt -> MyInt ceilingRatio x = ceilingCeiling0 x (gtRatio (ceilingR x) (fromIntRatio (Pos Zero)));
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/ceiling_1.hs
mit
6,131
0
11
1,229
2,890
1,505
1,385
140
1
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Betfair.APING.Types.RunnerStatus ( RunnerStatus(..) ) where import Data.Aeson.TH (Options (omitNothingFields), defaultOptions, deriveJSON) import Protolude import Text.PrettyPrint.GenericPretty data RunnerStatus = ACTIVE | WINNER | LOSER | REMOVED_VACANT | REMOVED | HIDDEN deriving (Eq, Show, Generic, Pretty, Read, Enum) $(deriveJSON defaultOptions {omitNothingFields = True} ''RunnerStatus)
joe9/betfair-api
src/Betfair/APING/Types/RunnerStatus.hs
mit
695
0
9
159
124
77
47
21
0
module Main where import Data.Map.Strict(Map) import qualified Data.Map.Strict as M import Data.Maybe(fromJust) import Data.Tree(flatten, unfoldTree) import Diagrams.Backend.SVG.CmdLine(defaultMain) import Diagrams.Prelude main = defaultMain $ pad 1.1 $ renderTree buildTree renderTree = mconcat . flatten . fmap drawBranch buildTree = unfoldTree (growTree fs) seed seed = (origin, unitY) drawBranch (p, v) = position [(p, fromOffsets [v])] growTree fs n = if stop n then branchTip n else branches fs n branchTip n = (n, []) branches fs n = (n, zipWith ($) fs (repeat n)) fs = buildXfm symMap id rule -- The rule has been transformed from "br[<B][>B]" rule = ["b", "r", "<", ",", "b", "r", ">"] -- The symbols have been parsed from JSON: -- [{"b": {"follow": null}}, -- could have a parameter to indicate offset -- {"r": {"scale": 0.6}}, -- {"<": {"angle": 0.14285714285714}}, -- {">": {"angle": -0.14285714285714}} -- ] symbols = (map toSymbolMap . filter isTerminal) grammar isTerminal (Follow _) = True isTerminal (Scale _ _) = True isTerminal (Turn _ _) = True isTerminal _ = False toSymbolMap (Follow s) = (s, followBranch) toSymbolMap (Scale s r) = (s, scaleBranch r) toSymbolMap (Turn s t) = (s, rotateBranch t) toSymbolMap t = error $ "Bad terminal in toSymbolMap:" ++ show t type SeedVal = ((Double, Double), (Double, Double)) type Grammar = [GrammarDef] data GrammarDef = Var String | Turn String Double | Scale String Double | Follow String | Seed String SeedVal | Rule String String deriving (Show) grammar = [ Follow "b" , Var "B" , Scale "r" 0.6 , Turn "<" 0.14285714285714 , Turn ">" (-0.14285714285714) , Seed "s" ((0, 0), (0, 1)) , Rule "R1" "b r [ B < ] [ B > ]" ] -- Assumes string has been converted to a comma-separated list of -- terminal symbols corresponding to transformations. buildXfm _ f [] = f : [] buildXfm m f (",":xs) = f : buildXfm m id xs buildXfm m f (x:xs) = buildXfm m (g . f) xs where g = fromJust (M.lookup x m) symMap = initMap symbols initMap = foldr updateMap M.empty updateMap (k,f) = M.insert k f stop (_, v) = magnitude v < 0.05 followBranch (p, v) = (p .+^ v, v) scaleBranch s (p, v) = (p, v ^* s) rotateBranch t (p, v) = (p, rotateBy t v)
bobgru/tree-derivations
src/LSystem2.hs
mit
2,460
0
10
658
849
469
380
55
2
module Control.AutoUpdate ( mkAutoUpdate ) where import Control.Monad import Control.Concurrent (forkIO) import Control.Concurrent.MVar (newEmptyMVar, putMVar, readMVar, takeMVar, tryPutMVar, tryTakeMVar) import Control.Exception (SomeException, catch, throw) import Data.IORef (newIORef, readIORef, writeIORef) import Control.AutoUpdate.Util (cb, handle ,waitForAnimationFrame, requestAnimationFrame, cancelAnimationFrame) import GHCJS.Foreign import System.IO mkAutoUpdate :: IO a -> IO (IO a) mkAutoUpdate ua = do currRef <- newIORef Nothing needsRunning <- newEmptyMVar -- The last value generated, to allow for blocking semantics when currRef -- is Nothing. lastValue <- newEmptyMVar void $ forkIO $ forever $ do -- block until a value is actually needed. takeMVar needsRunning h <- fixIO $ \h -> requestAnimationFrame $ do a <- catch ua $ \e -> do cancelAnimationFrame h return $ throw (e :: SomeException) writeIORef currRef $ Just a void $ tryTakeMVar lastValue putMVar lastValue a writeIORef currRef Nothing void $ takeMVar lastValue release $ cb h return $ do mval <- readIORef currRef case mval of Just val -> return val Nothing -> do void $ tryPutMVar needsRunning () readMVar lastValue
arianvp/ghcjs-auto-update
Control/AutoUpdate.hs
mit
1,496
0
23
464
376
188
188
35
2
module HTMLTokenizer.MonadPlus where import HTMLTokenizer.Prelude hiding (foldl, foldl1, concat) {-# INLINE foldl #-} foldl :: MonadPlus m => (a -> b -> a) -> a -> m b -> m a foldl step start fetch = loop start where loop !state = mplus (do !element <- fetch loop (step state element)) (return state) {-# INLINE foldl1 #-} foldl1 :: MonadPlus m => (a -> a -> a) -> m a -> m a foldl1 step fetch = do !start <- fetch foldl step start fetch {-# INLINE concat #-} concat :: (MonadPlus m, Monoid a) => m a -> m a concat = foldl mappend mempty {-# INLINE concat1 #-} concat1 :: (MonadPlus m, Semigroup a) => m a -> m a concat1 = foldl1 (<>) {-# INLINE foldlM #-} foldlM :: MonadPlus m => (a -> b -> m a) -> a -> m b -> m a foldlM step start fetch = loop start where loop !state = mplus (do !element <- fetch loop =<< step state element) (return state)
nikita-volkov/html-tokenizer
library/HTMLTokenizer/MonadPlus.hs
mit
967
0
13
293
380
187
193
36
1
module SolutionTree where import System.IO import Board {- > Big TODO: > - Generate all move permutations > - Work from the bottom up (with solutions that provide one marble left) > - Create a set of solutions > - Solve puzzle -} data Tree = Root { board :: Board, branches :: [Tree] } | Node { board :: Board, move :: Move, parent :: Tree, branches :: [Tree] } deriving (Eq, Show, Read) generateTree :: Tree -> [Tree] generateTree n | vms == [] = [] | otherwise = [let nn = Node b m n $ generateTree nn in nn | (m, b) <- nbs] where b = board n vms = stripSimilarMoves b $ validMoves b nbs = map (\x -> (x, makeMove b x)) vms -- The root node root :: Tree root = Root trunkBoard $ generateTree root -- Getting the move string that resulted in a board getMoveStringRaw :: Tree -> [Move] getMoveStringRaw t = undefined getMoveString :: Tree -> [Move] getMoveString t = reverse $ getMoveStringRaw t -- Making a list of trees from a tree makeList :: Tree -> [Tree] makeList t@(Root board branch) = t : (concat $ map (makeList) branch) makeList t@(Node board _ _ branch) = t : (concat $ map (makeList) branch) -- Finding the solution to the game findSolution :: [Tree] -> [Move] findSolution [] = [] findSolution (x:xs) | getNumBalls b == 1 = getMoveString x | otherwise = findSolution xs where b = board x
crockeo/ballgame
src/SolutionTree.hs
mit
1,375
0
12
324
466
250
216
27
1
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ViewPatterns #-} module GLM.Dot where import GLM.Parser import qualified GLM.Nesting as N import Data.Maybe import System.Environment import System.Exit import System.IO import Data.Digest.Pure.MD5 import Data.List import Data.String.Interpolate import qualified Data.ByteString.Lazy.Char8 as BS data Options = Options { edges :: Bool , flatten :: Bool } deriving (Eq, Show) def :: Options def = Options { edges = False , flatten = False } str5 :: String -> String str5 = take 9 . show . md5 . BS.pack main :: IO () main = getArgs >>= start def start :: Options -> [String] -> IO () start _ ["-h" ] = help start _ ["--help" ] = help start o ("-e" : args) = start (o {edges = True}) args start o ("--edges" : args) = start (o {edges = True}) args start o ("-f" : args) = start (o {flatten = True}) args start o ("--flatten": args) = start (o {flatten = True}) args start o args = go args >>= mapM_ (outputResult o) outputResult :: Options -> ParseResult -> IO () outputResult _ (Left issue) = putStrLn "Got an error:" >> spew issue >> exitFailure outputResult opts (Right results) = putStrLn [i|digraph {#{unl $ concatMap graph (filter crit ung)}}|] where unl s = "\n" ++ unlines (map ("\t" ++) s) ung = if (flatten opts) then N.flatten results else results rt = concatMap refs ung crit = criteria (edges opts) rt spew :: Show a => a -> IO () spew = hPutStrLn stderr . show criteria :: Bool -> [String] -> Entry -> Bool criteria False _ _ = True criteria True l e = isJust $ find (== name e) l refs :: Entry -> [String] refs e@(Entry _ p) = fromMaybe [] $ do f <- lookup "from" c t <- lookup "to" c return [name e, f, t] where c = catProps p help :: IO () help = putStrLn "Usage: glm2dot [-h|--help] [-e|--edges] [-f|--flatten] [FILE]*" go :: [String] -> IO [ParseResult] go xs@(_:_) = mapM processFile xs go [] = (return . glmParser "<STDIN>") `fmap` getContents processFile :: String -> IO ParseResult processFile f = glmParser f `fmap` readFile f chash :: Entry -> String chash = (++ "ef") . take 4 . str5 . (!! 1) . unSelector graph :: Entry -> [String] graph e@(Entry ("object":_:_) _) = fromMaybe [ [i|"#{nhash e}" [label="#{name e}", fillcolor="##{chash e}", style=filled];|] ] (edge e) graph e@(Entry s _) = [ [i|// Missed entry #{s} - #{name e}|] ] edge :: Entry -> Maybe [String] edge e@(Entry _ p) = do f <- lookup "from" c t <- lookup "to" c return [[i|"#{str5 f}" -> "#{str5 t}" [label="#{name e}"]; // #{f} -> #{t}|]] where c = catProps p nhash :: Entry -> String nhash = str5 . name name :: Entry -> String name (Entry (_:s:_) p) = maybe s noquote (lookup "name" c) where c = catProps p name _ = "noname" -- TODO: Shouldn't need this now... -- noquote :: String -> String noquote = filter (/= '\'')
sordina/GLM
src/GLM/Dot.hs
mit
2,923
0
11
676
1,153
620
533
-1
-1
import Huffman import Data.Char import System.Environment import System.IO import System.IO.Error import Data.List import Data.List.Split import qualified Data.Binary.Put as P import qualified Data.Binary.Get as G import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Internal as I getReg = do c <- G.getWord8 f <- G.getWord32be return (c,f) getRegs n = do if n == 0 then return[] else do {r <- getReg; rs <- getRegs (n-1); return(r:rs);} {-convertEncodedWord _ [] = ""-} {-convertEncodedWord n (x:xs)-} {-| n == 0 = ""-} {-| n > 7 = int2bin $ ord $ I.w2c x ++ convertEncodedWord (n-8) xs-} {-| otherwise = take n $ int2bin $ ord $ I.w2c x-} convertEncodedWord n xs = take n $ concat $ map (int2bin.ord.I.w2c) xs {-convertEncodedWord n xs = take n $ concat $ map (int2bin.fromIntegral) xs-} getEncoded = do empty <- G.isEmpty if empty then return[] else do {r <- G.getWord8; rs <- getEncoded; return(r:rs);} {-getEncoded = do-} {-empty <- G.isEmpty-} {-if empty then return[]-} {-else do {r <- G.getWord32be; rs <- getEncoded; return(r:rs);}-} getAll = do numOfCharacters <- G.getWord8 wordLength <- G.getWord8 freqList <- getRegs (fromIntegral numOfCharacters) encodedWord <- getEncoded return((numOfCharacters,wordLength,freqList,encodedWord)) expand tree = expand' tree where expand' (Folha a _) [] = [a] expand' (Folha a _) xs = a : expand' tree xs expand' (No _ left right) (x:xs) = expand' (if x == '0' then right else left) xs int2bin x | x `div` 2 == 0 = show x | otherwise = int2bin (x `div` 2) ++ show (x `mod` 2) convert [] = [] convert ((c,f):xs) = (I.w2c c,fromIntegral f) : convert xs printRegs[] = return () printRegs (x:xs) = do printReg x printRegs xs printReg (c,f) = putStrLn ((show(I.w2c c)) ++ "-" ++show f) printEncoded [] = return () printEncoded (x:xs) = do printChar x printEncoded xs printChar x = putStr (int2bin $ ord $ I.w2c x) printAll (c,n,lis,encoded) = do putStrLn (show $ ord $ I.w2c c) putStrLn (show $ ord $ I.w2c n) printRegs lis printEncoded encoded joinBlocksLn [] = "" joinBlocksLn (xs:xss) = xs ++ detToken ++ joinBlocksLn (xss) where detToken = if length xss /= 0 then "\n" else "" main = do args <- getArgs file <- L.readFile (head args) let (numOfCharacters,wordLength,freqList_,encodedWord_) = G.runGet getAll file printAll (numOfCharacters,wordLength,freqList_,encodedWord_) let freqList = convert freqList_ encodedWord = convertEncodedWord (ord $ I.w2c wordLength) encodedWord_ leafList = huffmanList_ freqList tree = huffmanTree_ leafList expandedWord = expand (head tree) encodedWord {-expandedWordList = splitOn ";" expandedWord-} {-writeFile "output.out" (joinBlocksLn expandedWordList)-} writeFile "output.out" expandedWord return ()
AndressaUmetsu/PapaEhPop
huffman/expand.hs
mit
2,985
1
14
692
1,037
535
502
70
4
module Hasql.Pool ( Pool, Settings(..), acquire, release, UsageError(..), use, ) where import Hasql.Pool.Prelude import qualified Hasql.Connection import qualified Hasql.Session import qualified Data.Pool as ResourcePool import qualified Hasql.Pool.ResourcePool as ResourcePool -- | -- A pool of connections to DB. newtype Pool = Pool (ResourcePool.Pool (Either Hasql.Connection.ConnectionError Hasql.Connection.Connection)) deriving (Show) -- | -- Settings of the connection pool. Consist of: -- -- * Pool-size. -- -- * Timeout. -- An amount of time for which an unused resource is kept open. -- The smallest acceptable value is 0.5 seconds. -- -- * Connection settings. -- type Settings = (Int, NominalDiffTime, Hasql.Connection.Settings) -- | -- Given the pool-size, timeout and connection settings -- create a connection-pool. acquire :: Settings -> IO Pool acquire (size, timeout, connectionSettings) = fmap Pool $ ResourcePool.createPool acquire release stripes timeout size where acquire = Hasql.Connection.acquire connectionSettings release = either (const (pure ())) Hasql.Connection.release stripes = 1 -- | -- Release the connection-pool. release :: Pool -> IO () release (Pool pool) = ResourcePool.destroyAllResources pool -- | -- A union over the connection establishment error and the session error. data UsageError = ConnectionError Hasql.Connection.ConnectionError | SessionError Hasql.Session.QueryError deriving (Show, Eq) -- | -- Use a connection from the pool to run a session and -- return the connection to the pool, when finished. use :: Pool -> Hasql.Session.Session a -> IO (Either UsageError a) use (Pool pool) session = fmap (either (Left . ConnectionError) (either (Left . SessionError) Right)) $ ResourcePool.withResourceOnEither pool $ traverse $ Hasql.Session.run session
nikita-volkov/hasql-pool
library/Hasql/Pool.hs
mit
1,888
0
14
333
408
239
169
41
1
----------------------------------------------------------- ---- | ---- Module: Anagram ---- Description: Find anagrams ---- Copyright: (c) 2015 Alex Dzyoba <[email protected]> ---- License: MIT ------------------------------------------------------------- module Anagram where import Data.List (sort) import qualified Data.Text as T toLower :: String -> String toLower s = T.unpack $ T.toLower $ T.pack s anagram :: String -> String -> Bool anagram s1 s2 = toLower s1 /= toLower s2 && -- avoid anagram of itself case (sort (toLower s1) == sort (toLower s2)) anagramsFor :: String -> [String] -> [String] anagramsFor string = filter (anagram string)
dzeban/haskell-exercism
anagram/haskell/anagram/Anagram.hs
mit
673
0
10
108
162
89
73
10
1
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Web.User where import API import Caltrops.Common import Web.Bootstrap import Web.Common import qualified Data.IntMap as IM import Data.IntMap (IntMap) import Data.Text (Text) import Data.SafeCopy import Data.Acid import Data.Typeable import Data.ByteString (ByteString) import GHC.Generics import Control.Monad.State import Control.Monad.Reader import qualified Text.Digestive.Blaze.Html5 as F import qualified Data.Text as T import Text.Blaze.Html5 (Html) import qualified Text.Blaze.Html5 as H import Text.Digestive type Logins = IntMap ByteString type Users = IntMap User data UserData = UserData { udataNextId :: Id , udataUsers :: Users , udataLogins :: Logins } deriving (Typeable) $(deriveSafeCopy 0 'base ''Id) $(deriveSafeCopy 0 'base ''User) $(deriveSafeCopy 0 'base ''UserData) updateUser :: User -> Update UserData () updateUser u = do let k = unId $ userId u users <- gets udataUsers modify $ \dat -> dat{ udataUsers = IM.insert k u users } updatePassword :: Id -> ByteString -> Update UserData () updatePassword (Id i) p = do logins <- gets udataLogins modify $ \dat -> dat{ udataLogins = IM.insert i p logins } putUserData :: UserData -> Update UserData () putUserData = put getUserData :: Query UserData UserData getUserData = ask fresh :: Update UserData Id fresh = do i <- gets udataNextId modify $ \dat -> dat{ udataNextId = i + 1 } return i $(makeAcidic ''UserData [ 'putUserData , 'getUserData , 'updateUser , 'fresh , 'updatePassword ]) -------------------------------------------------------------------------------- -- Forms -------------------------------------------------------------------------------- data UserUpdate = UserUpdate { userUpdateName :: Text , userUpdateEmail :: Text , userUpdatePass :: (Maybe Text, Maybe Text) } deriving (Typeable, Generic, Show, Eq) passwordUpdateForm :: Monad m => Form Text m (Maybe Text, Maybe Text) passwordUpdateForm = (,) <$> "password" .: optionalText Nothing <*> "password-check" .: optionalText Nothing userUpdateForm :: Monad m => Maybe User -> Form Text m UserUpdate userUpdateForm mu = UserUpdate <$> "name" .: check "name cannot be empty" notEmpty (text $ userName <$> mu) <*> "email" .: check "email cannot be empty" notEmpty (text $ userEmail <$> mu) <*> "password" .: check "passwords must match" mustmatch passwordUpdateForm where notEmpty = not . T.null mustmatch (a,b) = a == b userUpdateSuccessHtml :: Html userUpdateSuccessHtml = userContainer $ H.div "Successfully updated user." passwordUpdateView :: View Html -> Html passwordUpdateView v = do H.legend "Password:" bootstrapFormFieldPassword "password" "Password:" v bootstrapFormFieldPassword "password-check" "Password Check:" v userUpdateView :: View Html -> Html userUpdateView v = do H.legend "User:" bootstrapFormFieldInput "name" "Name:" v bootstrapFormFieldInput "email" "Email:" v passwordUpdateView $ subView "password" v F.errorList "password" v userUpdatePage :: Monad m => User -> m Html userUpdatePage u = do v <- getForm "user" $ userUpdateForm $ Just u let v' = H.toHtml <$> v return $ userContainer $ formWrapper (userUpdateView v') userUpdateLink updatedPassword :: UserUpdate -> Maybe Text updatedPassword UserUpdate{..} = do one <- fst userUpdatePass two <- snd userUpdatePass if one == two then Just one else Nothing applyUpdateUser :: UserUpdate -> User -> User applyUpdateUser UserUpdate{..} u = u{ userName = userUpdateName , userEmail = userUpdateEmail }
schell/caltrops
src/Web/User.hs
mit
4,277
0
13
1,035
1,112
583
529
104
2
{-#LANGUAGE ScopedTypeVariables #-} {-#LANGUAGE DeriveGeneric #-} {-#LANGUAGE DataKinds #-} {-#LANGUAGE GADTs #-} module Foreign.Storable.Generic.InternalSpec where -- Test tools import Test.Hspec import Test.QuickCheck import GenericType -- Tested modules import Foreign.Storable.Generic.Internal -- Additional data import Foreign.Storable.Generic.Tools import Foreign.Storable.Generic.Instances import GHC.Generics import Foreign.Marshal.Alloc (malloc, mallocBytes, free) import Foreign.Marshal.Array (peekArray, pokeArray) import Foreign.Ptr (Ptr, plusPtr) import Data.Word spec :: Spec spec = do describe "internalSizeOf" $ do it "is equal to: calcSize $ zip (glistSizeOf' a) (glistAlignment' a)" $ do property (\((NestedToType (GenericType val)) :: NestedToType 4) -> internalSizeOf val `shouldBe` (calcSize $ zip (glistSizeOf' val) (glistAlignment' val) ) ) describe "internalAlignment" $ do it "is equal to: maximum (glistAlignment' a)" $ do property (\((NestedToType (GenericType val)) :: NestedToType 4) -> internalAlignment val `shouldBe` (maximum $ glistAlignment' val) ) describe "internalOffsets" $ do it "is equal to: calcOffsets $ zip (glistSizeOf' a) (glistAlignment' a)" $ do property (\((NestedToType (GenericType val)) :: NestedToType 4) -> internalOffsets val `shouldBe` (calcOffsets $ zip (glistSizeOf' val) (glistAlignment' val) ) ) describe "internalPeekByteOff" $ do it "is equal to: gpeekByteOff' (internalOffsets a) ptr off" $ do property (\((NestedToType (GenericType (val :: f p))) :: NestedToType 4) -> do let size = internalSizeOf val no_fields = gnumberOf' (undefined :: f p) off <- generate $ suchThat arbitrary (\x -> x>=0 && x < 100) -- Area in memory to peek bytes <- generate $ ok_vector (off + size) ptr <- mallocBytes (off + size) pokeArray ptr bytes -- first peek v1 <- internalPeekByteOff ptr off :: IO (f p) v2 <- gpeekByteOff' (internalOffsets val) (no_fields - 1) ptr off :: IO (f p) free ptr v1 `shouldBe` v2 ) it "it reads only specified area of the memory" $ do property $ (\((NestedToType (GenericType (test_type1 :: f p))) :: NestedToType 4) -> do let size = internalSizeOf test_type1 pokeBytes = pokeArray :: (Ptr Word8 -> [Word8] -> IO ()) -- The memory area ptr <- mallocBytes (size+16) -- Beginning state. bytes1_beginning <- generate $ ok_vector 8 bytes1_middle <- generate $ ok_vector size bytes1_end <- generate $ ok_vector 8 pokeBytes ptr bytes1_beginning pokeBytes (plusPtr ptr 8) bytes1_middle pokeBytes (plusPtr ptr (size+8)) bytes1_end v1 <- internalPeekByteOff ptr 8 :: IO (f p) -- Changed state bytes2_beginning <- generate $ suchThat (ok_vector 8) (/=bytes1_beginning) bytes2_end <- generate $ suchThat (ok_vector 8) (/=bytes1_end) pokeBytes ptr bytes2_beginning pokeBytes (plusPtr ptr (size + 8)) bytes2_end v2 <- internalPeekByteOff ptr 8 :: IO (f p) v1 `shouldBe` v2 ) describe "internalPokeByteOff" $ do it "is equal to: gpokeByteOff' (internalOffsets a) ptr off v" $ do property (\((NestedToType (GenericType (val :: f p))) :: NestedToType 4) -> do let size = internalSizeOf val no_fields = gnumberOf' (undefined :: f p) off <- generate $ suchThat arbitrary (\x -> x>=0 && x < 100) -- Area in memory to poke ptr <- mallocBytes (off + size) -- first poke internalPokeByteOff ptr off val bytes1 <- peekArray (off + size) ptr :: IO [Word8] -- second poke gpokeByteOff' (internalOffsets val) (no_fields - 1) ptr off val bytes2 <- peekArray (off + size) ptr :: IO [Word8] free ptr bytes1 `shouldBe` bytes2 ) it "it modifies only specified area of the memory" $ do property $ (\((NestedToType (GenericType test_type1)) ::NestedToType 4)-> do test_type2 <- generate $ suchThat arbitrary (/=test_type1) -- if test_type1 is different from test_type2, then -- the memory state has to change when poking both of them let size = internalSizeOf test_type1 peekBytes = peekArray :: (Int -> Ptr Word8 -> IO [Word8]) -- The memory area ptr <- mallocBytes (size+16) -- Beginning state. mem_state1_beginning <- peekBytes 8 ptr mem_state1_middle <- peekBytes size (plusPtr ptr 8) mem_state1_end <- peekBytes 8 (plusPtr ptr (size+8)) internalPokeByteOff ptr 8 test_type1 -- Poked first variable mem_state2_beginning <- peekBytes 8 ptr mem_state2_middle <- peekBytes size (plusPtr ptr 8) mem_state2_end <- peekBytes 8 (plusPtr ptr (size+8)) internalPokeByteOff ptr 8 test_type2 -- Poked second state mem_state3_beginning <- peekBytes 8 ptr mem_state3_middle <- peekBytes size (plusPtr ptr 8) mem_state3_end <- peekBytes 8 (plusPtr ptr (size+8)) -- Beginnings and ends should stay the same. The middle one should be different from -- the one at the beginning. sequence_ [mem_state1_beginning `shouldBe` mem_state2_beginning ,mem_state2_beginning `shouldBe` mem_state3_beginning ,mem_state1_end `shouldBe` mem_state2_end ,mem_state2_end `shouldBe` mem_state3_end ,(mem_state1_middle /= mem_state2_middle) || (mem_state1_middle /= mem_state3_middle) `shouldBe` True] ) describe "other" $ do it "poke, then peek: receive the poked value" $ do property $ (\((NestedToType (GenericType (val :: f p) )) :: NestedToType 4) -> do let size = internalSizeOf val off <- generate $ suchThat arbitrary (\x -> x>=0 && x < 100) ptr <- mallocBytes (size + off) internalPokeByteOff ptr off val p_val <- internalPeekByteOff ptr off :: IO (f p) val `shouldBe` p_val )
mkloczko/derive-storable
test/Spec/Foreign/Storable/Generic/InternalSpec.hs
mit
7,448
0
25
2,924
1,805
897
908
105
1
module TypeLinking where import Debug.Trace import Data.Maybe import Data.List import Environment import TypeDatabase import AST import TypeChecking typeLinkingFailure :: String -> [Type] typeLinkingFailure msg = error msg --typeLinkingFailure msg = [] typeLinkingFailure' :: String -> [Symbol] typeLinkingFailure' msg = error msg --typeLinkingFailure' msg = [] typeLinkingCheck :: TypeNode -> [[String]] -> Environment -> [Type] typeLinkingCheck _ _ ENVE = [TypeVoid] typeLinkingCheck db imps (ENV su c) = if (elem Nothing imps') || (null cts') then [] else tps where (SU cname kd st inhf) = su (SU cnamei kdi sti inhfi) = inhf [sym] = [sym | sym <- symbolTable inhf, localName sym == last cname] SYM mds ls ln lt = sym imps' = map (traverseNodeEntry db) imps cts = map (\env -> typeLinkingCheck db imps env) c cts' = if and $ map (\tps -> tps /= []) cts then [TypeVoid] else [] --cts' = if or $ map null cts then [] else [TypeVoid] [varsym] = st tps = case kd of Var expr -> if typeLinkingExpr db imps su (Binary "=" (ID (Name ([localName varsym])) 0) expr 0) == [] then [] else cts' Field varsym (Just expr) -> let syms = dropWhile (varsym /=) [sym | sym@(SYM mds _ _ _) <- sti, not $ elem "static" mds] forward = or (map (\sym -> identifierInExpr (localName sym) expr) syms) in if forward then typeLinkingFailure $ "forward use of syms " ++ (show varsym) ++ (show expr) else if typeLinkingExpr db imps su (Binary "=" (ID (Name ([localName varsym])) 0) expr 0) == [] then typeLinkingFailure $ "field type mis match expression " ++ (show varsym) ++ (show expr) else cts' Field _ Nothing -> cts' Exp expr -> typeLinkingExpr db imps su expr Ret expr -> let rtp = scopeReturnType su in let incons = scopeConstructor su in case (rtp, isNothing expr) of (TypeVoid, True) -> [TypeVoid] (TypeVoid, False) -> typeLinkingFailure $ "Return in a void method: " ++ (show expr) (_, True) -> if incons then [TypeVoid] else typeLinkingFailure $ "Return nothing in a non-void method: " ++ (show expr) _ -> case filter filterNonFunction $ typeLinkingExpr db imps su (fromJust expr) of [] -> typeLinkingFailure $ "Return type no match: " ++ (show expr) [tp] -> if not . null $ assignConversion db tp rtp then [TypeVoid] else typeLinkingFailure $ "Return assign conversion failure: " ++ (show tp) ++ (show rtp) a -> typeLinkingFailure $ "Return type multi match: " ++ (show expr) ++ (show a) ForBlock -> let typeCond = cts !! 1 casting = castConversion db (head typeCond) TypeBoolean in case (typeCond, casting) of ([], _) -> typeLinkingFailure $ "For condition: " ++ (show typeCond) ([TypeVoid], _) -> cts' ([TypeBoolean], _) -> cts' (_, []) -> typeLinkingFailure $ "For condition: " ++ (show typeCond) (_, _) -> cts' WhileBlock expr -> let typeExpr = typeLinkingExpr db imps su expr condition = (not . null $ typeExpr) && (length typeExpr == 1) && (not . null $ castConversion db (head typeExpr) TypeBoolean) in if condition then cts' else typeLinkingFailure $ "While condition: " ++ (show typeExpr) IfBlock expr -> let typeExpr = typeLinkingExpr db imps su expr condition = (not . null $ typeExpr) && (length typeExpr == 1) && (not . null $ castConversion db (head typeExpr) TypeBoolean) in if condition then cts' else typeLinkingFailure $ "If condition: " ++ (show typeExpr) ++ (show expr) Class -> cts' Method _ -> cts' Interface -> cts' Statement -> cts' Package -> cts' {- typeLinkingPrefix :: TypeNode -> [[String]] -> [String] -> [[String]] typeLinkingPrefix db imps cname = concat tps where ps = map (\i -> (take i cname)) [1..(length $ init cname)] tps = map (traverseTypeEntryWithImports db imps) ps -} filterNonFunction (Function _ _ _) = False filterNonFunction _ = True --------------------------------------------------------------------------------------------------------- typeLinkingExpr :: TypeNode -> [[String]] -> SemanticUnit -> Expression -> [Type] typeLinkingExpr db imps su (Super _) = [TypeVoid] typeLinkingExpr db imps su Null = [TypeNull] typeLinkingExpr db imps su (Unary op expr _) = case op of "!" -> if null $ castConversion db tp TypeBoolean then typeLinkingFailure "Unary !" else [tp] "+" -> if null $ castConversion db tp TypeInt then typeLinkingFailure "Unary +" else [tp'] "-" -> if null $ castConversion db tp TypeInt then typeLinkingFailure "Unary -" else [tp'] where [tp] = typeLinkingExpr db imps su expr tp' = widenType tp typeLinkingExpr db imps su expr@(Binary op exprL exprR _) | length typeLs /= 1 || length typeRs /= 1 = [] | elem op ["+"] = case (typeL, typeR) of (TypeVoid, _) -> typeLinkingFailure "Binary + TypeVoid" (_, TypeVoid) -> typeLinkingFailure "Binary + TypeVoid" ((Object (Name ["java", "lang", "String"])), _) -> [(Object (Name ["java", "lang", "String"]))] (_, (Object (Name ["java", "lang", "String"]))) -> [(Object (Name ["java", "lang", "String"]))] (_, _) -> if typeLInt && typeRInt then typeLR' else typeLinkingFailure "Binary +" | elem op ["-", "*", "/", "%"] = if typeLInt && typeRInt then typeLR' else typeLinkingFailure "Binary arithematic op" | elem op ["<", ">", "<=", ">="] = if typeLInt && typeRInt then [TypeBoolean] else typeLinkingFailure "Binary comparision op" | elem op ["&&", "||", "&", "|"] = if typeLBool && typeRBool then [TypeBoolean] else typeLinkingFailure "Binary logical op" | elem op ["==", "!="] = if null equality then typeLinkingFailure $ "Binary " ++ (show typeL) ++ op ++ (show typeR) else [TypeBoolean] | elem op ["="] = if assignRL && (finalArrayLength db imps su exprL) then [typeL] else typeLinkingFailure $ "Binary =" ++ (show typeL) ++ (show typeR) ++ (show $ assignConversion db typeR typeL) where typeLs = case filter filterNonFunction $ typeLinkingExpr db imps su exprL of [] -> typeLinkingFailure $ "Binary typeL no match: type(left) " ++ op ++ " type(right)" ++ (show exprL) ++ (show exprR) [l] -> [l] a -> typeLinkingFailure $ "Binary typeL multi match: type(left) " ++ op ++ " type(right)" ++ (show exprL) ++ (show exprR) ++ (show a) [typeL] = typeLs typeRs = case filter filterNonFunction $ typeLinkingExpr db imps su exprR of [] -> typeLinkingFailure $ "Binary typeR no match: type(left) " ++ op ++ " type(right)" ++ (show exprL) ++ (show exprR) [r] -> [r] a -> typeLinkingFailure $ "Binary typeR multi match: type(left) " ++ op ++ " type(right)" ++ (show exprL) ++ (show exprR) ++ (show a) [typeR] = typeRs assignRL = not . null $ assignConversion db typeR typeL typeLR = case (null $ castConversion db typeL typeR, null $ castConversion db typeR typeL) of (True, True) -> [] (False, _) -> [typeR] (_, False) -> [typeL] typeLR' = map widenType typeLR typeLInt = not . null $ castConversion db typeL TypeInt typeRInt = not . null $ castConversion db typeR TypeInt typeLBool= not . null $ castConversion db typeL TypeBoolean typeRBool = not . null $ castConversion db typeR TypeBoolean equality = equalityCheck db typeL typeR typeLinkingExpr db imps su expr@(ID nm _) = map symbolToType (symbolLinkingExpr db imps su expr) typeLinkingExpr db imps su This = if scopeStatic su then typeLinkingFailure $ "This not accessible from static scope: " ++ (show su) else [lookUpThis su] typeLinkingExpr db imps su (Value tp _ _) = [tp] --ToDO: check if instance of is legit typeLinkingExpr db imps su (InstanceOf tp expr _) = let typeExpr = typeLinkingExpr db imps su expr in if (isPrimitive tp) || (length typeExpr /= 1) || (isPrimitive (head typeExpr)) then typeLinkingFailure "InstanceOf illegal use" else [TypeBoolean] typeLinkingExpr db imps su expr@(FunctionCall exprf args _) = [rt | FUNC _ _ _ _ rt <- (symbolLinkingExpr db imps su expr)] typeLinkingExpr db imps su expr@(Attribute s m _) = map symbolToType (symbolLinkingExpr db imps su expr) -- import rule plays here typeLinkingExpr db imps su expr@(NewObject tp args dp) = [rt | FUNC _ _ _ _ rt <- (symbolLinkingExpr db imps su expr)] typeLinkingExpr db imps su (NewArray tp exprd _) = if (not . null $ typeIdx) && (not . null $ castConversion db (head typeIdx) TypeInt) then if isPrimitive tp then [Array tp] else case [Object (Name nm) | TypeClass (Name nm) <- lookUpDB db imps su (typeToName tp)] of [] -> typeLinkingFailure $ "NewArray: []" ++ (show tp) ++ (show $ lookUpDB db imps su (typeToName tp)) [tp] -> [Array tp] tps' -> typeLinkingFailure (show tps') else typeLinkingFailure "Array: index is not an integer" where typeIdx = case typeLinkingExpr db imps su exprd of [] -> typeLinkingFailure $ "Array Index type []: " ++ (show exprd) [tp] -> [tp] tps -> typeLinkingFailure $ "Array Index multi: " ++ (show exprd) ++ (show tps) typeLinkingExpr db imps su (Dimension _ expr _) = case typeIdx of [tp] -> if elem tp [TypeByte, TypeShort, TypeInt, TypeChar] then [tp] else typeLinkingFailure "Array: index is not an integer" _ -> typeLinkingFailure "Array Index Type typeLinkingFailure" where typeIdx = typeLinkingExpr db imps su expr typeLinkingExpr db imps su (ArrayAccess arr idx _) = case typeArr of [Array tp] -> case typeIdx of [tp'] -> if elem tp' [TypeByte, TypeShort, TypeInt, TypeChar] then [tp] else typeLinkingFailure "Array: index is not an integer" _ -> typeLinkingFailure "Array Index Type typeLinkingFailure" _ -> typeLinkingFailure "Array Type cannot be found" where typeArr = typeLinkingExpr db imps su arr typeIdx = typeLinkingExpr db imps su idx -- to check: allow use array of primitive type to cast typeLinkingExpr db imps su (CastA casttp dim expr _) = case typeExpr of [] -> typeLinkingFailure $ "CastA: cannot type linking the expression " ++ (show expr) [tp] -> if null $ castConversion db tp targetType then typeLinkingFailure $ "CastA: cannot make the cast " ++ (show tp) ++ (show targetType) else [targetType] tps -> typeLinkingFailure $ "CastA: expression have multi types " ++ (show expr) ++ (show tps) where typeExpr = typeLinkingExpr db imps su expr targetType = if dim == Null then casttp else (Array casttp) -- to do: is it possible cast from A to B? typeLinkingExpr db imps su (CastB castexpr expr _) = if null typeCastExpr || null typeExpr || null casting then typeLinkingFailure "CastB: cannot type linking the expression" else typeCastExpr where typeCastExpr = case typeLinkingExpr db imps su castexpr of [] -> typeLinkingFailure $ "CastB CastExpr no match " ++ (show castexpr) [TypeClass tp] -> [Object tp] [tp] -> [tp] tps -> typeLinkingFailure $ "CastB CastExpr multi match " ++ (show castexpr) ++ (show tps) ++ (show db) typeExpr = case typeLinkingExpr db imps su expr of [] -> typeLinkingFailure $ "CastB Expr no match " ++ (show expr) [tp] -> [tp] tps -> typeLinkingFailure $ "CastB Expr multi match " ++ (show expr) ++ (show tps) ++ (show db) casting = case castConversion db (head typeExpr) (head typeCastExpr) of [] -> typeLinkingFailure $ "CastB Casting " ++ (show typeExpr) ++ (show typeCastExpr) tps -> tps -- to check: must be (Name [])? typeLinkingExpr db imps su (CastC castnm _ expr _) = if null tps || null typeExpr || null casting then typeLinkingFailure $ "CastC: cannot type linking the expression" ++ (show expr) ++ (show tps) else [targetType] where tps = case typeLinkingName db imps su castnm of [] -> typeLinkingFailure "CastC no match" [TypeClass tp] -> [Object tp] [tp] -> [tp] tpss -> typeLinkingFailure $ "CastC multi match: " ++ (show tpss) typeExpr = typeLinkingExpr db imps su expr targetType = Array (head tps) -- BUG? casting = castConversion db (head typeExpr) targetType typeLinkingExpr db imps su _ = [TypeVoid] --------------------------------------------------------------------------------------------------------- symbolLinkingExpr :: TypeNode -> [[String]] -> SemanticUnit -> Expression -> [Symbol] symbolLinkingExpr db imps su expr@(Attribute s m _) = case typeLinkingExpr db imps su s of [] -> typeLinkingFailure' ("Attr no match " ++ (show s) ++ (show m)) --should handle Class and instance differently [tp] -> if isPrimitive tp then typeLinkingFailure' $ "Attribute dereference a primitive " ++ (show tp) else let Just tn = getTypeEntry db (typeToName tp) syms = [node | node <- traverseInstanceEntryAccessible db cname db ((typeToName tp)++[m])] syms' = if accessibleType db cname (symbol tn) then syms else [node | node <- syms, not $ elem "protected" ((symbolModifiers . symbol) node)]--typeLinkingFailure' $ "no protected fields " ++ (show flds)-- in case syms' of [] -> typeLinkingFailure' ("Attr no match on member " ++ (show expr) ++ (show ((typeToName tp)++[m]))) --instance look up should not return multiple candidates nodes -> map symbol nodes _ -> typeLinkingFailure' ("Attr multi " ++ (show s) ++ (show m)) where cname = (typeToName . lookUpThis) su symbolLinkingExpr db imps su expr@(FunctionCall exprf args _) = if atsFailed then typeLinkingFailure' $ (show expr) ++ "Function types of Args " ++ (show ats) else case fss' of [] -> typeLinkingFailure' ("Function cannot find " ++ (show $ traverseFieldEntryWithImports db imps ["Arrays", "equals"]) ++ (show exprf) ++ (show fss) ++ (show args)) [fs] -> [fs] _ -> typeLinkingFailure' ("Function find multi " ++ (show exprf) ++ (show args)) where ats = map (typeLinkingExpr db imps su) args atsFailed = or $ map null ats fss = symbolLinkingExpr db imps su exprf fss' = [fs | fs@(FUNC mds ls ln pt rt) <- fss, argsMatching (concat ats) pt] -- import rule plays here symbolLinkingExpr db imps su (NewObject tp args dp) = if atsFailed then typeLinkingFailure' $ "NewObject types of Args " ++ (show ats) else case [TypeClass (Name nm) | TypeClass (Name nm) <- lookUpDB db imps su (typeToName tp)] of [] -> typeLinkingFailure' $ "New Object []: " ++ (show tp) ++ (show args) ++ (show imps) [(TypeClass (Name nm))]-> let Just tn = getTypeEntry db nm cons = [node | node@(TN (FUNC mds ls _ pt _) _) <- subNodes tn, elem "cons" mds, ls == nm, accessibleSymbol db cname (symbol node), argsMatching (concat ats) pt] cons' = if accessibleType db cname (symbol tn) then cons else [node | node <- cons, not $ elem "protected" ((symbolModifiers . symbol) node)]--error $ "using non protect accessible types" ++ (show (symbol tn)) in if elem "abstract" ((symbolModifiers . symbol) tn) then typeLinkingFailure' $ "New Object: cannot create abstract class object" ++ (show nm) else if cons' == [] then typeLinkingFailure' $ "New Object: no matching constructor for " ++ (show ats) ++ (show [node | node@(TN (FUNC mds _ _ pt _) _) <- subNodes tn, elem "cons" mds]) else map symbol cons' tcs -> typeLinkingFailure' $ "New Object multi: " ++ (show tcs) ++ (show tp) ++ (show args) where cname = (typeToName . lookUpThis) su ats = map (typeLinkingExpr db imps su) args atsFailed = or $ map null ats symbolLinkingExpr db imps su (ID nm _) = symbolLinkingName db imps su nm symbolLinkingExpr db imps su expr = error (show expr) --------------------------------------------------------------------------------------------------------- argsMatching :: [Type] -> [Type] -> Bool argsMatching x y | length x /= length y = False | (null x) && (null y) = True | casting == False = False | otherwise = argsMatching (tail x) (tail y) where xHead = head x yHead = head y casting = case (isPrimitive xHead, isPrimitive yHead) of (True, False) -> (boxingType xHead) == yHead (False, True) -> (boxingType yHead) == xHead _ -> xHead == yHead --------------------------------------------------------------------------------------------------------- typeLinkingName :: TypeNode -> [[String]] -> SemanticUnit -> Name -> [Type] typeLinkingName db imps su (Name cname@(nm:remain)) = case typeLinkingName' db imps su (Name cname) of [] -> typeLinkingFailure $ "Link Name failure: " ++ (show cname) tps -> tps typeLinkingName' :: TypeNode -> [[String]] -> SemanticUnit -> Name -> [Type] typeLinkingName' db imps su (Name cname@(nm:remain)) = map symbolToType (symbolLinkingName db imps su (Name cname)) symbolLinkingName :: TypeNode -> [[String]] -> SemanticUnit -> Name -> [Symbol] symbolLinkingName db imps su (Name cname@(nm:remain)) = case syms'' of [] -> case symsInheritance''' of --[] -> if cname == ["Arrays", "equals"] then error (show $ lookUpDBSymbol db imps su cname) else lookUpDBSymbol db imps su cname [] -> lookUpDBSymbol db imps su cname _ -> symsInheritance'' _ -> syms'' where baseName = (typeToName . lookUpThis) su syms = [sym | sym <- lookUpSymbolTable su nm, not $ elem "cons" (symbolModifiers sym)] symsLocal = [sym | sym@(SYM mds scope _ _) <- syms, (scope /= baseName)] symsStatic = symsLocal ++ [sym | sym@(SYM mds scope _ _) <- syms, elem "static" mds] ++ [func | func@(FUNC mds _ _ _ _) <- syms, elem "static" mds, (length cname) > 1] symsNStatic = symsLocal ++ [sym | sym <- syms, not $ elem sym symsStatic] syms' = if scopeStatic su then symsStatic else symsNStatic syms'' = if remain == [] then syms' else map symbol $ concat $ map (traverseInstanceEntryAccessible db baseName db) [((typeToName . localType) sym) ++ remain | sym@(SYM mds _ _ _) <- syms'] Just thisNode = getTypeEntry db baseName symsInheritance = [sym | sym <- map symbol (traverseInstanceEntryAccessible db baseName thisNode [nm]), not $ elem "cons" (symbolModifiers sym)] symsInheritanceStatic = [sym | sym@(SYM mds _ _ _) <- symsInheritance, elem "static" mds] ++ [func | func@(FUNC mds _ _ _ _) <- symsInheritance, elem "static" mds] symsInheritanceNStatic = [sym | sym <- symsInheritance, not $ elem sym symsInheritanceStatic] symsInheritance' = if scopeStatic su then symsInheritanceStatic else symsInheritanceNStatic symsInheritance'' = if remain == [] then symsInheritance' else map symbol $ concat $ map (traverseInstanceEntryAccessible db baseName db) [((typeToName . localType) sym) ++ remain | sym@(SYM mds _ _ _) <- symsInheritance'] symsInheritance''' = if scopeLocal su then symsInheritance'' else [] --------------------------------------------------------------------------------------------------------- lookUpThis :: SemanticUnit -> Type lookUpThis su = if elem (kind su) [Class, Interface] then Object (Name (scope su)) else lookUpThis (inheritFrom su) scopeStatic :: SemanticUnit -> Bool scopeStatic su | elem kd [Package, Interface] = error $ "wrong call to scopeStatic" | (kd == Class) = False | otherwise = rst where kd = kind su rst = case kd of Method (FUNC mds _ _ _ _) -> elem "static" mds Field (SYM mds _ _ _) _ -> elem "static" mds _ -> scopeStatic (inheritFrom su) scopeConstructor :: SemanticUnit -> Bool scopeConstructor su = case kd of Method (FUNC mds _ _ _ _) -> elem "cons" mds _ -> scopeConstructor (inheritFrom su) where kd = kind su scopeLocal :: SemanticUnit -> Bool scopeLocal su | elem kd [Package, Class, Interface] = False | otherwise = rst where kd = kind su rst = case kd of Method (FUNC mds _ _ _ _) -> True _ -> scopeLocal (inheritFrom su) scopeOffsetPos :: SemanticUnit -> Int scopeOffsetPos su = case kd of Method _ -> 0 Var _ -> 1 + scopeOffsetPos (inheritFrom su) _ -> scopeOffsetPos (inheritFrom su) where kd = kind su scopeOffset :: SemanticUnit -> Symbol -> Int scopeOffset su sym = case kd of Method _ -> if syms' /= [] then 0 - (length syms') else error $ "symbol not found on stack: " ++ (show sym) _ -> if syms == [sym] then scopeOffsetPos (inheritFrom su) else scopeOffset (inheritFrom su) sym where kd = kind su syms = symbolTable su syms' = dropWhile (sym /=) syms thisOffset :: SemanticUnit -> Int thisOffset su = case kd of Class -> -1 Method _ -> -1 - (length syms) _ -> thisOffset (inheritFrom su) where kd = kind su syms = symbolTable su scopeReturnType :: SemanticUnit -> Type scopeReturnType su = rst where kd = kind su rst = case kd of Method (FUNC mds _ _ _ lt) -> lt _ -> scopeReturnType (inheritFrom su) lookUpSymbolTable :: SemanticUnit -> String -> [Symbol] lookUpSymbolTable (Root _) str = [] lookUpSymbolTable su nm = case cur of [] -> lookUpSymbolTable parent nm _ -> cur where (SU _ _ st parent) = su cur = filter (\s -> (localName s) == nm) st lookUpDB :: TypeNode -> [[String]] -> SemanticUnit -> [String] -> [Type] lookUpDB db imps su cname = map symbolToType (lookUpDBSymbol db imps su cname) lookUpDBSymbol :: TypeNode -> [[String]] -> SemanticUnit -> [String] -> [Symbol] lookUpDBSymbol db imps su cname | or $ map (\(pre, post) -> traverseTypeEntryWithImports db imps pre /= []) ps'' = [] -- prefix of a type is resolved to a type | length tps' > 0 = tps' | otherwise = (map symbol $ nub tps) where baseName = (typeToName . lookUpThis) su ps = map (\i -> (take i cname, drop i cname)) [1..(length cname)] ps' = reverse $ takeWhile (\(pre, post) -> traverseTypeEntryWithImports db imps pre == []) (reverse ps) ps'' = reverse $ drop 1 $ dropWhile (\(pre, post) -> traverseTypeEntryWithImports db imps pre == []) (reverse ps) tps = concat $ map (\(pre, post) -> concat $ map (\tn -> traverseInstanceEntryAccessible db baseName tn post) (traverseFieldEntryWithImports db imps pre)) ps' tps' = map (\nm -> symbol $ fromJust $ getTypeEntry db nm) (lookUpType db imps cname) ------------------------------------------------------------------------------------ checkSameNameInEnvironment :: Environment -> Bool checkSameNameInEnvironment ENVE = False checkSameNameInEnvironment (ENV su [ENVE]) = checkSameNameUp su [] checkSameNameInEnvironment (ENV su []) = checkSameNameUp su [] checkSameNameInEnvironment (ENV su chs) = or $ map checkSameNameInEnvironment chs checkSameNameUp :: SemanticUnit -> [Symbol] -> Bool checkSameNameUp (Root _) accst = checkSameNameInSymbolTable accst checkSameNameUp su@(SU _ kd st parent) accst = case kd of Method _ -> res || checkSameNameUp parent [] Interface -> res || checkSameNameUp parent [] Class -> res || checkSameNameUp parent [] _ -> checkSameNameUp parent nextst where nextst = accst ++ st res = functionCheck || checkSameNameInSymbolTable nextst functionCheck = length cons /= (length . nub) cons || length funcs /= (length . nub) funcs cons = [(ln, pt) | f@(FUNC mds _ ln pt lt) <- st, elem "cons" mds] funcs = [(ln, pt) | f@(FUNC mds _ ln pt lt) <- st, not $ elem "cons" mds] checkSameNameInSymbolTable :: [Symbol] -> Bool checkSameNameInSymbolTable st = length nms /= (length . nub) nms where syms = [SYM mds ls nm tp | SYM mds ls nm tp <- st] nms = map localName syms ------------------------------------------------------------------------------ forwardSYMInExpr :: String -> Expression -> Bool forwardSYMInExpr nm (Unary op expr _) = forwardSYMInExpr nm expr forwardSYMInExpr nm expr@(Binary op exprL exprR _) | elem op ["="] = case exprL of ID exprL' _ -> forwardSYMInExpr nm exprR _ -> or [forwardSYMInExpr nm exprL, forwardSYMInExpr nm exprR] | otherwise = or [forwardSYMInExpr nm exprL, forwardSYMInExpr nm exprR] forwardSYMInExpr nm (ID (Name cname) _) = nm == head cname forwardSYMInExpr nm This = False forwardSYMInExpr nm (Value tp _ _) = False forwardSYMInExpr nm (InstanceOf tp expr _) = forwardSYMInExpr nm expr forwardSYMInExpr nm (FunctionCall exprf args _) = or ((forwardSYMInExpr nm exprf):(map (forwardSYMInExpr nm) args)) forwardSYMInExpr nm expr@(Attribute s m _) = forwardSYMInExpr nm s forwardSYMInExpr nm (NewObject tp args dp) = or (map (forwardSYMInExpr nm) args) forwardSYMInExpr nm (NewArray tp expr _) = forwardSYMInExpr nm expr forwardSYMInExpr nm (Dimension _ exprd _) = forwardSYMInExpr nm exprd forwardSYMInExpr nm (ArrayAccess arr idx _) = or [forwardSYMInExpr nm arr, forwardSYMInExpr nm idx] forwardSYMInExpr nm (CastA casttp dim expr _) = forwardSYMInExpr nm expr forwardSYMInExpr nm (CastB castexpr expr _) = forwardSYMInExpr nm expr forwardSYMInExpr nm (CastC castnm _ expr _) = forwardSYMInExpr nm expr forwardSYMInExpr nm _ = False finalArrayLength :: TypeNode -> [[String]] -> SemanticUnit -> Expression -> Bool finalArrayLength db imps su (Attribute s m _) = case (typeS, m) of (Array _, "length") -> False _ -> True where [typeS] = typeLinkingExpr db imps su s finalArrayLength db imps su (ID (Name nm) _) = if (length nm == 1) then True else case (last nm, tp) of ("length", Array _) -> False _ -> True where [tp] = typeLinkingName db imps su (Name (init nm)) finalArrayLength _ _ _ _ = True
yangsiwei880813/CS644
src/TypeLinking.hs
gpl-2.0
31,614
0
24
11,696
9,230
4,732
4,498
371
50
-- Copyright (C) 2014-2016 Sebastian Wiesner <[email protected]> -- Copyright (C) 2016 Danny Navarro -- Copyright (C) 2015 Mark Karpov <[email protected]> -- Copyright (C) 2015 Michael Alan Dorman <[email protected]> -- Copyright (C) 2014 Gracjan Polak <[email protected]> -- This file is not part of GNU Emacs. -- 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 3 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, see <http://www.gnu.org/licenses/>. {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeSynonymInstances #-} module Main (main) where #if __GLASGOW_HASKELL__ >= 800 #define Cabal2 MIN_VERSION_Cabal(2,0,0) #else -- Hack - we may actually be using Cabal 2.0 with e.g. 7.8 GHC. But -- that's not likely to occur for average user who's relying on -- packages bundled with GHC. The 2.0 Cabal is bundled starting with 8.2.1. #define Cabal2 0 #endif import qualified Control.Applicative as A import Control.Exception (SomeException, try) import Data.Char (isSpace) import Data.List (isPrefixOf, nub) import Data.Maybe (listToMaybe) import Data.Set (Set) import qualified Data.Set as S #ifdef USE_COMPILER_ID import Distribution.Compiler (CompilerFlavor(GHC), CompilerId(CompilerId), buildCompilerFlavor) #else import Distribution.Compiler (AbiTag(NoAbiTag), CompilerFlavor(GHC), CompilerId(CompilerId), CompilerInfo, buildCompilerFlavor, unknownCompilerInfo) #endif import Distribution.Package (pkgName, Dependency(..)) import Distribution.PackageDescription (GenericPackageDescription, PackageDescription(..), allBuildInfo, BuildInfo(..), usedExtensions, allLanguages, hcOptions, exeName, Executable) import Distribution.Simple.BuildPaths (defaultDistPref) import Distribution.Simple.Utils (cabalVersion) import Distribution.System (buildPlatform) import Distribution.Text (display) import Distribution.Verbosity (silent) import Language.Haskell.Extension (Extension(..),Language(..)) import System.Environment (getArgs) import System.Exit (ExitCode(..), exitFailure) import System.FilePath ((</>),dropFileName,normalise) import System.Info (compilerVersion) import System.Process (readProcessWithExitCode) #if __GLASGOW_HASKELL__ >= 710 && !Cabal2 import Data.Version (Version) #endif #if Cabal2 import Distribution.Package (unPackageName, depPkgName, PackageName) import Distribution.PackageDescription.Configuration (finalizePD) import Distribution.Types.ComponentRequestedSpec (ComponentRequestedSpec(..)) import Distribution.PackageDescription.Parse (readGenericPackageDescription) import Distribution.Types.UnqualComponentName (unUnqualComponentName) import qualified Distribution.Version as CabalVersion #else import Control.Arrow (second) import Data.Version (showVersion) import Distribution.Package (PackageName(..)) import Distribution.PackageDescription (TestSuite, Benchmark, condTestSuites, condBenchmarks, benchmarkEnabled, testEnabled) import Distribution.PackageDescription.Configuration (finalizePackageDescription, mapTreeData) import Distribution.PackageDescription.Parse (readPackageDescription) #endif data Sexp = SList [Sexp] | SString String | SSymbol String data TargetTool = Cabal | Stack sym :: String -> Sexp sym = SSymbol instance Show Sexp where show (SSymbol s) = s show (SString s) = show s -- Poor man's escaping show (SList s) = "(" ++ unwords (map show s) ++ ")" class ToSexp a where toSexp :: a -> Sexp instance ToSexp String where toSexp = SString instance ToSexp Extension where toSexp (EnableExtension ext) = toSexp (show ext) toSexp (DisableExtension ext) = toSexp ("No" ++ show ext) toSexp (UnknownExtension ext) = toSexp ext instance ToSexp Language where toSexp (UnknownLanguage lang) = toSexp lang toSexp lang = toSexp (show lang) instance ToSexp Dependency where #if Cabal2 toSexp = toSexp . unPackageName . depPkgName #else toSexp (Dependency (PackageName dependency) _) = toSexp dependency #endif instance ToSexp Sexp where toSexp = id cons :: (ToSexp a, ToSexp b) => a -> [b] -> Sexp cons h t = SList (toSexp h : map toSexp t) -- | Get possible dist directory distDir :: TargetTool -> IO FilePath distDir Cabal = return defaultDistPref distDir Stack = do res <- try $ readProcessWithExitCode "stack" ["path", "--dist-dir"] [] return $ case res of Left (_ :: SomeException) -> defaultDistDir Right (ExitSuccess, stdOut, _) -> stripWhitespace stdOut Right (ExitFailure _, _, _) -> defaultDistDir where defaultDistDir :: FilePath defaultDistDir = ".stack-work" </> defaultDistPref </> display buildPlatform </> "Cabal-" ++ cabalVersion' getBuildDirectories :: TargetTool -> PackageDescription -> FilePath -> IO ([FilePath], FilePath) getBuildDirectories tool pkgDesc cabalDir = do distDir' <- distDir tool let buildDir :: FilePath buildDir = cabalDir </> distDir' </> "build" autogenDir :: FilePath autogenDir = buildDir </> "autogen" executableBuildDir :: Executable -> FilePath executableBuildDir e = buildDir </> getExeName e </> (getExeName e ++ "-tmp") buildDirs :: [FilePath] buildDirs = autogenDir : map executableBuildDir (executables pkgDesc) buildDirs' = case library pkgDesc of Just _ -> buildDir : buildDirs Nothing -> buildDirs return (buildDirs', autogenDir) getSourceDirectories :: [BuildInfo] -> FilePath -> [String] getSourceDirectories buildInfo cabalDir = map (cabalDir </>) (concatMap hsSourceDirs buildInfo) allowedOptions :: Set String allowedOptions = S.fromList [ "-W" , "-w" , "-Wall" , "-fglasgow-exts" , "-fpackage-trust" , "-fhelpful-errors" , "-F" , "-cpp"] allowedOptionPrefixes :: [String] allowedOptionPrefixes = [ "-fwarn-" , "-fno-warn-" , "-fcontext-stack=" , "-firrefutable-tuples" , "-D" , "-U" , "-I" , "-fplugin=" , "-fplugin-opt=" , "-pgm" , "-opt"] isAllowedOption :: String -> Bool isAllowedOption opt = S.member opt allowedOptions || any (`isPrefixOf` opt) allowedOptionPrefixes dumpPackageDescription :: PackageDescription -> FilePath -> IO Sexp dumpPackageDescription pkgDesc cabalFile = do (cabalDirs, autogenDir) <- getBuildDirectories Cabal pkgDesc cabalDir (stackDirs, autogenDir') <- getBuildDirectories Stack pkgDesc cabalDir let buildDirs = cabalDirs ++ stackDirs autogenDirs = [autogenDir, autogenDir'] return $ SList [ cons (sym "build-directories") (ordNub (map normalise buildDirs)) , cons (sym "source-directories") sourceDirs , cons (sym "extensions") exts , cons (sym "languages") langs , cons (sym "dependencies") deps , cons (sym "other-options") (cppOpts ++ ghcOpts) , cons (sym "autogen-directories") (map normalise autogenDirs) ] where cabalDir :: FilePath cabalDir = dropFileName cabalFile buildInfo :: [BuildInfo] buildInfo = allBuildInfo pkgDesc sourceDirs :: [FilePath] sourceDirs = ordNub (map normalise (getSourceDirectories buildInfo cabalDir)) exts :: [Extension] exts = nub (concatMap usedExtensions buildInfo) langs :: [Language] langs = nub (concatMap allLanguages buildInfo) thisPackage :: PackageName thisPackage = pkgName (package pkgDesc) deps :: [Dependency] deps = nub (filter (\(Dependency name _) -> name /= thisPackage) (buildDepends pkgDesc)) -- The "cpp-options" configuration field. cppOpts :: [String] cppOpts = ordNub (filter isAllowedOption (concatMap cppOptions buildInfo)) -- The "ghc-options" configuration field. ghcOpts :: [String] ghcOpts = ordNub (filter isAllowedOption (concatMap (hcOptions GHC) buildInfo)) dumpCabalConfiguration :: FilePath -> IO () dumpCabalConfiguration cabalFile = do genericDesc <- #if Cabal2 readGenericPackageDescription silent cabalFile #else readPackageDescription silent cabalFile #endif case getConcretePackageDescription genericDesc of Left e -> putStrLn $ "Issue with package configuration\n" ++ show e Right pkgDesc -> print =<< dumpPackageDescription pkgDesc cabalFile getConcretePackageDescription :: GenericPackageDescription -> Either [Dependency] PackageDescription getConcretePackageDescription genericDesc = do #if Cabal2 let enabled :: ComponentRequestedSpec enabled = ComponentRequestedSpec { testsRequested = True , benchmarksRequested = True } fst A.<$> finalizePD [] -- Flag assignment enabled -- Enable all components (const True) -- Whether given dependency is available buildPlatform buildCompilerId [] -- Additional constraints genericDesc #else -- This let block is eerily like one in Cabal.Distribution.Simple.Configure let enableTest :: TestSuite -> TestSuite enableTest t = t { testEnabled = True } enableBenchmark :: Benchmark -> Benchmark enableBenchmark bm = bm { benchmarkEnabled = True } flaggedTests = map (second (mapTreeData enableTest)) (condTestSuites genericDesc) flaggedBenchmarks = map (second (mapTreeData enableBenchmark)) (condBenchmarks genericDesc) genericDesc' = genericDesc { condTestSuites = flaggedTests , condBenchmarks = flaggedBenchmarks } fst A.<$> finalizePackageDescription [] (const True) buildPlatform buildCompilerId [] genericDesc' #endif #ifdef USE_COMPILER_ID buildCompilerId :: CompilerId buildCompilerId = CompilerId buildCompilerFlavor compilerVersion #else buildCompilerId :: CompilerInfo buildCompilerId = unknownCompilerInfo compId NoAbiTag where compId :: CompilerId compId = CompilerId buildCompilerFlavor compVersion # if Cabal2 compVersion :: CabalVersion.Version compVersion = CabalVersion.mkVersion' compilerVersion # else compVersion :: Version compVersion = compilerVersion # endif #endif getExeName :: Executable -> FilePath getExeName = #if Cabal2 unUnqualComponentName . exeName #else exeName #endif -- Textual representation of cabal version cabalVersion' :: String cabalVersion' = #if Cabal2 CabalVersion.showVersion cabalVersion #else showVersion cabalVersion #endif ordNub :: forall a. Ord a => [a] -> [a] ordNub = go S.empty where go :: Set a -> [a] -> [a] go _ [] = [] go acc (x:xs) | S.member x acc = go acc xs | otherwise = x : go (S.insert x acc) xs stripWhitespace :: String -> String stripWhitespace = reverse . dropWhile isSpace . reverse . dropWhile isSpace main :: IO () main = do args <- getArgs let cabalFile = listToMaybe args maybe exitFailure dumpCabalConfiguration cabalFile
mrkkrp/flycheck-haskell
get-cabal-configuration.hs
gpl-3.0
11,782
0
14
2,571
2,237
1,230
1,007
225
3
module Data.Heap ( Heap, singleton, pop, fromList, toList ) where import Data.Monoid (Monoid(..),(<>)) data Heap p a = Empty | Heap p a (Heap p a) (Heap p a) instance (Ord p) => Monoid (Heap p a) where mempty = Empty mappend heap1@(Heap p1 a1 l1 r1) heap2@(Heap p2 a2 l2 r2) | p1 <= p2 = Heap p1 a1 (heap2 <> r1) l1 | otherwise = Heap p2 a2 (heap1 <> r2) l2 mappend heap Empty = heap mappend Empty heap = heap instance (Show p, Ord p, Show a) => Show (Heap p a) where show h = "fromList " ++ show (toList h) instance Functor (Heap p) where fmap _ Empty = Empty fmap f (Heap p a l r) = Heap p (f a) (fmap f l) (fmap f r) singleton :: p -> a -> Heap p a singleton p a = Heap p a Empty Empty pop :: (Ord p) => Heap p a -> Maybe (p,a,Heap p a) pop Empty = Nothing pop (Heap p a l r) = Just (p,a,l <> r) fromList :: (Ord p) => [(p,a)] -> Heap p a fromList = tf . map (uncurry singleton) where tf [] = Empty tf [x] = x tf l = tf (mp l) mp [] = [] mp [x] = [x] mp (a:b:r) = (a <> b) : mp r toList heap = case pop heap of Nothing -> [] Just (p,a,h) -> (p,a) : toList h
quickdudley/sokosolve
Data/Heap.hs
gpl-3.0
1,120
0
10
305
678
354
324
36
5
module Integration where -- https://stepic.org/lesson/%D0%9B%D0%BE%D0%BA%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%B5-%D1%81%D0%B2%D1%8F%D0%B7%D1%8B%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-%D0%B8-%D0%BF%D1%80%D0%B0%D0%B2%D0%B8%D0%BB%D0%B0-%D0%BE%D1%82%D1%81%D1%82%D1%83%D0%BF%D0%BE%D0%B2-8414/step/9?unit=1553 integration :: (Double -> Double) -> Double -> Double -> Double integration f a b = let h = (b - a) / 1000 aHalf = h / 2 y x s i | a == 0 && b == 0 = 0 | i == 0 = y (a + h) (s + f a) (i + 1) | i == 1000 = s + (f b) | otherwise = y (x + h) (s + 2 * f x) (i + 1) in aHalf * (y a 0 0)
devtype-blogspot-com/Haskell-Examples
Integration/Integration.hs
gpl-3.0
637
0
14
160
227
115
112
11
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE StandaloneDeriving #-} -- Tests.hs -- Copyright 2015 Remy E. Goldschmidt <[email protected]> -- This file is part of wai-middleware-preprocessor. -- wai-middleware-preprocessor 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 3 of the License, or -- (at your option) any later version. -- -- wai-middleware-preprocessor 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 wai-middleware-preprocessor. If not, see <http://www.gnu.org/licenses/>. module Network.Wai.Middleware.Preprocessor.Tests where import Distribution.TestSuite import Network.Wai.Middleware.Preprocessor import Test.QuickCheck tests :: IO [Test] tests = return []
taktoa/wai-middleware-preprocessor
test/Network/Wai/Middleware/Preprocessor/Tests.hs
gpl-3.0
1,173
0
6
219
65
47
18
9
1
{-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE NoMonoPatBinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE DataKinds #-} ----------------------------------------------------------------------------- -- | -- Module : Hoodle.Type.PageArrangement -- Copyright : (c) 2012, 2013 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <[email protected]> -- Stability : experimental -- Portability : GHC -- ----------------------------------------------------------------------------- module Hoodle.Type.PageArrangement where -- from other packages import Control.Applicative import Control.Lens (Simple,Lens,view,lens) import Data.Foldable (toList) -- from hoodle-platform import Data.Hoodle.Simple (Dimension(..)) import Data.Hoodle.Generic import Data.Hoodle.BBox -- from this package import Hoodle.Type.Predefined import Hoodle.Type.Alias import Hoodle.Util -- -- | supported zoom modes data ZoomMode = Original | FitWidth | FitHeight | Zoom Double deriving (Show,Eq) -- | supported view modes data ViewMode = SinglePage | ContinuousPage -- | newtype PageNum = PageNum { unPageNum :: Int } deriving (Eq,Show,Ord,Num) -- | newtype ScreenCoordinate = ScrCoord { unScrCoord :: (Double,Double) } deriving (Show) -- | newtype CanvasCoordinate = CvsCoord { unCvsCoord :: (Double,Double) } deriving (Show) -- | newtype DesktopCoordinate = DeskCoord { unDeskCoord :: (Double,Double) } deriving (Show) -- | newtype PageCoordinate = PageCoord { unPageCoord :: (Double,Double) } deriving (Show) -- | newtype ScreenDimension = ScreenDimension { unScreenDimension :: Dimension } deriving (Show) -- | newtype CanvasDimension = CanvasDimension { unCanvasDimension :: Dimension } deriving (Show) -- | newtype CanvasOrigin = CanvasOrigin { unCanvasOrigin :: (Double,Double) } deriving (Show) -- | newtype PageOrigin = PageOrigin { unPageOrigin :: (Double,Double) } deriving (Show) -- | newtype PageDimension = PageDimension { unPageDimension :: Dimension } deriving (Show) -- | newtype DesktopDimension = DesktopDimension { unDesktopDimension :: Dimension } deriving (Show) -- | newtype ViewPortBBox = ViewPortBBox { unViewPortBBox :: BBox } deriving (Show) -- | apply :: (BBox -> BBox) -> ViewPortBBox -> ViewPortBBox apply f (ViewPortBBox bbox1) = ViewPortBBox (f bbox1) {-# INLINE apply #-} -- | xformViewPortFitInSize :: Dimension -> (BBox -> BBox) -> ViewPortBBox -> ViewPortBBox xformViewPortFitInSize (Dim w h) f (ViewPortBBox bbx) = let BBox (x1,y1) (x2,y2) = f bbx xmargin = if 0.5*((x2-x1)-w) > 0 then 0.5*((x2-x1)-w) else 0 ymargin = if 0.5*((y2-y1)-h) > 0 then 0.5*((y2-y1)-h) else 0 (x1',x2') | x2>w && w-(x2-x1)>0 = (w-(x2-x1),w) | x2>w && w-(x2-x1)<=0 = (-xmargin,-xmargin+x2-x1) | x1< (-xmargin) = (-xmargin,-xmargin+x2-x1) | otherwise = (x1,x2) (y1',y2') | y2>h && h-(y2-y1)>0 = (h-(y2-y1),h) | y2>h && h-(y2-y1)<=0 = (-ymargin,-ymargin+y2-y1) | y1 < (-ymargin) = (-ymargin,-ymargin+y2-y1) | otherwise = (y1,y2) in ViewPortBBox (BBox (x1',y1') (x2',y2') ) -- | data structure for coordinate arrangement of pages in desktop coordinate data PageArrangement (a :: ViewMode) where SingleArrangement :: CanvasDimension -> PageDimension -> ViewPortBBox -> PageArrangement SinglePage ContinuousArrangement :: CanvasDimension -> DesktopDimension -> (PageNum -> Maybe (PageOrigin,PageDimension)) -> ViewPortBBox -> PageArrangement ContinuousPage -- | getRatioPageCanvas :: ZoomMode -> PageDimension -> CanvasDimension -> (Double,Double) getRatioPageCanvas zmode (PageDimension (Dim w h)) (CanvasDimension (Dim w' h')) = case zmode of Original -> (1.0,1.0) FitWidth -> (w'/w,w'/w) FitHeight -> (h'/h,h'/h) Zoom s -> (s,s) -- | makeSingleArrangement :: ZoomMode -> PageDimension -> CanvasDimension -> (Double,Double) -> PageArrangement SinglePage makeSingleArrangement zmode pdim cdim@(CanvasDimension (Dim w' h')) (x,y) = let (sinvx,sinvy) = getRatioPageCanvas zmode pdim cdim bbox = BBox (x,y) (x+w'/sinvx,y+h'/sinvy) in SingleArrangement cdim pdim (ViewPortBBox bbox) -- | data DesktopConstraint = DesktopWidthConstrained Double -- | makeContinuousArrangement :: ZoomMode -> CanvasDimension -> Hoodle EditMode -> (PageNum,PageCoordinate) -> PageArrangement ContinuousPage makeContinuousArrangement zmode cdim@(CanvasDimension (Dim cw ch)) hdl (pnum,PageCoord (xpos,ypos)) = let dim = view gdimension . head . toList . view gpages $ hdl (sinvx,sinvy) = getRatioPageCanvas zmode (PageDimension dim) cdim cnstrnt = DesktopWidthConstrained (cw/sinvx) -- default to zero if error (PageOrigin (x0,y0),_) = maybe (PageOrigin (0,0),PageDimension (Dim cw ch)) id (pageArrFuncCont cnstrnt hdl pnum) ddim@(DesktopDimension iddim) = deskDimCont cnstrnt hdl (x1,y1) = (xpos+x0,ypos+y0) (x2,y2) = (xpos+x0+cw/sinvx,ypos+y0+ch/sinvy) ovport =ViewPortBBox (BBox (x1,y1) (x2,y2)) vport = xformViewPortFitInSize iddim id ovport in ContinuousArrangement cdim ddim (pageArrFuncCont cnstrnt hdl) vport -- | pageArrFuncCont :: DesktopConstraint -> Hoodle EditMode -> PageNum -> Maybe (PageOrigin,PageDimension) pageArrFuncCont (DesktopWidthConstrained w') hdl (PageNum n) | n < 0 = Nothing | n >= len = Nothing | otherwise = Just (PageOrigin (xys !! n), PageDimension (pdims !! n)) where addf (x,y) (w,h) = if x+2*w+predefinedPageSpacing < w' then (x+w+predefinedPageSpacing,y) else (0,y+h+predefinedPageSpacing) pgs = toList . view gpages $ hdl len = length pgs pdims = map (view gdimension) pgs wh2xyFrmPg = ((,) <$> dim_width <*> dim_height) . view gdimension xys = scanl addf (0,0) . map wh2xyFrmPg $ pgs -- | deskDimCont :: DesktopConstraint -> Hoodle EditMode -> DesktopDimension deskDimCont cnstrnt hdl = let pgs = toList . view gpages $ hdl len = length pgs olst = maybeError' "deskDimCont" $ mapM (pageArrFuncCont cnstrnt hdl . PageNum) [0..len-1] f (PageOrigin (x,y),PageDimension (Dim w h)) (Dim w' h') = let w'' = if w' < x+w then x+w else w' h'' = if h' < y+h then y+h else h' in Dim w'' h'' in DesktopDimension $ foldr f (Dim 0 0) olst ------------ -- lenses ------------ -- | pageDimension :: Simple Lens (PageArrangement SinglePage) PageDimension pageDimension = lens getter setter where getter (SingleArrangement _ pdim _) = pdim getter (ContinuousArrangement _ _ _ _) = error $ "in pageDimension " -- partial setter (SingleArrangement cdim _ vbbox) pdim = SingleArrangement cdim pdim vbbox setter (ContinuousArrangement _ _ _ _) _pdim = error $ "in pageDimension " -- partial -- | canvasDimension :: Simple Lens (PageArrangement a) CanvasDimension canvasDimension = lens getter setter where getter :: PageArrangement a -> CanvasDimension getter (SingleArrangement cdim _ _) = cdim getter (ContinuousArrangement cdim _ _ _) = cdim setter :: PageArrangement a -> CanvasDimension -> PageArrangement a setter (SingleArrangement _ pdim vbbox) cdim = SingleArrangement cdim pdim vbbox setter (ContinuousArrangement _ ddim pfunc vbbox) cdim = ContinuousArrangement cdim ddim pfunc vbbox -- | viewPortBBox :: Simple Lens (PageArrangement a) ViewPortBBox viewPortBBox = lens getter setter where getter :: PageArrangement a -> ViewPortBBox getter (SingleArrangement _ _ vbbox) = vbbox getter (ContinuousArrangement _ _ _ vbbox) = vbbox setter :: PageArrangement a -> ViewPortBBox -> PageArrangement a setter (SingleArrangement cdim pdim _) vbbox = SingleArrangement cdim pdim vbbox setter (ContinuousArrangement cdim ddim pfunc _) vbbox = ContinuousArrangement cdim ddim pfunc vbbox -- | desktopDimension :: Simple Lens (PageArrangement a) DesktopDimension desktopDimension = lens getter (error "setter for desktopDimension is not defined") where getter :: PageArrangement a -> DesktopDimension getter (SingleArrangement _ (PageDimension dim) _) = DesktopDimension dim getter (ContinuousArrangement _ ddim _ _) = ddim
wavewave/hoodle-core
src/Hoodle/Type/PageArrangement.hs
gpl-3.0
9,861
0
15
3,126
2,795
1,527
1,268
164
4
{- GPLV3.0 or later copyright brmlab.cz contact [email protected] Also copyright cheater http://cheater.posterous.com/haskell-curses Copyright 2012. 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 3 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, see <http://www.gnu.org/licenses/>. This is a simple library for displaying a menu in a terminal. It's main function is displayMenu which takes a list of strings and presents them as options to the user, and returns the string that the user selects... This code was written by cheater__ and published here: http://cheater.posterous.com/haskell-curses 18:53 < cheater_> hi timthelion 18:54 < timthelion> cheater_: hi! 18:54 < timthelion> cheater_: Did you get my message? 18:54 < cheater_> i think so 18:54 < cheater_> you had some code you wanted to use right? 18:54 < timthelion> Yes. 18:54 < cheater_> what license do you want to release it under? 18:55 < timthelion> GPL 3.0. 18:55 < cheater_> ok, that's fine with me 18:55 < timthelion> thank you :) -} module Graphics.Vty.Menu(displayMenu,displayMenuOfValues) where import qualified Graphics.Vty as Vty import Graphics.Vty.Input import Graphics.Vty.Output import Graphics.Vty.Config getName :: String -> String getName item = item -- returns the name of a item. -- This will become more complicated some day. itemImage :: String -> Bool -> Vty.Image itemImage item cursor = do -- prints out info on an item let wfc = Vty.withForeColor wbc = Vty.withBackColor (indicator, useColor) = if cursor then (" > ", True) else (" ", False) attr = if useColor then Vty.currentAttr `wfc` Vty.black `wbc` Vty.white else Vty.currentAttr `wfc` Vty.white `wbc` Vty.black Vty.string attr $ indicator ++ (getName item) allocate :: IO Vty.Vty allocate = do -- sets up Vty vt <- standardIOConfig >>= Vty.mkVty return vt deallocate :: Vty.Vty -> IO () deallocate vt = -- frees Vty resouces Vty.shutdown vt handleKeyboard :: Vty.Key -> Int -> Int -> [String] -> Vty.Vty -> IO (Vty.Vty,Maybe Int) handleKeyboard key position offset items vt = case key of -- handles keyboard input KChar 'q' -> return (vt,Nothing) KEsc -> return (vt,Nothing) KEnter -> return (vt,Just position) KChar 'j' -> work (position + 1) offset items vt KDown -> work (position + 1) offset items vt KChar 'k' -> work (position - 1) offset items vt KUp -> work (position - 1) offset items vt KPageUp -> do bounds <- Vty.displayBounds $ Vty.outputIface vt work (position - (Vty.regionHeight bounds)) offset items vt KPageDown -> do bounds <- Vty.displayBounds $ Vty.outputIface vt work (position + (Vty.regionHeight bounds)) offset items vt KHome -> work 0 offset items vt KEnd -> work (length items - 1) offset items vt _ -> work position offset items vt work :: Int -> Int -> [String] -> Vty.Vty -> IO (Vty.Vty,Maybe Int) work requestedPosition offset items vt = do -- displays items let position = max 0 (min requestedPosition (length items - 1)) (cols, rows) <- Vty.displayBounds $ Vty.outputIface vt let (cols2, rows2) = (fromEnum cols, fromEnum rows) screenPosition = position + offset offset2 = if screenPosition >= rows2 then offset - (screenPosition - rows2 + 1) else if screenPosition < 0 then offset - screenPosition else offset items2 = drop (0 - offset2) $ zip [0..] items itemImages = map (\(line, item) -> itemImage item (line == position)) items2 imagesUnified = Vty.vertCat itemImages pic = Vty.picForImage $ imagesUnified Vty.update vt pic eventLoop position offset2 items vt eventLoop :: Int -> Int -> [String] -> Vty.Vty -> IO (Vty.Vty, Maybe Int) eventLoop position offset items vt = do ev <- Vty.nextEvent vt case ev of Vty.EvKey key _ -> handleKeyboard key position offset items vt _ -> eventLoop position offset items vt displayMenu :: [String] -> IO (Maybe String) displayMenu items = do displayMenuOfValues $ zip items items displayMenuOfValues :: [(String,a)] -> IO (Maybe a) displayMenuOfValues items = do vty <- allocate (vty',maybePos) <- work 0 0 (map fst items) vty deallocate vty' case maybePos of Just pos -> return $ Just $ snd $ items !! pos Nothing -> return Nothing --main = do -- choice <- displayMenu ["Hi","Bye","The other thing."] -- print choice -- the main program
timthelion/vty-menu
Graphics/Vty/Menu.hs
gpl-3.0
4,975
0
15
1,085
1,220
628
592
85
12
{-# 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.Tasks.TaskLists.Update -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates the authenticated user\'s specified task list. -- -- /See:/ <https://developers.google.com/google-apps/tasks/firstapp Tasks API Reference> for @tasks.tasklists.update@. module Network.Google.Resource.Tasks.TaskLists.Update ( -- * REST Resource TaskListsUpdateResource -- * Creating a Request , taskListsUpdate , TaskListsUpdate -- * Request Lenses , tluPayload , tluTaskList ) where import Network.Google.AppsTasks.Types import Network.Google.Prelude -- | A resource alias for @tasks.tasklists.update@ method which the -- 'TaskListsUpdate' request conforms to. type TaskListsUpdateResource = "tasks" :> "v1" :> "users" :> "@me" :> "lists" :> Capture "tasklist" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] TaskList :> Put '[JSON] TaskList -- | Updates the authenticated user\'s specified task list. -- -- /See:/ 'taskListsUpdate' smart constructor. data TaskListsUpdate = TaskListsUpdate' { _tluPayload :: !TaskList , _tluTaskList :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TaskListsUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tluPayload' -- -- * 'tluTaskList' taskListsUpdate :: TaskList -- ^ 'tluPayload' -> Text -- ^ 'tluTaskList' -> TaskListsUpdate taskListsUpdate pTluPayload_ pTluTaskList_ = TaskListsUpdate' { _tluPayload = pTluPayload_ , _tluTaskList = pTluTaskList_ } -- | Multipart request metadata. tluPayload :: Lens' TaskListsUpdate TaskList tluPayload = lens _tluPayload (\ s a -> s{_tluPayload = a}) -- | Task list identifier. tluTaskList :: Lens' TaskListsUpdate Text tluTaskList = lens _tluTaskList (\ s a -> s{_tluTaskList = a}) instance GoogleRequest TaskListsUpdate where type Rs TaskListsUpdate = TaskList type Scopes TaskListsUpdate = '["https://www.googleapis.com/auth/tasks"] requestClient TaskListsUpdate'{..} = go _tluTaskList (Just AltJSON) _tluPayload appsTasksService where go = buildClient (Proxy :: Proxy TaskListsUpdateResource) mempty
rueshyna/gogol
gogol-apps-tasks/gen/Network/Google/Resource/Tasks/TaskLists/Update.hs
mpl-2.0
3,131
0
15
746
390
234
156
63
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.FireStore.Projects.Databases.Documents.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists documents. -- -- /See:/ <https://cloud.google.com/firestore Cloud Firestore API Reference> for @firestore.projects.databases.documents.list@. module Network.Google.Resource.FireStore.Projects.Databases.Documents.List ( -- * REST Resource ProjectsDatabasesDocumentsListResource -- * Creating a Request , projectsDatabasesDocumentsList , ProjectsDatabasesDocumentsList -- * Request Lenses , pParent , pXgafv , pReadTime , pUploadProtocol , pOrderBy , pAccessToken , pCollectionId , pUploadType , pTransaction , pShowMissing , pPageToken , pPageSize , pMaskFieldPaths , pCallback ) where import Network.Google.FireStore.Types import Network.Google.Prelude -- | A resource alias for @firestore.projects.databases.documents.list@ method which the -- 'ProjectsDatabasesDocumentsList' request conforms to. type ProjectsDatabasesDocumentsListResource = "v1" :> Capture "parent" Text :> Capture "collectionId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "readTime" DateTime' :> QueryParam "upload_protocol" Text :> QueryParam "orderBy" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "transaction" Bytes :> QueryParam "showMissing" Bool :> QueryParam "pageToken" Text :> QueryParam "pageSize" (Textual Int32) :> QueryParams "mask.fieldPaths" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ListDocumentsResponse -- | Lists documents. -- -- /See:/ 'projectsDatabasesDocumentsList' smart constructor. data ProjectsDatabasesDocumentsList = ProjectsDatabasesDocumentsList' { _pParent :: !Text , _pXgafv :: !(Maybe Xgafv) , _pReadTime :: !(Maybe DateTime') , _pUploadProtocol :: !(Maybe Text) , _pOrderBy :: !(Maybe Text) , _pAccessToken :: !(Maybe Text) , _pCollectionId :: !Text , _pUploadType :: !(Maybe Text) , _pTransaction :: !(Maybe Bytes) , _pShowMissing :: !(Maybe Bool) , _pPageToken :: !(Maybe Text) , _pPageSize :: !(Maybe (Textual Int32)) , _pMaskFieldPaths :: !(Maybe [Text]) , _pCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsDatabasesDocumentsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pParent' -- -- * 'pXgafv' -- -- * 'pReadTime' -- -- * 'pUploadProtocol' -- -- * 'pOrderBy' -- -- * 'pAccessToken' -- -- * 'pCollectionId' -- -- * 'pUploadType' -- -- * 'pTransaction' -- -- * 'pShowMissing' -- -- * 'pPageToken' -- -- * 'pPageSize' -- -- * 'pMaskFieldPaths' -- -- * 'pCallback' projectsDatabasesDocumentsList :: Text -- ^ 'pParent' -> Text -- ^ 'pCollectionId' -> ProjectsDatabasesDocumentsList projectsDatabasesDocumentsList pPParent_ pPCollectionId_ = ProjectsDatabasesDocumentsList' { _pParent = pPParent_ , _pXgafv = Nothing , _pReadTime = Nothing , _pUploadProtocol = Nothing , _pOrderBy = Nothing , _pAccessToken = Nothing , _pCollectionId = pPCollectionId_ , _pUploadType = Nothing , _pTransaction = Nothing , _pShowMissing = Nothing , _pPageToken = Nothing , _pPageSize = Nothing , _pMaskFieldPaths = Nothing , _pCallback = Nothing } -- | Required. The parent resource name. In the format: -- \`projects\/{project_id}\/databases\/{database_id}\/documents\` or -- \`projects\/{project_id}\/databases\/{database_id}\/documents\/{document_path}\`. -- For example: \`projects\/my-project\/databases\/my-database\/documents\` -- or -- \`projects\/my-project\/databases\/my-database\/documents\/chatrooms\/my-chatroom\` pParent :: Lens' ProjectsDatabasesDocumentsList Text pParent = lens _pParent (\ s a -> s{_pParent = a}) -- | V1 error format. pXgafv :: Lens' ProjectsDatabasesDocumentsList (Maybe Xgafv) pXgafv = lens _pXgafv (\ s a -> s{_pXgafv = a}) -- | Reads documents as they were at the given time. This may not be older -- than 270 seconds. pReadTime :: Lens' ProjectsDatabasesDocumentsList (Maybe UTCTime) pReadTime = lens _pReadTime (\ s a -> s{_pReadTime = a}) . mapping _DateTime -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pUploadProtocol :: Lens' ProjectsDatabasesDocumentsList (Maybe Text) pUploadProtocol = lens _pUploadProtocol (\ s a -> s{_pUploadProtocol = a}) -- | The order to sort results by. For example: \`priority desc, name\`. pOrderBy :: Lens' ProjectsDatabasesDocumentsList (Maybe Text) pOrderBy = lens _pOrderBy (\ s a -> s{_pOrderBy = a}) -- | OAuth access token. pAccessToken :: Lens' ProjectsDatabasesDocumentsList (Maybe Text) pAccessToken = lens _pAccessToken (\ s a -> s{_pAccessToken = a}) -- | Required. The collection ID, relative to \`parent\`, to list. For -- example: \`chatrooms\` or \`messages\`. pCollectionId :: Lens' ProjectsDatabasesDocumentsList Text pCollectionId = lens _pCollectionId (\ s a -> s{_pCollectionId = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pUploadType :: Lens' ProjectsDatabasesDocumentsList (Maybe Text) pUploadType = lens _pUploadType (\ s a -> s{_pUploadType = a}) -- | Reads documents in a transaction. pTransaction :: Lens' ProjectsDatabasesDocumentsList (Maybe ByteString) pTransaction = lens _pTransaction (\ s a -> s{_pTransaction = a}) . mapping _Bytes -- | If the list should show missing documents. A missing document is a -- document that does not exist but has sub-documents. These documents will -- be returned with a key but will not have fields, Document.create_time, -- or Document.update_time set. Requests with \`show_missing\` may not -- specify \`where\` or \`order_by\`. pShowMissing :: Lens' ProjectsDatabasesDocumentsList (Maybe Bool) pShowMissing = lens _pShowMissing (\ s a -> s{_pShowMissing = a}) -- | The \`next_page_token\` value returned from a previous List request, if -- any. pPageToken :: Lens' ProjectsDatabasesDocumentsList (Maybe Text) pPageToken = lens _pPageToken (\ s a -> s{_pPageToken = a}) -- | The maximum number of documents to return. pPageSize :: Lens' ProjectsDatabasesDocumentsList (Maybe Int32) pPageSize = lens _pPageSize (\ s a -> s{_pPageSize = a}) . mapping _Coerce -- | The list of field paths in the mask. See Document.fields for a field -- path syntax reference. pMaskFieldPaths :: Lens' ProjectsDatabasesDocumentsList [Text] pMaskFieldPaths = lens _pMaskFieldPaths (\ s a -> s{_pMaskFieldPaths = a}) . _Default . _Coerce -- | JSONP pCallback :: Lens' ProjectsDatabasesDocumentsList (Maybe Text) pCallback = lens _pCallback (\ s a -> s{_pCallback = a}) instance GoogleRequest ProjectsDatabasesDocumentsList where type Rs ProjectsDatabasesDocumentsList = ListDocumentsResponse type Scopes ProjectsDatabasesDocumentsList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/datastore"] requestClient ProjectsDatabasesDocumentsList'{..} = go _pParent _pCollectionId _pXgafv _pReadTime _pUploadProtocol _pOrderBy _pAccessToken _pUploadType _pTransaction _pShowMissing _pPageToken _pPageSize (_pMaskFieldPaths ^. _Default) _pCallback (Just AltJSON) fireStoreService where go = buildClient (Proxy :: Proxy ProjectsDatabasesDocumentsListResource) mempty
brendanhay/gogol
gogol-firestore/gen/Network/Google/Resource/FireStore/Projects/Databases/Documents/List.hs
mpl-2.0
8,816
0
23
2,072
1,395
804
591
188
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Logging.Organizations.Sinks.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes a sink. If the sink has a unique writer_identity, then that -- service account is also deleted. -- -- /See:/ <https://cloud.google.com/logging/docs/ Stackdriver Logging API Reference> for @logging.organizations.sinks.delete@. module Network.Google.Resource.Logging.Organizations.Sinks.Delete ( -- * REST Resource OrganizationsSinksDeleteResource -- * Creating a Request , organizationsSinksDelete , OrganizationsSinksDelete -- * Request Lenses , osdXgafv , osdUploadProtocol , osdPp , osdAccessToken , osdUploadType , osdBearerToken , osdSinkName , osdCallback ) where import Network.Google.Logging.Types import Network.Google.Prelude -- | A resource alias for @logging.organizations.sinks.delete@ method which the -- 'OrganizationsSinksDelete' request conforms to. type OrganizationsSinksDeleteResource = "v2" :> Capture "sinkName" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] Empty -- | Deletes a sink. If the sink has a unique writer_identity, then that -- service account is also deleted. -- -- /See:/ 'organizationsSinksDelete' smart constructor. data OrganizationsSinksDelete = OrganizationsSinksDelete' { _osdXgafv :: !(Maybe Xgafv) , _osdUploadProtocol :: !(Maybe Text) , _osdPp :: !Bool , _osdAccessToken :: !(Maybe Text) , _osdUploadType :: !(Maybe Text) , _osdBearerToken :: !(Maybe Text) , _osdSinkName :: !Text , _osdCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrganizationsSinksDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'osdXgafv' -- -- * 'osdUploadProtocol' -- -- * 'osdPp' -- -- * 'osdAccessToken' -- -- * 'osdUploadType' -- -- * 'osdBearerToken' -- -- * 'osdSinkName' -- -- * 'osdCallback' organizationsSinksDelete :: Text -- ^ 'osdSinkName' -> OrganizationsSinksDelete organizationsSinksDelete pOsdSinkName_ = OrganizationsSinksDelete' { _osdXgafv = Nothing , _osdUploadProtocol = Nothing , _osdPp = True , _osdAccessToken = Nothing , _osdUploadType = Nothing , _osdBearerToken = Nothing , _osdSinkName = pOsdSinkName_ , _osdCallback = Nothing } -- | V1 error format. osdXgafv :: Lens' OrganizationsSinksDelete (Maybe Xgafv) osdXgafv = lens _osdXgafv (\ s a -> s{_osdXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). osdUploadProtocol :: Lens' OrganizationsSinksDelete (Maybe Text) osdUploadProtocol = lens _osdUploadProtocol (\ s a -> s{_osdUploadProtocol = a}) -- | Pretty-print response. osdPp :: Lens' OrganizationsSinksDelete Bool osdPp = lens _osdPp (\ s a -> s{_osdPp = a}) -- | OAuth access token. osdAccessToken :: Lens' OrganizationsSinksDelete (Maybe Text) osdAccessToken = lens _osdAccessToken (\ s a -> s{_osdAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). osdUploadType :: Lens' OrganizationsSinksDelete (Maybe Text) osdUploadType = lens _osdUploadType (\ s a -> s{_osdUploadType = a}) -- | OAuth bearer token. osdBearerToken :: Lens' OrganizationsSinksDelete (Maybe Text) osdBearerToken = lens _osdBearerToken (\ s a -> s{_osdBearerToken = a}) -- | Required. The full resource name of the sink to delete, including the -- parent resource and the sink identifier: -- \"projects\/[PROJECT_ID]\/sinks\/[SINK_ID]\" -- \"organizations\/[ORGANIZATION_ID]\/sinks\/[SINK_ID]\" It is an error if -- the sink does not exist. Example: -- \"projects\/my-project-id\/sinks\/my-sink-id\". It is an error if the -- sink does not exist. osdSinkName :: Lens' OrganizationsSinksDelete Text osdSinkName = lens _osdSinkName (\ s a -> s{_osdSinkName = a}) -- | JSONP osdCallback :: Lens' OrganizationsSinksDelete (Maybe Text) osdCallback = lens _osdCallback (\ s a -> s{_osdCallback = a}) instance GoogleRequest OrganizationsSinksDelete where type Rs OrganizationsSinksDelete = Empty type Scopes OrganizationsSinksDelete = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/logging.admin"] requestClient OrganizationsSinksDelete'{..} = go _osdSinkName _osdXgafv _osdUploadProtocol (Just _osdPp) _osdAccessToken _osdUploadType _osdBearerToken _osdCallback (Just AltJSON) loggingService where go = buildClient (Proxy :: Proxy OrganizationsSinksDeleteResource) mempty
rueshyna/gogol
gogol-logging/gen/Network/Google/Resource/Logging/Organizations/Sinks/Delete.hs
mpl-2.0
5,879
0
17
1,351
860
503
357
121
1
{-# LANGUAGE CPP #-} -- | -- Module : GHC.Vacuum.ClosureType -- Copyright : (c) Matt Morrow 2009, Austin Seipp 2011-2012 -- License : LGPLv3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (GHC only) -- -- This module exports the different kind of closure types there -- are per GHC version. -- -- NOTE: the 'ClosureType' datatype is automatically generated, based -- on the version of GHC, and the proper one is included for you. -- module GHC.Vacuum.ClosureType ( ClosureType(..) , isFun -- :: ClosureType -> Bool , isThunk -- :: ClosureType -> Bool , isCon -- :: ClosureType -> Bool ) where -- Import the correct ClosureType datatype based on -- the version #if __GLASGOW_HASKELL__ == 700 import GHC.Vacuum.ClosureType.V700 (ClosureType(..)) #elif __GLASGOW_HASKELL__ == 702 import GHC.Vacuum.ClosureType.V702 (ClosureType(..)) #elif __GLASGOW_HASKELL__ == 704 import GHC.Vacuum.ClosureType.V704 (ClosureType(..)) #elif __GLASGOW_HASKELL__ == 706 import GHC.Vacuum.ClosureType.V706 (ClosureType(..)) #elif __GLASGOW_HASKELL__ == 708 import GHC.Vacuum.ClosureType.V708 (ClosureType(..)) #else #error Unsupported GHC version in ClosureTypes.hs! #endif ------------------------------------------------ isFun :: ClosureType -> Bool isFun FUN = True isFun FUN_1_0 = True isFun FUN_0_1 = True isFun FUN_2_0 = True isFun FUN_1_1 = True isFun FUN_0_2 = True isFun FUN_STATIC = True isFun _ = False isThunk :: ClosureType -> Bool isThunk AP = True isThunk THUNK = True isThunk THUNK_1_0 = True isThunk THUNK_0_1 = True isThunk THUNK_2_0 = True isThunk THUNK_1_1 = True isThunk THUNK_0_2 = True isThunk THUNK_STATIC = True isThunk THUNK_SELECTOR = True isThunk _ = False isCon :: ClosureType -> Bool isCon CONSTR = True isCon CONSTR_1_0 = True isCon CONSTR_0_1 = True isCon CONSTR_2_0 = True isCon CONSTR_1_1 = True isCon CONSTR_0_2 = True isCon CONSTR_STATIC = True isCon CONSTR_NOCAF_STATIC = True isCon _ = False
thoughtpolice/vacuum
src/GHC/Vacuum/ClosureType.hs
lgpl-3.0
2,030
0
6
360
309
176
133
-1
-1
module Affection.MessageBus.Message.Class where -- | Typeclass definition for messages class Message msg where -- | return the time when the message was sent msgTime :: msg -> Double
nek0/affection
src/Affection/MessageBus/Message/Class.hs
lgpl-3.0
188
0
7
33
28
17
11
3
0
------------------------------------------------- -- | -- Module : Crypto.Noise -- Maintainer : John Galt <[email protected]> -- Stability : experimental -- Portability : POSIX -- -- Please see the README for usage information. module Crypto.Noise ( -- * Types NoiseState , NoiseResult(..) , HandshakePattern , HandshakeRole(..) , HandshakeOpts -- * Functions , defaultHandshakeOpts , noiseState , writeMessage , readMessage , processPSKs , remoteStaticKey , handshakeComplete , handshakeHash , rekeySending , rekeyReceiving , handshakePattern -- * HandshakeOpts Setters , setLocalEphemeral , setLocalStatic , setRemoteEphemeral , setRemoteStatic -- * Classes , Cipher , DH , Hash -- * Re-exports , ScrubbedBytes , convert ) where import Control.Arrow (arr, second, (***)) import Control.Exception.Safe import Control.Lens import Data.ByteArray (ScrubbedBytes, convert) import Data.Maybe (isJust) import Crypto.Noise.Cipher import Crypto.Noise.DH import Crypto.Noise.Hash import Crypto.Noise.Internal.CipherState import Crypto.Noise.Internal.Handshake.Pattern hiding (psk) import Crypto.Noise.Internal.Handshake.State import Crypto.Noise.Internal.NoiseState import Crypto.Noise.Internal.SymmetricState -- | This type is used to indicate to the user the result of either writing or -- reading a message. In the simplest case, when processing a handshake or -- transport message, the (en|de)crypted message and mutated state will be -- available in 'NoiseResultMessage'. -- -- If during the course of the handshake a pre-shared key is needed, a -- 'NoiseResultNeedPSK' value will be returned along with the mutated state. -- To continue, the user must re-issue the 'writeMessage' or 'readMessage' -- call, passing in the PSK as the payload. If no further PSKs are required, -- the result will be 'NoiseResultMessage'. -- -- If an exception is encountered at any point while processing a handshake or -- transport message, 'NoiseResultException' will be returned. data NoiseResult c d h = NoiseResultMessage ScrubbedBytes (NoiseState c d h) | NoiseResultNeedPSK (NoiseState c d h) | NoiseResultException SomeException -- | Creates a handshake or transport message with the provided payload. Note -- that the payload may not be authenticated or encrypted at all points during -- the handshake. Please see section 7.4 of the protocol document for details. -- -- If a previous call to this function indicated that a pre-shared key is -- needed, it shall be provided as the payload. See the documentation of -- 'NoiseResult' for details. -- -- To prevent catastrophic key re-use, this function may only be used to -- secure 2^64 - 1 post-handshake messages. writeMessage :: (Cipher c, DH d, Hash h) => ScrubbedBytes -> NoiseState c d h -> NoiseResult c d h writeMessage msg ns = maybe (convertHandshakeResult $ resumeHandshake msg ns) (convertTransportResult . encryptMsg) (ns ^. nsSendingCipherState) where ctToMsg = arr cipherTextToBytes updateState = arr $ \cs -> ns & nsSendingCipherState ?~ cs encryptMsg cs = (ctToMsg *** updateState) <$> encryptWithAd mempty msg cs -- | Reads a handshake or transport message and returns the embedded payload. If -- the handshake fails, a 'HandshakeError' will be returned. After the -- handshake is complete, if decryption fails a 'DecryptionError' is returned. -- -- If a previous call to this function indicated that a pre-shared key is -- needed, it shall be provided as the payload. See the documentation of -- 'NoiseResult' for details. -- -- To prevent catastrophic key re-use, this function may only be used to -- receive 2^64 - 1 post-handshake messages. readMessage :: (Cipher c, DH d, Hash h) => ScrubbedBytes -> NoiseState c d h -> NoiseResult c d h readMessage ct ns = maybe (convertHandshakeResult $ resumeHandshake ct ns) (convertTransportResult . decryptMsg) (ns ^. nsReceivingCipherState) where ct' = cipherBytesToText ct updateState = arr $ \cs -> ns & nsReceivingCipherState ?~ cs decryptMsg cs = second updateState <$> decryptWithAd mempty ct' cs -- | Given an operation ('writeMessage' or 'readMessage'), a list of PSKs, and -- a 'NoiseResult', this function will repeatedly apply PSKs to the NoiseState -- until no more are requested or the list of PSKs becomes empty. This is -- useful for patterns which require two or more PSKs, and you know exactly -- what they all should be ahead of time. processPSKs :: (Cipher c, DH d, Hash h) => (ScrubbedBytes -> NoiseState c d h -> NoiseResult c d h) -> [ScrubbedBytes] -> NoiseResult c d h -> ([ScrubbedBytes], NoiseResult c d h) processPSKs _ [] result = ([], result) processPSKs f psks@(psk : rest) result = case result of NoiseResultNeedPSK state' -> processPSKs f rest (f psk state') r -> (psks, r) -- | For handshake patterns where the remote party's static key is -- transmitted, this function can be used to retrieve it. This allows -- for the creation of public key-based access-control lists. remoteStaticKey :: NoiseState c d h -> Maybe (PublicKey d) remoteStaticKey ns = ns ^. nsHandshakeState . hsOpts . hoRemoteStatic -- | Returns @True@ if the handshake is complete. handshakeComplete :: NoiseState c d h -> Bool handshakeComplete ns = isJust (ns ^. nsSendingCipherState) && isJust (ns ^. nsReceivingCipherState) -- | Retrieves the @h@ value associated with the conversation's -- @SymmetricState@. This value is intended to be used for channel -- binding. For example, the initiator might cryptographically sign this -- value as part of some higher-level authentication scheme. -- -- The value returned by this function is only meaningful after the -- handshake is complete. -- -- See section 11.2 of the protocol for details. handshakeHash :: Hash h => NoiseState c d h -> ScrubbedBytes handshakeHash ns = either id hashToBytes $ ns ^. nsHandshakeState . hsSymmetricState . ssh -- | Rekeys the sending @CipherState@ according to section 11.3 of the protocol. rekeySending :: (Cipher c, DH d, Hash h) => NoiseState c d h -> NoiseState c d h rekeySending ns = ns & nsSendingCipherState %~ (<*>) (pure rekey) -- | Rekeys the receiving @CipherState@ according to section 11.3 of the -- protocol. rekeyReceiving :: (Cipher c, DH d, Hash h) => NoiseState c d h -> NoiseState c d h rekeyReceiving ns = ns & nsReceivingCipherState %~ (<*>) (pure rekey) -------------------------------------------------------------------------------- convertHandshakeResult :: (Cipher c, DH d, Hash h) => Either SomeException (HandshakeResult, NoiseState c d h) -> NoiseResult c d h convertHandshakeResult hsr = case hsr of Left ex -> NoiseResultException ex Right (HandshakeResultMessage m, ns) -> NoiseResultMessage m ns Right (HandshakeResultNeedPSK , ns) -> NoiseResultNeedPSK ns convertTransportResult :: (Cipher c, DH d, Hash h) => Either SomeException (ScrubbedBytes, NoiseState c d h) -> NoiseResult c d h convertTransportResult = either NoiseResultException (uncurry NoiseResultMessage)
centromere/cacophony
src/Crypto/Noise.hs
unlicense
7,537
0
10
1,692
1,261
707
554
-1
-1
{-# LANGUAGE UnicodeSyntax #-} import Data.Ratio import Control.Monad import Data.List ((\\), intersect) import Debug.Trace (traceShow) type Rational = (Int, Int) -- Cancel how an inexperienced mathematician would cancel inexperiencedCancel :: Int -> Int -> Ratio Int inexperiencedCancel a b = let astr = show a bstr = show b a' = read (astr \\ bstr) b' = read (bstr \\ astr) in a' % b' -- Is the fraction trivially cancellable, e.g. 30/50 or 1/11 -- Might need modifications for numbers > 99 isTrivial :: Int -> Int -> Bool isTrivial a b = let astr = show a bstr = show b -- Cancelling must NOT remove all digits of num/den anull = null (astr \\ bstr) bnull = null (bstr \\ astr) -- Cancelling must remove some digits intersectNull = null $ intersect astr bstr in '0' `elem` (show a) || '0' `elem` (show b) || (a == b) || anull || bnull || intersectNull -- Check if a fraction is 'curious' according to Project Euler problem 33 checkFraction :: Int -> Int -> Bool checkFraction a b | isTrivial a b = False | a > b = False -- Fraction must be less than one | inexperiencedCancel a b == a % b = True | otherwise = False main :: IO () main = do -- Define the search space let space = [(a, b) | a <- [1..99], b <- [1..99]] -- Compute the four fractions of interest let resultingFractions = filter (uncurry checkFraction) space -- Compute product let fractProduct = product $ map (uncurry (%)) resultingFractions -- Print the denominator print $ denominator fractProduct
ulikoehler/ProjectEuler
Euler33.hs
apache-2.0
1,623
0
15
427
475
250
225
34
1
{-# LANGUAGE ScopedTypeVariables #-} module SetOfTests where import Control.Monad (liftM2) import Test.QuickCheck hiding (elements) import BRC.SetOf import BRC.Size runAll :: forall e . forall s . (Show e, Show s, Eq e, SetOf e s) => Gen e -> Gen s -> IO () runAll ge gs = mapM_ quickCheck [allE (\x -> elements ((singleton x) :: s) == [x]), allS prop_univIsIntersectionIdentity, allS prop_emptyIsIntersectionZero, allS prop_emptyIsUnionIdentity, allS prop_univIsUnionZero, allS prop_intersectionWithSelfIsSelf, allS prop_unionWithSelfIsSelf, allS2 prop_intersectionCommutative, allS3 prop_intersectionAssociative, allS2 prop_unionCommutative, allS3 prop_unionAssociative, allS3 prop_distributivity, allS prop_sameAsReflexive, allS2 prop_sameAsSymmetric, allS3 prop_sameAsTransitive, allS prop_univIsBiggest, allS prop_emptyHasSizeZero, allS2 prop_intersectionNoLarger, allS prop_elementCount] where allE = forAll ge allS = forAll gs allS2 = forAll gs2 . uncurry allS3 = forAll (gPair gs2 gs) . uncurry . uncurry gs2 = gPair gs gs gPair = liftM2 (,) prop_univIsIntersectionIdentity :: SetOf e s => s -> Bool prop_univIsIntersectionIdentity s = (s `intersection` univ) `sameAs` s prop_emptyIsIntersectionZero :: SetOf e s => s -> Bool prop_emptyIsIntersectionZero s = (s `intersection` empty) `sameAs` empty prop_emptyIsUnionIdentity :: SetOf e s => s -> Bool prop_emptyIsUnionIdentity s = (s `union` empty) `sameAs` s prop_univIsUnionZero :: SetOf e s => s -> Bool prop_univIsUnionZero s = (s `union` univ) `sameAs` univ prop_intersectionWithSelfIsSelf :: SetOf e s => s -> Bool prop_intersectionWithSelfIsSelf s = (s `intersection` s) `sameAs` s prop_unionWithSelfIsSelf :: SetOf e s => s -> Bool prop_unionWithSelfIsSelf s = (s `union` s) `sameAs` s prop_intersectionCommutative :: SetOf e s => s -> s -> Bool prop_intersectionCommutative = prop_commutative intersection prop_intersectionAssociative :: SetOf e s => s -> s -> s -> Bool prop_intersectionAssociative = prop_associative intersection prop_unionCommutative :: SetOf e s => s -> s -> Bool prop_unionCommutative = prop_commutative union prop_unionAssociative :: SetOf e s => s -> s -> s -> Bool prop_unionAssociative = prop_associative union prop_distributivity :: SetOf e s => s -> s -> s -> Bool prop_distributivity x y z = (x `intersection` (y `union` z)) `sameAs` ((x `intersection` y) `union` (x `intersection` z)) prop_sameAsSymmetric :: SetOf e s => s -> s -> Bool prop_sameAsSymmetric x y = (x `sameAs` y) == (y `sameAs` x) prop_sameAsReflexive :: SetOf e s => s -> Bool prop_sameAsReflexive x = x `sameAs` x prop_sameAsTransitive :: SetOf e s => s -> s -> s -> Bool prop_sameAsTransitive x y z = ((x `sameAs` y) && (y `sameAs` z)) `implies` (x `sameAs` z) prop_univIsBiggest :: forall e s . SetOf e s => s -> Bool prop_univIsBiggest s = size s <= size (univ :: s) prop_emptyHasSizeZero :: SetOf e s => s -> Bool prop_emptyHasSizeZero s = (s `sameAs` empty) == (isZero (size s)) prop_intersectionNoLarger :: SetOf e s => s -> s -> Bool prop_intersectionNoLarger x y = let i = size (x `intersection` y) in i <= size x && i <= size y prop_elementCount :: SetOf e s => s -> Bool prop_elementCount x = let i = size x in isFinite i `implies` maybe False (== length (elements x)) (maybeCount i) prop_commutative :: SetOf e s => (s -> s -> s) -> s -> s -> Bool prop_commutative op x y = (x `op` y) `sameAs` (y `op` x) prop_associative :: SetOf e s => (s -> s -> s) -> s -> s -> s -> Bool prop_associative op x y z = ((x `op` y) `op` z) `sameAs` (x `op` (y `op` z)) implies :: Bool -> Bool -> Bool x `implies` y = not x || y
kcharter/brc-solver
tests/SetOfTests.hs
bsd-2-clause
4,050
0
14
1,039
1,410
760
650
82
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} module Handler.Update where import Control.Applicative import Data.Aeson import qualified Data.Text as T import Filesystem.Path import Filesystem.Path.CurrentOS (fromText, toText, encodeString) import Filesystem import Import hiding (object, FilePath) import System.Exit import System.IO (hGetContents) import System.Process import Text.Blaze import Yesod.Default.Config import Yesod.Json () import Prelude hiding (FilePath) data UpdateStatus = UpdateStatus { name :: T.Text , success :: Bool } instance ToJSON UpdateStatus where toJSON (UpdateStatus n s) = object [ "name" .= n , "success" .= s ] getUpdateR :: T.Text -> Handler RepHtml getUpdateR repoName = do (Extra {..}) <- appExtra . settings <$> getYesod if repoName `elem` extraRepos then defaultLayout $ updateWidget (fromText extraBaseDir) (fromText repoName) else notFound instance ToMarkup FilePath where toMarkup = toMarkup . encodeString instance ToMarkup ExitCode where toMarkup = toMarkup . show updateWidget :: FilePath -> FilePath -> Widget updateWidget baseDir repoName = do setTitle . toHtml $ T.concat ["Update ", either id id $ toText repoName] (_, mout, _, pr) <- liftIO . createProcess $ (proc "git" ["pull"]) { cwd = Just $ encodeString repoDir , std_out = CreatePipe } ec <- liftIO $ waitForProcess pr out <- liftIO $ maybe (return "<no output>") hGetContents mout $(widgetFile "update") where repoDir = baseDir </> repoName
erochest/NeatlineUpdate
Handler/Update.hs
bsd-2-clause
1,853
0
12
591
468
256
212
-1
-1
{-# Language FlexibleInstances, RankNTypes, RecordWildCards, TemplateHaskell #-} module Test.Ambiguous where import Control.Applicative ((<|>), empty, liftA2) import Data.Foldable (fold) import Data.Semigroup ((<>)) import qualified Rank2.TH import Text.Grampa import Text.Grampa.Combinators import Text.Grampa.ContextFree.LeftRecursive (Parser) import Debug.Trace data Amb = Xy1 String String | Xy2 (Ambiguous Amb) String | Xyz (Ambiguous Amb) String | Xyzw (Ambiguous Amb) String deriving (Eq, Show) data Test p = Test{ amb :: p (Ambiguous Amb) } grammar :: Test (Parser Test String) -> Test (Parser Test String) grammar Test{..} = Test{ amb = ambiguous (Xy1 <$> string "x" <*> moptional (string "y") <|> Xy2 <$> amb <*> string "y" <|> Xyz <$> amb <*> string "z" <|> Xyzw <$> amb <*> string "w") } $(Rank2.TH.deriveAll ''Test)
blamario/grampa
grammatical-parsers/test/Test/Ambiguous.hs
bsd-2-clause
944
0
21
233
306
167
139
24
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ViewPatterns #-} -- | All data types. module Stack.Build.Types (StackBuildException(..) ,InstallLocation(..) ,ModTime ,modTime ,Installed(..) ,PackageInstallInfo(..) ,Task(..) ,LocalPackage(..) ,BaseConfigOpts(..) ,Plan(..) ,FinalAction(..) ,BuildOpts(..) ,TaskType(..) ,TaskConfigOpts(..) ,ConfigCache(..) ,ConstructPlanException(..) ,configureOpts ,BadDependency(..) ,wantedLocalPackages) where import Control.DeepSeq import Control.Exception import Data.Binary (Binary(..)) import qualified Data.ByteString as S import Data.Char (isSpace) import Data.Data import Data.Hashable import Data.List (dropWhileEnd, nub, intercalate) import qualified Data.Map as Map import Data.Map.Strict (Map) import Data.Maybe import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8With) import Data.Text.Encoding.Error (lenientDecode) import Data.Time.Calendar import Data.Time.Clock import Distribution.System (Arch) import Distribution.Text (display) import GHC.Generics import Path (Path, Abs, File, Dir, mkRelDir, toFilePath, parseRelDir, (</>)) import Prelude import Stack.Package import Stack.Types import System.Exit (ExitCode) import System.FilePath (dropTrailingPathSeparator, pathSeparator) ---------------------------------------------- -- Exceptions data StackBuildException = Couldn'tFindPkgId PackageName | GHCVersionMismatch (Maybe (Version, Arch)) (Version, Arch) (Maybe (Path Abs File)) -- ^ Path to the stack.yaml file | Couldn'tParseTargets [Text] | UnknownTargets (Set PackageName) -- no known version (Map PackageName Version) -- not in snapshot, here's the most recent version in the index (Path Abs File) -- stack.yaml | TestSuiteFailure PackageIdentifier (Map Text (Maybe ExitCode)) (Maybe (Path Abs File)) S.ByteString | ConstructPlanExceptions [ConstructPlanException] (Path Abs File) -- stack.yaml | CabalExitedUnsuccessfully ExitCode PackageIdentifier (Path Abs File) -- cabal Executable [String] -- cabal arguments (Maybe (Path Abs File)) -- logfiles location S.ByteString -- log contents | ExecutionFailure [SomeException] deriving Typeable instance Show StackBuildException where show (Couldn'tFindPkgId name) = ("After installing " <> packageNameString name <> ", the package id couldn't be found " <> "(via ghc-pkg describe " <> packageNameString name <> "). This shouldn't happen, " <> "please report as a bug") show (GHCVersionMismatch mactual (expected, earch) mstack) = concat [ case mactual of Nothing -> "No GHC found, expected version " Just (actual, arch) -> concat [ "GHC version mismatched, found " , versionString actual , " (" , display arch , ")" , ", but expected version " ] , versionString expected , " (" , display earch , ") (based on " , case mstack of Nothing -> "command line arguments" Just stack -> "resolver setting in " ++ toFilePath stack , "). Try running stack setup" ] show (Couldn'tParseTargets targets) = unlines $ "The following targets could not be parsed as package names or directories:" : map T.unpack targets show (UnknownTargets noKnown notInSnapshot stackYaml) = unlines $ noKnown' ++ notInSnapshot' where noKnown' | Set.null noKnown = [] | otherwise = return $ "The following target packages were not found: " ++ intercalate ", " (map packageNameString $ Set.toList noKnown) notInSnapshot' | Map.null notInSnapshot = [] | otherwise = "The following packages are not in your snapshot, but exist" : "in your package index. Recommended action: add them to your" : ("extra-deps in " ++ toFilePath stackYaml) : "(Note: these are the most recent versions," : "but there's no guarantee that they'll build together)." : "" : map (\(name, version) -> "- " ++ packageIdentifierString (PackageIdentifier name version)) (Map.toList notInSnapshot) show (TestSuiteFailure ident codes mlogFile bs) = unlines $ concat [ ["Test suite failure for package " ++ packageIdentifierString ident] , flip map (Map.toList codes) $ \(name, mcode) -> concat [ " " , T.unpack name , ": " , case mcode of Nothing -> " executable not found" Just ec -> " exited with: " ++ show ec ] , return $ case mlogFile of Nothing -> "Logs printed to console" -- TODO Should we load up the full error output and print it here? Just logFile -> "Full log available at " ++ toFilePath logFile , if S.null bs then [] else ["", "", doubleIndent $ T.unpack $ decodeUtf8With lenientDecode bs] ] where indent = dropWhileEnd isSpace . unlines . fmap (\line -> " " ++ line) . lines doubleIndent = indent . indent show (ConstructPlanExceptions exceptions stackYaml) = "While constructing the BuildPlan the following exceptions were encountered:" ++ appendExceptions exceptions' ++ if Map.null extras then "" else (unlines $ ("\n\nRecommended action: try adding the following to your extra-deps in " ++ toFilePath stackYaml) : map (\(name, version) -> concat [ "- " , packageNameString name , "-" , versionString version ]) (Map.toList extras) ++ ["", "You may also want to try the 'stack solver' command"] ) where exceptions' = removeDuplicates exceptions appendExceptions = foldr (\e -> (++) ("\n\n--" ++ show e)) "" removeDuplicates = nub extras = Map.unions $ map getExtras exceptions' getExtras (DependencyCycleDetected _) = Map.empty getExtras (UnknownPackage _) = Map.empty getExtras (DependencyPlanFailures _ m) = Map.unions $ map go $ Map.toList m where go (name, (_range, NotInBuildPlan (Just version))) = Map.singleton name version go _ = Map.empty -- Supressing duplicate output show (CabalExitedUnsuccessfully exitCode taskProvides' execName fullArgs logFiles bs) = let fullCmd = (dropQuotes (show execName) ++ " " ++ (unwords fullArgs)) logLocations = maybe "" (\fp -> "\n Logs have been written to: " ++ show fp) logFiles in "\n-- While building package " ++ dropQuotes (show taskProvides') ++ " using:\n" ++ " " ++ fullCmd ++ "\n" ++ " Process exited with code: " ++ show exitCode ++ logLocations ++ (if S.null bs then "" else "\n\n" ++ doubleIndent (T.unpack $ decodeUtf8With lenientDecode bs)) where -- appendLines = foldr (\pName-> (++) ("\n" ++ show pName)) "" indent = dropWhileEnd isSpace . unlines . fmap (\line -> " " ++ line) . lines dropQuotes = filter ('\"' /=) doubleIndent = indent . indent show (ExecutionFailure es) = intercalate "\n\n" $ map show es instance Exception StackBuildException data ConstructPlanException = DependencyCycleDetected [PackageName] | DependencyPlanFailures PackageIdentifier (Map PackageName (VersionRange, BadDependency)) | UnknownPackage PackageName -- TODO perhaps this constructor will be removed, and BadDependency will handle it all -- ^ Recommend adding to extra-deps, give a helpful version number? deriving (Typeable, Eq) -- | Reason why a dependency was not used data BadDependency = NotInBuildPlan (Maybe Version) -- recommended version, for extra-deps output | Couldn'tResolveItsDependencies | DependencyMismatch Version deriving (Typeable, Eq) instance Show ConstructPlanException where show e = let details = case e of (DependencyCycleDetected pNames) -> "While checking call stack,\n" ++ " dependency cycle detected in packages:" ++ indent (appendLines pNames) (DependencyPlanFailures pIdent (Map.toList -> pDeps)) -> "Failure when adding dependencies:" ++ doubleIndent (appendDeps pDeps) ++ "\n" ++ " needed for package: " ++ packageIdentifierString pIdent (UnknownPackage pName) -> "While attempting to add dependency,\n" ++ " Could not find package " ++ show pName ++ " in known packages" in indent details where appendLines = foldr (\pName-> (++) ("\n" ++ show pName)) "" indent = dropWhileEnd isSpace . unlines . fmap (\line -> " " ++ line) . lines doubleIndent = indent . indent appendDeps = foldr (\dep-> (++) ("\n" ++ showDep dep)) "" showDep (name, (range, badDep)) = concat [ show name , ": needed (" , display range , "), but " , case badDep of NotInBuildPlan mlatest -> "not present in build plan" ++ (case mlatest of Nothing -> "" Just latest -> ", latest is " ++ versionString latest) Couldn'tResolveItsDependencies -> "couldn't resolve its dependencies" DependencyMismatch version -> versionString version ++ " found" ] {- TODO Perhaps change the showDep function to look more like this: dropQuotes = filter ((/=) '\"') (VersionOutsideRange pName pIdentifier versionRange) -> "Exception: Stack.Build.VersionOutsideRange\n" ++ " While adding dependency for package " ++ show pName ++ ",\n" ++ " " ++ dropQuotes (show pIdentifier) ++ " was found to be outside its allowed version range.\n" ++ " Allowed version range is " ++ display versionRange ++ ",\n" ++ " should you correct the version range for " ++ dropQuotes (show pIdentifier) ++ ", found in [extra-deps] in the project's stack.yaml?" -} ---------------------------------------------- -- | Configuration for building. data BuildOpts = BuildOpts {boptsTargets :: ![Text] ,boptsLibProfile :: !Bool ,boptsExeProfile :: !Bool ,boptsEnableOptimizations :: !(Maybe Bool) ,boptsHaddock :: !Bool -- ^ Build haddocks? ,boptsHaddockDeps :: !(Maybe Bool) -- ^ Build haddocks for dependencies? ,boptsFinalAction :: !FinalAction ,boptsDryrun :: !Bool ,boptsGhcOptions :: ![Text] ,boptsFlags :: !(Map (Maybe PackageName) (Map FlagName Bool)) ,boptsInstallExes :: !Bool -- ^ Install executables to user path after building? ,boptsPreFetch :: !Bool -- ^ Fetch all packages immediately ,boptsTestArgs :: ![String] -- ^ Arguments to pass to the test suites if we're running them. ,boptsOnlySnapshot :: !Bool -- ^ Only install packages in the snapshot database, skipping -- packages intended for the local database. ,boptsCoverage :: !Bool -- ^ Enable code coverage report generation for test -- suites. } deriving (Show) -- | Run a Setup.hs action after building a package, before installing. data FinalAction = DoTests | DoBenchmarks | DoNothing deriving (Eq,Bounded,Enum,Show) -- | Package dependency oracle. newtype PkgDepsOracle = PkgDeps PackageName deriving (Show,Typeable,Eq,Hashable,Binary,NFData) -- | A location to install a package into, either snapshot or local data InstallLocation = Snap | Local deriving (Show, Eq) instance Monoid InstallLocation where mempty = Snap mappend Local _ = Local mappend _ Local = Local mappend Snap Snap = Snap -- | Datatype which tells how which version of a package to install and where -- to install it into class PackageInstallInfo a where piiVersion :: a -> Version piiLocation :: a -> InstallLocation -- | Information on a locally available package of source code data LocalPackage = LocalPackage { lpPackage :: !Package -- ^ The @Package@ info itself, after resolution with package flags, not including any final actions , lpPackageFinal :: !Package -- ^ Same as lpPackage, but with any test suites or benchmarks enabled as necessary , lpWanted :: !Bool -- ^ Is this package a \"wanted\" target based on command line input , lpDir :: !(Path Abs Dir) -- ^ Directory of the package. , lpCabalFile :: !(Path Abs File) -- ^ The .cabal file , lpDirtyFiles :: !Bool -- ^ are there files that have changed since the last build? , lpComponents :: !(Set Text) -- ^ components to build, passed directly to Setup.hs build } deriving Show -- | Stored on disk to know whether the flags have changed or any -- files have changed. data ConfigCache = ConfigCache { configCacheOpts :: ![S.ByteString] -- ^ All options used for this package. , configCacheDeps :: !(Set GhcPkgId) -- ^ The GhcPkgIds of all of the dependencies. Since Cabal doesn't take -- the complete GhcPkgId (only a PackageIdentifier) in the configure -- options, just using the previous value is insufficient to know if -- dependencies have changed. , configCacheComponents :: !(Set S.ByteString) -- ^ The components to be built. It's a bit of a hack to include this in -- here, as it's not a configure option (just a build option), but this -- is a convenient way to force compilation when the components change. , configCacheHaddock :: !Bool -- ^ Are haddocks to be built? } deriving (Generic,Eq,Show) instance Binary ConfigCache -- | A task to perform when building data Task = Task { taskProvides :: !PackageIdentifier -- ^ the package/version to be built , taskType :: !TaskType -- ^ the task type, telling us how to build this , taskConfigOpts :: !TaskConfigOpts , taskPresent :: !(Set GhcPkgId) -- ^ GhcPkgIds of already-installed dependencies } deriving Show -- | Given the IDs of any missing packages, produce the configure options data TaskConfigOpts = TaskConfigOpts { tcoMissing :: !(Set PackageIdentifier) -- ^ Dependencies for which we don't yet have an GhcPkgId , tcoOpts :: !(Set GhcPkgId -> [Text]) -- ^ Produce the list of options given the missing @GhcPkgId@s } instance Show TaskConfigOpts where show (TaskConfigOpts missing f) = concat [ "Missing: " , show missing , ". Without those: " , show $ f Set.empty ] -- | The type of a task, either building local code or something from the -- package index (upstream) data TaskType = TTLocal LocalPackage | TTUpstream Package InstallLocation deriving Show -- | A complete plan of what needs to be built and how to do it data Plan = Plan { planTasks :: !(Map PackageName Task) , planFinals :: !(Map PackageName Task) -- ^ Final actions to be taken (test, benchmark, etc) , planUnregisterLocal :: !(Map GhcPkgId Text) -- ^ Text is reason we're unregistering, for display only , planInstallExes :: !(Map Text InstallLocation) -- ^ Executables that should be installed after successful building } deriving Show -- | Basic information used to calculate what the configure options are data BaseConfigOpts = BaseConfigOpts { bcoSnapDB :: !(Path Abs Dir) , bcoLocalDB :: !(Path Abs Dir) , bcoSnapInstallRoot :: !(Path Abs Dir) , bcoLocalInstallRoot :: !(Path Abs Dir) , bcoBuildOpts :: !BuildOpts } -- | Render a @BaseConfigOpts@ to an actual list of options configureOpts :: EnvConfig -> BaseConfigOpts -> Set GhcPkgId -- ^ dependencies -> Bool -- ^ wanted? -> InstallLocation -> Package -> [Text] configureOpts econfig bco deps wanted loc package = map T.pack $ concat [ ["--user", "--package-db=clear", "--package-db=global"] , map (("--package-db=" ++) . toFilePath) $ case loc of Snap -> [bcoSnapDB bco] Local -> [bcoSnapDB bco, bcoLocalDB bco] , depOptions , [ "--libdir=" ++ toFilePathNoTrailingSlash (installRoot </> $(mkRelDir "lib")) , "--bindir=" ++ toFilePathNoTrailingSlash (installRoot </> bindirSuffix) , "--datadir=" ++ toFilePathNoTrailingSlash (installRoot </> $(mkRelDir "share")) , "--docdir=" ++ toFilePathNoTrailingSlash docDir , "--htmldir=" ++ toFilePathNoTrailingSlash docDir , "--haddockdir=" ++ toFilePathNoTrailingSlash docDir] , ["--enable-library-profiling" | boptsLibProfile bopts || boptsExeProfile bopts] , ["--enable-executable-profiling" | boptsExeProfile bopts] , map (\(name,enabled) -> "-f" <> (if enabled then "" else "-") <> flagNameString name) (Map.toList (packageFlags package)) -- FIXME Chris: where does this come from now? , ["--ghc-options=-O2" | gconfigOptimize gconfig] , if wanted then concatMap (\x -> ["--ghc-options", T.unpack x]) (boptsGhcOptions bopts) else [] , map (("--extra-include-dirs=" ++) . T.unpack) (Set.toList (configExtraIncludeDirs config)) , map (("--extra-lib-dirs=" ++) . T.unpack) (Set.toList (configExtraLibDirs config)) ] where config = getConfig econfig bopts = bcoBuildOpts bco toFilePathNoTrailingSlash = dropTrailingPathSeparator . toFilePath docDir = case pkgVerDir of Nothing -> installRoot </> docdirSuffix Just dir -> installRoot </> docdirSuffix </> dir installRoot = case loc of Snap -> bcoSnapInstallRoot bco Local -> bcoLocalInstallRoot bco pkgVerDir = parseRelDir (packageIdentifierString (PackageIdentifier (packageName package) (packageVersion package)) ++ [pathSeparator]) depOptions = map toDepOption $ Set.toList deps where toDepOption = if envConfigCabalVersion econfig >= $(mkVersion "1.22") then toDepOption1_22 else toDepOption1_18 toDepOption1_22 gid = concat [ "--dependency=" , packageNameString $ packageIdentifierName $ ghcPkgIdPackageIdentifier gid , "=" , ghcPkgIdString gid ] toDepOption1_18 gid = concat [ "--constraint=" , packageNameString name , "==" , versionString version ] where PackageIdentifier name version = ghcPkgIdPackageIdentifier gid -- | Get set of wanted package names from locals. wantedLocalPackages :: [LocalPackage] -> Set PackageName wantedLocalPackages = Set.fromList . map (packageName . lpPackage) . filter lpWanted -- | Used for storage and comparison. newtype ModTime = ModTime (Integer,Rational) deriving (Ord,Show,Generic,Eq) instance Binary ModTime -- | One-way conversion to serialized time. modTime :: UTCTime -> ModTime modTime x = ModTime ( toModifiedJulianDay (utctDay x) , toRational (utctDayTime x)) data Installed = Library GhcPkgId | Executable PackageIdentifier deriving (Show, Eq, Ord)
hesselink/stack
src/Stack/Build/Types.hs
bsd-3-clause
20,984
0
19
6,472
3,961
2,166
1,795
462
7
module Web.RTBBidder.Types ( Banner(..) , Imp(..) , Request(..) , Bid(..) , SeatBid(..) , Response(..) , Bidder , RTBProtocol(..) ) where import qualified Network.Wai as WAI import Web.RTBBidder.Types.Request (Request(..)) import Web.RTBBidder.Types.Request.Imp (Imp(..)) import Web.RTBBidder.Types.Request.Banner (Banner(..)) import Web.RTBBidder.Types.Response (Response(..)) import Web.RTBBidder.Types.Response.Bid (Bid(..)) import Web.RTBBidder.Types.Response.SeatBid (SeatBid(..)) type Bidder = Request -> IO Response data RTBProtocol = RTBProtocol { rtbDecodeReq :: WAI.Request -> IO (Either String Request) , rtbEncodeRes :: Response -> IO WAI.Response }
hiratara/hs-rtb-bidder
src/Web/RTBBidder/Types.hs
bsd-3-clause
689
0
12
98
229
151
78
20
0
module TopOrLocal where topLevelFunction :: Integer -> Integer topLevelFunction x = x + woot + topLevelValue where woot :: Integer woot = 10 topLevelValue :: Integer topLevelValue = 5 area d = pi * (r * r) where r = d / 2 thirdLetter :: String -> Char thirdLetter x = x !! 2 letterIndex :: Int -> Char letterIndex x = s !! x where s = "Curry is awesome!"
renevp/hello-haskell
src/topOrLocal.hs
bsd-3-clause
376
0
7
92
130
71
59
14
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP, ForeignFunctionInterface #-} import Control.Concurrent (forkIO, threadWaitRead, threadWaitWrite) import Control.Monad (when, forever, liftM) import qualified Data.ByteString as B import Data.ByteString.Char8 (ByteString, pack) import Data.ByteString.Internal (toForeignPtr) import Foreign import Foreign.C.Types import Network.Socket (Socket(..), SocketType(..), AddrInfoFlag(..), SocketOption(..), accept, addrAddress, addrFamily, addrFlags, bindSocket, defaultProtocol, defaultHints, fdSocket, getAddrInfo, listen, setSocketOption, socket) import Network.Socket.Internal (throwSocketErrorIfMinus1RetryMayBlock) import Network.Socket.ByteString (recv, sendAll) import System.Environment (getArgs) main = do listenSock <- startListenSock forever $ do (sock, _) <- accept listenSock forkIO $ worker sock startListenSock :: IO Socket startListenSock = do args <- getArgs let portNumber = head args addrinfos <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just $ portNumber) let serveraddr = head addrinfos listenSock <- socket (addrFamily serveraddr) Stream defaultProtocol bindSocket listenSock $ addrAddress serveraddr setSocketOption listenSock ReuseAddr 1 listen listenSock listenQueueLength return listenSock where listenQueueLength :: Int listenQueueLength = 8192 worker :: Socket -> IO () worker sock = loop expectedRequestLength where loop :: Int -> IO () loop !left | left == 0 = do sendAll sock reply loop expectedRequestLength | otherwise = do bs' <- recv sock left if B.length bs' == 0 then return () else loop $ left - B.length bs' -- REPLY reply :: ByteString reply = B.append fauxHeader fauxIndex replyLen :: Int replyLen = B.length reply fauxHeader :: ByteString fauxHeader = pack s where s = "HTTP/1.1 200 OK\r\nDate: Tue, 09 Oct 2012 16:36:18 GMT\r\nContent-Length: 151\r\nServer: Mighttpd/2.8.1\r\nLast-Modified: Mon, 09 Jul 2012 03:42:33 GMT\r\nContent-Type: text/html\r\n\r\n" fauxIndex :: ByteString fauxIndex = pack s where s = "<html>\n<head>\n<title>Welcome to nginx!</title>\n</head>\n<body bgcolor=\"white\" text=\"black\">\n<center><h1>Welcome to nginx!</h1></center>\n</body>\n</html>\n" -- EXPECTED REQUEST expectedRequest :: ByteString expectedRequest = pack "GET / HTTP/1.1\r\nHost: 10.12.0.1:8080\r\nUser-Agent: weighttp/0.3\r\nConnection: keep-alive\r\n\r\n" expectedRequestLength :: Int expectedRequestLength = B.length expectedRequest
AndreasVoellmy/SimpleServer
SimpleServerByteString2.hs
bsd-3-clause
2,769
0
14
606
617
329
288
62
2
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Distance.CA.Tests ( tests ) where import Data.String import Prelude import Test.Tasty import Duckling.Distance.CA.Corpus import Duckling.Dimensions.Types import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "CA Tests" [ makeCorpusTest [Seal Distance] corpus ]
facebookincubator/duckling
tests/Duckling/Distance/CA/Tests.hs
bsd-3-clause
507
0
9
78
79
50
29
11
1
module Calc ( eval, evalStr, lit, add, mul, MinMax (MinMax), Mod7 (Mod7), testInteger, testBool, testMM, testSat ) where import ExprT import Parser -- Exercise 1 eval :: ExprT -> Integer eval (Lit n) = n eval (Add x y) = (eval x) + (eval y) eval (Mul x y) = (eval x) * (eval y) -- Exercise 2 evalStr :: String -> Maybe Integer evalStr s = fmap eval (parseExp Lit Add Mul s) -- Exercise 3 -- mul (add (lit 2) (lit 3)) (lit 4) :: ExprT == Mul (Add (Lit 2) (Lit 3)) (Lit 4) class Expr a where lit :: Integer -> a add :: a -> a -> a mul :: a -> a -> a instance Expr ExprT where lit = Lit add = Add mul = Mul -- Exercise 4 instance Expr Integer where lit = id add = (+) mul = (*) instance Expr Bool where lit x = x > 0 add x y = x || y mul x y = x && y newtype MinMax = MinMax Integer deriving (Eq, Show) newtype Mod7 = Mod7 Integer deriving (Eq, Show) instance Expr MinMax where lit = MinMax add (MinMax x) (MinMax y) = MinMax $ max x y mul (MinMax x) (MinMax y) = MinMax $ min x y instance Expr Mod7 where lit x = Mod7 $ mod x 7 add (Mod7 x) (Mod7 y) = Mod7 $ mod (x + y) 7 mul (Mod7 x) (Mod7 y) = Mod7 $ mod (x * y) 7 testExp :: Expr a => Maybe a testExp = parseExp lit add mul "(3 * -4) + 5" testInteger = testExp :: Maybe Integer testBool = testExp :: Maybe Bool testMM = testExp :: Maybe MinMax testSat = testExp :: Maybe Mod7
wangwangwar/cis194
src/ch5/Calc.hs
bsd-3-clause
1,484
0
9
454
611
327
284
56
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- Determine which packages are already installed module Stack.Build.Installed ( InstalledMap , Installed (..) , GetInstalledOpts (..) , getInstalled ) where import Control.Applicative import Control.Arrow ((&&&)) import Control.Monad import Control.Monad.Catch (MonadCatch, MonadMask) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Resource import Data.Conduit import qualified Data.Conduit.List as CL import Data.Function import qualified Data.HashSet as HashSet import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import qualified Data.Map.Strict as Map import Data.Maybe import Network.HTTP.Client.Conduit (HasHttpManager) import Path import Prelude hiding (FilePath, writeFile) import Stack.Build.Cache import Stack.Types.Build import Stack.Constants import Stack.GhcPkg import Stack.PackageDump import Stack.Types import Stack.Types.Internal type M env m = (MonadIO m,MonadReader env m,HasHttpManager env,HasEnvConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,MonadMask m,HasLogLevel env) data LoadHelper = LoadHelper { lhId :: !GhcPkgId , lhDeps :: ![GhcPkgId] , lhPair :: !(PackageName, (Version, InstallLocation, Installed)) -- TODO Version is now redundant and can be gleaned from Installed } deriving Show type InstalledMap = Map PackageName (Version, InstallLocation, Installed) -- TODO Version is now redundant and can be gleaned from Installed -- | Options for 'getInstalled'. data GetInstalledOpts = GetInstalledOpts { getInstalledProfiling :: !Bool -- ^ Require profiling libraries? , getInstalledHaddock :: !Bool -- ^ Require haddocks? } -- | Returns the new InstalledMap and all of the locally registered packages. getInstalled :: (M env m, PackageInstallInfo pii) => EnvOverride -> GetInstalledOpts -> Map PackageName pii -- ^ does not contain any installed information -> m ( InstalledMap , [DumpPackage () ()] -- globally installed , Map GhcPkgId PackageIdentifier -- locally installed ) getInstalled menv opts sourceMap = do snapDBPath <- packageDatabaseDeps localDBPath <- packageDatabaseLocal extraDBPaths <- packageDatabaseExtra bconfig <- asks getBuildConfig mcache <- if getInstalledProfiling opts || getInstalledHaddock opts then liftM Just $ loadInstalledCache $ configInstalledCache bconfig else return Nothing let loadDatabase' = loadDatabase menv opts mcache sourceMap (installedLibs0, globalInstalled) <- loadDatabase' Nothing [] (installedLibs1, _extraInstalled) <- (foldM (\lhs' pkgdb -> do lhs'' <- loadDatabase' (Just (ExtraGlobal, pkgdb)) (fst lhs') return lhs'') ((installedLibs0, globalInstalled)) extraDBPaths) (installedLibs2, _snapInstalled) <- loadDatabase' (Just (InstalledTo Snap, snapDBPath)) installedLibs1 (installedLibs3, localInstalled) <- loadDatabase' (Just (InstalledTo Local, localDBPath)) installedLibs2 let installedLibs = M.fromList $ map lhPair installedLibs3 case mcache of Nothing -> return () Just pcache -> saveInstalledCache (configInstalledCache bconfig) pcache -- Add in the executables that are installed, making sure to only trust a -- listed installation under the right circumstances (see below) let exesToSM loc = Map.unions . map (exeToSM loc) exeToSM loc (PackageIdentifier name version) = case Map.lookup name sourceMap of -- Doesn't conflict with anything, so that's OK Nothing -> m Just pii -- Not the version we want, ignore it | version /= piiVersion pii || loc /= piiLocation pii -> Map.empty | otherwise -> m where m = Map.singleton name (version, loc, Executable $ PackageIdentifier name version) exesSnap <- getInstalledExes Snap exesLocal <- getInstalledExes Local let installedMap = Map.unions [ exesToSM Local exesLocal , exesToSM Snap exesSnap , installedLibs ] return ( installedMap , globalInstalled , Map.fromList $ map (dpGhcPkgId &&& dpPackageIdent) localInstalled ) -- | Outputs both the modified InstalledMap and the Set of all installed packages in this database -- -- The goal is to ascertain that the dependencies for a package are present, -- that it has profiling if necessary, and that it matches the version and -- location needed by the SourceMap loadDatabase :: (M env m, PackageInstallInfo pii) => EnvOverride -> GetInstalledOpts -> Maybe InstalledCache -- ^ if Just, profiling or haddock is required -> Map PackageName pii -- ^ to determine which installed things we should include -> Maybe (InstalledPackageLocation, Path Abs Dir) -- ^ package database, Nothing for global -> [LoadHelper] -- ^ from parent databases -> m ([LoadHelper], [DumpPackage () ()]) loadDatabase menv opts mcache sourceMap mdb lhs0 = do wc <- getWhichCompiler (lhs1, dps) <- ghcPkgDump menv wc (fmap snd (maybeToList mdb)) $ conduitDumpPackage =$ sink let lhs = pruneDeps id lhId lhDeps const (lhs0 ++ lhs1) return (map (\lh -> lh { lhDeps = [] }) $ Map.elems lhs, dps) where conduitProfilingCache = case mcache of Just cache | getInstalledProfiling opts -> addProfiling cache -- Just an optimization to avoid calculating the profiling -- values when they aren't necessary _ -> CL.map (\dp -> dp { dpProfiling = False }) conduitHaddockCache = case mcache of Just cache | getInstalledHaddock opts -> addHaddock cache -- Just an optimization to avoid calculating the haddock -- values when they aren't necessary _ -> CL.map (\dp -> dp { dpHaddock = False }) sinkDP = conduitProfilingCache =$ conduitHaddockCache =$ CL.mapMaybe (isAllowed opts mcache sourceMap (fmap fst mdb)) =$ CL.consume sink = getZipSink $ (,) <$> ZipSink sinkDP <*> ZipSink CL.consume -- | Check if a can be included in the set of installed packages or not, based -- on the package selections made by the user. This does not perform any -- dirtiness or flag change checks. isAllowed :: PackageInstallInfo pii => GetInstalledOpts -> Maybe InstalledCache -> Map PackageName pii -> Maybe InstalledPackageLocation -> DumpPackage Bool Bool -> Maybe LoadHelper isAllowed opts mcache sourceMap mloc dp -- Check that it can do profiling if necessary | getInstalledProfiling opts && isJust mcache && not (dpProfiling dp) = Nothing -- Check that it has haddocks if necessary | getInstalledHaddock opts && isJust mcache && not (dpHaddock dp) = Nothing | toInclude = Just LoadHelper { lhId = gid , lhDeps = -- We always want to consider the wired in packages as having all -- of their dependencies installed, since we have no ability to -- reinstall them. This is especially important for using different -- minor versions of GHC, where the dependencies of wired-in -- packages may change slightly and therefore not match the -- snapshot. if name `HashSet.member` wiredInPackages then [] else dpDepends dp , lhPair = (name, (version, toPackageLocation mloc, Library ident gid)) } | otherwise = Nothing where toPackageLocation :: Maybe InstalledPackageLocation -> InstallLocation toPackageLocation Nothing = Snap toPackageLocation (Just ExtraGlobal) = Snap toPackageLocation (Just (InstalledTo loc)) = loc toInclude = case Map.lookup name sourceMap of Nothing -> case mloc of -- The sourceMap has nothing to say about this global -- package, so we can use it Nothing -> True Just ExtraGlobal -> True -- For non-global packages, don't include unknown packages. -- See: -- https://github.com/commercialhaskell/stack/issues/292 Just _ -> False Just pii -> version == piiVersion pii -- only accept the desired version && checkLocation (piiLocation pii) -- Ensure that the installed location matches where the sourceMap says it -- should be installed checkLocation Snap = mloc /= Just (InstalledTo Local) -- we can allow either global or snap checkLocation Local = mloc == Just (InstalledTo Local) || mloc == Just ExtraGlobal -- 'locally' installed snapshot packages can come from extra dbs gid = dpGhcPkgId dp ident@(PackageIdentifier name version) = dpPackageIdent dp
rrnewton/stack
src/Stack/Build/Installed.hs
bsd-3-clause
9,835
9
20
2,971
1,804
982
822
174
8
-- File created: 2009-07-20 13:30:25 module Haschoo.Evaluator.Standard.IO (procedures) where import Control.Arrow ((&&&)) import Control.Exception (bracket) import Control.Monad (liftM2) import Data.Array.IArray (elems) import Data.Array.MArray (getElems) import System.IO ( Handle, IOMode(..), stdin, stdout , openFile, hClose, hIsEOF , hGetChar, hLookAhead, hReady , hPutStr, hPutStrLn, hPutChar) import Haschoo.Parser (runParser, value) import Haschoo.Types ( ScmValue(..), scmShow, scmShowWith , isAggregate) import Haschoo.Utils (ErrOr, ($<), (.:)) import Haschoo.Evaluator.Utils ( tooFewArgs, tooManyArgs , notProcedure, notString, notChar) import Haschoo.Evaluator.Standard.Strings (isString, strToList) procedures :: [(String, ScmValue)] procedures = map (\(a,b) -> (a, ScmFunc a b)) [ ("port?", return . fmap ScmBool . scmIsPort) , "input-port?" $< id &&& return .: fmap ScmBool .: scmIsInputPort , "output-port?" $< id &&& return .: fmap ScmBool .: scmIsOutputPort , ("eof-object?", return . fmap ScmBool . scmIsEof) , "call-with-input-file" $< id &&& scmCallWithFile ReadMode ScmInput , "call-with-output-file" $< id &&& scmCallWithFile WriteMode ScmOutput , "current-input-port" $< id &&& flip constant (return $ ScmInput stdin) , "current-output-port" $< id &&& flip constant (return $ ScmOutput stdout) , "open-input-file" $< id &&& scmOpenFile ReadMode ScmInput , "open-output-file" $< id &&& scmOpenFile WriteMode ScmOutput , ("close-input-port", scmCloseInputPort) , ("close-output-port", scmCloseOutputPort) , "read" $< id &&& \s -> withInput 0 s (constant s . scmRead) , "read-char" $< id &&& \s -> withInput 0 s (constant s . scmReadChar) , "peek-char" $< id &&& \s -> withInput 0 s (constant s . scmPeekChar) , "char-ready" $< id &&& \s -> withInput 0 s (constant s . scmCharReady) , "write" $< id &&& \s -> withOutput 1 s scmWrite , "display" $< id &&& \s -> withOutput 1 s scmDisplay , "newline" $< id &&& \s -> withOutput 0 s (constant s . scmNewline) , "write-char" $< id &&& \s -> withOutput 1 s scmWriteChar ] scmIsInputPort, scmIsOutputPort :: String -> [ScmValue] -> ErrOr Bool scmIsInputPort _ [ScmInput _] = Right True scmIsInputPort _ [_] = Right False scmIsInputPort s [] = tooFewArgs s scmIsInputPort s _ = tooManyArgs s scmIsOutputPort _ [ScmOutput _] = Right True scmIsOutputPort _ [_] = Right False scmIsOutputPort s [] = tooFewArgs s scmIsOutputPort s _ = tooManyArgs s scmIsPort :: [ScmValue] -> ErrOr Bool scmIsPort x = liftM2 (||) (scmIsInputPort "port?" x) (scmIsOutputPort "port?" x) scmIsEof :: [ScmValue] -> ErrOr Bool scmIsEof [ScmEOF] = Right True scmIsEof [_] = Right False scmIsEof [] = tooFewArgs "eof-object?" scmIsEof _ = tooManyArgs "eof-object?" scmCallWithFile :: IOMode -> (Handle -> ScmValue) -> String -> [ScmValue] -> IO (ErrOr ScmValue) scmCallWithFile mode toPort _ [s, ScmFunc _ f] | isString s = do path <- strToList s bracket (openFile path mode) hClose (f . (:[]) . toPort) scmCallWithFile _ _ s [_, ScmFunc _ _] = return$ notString s scmCallWithFile _ _ s [_,_] = return$ notProcedure s scmCallWithFile _ _ s (_:_:_) = return$ tooManyArgs s scmCallWithFile _ _ s _ = return$ tooFewArgs s scmOpenFile :: IOMode -> (Handle -> ScmValue) -> String -> [ScmValue] -> IO (ErrOr ScmValue) scmOpenFile mode toPort _ [s] | isString s = do path <- strToList s fmap (Right . toPort) (openFile path mode) scmOpenFile _ _ s [_] = return$ notString s scmOpenFile _ _ s [] = return$ tooFewArgs s scmOpenFile _ _ s _ = return$ tooManyArgs s scmCloseInputPort, scmCloseOutputPort :: [ScmValue] -> IO (ErrOr ScmValue) scmCloseInputPort [ScmInput h] = hClose h >> return (Right ScmVoid) scmCloseInputPort [_] = return$ notInput "close-input-port" scmCloseInputPort [] = return$ tooFewArgs "close-input-port" scmCloseInputPort _ = return$ tooManyArgs "close-input-port" scmCloseOutputPort [ScmOutput h] = hClose h >> return (Right ScmVoid) scmCloseOutputPort [_] = return$ notOutput "close-output-port" scmCloseOutputPort [] = return$ tooFewArgs "close-output-port" scmCloseOutputPort _ = return$ tooManyArgs "close-output-port" -- Meh, this is a pain. The parser is pure so we'd basically need to give it -- the result of hGetContents; but that breaks any further input ("semi-closes" -- the handle). So just read a char at a time until we get a successful parse. -- -- The spec doesn't say what to do if we get nonsense like anything starting -- with ")", so we choose to loop forever (or until EOF). -- -- O(n^2 + np) where n is the length of the input and p the time it takes for a -- parse. scmRead :: Handle -> IO ScmValue scmRead hdl = go [] where go s = do eof <- hIsEOF hdl if eof then return ScmEOF else do c <- hGetChar hdl let s' = s ++ [c] either (const $ go s') return (runParser value "" s') scmReadChar, scmPeekChar, scmCharReady :: Handle -> IO ScmValue scmReadChar = fmap ScmChar . hGetChar scmPeekChar = fmap ScmChar . hLookAhead scmCharReady = fmap ScmBool . hReady scmWrite, scmDisplay :: Handle -> [ScmValue] -> IO (ErrOr ScmValue) scmWrite = scmPrint scmShow "write" scmDisplay = scmPrint f "display" where f (ScmString s) = return (elems s) f (ScmMString s) = getElems s f (ScmChar c) = return [c] f x | isAggregate x = scmShowWith f x | otherwise = scmShow x scmPrint :: (ScmValue -> IO String) -> String -> Handle -> [ScmValue] -> IO (ErrOr ScmValue) scmPrint f _ h [x] = f x >>= hPutStr h >> return (Right ScmVoid) scmPrint _ s _ [] = return$ tooFewArgs s scmPrint _ s _ _ = return$ tooManyArgs s scmNewline :: Handle -> IO ScmValue scmNewline h = hPutStrLn h "" >> return ScmVoid scmWriteChar :: Handle -> [ScmValue] -> IO (ErrOr ScmValue) scmWriteChar h [ScmChar c] = hPutChar h c >> return (Right ScmVoid) scmWriteChar _ [_] = return$ notChar "write-char" scmWriteChar _ [] = return$ tooFewArgs "write-char" scmWriteChar _ _ = return$ tooManyArgs "write-char" ----- notInput, notOutput :: String -> ErrOr a notInput = fail . ("Non-input-port argument to " ++) notOutput = fail . ("Non-output-port argument to " ++) constant :: String -> IO ScmValue -> [ScmValue] -> IO (ErrOr ScmValue) constant _ x [] = fmap Right x constant s _ _ = return$ tooManyArgs s -- These take advantage of the fact that the port is always the last argument -- -- withInput does an EOF check as well withInput, withOutput :: Int -> String -> (Handle -> [ScmValue] -> IO (ErrOr ScmValue)) -> [ScmValue] -> IO (ErrOr ScmValue) withInput idx s f = withPort stdin apply idx s f where apply (ScmInput h) xs = do eof <- hIsEOF h if eof then return$ Right ScmEOF else f h xs apply _ _ = return$ notInput s withOutput idx s f = withPort stdout apply idx s f where apply (ScmOutput h) = f h apply _ = const.return$ notOutput s withPort :: Handle -> (ScmValue -> ([ScmValue] -> IO (ErrOr ScmValue))) -> Int -> String -> (Handle -> [ScmValue] -> IO (ErrOr ScmValue)) -> [ScmValue] -> IO (ErrOr ScmValue) withPort defaultHdl apply idx s f args = let (xs, p) = splitAt idx args in case p of [x] -> apply x xs [] -> f defaultHdl xs _ -> return$ tooManyArgs s
Deewiant/haschoo
Haschoo/Evaluator/Standard/IO.hs
bsd-3-clause
7,960
0
16
2,116
2,646
1,363
1,283
148
4
{- | Module : Main Description : Saeplog web server Copyright : (c) Sebastian Witte License : BSD3 Maintainer : [email protected] Stability : experimental -} module Main where import System.Exit import System.IO import Web.RBB (rbb) main :: IO () main = rbb $ do mapM_ (hPutStrLn stderr) [ "" , "You do not seem to have configured your web site at all!" , "" , "As you should decide how your site is going to look like, the" , "default configuration does not do anything other than printing" , "this help text." , "" , "To get you started on creating your own website with haskell and" , "this blogging library, check out the documentation on github:" , " https://github.com/saep/repo-based-blog" , "" ] exitFailure
saep/repo-based-blog
executable/Main.hs
bsd-3-clause
855
0
10
260
94
55
39
19
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Rules.NB ( rules ) where import Duckling.Dimensions.Types import qualified Duckling.AmountOfMoney.NB.Rules as AmountOfMoney import qualified Duckling.Duration.NB.Rules as Duration import qualified Duckling.Numeral.NB.Rules as Numeral import qualified Duckling.Ordinal.NB.Rules as Ordinal import qualified Duckling.Time.NB.Rules as Time import qualified Duckling.TimeGrain.NB.Rules as TimeGrain import Duckling.Types rules :: Some Dimension -> [Rule] rules (This Distance) = [] rules (This Duration) = Duration.rules rules (This Numeral) = Numeral.rules rules (This Email) = [] rules (This AmountOfMoney) = AmountOfMoney.rules rules (This Ordinal) = Ordinal.rules rules (This PhoneNumber) = [] rules (This Quantity) = [] rules (This RegexMatch) = [] rules (This Temperature) = [] rules (This Time) = Time.rules rules (This TimeGrain) = TimeGrain.rules rules (This Url) = [] rules (This Volume) = []
rfranek/duckling
Duckling/Rules/NB.hs
bsd-3-clause
1,282
0
7
186
330
191
139
27
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. module Duckling.Time.VI.Tests ( tests ) where import Data.String import Prelude import Test.Tasty import Duckling.Dimensions.Types import Duckling.Time.VI.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "VI Tests" [ makeCorpusTest [This Time] corpus ]
rfranek/duckling
tests/Duckling/Time/VI/Tests.hs
bsd-3-clause
590
0
9
95
80
51
29
11
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | Utilities for syntactic processing of URLs. module Network.SPDY.Url where import Data.String (IsString) import Network (HostName) import Network.Socket (PortNumber) -- | A web origin, as defined in RFC 6454. data Origin = Origin { originScheme :: Scheme , originHost :: Host , originPort :: PortNumber } deriving (Eq, Ord, Show) -- | The scheme part of a URI. newtype Scheme = Scheme String deriving (Eq, Ord, Show, IsString) -- | The host part of a URI. newtype Host = Host String deriving (Eq, Ord, Show, IsString) toHostName :: Host -> HostName toHostName (Host host) = host
kcharter/spdy-base
src/Network/SPDY/Url.hs
bsd-3-clause
678
0
8
152
159
94
65
12
1
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings, FlexibleInstances #-} {-# LANGUAGE ViewPatterns, TupleSections #-} -- | -- Copyright : 2012 Eric Kow (Computational Linguistics Ltd.) -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Discourse history tracking. The history module provides an -- abstraction representation of what has already been said during refex -- generation and a number of queries that would help the refex -- generator to steer its decsions module NLP.Antfarm.History where import Control.Applicative ((<$>)) import Data.List ( foldl', elemIndex, delete ) import Data.Maybe ( isJust, mapMaybe ) import Data.Text ( Text ) import Data.Tree ( Tree(..), flatten ) import Prelude hiding ( lex ) import qualified Data.Set as Set import qualified Data.Map as Map import NLP.Antfarm.Refex -- | A 'RefGroup' is considered to refer exactly to its indices if it -- has no bounds information or examples associated with it. isExact :: RefGroup -> Bool isExact rg = rgBounds rg == emptyBounds -- | A discourse unit that would refer to just an element mkSingletonDu :: RefKey -> DiscourseUnit mkSingletonDu (c,i) = Node (RefGroup c (Set.singleton i) emptyBounds) [] {- Note [discourse tree] ~~~~~~~~~~~~~~~~~~~~~ Our notion of a discourse unit is a tree of a RefGroup and its examples (and their examples, etc). When we enter such a unit into the history, we also enter all of the examples as separate entries at the same time. This facilitates queries on the units, and also affects the counts. For example, if we say “two atoms (a carbon and an oxygen)” we can consider the oxygen to have already beeen referenced once so when we bring up another oxygen, we say “another oxygen” accounting for the fact that oxygen had already been mentioned once -} instance Ord (Tree RefGroup) where compare (Node r1 ks1) (Node r2 ks2) = case compare r1 r2 of EQ -> compare ks1 ks2 x -> x -- | The discoure history keeps track of decisions we have already made -- about how to realise previous parts of the referring expression. -- This sort of information can help us to make more fluent decisions -- on how to realise the current fragment data RefHistory = RefHistory { -- | How many times a 'DiscourseUnit' has been mentioned rhCount :: Map.Map DiscourseUnit RefCount -- | For each class: an ordering of indices that reflects what -- ordinal expression should be used for them (if at all) -- -- So @[c8,c3,c4]@ means -- -- c8: the first -- c3: the second -- c4: the third , rhOrder :: Map.Map Text [Text] } type RefCount = Int -- | Discourse history without any objects emptyHistory :: RefHistory emptyHistory = RefHistory Map.empty Map.empty -- ---------------------------------------------------------------------- -- * building the discourse history -- ---------------------------------------------------------------------- -- See note `discourse tree' -- -- | Take note of the fact that these discourse units have been mentioned -- (again) in the history. -- -- You probably want to realise the units first, then add them to the -- history. addToHistory :: [DiscourseUnit] -> RefHistory -> RefHistory addToHistory ks st = st { -- incr number of mentions for each mention of an -- entity in the expression rhCount = foldl' plusOne (rhCount st) (concatMap subtrees ks) -- note ordinal position (eg. 1st, 2nd) of any new singleton -- instances of each entity type we see , rhOrder = foldl' addOrdinal (rhOrder st) (concatMap duSingletons ks) } where -- | incr ref counts of 'k' in 'm' plusOne m k = Map.insertWith' (+) k 1 m -- | note ordinal position of instances 'i' (relative to other members -- of class 'c'), but only if this is the first mention of it addOrdinal m (c,i) = Map.insertWith' append c [i] m where append new old = if all (`elem` old) new then old else old ++ new -- | Individuals mentioned in a discourse unit -- (see 'refSingleton') duSingletons :: DiscourseUnit -> [RefKey] duSingletons = mapMaybe refSingleton . flatten -- | A 'refSingleton' is an instance that appears by itself in a 'RefGroup' -- without other items or constraints that imply that there could be other -- items refSingleton :: RefGroup -> Maybe RefKey refSingleton (RefGroup c is bnds) = case Set.toList is of [i] -> if kosher bnds then Just (c,i) else Nothing _ -> Nothing where -- either no bounds information, or “exactly 1" are acceptable kosher (Bounds [] Nothing Nothing) = True kosher (Bounds [] (Just 1) (Just 1)) = True kosher _ = False -- | If a RefGroup has explicit constraints, augment them with the -- implicit constraints that arise from treating each item -- as evidence of an at least constraint -- -- It's a good idea to run this once when building 'RefGroup's, -- but you may also decide that this sort of behaviour is not -- desirable for your application, so it's off by default noteImplicitBounds :: RefGroup -> RefGroup noteImplicitBounds rg = if implicits > 0 then rg { rgBounds = bounds2 } else rg where bounds1 = rgBounds rg bounds2 = -- We only ever modify the lower bound constraints: -- -- * if there's a lower bound constraint, raise it to -- the number of implicits (as needed) -- * otherwise, set the lower bound (but only if we -- already have an explicit constraint, in the form -- of an upper bound) -- -- Note also we don't bother to verify that upper bounds -- make sense wrt their lower bounds case bLower bounds1 of Just l -> bounds1 { bLower = Just (max l implicits) } Nothing -> if isJust (bUpper bounds1) then bounds1 { bLower = Just implicits } else bounds1 implicits = Set.size (rgIdxes rg) -- ---------------------------------------------------------------------- -- * query -- ---------------------------------------------------------------------- -- | @hasDistractorGroup st k@ returns whether or not the discourse history -- @st@ contains a group with distractors to @k@. -- -- See 'distractorGroups' for more details hasDistractorGroup :: RefHistory -> RefKey -> Bool hasDistractorGroup st k = not . null $ distractorGroups st k -- | @distractorGroups st k@ returns all the distractor groups for @k@ -- in the discourse history. -- -- A distractor is defined (here) as something that has the the same class -- as @k@ but a different index, basically anything that might be confused -- for the object in question distractorGroups :: RefHistory -> RefKey -> [DiscourseUnit] distractorGroups st (c, i) = filter distracting (Map.keys (rhCount st)) where distracting = not . safe safe (Node rg2 _) = c /= rgClass rg2 -- different classes (OK) || i `Set.member` rgIdxes rg2 -- includes me (OK) || isClasswide rg2 -- classes aren't instances (OK) -- | @hasSupersetMention st g@ returns whether or not the discourse history -- contains a group that includes all members of @g@ -- -- Note that if a group has already occured in the discourse history, this -- returns a True (ie. not a strict superset) hasSupersetMention :: RefHistory -> DiscourseUnit -> Bool hasSupersetMention st k = not . Map.null . rhCount $ supersetMentions k st -- | @supersetMentions g st@ returns the portion of discourse history @st@ -- in which all groups are supersets of @g@ (inclusive, not strict super) supersetMentions :: DiscourseUnit -> RefHistory -> RefHistory supersetMentions (Node g _) h = h { rhCount = Map.filterWithKey hasK (rhCount h) } where hasK (Node g2 _) _ = rgClass g == rgClass g2 && rgIdxes g `Set.isSubsetOf` rgIdxes g2 -- | @lastMention st k@ returns the number of times @k@ has been mentioned lastMention :: RefHistory -> RefKey -> Int lastMention st (c,i) = sum . Map.elems . rhCount $ supersetMentions (mkSingletonDu (c,i)) st -- | @lastMention st g@ returns the number of times the group @g@ has been -- mentioned lastMentions :: RefHistory -> DiscourseUnit -> Int lastMentions st k = Map.findWithDefault 0 k (rhCount st) -- | True if the given instance @k@ has never been mentioned before isFirstMention :: RefHistory -> RefKey -> Bool isFirstMention st k = lastMention st k == 0 -- ---------------------------------------------------------------------- -- * subtle queries -- ---------------------------------------------------------------------- -- | If it makes sense to refer to a key using an ordinal expression, -- the order we should assign it (Nothing if we either can't sensibly -- assign one, or the history does not give us enough information to -- do so) mentionOrder :: RefHistory -> RefKey -> Maybe Int mentionOrder rh (c,i) = if isOnlySingletons rh then case Map.lookup c (rhOrder rh) of -- +1 is for natural language (we don't say "zeroth") Just is | length is > 1 -> (+ 1) <$> elemIndex i is _ -> Nothing else Nothing where -- the c's never appear with others of their own kind in the same -- 'RefGroup' [we want to be able to say things like "the 5th ant" -- but we haven't yet worked out how this would work if 'ant' has -- already appeared in expressions like "the 3 ants"... in that -- case, what does 5th mean?] isOnlySingletons = not . any isMultiMatch . Map.keys . rhCount -- if a refgroup is of the given class (and has more than one elm) isMultiMatch (Node g _) = c == rgClass g && Set.size (rgIdxes g) > 1 -- | Is a subset of a previously mentioned group @g@ where there are no -- distractors to @g@ in the discourse history hasTidyBackpointer :: RefHistory -> DiscourseUnit -> Bool hasTidyBackpointer st du@(Node rg _) = not (any (hasDistractorGroup st) keys) -- (tidy) nothing to confuse w du && lastMentions st du == 0 -- (tidy) first time we mentioned du && hasSupersetMention st du -- (backpointer) but we already mentioned -- a group that includes all members of du where -- keys are just class/idx tuples ('a', '3') for example keys = Set.toList (refKeys rg) -- | @isTheOther st k@ returns whether or not there is a two-member group in -- the discourse history which @k@ is a member of such that the other -- member has already been mentioned as a part of a singleton group. -- -- The idea is that if you have said "one of the X", you will want to say -- "the other X" for the other member of that group isTheOther :: RefHistory -> RefKey -> Bool isTheOther st (c,i) = any isBuddy $ Map.keys (rhCount st) where isBuddy (Node g2 []) | isExact g2 && c == rgClass g2 = -- the other instance was mentioned at least once case getBuddy (rgIdxes g2) of Just b -> lastMentions st (mkSingletonDu (c,b)) >= 1 Nothing -> False isBuddy _ = False -- only trigger this for classes where they've been exactly -- two instances ["the ant, the other ant" is fine, but -- "the ant, a second ant, the other ant" is confusing... -- which other ant?] getBuddy (Set.toList -> idx) | length idx == 2 = case delete i idx of [b] -> Just b -- must be *exactly* one other item _ -> Nothing getBuddy _ = Nothing -- | Is the class itself, not any individual entity within that class -- ie. “ants” instead of “an ant” or “some ants” -- -- By convention, any group which containts no indices or constraints -- is considered to be classwide. isClasswide :: RefGroup -> Bool isClasswide rg = Set.null (rgIdxes rg) && isExact rg -- ---------------------------------------------------------------------- -- * odds and ends -- ---------------------------------------------------------------------- -- | Like 'flatten', but returns whole subtrees instead of -- just nodes: -- -- > a(b c(d e(f g)) h) -- > b -- > c(d e(f g)) -- > d -- > e(f g) -- > f -- > g -- > h -- -- Invariant: @map rootLabel (subtrees x) == flatten x@ subtrees :: Tree a -> [Tree a] subtrees t = grab t [] where grab st@(Node _ ts) xs = st : foldr grab xs ts mkLeaf :: a -> Tree a mkLeaf x = Node x [] fst3 :: (a, b, c) -> a fst3 (x, _, _) = x snd3 :: (a, b, c) -> b snd3 (_, y, _) = y thd3 :: (a, b, c) -> c thd3 (_, _, z) = z
kowey/antfarm
NLP/Antfarm/History.hs
bsd-3-clause
12,781
0
15
3,094
2,044
1,137
907
129
5
module Main where import Data.Maybe import Data.List import qualified Data.ByteString.Lazy.Char8 as B import System.Environment import System.Exit import System.Process import System.IO import Lib import Opts import Check produceAST :: [Flag] -> IO () produceAST flags = do pipeBinary lang $ compileToJSON pat where (Language lang) = fromMaybe (Language "echo") (find isLanguage flags) (Pattern pat) = fromJust $ find isPattern flags pipeBinary :: String -> B.ByteString -> IO a pipeBinary name ast = do dir <- fromMaybe "./langs" <$> lookupEnv "REVM_ROOT" (stdin, stdout, stderr, procHandle) <- createProcess $ (shell $ dir ++ "/lang-" ++ name) { std_in = CreatePipe } B.hPutStrLn (fromJust stdin) ast exitCode <- waitForProcess procHandle exitWith exitCode main :: IO () main = do result <- getArgs >>= programOpts let errs = filter (getCheck result) checks if not $ null errs then printUsage $ concatMap checkMessage errs else let (opts, _) = result in produceAST opts
forestbelton/revm
app/Main.hs
bsd-3-clause
1,063
0
13
238
362
184
178
31
2
{-# LANGUAGe BangPatterns #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGe TemplateHaskell #-} module Mandelbrot.NikolaV4 (mandelbrotImageGenerator) where import Data.IORef import Data.Int import Data.Word import Data.Array.Nikola.Backend.CUDA.TH import Data.Array.Repa import Data.Array.Repa.Eval import Data.Array.Repa.Mutable import Data.Array.Repa.Repr.ForeignPtr as F import Data.Array.Repa.Repr.UnboxedForeign as UF import Data.Array.Repa.Repr.CUDA.UnboxedForeign as CUF import qualified Data.Vector.UnboxedForeign as VUF import qualified Data.Vector.Storable as V import qualified Mandelbrot.NikolaV4.Implementation as I type R = Double type Complex = (R, R) type RGBA = Word32 type Bitmap r = Array r DIM2 RGBA type MBitmap r = MArray r DIM2 RGBA type ComplexPlane r = Array r DIM2 Complex type MComplexPlane r = MArray r DIM2 Complex type StepPlane r = Array r DIM2 (Complex, Int32) type MStepPlane r = MArray r DIM2 (Complex, Int32) prettyMandelbrot :: Int32 -> StepPlane CUF -> MBitmap CUF -> IO () prettyMandelbrot = $(compile I.prettyMandelbrot) mandelbrot :: R -> R -> R -> R -> Int32 -> Int32 -> Int32 -> MComplexPlane CUF -> MStepPlane CUF -> IO () mandelbrot = $(compile I.mandelbrot) type MandelFun = R -> R -> R -> R -> Int -> Int -> Int -> IO (Bitmap F) data MandelState = MandelState { manDim :: DIM2 , manMBmapH :: MVec UF RGBA , manMBmapD :: MBitmap CUF , manMCs :: MComplexPlane CUF , manMZs :: MStepPlane CUF } mandelbrotImageGenerator :: IO MandelFun mandelbrotImageGenerator = do state <- newState (ix2 0 0) stateRef <- newIORef state return $ mandelbrotImage stateRef where mandelbrotImage :: IORef MandelState -> MandelFun mandelbrotImage stateRef lowx lowy highx highy viewx viewy depth = do let sh = ix2 viewy viewx state <- updateState stateRef sh let mbmapH = manMBmapH state mbmapD = manMBmapD state mcs = manMCs state mzs = manMZs state mandelbrot lowx' lowy' highx' highy' viewx' viewy' depth' mcs mzs zs <- unsafeFreezeMArray mzs prettyMandelbrot depth' zs mbmapD bmapD <- unsafeFreezeMArray mbmapD loadHostP bmapD mbmapH bmapH <- unsafeFreezeMVec sh mbmapH return (convertBitmap bmapH) where lowx', lowy', highx', highy' :: R lowx' = realToFrac lowx lowy' = realToFrac lowy highx' = realToFrac highx highy' = realToFrac highy viewx', viewy', depth' :: Int32 viewx' = fromIntegral viewx viewy' = fromIntegral viewy depth' = fromIntegral depth convertBitmap :: Bitmap UF -> Bitmap F convertBitmap bmap = let VUF.V_Word32 v = UF.toUnboxedForeign bmap (fp, _) = V.unsafeToForeignPtr0 v in F.fromForeignPtr (extent bmap) fp newState :: DIM2 -> IO MandelState newState sh = do mbmapH <- newMVec (size sh) mbmapD <- newMArray sh mcs <- newMArray sh mzs <- newMArray sh return $ MandelState sh mbmapH mbmapD mcs mzs updateState :: IORef MandelState -> DIM2 -> IO MandelState updateState stateRef sh = do state <- readIORef stateRef if manDim state == sh then return state else do state' <- newState sh writeIORef stateRef state' return state'
mainland/nikola
examples/mandelbrot/Mandelbrot/NikolaV4.hs
bsd-3-clause
3,685
0
15
1,159
994
520
474
102
2
module Test.WVar where import qualified Test.Hspec as HS import qualified Test.QuickCheck as Q import qualified Control.Concurrent.WVar as WV import qualified Control.Monad as M withLatestCache :: (IO (v, v, WV.WVar v, WV.WCached v) -> r) -> IO (v, WV.WVar v) -> r withLatestCache f prepare = f prepare' where prepare' = do (val, wv) <- prepare wc <- WV.cacheWVar wv return (val, val, wv, wc) whenWVarIsFresh :: (IO (Int, WV.WVar Int) -> HS.Spec) -> HS.Spec whenWVarIsFresh f = HS.describe "when WVar is fresh" $ f prepare where prepare = do val <- Q.generate Q.arbitrary wv <- WV.newWVar val return (val, wv) whenWVarIsUpdating :: Q.Arbitrary v => (IO (v, WV.WVar v) -> HS.Spec) -> HS.Spec whenWVarIsUpdating f = HS.describe "when WVar is updating" $ f prepare where prepare = do val <- Q.generate Q.arbitrary wv <- WV.newWVar val M.void $ WV.takeWVar wv return (val, wv) whenWVarIsFreshButCacheStaled :: (Eq v, Q.Arbitrary v) => (IO (v, v, WV.WVar v, WV.WCached v) -> HS.Spec) -> HS.Spec whenWVarIsFreshButCacheStaled f = HS.describe "when WVar is fresh but cache staled" $ f prepare where prepare = do val1 <- Q.generate Q.arbitrary val2 <- Q.generate $ Q.arbitrary `Q.suchThat` (/= val1) wv <- WV.newWVar val1 wc <- WV.cacheWVar wv WV.putWVar wv val2 return (val1, val2, wv, wc) whenWVarIsUpdatingAndCacheStaled :: (Eq v, Q.Arbitrary v) => (IO (v, v, WV.WVar v, WV.WCached v) -> HS.Spec) -> HS.Spec whenWVarIsUpdatingAndCacheStaled f = HS.describe "when WVar is updating and cache staled" $ f prepare where prepare = do val <- Q.generate Q.arbitrary wv <- WV.newWVar val wc <- WV.cacheWVar wv M.void $ WV.takeWVar wv return (val, val, wv, wc)
asakamirai/kazura-queue
test/Test/WVar.hs
bsd-3-clause
1,902
0
12
519
723
367
356
48
1
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeFamilies #-} module Snap.Snaplet.HTTPAuth.Types.IAuthDataSource ( IAuthDataSource (..), AuthDataWrapper (..), wrapDataSource ) where import qualified Data.Configurator.Types as CT import Data.Text (Text) import Snap.Snaplet.HTTPAuth.Types.AuthHeader import Snap.Snaplet.HTTPAuth.Types.AuthUser ------------------------------------------------------------------------ class IAuthDataSource r where getUser :: r -> AuthHeaderWrapper -> IO (Maybe AuthUser) validateUser :: r -> [String] -> AuthUser -> Bool ------------------------------------------------------------------------ -- | A wrapper around an object that implements the IAuthDataSource class. -- Contains a tuple of two functions: -- (getUser) a function that takes a Maybe AuthHeaderWrapper and returns -- a Maybe AuthUser, -- and (validateUser) a function that takes a list of roles specific to -- the Handler, and an AuthUser. It returns True if the user is allowed -- to run this handler, and False if not. data AuthDataWrapper = AuthDataWrapper { authDataUnwrap :: (AuthHeaderWrapper -> IO (Maybe AuthUser), [String] -> AuthUser -> Bool) } -- | Wraps up an arbitrary IAuthDataSource value as an AuthDataWrapper -- so that it can be packaged in a list of AuthDataWrappers, which is -- easy to pass to validation methods. wrapDataSource :: (IAuthDataSource r) => r -- ^ A value of class IAuthDataSource. -> AuthDataWrapper -- ^ A container for an arbitrary object of class IAuthDataSource. wrapDataSource b = AuthDataWrapper (getUser b, validateUser b)
anchor/snaplet-httpauth
lib/Snap/Snaplet/HTTPAuth/Types/IAuthDataSource.hs
bsd-3-clause
1,807
0
13
334
220
137
83
24
1
{-# LANGUAGE OverloadedStrings #-} {-| Module : Foreign.Lua.Userdata Copyright : © 2007–2012 Gracjan Polak, 2012–2016 Ömer Sinan Ağacan, 2017-2019 Albert Krewinkel License : MIT Maintainer : Albert Krewinkel <[email protected]> Stability : beta Portability : non-portable (depends on GHC) Convenience functions to convert Haskell values into Lua userdata. The main purpose of this module is to allow fast and simple creation of instances for @'Peekable'@ and @'Pushable'@. E.g., given a data type Person > data Person = Person { name :: String, age :: Int } > deriving (Eq, Show, Typeable, Data) we can simply do > instance Lua.Peekable Person where > safePeek = safePeekAny > > instance Lua.Pushable Person where > push = pushAny The other functions can be used to exert more control over the userdata wrapping and unwrapping process. -} module Foreign.Lua.Userdata ( pushAny , pushAnyWithMetatable , toAny , toAnyWithName , peekAny , ensureUserdataMetatable , metatableName ) where -- import Control.Applicative (empty) import Control.Monad (when) import Data.Data (Data, dataTypeName, dataTypeOf) import Foreign.Lua.Core (Lua) import Foreign.Lua.Types.Peekable (reportValueOnFailure) import qualified Foreign.Lua.Core as Lua import qualified Foreign.C as C import qualified Foreign.Ptr as Ptr import qualified Foreign.StablePtr as StablePtr import qualified Foreign.Storable as Storable -- | Push data by wrapping it into a userdata object. pushAny :: Data a => a -> Lua () pushAny x = let name = metatableName x pushMetatable = ensureUserdataMetatable name (return ()) in pushAnyWithMetatable pushMetatable x -- | Push data by wrapping it into a userdata object, using the object at the -- top of the stack after performing the given operation as metatable. pushAnyWithMetatable :: Lua () -- ^ operation to push the metatable -> a -- ^ object to push to Lua. -> Lua () pushAnyWithMetatable mtOp x = do xPtr <- Lua.liftIO (StablePtr.newStablePtr x) udPtr <- Lua.newuserdata (Storable.sizeOf xPtr) Lua.liftIO $ Storable.poke (Ptr.castPtr udPtr) xPtr mtOp Lua.setmetatable (Lua.nthFromTop 2) return () -- | Push the metatable used to define the behavior of the given value in Lua. -- The table will be created if it doesn't exist yet. ensureUserdataMetatable :: String -- ^ name of the registered -- metatable which should be used. -> Lua () -- ^ set additional properties; this -- operation will be called with the newly -- created metadata table at the top of -- the stack. -> Lua () ensureUserdataMetatable name modMt = do mtCreated <- Lua.newmetatable name when mtCreated $ do -- Prevent accessing or changing the metatable with -- getmetatable/setmetatable. Lua.pushboolean True Lua.setfield (Lua.nthFromTop 2) "__metatable" -- Mark objects for finalization when collecting garbage. Lua.pushcfunction hslua_userdata_gc_ptr Lua.setfield (Lua.nthFromTop 2) "__gc" -- Execute additional modifications on metatable modMt -- | Retrieve data which has been pushed with @'pushAny'@. toAny :: Data a => Lua.StackIndex -> Lua (Maybe a) toAny idx = toAny' undefined where toAny' :: Data a => a -> Lua (Maybe a) toAny' x = toAnyWithName idx (metatableName x) -- | Retrieve data which has been pushed with @'pushAnyWithMetatable'@, where -- *name* must is the value of the @__name@ field of the metatable. toAnyWithName :: Lua.StackIndex -> String -- ^ expected metatable name -> Lua (Maybe a) toAnyWithName idx name = do l <- Lua.state udPtr <- Lua.liftIO (C.withCString name (luaL_testudata l idx)) if udPtr == Ptr.nullPtr then return Nothing else fmap Just . Lua.liftIO $ Storable.peek (Ptr.castPtr udPtr) >>= StablePtr.deRefStablePtr -- | Retrieve Haskell data which was pushed to Lua as userdata. peekAny :: Data a => Lua.StackIndex -> Lua a peekAny idx = peek' undefined where peek' :: Data a => a -> Lua a peek' x = reportValueOnFailure (dataTypeName (dataTypeOf x)) toAny idx -- | Return the default name for userdata to be used when wrapping an object as -- the given type as userdata. The argument is never evaluated. metatableName :: Data a => a -> String metatableName x = "HSLUA_" ++ dataTypeName (dataTypeOf x) -- | Function to free the stable pointer in a userdata, ensuring the Haskell -- value can be garbage collected. This function does not call back into -- Haskell, making is safe to call even from functions imported as unsafe. foreign import ccall "&hslua_userdata_gc" hslua_userdata_gc_ptr :: Lua.CFunction -- | See -- <https://www.lua.org/manual/5.3/manual.html#luaL_testudata luaL_testudata> foreign import ccall "luaL_testudata" luaL_testudata :: Lua.State -> Lua.StackIndex -> C.CString -> IO (Ptr.Ptr ())
osa1/hslua
src/Foreign/Lua/Userdata.hs
mit
5,158
0
13
1,218
835
435
400
70
2
-- -- -- ----------------- -- Exercise 7.19. ----------------- -- -- -- module E'7'19 where import Prelude import qualified Prelude ( (<) , (>) ) type IntegerPair = (Integer, Integer) iSort''' :: [IntegerPair] -> [IntegerPair] iSort''' [] = [] iSort''' ( integerPair : remainingIntegerPairs ) = ins''' integerPair (iSort''' remainingIntegerPairs) ins''' :: IntegerPair -> [IntegerPair] -> [IntegerPair] ins''' integerPair [] = [integerPair] ins''' integerPair@( integerPairLeft , integerPairRight ) -- integerPair is an alias for (integerPairLeft, integerPairRight). ( listIntegerPair@(listIntegerPairLeft , listIntegerPairRight) : remainingListIntegerPairs -- listIntegerPair is an alias for (listIntegerPairLeft, listIntegerPairRight). ) | integerPair < listIntegerPair = integerPair : (listIntegerPair : remainingListIntegerPairs) -- Uses a redefinition of <, see below. Be aware of locality. | otherwise = listIntegerPair : (ins''' integerPair remainingListIntegerPairs) where (<) :: IntegerPair -> IntegerPair -> Bool (<) (firstLeft , secondLeft) (firstRight , secondRight) | firstLeft Prelude.< firstRight = True | firstLeft Prelude.> firstRight = False | otherwise = if (secondLeft Prelude.< secondRight) then ( True ) else ( False ) {- GHCi> iSort''' [ (2, 1), (2, 0), (1, 0) ] -} -- [ ( 1 , 0 ) , ( 2 , 0 ) , ( 2 , 1 ) ]
pascal-knodel/haskell-craft
_/links/E'7'19.hs
mit
1,537
0
10
401
313
182
131
22
2
{-# LANGUAGE TemplateHaskell, ForeignFunctionInterface #-} module Graphics.Wayland.Internal.SpliceClientTypes where import Data.Functor import Language.Haskell.TH import Foreign.C.Types import Graphics.Wayland.Scanner.Protocol import Graphics.Wayland.Scanner $(runIO readProtocol >>= generateClientTypes)
abooij/haskell-wayland
Graphics/Wayland/Internal/SpliceClientTypes.hs
mit
309
0
8
26
53
33
20
8
0
module Distribution.Client.Dependency.Modular.Solver where import Data.Map as M import Distribution.Client.Dependency.Types import Distribution.Client.Dependency.Modular.Assignment import Distribution.Client.Dependency.Modular.Builder import Distribution.Client.Dependency.Modular.Dependency import Distribution.Client.Dependency.Modular.Explore import Distribution.Client.Dependency.Modular.Index import Distribution.Client.Dependency.Modular.Log import Distribution.Client.Dependency.Modular.Message import Distribution.Client.Dependency.Modular.Package import qualified Distribution.Client.Dependency.Modular.Preference as P import Distribution.Client.Dependency.Modular.Validate -- | Various options for the modular solver. data SolverConfig = SolverConfig { preferEasyGoalChoices :: Bool, independentGoals :: Bool, avoidReinstalls :: Bool, shadowPkgs :: Bool, maxBackjumps :: Maybe Int } solve :: SolverConfig -> -- solver parameters Index -> -- all available packages as an index (PN -> PackagePreferences) -> -- preferences Map PN [PackageConstraint] -> -- global constraints [PN] -> -- global goals Log Message (Assignment, RevDepMap) solve sc idx userPrefs userConstraints userGoals = explorePhase $ heuristicsPhase $ preferencesPhase $ validationPhase $ prunePhase $ buildPhase where explorePhase = exploreTreeLog . backjump heuristicsPhase = P.firstGoal . -- after doing goal-choice heuristics, commit to the first choice (saves space) if preferEasyGoalChoices sc then P.preferBaseGoalChoice . P.deferDefaultFlagChoices . P.lpreferEasyGoalChoices else P.preferBaseGoalChoice preferencesPhase = P.preferPackagePreferences userPrefs validationPhase = P.enforceManualFlags . -- can only be done after user constraints P.enforcePackageConstraints userConstraints . validateTree idx prunePhase = (if avoidReinstalls sc then P.avoidReinstalls (const True) else id) . -- packages that can never be "upgraded": P.requireInstalled (`elem` [PackageName "base", PackageName "ghc-prim"]) buildPhase = buildTree idx (independentGoals sc) userGoals
jwiegley/ghc-release
libraries/Cabal/cabal-install/Distribution/Client/Dependency/Modular/Solver.hs
gpl-3.0
2,454
0
12
612
404
244
160
45
3
{-# 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.RDS.DescribeDBLogFiles -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- 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 <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Returns a list of DB log files for the DB instance. -- -- <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DescribeDBLogFiles.html> module Network.AWS.RDS.DescribeDBLogFiles ( -- * Request DescribeDBLogFiles -- ** Request constructor , describeDBLogFiles -- ** Request lenses , ddblfDBInstanceIdentifier , ddblfFileLastWritten , ddblfFileSize , ddblfFilenameContains , ddblfFilters , ddblfMarker , ddblfMaxRecords -- * Response , DescribeDBLogFilesResponse -- ** Response constructor , describeDBLogFilesResponse -- ** Response lenses , ddblfrDescribeDBLogFiles , ddblfrMarker ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.RDS.Types import qualified GHC.Exts data DescribeDBLogFiles = DescribeDBLogFiles { _ddblfDBInstanceIdentifier :: Text , _ddblfFileLastWritten :: Maybe Integer , _ddblfFileSize :: Maybe Integer , _ddblfFilenameContains :: Maybe Text , _ddblfFilters :: List "member" Filter , _ddblfMarker :: Maybe Text , _ddblfMaxRecords :: Maybe Int } deriving (Eq, Read, Show) -- | 'DescribeDBLogFiles' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ddblfDBInstanceIdentifier' @::@ 'Text' -- -- * 'ddblfFileLastWritten' @::@ 'Maybe' 'Integer' -- -- * 'ddblfFileSize' @::@ 'Maybe' 'Integer' -- -- * 'ddblfFilenameContains' @::@ 'Maybe' 'Text' -- -- * 'ddblfFilters' @::@ ['Filter'] -- -- * 'ddblfMarker' @::@ 'Maybe' 'Text' -- -- * 'ddblfMaxRecords' @::@ 'Maybe' 'Int' -- describeDBLogFiles :: Text -- ^ 'ddblfDBInstanceIdentifier' -> DescribeDBLogFiles describeDBLogFiles p1 = DescribeDBLogFiles { _ddblfDBInstanceIdentifier = p1 , _ddblfFilenameContains = Nothing , _ddblfFileLastWritten = Nothing , _ddblfFileSize = Nothing , _ddblfFilters = mempty , _ddblfMaxRecords = Nothing , _ddblfMarker = Nothing } -- | The customer-assigned name of the DB instance that contains the log files -- you want to list. -- -- Constraints: -- -- Must contain from 1 to 63 alphanumeric characters or hyphens First -- character must be a letter Cannot end with a hyphen or contain two -- consecutive hyphens ddblfDBInstanceIdentifier :: Lens' DescribeDBLogFiles Text ddblfDBInstanceIdentifier = lens _ddblfDBInstanceIdentifier (\s a -> s { _ddblfDBInstanceIdentifier = a }) -- | Filters the available log files for files written since the specified date, -- in POSIX timestamp format. ddblfFileLastWritten :: Lens' DescribeDBLogFiles (Maybe Integer) ddblfFileLastWritten = lens _ddblfFileLastWritten (\s a -> s { _ddblfFileLastWritten = a }) -- | Filters the available log files for files larger than the specified size. ddblfFileSize :: Lens' DescribeDBLogFiles (Maybe Integer) ddblfFileSize = lens _ddblfFileSize (\s a -> s { _ddblfFileSize = a }) -- | Filters the available log files for log file names that contain the -- specified string. ddblfFilenameContains :: Lens' DescribeDBLogFiles (Maybe Text) ddblfFilenameContains = lens _ddblfFilenameContains (\s a -> s { _ddblfFilenameContains = a }) -- | This parameter is not currently supported. ddblfFilters :: Lens' DescribeDBLogFiles [Filter] ddblfFilters = lens _ddblfFilters (\s a -> s { _ddblfFilters = a }) . _List -- | The pagination token provided in the previous request. If this parameter is -- specified the response includes only records beyond the marker, up to -- MaxRecords. ddblfMarker :: Lens' DescribeDBLogFiles (Maybe Text) ddblfMarker = lens _ddblfMarker (\s a -> s { _ddblfMarker = a }) -- | The maximum number of records to include in the response. If more records -- exist than the specified MaxRecords value, a pagination token called a marker -- is included in the response so that the remaining results can be retrieved. ddblfMaxRecords :: Lens' DescribeDBLogFiles (Maybe Int) ddblfMaxRecords = lens _ddblfMaxRecords (\s a -> s { _ddblfMaxRecords = a }) data DescribeDBLogFilesResponse = DescribeDBLogFilesResponse { _ddblfrDescribeDBLogFiles :: List "member" DescribeDBLogFilesDetails , _ddblfrMarker :: Maybe Text } deriving (Eq, Read, Show) -- | 'DescribeDBLogFilesResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ddblfrDescribeDBLogFiles' @::@ ['DescribeDBLogFilesDetails'] -- -- * 'ddblfrMarker' @::@ 'Maybe' 'Text' -- describeDBLogFilesResponse :: DescribeDBLogFilesResponse describeDBLogFilesResponse = DescribeDBLogFilesResponse { _ddblfrDescribeDBLogFiles = mempty , _ddblfrMarker = Nothing } -- | The DB log files returned. ddblfrDescribeDBLogFiles :: Lens' DescribeDBLogFilesResponse [DescribeDBLogFilesDetails] ddblfrDescribeDBLogFiles = lens _ddblfrDescribeDBLogFiles (\s a -> s { _ddblfrDescribeDBLogFiles = a }) . _List -- | A pagination token that can be used in a subsequent DescribeDBLogFiles -- request. ddblfrMarker :: Lens' DescribeDBLogFilesResponse (Maybe Text) ddblfrMarker = lens _ddblfrMarker (\s a -> s { _ddblfrMarker = a }) instance ToPath DescribeDBLogFiles where toPath = const "/" instance ToQuery DescribeDBLogFiles where toQuery DescribeDBLogFiles{..} = mconcat [ "DBInstanceIdentifier" =? _ddblfDBInstanceIdentifier , "FileLastWritten" =? _ddblfFileLastWritten , "FileSize" =? _ddblfFileSize , "FilenameContains" =? _ddblfFilenameContains , "Filters" =? _ddblfFilters , "Marker" =? _ddblfMarker , "MaxRecords" =? _ddblfMaxRecords ] instance ToHeaders DescribeDBLogFiles instance AWSRequest DescribeDBLogFiles where type Sv DescribeDBLogFiles = RDS type Rs DescribeDBLogFiles = DescribeDBLogFilesResponse request = post "DescribeDBLogFiles" response = xmlResponse instance FromXML DescribeDBLogFilesResponse where parseXML = withElement "DescribeDBLogFilesResult" $ \x -> DescribeDBLogFilesResponse <$> x .@? "DescribeDBLogFiles" .!@ mempty <*> x .@? "Marker" instance AWSPager DescribeDBLogFiles where page rq rs | stop (rs ^. ddblfrMarker) = Nothing | otherwise = (\x -> rq & ddblfMarker ?~ x) <$> (rs ^. ddblfrMarker)
kim/amazonka
amazonka-rds/gen/Network/AWS/RDS/DescribeDBLogFiles.hs
mpl-2.0
7,501
0
12
1,662
1,013
601
412
107
1
{-# LANGUAGE CPP, DeriveDataTypeable #-} module ETA.HsSyn.HsDoc ( HsDocString(..), LHsDocString, ppr_mbDoc ) where #include "HsVersions.h" import ETA.Utils.Outputable import ETA.BasicTypes.SrcLoc import ETA.Utils.FastString import Data.Data newtype HsDocString = HsDocString FastString deriving (Eq, Show, Data, Typeable) type LHsDocString = Located HsDocString instance Outputable HsDocString where ppr (HsDocString fs) = ftext fs ppr_mbDoc :: Maybe LHsDocString -> SDoc ppr_mbDoc (Just doc) = ppr doc ppr_mbDoc Nothing = empty
alexander-at-github/eta
compiler/ETA/HsSyn/HsDoc.hs
bsd-3-clause
553
0
8
88
145
82
63
17
1
-- -- Copyright (c) 2012 Citrix Systems, Inc. -- -- 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 -- {-# LANGUAGE TypeSynonymInstances #-} module Vm.DmTypes ( DomainID , XbDeviceID (..) , DiskID , DiskMap , DiskMode (..) , DiskType (..) , DiskSnapshotMode (..) , DiskDeviceType (..) , ManagedDiskType (..) , Disk (..) , Sha1Sum , NicDef (..) , NicDefMap , NicID , Mac , macToBytes, bytesToMac , Nic (..) , NetworkInfo (..) , Network , networkObjectPath , networkToStr, networkFromStr , fallbackNetwork , isCdrom ) where import Data.Int import Data.String import Data.List (intersperse) import Data.Char (digitToInt) import qualified Data.Text.Lazy as TL import qualified Data.Map as M import Text.Printf import Vm.Uuid import Tools.Misc import Rpc.Core (ObjectPath, mkObjectPath_, strObjectPath) type DomainID = Int32 -- | xenbus device ID newtype XbDeviceID = XbDeviceID { xbdevID :: Int } deriving (Eq,Ord) instance Show XbDeviceID where show d = show (xbdevID d) instance IsString XbDeviceID where fromString x = XbDeviceID (fromString x) -- | Disk definitions type DiskID = Int type DiskMap = M.Map DiskID Disk instance IsString DiskID where fromString = read data DiskMode = ReadOnly | ReadWrite deriving (Eq, Show) data DiskType = DiskImage | PhysicalDevice | QemuCopyOnWrite | VirtualHardDisk | ExternalVdi | Aio deriving (Eq, Show) data DiskSnapshotMode = SnapshotTemporary | SnapshotTemporaryEncrypted | SnapshotCoalesce | SnapshotScripted | SnapshotScriptedAuthor | SnapshotScriptedNoSnapshot deriving (Eq, Show) data DiskDeviceType = DiskDeviceTypeDisk | DiskDeviceTypeCdRom deriving (Eq, Show) data ManagedDiskType = UnmanagedDisk | ApplicationDisk | UserDisk | SystemDisk deriving (Eq, Show) -- Virtual disk specification data Disk = Disk { diskPath :: FilePath , diskType :: DiskType , diskMode :: DiskMode , diskDevice :: String , diskDeviceType :: DiskDeviceType , diskSnapshotMode :: Maybe DiskSnapshotMode , diskSha1Sum :: Maybe Sha1Sum , diskShared :: Bool , diskEnabled :: Bool , diskManagedType :: ManagedDiskType } deriving (Eq, Show) type Sha1Sum = Integer -- NIC definition in database data NicDef = NicDef { nicdefId :: NicID , nicdefNetwork :: Network , nicdefWirelessDriver :: Bool , nicdefBackendUuid :: Maybe Uuid , nicdefBackendName :: Maybe String , nicdefBackendDomid :: Maybe DomainID , nicdefEnable :: Bool , nicdefMac :: Maybe String } deriving (Eq, Show) type NicDefMap = M.Map NicID NicDef type NicID = XbDeviceID type Mac = String -- Actual NIC as plugged in data Nic = Nic { nicId :: NicID , nicNetwork :: Network , nicMac :: Mac } deriving (Eq, Show) -- | path references the network object hold within networking daemon newtype Network = Network ObjectPath deriving (Eq, Show) networkObjectPath :: Network -> ObjectPath networkObjectPath (Network n) = n data NetworkInfo = NetworkInfo { niHandle :: Network , niName :: String , niBridgeName :: String , niBackend :: Uuid , niIsWireless :: Bool , niIsShared :: Bool , niIsInternal :: Bool , niIsConfigured :: Bool , niCarrier :: Bool } deriving (Eq,Show) fallbackNetwork :: Network fallbackNetwork = Network (fromString "/wired/0/bridged") networkToStr :: Network -> String networkToStr (Network p) = TL.unpack (strObjectPath p) networkFromStr :: String -> Network networkFromStr s = Network (mkObjectPath_ $ fromString $ legacyNNames s) -- TODO: ideally this could be handled somewhere in the upgrade process legacyNNames "brbridged" = "/wired/0/bridged" legacyNNames "brshared" = "/wired/0/shared" legacyNNames "brwireless" = "/wireless/0/shared" legacyNNames "brinternal" = "/internal" legacyNNames x = x isCdrom :: Disk -> Bool isCdrom disk = diskDevice disk == "hdc" macToBytes :: Mac -> [Int] macToBytes = map hexify . (split ':') where hexify [a,b] = 0x10 * digitToInt a + digitToInt b hexify _ = error "bad mac string" bytesToMac :: [Int] -> Mac bytesToMac = concat . intersperse ":" . map stringify where stringify x = printf "%02x" x
jean-edouard/manager
xenmgr/Vm/DmTypes.hs
gpl-2.0
5,594
0
9
1,707
1,092
648
444
130
2
{-# LANGUAGE CPP, ScopedTypeVariables, MagicHash, UnboxedTuples #-} ----------------------------------------------------------------------------- -- -- GHC Interactive support for inspecting arbitrary closures at runtime -- -- Pepe Iborra (supported by Google SoC) 2006 -- ----------------------------------------------------------------------------- {-# OPTIONS_GHC -fno-warn-tabs #-} -- The above warning supression flag is a temporary kludge. -- While working on this module you are encouraged to remove it and -- detab the module (please do the detabbing in a separate patch). See -- http://ghc.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces -- for details module RtClosureInspect( cvObtainTerm, -- :: HscEnv -> Int -> Bool -> Maybe Type -> HValue -> IO Term cvReconstructType, improveRTTIType, Term(..), isTerm, isSuspension, isPrim, isFun, isFunLike, isNewtypeWrap, isFullyEvaluated, isFullyEvaluatedTerm, termType, mapTermType, termTyVars, foldTerm, TermFold(..), foldTermM, TermFoldM(..), idTermFold, pprTerm, cPprTerm, cPprTermBase, CustomTermPrinter, -- unsafeDeepSeq, Closure(..), getClosureData, ClosureType(..), isConstr, isIndirection ) where #include "HsVersions.h" import DebuggerUtils import ByteCodeItbls ( StgInfoTable, peekItbl ) import qualified ByteCodeItbls as BCI( StgInfoTable(..) ) import BasicTypes ( HValue ) import HscTypes import DataCon import Type import qualified Unify as U import Var import TcRnMonad import TcType import TcMType import TcHsSyn ( zonkTcTypeToType, mkEmptyZonkEnv ) import TcUnify import TcEnv import TyCon import Name import VarEnv import Util import VarSet import BasicTypes ( TupleSort(UnboxedTuple) ) import TysPrim import PrelNames import TysWiredIn import DynFlags import Outputable as Ppr import GHC.Arr ( Array(..) ) import GHC.Exts import GHC.IO ( IO(..) ) import StaticFlags( opt_PprStyle_Debug ) import Control.Monad import Data.Maybe import Data.Array.Base import Data.Ix import Data.List import qualified Data.Sequence as Seq import Data.Monoid (mappend) import Data.Sequence (viewl, ViewL(..)) import Foreign.Safe import System.IO.Unsafe --------------------------------------------- -- * A representation of semi evaluated Terms --------------------------------------------- data Term = Term { ty :: RttiType , dc :: Either String DataCon -- Carries a text representation if the datacon is -- not exported by the .hi file, which is the case -- for private constructors in -O0 compiled libraries , val :: HValue , subTerms :: [Term] } | Prim { ty :: RttiType , value :: [Word] } | Suspension { ctype :: ClosureType , ty :: RttiType , val :: HValue , bound_to :: Maybe Name -- Useful for printing } | NewtypeWrap{ -- At runtime there are no newtypes, and hence no -- newtype constructors. A NewtypeWrap is just a -- made-up tag saying "heads up, there used to be -- a newtype constructor here". ty :: RttiType , dc :: Either String DataCon , wrapped_term :: Term } | RefWrap { -- The contents of a reference ty :: RttiType , wrapped_term :: Term } isTerm, isSuspension, isPrim, isFun, isFunLike, isNewtypeWrap :: Term -> Bool isTerm Term{} = True isTerm _ = False isSuspension Suspension{} = True isSuspension _ = False isPrim Prim{} = True isPrim _ = False isNewtypeWrap NewtypeWrap{} = True isNewtypeWrap _ = False isFun Suspension{ctype=Fun} = True isFun _ = False isFunLike s@Suspension{ty=ty} = isFun s || isFunTy ty isFunLike _ = False termType :: Term -> RttiType termType t = ty t isFullyEvaluatedTerm :: Term -> Bool isFullyEvaluatedTerm Term {subTerms=tt} = all isFullyEvaluatedTerm tt isFullyEvaluatedTerm Prim {} = True isFullyEvaluatedTerm NewtypeWrap{wrapped_term=t} = isFullyEvaluatedTerm t isFullyEvaluatedTerm RefWrap{wrapped_term=t} = isFullyEvaluatedTerm t isFullyEvaluatedTerm _ = False instance Outputable (Term) where ppr t | Just doc <- cPprTerm cPprTermBase t = doc | otherwise = panic "Outputable Term instance" ------------------------------------------------------------------------- -- Runtime Closure Datatype and functions for retrieving closure related stuff ------------------------------------------------------------------------- data ClosureType = Constr | Fun | Thunk Int | ThunkSelector | Blackhole | AP | PAP | Indirection Int | MutVar Int | MVar Int | Other Int deriving (Show, Eq) data Closure = Closure { tipe :: ClosureType , infoPtr :: Ptr () , infoTable :: StgInfoTable , ptrs :: Array Int HValue , nonPtrs :: [Word] } instance Outputable ClosureType where ppr = text . show #include "../includes/rts/storage/ClosureTypes.h" aP_CODE, pAP_CODE :: Int aP_CODE = AP pAP_CODE = PAP #undef AP #undef PAP getClosureData :: DynFlags -> a -> IO Closure getClosureData dflags a = case unpackClosure# a of (# iptr, ptrs, nptrs #) -> do let iptr' | ghciTablesNextToCode = Ptr iptr | otherwise = -- the info pointer we get back from unpackClosure# -- is to the beginning of the standard info table, -- but the Storable instance for info tables takes -- into account the extra entry pointer when -- !ghciTablesNextToCode, so we must adjust here: Ptr iptr `plusPtr` negate (wORD_SIZE dflags) itbl <- peekItbl dflags iptr' let tipe = readCType (BCI.tipe itbl) elems = fromIntegral (BCI.ptrs itbl) ptrsList = Array 0 (elems - 1) elems ptrs nptrs_data = [W# (indexWordArray# nptrs i) | I# i <- [0.. fromIntegral (BCI.nptrs itbl)-1] ] ASSERT(elems >= 0) return () ptrsList `seq` return (Closure tipe (Ptr iptr) itbl ptrsList nptrs_data) readCType :: Integral a => a -> ClosureType readCType i | i >= CONSTR && i <= CONSTR_NOCAF_STATIC = Constr | i >= FUN && i <= FUN_STATIC = Fun | i >= THUNK && i < THUNK_SELECTOR = Thunk i' | i == THUNK_SELECTOR = ThunkSelector | i == BLACKHOLE = Blackhole | i >= IND && i <= IND_STATIC = Indirection i' | i' == aP_CODE = AP | i == AP_STACK = AP | i' == pAP_CODE = PAP | i == MUT_VAR_CLEAN || i == MUT_VAR_DIRTY= MutVar i' | i == MVAR_CLEAN || i == MVAR_DIRTY = MVar i' | otherwise = Other i' where i' = fromIntegral i isConstr, isIndirection, isThunk :: ClosureType -> Bool isConstr Constr = True isConstr _ = False isIndirection (Indirection _) = True isIndirection _ = False isThunk (Thunk _) = True isThunk ThunkSelector = True isThunk AP = True isThunk _ = False isFullyEvaluated :: DynFlags -> a -> IO Bool isFullyEvaluated dflags a = do closure <- getClosureData dflags a case tipe closure of Constr -> do are_subs_evaluated <- amapM (isFullyEvaluated dflags) (ptrs closure) return$ and are_subs_evaluated _ -> return False where amapM f = sequence . amap' f -- TODO: Fix it. Probably the otherwise case is failing, trace/debug it {- unsafeDeepSeq :: a -> b -> b unsafeDeepSeq = unsafeDeepSeq1 2 where unsafeDeepSeq1 0 a b = seq a $! b unsafeDeepSeq1 i a b -- 1st case avoids infinite loops for non reducible thunks | not (isConstr tipe) = seq a $! unsafeDeepSeq1 (i-1) a b -- | unsafePerformIO (isFullyEvaluated a) = b | otherwise = case unsafePerformIO (getClosureData a) of closure -> foldl' (flip unsafeDeepSeq) b (ptrs closure) where tipe = unsafePerformIO (getClosureType a) -} ----------------------------------- -- * Traversals for Terms ----------------------------------- type TermProcessor a b = RttiType -> Either String DataCon -> HValue -> [a] -> b data TermFold a = TermFold { fTerm :: TermProcessor a a , fPrim :: RttiType -> [Word] -> a , fSuspension :: ClosureType -> RttiType -> HValue -> Maybe Name -> a , fNewtypeWrap :: RttiType -> Either String DataCon -> a -> a , fRefWrap :: RttiType -> a -> a } data TermFoldM m a = TermFoldM {fTermM :: TermProcessor a (m a) , fPrimM :: RttiType -> [Word] -> m a , fSuspensionM :: ClosureType -> RttiType -> HValue -> Maybe Name -> m a , fNewtypeWrapM :: RttiType -> Either String DataCon -> a -> m a , fRefWrapM :: RttiType -> a -> m a } foldTerm :: TermFold a -> Term -> a foldTerm tf (Term ty dc v tt) = fTerm tf ty dc v (map (foldTerm tf) tt) foldTerm tf (Prim ty v ) = fPrim tf ty v foldTerm tf (Suspension ct ty v b) = fSuspension tf ct ty v b foldTerm tf (NewtypeWrap ty dc t) = fNewtypeWrap tf ty dc (foldTerm tf t) foldTerm tf (RefWrap ty t) = fRefWrap tf ty (foldTerm tf t) foldTermM :: Monad m => TermFoldM m a -> Term -> m a foldTermM tf (Term ty dc v tt) = mapM (foldTermM tf) tt >>= fTermM tf ty dc v foldTermM tf (Prim ty v ) = fPrimM tf ty v foldTermM tf (Suspension ct ty v b) = fSuspensionM tf ct ty v b foldTermM tf (NewtypeWrap ty dc t) = foldTermM tf t >>= fNewtypeWrapM tf ty dc foldTermM tf (RefWrap ty t) = foldTermM tf t >>= fRefWrapM tf ty idTermFold :: TermFold Term idTermFold = TermFold { fTerm = Term, fPrim = Prim, fSuspension = Suspension, fNewtypeWrap = NewtypeWrap, fRefWrap = RefWrap } mapTermType :: (RttiType -> Type) -> Term -> Term mapTermType f = foldTerm idTermFold { fTerm = \ty dc hval tt -> Term (f ty) dc hval tt, fSuspension = \ct ty hval n -> Suspension ct (f ty) hval n, fNewtypeWrap= \ty dc t -> NewtypeWrap (f ty) dc t, fRefWrap = \ty t -> RefWrap (f ty) t} mapTermTypeM :: Monad m => (RttiType -> m Type) -> Term -> m Term mapTermTypeM f = foldTermM TermFoldM { fTermM = \ty dc hval tt -> f ty >>= \ty' -> return $ Term ty' dc hval tt, fPrimM = (return.) . Prim, fSuspensionM = \ct ty hval n -> f ty >>= \ty' -> return $ Suspension ct ty' hval n, fNewtypeWrapM= \ty dc t -> f ty >>= \ty' -> return $ NewtypeWrap ty' dc t, fRefWrapM = \ty t -> f ty >>= \ty' -> return $ RefWrap ty' t} termTyVars :: Term -> TyVarSet termTyVars = foldTerm TermFold { fTerm = \ty _ _ tt -> tyVarsOfType ty `plusVarEnv` concatVarEnv tt, fSuspension = \_ ty _ _ -> tyVarsOfType ty, fPrim = \ _ _ -> emptyVarEnv, fNewtypeWrap= \ty _ t -> tyVarsOfType ty `plusVarEnv` t, fRefWrap = \ty t -> tyVarsOfType ty `plusVarEnv` t} where concatVarEnv = foldr plusVarEnv emptyVarEnv ---------------------------------- -- Pretty printing of terms ---------------------------------- type Precedence = Int type TermPrinter = Precedence -> Term -> SDoc type TermPrinterM m = Precedence -> Term -> m SDoc app_prec,cons_prec, max_prec ::Int max_prec = 10 app_prec = max_prec cons_prec = 5 -- TODO Extract this info from GHC itself pprTerm :: TermPrinter -> TermPrinter pprTerm y p t | Just doc <- pprTermM (\p -> Just . y p) p t = doc pprTerm _ _ _ = panic "pprTerm" pprTermM, ppr_termM, pprNewtypeWrap :: Monad m => TermPrinterM m -> TermPrinterM m pprTermM y p t = pprDeeper `liftM` ppr_termM y p t ppr_termM y p Term{dc=Left dc_tag, subTerms=tt} = do tt_docs <- mapM (y app_prec) tt return $ cparen (not (null tt) && p >= app_prec) (text dc_tag <+> pprDeeperList fsep tt_docs) ppr_termM y p Term{dc=Right dc, subTerms=tt} {- | dataConIsInfix dc, (t1:t2:tt') <- tt --TODO fixity = parens (ppr_term1 True t1 <+> ppr dc <+> ppr_term1 True ppr t2) <+> hsep (map (ppr_term1 True) tt) -} -- TODO Printing infix constructors properly | null sub_terms_to_show = return (ppr dc) | otherwise = do { tt_docs <- mapM (y app_prec) sub_terms_to_show ; return $ cparen (p >= app_prec) $ sep [ppr dc, nest 2 (pprDeeperList fsep tt_docs)] } where sub_terms_to_show -- Don't show the dictionary arguments to -- constructors unless -dppr-debug is on | opt_PprStyle_Debug = tt | otherwise = dropList (dataConTheta dc) tt ppr_termM y p t@NewtypeWrap{} = pprNewtypeWrap y p t ppr_termM y p RefWrap{wrapped_term=t} = do contents <- y app_prec t return$ cparen (p >= app_prec) (text "GHC.Prim.MutVar#" <+> contents) -- The constructor name is wired in here ^^^ for the sake of simplicity. -- I don't think mutvars are going to change in a near future. -- In any case this is solely a presentation matter: MutVar# is -- a datatype with no constructors, implemented by the RTS -- (hence there is no way to obtain a datacon and print it). ppr_termM _ _ t = ppr_termM1 t ppr_termM1 :: Monad m => Term -> m SDoc ppr_termM1 Prim{value=words, ty=ty} = return $ repPrim (tyConAppTyCon ty) words ppr_termM1 Suspension{ty=ty, bound_to=Nothing} = return (char '_' <+> ifPprDebug (text "::" <> ppr ty)) ppr_termM1 Suspension{ty=ty, bound_to=Just n} -- | Just _ <- splitFunTy_maybe ty = return$ ptext (sLit("<function>") | otherwise = return$ parens$ ppr n <> text "::" <> ppr ty ppr_termM1 Term{} = panic "ppr_termM1 - Term" ppr_termM1 RefWrap{} = panic "ppr_termM1 - RefWrap" ppr_termM1 NewtypeWrap{} = panic "ppr_termM1 - NewtypeWrap" pprNewtypeWrap y p NewtypeWrap{ty=ty, wrapped_term=t} | Just (tc,_) <- tcSplitTyConApp_maybe ty , ASSERT(isNewTyCon tc) True , Just new_dc <- tyConSingleDataCon_maybe tc = do real_term <- y max_prec t return $ cparen (p >= app_prec) (ppr new_dc <+> real_term) pprNewtypeWrap _ _ _ = panic "pprNewtypeWrap" ------------------------------------------------------- -- Custom Term Pretty Printers ------------------------------------------------------- -- We can want to customize the representation of a -- term depending on its type. -- However, note that custom printers have to work with -- type representations, instead of directly with types. -- We cannot use type classes here, unless we employ some -- typerep trickery (e.g. Weirich's RepLib tricks), -- which I didn't. Therefore, this code replicates a lot -- of what type classes provide for free. type CustomTermPrinter m = TermPrinterM m -> [Precedence -> Term -> (m (Maybe SDoc))] -- | Takes a list of custom printers with a explicit recursion knot and a term, -- and returns the output of the first successful printer, or the default printer cPprTerm :: Monad m => CustomTermPrinter m -> Term -> m SDoc cPprTerm printers_ = go 0 where printers = printers_ go go prec t = do let default_ = Just `liftM` pprTermM go prec t mb_customDocs = [pp prec t | pp <- printers] ++ [default_] Just doc <- firstJustM mb_customDocs return$ cparen (prec>app_prec+1) doc firstJustM (mb:mbs) = mb >>= maybe (firstJustM mbs) (return . Just) firstJustM [] = return Nothing -- Default set of custom printers. Note that the recursion knot is explicit cPprTermBase :: forall m. Monad m => CustomTermPrinter m cPprTermBase y = [ ifTerm (isTupleTy.ty) (\_p -> liftM (parens . hcat . punctuate comma) . mapM (y (-1)) . subTerms) , ifTerm (\t -> isTyCon listTyCon (ty t) && subTerms t `lengthIs` 2) ppr_list , ifTerm (isTyCon intTyCon . ty) ppr_int , ifTerm (isTyCon charTyCon . ty) ppr_char , ifTerm (isTyCon floatTyCon . ty) ppr_float , ifTerm (isTyCon doubleTyCon . ty) ppr_double , ifTerm (isIntegerTy . ty) ppr_integer ] where ifTerm :: (Term -> Bool) -> (Precedence -> Term -> m SDoc) -> Precedence -> Term -> m (Maybe SDoc) ifTerm pred f prec t@Term{} | pred t = Just `liftM` f prec t ifTerm _ _ _ _ = return Nothing isTupleTy ty = fromMaybe False $ do (tc,_) <- tcSplitTyConApp_maybe ty return (isBoxedTupleTyCon tc) isTyCon a_tc ty = fromMaybe False $ do (tc,_) <- tcSplitTyConApp_maybe ty return (a_tc == tc) isIntegerTy ty = fromMaybe False $ do (tc,_) <- tcSplitTyConApp_maybe ty return (tyConName tc == integerTyConName) ppr_int, ppr_char, ppr_float, ppr_double, ppr_integer :: Precedence -> Term -> m SDoc ppr_int _ v = return (Ppr.int (unsafeCoerce# (val v))) ppr_char _ v = return (Ppr.char '\'' <> Ppr.char (unsafeCoerce# (val v)) <> Ppr.char '\'') ppr_float _ v = return (Ppr.float (unsafeCoerce# (val v))) ppr_double _ v = return (Ppr.double (unsafeCoerce# (val v))) ppr_integer _ v = return (Ppr.integer (unsafeCoerce# (val v))) --Note pprinting of list terms is not lazy ppr_list :: Precedence -> Term -> m SDoc ppr_list p (Term{subTerms=[h,t]}) = do let elems = h : getListTerms t isConsLast = not(termType(last elems) `eqType` termType h) is_string = all (isCharTy . ty) elems print_elems <- mapM (y cons_prec) elems if is_string then return (Ppr.doubleQuotes (Ppr.text (unsafeCoerce# (map val elems)))) else if isConsLast then return $ cparen (p >= cons_prec) $ pprDeeperList fsep $ punctuate (space<>colon) print_elems else return $ brackets $ pprDeeperList fcat $ punctuate comma print_elems where getListTerms Term{subTerms=[h,t]} = h : getListTerms t getListTerms Term{subTerms=[]} = [] getListTerms t@Suspension{} = [t] getListTerms t = pprPanic "getListTerms" (ppr t) ppr_list _ _ = panic "doList" repPrim :: TyCon -> [Word] -> SDoc repPrim t = rep where rep x | t == charPrimTyCon = text $ show (build x :: Char) | t == intPrimTyCon = text $ show (build x :: Int) | t == wordPrimTyCon = text $ show (build x :: Word) | t == floatPrimTyCon = text $ show (build x :: Float) | t == doublePrimTyCon = text $ show (build x :: Double) | t == int32PrimTyCon = text $ show (build x :: Int32) | t == word32PrimTyCon = text $ show (build x :: Word32) | t == int64PrimTyCon = text $ show (build x :: Int64) | t == word64PrimTyCon = text $ show (build x :: Word64) | t == addrPrimTyCon = text $ show (nullPtr `plusPtr` build x) | t == stablePtrPrimTyCon = text "<stablePtr>" | t == stableNamePrimTyCon = text "<stableName>" | t == statePrimTyCon = text "<statethread>" | t == proxyPrimTyCon = text "<proxy>" | t == realWorldTyCon = text "<realworld>" | t == threadIdPrimTyCon = text "<ThreadId>" | t == weakPrimTyCon = text "<Weak>" | t == arrayPrimTyCon = text "<array>" | t == smallArrayPrimTyCon = text "<smallArray>" | t == byteArrayPrimTyCon = text "<bytearray>" | t == mutableArrayPrimTyCon = text "<mutableArray>" | t == smallMutableArrayPrimTyCon = text "<smallMutableArray>" | t == mutableByteArrayPrimTyCon = text "<mutableByteArray>" | t == mutVarPrimTyCon = text "<mutVar>" | t == mVarPrimTyCon = text "<mVar>" | t == tVarPrimTyCon = text "<tVar>" | otherwise = char '<' <> ppr t <> char '>' where build ww = unsafePerformIO $ withArray ww (peek . castPtr) -- This ^^^ relies on the representation of Haskell heap values being -- the same as in a C array. ----------------------------------- -- Type Reconstruction ----------------------------------- {- Type Reconstruction is type inference done on heap closures. The algorithm walks the heap generating a set of equations, which are solved with syntactic unification. A type reconstruction equation looks like: <datacon reptype> = <actual heap contents> The full equation set is generated by traversing all the subterms, starting from a given term. The only difficult part is that newtypes are only found in the lhs of equations. Right hand sides are missing them. We can either (a) drop them from the lhs, or (b) reconstruct them in the rhs when possible. The function congruenceNewtypes takes a shot at (b) -} -- A (non-mutable) tau type containing -- existentially quantified tyvars. -- (since GHC type language currently does not support -- existentials, we leave these variables unquantified) type RttiType = Type -- An incomplete type as stored in GHCi: -- no polymorphism: no quantifiers & all tyvars are skolem. type GhciType = Type -- The Type Reconstruction monad -------------------------------- type TR a = TcM a runTR :: HscEnv -> TR a -> IO a runTR hsc_env thing = do mb_val <- runTR_maybe hsc_env thing case mb_val of Nothing -> error "unable to :print the term" Just x -> return x runTR_maybe :: HscEnv -> TR a -> IO (Maybe a) runTR_maybe hsc_env thing_inside = do { (_errs, res) <- initTc hsc_env HsSrcFile False (icInteractiveModule (hsc_IC hsc_env)) thing_inside ; return res } traceTR :: SDoc -> TR () traceTR = liftTcM . traceOptTcRn Opt_D_dump_rtti -- Semantically different to recoverM in TcRnMonad -- recoverM retains the errors in the first action, -- whereas recoverTc here does not recoverTR :: TR a -> TR a -> TR a recoverTR recover thing = do (_,mb_res) <- tryTcErrs thing case mb_res of Nothing -> recover Just res -> return res trIO :: IO a -> TR a trIO = liftTcM . liftIO liftTcM :: TcM a -> TR a liftTcM = id newVar :: Kind -> TR TcType newVar = liftTcM . newFlexiTyVarTy instTyVars :: [TyVar] -> TR ([TcTyVar], [TcType], TvSubst) -- Instantiate fresh mutable type variables from some TyVars -- This function preserves the print-name, which helps error messages instTyVars = liftTcM . tcInstTyVars type RttiInstantiation = [(TcTyVar, TyVar)] -- Associates the typechecker-world meta type variables -- (which are mutable and may be refined), to their -- debugger-world RuntimeUnk counterparts. -- If the TcTyVar has not been refined by the runtime type -- elaboration, then we want to turn it back into the -- original RuntimeUnk -- | Returns the instantiated type scheme ty', and the -- mapping from new (instantiated) -to- old (skolem) type variables instScheme :: QuantifiedType -> TR (TcType, RttiInstantiation) instScheme (tvs, ty) = liftTcM $ do { (tvs', _, subst) <- tcInstTyVars tvs ; let rtti_inst = [(tv',tv) | (tv',tv) <- tvs' `zip` tvs] ; return (substTy subst ty, rtti_inst) } applyRevSubst :: RttiInstantiation -> TR () -- Apply the *reverse* substitution in-place to any un-filled-in -- meta tyvars. This recovers the original debugger-world variable -- unless it has been refined by new information from the heap applyRevSubst pairs = liftTcM (mapM_ do_pair pairs) where do_pair (tc_tv, rtti_tv) = do { tc_ty <- zonkTcTyVar tc_tv ; case tcGetTyVar_maybe tc_ty of Just tv | isMetaTyVar tv -> writeMetaTyVar tv (mkTyVarTy rtti_tv) _ -> return () } -- Adds a constraint of the form t1 == t2 -- t1 is expected to come from walking the heap -- t2 is expected to come from a datacon signature -- Before unification, congruenceNewtypes needs to -- do its magic. addConstraint :: TcType -> TcType -> TR () addConstraint actual expected = do traceTR (text "add constraint:" <+> fsep [ppr actual, equals, ppr expected]) recoverTR (traceTR $ fsep [text "Failed to unify", ppr actual, text "with", ppr expected]) $ do { (ty1, ty2) <- congruenceNewtypes actual expected ; _ <- captureConstraints $ unifyType ty1 ty2 ; return () } -- TOMDO: what about the coercion? -- we should consider family instances -- Type & Term reconstruction ------------------------------ cvObtainTerm :: HscEnv -> Int -> Bool -> RttiType -> HValue -> IO Term cvObtainTerm hsc_env max_depth force old_ty hval = runTR hsc_env $ do -- we quantify existential tyvars as universal, -- as this is needed to be able to manipulate -- them properly let quant_old_ty@(old_tvs, old_tau) = quantifyType old_ty sigma_old_ty = mkForAllTys old_tvs old_tau traceTR (text "Term reconstruction started with initial type " <> ppr old_ty) term <- if null old_tvs then do term <- go max_depth sigma_old_ty sigma_old_ty hval term' <- zonkTerm term return $ fixFunDictionaries $ expandNewtypes term' else do (old_ty', rev_subst) <- instScheme quant_old_ty my_ty <- newVar openTypeKind when (check1 quant_old_ty) (traceTR (text "check1 passed") >> addConstraint my_ty old_ty') term <- go max_depth my_ty sigma_old_ty hval new_ty <- zonkTcType (termType term) if isMonomorphic new_ty || check2 (quantifyType new_ty) quant_old_ty then do traceTR (text "check2 passed") addConstraint new_ty old_ty' applyRevSubst rev_subst zterm' <- zonkTerm term return ((fixFunDictionaries . expandNewtypes) zterm') else do traceTR (text "check2 failed" <+> parens (ppr term <+> text "::" <+> ppr new_ty)) -- we have unsound types. Replace constructor types in -- subterms with tyvars zterm' <- mapTermTypeM (\ty -> case tcSplitTyConApp_maybe ty of Just (tc, _:_) | tc /= funTyCon -> newVar openTypeKind _ -> return ty) term zonkTerm zterm' traceTR (text "Term reconstruction completed." $$ text "Term obtained: " <> ppr term $$ text "Type obtained: " <> ppr (termType term)) return term where dflags = hsc_dflags hsc_env go :: Int -> Type -> Type -> HValue -> TcM Term -- I believe that my_ty should not have any enclosing -- foralls, nor any free RuntimeUnk skolems; -- that is partly what the quantifyType stuff achieved -- -- [SPJ May 11] I don't understand the difference between my_ty and old_ty go max_depth _ _ _ | seq max_depth False = undefined go 0 my_ty _old_ty a = do traceTR (text "Gave up reconstructing a term after" <> int max_depth <> text " steps") clos <- trIO $ getClosureData dflags a return (Suspension (tipe clos) my_ty a Nothing) go max_depth my_ty old_ty a = do let monomorphic = not(isTyVarTy my_ty) -- This ^^^ is a convention. The ancestor tests for -- monomorphism and passes a type instead of a tv clos <- trIO $ getClosureData dflags a case tipe clos of -- Thunks we may want to force t | isThunk t && force -> traceTR (text "Forcing a " <> text (show t)) >> seq a (go (pred max_depth) my_ty old_ty a) -- Blackholes are indirections iff the payload is not TSO or BLOCKING_QUEUE. So we -- treat them like indirections; if the payload is TSO or BLOCKING_QUEUE, we'll end up -- showing '_' which is what we want. Blackhole -> do traceTR (text "Following a BLACKHOLE") appArr (go max_depth my_ty old_ty) (ptrs clos) 0 -- We always follow indirections Indirection i -> do traceTR (text "Following an indirection" <> parens (int i) ) go max_depth my_ty old_ty $! (ptrs clos ! 0) -- We also follow references MutVar _ | Just (tycon,[world,contents_ty]) <- tcSplitTyConApp_maybe old_ty -> do -- Deal with the MutVar# primitive -- It does not have a constructor at all, -- so we simulate the following one -- MutVar# :: contents_ty -> MutVar# s contents_ty traceTR (text "Following a MutVar") contents_tv <- newVar liftedTypeKind contents <- trIO$ IO$ \w -> readMutVar# (unsafeCoerce# a) w ASSERT(isUnliftedTypeKind $ typeKind my_ty) return () (mutvar_ty,_) <- instScheme $ quantifyType $ mkFunTy contents_ty (mkTyConApp tycon [world,contents_ty]) addConstraint (mkFunTy contents_tv my_ty) mutvar_ty x <- go (pred max_depth) contents_tv contents_ty contents return (RefWrap my_ty x) -- The interesting case Constr -> do traceTR (text "entering a constructor " <> if monomorphic then parens (text "already monomorphic: " <> ppr my_ty) else Ppr.empty) Right dcname <- dataConInfoPtrToName (infoPtr clos) (_,mb_dc) <- tryTcErrs (tcLookupDataCon dcname) case mb_dc of Nothing -> do -- This can happen for private constructors compiled -O0 -- where the .hi descriptor does not export them -- In such case, we return a best approximation: -- ignore the unpointed args, and recover the pointeds -- This preserves laziness, and should be safe. traceTR (text "Not constructor" <+> ppr dcname) let dflags = hsc_dflags hsc_env tag = showPpr dflags dcname vars <- replicateM (length$ elems$ ptrs clos) (newVar liftedTypeKind) subTerms <- sequence [appArr (go (pred max_depth) tv tv) (ptrs clos) i | (i, tv) <- zip [0..] vars] return (Term my_ty (Left ('<' : tag ++ ">")) a subTerms) Just dc -> do traceTR (text "Is constructor" <+> (ppr dc $$ ppr my_ty)) subTtypes <- getDataConArgTys dc my_ty subTerms <- extractSubTerms (\ty -> go (pred max_depth) ty ty) clos subTtypes return (Term my_ty (Right dc) a subTerms) -- The otherwise case: can be a Thunk,AP,PAP,etc. tipe_clos -> return (Suspension tipe_clos my_ty a Nothing) -- insert NewtypeWraps around newtypes expandNewtypes = foldTerm idTermFold { fTerm = worker } where worker ty dc hval tt | Just (tc, args) <- tcSplitTyConApp_maybe ty , isNewTyCon tc , wrapped_type <- newTyConInstRhs tc args , Just dc' <- tyConSingleDataCon_maybe tc , t' <- worker wrapped_type dc hval tt = NewtypeWrap ty (Right dc') t' | otherwise = Term ty dc hval tt -- Avoid returning types where predicates have been expanded to dictionaries. fixFunDictionaries = foldTerm idTermFold {fSuspension = worker} where worker ct ty hval n | isFunTy ty = Suspension ct (dictsView ty) hval n | otherwise = Suspension ct ty hval n extractSubTerms :: (Type -> HValue -> TcM Term) -> Closure -> [Type] -> TcM [Term] extractSubTerms recurse clos = liftM thirdOf3 . go 0 (nonPtrs clos) where go ptr_i ws [] = return (ptr_i, ws, []) go ptr_i ws (ty:tys) | Just (tc, elem_tys) <- tcSplitTyConApp_maybe ty , isUnboxedTupleTyCon tc = do (ptr_i, ws, terms0) <- go ptr_i ws elem_tys (ptr_i, ws, terms1) <- go ptr_i ws tys return (ptr_i, ws, unboxedTupleTerm ty terms0 : terms1) | otherwise = case repType ty of UnaryRep rep_ty -> do (ptr_i, ws, term0) <- go_rep ptr_i ws ty (typePrimRep rep_ty) (ptr_i, ws, terms1) <- go ptr_i ws tys return (ptr_i, ws, term0 : terms1) UbxTupleRep rep_tys -> do (ptr_i, ws, terms0) <- go_unary_types ptr_i ws rep_tys (ptr_i, ws, terms1) <- go ptr_i ws tys return (ptr_i, ws, unboxedTupleTerm ty terms0 : terms1) go_unary_types ptr_i ws [] = return (ptr_i, ws, []) go_unary_types ptr_i ws (rep_ty:rep_tys) = do tv <- newVar liftedTypeKind (ptr_i, ws, term0) <- go_rep ptr_i ws tv (typePrimRep rep_ty) (ptr_i, ws, terms1) <- go_unary_types ptr_i ws rep_tys return (ptr_i, ws, term0 : terms1) go_rep ptr_i ws ty rep = case rep of PtrRep -> do t <- appArr (recurse ty) (ptrs clos) ptr_i return (ptr_i + 1, ws, t) _ -> do dflags <- getDynFlags let (ws0, ws1) = splitAt (primRepSizeW dflags rep) ws return (ptr_i, ws1, Prim ty ws0) unboxedTupleTerm ty terms = Term ty (Right (tupleCon UnboxedTuple (length terms))) (error "unboxedTupleTerm: no HValue for unboxed tuple") terms -- Fast, breadth-first Type reconstruction ------------------------------------------ cvReconstructType :: HscEnv -> Int -> GhciType -> HValue -> IO (Maybe Type) cvReconstructType hsc_env max_depth old_ty hval = runTR_maybe hsc_env $ do traceTR (text "RTTI started with initial type " <> ppr old_ty) let sigma_old_ty@(old_tvs, _) = quantifyType old_ty new_ty <- if null old_tvs then return old_ty else do (old_ty', rev_subst) <- instScheme sigma_old_ty my_ty <- newVar openTypeKind when (check1 sigma_old_ty) (traceTR (text "check1 passed") >> addConstraint my_ty old_ty') search (isMonomorphic `fmap` zonkTcType my_ty) (\(ty,a) -> go ty a) (Seq.singleton (my_ty, hval)) max_depth new_ty <- zonkTcType my_ty if isMonomorphic new_ty || check2 (quantifyType new_ty) sigma_old_ty then do traceTR (text "check2 passed" <+> ppr old_ty $$ ppr new_ty) addConstraint my_ty old_ty' applyRevSubst rev_subst zonkRttiType new_ty else traceTR (text "check2 failed" <+> parens (ppr new_ty)) >> return old_ty traceTR (text "RTTI completed. Type obtained:" <+> ppr new_ty) return new_ty where dflags = hsc_dflags hsc_env -- search :: m Bool -> ([a] -> [a] -> [a]) -> [a] -> m () search _ _ _ 0 = traceTR (text "Failed to reconstruct a type after " <> int max_depth <> text " steps") search stop expand l d = case viewl l of EmptyL -> return () x :< xx -> unlessM stop $ do new <- expand x search stop expand (xx `mappend` Seq.fromList new) $! (pred d) -- returns unification tasks,since we are going to want a breadth-first search go :: Type -> HValue -> TR [(Type, HValue)] go my_ty a = do traceTR (text "go" <+> ppr my_ty) clos <- trIO $ getClosureData dflags a case tipe clos of Blackhole -> appArr (go my_ty) (ptrs clos) 0 -- carefully, don't eval the TSO Indirection _ -> go my_ty $! (ptrs clos ! 0) MutVar _ -> do contents <- trIO$ IO$ \w -> readMutVar# (unsafeCoerce# a) w tv' <- newVar liftedTypeKind world <- newVar liftedTypeKind addConstraint my_ty (mkTyConApp mutVarPrimTyCon [world,tv']) return [(tv', contents)] Constr -> do Right dcname <- dataConInfoPtrToName (infoPtr clos) traceTR (text "Constr1" <+> ppr dcname) (_,mb_dc) <- tryTcErrs (tcLookupDataCon dcname) case mb_dc of Nothing-> do -- TODO: Check this case forM [0..length (elems $ ptrs clos)] $ \i -> do tv <- newVar liftedTypeKind return$ appArr (\e->(tv,e)) (ptrs clos) i Just dc -> do arg_tys <- getDataConArgTys dc my_ty (_, itys) <- findPtrTyss 0 arg_tys traceTR (text "Constr2" <+> ppr dcname <+> ppr arg_tys) return $ [ appArr (\e-> (ty,e)) (ptrs clos) i | (i,ty) <- itys] _ -> return [] findPtrTys :: Int -- Current pointer index -> Type -- Type -> TR (Int, [(Int, Type)]) findPtrTys i ty | Just (tc, elem_tys) <- tcSplitTyConApp_maybe ty , isUnboxedTupleTyCon tc = findPtrTyss i elem_tys | otherwise = case repType ty of UnaryRep rep_ty | typePrimRep rep_ty == PtrRep -> return (i + 1, [(i, ty)]) | otherwise -> return (i, []) UbxTupleRep rep_tys -> foldM (\(i, extras) rep_ty -> if typePrimRep rep_ty == PtrRep then newVar liftedTypeKind >>= \tv -> return (i + 1, extras ++ [(i, tv)]) else return (i, extras)) (i, []) rep_tys findPtrTyss :: Int -> [Type] -> TR (Int, [(Int, Type)]) findPtrTyss i tys = foldM step (i, []) tys where step (i, discovered) elem_ty = findPtrTys i elem_ty >>= \(i, extras) -> return (i, discovered ++ extras) -- Compute the difference between a base type and the type found by RTTI -- improveType <base_type> <rtti_type> -- The types can contain skolem type variables, which need to be treated as normal vars. -- In particular, we want them to unify with things. improveRTTIType :: HscEnv -> RttiType -> RttiType -> Maybe TvSubst improveRTTIType _ base_ty new_ty = U.tcUnifyTy base_ty new_ty getDataConArgTys :: DataCon -> Type -> TR [Type] -- Given the result type ty of a constructor application (D a b c :: ty) -- return the types of the arguments. This is RTTI-land, so 'ty' might -- not be fully known. Moreover, the arg types might involve existentials; -- if so, make up fresh RTTI type variables for them -- -- I believe that con_app_ty should not have any enclosing foralls getDataConArgTys dc con_app_ty = do { let UnaryRep rep_con_app_ty = repType con_app_ty ; traceTR (text "getDataConArgTys 1" <+> (ppr con_app_ty $$ ppr rep_con_app_ty $$ ppr (tcSplitTyConApp_maybe rep_con_app_ty))) ; (_, _, subst) <- instTyVars (univ_tvs ++ ex_tvs) ; addConstraint rep_con_app_ty (substTy subst (dataConOrigResTy dc)) -- See Note [Constructor arg types] ; let con_arg_tys = substTys subst (dataConRepArgTys dc) ; traceTR (text "getDataConArgTys 2" <+> (ppr rep_con_app_ty $$ ppr con_arg_tys $$ ppr subst)) ; return con_arg_tys } where univ_tvs = dataConUnivTyVars dc ex_tvs = dataConExTyVars dc {- Note [Constructor arg types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider a GADT (cf Trac #7386) data family D a b data instance D [a] a where MkT :: a -> D [a] (Maybe a) ... In getDataConArgTys * con_app_ty is the known type (from outside) of the constructor application, say D [Int] Int * The data constructor MkT has a (representation) dataConTyCon = DList, say where data DList a where MkT :: a -> DList a (Maybe a) ... So the dataConTyCon of the data constructor, DList, differs from the "outside" type, D. So we can't straightforwardly decompose the "outside" type, and we end up in the "_" branch of the case. Then we match the dataConOrigResTy of the data constructor against the outside type, hoping to get a substitution that tells how to instantiate the *representation* type constructor. This looks a bit delicate to me, but it seems to work. -} -- Soundness checks -------------------- {- This is not formalized anywhere, so hold to your seats! RTTI in the presence of newtypes can be a tricky and unsound business. Example: ~~~~~~~~~ Suppose we are doing RTTI for a partially evaluated closure t, the real type of which is t :: MkT Int, for newtype MkT a = MkT [Maybe a] The table below shows the results of RTTI and the improvement calculated for different combinations of evaluatedness and :type t. Regard the two first columns as input and the next two as output. # | t | :type t | rtti(t) | improv. | result ------------------------------------------------------------ 1 | _ | t b | a | none | OK 2 | _ | MkT b | a | none | OK 3 | _ | t Int | a | none | OK If t is not evaluated at *all*, we are safe. 4 | (_ : _) | t b | [a] | t = [] | UNSOUND 5 | (_ : _) | MkT b | MkT a | none | OK (compensating for the missing newtype) 6 | (_ : _) | t Int | [Int] | t = [] | UNSOUND If a is a minimal whnf, we run into trouble. Note that row 5 above does newtype enrichment on the ty_rtty parameter. 7 | (Just _:_)| t b |[Maybe a] | t = [], | UNSOUND | | | b = Maybe a| 8 | (Just _:_)| MkT b | MkT a | none | OK 9 | (Just _:_)| t Int | FAIL | none | OK And if t is any more evaluated than whnf, we are still in trouble. Because constraints are solved in top-down order, when we reach the Maybe subterm what we got is already unsound. This explains why the row 9 fails to complete. 10 | (Just _:_)| t Int | [Maybe a] | FAIL | OK 11 | (Just 1:_)| t Int | [Maybe Int] | FAIL | OK We can undo the failure in row 9 by leaving out the constraint coming from the type signature of t (i.e., the 2nd column). Note that this type information is still used to calculate the improvement. But we fail when trying to calculate the improvement, as there is no unifier for t Int = [Maybe a] or t Int = [Maybe Int]. Another set of examples with t :: [MkT (Maybe Int)] \equiv [[Maybe (Maybe Int)]] # | t | :type t | rtti(t) | improvement | result --------------------------------------------------------------------- 1 |(Just _:_) | [t (Maybe a)] | [[Maybe b]] | t = [] | | | | | b = Maybe a | The checks: ~~~~~~~~~~~ Consider a function obtainType that takes a value and a type and produces the Term representation and a substitution (the improvement). Assume an auxiliar rtti' function which does the actual job if recovering the type, but which may produce a false type. In pseudocode: rtti' :: a -> IO Type -- Does not use the static type information obtainType :: a -> Type -> IO (Maybe (Term, Improvement)) obtainType v old_ty = do rtti_ty <- rtti' v if monomorphic rtti_ty || (check rtti_ty old_ty) then ... else return Nothing where check rtti_ty old_ty = check1 rtti_ty && check2 rtti_ty old_ty check1 :: Type -> Bool check2 :: Type -> Type -> Bool Now, if rtti' returns a monomorphic type, we are safe. If that is not the case, then we consider two conditions. 1. To prevent the class of unsoundness displayed by rows 4 and 7 in the example: no higher kind tyvars accepted. check1 (t a) = NO check1 (t Int) = NO check1 ([] a) = YES 2. To prevent the class of unsoundness shown by row 6, the rtti type should be structurally more defined than the old type we are comparing it to. check2 :: NewType -> OldType -> Bool check2 a _ = True check2 [a] a = True check2 [a] (t Int) = False check2 [a] (t a) = False -- By check1 we never reach this equation check2 [Int] a = True check2 [Int] (t Int) = True check2 [Maybe a] (t Int) = False check2 [Maybe Int] (t Int) = True check2 (Maybe [a]) (m [Int]) = False check2 (Maybe [Int]) (m [Int]) = True -} check1 :: QuantifiedType -> Bool check1 (tvs, _) = not $ any isHigherKind (map tyVarKind tvs) where isHigherKind = not . null . fst . splitKindFunTys check2 :: QuantifiedType -> QuantifiedType -> Bool check2 (_, rtti_ty) (_, old_ty) | Just (_, rttis) <- tcSplitTyConApp_maybe rtti_ty = case () of _ | Just (_,olds) <- tcSplitTyConApp_maybe old_ty -> and$ zipWith check2 (map quantifyType rttis) (map quantifyType olds) _ | Just _ <- splitAppTy_maybe old_ty -> isMonomorphicOnNonPhantomArgs rtti_ty _ -> True | otherwise = True -- Dealing with newtypes -------------------------- {- congruenceNewtypes does a parallel fold over two Type values, compensating for missing newtypes on both sides. This is necessary because newtypes are not present in runtime, but sometimes there is evidence available. Evidence can come from DataCon signatures or from compile-time type inference. What we are doing here is an approximation of unification modulo a set of equations derived from newtype definitions. These equations should be the same as the equality coercions generated for newtypes in System Fc. The idea is to perform a sort of rewriting, taking those equations as rules, before launching unification. The caller must ensure the following. The 1st type (lhs) comes from the heap structure of ptrs,nptrs. The 2nd type (rhs) comes from a DataCon type signature. Rewriting (i.e. adding/removing a newtype wrapper) can happen in both types, but in the rhs it is restricted to the result type. Note that it is very tricky to make this 'rewriting' work with the unification implemented by TcM, where substitutions are operationally inlined. The order in which constraints are unified is vital as we cannot modify anything that has been touched by a previous unification step. Therefore, congruenceNewtypes is sound only if the types recovered by the RTTI mechanism are unified Top-Down. -} congruenceNewtypes :: TcType -> TcType -> TR (TcType,TcType) congruenceNewtypes lhs rhs = go lhs rhs >>= \rhs' -> return (lhs,rhs') where go l r -- TyVar lhs inductive case | Just tv <- getTyVar_maybe l , isTcTyVar tv , isMetaTyVar tv = recoverTR (return r) $ do Indirect ty_v <- readMetaTyVar tv traceTR $ fsep [text "(congruence) Following indirect tyvar:", ppr tv, equals, ppr ty_v] go ty_v r -- FunTy inductive case | Just (l1,l2) <- splitFunTy_maybe l , Just (r1,r2) <- splitFunTy_maybe r = do r2' <- go l2 r2 r1' <- go l1 r1 return (mkFunTy r1' r2') -- TyconApp Inductive case; this is the interesting bit. | Just (tycon_l, _) <- tcSplitTyConApp_maybe lhs , Just (tycon_r, _) <- tcSplitTyConApp_maybe rhs , tycon_l /= tycon_r = upgrade tycon_l r | otherwise = return r where upgrade :: TyCon -> Type -> TR Type upgrade new_tycon ty | not (isNewTyCon new_tycon) = do traceTR (text "(Upgrade) Not matching newtype evidence: " <> ppr new_tycon <> text " for " <> ppr ty) return ty | otherwise = do traceTR (text "(Upgrade) upgraded " <> ppr ty <> text " in presence of newtype evidence " <> ppr new_tycon) (_, vars, _) <- instTyVars (tyConTyVars new_tycon) let ty' = mkTyConApp new_tycon vars UnaryRep rep_ty = repType ty' _ <- liftTcM (unifyType ty rep_ty) -- assumes that reptype doesn't ^^^^ touch tyconApp args return ty' zonkTerm :: Term -> TcM Term zonkTerm = foldTermM (TermFoldM { fTermM = \ty dc v tt -> zonkRttiType ty >>= \ty' -> return (Term ty' dc v tt) , fSuspensionM = \ct ty v b -> zonkRttiType ty >>= \ty -> return (Suspension ct ty v b) , fNewtypeWrapM = \ty dc t -> zonkRttiType ty >>= \ty' -> return$ NewtypeWrap ty' dc t , fRefWrapM = \ty t -> return RefWrap `ap` zonkRttiType ty `ap` return t , fPrimM = (return.) . Prim }) zonkRttiType :: TcType -> TcM Type -- Zonk the type, replacing any unbound Meta tyvars -- by skolems, safely out of Meta-tyvar-land zonkRttiType = zonkTcTypeToType (mkEmptyZonkEnv zonk_unbound_meta) where zonk_unbound_meta tv = ASSERT( isTcTyVar tv ) do { tv' <- skolemiseUnboundMetaTyVar tv RuntimeUnk -- This is where RuntimeUnks are born: -- otherwise-unconstrained unification variables are -- turned into RuntimeUnks as they leave the -- typechecker's monad ; return (mkTyVarTy tv') } -------------------------------------------------------------------------------- -- Restore Class predicates out of a representation type dictsView :: Type -> Type dictsView ty = ty -- Use only for RTTI types isMonomorphic :: RttiType -> Bool isMonomorphic ty = noExistentials && noUniversals where (tvs, _, ty') = tcSplitSigmaTy ty noExistentials = isEmptyVarSet (tyVarsOfType ty') noUniversals = null tvs -- Use only for RTTI types isMonomorphicOnNonPhantomArgs :: RttiType -> Bool isMonomorphicOnNonPhantomArgs ty | UnaryRep rep_ty <- repType ty , Just (tc, all_args) <- tcSplitTyConApp_maybe rep_ty , phantom_vars <- tyConPhantomTyVars tc , concrete_args <- [ arg | (tyv,arg) <- tyConTyVars tc `zip` all_args , tyv `notElem` phantom_vars] = all isMonomorphicOnNonPhantomArgs concrete_args | Just (ty1, ty2) <- splitFunTy_maybe ty = all isMonomorphicOnNonPhantomArgs [ty1,ty2] | otherwise = isMonomorphic ty tyConPhantomTyVars :: TyCon -> [TyVar] tyConPhantomTyVars tc | isAlgTyCon tc , Just dcs <- tyConDataCons_maybe tc , dc_vars <- concatMap dataConUnivTyVars dcs = tyConTyVars tc \\ dc_vars tyConPhantomTyVars _ = [] type QuantifiedType = ([TyVar], Type) -- Make the free type variables explicit -- The returned Type should have no top-level foralls (I believe) quantifyType :: Type -> QuantifiedType -- Generalize the type: find all free and forall'd tyvars -- and return them, together with the type inside, which -- should not be a forall type. -- -- Thus (quantifyType (forall a. a->[b])) -- returns ([a,b], a -> [b]) quantifyType ty = (varSetElems (tyVarsOfType rho), rho) where (_tvs, rho) = tcSplitForAllTys ty unlessM :: Monad m => m Bool -> m () -> m () unlessM condM acc = condM >>= \c -> unless c acc -- Strict application of f at index i appArr :: Ix i => (e -> a) -> Array i e -> Int -> a appArr f a@(Array _ _ _ ptrs#) i@(I# i#) = ASSERT2(i < length(elems a), ppr(length$ elems a, i)) case indexArray# ptrs# i# of (# e #) -> f e amap' :: (t -> b) -> Array Int t -> [b] amap' f (Array i0 i _ arr#) = map g [0 .. i - i0] where g (I# i#) = case indexArray# arr# i# of (# e #) -> f e
frantisekfarka/ghc-dsi
compiler/ghci/RtClosureInspect.hs
bsd-3-clause
52,711
29
27
16,099
12,166
6,188
5,978
-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="bs-BA"> <title>Regular Expression Tester</title> <maps> <homeID>regextester</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>
thc202/zap-extensions
addOns/regextester/src/main/javahelp/help_bs_BA/helpset_bs_BA.hs
apache-2.0
978
77
66
157
409
207
202
-1
-1
module PropSyntaxUtil(module HsConstants,module PropSyntaxUtil) where import HsConstants import PropSyntax(hsTyCon,HsType) -- Built-in type constructors/names unit_tycon = hsTyCon unit_tycon_name :: HsType fun_tycon = hsTyCon fun_tycon_name :: HsType list_tycon = hsTyCon list_tycon_name :: HsType tuple_tycon i = hsTyCon $ tuple_tycon_name i :: HsType
forste/haReFork
tools/property/syntax/PropSyntaxUtil.hs
bsd-3-clause
390
0
6
77
80
47
33
7
1
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, FlexibleContexts, UndecidableInstances #-} -- Example of improvement, due to George Russel module Folders where data Folder = Folder newtype SB x = SB x newtype SS x = SS x data NodeArcsHidden = NodeArcsHidden class HasSS hasS x | hasS -> x where toSS :: hasS -> SS x instance HasSS (SB x) x where toSS (SB x) = (SS x) class HMV option graph node where modd :: option -> graph -> node value -> IO () instance HMV NodeArcsHidden graph node => HMV (Maybe NodeArcsHidden) graph node where modd = error "burk" gn :: HMV NodeArcsHidden graph node => graph -> SS (graph -> node Int -> IO ()) gn graph = fmapSS (\ arcsHidden -> (\ graph node -> modd arcsHidden graph node)) (toSS (error "C" :: SB (Maybe NodeArcsHidden))) -- The call to modd gives rise to -- HMV option graph node -- The call to toSS gives rise to -- HasSS (SB (Maybe NodeArcsHidden)) x -- where (toSS (error ...)) :: SS x -- and hence arcsHidden :: x -- -- Then improvement should give x = Maybe NodeArcsHidden -- and hence option=Maybe NodeArcsHidden fmapSS :: (a->b) -> SS a -> SS b fmapSS = error "urk"
ryantm/ghc
testsuite/tests/typecheck/should_compile/tc181.hs
bsd-3-clause
1,219
2
12
280
327
173
154
23
1
module Compose where -- (.) :: (b -> c) -> (a -> b) -> a -> c -- Compose :: (* -> *) -> (* -> *) -> * -> * newtype Compose f g a = Compose { getCompose :: f (g a) } deriving (Eq, Show) -- (fmap . fmap) (+1) (Compose [Just (Compose $ Just [1])]) instance (Functor f, Functor g) => Functor (Compose f g) where fmap f (Compose fga) = Compose $ (fmap . fmap) f fga -- (Compose (Just [(+1)])) <*> (Compose (Just [5])) instance (Applicative f, Applicative g) => Applicative (Compose f g) where pure = Compose . (pure . pure) (Compose f) <*> (Compose x) = Compose $ ((<*>) <$> f) <*> x
JoshuaGross/haskell-learning-log
Code/Haskellbook/ComposeTypes/src/Compose.hs
mit
592
0
9
134
194
107
87
7
0
{-# LANGUAGE OverloadedStrings #-} {-| Module : Network.Wai.Twilio.RequestValidatorMiddleware Description : A wai middleware for validating incoming Twilio requests Copyright : (c) 2015 Steve Kollmansberger Maintainer : [email protected] Stability : experimental See https://www.twilio.com/docs/security for details. Twilio includes an X-Twilio-Signature in each request, signing the request using your API auth token. -} module Network.Wai.Twilio.RequestValidatorMiddleware (requestValidator) where import qualified Crypto.MAC.HMAC as HMAC import qualified Crypto.Hash.SHA1 as SHA1 import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Lazy as BL import Data.ByteString.Builder import Data.ByteString.Base64 import Data.List import Data.Monoid import Data.IORef import Network.HTTP.Types import Network.Wai import Network.Wai.Middleware.Approot url :: B.ByteString -> Request -> Builder url approot r = "http" <> (if isSecure r then "s" else "") <> "://" <> (byteString $ maybe "" id (requestHeaderHost r)) <> (byteString approot) <> (byteString $ rawPathInfo r) <> (byteString $ rawQueryString r) -- load request bytestring using Wai strictRequestBody postParams :: B.ByteString -> Builder postParams r = foldl (<>) "" stringified where ordered = sortBy (\a b -> compare (fst a) (fst b)) (parseQuery r) stringified = map (\(k, mv) -> byteString k <> (byteString $ maybe "" id mv)) ordered hmacsha1 = HMAC.hmac SHA1.hash 64 signature :: B.ByteString -> Builder -> B.ByteString signature authtoken contents = encode $ hmacsha1 authtoken rbs where rbs = BL.toStrict $ toLazyByteString contents calcSignature :: B.ByteString -> Request -> B.ByteString -> B.ByteString calcSignature authtoken r rb = let rootUrl = maybe "" id (getApprootMay r) url' = url rootUrl r requestbody' = case requestMethod r of "POST" -> postParams rb _ -> "" in signature authtoken (url' <> requestbody') verifySignature :: B.ByteString -> B.ByteString -> Request -> IO Bool verifySignature authtoken body r = case lookup "X-Twilio-Signature" $ requestHeaders r of Nothing -> return False -- If signature missing from request, must not be valid (Just givenSignature) -> return $ (givenSignature ==) $ calcSignature authtoken r $ body readRequestBodyAndPushback :: Request -> IO (B.ByteString, IO B.ByteString) readRequestBodyAndPushback req = do -- This loop body and then the ichunks rbody stuff comes from http://hackage.haskell.org/package/wai-extra-3.0.3.2/docs/src/Network-Wai-Middleware-RequestLogger.html -- ** BEGIN READ BODY let loop front = do bs <- requestBody req if BC.null bs then return $ front [] else loop $ front . (bs:) body <- loop id -- ** END READ BODY -- ** BEGIN BODY PUSHBACK ichunks <- newIORef body let rbody = atomicModifyIORef ichunks $ \chunks -> case chunks of [] -> ([], BC.empty) x:y -> (y, x) -- ** END BODY PUSHBACK return (B.concat body, rbody) -- | Middleware to validate Twilio request. Parameterized by API auth token. -- Returns 401 Unauthorized if the request does not contain a valid signature based on the given auth token. requestValidator :: B.ByteString -- ^ AuthToken from your Twilio page -> Middleware requestValidator authtoken app req respond = do -- strictRequestBody appears to work only once, so we re-insert result into request when validated. (body, rbody) <- readRequestBodyAndPushback req vs <- verifySignature authtoken body req case vs of False -> respond $ responseLBS unauthorized401 [] "Invalid X-Twilio-Signature" True -> app (req {requestBody = rbody}) respond
steven777400/TwilioIVR
src/Network/Wai/Twilio/RequestValidatorMiddleware.hs
mit
3,916
0
16
861
899
477
422
66
3
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE OverloadedStrings #-} module Network.Sendgrid.Api ( Authentication(..) , EmailMessage(..) , MailSuccess(..) , makeRequest , getRequest , postRequest , sendEmail ) where import Control.Applicative ((<$>), (<*>)) import Control.Monad (mzero) import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Trans.Control import qualified Data.Aeson as Aeson import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy as L import Data.List (partition) import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) import qualified Data.Text as T import Network.HTTP.Conduit import Network.Sendgrid.Utils (urlEncode) baseUrl :: String baseUrl = "https://api.sendgrid.com/api/" class Tupled a where asTuple :: a -> [(String, String)] data Authentication = Authentication { user :: String , key :: String } deriving ( Show ) instance Tupled Authentication where asTuple a = [ ("api_user", u) , ("api_key", k) ] where u = user a k = key a data EmailMessage = EmailMessage { to :: String , from :: String , subject :: String , text :: Maybe String , html :: Maybe String } deriving ( Eq, Show ) instance Tupled EmailMessage where asTuple a = let t = (to a) f = (from a) s = (subject a) x = (text a) h = (html a) in [ ("to", t) , ("from", f) , ("subject", s) , ("text", fromMaybe "" x) , ("html", fromMaybe "" h) ] urlEncodeVars :: [(String,String)] -> String urlEncodeVars [] = [] urlEncodeVars ((n,v):t) = let (same,diff) = partition ((==n) . fst) t in urlEncode n ++ '=' : foldl (\x y -> x ++ ',' : urlEncode y) (urlEncode $ v) (map snd same) ++ urlEncodeRest diff where urlEncodeRest [] = [] urlEncodeRest diff = '&' : urlEncodeVars diff data Method = GET | POST class AsByteString a where asByteString :: a -> BS.ByteString showBS :: Show a => a -> BS.ByteString showBS = BS.pack . show instance AsByteString Method where asByteString = showBS instance Show Method where show GET = "GET" show POST = "POST" -- | HTTP request helpers makeRequest :: (MonadBaseControl IO m, MonadIO m, MonadThrow m, Show a) => a -> String -> [(String, String)] -> m L.ByteString makeRequest method url body = let rBody = BS.pack . urlEncodeVars $ body in do initReq <- parseUrl url let req = initReq { method = showBS method , requestHeaders = [ ("content-type", "application/x-www-form-urlencoded") ] , requestBody = RequestBodyBS $ rBody } response <- withManager $ httpLbs req return $ responseBody response postRequest :: (MonadThrow m, MonadIO m, MonadBaseControl IO m) => String -> [ (String, String) ] -> m L.ByteString postRequest = makeRequest POST getRequest :: (MonadThrow m, MonadIO m, MonadBaseControl IO m) => String -> [ (String, String) ] -> m L.ByteString getRequest = makeRequest GET data Profile = Profile { profileUsername :: String , profileEmail :: String , profileActive :: String , profileFirstName :: String , profileLastName :: String , profileAddress :: String , profileCity :: String , profileState :: String , profileZip :: String , profileCountry :: String , profilePhone :: String , profileWebsite :: String } deriving ( Show ) instance Aeson.FromJSON Profile where parseJSON (Aeson.Object o) = Profile <$> o Aeson..: "username" <*> o Aeson..: "email" <*> o Aeson..: "active" <*> o Aeson..: "first_name" <*> o Aeson..: "last_name" <*> o Aeson..: "address" <*> o Aeson..: "city" <*> o Aeson..: "state" <*> o Aeson..: "zip" <*> o Aeson..: "country" <*> o Aeson..: "phone" <*> o Aeson..: "website" parseJSON _ = mzero getProfile :: (MonadThrow m, MonadIO m, MonadBaseControl IO m, Tupled a) => a -> m (L.ByteString) getProfile auth = makeRequest POST (baseUrl <> "profile.get.json") (asTuple auth) data MailSuccess = MailSuccess { message :: String } deriving ( Show ) instance Aeson.FromJSON MailSuccess where parseJSON (Aeson.Object o) = MailSuccess <$> o Aeson..: "message" parseJSON _ = mzero -- | Send an email message i.e sendEmail (Authentication "FOO" "BAR") (Message ...) sendEmail :: (Tupled a, Tupled b) => a -> b -> IO (Maybe MailSuccess) sendEmail auth message = let fullUrl = baseUrl <> "mail.send.json" response = makeRequest POST fullUrl (asTuple auth <> asTuple message) in Aeson.decode <$> response
owainlewis/sendgrid-hs
src/Network/Sendgrid/Api.hs
mit
5,150
0
29
1,539
1,517
842
675
149
2
-- By listing the first six prime numbers: -- -- 2, 3, 5, 7, 11, 13 -- -- we can see that the 6th prime is 13. -- -- What is the 10 001st prime number? import Numbers result = head $ drop 9999 $ primes [3, 5 ..] main = do putStrLn $ show result
carletes/project-euler
problem-7.hs
mit
253
0
8
64
52
30
22
4
1
module Text.Marquee.SyntaxTrees.AST where import Data.Text (Text(), append, empty) import qualified Data.Map as M import Data.Text.Marquee import Text.Marquee.SyntaxTrees.CST as C type Markdown = [MarkdownElement] data MarkdownElement = BlankLine | ThematicBreak | Heading Int MarkdownInline | Indented Text | Fenced Text Text | HTML Text | Paragraph MarkdownInline | Blockquote [MarkdownElement] | UnorderedList [Markdown] | OrderedList [(Int, Markdown)] deriving (Eq, Show) data MarkdownInline = NoInline | LineBreak | HardLineBreak | Text Text -- Special | Codespan Text | Bold MarkdownInline | Italic MarkdownInline | Link MarkdownInline Text (Maybe Text) | Image MarkdownInline Text (Maybe Text) | HTMLText Text -- Cons | Cons MarkdownInline MarkdownInline deriving (Eq, Show) -- -- instance Show MarkdownInline where -- -- show NoInline = "" -- -- show LineEnding = "\n" -- -- show (Text xs) = xs -- -- show (Codespan xs) = "`" ++ xs ++ "`" -- -- show (Bold xs) = "**" ++ show xs ++ "**" -- -- show (Italic xs) = "*" ++ show xs ++ "*" -- -- show (Link xs url mtitle) = "[" ++ show xs ++ "]" ++ "(" ++ url ++ ")" -- -- show (Cons x y) = show x ++ show y cons :: MarkdownInline -> MarkdownInline -> MarkdownInline cons x NoInline = x cons NoInline y = y cons (Text xs) (Text ys) = Text (xs `append` ys) cons (Text xs) (Cons (Text ys) zs) = cons (Text $ xs `append` ys) zs cons x y = Cons x y infixr 5 <#> (<#>) :: MarkdownInline -> MarkdownInline -> MarkdownInline (<#>) = cons noInline :: MarkdownInline noInline = NoInline lineBreak :: MarkdownInline lineBreak = LineBreak softLineBreak :: MarkdownInline softLineBreak = LineBreak hardLineBreak :: MarkdownInline hardLineBreak = HardLineBreak text :: Text -> MarkdownInline text = Text codespan :: Text -> MarkdownInline codespan = Codespan . trim em :: MarkdownInline -> MarkdownInline em (Italic xs) = Bold xs em xs = Italic xs link :: MarkdownInline -> Text -> Maybe Text -> MarkdownInline link = Link image :: MarkdownInline -> Text -> Maybe Text -> MarkdownInline image = Image htmlText :: Text -> MarkdownInline htmlText = HTMLText containsLink :: MarkdownInline -> Bool containsLink (Link _ _ _) = True containsLink (Cons x y) = containsLink x || containsLink y containsLink _ = False plain :: MarkdownInline -> Text plain (Text x) = x plain (Codespan x) = x plain (Bold x) = plain x plain (Italic x) = plain x plain (Link x _ _) = plain x plain (Cons x y) = plain x `append` plain y plain _ = empty -- -- CST to AST type Link = (Text, Maybe Text) type LinkMap = M.Map Text Link stripLinkReferences :: C.Doc -> (LinkMap, C.Doc) stripLinkReferences = foldr f (M.empty, []) where f (LinkReference ref url mtitle) (map, xs) = (M.insert ref (url, mtitle) map, xs) f x (map, xs) = (map, x : xs)
DanielRS/marquee
src/Text/Marquee/SyntaxTrees/AST.hs
mit
3,446
0
9
1,172
898
501
397
79
2
module Jan24 where import Test.QuickCheck {-- EXTRA LIST COMPREHENSION ------------------------ note that i connects and continues in the second list generator. [ (i,j) | i <- [1..3], j <-[i..3]] = [(i,j) | j <- [1..3]] ++ [(2,j) | j <- [2..3]] ++ [(3,j) | j <- [3..3]] ++ = [(1,1),(1,2),(1,3)] ++ [(2,2),(2,3) ] ++ [(3,3)] ++ = [(1,1),(1,2),(1,3),(2,2),(2,3),(3,3)] -------------------------------------------- -- adding a filter ------------------------------------------- [ (i,j) | i <- [1..3], j <-[1..3], i <= j ] = [ (1,j) | j <- [1..3],1 <= j ] ++ [ (2,j) | j <- [1..3],2 <= j ] ++ [ (3,j) | j <- [1..3],3 <= j ] = [(1,1)|1<=1]++[(1,2)|1<=2]++[(1,3)|1<=3]++ [(2,1)|2<=1]++[(2,2)|2<=2]++[(1,3)|2<=3]++ [(3,1)|3<=1]++[(3,2)|3<=2]++[(3,3)|3<=3] = [(1,1)] ++ [(1,2)] ++ [(1,3)] ++ [] ++ [(2,2)] ++ [(2,3)] ++ [] ++ [] ++ [(3,3)] = [(1,1),(1,2),(1,3),(2,2),(2,3),(3,3)] ------------------------------------------ -- FORMAL DEFINITION FOR LIST COMPREHENSION ------------------------------------------ q ::= x <- l, q | b, q | * [e | * ] -- empty = [e] [e | x <- [l1,...,ln],q] = (let x = l1 in [e | q ]) ++ ... ++ (let x = ln in [e | q ]) [e | b, q ] = if b then [ e | q ] else [] ----------------------------------------- -- HERE IT IS AS A PROGRAM ----------------------------------------- in the lists comprhension they are either drawn from or filters [(i,j) | i <- [1..3], j <- [1..3], i <= j, * ] ---------------------------------------- -- the goal is to a capture a pattern that appears over and over and capture it in a single function. ----------------------------------------} -- MAP -- FILTER -- FOLD -- ---------------------------------------- -- TEMPLATE HASKELL is Meta Haskell which can alter/influence Haskell squares xs = [ x*x | x <- xs] squares' [] = [] squares' (x:xs) = x*x : squares xs prop_sqr xs = squares' xs == squares xs -- prop_ is the predicate that suggests that we will propositionally test an expression / assertion -- our current assertion is that squares' will yield the same result as squares, and we will generate random inputs that conform to the given type latitudes allowed. {- *Jan24> quickCheck prop_sqr Loading package array-0.4.0.1 ... linking ... done. Loading package deepseq-1.3.0.1 ... linking ... done. Loading package old-locale-1.0.0.5 ... linking ... done. Loading package time-1.4.0.1 ... linking ... done. Loading package random-1.0.1.1 ... linking ... done. Loading package containers-0.5.0.0 ... linking ... done. Loading package pretty-1.1.1.0 ... linking ... done. Loading package template-haskell ... linking ... done. Loading package QuickCheck-2.6 ... linking ... done. +++ OK, passed 100 tests. -}
HaskellForCats/HaskellForCats
30MinHaskell/z_notes/3_b_quickCheckt.hs
mit
2,772
0
7
530
95
52
43
6
1
-- Your Ride Is Here -- http://www.codewars.com/kata/55491e9e50f2fc92f3000074/ module Codewars.Kata.Ride where import Codewars.Kata.Ride.Types import Data.Char (ord) ride :: String -> String -> Ride ride a b = if f a == f b then Go else Stay where f = (`mod` 47) . product . map (\c -> ord c - ord 'A' + 1)
gafiatulin/codewars
src/6 kyu/Ride.hs
mit
314
0
13
61
113
64
49
6
2
module Problem52 where {-- Task description: It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. --} import Data.List (sort) sameDigits x y = (==)(sort $ show x) (sort $ show y) allSame :: [Int] -> Bool allSame (x:xs) = all (sameDigits x) xs allSame _ = False vals = [fmap (x*) [2..6] | x <- [1..]] results = flip zip [1..] $ fmap allSame vals solution = snd . head $ filter fst results main = print solution
runjak/projectEuler
src/Problem52.hs
mit
593
0
8
124
179
96
83
10
1
{-# LANGUAGE DeriveGeneric, NoMonomorphismRestriction #-} module HsSearch.SearchOptions ( SearchOption(..) , getSearchOptions , getUsage , settingsFromArgs) where import qualified Data.ByteString.Lazy.Char8 as BC import Data.Char (toLower) import Data.Either (isLeft, lefts, rights) import Data.List (isPrefixOf, sortBy) import Data.Maybe (isJust) import GHC.Generics import Data.Aeson import HsSearch.Paths_hssearch (getDataFileName) import HsSearch.FileTypes (getFileTypeForName) import HsSearch.FileUtil (getFileString) import HsSearch.SearchSettings data SearchOption = SearchOption { long :: String , short :: Maybe String , desc :: String } deriving (Show, Eq, Generic) instance FromJSON SearchOption newtype SearchOptions = SearchOptions {searchoptions :: [SearchOption]} deriving (Show, Eq, Generic) instance FromJSON SearchOptions searchOptionsFile :: FilePath searchOptionsFile = "searchoptions.json" getSearchOptions :: IO [SearchOption] getSearchOptions = do searchOptionsPath <- getDataFileName searchOptionsFile searchOptionsJsonString <- getFileString searchOptionsPath case searchOptionsJsonString of (Left _) -> return [] (Right jsonString) -> case (eitherDecode (BC.pack jsonString) :: Either String SearchOptions) of (Left e) -> return [SearchOption {long=e, short=Nothing, desc=e}] (Right jsonSearchOptions) -> return (searchoptions jsonSearchOptions) getUsage :: [SearchOption] -> String getUsage searchOptions = "Usage:\n hssearch [options] -s <searchpattern> <startpath>\n\nOptions:\n" ++ searchOptionsToString searchOptions getOptStrings :: [SearchOption] -> [String] getOptStrings = map formatOpts where formatOpts SearchOption {long=l, short=Nothing} = getLong l formatOpts SearchOption {long=l, short=Just s} = shortAndLong s l getLong l = "--" ++ l shortAndLong s l = "-" ++ s ++ "," ++ getLong l getOptDesc :: SearchOption -> String getOptDesc SearchOption {desc=""} = error "No description for SearchOption" getOptDesc SearchOption {desc=d} = d sortSearchOption :: SearchOption -> SearchOption -> Ordering sortSearchOption SearchOption {long=l1, short=s1} SearchOption {long=l2, short=s2} = compare (shortOrLong s1 l1) (shortOrLong s2 l2) where shortOrLong Nothing l = l shortOrLong (Just s) l = map toLower s ++ "@" ++ l sortSearchOptions :: [SearchOption] -> [SearchOption] sortSearchOptions = sortBy sortSearchOption padString :: String -> Int -> String padString s len | length s < len = s ++ replicate (len - length s) ' ' | otherwise = s searchOptionsToString :: [SearchOption] -> String searchOptionsToString searchOptions = unlines $ zipWith formatOptLine optStrings optDescs where sorted = sortSearchOptions searchOptions optStrings = getOptStrings sorted optDescs = map getOptDesc sorted longest = maximum $ map length optStrings formatOptLine o d = " " ++ padString o longest ++ " " ++ d data ActionType = ArgActionType | BoolFlagActionType | FlagActionType | UnknownActionType deriving (Show, Eq) type ArgAction = SearchSettings -> String -> SearchSettings type BoolFlagAction = SearchSettings -> Bool -> SearchSettings type FlagAction = SearchSettings -> SearchSettings argActions :: [(String, ArgAction)] argActions = [ ("encoding", \ss s -> ss {textFileEncoding=s}) , ("in-archiveext", \ss s -> ss {inArchiveExtensions = inArchiveExtensions ss ++ newExtensions s}) , ("in-archivefilepattern", \ss s -> ss {inArchiveFilePatterns = inArchiveFilePatterns ss ++ [s]}) , ("in-dirpattern", \ss s -> ss {inDirPatterns = inDirPatterns ss ++ [s]}) , ("in-ext", \ss s -> ss {inExtensions = inExtensions ss ++ newExtensions s}) , ("in-filepattern", \ss s -> ss {inFilePatterns = inFilePatterns ss ++ [s]}) , ("in-filetype", \ss s -> ss {inFileTypes = inFileTypes ss ++ [getFileTypeForName s]}) , ("in-linesafterpattern", \ss s -> ss {inLinesAfterPatterns = inLinesAfterPatterns ss ++ [s]}) , ("in-linesbeforepattern", \ss s -> ss {inLinesBeforePatterns = inLinesBeforePatterns ss ++ [s]}) , ("linesafter", \ss s -> ss {linesAfter = read s}) , ("linesaftertopattern", \ss s -> ss {linesAfterToPatterns = linesAfterToPatterns ss ++ [s]}) , ("linesafteruntilpattern", \ss s -> ss {linesAfterUntilPatterns = linesAfterUntilPatterns ss ++ [s]}) , ("linesbefore", \ss s -> ss {linesBefore = read s}) , ("maxlinelength", \ss s -> ss {maxLineLength = read s}) , ("out-archiveext", \ss s -> ss {outArchiveExtensions = outArchiveExtensions ss ++ newExtensions s}) , ("out-archivefilepattern", \ss s -> ss {outArchiveFilePatterns = outArchiveFilePatterns ss ++ [s]}) , ("out-dirpattern", \ss s -> ss {outDirPatterns = outDirPatterns ss ++ [s]}) , ("out-ext", \ss s -> ss {outExtensions = outExtensions ss ++ newExtensions s}) , ("out-filepattern", \ss s -> ss {outFilePatterns = outFilePatterns ss ++ [s]}) , ("out-filetype", \ss s -> ss {outFileTypes = outFileTypes ss ++ [getFileTypeForName s]}) , ("out-linesafterpattern", \ss s -> ss {outLinesAfterPatterns = outLinesAfterPatterns ss ++ [s]}) , ("out-linesbeforepattern", \ss s -> ss {outLinesBeforePatterns = outLinesBeforePatterns ss ++ [s]}) , ("searchpattern", \ss s -> ss {searchPatterns = searchPatterns ss ++ [s]}) ] flagActions :: [(String, FlagAction)] flagActions = [ ("allmatches", \ss -> ss {firstMatch=False}) , ("archivesonly", \ss -> ss {archivesOnly=True, searchArchives=True}) , ("colorize", \ss -> ss {colorize=True}) , ("debug", \ss -> ss {debug=True, verbose=True}) , ("excludehidden", \ss -> ss {excludeHidden=True}) , ("firstmatch", \ss -> ss {firstMatch=True}) , ("help", \ss -> ss {printUsage=True}) , ("includehidden", \ss -> ss {excludeHidden=False}) , ("listdirs", \ss -> ss {listDirs=True}) , ("listfiles", \ss -> ss {listFiles=True}) , ("listlines", \ss -> ss {listLines=True}) , ("multilinesearch", \ss -> ss {multiLineSearch=True}) , ("nocolorize", \ss -> ss {colorize=False}) , ("noprintmatches", \ss -> ss {printResults=False}) , ("norecursive", \ss -> ss {recursive=False}) , ("nosearcharchives", \ss -> ss {searchArchives=False}) , ("printmatches", \ss -> ss {printResults=True}) , ("recursive", \ss -> ss {recursive=True}) , ("searcharchives", \ss -> ss {searchArchives=True}) , ("uniquelines", \ss -> ss {uniqueLines=True}) , ("verbose", \ss -> ss {verbose=True}) , ("version", \ss -> ss {printVersion=True}) ] boolFlagActions :: [(String, BoolFlagAction)] boolFlagActions = [ ("allmatches", \ss b -> ss {firstMatch=not b}) , ("archivesonly", \ss b -> ss {archivesOnly=b, searchArchives=b}) , ("colorize", \ss b -> ss {colorize=b}) , ("debug", \ss b -> ss {debug=b, verbose=b}) , ("excludehidden", \ss b -> ss {excludeHidden=b}) , ("firstmatch", \ss b -> ss {firstMatch=b}) , ("help", \ss b -> ss {printUsage=b}) , ("includehidden", \ss b -> ss {excludeHidden=not b}) , ("listdirs", \ss b -> ss {listDirs=b}) , ("listfiles", \ss b -> ss {listFiles=b}) , ("listlines", \ss b -> ss {listLines=b}) , ("multilinesearch", \ss b -> ss {multiLineSearch=b}) , ("nocolorize", \ss b -> ss {colorize=not b}) , ("noprintmatches", \ss b -> ss {printResults=not b}) , ("norecursive", \ss b -> ss {recursive=not b}) , ("nosearcharchives", \ss b -> ss {searchArchives=not b}) , ("printmatches", \ss b -> ss {printResults=b}) , ("recursive", \ss b -> ss {recursive=b}) , ("searcharchives", \ss b -> ss {searchArchives=b}) , ("uniquelines", \ss b -> ss {uniqueLines=b}) , ("verbose", \ss b -> ss {verbose=b}) , ("version", \ss b -> ss {printVersion=b}) ] shortToLong :: [SearchOption] -> String -> Either String String shortToLong _ "" = Left "Missing argument" shortToLong opts s | length s == 2 && head s == '-' = if any (\so -> short so == Just (tail s)) optsWithShort then Right $ "--" ++ getLongForShort s else Left $ "Invalid option: " ++ tail s ++ "\n" | otherwise = Right s where optsWithShort = filter (isJust . short) opts getLongForShort x = (long . head . filter (\so -> short so == Just (tail x))) optsWithShort settingsFromArgs :: [SearchOption] -> [String] -> Either String SearchSettings settingsFromArgs opts arguments = if any isLeft longArgs then (Left . head . lefts) longArgs else recSettingsFromArgs defaultSearchSettings $ rights longArgs where recSettingsFromArgs :: SearchSettings -> [String] -> Either String SearchSettings recSettingsFromArgs settings args = case args of [] -> Right settings [a] | "-" `isPrefixOf` a -> case getActionType (argName a) of ArgActionType -> Left $ "Missing value for option: " ++ a ++ "\n" BoolFlagActionType -> recSettingsFromArgs (getBoolFlagAction (argName a) settings True) [] FlagActionType -> recSettingsFromArgs (getFlagAction (argName a) settings) [] UnknownActionType -> Left $ "Invalid option: " ++ a ++ "\n" a:as | "-" `isPrefixOf` a -> case getActionType (argName a) of ArgActionType -> recSettingsFromArgs (getArgAction (argName a) settings (head as)) (tail as) BoolFlagActionType -> recSettingsFromArgs (getBoolFlagAction (argName a) settings True) as FlagActionType -> recSettingsFromArgs (getFlagAction (argName a) settings) as UnknownActionType -> Left $ "Invalid option: " ++ argName a ++ "\n" a:as -> recSettingsFromArgs (settings {startPath=a}) as longArgs :: [Either String String] longArgs = map (shortToLong opts) arguments getActionType :: String -> ActionType getActionType a | isArgAction a = ArgActionType | isBoolFlagAction a = BoolFlagActionType | isFlagAction a = FlagActionType | otherwise = UnknownActionType argName :: String -> String argName = dropWhile (=='-') getArgAction :: String -> ArgAction getArgAction a = snd $ head $ filter (\(x,_) -> a==x) argActions getBoolFlagAction :: String -> BoolFlagAction getBoolFlagAction a = snd $ head $ filter (\(x,_) -> a==x) boolFlagActions getFlagAction :: String -> FlagAction getFlagAction a = snd $ head $ filter (\(x,_) -> a==x) flagActions isArgAction :: String -> Bool isArgAction a = isJust $ lookup a argActions isBoolFlagAction :: String -> Bool isBoolFlagAction a = isJust $ lookup a boolFlagActions isFlagAction :: String -> Bool isFlagAction a = isJust $ lookup a flagActions
clarkcb/xsearch
haskell/hssearch/src/HsSearch/SearchOptions.hs
mit
11,724
0
18
3,164
3,773
2,125
1,648
203
11
{-# LANGUAGE DataKinds #-} import Control.Monad.Trans import Options.Declarative greet :: Flag "g" '["greet"] "STRING" "greeting message" (Def "Hello" String) -> Flag "" '["decolate"] "" "decolate message" Bool -> Arg "NAME" String -> Cmd "Greeting command" () greet msg deco name = do let f x | get deco = "*** " ++ x ++ " ***" | otherwise = x liftIO $ putStrLn $ f $ get msg ++ ", " ++ get name ++ "!" connect :: Flag "h" '["host"] "HOST" "host name" (Def "localhost" String) -> Flag "p" '["port"] "PORT" "port number" (Def "8080" Int ) -> Cmd "Connect command" () connect host port = do let addr = get host ++ ":" ++ show (get port) liftIO $ putStrLn $ "connect to " ++ addr getOptExample :: Flag "o" '["output"] "FILE" "output FILE" (Def "stdout" String) -> Flag "c" '[] "FILE" "input FILE" (Def "stdin" String) -> Flag "L" '["libdir"] "DIR" "library directory" String -> Cmd "GetOpt example" () getOptExample output input libdir = liftIO $ print (get output, get input, get libdir) main :: IO () main = run_ $ Group "Test program for sub commands" [ subCmd "greet" greet , subCmd "connect" connect , subCmd "getopt" getOptExample ]
tanakh/optparse-declarative
example/subcmd.hs
mit
1,276
0
13
342
459
223
236
30
1