code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
module Options.Nested.Types where import Options.Nested.Types.Parser import Control.Applicative import Data.Maybe (isJust) import Data.Monoid import Data.Tree -- | A command tree is a rose tree of the command label and it's optional flag -- parser. type CommandTree a = Forest (String, Maybe a) -- | A list of the acceptable sub-command invocations for a given rose-tree -- schema. executables :: CommandTree b -> [[String]] executables = map (map fst) . filter (isJust . snd . last) . concatMap steps data LabelledArg a = LabelledArg Label a deriving (Show, Eq) data PositionedArg a = PositionedArg a deriving (Show, Eq) data Label = ShortLabel Char | LongLabel String | BothLabels Char String deriving (Show, Eq)
athanclark/optparse-nested
src/Options/Nested/Types.hs
Haskell
bsd-3-clause
804
{-# OPTIONS_GHC -fno-warn-orphans #-} module Lambdasim.Time where import Data.Time hiding (utc) import Data.Ratio ((%)) import Control.Monad (liftM) import Control.Parallel.Strategies import Prelude () import Lambdasim.Prelude addTime :: Time -> UTCTime -> UTCTime addTime x = addUTCTime (toNominalDiffTime x) toNominalDiffTime :: Time -> NominalDiffTime toNominalDiffTime t = fromRational (ps % 1000000000000) where ps = round (t /~ pico second) toMicroseconds :: Time -> Int toMicroseconds t = round (t /~ micro second) toNearestSecond :: UTCTime -> UTCTime toNearestSecond utc = utc { utctDayTime = rounded } where rounded = secondsToDiffTime seconds seconds = round (toRational dayTime) dayTime = utctDayTime utc getRoundedTime :: IO UTCTime getRoundedTime = liftM toNearestSecond getCurrentTime instance NFData UTCTime where rnf x = utctDay x `seq` utctDayTime x `seq` ()
jystic/lambdasim
src/Lambdasim/Time.hs
Haskell
bsd-3-clause
911
module Ling.Rename where import qualified Data.Map as Map import Data.Map (Map) import Data.Maybe (fromMaybe) import Control.Applicative import Control.Lens import Ling.Abs (Name) import Ling.Utils import Ling.Norm -- import Ling.Print.Instances () type Ren = Map Name Name type E a = a -> a class Rename a where rename :: Ren -> E a rename1 :: Rename a => (Name, Name) -> E a rename1 = rename . l2m . pure instance Rename Name where rename f n = fromMaybe n (f ^. at n) instance Rename Term where rename f e0 = case e0 of Def x es -> Def (rename f x) (rename f es) Lam arg t -> Lam (rename f arg) (rename (hideArg arg f) t) TFun arg t -> TFun (rename f arg) (rename (hideArg arg f) t) TSig arg t -> TSig (rename f arg) (rename (hideArg arg f) t) TTyp -> e0 Lit{} -> e0 Ann{} -> error "rename/Ann: impossible" Proc{} -> error "rename/Proc: TODO" TProto{} -> error "rename/TProto: TODO" instance Rename a => Rename (Arg a) where rename f (Arg x e) = Arg (rename f x) (rename f e) instance Rename a => Rename [a] where rename = map . rename instance Rename a => Rename (Maybe a) where rename = fmap . rename hideArg :: Arg a -> E Ren hideArg (Arg x _) = Map.delete x hidePref :: Pref -> E Ren hidePref (Recv _ arg) = hideArg arg hidePref (NewSlice _ x) = Map.delete x hidePref _ = id hidePrefs :: [Pref] -> E Ren hidePrefs = flip (foldr hidePref) instance Rename Pref where rename f pref = case pref of TenSplit c ds -> TenSplit (rename f c) (rename f ds) ParSplit c ds -> ParSplit (rename f c) (rename f ds) Send c e -> Send (rename f c) (rename f e) Recv c arg -> Recv (rename f c) (rename f arg) Nu c d -> Nu (rename f c) (rename f d) NewSlice t x -> NewSlice (rename f t) (rename f x) instance Rename Proc where rename f (Act prefs procs) = Act (rename f prefs) (rename (hidePrefs prefs f) procs) rename f (Ax s c d es) = Ax (rename f s) (rename f c) (rename f d) (rename f es) rename f (At t cs) = At (rename f t) (rename f cs) instance Rename Session where rename f s0 = case s0 of Ten ss -> Ten (rename f ss) Par ss -> Par (rename f ss) Seq ss -> Seq (rename f ss) Snd t s -> Snd (rename f t) (rename f s) Rcv t s -> Rcv (rename f t) (rename f s) Atm p n -> Atm p (rename f n) End -> End instance Rename RSession where rename f (Repl s t) = Repl (rename f s) (rename f t)
jyp/ling
Ling/Rename.hs
Haskell
bsd-3-clause
2,485
import Control.Monad.ST (runST) import Criterion.Main import Data.Complex import Statistics.Sample import Statistics.Transform import Statistics.Correlation.Pearson import System.Random.MWC import qualified Data.Vector.Unboxed as U -- Test sample sample :: U.Vector Double sample = runST $ flip uniformVector 10000 =<< create -- Weighted test sample sampleW :: U.Vector (Double,Double) sampleW = U.zip sample (U.reverse sample) -- Comlex vector for FFT tests sampleC :: U.Vector (Complex Double) sampleC = U.zipWith (:+) sample (U.reverse sample) -- Simple benchmark for functions from Statistics.Sample main :: IO () main = defaultMain [ bgroup "sample" [ bench "range" $ nf (\x -> range x) sample -- Mean , bench "mean" $ nf (\x -> mean x) sample , bench "meanWeighted" $ nf (\x -> meanWeighted x) sampleW , bench "harmonicMean" $ nf (\x -> harmonicMean x) sample , bench "geometricMean" $ nf (\x -> geometricMean x) sample -- Variance , bench "variance" $ nf (\x -> variance x) sample , bench "varianceUnbiased" $ nf (\x -> varianceUnbiased x) sample , bench "varianceWeighted" $ nf (\x -> varianceWeighted x) sampleW -- Correlation , bench "pearson" $ nf (\x -> pearson (U.reverse sample) x) sample , bench "pearson'" $ nf (\x -> pearson' (U.reverse sample) x) sample , bench "pearsonFast" $ nf (\x -> pearsonFast (U.reverse sample) x) sample -- Other , bench "stdDev" $ nf (\x -> stdDev x) sample , bench "skewness" $ nf (\x -> skewness x) sample , bench "kurtosis" $ nf (\x -> kurtosis x) sample -- Central moments , bench "C.M. 2" $ nf (\x -> centralMoment 2 x) sample , bench "C.M. 3" $ nf (\x -> centralMoment 3 x) sample , bench "C.M. 4" $ nf (\x -> centralMoment 4 x) sample , bench "C.M. 5" $ nf (\x -> centralMoment 5 x) sample ] , bgroup "FFT" [ bgroup "fft" [ bench (show n) $ whnf fft (U.take n sampleC) | n <- fftSizes ] , bgroup "ifft" [ bench (show n) $ whnf ifft (U.take n sampleC) | n <- fftSizes ] , bgroup "dct" [ bench (show n) $ whnf dct (U.take n sample) | n <- fftSizes ] , bgroup "dct_" [ bench (show n) $ whnf dct_ (U.take n sampleC) | n <- fftSizes ] , bgroup "idct" [ bench (show n) $ whnf idct (U.take n sample) | n <- fftSizes ] , bgroup "idct_" [ bench (show n) $ whnf idct_ (U.take n sampleC) | n <- fftSizes ] ] ] fftSizes :: [Int] fftSizes = [32,128,512,2048]
bos/statistics
benchmark/bench.hs
Haskell
bsd-2-clause
2,701
{-# LANGUAGE OverloadedStrings #-} module Distribution.Nixpkgs.Haskell.FromCabal.Name ( toNixName, libNixName, buildToolNixName ) where import Data.String import Distribution.Package import Language.Nix -- | Map Cabal names to Nix attribute names. toNixName :: PackageName -> Identifier toNixName (PackageName "") = error "toNixName: invalid empty package name" toNixName (PackageName n) = fromString n -- | Map libraries to Nix packages. -- -- TODO: This list should not be hard-coded here; it belongs into the Nixpkgs -- repository. libNixName :: String -> [Identifier] libNixName "" = [] libNixName "adns" = return "adns" libNixName "alsa" = return "alsaLib" libNixName "alut" = return "freealut" libNixName "appindicator-0.1" = return "appindicator" libNixName "appindicator3-0.1" = return "appindicator" libNixName "asound" = return "alsaLib" libNixName "awesomium-1.6.5" = return "awesomium" libNixName "bz2" = return "bzip2" libNixName "cairo-pdf" = return "cairo" libNixName "cairo-ps" = return "cairo" libNixName "cairo" = return "cairo" libNixName "cairo-svg" = return "cairo" libNixName "CEGUIBase-0.7.7" = return "CEGUIBase" libNixName "CEGUIOgreRenderer-0.7.7" = return "CEGUIOgreRenderer" libNixName "clutter-1.0" = return "clutter" libNixName "crypto" = return "openssl" libNixName "crypt" = [] -- provided by glibc libNixName "curses" = return "ncurses" libNixName "c++" = [] -- What is that? libNixName "dl" = [] -- provided by glibc libNixName "fftw3f" = return "fftwFloat" libNixName "fftw3" = return "fftw" libNixName "gconf-2.0" = return "GConf" libNixName "gconf" = return "GConf" libNixName "gdk-2.0" = return "gtk" libNixName "gdk-pixbuf-2.0" = return "gdk_pixbuf" libNixName "gdk-x11-2.0" = return "gdk_x11" libNixName "gio-2.0" = return "glib" libNixName "glib-2.0" = return "glib" libNixName "GL" = return "mesa" libNixName "GLU" = ["freeglut","mesa"] libNixName "glut" = ["freeglut","mesa"] libNixName "gmime-2.4" = return "gmime" libNixName "gnome-keyring-1" = return "gnome_keyring" libNixName "gnome-keyring" = return "gnome_keyring" libNixName "gnome-vfs-2.0" = return "gnome_vfs" libNixName "gnome-vfs-module-2.0" = return "gnome_vfs_module" libNixName "gobject-2.0" = return "glib" libNixName "gstreamer-0.10" = return "gstreamer" libNixName "gstreamer-audio-0.10" = return "gst_plugins_base" libNixName "gstreamer-base-0.10" = return "gst_plugins_base" libNixName "gstreamer-controller-0.10" = return "gstreamer" libNixName "gstreamer-dataprotocol-0.10" = return "gstreamer" libNixName "gstreamer-net-0.10" = return "gst_plugins_base" libNixName "gstreamer-plugins-base-0.10" = return "gst_plugins_base" libNixName "gthread-2.0" = return "glib" libNixName "gtk+-2.0" = return "gtk" libNixName "gtk+-3.0" = return "gtk3" libNixName "gtkglext-1.0" = return "gtkglext" libNixName "gtksourceview-2.0" = return "gtksourceview" libNixName "gtksourceview-3.0" = return "gtksourceview" libNixName "gtk-x11-2.0" = return "gtk_x11" libNixName "icudata" = return "icu" libNixName "icui18n" = return "icu" libNixName "icuuc" = return "icu" libNixName "idn" = return "libidn" libNixName "IL" = return "libdevil" libNixName "ImageMagick" = return "imagemagick" libNixName "Imlib2" = return "imlib2" libNixName "iw" = return "wirelesstools" libNixName "jack" = return "libjack2" libNixName "jpeg" = return "libjpeg" libNixName "ldap" = return "openldap" libNixName "libavutil" = return "ffmpeg" libNixName "libglade-2.0" = return "libglade" libNixName "libgsasl" = return "gsasl" libNixName "librsvg-2.0" = return "librsvg" libNixName "libsoup-gnome-2.4" = return "libsoup" libNixName "libsystemd" = return "systemd" libNixName "libusb-1.0" = return "libusb" libNixName "libxml-2.0" = return "libxml2" libNixName "libzip" = return "libzip" libNixName "libzmq" = return "zeromq" libNixName "MagickWand" = return "imagemagick" libNixName "magic" = return "file" libNixName "m" = [] -- in stdenv libNixName "mono-2.0" = return "mono" libNixName "mpi" = return "openmpi" libNixName "ncursesw" = return "ncurses" libNixName "netsnmp" = return "net_snmp" libNixName "notify" = return "libnotify" libNixName "odbc" = return "unixODBC" libNixName "panelw" = return "ncurses" libNixName "pangocairo" = return "pango" libNixName "pcap" = return "libpcap" libNixName "pcre" = return "pcre" libNixName "pfs-1.2" = return "pfstools" libNixName "png" = return "libpng" libNixName "poppler-glib" = return "poppler" libNixName "portaudio-2.0" = return "portaudio" libNixName "pq" = return "postgresql" libNixName "pthread" = [] libNixName "pulse-simple" = return "libpulseaudio" libNixName "python-3.3" = return "python3" libNixName "Qt5Core" = return "qt5" libNixName "Qt5Gui" = return "qt5" libNixName "Qt5Qml" = return "qt5" libNixName "Qt5Quick" = return "qt5" libNixName "Qt5Widgets" = return "qt5" libNixName "rtlsdr" = return "rtl-sdr" libNixName "rt" = [] -- in glibc libNixName "ruby1.8" = return "ruby" libNixName "sass" = return "libsass" libNixName "sane-backends" = return "saneBackends" libNixName "SDL2-2.0" = return "SDL2" libNixName "sdl2" = return "SDL2" libNixName "sndfile" = return "libsndfile" libNixName "sodium" = return "libsodium" libNixName "sqlite3" = return "sqlite" libNixName "ssl" = return "openssl" libNixName "stdc++.dll" = [] -- What is that? libNixName "stdc++" = [] -- What is that? libNixName "systemd-journal" = return "systemd" libNixName "tag_c" = return "taglib" libNixName "taglib_c" = return "taglib" libNixName "udev" = return "systemd"; libNixName "uuid" = return "libossp_uuid"; libNixName "vte-2.90" = return "vte" libNixName "wayland-client" = return "wayland" libNixName "wayland-cursor" = return "wayland" libNixName "wayland-egl" = return "mesa" libNixName "wayland-server" = return "wayland" libNixName "webkit-1.0" = return "webkit" libNixName "webkitgtk-3.0" = return "webkit" libNixName "webkitgtk" = return "webkit" libNixName "X11" = return "libX11" libNixName "xau" = return "libXau" libNixName "Xcursor" = return "libXcursor" libNixName "xerces-c" = return "xercesc" libNixName "Xext" = return "libXext" libNixName "xft" = return "libXft" libNixName "Xinerama" = return "libXinerama" libNixName "Xi" = return "libXi" libNixName "xkbcommon" = return "libxkbcommon" libNixName "xml2" = return "libxml2" libNixName "Xpm" = return "libXpm" libNixName "Xrandr" = return "libXrandr" libNixName "Xss" = return "libXScrnSaver" libNixName "Xtst" = return "libXtst" libNixName "Xxf86vm" = return "libXxf86vm" libNixName "zmq" = return "zeromq" libNixName "z" = return "zlib" libNixName x = return (fromString x) -- | Map build tool names to Nix attribute names. buildToolNixName :: String -> [Identifier] buildToolNixName "" = return (error "buildToolNixName: invalid empty dependency name") buildToolNixName "cabal" = return "cabal-install" buildToolNixName "ghc" = [] buildToolNixName "gtk2hsC2hs" = return "gtk2hs-buildtools" buildToolNixName "gtk2hsHookGenerator" = return "gtk2hs-buildtools" buildToolNixName "gtk2hsTypeGen" = return "gtk2hs-buildtools" buildToolNixName "hsc2hs" = [] buildToolNixName x = return (fromString x)
psibi/cabal2nix
src/Distribution/Nixpkgs/Haskell/FromCabal/Name.hs
Haskell
bsd-3-clause
10,974
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls, LambdaCase, TupleSections, GeneralizedNewtypeDeriving #-} module Sound.Pd.Internal where import Foreign.C import Foreign.Ptr import Foreign.StablePtr import Control.Concurrent import Control.Monad import Sound.Pd.OpenAL data FileOpaque type File = Ptr FileOpaque data BindingOpaque type Binding = Ptr BindingOpaque data AtomOpaque type AtomPtr = Ptr AtomOpaque type PdChan = Chan (IO ()) -- Run a command on the Pd thread and block awaiting the result pdRun :: PdChan -> IO a -> IO a pdRun chan action = do result <- newEmptyMVar writeChan chan (action >>= putMVar result) takeMVar result foreign import ccall "startAudio" startAudio :: CInt -> CInt -> StablePtr PdChan -> IO (Ptr OpenALSource) foreign import ccall "stopAudio" stopAudio :: IO () foreign import ccall "libpd_process_float" libpd_process_float :: CInt -> Ptr CFloat -> Ptr CFloat -> IO CInt foreign import ccall "libpd_process_double" libpd_process_double :: CInt -> Ptr CDouble -> Ptr CDouble -> IO CInt foreign import ccall "libpd_process_short" libpd_process_short :: CInt -> Ptr CShort -> Ptr CShort -> IO CInt foreign export ccall processFloat :: StablePtr PdChan -> CInt -> Ptr CFloat -> Ptr CFloat -> IO () processFloat :: StablePtr PdChan -> CInt -> Ptr CFloat -> Ptr CFloat -> IO () processFloat stablePdChan ticks inBuffer outBuffer = do chan <- deRefStablePtr stablePdChan pdRun chan $ void $ libpd_process_float ticks inBuffer outBuffer foreign export ccall processDouble :: StablePtr PdChan -> CInt -> Ptr CDouble -> Ptr CDouble -> IO () processDouble :: StablePtr PdChan -> CInt -> Ptr CDouble -> Ptr CDouble -> IO () processDouble stablePdChan ticks inBuffer outBuffer = do chan <- deRefStablePtr stablePdChan pdRun chan $ void $ libpd_process_double ticks inBuffer outBuffer foreign export ccall processShort :: StablePtr PdChan -> CInt -> Ptr CShort -> Ptr CShort -> IO () processShort :: StablePtr PdChan -> CInt -> Ptr CShort -> Ptr CShort -> IO () processShort stablePdChan ticks inBuffer outBuffer = do chan <- deRefStablePtr stablePdChan pdRun chan $ void $ libpd_process_short ticks inBuffer outBuffer foreign import ccall "libpd_init" libpd_init :: IO () foreign import ccall "libpd_add_to_search_path" libpd_add_to_search_path :: CString -> IO () foreign import ccall "libpd_openfile" libpd_openfile :: CString -> CString -> IO File foreign import ccall "libpd_closefile" libpd_closefile :: File -> IO () foreign import ccall "libpd_getdollarzero" libpd_getdollarzero :: File -> IO CInt foreign import ccall "libpd_bang" libpd_bang :: CString -> IO CInt foreign import ccall "libpd_float" libpd_float :: CString -> CFloat -> IO CInt foreign import ccall "libpd_symbol" libpd_symbol :: CString -> CString -> IO CInt foreign import ccall "libpd_start_message" libpd_start_message :: CInt -> IO CInt foreign import ccall "libpd_finish_message" libpd_finish_message :: CString -> CString -> IO CInt foreign import ccall "libpd_finish_list" libpd_finish_list :: CString -> IO CInt foreign import ccall "libpd_add_float" libpd_add_float :: CFloat -> IO () foreign import ccall "libpd_add_symbol" libpd_add_symbol :: CString -> IO () type CPrintHook = CString -> IO () foreign import ccall "wrapper" mkPrintHook :: CPrintHook -> IO (FunPtr CPrintHook) foreign import ccall "libpd_set_printhook" libpd_set_printhook :: FunPtr CPrintHook -> IO () type CBangHook = CString -> IO () foreign import ccall "wrapper" mkBangHook :: CBangHook -> IO (FunPtr CBangHook) foreign import ccall "libpd_set_banghook" libpd_set_banghook :: FunPtr CBangHook -> IO () type CFloatHook = CString -> CFloat -> IO () foreign import ccall "wrapper" mkFloatHook :: CFloatHook -> IO (FunPtr CFloatHook) foreign import ccall "libpd_set_floathook" libpd_set_floathook :: FunPtr CFloatHook -> IO () type CSymbolHook = CString -> CString -> IO () foreign import ccall "wrapper" mkSymbolHook :: CSymbolHook -> IO (FunPtr CSymbolHook) foreign import ccall "libpd_set_symbolhook" libpd_set_symbolhook :: FunPtr CSymbolHook -> IO () type CListHook = CString -> CInt -> AtomPtr -> IO () foreign import ccall "wrapper" mkListHook :: CListHook -> IO (FunPtr CListHook) foreign import ccall "libpd_set_listhook" libpd_set_listhook :: FunPtr CListHook -> IO () type CMessageHook = CString -> CString -> CInt -> AtomPtr -> IO () foreign import ccall "wrapper" mkMessageHook :: CMessageHook -> IO (FunPtr CMessageHook) foreign import ccall "libpd_set_messagehook" libpd_set_messagehook :: FunPtr CMessageHook -> IO () foreign import ccall "libpd_get_symbol" libpd_get_symbol :: AtomPtr -> IO CString foreign import ccall "libpd_get_float" libpd_get_float :: AtomPtr -> IO CFloat foreign import ccall "libpd_is_symbol" libpd_is_symbol :: AtomPtr -> IO CInt foreign import ccall "libpd_is_float" libpd_is_float :: AtomPtr -> IO CInt foreign import ccall "libpd_next_atom" libpd_next_atom :: AtomPtr -> AtomPtr foreign import ccall "libpd_exists" libpd_exists :: CString -> IO CInt foreign import ccall "libpd_bind" libpd_bind :: CString -> IO Binding foreign import ccall "libpd_unbind" libpd_unbind :: Binding -> IO () -- Arrays foreign import ccall "libpd_arraysize" libpd_arraysize :: CString -> IO CInt foreign import ccall "libpd_read_array" libpd_read_array :: Ptr CFloat -> CString -> CInt -> CInt -> IO CInt foreign import ccall "libpd_write_array" libpd_write_array :: CString -> CInt -> Ptr CFloat -> CInt -> IO CInt
lukexi/pd-hs
src/Sound/Pd/Internal.hs
Haskell
bsd-3-clause
5,558
import Data.List isPossible :: [String] -> String -> (Int, Int) -> (Int, Int) -> Bool isPossible _ [] _ _ = True isPossible grid (w:ws) (x, y) (dx, dy) | x < 10 && y < 10 && (grid !! x !! y == w || grid !! x !! y == '-') = isPossible grid ws (x + dx, y + dy) (dx, dy) | otherwise = False putWords :: [String] -> String -> (Int, Int) -> (Int, Int) -> [String] putWords grid word (x, y) (dx, dy) = [[charAt r c | c <- [0..9]] | r <- [0..9]] where len = length word idx = [(x + dx * i, y + dy * i) | i <- [0..len - 1]] charAt r c = case findIndex (==(r, c)) idx of Nothing -> grid !! r !! c Just i -> word !! i solve :: [String] -> [String] -> String solve grid [] = if (or . map (any (=='-')) $ grid) then "" else intercalate "\n" $ grid solve grid (word:ws) | length ans1 > 0 = ans1 !! 0 | length ans2 > 0 = ans2 !! 0 | otherwise = "" where indices = [(r, c) | r <- [0..9], c <- [0..9]] hi = filter (\idx -> isPossible grid word idx (0, 1)) indices vi = filter (\idx -> isPossible grid word idx (1, 0)) indices ans1 = filter (\sol -> length sol > 0) $ map (\idx -> solve (putWords grid word idx (0, 1)) ws) hi ans2 = filter (\sol -> length sol > 0) $ map (\idx -> solve (putWords grid word idx (1, 0)) ws) vi main :: IO () main = do contents <- getContents let (grid, wordList':_) = splitAt 10 . words $ contents wordList = getWords wordList' putStrLn $ solve grid wordList getWords :: String -> [String] getWords wordList = pre : if null suc then [] else getWords $ tail suc where (pre, suc) = break (\x -> x == ';') wordList
EdisonAlgorithms/HackerRank
practice/fp/recursion/crosswords-101/crosswords-101.hs
Haskell
mit
1,691
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- -- Code generator utilities; mostly monadic -- -- (c) The University of Glasgow 2004-2006 -- ----------------------------------------------------------------------------- module StgCmmUtils ( cgLit, mkSimpleLit, emitDataLits, mkDataLits, emitRODataLits, mkRODataLits, emitRtsCall, emitRtsCallWithResult, emitRtsCallGen, assignTemp, newTemp, newUnboxedTupleRegs, emitMultiAssign, emitCmmLitSwitch, emitSwitch, tagToClosure, mkTaggedObjectLoad, callerSaves, callerSaveVolatileRegs, get_GlobalReg_addr, cmmAndWord, cmmOrWord, cmmNegate, cmmEqWord, cmmNeWord, cmmUGtWord, cmmSubWord, cmmMulWord, cmmAddWord, cmmUShrWord, cmmOffsetExprW, cmmOffsetExprB, cmmRegOffW, cmmRegOffB, cmmLabelOffW, cmmLabelOffB, cmmOffsetW, cmmOffsetB, cmmOffsetLitW, cmmOffsetLitB, cmmLoadIndexW, cmmConstrTag1, cmmUntag, cmmIsTagged, addToMem, addToMemE, addToMemLblE, addToMemLbl, mkWordCLit, newStringCLit, newByteStringCLit, blankWord ) where #include "HsVersions.h" import StgCmmMonad import StgCmmClosure import Cmm import BlockId import MkGraph import CodeGen.Platform import CLabel import CmmUtils import CmmSwitch import ForeignCall import IdInfo import Type import TyCon import SMRep import Module import Literal import Digraph import Util import Unique import UniqSupply (MonadUnique(..)) import DynFlags import FastString import Outputable import qualified Data.ByteString as BS import qualified Data.Map as M import Data.Char import Data.List import Data.Ord import Data.Word ------------------------------------------------------------------------- -- -- Literals -- ------------------------------------------------------------------------- cgLit :: Literal -> FCode CmmLit cgLit (MachStr s) = newByteStringCLit (BS.unpack s) -- not unpackFS; we want the UTF-8 byte stream. cgLit other_lit = do dflags <- getDynFlags return (mkSimpleLit dflags other_lit) mkSimpleLit :: DynFlags -> Literal -> CmmLit mkSimpleLit dflags (MachChar c) = CmmInt (fromIntegral (ord c)) (wordWidth dflags) mkSimpleLit dflags MachNullAddr = zeroCLit dflags mkSimpleLit dflags (MachInt i) = CmmInt i (wordWidth dflags) mkSimpleLit _ (MachInt64 i) = CmmInt i W64 mkSimpleLit dflags (MachWord i) = CmmInt i (wordWidth dflags) mkSimpleLit _ (MachWord64 i) = CmmInt i W64 mkSimpleLit _ (MachFloat r) = CmmFloat r W32 mkSimpleLit _ (MachDouble r) = CmmFloat r W64 mkSimpleLit _ (MachLabel fs ms fod) = CmmLabel (mkForeignLabel fs ms labelSrc fod) where -- TODO: Literal labels might not actually be in the current package... labelSrc = ForeignLabelInThisPackage mkSimpleLit _ other = pprPanic "mkSimpleLit" (ppr other) -------------------------------------------------------------------------- -- -- Incrementing a memory location -- -------------------------------------------------------------------------- addToMemLbl :: CmmType -> CLabel -> Int -> CmmAGraph addToMemLbl rep lbl n = addToMem rep (CmmLit (CmmLabel lbl)) n addToMemLblE :: CmmType -> CLabel -> CmmExpr -> CmmAGraph addToMemLblE rep lbl = addToMemE rep (CmmLit (CmmLabel lbl)) addToMem :: CmmType -- rep of the counter -> CmmExpr -- Address -> Int -- What to add (a word) -> CmmAGraph addToMem rep ptr n = addToMemE rep ptr (CmmLit (CmmInt (toInteger n) (typeWidth rep))) addToMemE :: CmmType -- rep of the counter -> CmmExpr -- Address -> CmmExpr -- What to add (a word-typed expression) -> CmmAGraph addToMemE rep ptr n = mkStore ptr (CmmMachOp (MO_Add (typeWidth rep)) [CmmLoad ptr rep, n]) ------------------------------------------------------------------------- -- -- Loading a field from an object, -- where the object pointer is itself tagged -- ------------------------------------------------------------------------- mkTaggedObjectLoad :: DynFlags -> LocalReg -> LocalReg -> ByteOff -> DynTag -> CmmAGraph -- (loadTaggedObjectField reg base off tag) generates assignment -- reg = bitsK[ base + off - tag ] -- where K is fixed by 'reg' mkTaggedObjectLoad dflags reg base offset tag = mkAssign (CmmLocal reg) (CmmLoad (cmmOffsetB dflags (CmmReg (CmmLocal base)) (offset - tag)) (localRegType reg)) ------------------------------------------------------------------------- -- -- Converting a closure tag to a closure for enumeration types -- (this is the implementation of tagToEnum#). -- ------------------------------------------------------------------------- tagToClosure :: DynFlags -> TyCon -> CmmExpr -> CmmExpr tagToClosure dflags tycon tag = CmmLoad (cmmOffsetExprW dflags closure_tbl tag) (bWord dflags) where closure_tbl = CmmLit (CmmLabel lbl) lbl = mkClosureTableLabel (tyConName tycon) NoCafRefs ------------------------------------------------------------------------- -- -- Conditionals and rts calls -- ------------------------------------------------------------------------- emitRtsCall :: UnitId -> FastString -> [(CmmExpr,ForeignHint)] -> Bool -> FCode () emitRtsCall pkg fun args safe = emitRtsCallGen [] (mkCmmCodeLabel pkg fun) args safe emitRtsCallWithResult :: LocalReg -> ForeignHint -> UnitId -> FastString -> [(CmmExpr,ForeignHint)] -> Bool -> FCode () emitRtsCallWithResult res hint pkg fun args safe = emitRtsCallGen [(res,hint)] (mkCmmCodeLabel pkg fun) args safe -- Make a call to an RTS C procedure emitRtsCallGen :: [(LocalReg,ForeignHint)] -> CLabel -> [(CmmExpr,ForeignHint)] -> Bool -- True <=> CmmSafe call -> FCode () emitRtsCallGen res lbl args safe = do { dflags <- getDynFlags ; updfr_off <- getUpdFrameOff ; let (caller_save, caller_load) = callerSaveVolatileRegs dflags ; emit caller_save ; call updfr_off ; emit caller_load } where call updfr_off = if safe then emit =<< mkCmmCall fun_expr res' args' updfr_off else do let conv = ForeignConvention CCallConv arg_hints res_hints CmmMayReturn emit $ mkUnsafeCall (ForeignTarget fun_expr conv) res' args' (args', arg_hints) = unzip args (res', res_hints) = unzip res fun_expr = mkLblExpr lbl ----------------------------------------------------------------------------- -- -- Caller-Save Registers -- ----------------------------------------------------------------------------- -- Here we generate the sequence of saves/restores required around a -- foreign call instruction. -- TODO: reconcile with includes/Regs.h -- * Regs.h claims that BaseReg should be saved last and loaded first -- * This might not have been tickled before since BaseReg is callee save -- * Regs.h saves SparkHd, ParkT1, SparkBase and SparkLim -- -- This code isn't actually used right now, because callerSaves -- only ever returns true in the current universe for registers NOT in -- system_regs (just do a grep for CALLER_SAVES in -- includes/stg/MachRegs.h). It's all one giant no-op, and for -- good reason: having to save system registers on every foreign call -- would be very expensive, so we avoid assigning them to those -- registers when we add support for an architecture. -- -- Note that the old code generator actually does more work here: it -- also saves other global registers. We can't (nor want) to do that -- here, as we don't have liveness information. And really, we -- shouldn't be doing the workaround at this point in the pipeline, see -- Note [Register parameter passing] and the ToDo on CmmCall in -- cmm/CmmNode.hs. Right now the workaround is to avoid inlining across -- unsafe foreign calls in rewriteAssignments, but this is strictly -- temporary. callerSaveVolatileRegs :: DynFlags -> (CmmAGraph, CmmAGraph) callerSaveVolatileRegs dflags = (caller_save, caller_load) where platform = targetPlatform dflags caller_save = catAGraphs (map callerSaveGlobalReg regs_to_save) caller_load = catAGraphs (map callerRestoreGlobalReg regs_to_save) system_regs = [ Sp,SpLim,Hp,HpLim,CCCS,CurrentTSO,CurrentNursery {- ,SparkHd,SparkTl,SparkBase,SparkLim -} , BaseReg ] regs_to_save = filter (callerSaves platform) system_regs callerSaveGlobalReg reg = mkStore (get_GlobalReg_addr dflags reg) (CmmReg (CmmGlobal reg)) callerRestoreGlobalReg reg = mkAssign (CmmGlobal reg) (CmmLoad (get_GlobalReg_addr dflags reg) (globalRegType dflags reg)) -- ----------------------------------------------------------------------------- -- Global registers -- We map STG registers onto appropriate CmmExprs. Either they map -- to real machine registers or stored as offsets from BaseReg. Given -- a GlobalReg, get_GlobalReg_addr always produces the -- register table address for it. -- (See also get_GlobalReg_reg_or_addr in MachRegs) get_GlobalReg_addr :: DynFlags -> GlobalReg -> CmmExpr get_GlobalReg_addr dflags BaseReg = regTableOffset dflags 0 get_GlobalReg_addr dflags mid = get_Regtable_addr_from_offset dflags (globalRegType dflags mid) (baseRegOffset dflags mid) -- Calculate a literal representing an offset into the register table. -- Used when we don't have an actual BaseReg to offset from. regTableOffset :: DynFlags -> Int -> CmmExpr regTableOffset dflags n = CmmLit (CmmLabelOff mkMainCapabilityLabel (oFFSET_Capability_r dflags + n)) get_Regtable_addr_from_offset :: DynFlags -> CmmType -> Int -> CmmExpr get_Regtable_addr_from_offset dflags _rep offset = if haveRegBase (targetPlatform dflags) then CmmRegOff (CmmGlobal BaseReg) offset else regTableOffset dflags offset -- ----------------------------------------------------------------------------- -- Information about global registers baseRegOffset :: DynFlags -> GlobalReg -> Int baseRegOffset dflags Sp = oFFSET_StgRegTable_rSp dflags baseRegOffset dflags SpLim = oFFSET_StgRegTable_rSpLim dflags baseRegOffset dflags (LongReg 1) = oFFSET_StgRegTable_rL1 dflags baseRegOffset dflags Hp = oFFSET_StgRegTable_rHp dflags baseRegOffset dflags HpLim = oFFSET_StgRegTable_rHpLim dflags baseRegOffset dflags CCCS = oFFSET_StgRegTable_rCCCS dflags baseRegOffset dflags CurrentTSO = oFFSET_StgRegTable_rCurrentTSO dflags baseRegOffset dflags CurrentNursery = oFFSET_StgRegTable_rCurrentNursery dflags baseRegOffset dflags HpAlloc = oFFSET_StgRegTable_rHpAlloc dflags baseRegOffset dflags GCEnter1 = oFFSET_stgGCEnter1 dflags baseRegOffset dflags GCFun = oFFSET_stgGCFun dflags baseRegOffset _ reg = pprPanic "baseRegOffset:" (ppr reg) ------------------------------------------------------------------------- -- -- Strings generate a top-level data block -- ------------------------------------------------------------------------- emitDataLits :: CLabel -> [CmmLit] -> FCode () -- Emit a data-segment data block emitDataLits lbl lits = emitDecl (mkDataLits (Section Data lbl) lbl lits) emitRODataLits :: CLabel -> [CmmLit] -> FCode () -- Emit a read-only data block emitRODataLits lbl lits = emitDecl (mkRODataLits lbl lits) newStringCLit :: String -> FCode CmmLit -- Make a global definition for the string, -- and return its label newStringCLit str = newByteStringCLit (map (fromIntegral . ord) str) newByteStringCLit :: [Word8] -> FCode CmmLit newByteStringCLit bytes = do { uniq <- newUnique ; let (lit, decl) = mkByteStringCLit uniq bytes ; emitDecl decl ; return lit } ------------------------------------------------------------------------- -- -- Assigning expressions to temporaries -- ------------------------------------------------------------------------- assignTemp :: CmmExpr -> FCode LocalReg -- Make sure the argument is in a local register. -- We don't bother being particularly aggressive with avoiding -- unnecessary local registers, since we can rely on a later -- optimization pass to inline as necessary (and skipping out -- on things like global registers can be a little dangerous -- due to them being trashed on foreign calls--though it means -- the optimization pass doesn't have to do as much work) assignTemp (CmmReg (CmmLocal reg)) = return reg assignTemp e = do { dflags <- getDynFlags ; uniq <- newUnique ; let reg = LocalReg uniq (cmmExprType dflags e) ; emitAssign (CmmLocal reg) e ; return reg } newTemp :: MonadUnique m => CmmType -> m LocalReg newTemp rep = do { uniq <- getUniqueM ; return (LocalReg uniq rep) } newUnboxedTupleRegs :: Type -> FCode ([LocalReg], [ForeignHint]) -- Choose suitable local regs to use for the components -- of an unboxed tuple that we are about to return to -- the Sequel. If the Sequel is a join point, using the -- regs it wants will save later assignments. newUnboxedTupleRegs res_ty = ASSERT( isUnboxedTupleType res_ty ) do { dflags <- getDynFlags ; sequel <- getSequel ; regs <- choose_regs dflags sequel ; ASSERT( regs `equalLength` reps ) return (regs, map primRepForeignHint reps) } where UbxTupleRep ty_args = repType res_ty reps = [ rep | ty <- ty_args , let rep = typePrimRep ty , not (isVoidRep rep) ] choose_regs _ (AssignTo regs _) = return regs choose_regs dflags _ = mapM (newTemp . primRepCmmType dflags) reps ------------------------------------------------------------------------- -- emitMultiAssign ------------------------------------------------------------------------- emitMultiAssign :: [LocalReg] -> [CmmExpr] -> FCode () -- Emit code to perform the assignments in the -- input simultaneously, using temporary variables when necessary. type Key = Int type Vrtx = (Key, Stmt) -- Give each vertex a unique number, -- for fast comparison type Stmt = (LocalReg, CmmExpr) -- r := e -- We use the strongly-connected component algorithm, in which -- * the vertices are the statements -- * an edge goes from s1 to s2 iff -- s1 assigns to something s2 uses -- that is, if s1 should *follow* s2 in the final order emitMultiAssign [] [] = return () emitMultiAssign [reg] [rhs] = emitAssign (CmmLocal reg) rhs emitMultiAssign regs rhss = do dflags <- getDynFlags ASSERT( equalLength regs rhss ) unscramble dflags ([1..] `zip` (regs `zip` rhss)) unscramble :: DynFlags -> [Vrtx] -> FCode () unscramble dflags vertices = mapM_ do_component components where edges :: [ (Vrtx, Key, [Key]) ] edges = [ (vertex, key1, edges_from stmt1) | vertex@(key1, stmt1) <- vertices ] edges_from :: Stmt -> [Key] edges_from stmt1 = [ key2 | (key2, stmt2) <- vertices, stmt1 `mustFollow` stmt2 ] components :: [SCC Vrtx] components = stronglyConnCompFromEdgedVertices edges -- do_components deal with one strongly-connected component -- Not cyclic, or singleton? Just do it do_component :: SCC Vrtx -> FCode () do_component (AcyclicSCC (_,stmt)) = mk_graph stmt do_component (CyclicSCC []) = panic "do_component" do_component (CyclicSCC [(_,stmt)]) = mk_graph stmt -- Cyclic? Then go via temporaries. Pick one to -- break the loop and try again with the rest. do_component (CyclicSCC ((_,first_stmt) : rest)) = do dflags <- getDynFlags u <- newUnique let (to_tmp, from_tmp) = split dflags u first_stmt mk_graph to_tmp unscramble dflags rest mk_graph from_tmp split :: DynFlags -> Unique -> Stmt -> (Stmt, Stmt) split dflags uniq (reg, rhs) = ((tmp, rhs), (reg, CmmReg (CmmLocal tmp))) where rep = cmmExprType dflags rhs tmp = LocalReg uniq rep mk_graph :: Stmt -> FCode () mk_graph (reg, rhs) = emitAssign (CmmLocal reg) rhs mustFollow :: Stmt -> Stmt -> Bool (reg, _) `mustFollow` (_, rhs) = regUsedIn dflags (CmmLocal reg) rhs ------------------------------------------------------------------------- -- mkSwitch ------------------------------------------------------------------------- emitSwitch :: CmmExpr -- Tag to switch on -> [(ConTagZ, CmmAGraphScoped)] -- Tagged branches -> Maybe CmmAGraphScoped -- Default branch (if any) -> ConTagZ -> ConTagZ -- Min and Max possible values; -- behaviour outside this range is -- undefined -> FCode () -- First, two rather common cases in which there is no work to do emitSwitch _ [] (Just code) _ _ = emit (fst code) emitSwitch _ [(_,code)] Nothing _ _ = emit (fst code) -- Right, off we go emitSwitch tag_expr branches mb_deflt lo_tag hi_tag = do join_lbl <- newLabelC mb_deflt_lbl <- label_default join_lbl mb_deflt branches_lbls <- label_branches join_lbl branches tag_expr' <- assignTemp' tag_expr -- Sort the branches before calling mk_discrete_switch let branches_lbls' = [ (fromIntegral i, l) | (i,l) <- sortBy (comparing fst) branches_lbls ] let range = (fromIntegral lo_tag, fromIntegral hi_tag) emit $ mk_discrete_switch False tag_expr' branches_lbls' mb_deflt_lbl range emitLabel join_lbl mk_discrete_switch :: Bool -- ^ Use signed comparisons -> CmmExpr -> [(Integer, BlockId)] -> Maybe BlockId -> (Integer, Integer) -> CmmAGraph -- SINGLETON TAG RANGE: no case analysis to do mk_discrete_switch _ _tag_expr [(tag, lbl)] _ (lo_tag, hi_tag) | lo_tag == hi_tag = ASSERT( tag == lo_tag ) mkBranch lbl -- SINGLETON BRANCH, NO DEFAULT: no case analysis to do mk_discrete_switch _ _tag_expr [(_tag,lbl)] Nothing _ = mkBranch lbl -- The simplifier might have eliminated a case -- so we may have e.g. case xs of -- [] -> e -- In that situation we can be sure the (:) case -- can't happen, so no need to test -- SOMETHING MORE COMPLICATED: defer to CmmImplementSwitchPlans -- See Note [Cmm Switches, the general plan] in CmmSwitch mk_discrete_switch signed tag_expr branches mb_deflt range = mkSwitch tag_expr $ mkSwitchTargets signed range mb_deflt (M.fromList branches) divideBranches :: Ord a => [(a,b)] -> ([(a,b)], a, [(a,b)]) divideBranches branches = (lo_branches, mid, hi_branches) where -- 2 branches => n_branches `div` 2 = 1 -- => branches !! 1 give the *second* tag -- There are always at least 2 branches here (mid,_) = branches !! (length branches `div` 2) (lo_branches, hi_branches) = span is_lo branches is_lo (t,_) = t < mid -------------- emitCmmLitSwitch :: CmmExpr -- Tag to switch on -> [(Literal, CmmAGraphScoped)] -- Tagged branches -> CmmAGraphScoped -- Default branch (always) -> FCode () -- Emit the code emitCmmLitSwitch _scrut [] deflt = emit $ fst deflt emitCmmLitSwitch scrut branches deflt = do scrut' <- assignTemp' scrut join_lbl <- newLabelC deflt_lbl <- label_code join_lbl deflt branches_lbls <- label_branches join_lbl branches dflags <- getDynFlags let cmm_ty = cmmExprType dflags scrut rep = typeWidth cmm_ty -- We find the necessary type information in the literals in the branches let signed = case head branches of (MachInt _, _) -> True (MachInt64 _, _) -> True _ -> False let range | signed = (tARGET_MIN_INT dflags, tARGET_MAX_INT dflags) | otherwise = (0, tARGET_MAX_WORD dflags) if isFloatType cmm_ty then emit =<< mk_float_switch rep scrut' deflt_lbl noBound branches_lbls else emit $ mk_discrete_switch signed scrut' [(litValue lit,l) | (lit,l) <- branches_lbls] (Just deflt_lbl) range emitLabel join_lbl -- | lower bound (inclusive), upper bound (exclusive) type LitBound = (Maybe Literal, Maybe Literal) noBound :: LitBound noBound = (Nothing, Nothing) mk_float_switch :: Width -> CmmExpr -> BlockId -> LitBound -> [(Literal,BlockId)] -> FCode CmmAGraph mk_float_switch rep scrut deflt _bounds [(lit,blk)] = do dflags <- getDynFlags return $ mkCbranch (cond dflags) deflt blk Nothing where cond dflags = CmmMachOp ne [scrut, CmmLit cmm_lit] where cmm_lit = mkSimpleLit dflags lit ne = MO_F_Ne rep mk_float_switch rep scrut deflt_blk_id (lo_bound, hi_bound) branches = do dflags <- getDynFlags lo_blk <- mk_float_switch rep scrut deflt_blk_id bounds_lo lo_branches hi_blk <- mk_float_switch rep scrut deflt_blk_id bounds_hi hi_branches mkCmmIfThenElse (cond dflags) lo_blk hi_blk where (lo_branches, mid_lit, hi_branches) = divideBranches branches bounds_lo = (lo_bound, Just mid_lit) bounds_hi = (Just mid_lit, hi_bound) cond dflags = CmmMachOp lt [scrut, CmmLit cmm_lit] where cmm_lit = mkSimpleLit dflags mid_lit lt = MO_F_Lt rep -------------- label_default :: BlockId -> Maybe CmmAGraphScoped -> FCode (Maybe BlockId) label_default _ Nothing = return Nothing label_default join_lbl (Just code) = do lbl <- label_code join_lbl code return (Just lbl) -------------- label_branches :: BlockId -> [(a,CmmAGraphScoped)] -> FCode [(a,BlockId)] label_branches _join_lbl [] = return [] label_branches join_lbl ((tag,code):branches) = do lbl <- label_code join_lbl code branches' <- label_branches join_lbl branches return ((tag,lbl):branches') -------------- label_code :: BlockId -> CmmAGraphScoped -> FCode BlockId -- label_code J code -- generates -- [L: code; goto J] -- and returns L label_code join_lbl (code,tsc) = do lbl <- newLabelC emitOutOfLine lbl (code MkGraph.<*> mkBranch join_lbl, tsc) return lbl -------------- assignTemp' :: CmmExpr -> FCode CmmExpr assignTemp' e | isTrivialCmmExpr e = return e | otherwise = do dflags <- getDynFlags lreg <- newTemp (cmmExprType dflags e) let reg = CmmLocal lreg emitAssign reg e return (CmmReg reg)
oldmanmike/ghc
compiler/codeGen/StgCmmUtils.hs
Haskell
bsd-3-clause
23,049
module C where -- Test file baz = 13
RefactoringTools/HaRe
test/testdata/C.hs
Haskell
bsd-3-clause
39
module Meas () where import Language.Haskell.Liquid.Prelude mylen :: [a] -> Int mylen [] = 0 mylen (_:xs) = 1 + mylen xs mymap f [] = [] mymap f (x:xs) = (f x) : (mymap f xs) zs :: [Int] zs = [1..100] prop2 = liquidAssertB (n1 == n2) where n1 = mylen zs n2 = mylen $ mymap (+ 1) zs
mightymoose/liquidhaskell
tests/pos/meas3.hs
Haskell
bsd-3-clause
320
{-# LANGUAGE Unsafe #-} {-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples, RankNTypes #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.ST -- Copyright : (c) The University of Glasgow, 1992-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : cvs-ghc@haskell.org -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- The 'ST' Monad. -- ----------------------------------------------------------------------------- module GHC.ST ( ST(..), STret(..), STRep, fixST, runST, -- * Unsafe functions liftST, unsafeInterleaveST ) where import GHC.Base import GHC.Show default () -- The state-transformer monad proper. By default the monad is strict; -- too many people got bitten by space leaks when it was lazy. -- | The strict state-transformer monad. -- A computation of type @'ST' s a@ transforms an internal state indexed -- by @s@, and returns a value of type @a@. -- The @s@ parameter is either -- -- * an uninstantiated type variable (inside invocations of 'runST'), or -- -- * 'RealWorld' (inside invocations of 'Control.Monad.ST.stToIO'). -- -- It serves to keep the internal states of different invocations -- of 'runST' separate from each other and from invocations of -- 'Control.Monad.ST.stToIO'. -- -- The '>>=' and '>>' operations are strict in the state (though not in -- values stored in the state). For example, -- -- @'runST' (writeSTRef _|_ v >>= f) = _|_@ newtype ST s a = ST (STRep s a) type STRep s a = State# s -> (# State# s, a #) instance Functor (ST s) where fmap f (ST m) = ST $ \ s -> case (m s) of { (# new_s, r #) -> (# new_s, f r #) } instance Applicative (ST s) where {-# INLINE pure #-} {-# INLINE (*>) #-} pure x = ST (\ s -> (# s, x #)) m *> k = m >>= \ _ -> k (<*>) = ap instance Monad (ST s) where {-# INLINE (>>=) #-} (>>) = (*>) (ST m) >>= k = ST (\ s -> case (m s) of { (# new_s, r #) -> case (k r) of { ST k2 -> (k2 new_s) }}) data STret s a = STret (State# s) a -- liftST is useful when we want a lifted result from an ST computation. See -- fixST below. liftST :: ST s a -> State# s -> STret s a liftST (ST m) = \s -> case m s of (# s', r #) -> STret s' r {-# NOINLINE unsafeInterleaveST #-} unsafeInterleaveST :: ST s a -> ST s a unsafeInterleaveST (ST m) = ST ( \ s -> let r = case m s of (# _, res #) -> res in (# s, r #) ) -- | Allow the result of a state transformer computation to be used (lazily) -- inside the computation. -- Note that if @f@ is strict, @'fixST' f = _|_@. fixST :: (a -> ST s a) -> ST s a fixST k = ST $ \ s -> let ans = liftST (k r) s STret _ r = ans in case ans of STret s' x -> (# s', x #) instance Show (ST s a) where showsPrec _ _ = showString "<<ST action>>" showList = showList__ (showsPrec 0) {-# INLINE runST #-} -- | Return the value computed by a state transformer computation. -- The @forall@ ensures that the internal state used by the 'ST' -- computation is inaccessible to the rest of the program. runST :: (forall s. ST s a) -> a runST (ST st_rep) = case runRW# st_rep of (# _, a #) -> a -- See Note [Definition of runRW#] in GHC.Magic
tolysz/prepare-ghcjs
spec-lts8/base/GHC/ST.hs
Haskell
bsd-3-clause
3,357
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- | Generate HPC (Haskell Program Coverage) reports module Stack.Build.Coverage ( generateHpcReport , generateHpcMarkupIndex ) where import Control.Applicative import Control.Exception.Lifted import Control.Monad (liftM) import Control.Monad.Catch (MonadCatch) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Resource import qualified Data.ByteString.Char8 as S8 import Data.Foldable (forM_) import Data.Function import Data.List import qualified Data.Map.Strict as Map import Data.Maybe import Data.Monoid ((<>)) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.IO as T import qualified Data.Text.Lazy as LT import Data.Traversable (forM) import Path import Path.IO import Prelude hiding (FilePath, writeFile) import Stack.Constants import Stack.Types import System.Process.Read import Text.Hastache (htmlEscape) -- | Generates the HTML coverage report and shows a textual coverage -- summary. generateHpcReport :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env) => Path Abs Dir -> Text -> Text -> Text -> m () generateHpcReport pkgDir pkgName pkgId testName = do let whichTest = pkgName <> "'s test-suite \"" <> testName <> "\"" -- Compute destination directory. installDir <- installationRootLocal testNamePath <- parseRelDir (T.unpack testName) pkgIdPath <- parseRelDir (T.unpack pkgId) let destDir = installDir </> hpcDirSuffix </> pkgIdPath </> testNamePath -- Directories for .mix files. hpcDir <- hpcDirFromDir pkgDir hpcRelDir <- (</> dotHpc) <$> hpcRelativeDir -- Compute arguments used for both "hpc markup" and "hpc report". pkgDirs <- Map.keys . envConfigPackages <$> asks getEnvConfig let args = -- Use index files from all packages (allows cross-package -- coverage results). concatMap (\x -> ["--srcdir", toFilePath x]) pkgDirs ++ -- Look for index files in the correct dir (relative to -- each pkgdir). ["--hpcdir", toFilePath hpcRelDir, "--reset-hpcdirs" -- Restrict to just the current library code (see #634 - -- this will likely be customizable in the future) ,"--include", T.unpack (pkgId <> ":")] -- If a .tix file exists, generate an HPC report for it. tixFile <- parseRelFile (T.unpack testName ++ ".tix") let tixFileAbs = hpcDir </> tixFile tixFileExists <- fileExists tixFileAbs if not tixFileExists then $logError $ T.concat [ "Didn't find .tix coverage file for " , whichTest , " - expected to find it at " , T.pack (toFilePath tixFileAbs) , "." ] else (`onException` $logError ("Error occurred while producing coverage report for " <> whichTest)) $ do menv <- getMinimalEnvOverride $logInfo $ "Generating HTML coverage report for " <> whichTest _ <- readProcessStdout (Just hpcDir) menv "hpc" ("markup" : toFilePath tixFileAbs : ("--destdir=" ++ toFilePath destDir) : args) output <- readProcessStdout (Just hpcDir) menv "hpc" ("report" : toFilePath tixFileAbs : args) -- Print output, stripping @\r@ characters because -- Windows. forM_ (S8.lines output) ($logInfo . T.decodeUtf8 . S8.filter (not . (=='\r'))) $logInfo ("The HTML coverage report for " <> whichTest <> " is available at " <> T.pack (toFilePath (destDir </> $(mkRelFile "hpc_index.html")))) generateHpcMarkupIndex :: (MonadIO m,MonadReader env m,MonadLogger m,MonadCatch m,HasEnvConfig env) => m () generateHpcMarkupIndex = do installDir <- installationRootLocal let markupDir = installDir </> hpcDirSuffix outputFile = markupDir </> $(mkRelFile "index.html") (dirs, _) <- listDirectory markupDir rows <- liftM (catMaybes . concat) $ forM dirs $ \dir -> do (subdirs, _) <- listDirectory dir forM subdirs $ \subdir -> do let indexPath = subdir </> $(mkRelFile "hpc_index.html") exists <- fileExists indexPath if not exists then return Nothing else do relPath <- stripDir markupDir indexPath let package = dirname dir testsuite = dirname subdir return $ Just $ T.concat [ "<tr><td>" , pathToHtml package , "</td><td><a href=\"" , pathToHtml relPath , "\">" , pathToHtml testsuite , "</a></td></tr>" ] liftIO $ T.writeFile (toFilePath outputFile) $ T.concat $ [ "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" -- Part of the css from HPC's output HTML , "<style type=\"text/css\">" , "table.dashboard { border-collapse: collapse; border: solid 1px black }" , ".dashboard td { border: solid 1px black }" , ".dashboard th { border: solid 1px black }" , "</style>" , "</head>" , "<body>" ] ++ (if null rows then [ "<b>No hpc_index.html files found in \"" , pathToHtml markupDir , "\".</b>" ] else [ "<table class=\"dashboard\" width=\"100%\" boder=\"1\"><tbody>" , "<p><b>NOTE: This is merely a listing of the html files found in the coverage reports directory. Some of these reports may be old.</b></p>" , "<tr><th>Package</th><th>TestSuite</th></tr>" ] ++ rows ++ ["</tbody></table>"]) ++ ["</body></html>"] $logInfo $ "\nAn index of the generated HTML coverage reports is available at " <> T.pack (toFilePath outputFile) pathToHtml :: Path b t -> Text pathToHtml = T.dropWhileEnd (=='/') . LT.toStrict . htmlEscape . LT.pack . toFilePath
akhileshs/stack
src/Stack/Build/Coverage.hs
Haskell
bsd-3-clause
6,914
{-# LANGUAGE CPP, RecordWildCards #-} ----------------------------------------------------------------------------- -- -- Stg to C-- code generation: -- -- The types LambdaFormInfo -- ClosureInfo -- -- Nothing monadic in here! -- ----------------------------------------------------------------------------- module StgCmmClosure ( DynTag, tagForCon, isSmallFamily, ConTagZ, dataConTagZ, idPrimRep, isVoidRep, isGcPtrRep, addIdReps, addArgReps, argPrimRep, -- * LambdaFormInfo LambdaFormInfo, -- Abstract StandardFormInfo, -- ...ditto... mkLFThunk, mkLFReEntrant, mkConLFInfo, mkSelectorLFInfo, mkApLFInfo, mkLFImported, mkLFArgument, mkLFLetNoEscape, lfDynTag, maybeIsLFCon, isLFThunk, isLFReEntrant, lfUpdatable, -- * Used by other modules CgLoc(..), SelfLoopInfo, CallMethod(..), nodeMustPointToIt, isKnownFun, funTag, tagForArity, getCallMethod, -- * ClosureInfo ClosureInfo, mkClosureInfo, mkCmmInfo, -- ** Inspection closureLFInfo, closureName, -- ** Labels -- These just need the info table label closureInfoLabel, staticClosureLabel, closureSlowEntryLabel, closureLocalEntryLabel, -- ** Predicates -- These are really just functions on LambdaFormInfo closureUpdReqd, closureSingleEntry, closureReEntrant, closureFunInfo, isToplevClosure, blackHoleOnEntry, -- Needs LambdaFormInfo and SMRep isStaticClosure, -- Needs SMPre -- * InfoTables mkDataConInfoTable, cafBlackHoleInfoTable, indStaticInfoTable, staticClosureNeedsLink, ) where #include "../includes/MachDeps.h" #define FAST_STRING_NOT_NEEDED #include "HsVersions.h" import StgSyn import SMRep import Cmm import PprCmmExpr() import BlockId import CLabel import Id import IdInfo import DataCon import FastString import Name import Type import TypeRep import TcType import TyCon import BasicTypes import Outputable import DynFlags import Util ----------------------------------------------------------------------------- -- Data types and synonyms ----------------------------------------------------------------------------- -- These data types are mostly used by other modules, especially StgCmmMonad, -- but we define them here because some functions in this module need to -- have access to them as well data CgLoc = CmmLoc CmmExpr -- A stable CmmExpr; that is, one not mentioning -- Hp, so that it remains valid across calls | LneLoc BlockId [LocalReg] -- A join point -- A join point (= let-no-escape) should only -- be tail-called, and in a saturated way. -- To tail-call it, assign to these locals, -- and branch to the block id instance Outputable CgLoc where ppr (CmmLoc e) = ptext (sLit "cmm") <+> ppr e ppr (LneLoc b rs) = ptext (sLit "lne") <+> ppr b <+> ppr rs type SelfLoopInfo = (Id, BlockId, [LocalReg]) -- used by ticky profiling isKnownFun :: LambdaFormInfo -> Bool isKnownFun (LFReEntrant _ _ _ _) = True isKnownFun LFLetNoEscape = True isKnownFun _ = False ----------------------------------------------------------------------------- -- Representations ----------------------------------------------------------------------------- -- Why are these here? idPrimRep :: Id -> PrimRep idPrimRep id = typePrimRep (idType id) -- NB: typePrimRep fails on unboxed tuples, -- but by StgCmm no Ids have unboxed tuple type addIdReps :: [Id] -> [(PrimRep, Id)] addIdReps ids = [(idPrimRep id, id) | id <- ids] addArgReps :: [StgArg] -> [(PrimRep, StgArg)] addArgReps args = [(argPrimRep arg, arg) | arg <- args] argPrimRep :: StgArg -> PrimRep argPrimRep arg = typePrimRep (stgArgType arg) ----------------------------------------------------------------------------- -- LambdaFormInfo ----------------------------------------------------------------------------- -- Information about an identifier, from the code generator's point of -- view. Every identifier is bound to a LambdaFormInfo in the -- environment, which gives the code generator enough info to be able to -- tail call or return that identifier. data LambdaFormInfo = LFReEntrant -- Reentrant closure (a function) TopLevelFlag -- True if top level !RepArity -- Arity. Invariant: always > 0 !Bool -- True <=> no fvs ArgDescr -- Argument descriptor (should really be in ClosureInfo) | LFThunk -- Thunk (zero arity) TopLevelFlag !Bool -- True <=> no free vars !Bool -- True <=> updatable (i.e., *not* single-entry) StandardFormInfo !Bool -- True <=> *might* be a function type | LFCon -- A saturated constructor application DataCon -- The constructor | LFUnknown -- Used for function arguments and imported things. -- We know nothing about this closure. -- Treat like updatable "LFThunk"... -- Imported things which we *do* know something about use -- one of the other LF constructors (eg LFReEntrant for -- known functions) !Bool -- True <=> *might* be a function type -- The False case is good when we want to enter it, -- because then we know the entry code will do -- For a function, the entry code is the fast entry point | LFUnLifted -- A value of unboxed type; -- always a value, needs evaluation | LFLetNoEscape -- See LetNoEscape module for precise description ------------------------- -- StandardFormInfo tells whether this thunk has one of -- a small number of standard forms data StandardFormInfo = NonStandardThunk -- The usual case: not of the standard forms | SelectorThunk -- A SelectorThunk is of form -- case x of -- con a1,..,an -> ak -- and the constructor is from a single-constr type. WordOff -- 0-origin offset of ak within the "goods" of -- constructor (Recall that the a1,...,an may be laid -- out in the heap in a non-obvious order.) | ApThunk -- An ApThunk is of form -- x1 ... xn -- The code for the thunk just pushes x2..xn on the stack and enters x1. -- There are a few of these (for 1 <= n <= MAX_SPEC_AP_SIZE) pre-compiled -- in the RTS to save space. RepArity -- Arity, n ------------------------------------------------------ -- Building LambdaFormInfo ------------------------------------------------------ mkLFArgument :: Id -> LambdaFormInfo mkLFArgument id | isUnLiftedType ty = LFUnLifted | might_be_a_function ty = LFUnknown True | otherwise = LFUnknown False where ty = idType id ------------- mkLFLetNoEscape :: LambdaFormInfo mkLFLetNoEscape = LFLetNoEscape ------------- mkLFReEntrant :: TopLevelFlag -- True of top level -> [Id] -- Free vars -> [Id] -- Args -> ArgDescr -- Argument descriptor -> LambdaFormInfo mkLFReEntrant top fvs args arg_descr = LFReEntrant top (length args) (null fvs) arg_descr ------------- mkLFThunk :: Type -> TopLevelFlag -> [Id] -> UpdateFlag -> LambdaFormInfo mkLFThunk thunk_ty top fvs upd_flag = ASSERT( not (isUpdatable upd_flag) || not (isUnLiftedType thunk_ty) ) LFThunk top (null fvs) (isUpdatable upd_flag) NonStandardThunk (might_be_a_function thunk_ty) -------------- might_be_a_function :: Type -> Bool -- Return False only if we are *sure* it's a data type -- Look through newtypes etc as much as poss might_be_a_function ty | UnaryRep rep <- repType ty , Just tc <- tyConAppTyCon_maybe rep , isDataTyCon tc = False | otherwise = True ------------- mkConLFInfo :: DataCon -> LambdaFormInfo mkConLFInfo con = LFCon con ------------- mkSelectorLFInfo :: Id -> Int -> Bool -> LambdaFormInfo mkSelectorLFInfo id offset updatable = LFThunk NotTopLevel False updatable (SelectorThunk offset) (might_be_a_function (idType id)) ------------- mkApLFInfo :: Id -> UpdateFlag -> Arity -> LambdaFormInfo mkApLFInfo id upd_flag arity = LFThunk NotTopLevel (arity == 0) (isUpdatable upd_flag) (ApThunk arity) (might_be_a_function (idType id)) ------------- mkLFImported :: Id -> LambdaFormInfo mkLFImported id | Just con <- isDataConWorkId_maybe id , isNullaryRepDataCon con = LFCon con -- An imported nullary constructor -- We assume that the constructor is evaluated so that -- the id really does point directly to the constructor | arity > 0 = LFReEntrant TopLevel arity True (panic "arg_descr") | otherwise = mkLFArgument id -- Not sure of exact arity where arity = idRepArity id ----------------------------------------------------- -- Dynamic pointer tagging ----------------------------------------------------- type ConTagZ = Int -- A *zero-indexed* contructor tag type DynTag = Int -- The tag on a *pointer* -- (from the dynamic-tagging paper) -- Note [Data constructor dynamic tags] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- The family size of a data type (the number of constructors -- or the arity of a function) can be either: -- * small, if the family size < 2**tag_bits -- * big, otherwise. -- -- Small families can have the constructor tag in the tag bits. -- Big families only use the tag value 1 to represent evaluatedness. -- We don't have very many tag bits: for example, we have 2 bits on -- x86-32 and 3 bits on x86-64. isSmallFamily :: DynFlags -> Int -> Bool isSmallFamily dflags fam_size = fam_size <= mAX_PTR_TAG dflags -- We keep the *zero-indexed* tag in the srt_len field of the info -- table of a data constructor. dataConTagZ :: DataCon -> ConTagZ dataConTagZ con = dataConTag con - fIRST_TAG tagForCon :: DynFlags -> DataCon -> DynTag tagForCon dflags con | isSmallFamily dflags fam_size = con_tag + 1 | otherwise = 1 where con_tag = dataConTagZ con fam_size = tyConFamilySize (dataConTyCon con) tagForArity :: DynFlags -> RepArity -> DynTag tagForArity dflags arity | isSmallFamily dflags arity = arity | otherwise = 0 lfDynTag :: DynFlags -> LambdaFormInfo -> DynTag -- Return the tag in the low order bits of a variable bound -- to this LambdaForm lfDynTag dflags (LFCon con) = tagForCon dflags con lfDynTag dflags (LFReEntrant _ arity _ _) = tagForArity dflags arity lfDynTag _ _other = 0 ----------------------------------------------------------------------------- -- Observing LambdaFormInfo ----------------------------------------------------------------------------- ------------- maybeIsLFCon :: LambdaFormInfo -> Maybe DataCon maybeIsLFCon (LFCon con) = Just con maybeIsLFCon _ = Nothing ------------ isLFThunk :: LambdaFormInfo -> Bool isLFThunk (LFThunk {}) = True isLFThunk _ = False isLFReEntrant :: LambdaFormInfo -> Bool isLFReEntrant (LFReEntrant {}) = True isLFReEntrant _ = False ----------------------------------------------------------------------------- -- Choosing SM reps ----------------------------------------------------------------------------- lfClosureType :: LambdaFormInfo -> ClosureTypeInfo lfClosureType (LFReEntrant _ arity _ argd) = Fun arity argd lfClosureType (LFCon con) = Constr (dataConTagZ con) (dataConIdentity con) lfClosureType (LFThunk _ _ _ is_sel _) = thunkClosureType is_sel lfClosureType _ = panic "lfClosureType" thunkClosureType :: StandardFormInfo -> ClosureTypeInfo thunkClosureType (SelectorThunk off) = ThunkSelector off thunkClosureType _ = Thunk -- We *do* get non-updatable top-level thunks sometimes. eg. f = g -- gets compiled to a jump to g (if g has non-zero arity), instead of -- messing around with update frames and PAPs. We set the closure type -- to FUN_STATIC in this case. ----------------------------------------------------------------------------- -- nodeMustPointToIt ----------------------------------------------------------------------------- nodeMustPointToIt :: DynFlags -> LambdaFormInfo -> Bool -- If nodeMustPointToIt is true, then the entry convention for -- this closure has R1 (the "Node" register) pointing to the -- closure itself --- the "self" argument nodeMustPointToIt _ (LFReEntrant top _ no_fvs _) = not no_fvs -- Certainly if it has fvs we need to point to it || isNotTopLevel top -- See Note [GC recovery] -- For lex_profiling we also access the cost centre for a -- non-inherited (i.e. non-top-level) function. -- The isNotTopLevel test above ensures this is ok. nodeMustPointToIt dflags (LFThunk top no_fvs updatable NonStandardThunk _) = not no_fvs -- Self parameter || isNotTopLevel top -- Note [GC recovery] || updatable -- Need to push update frame || gopt Opt_SccProfilingOn dflags -- For the non-updatable (single-entry case): -- -- True if has fvs (in which case we need access to them, and we -- should black-hole it) -- or profiling (in which case we need to recover the cost centre -- from inside it) ToDo: do we need this even for -- top-level thunks? If not, -- isNotTopLevel subsumes this nodeMustPointToIt _ (LFThunk {}) -- Node must point to a standard-form thunk = True nodeMustPointToIt _ (LFCon _) = True -- Strictly speaking, the above two don't need Node to point -- to it if the arity = 0. But this is a *really* unlikely -- situation. If we know it's nil (say) and we are entering -- it. Eg: let x = [] in x then we will certainly have inlined -- x, since nil is a simple atom. So we gain little by not -- having Node point to known zero-arity things. On the other -- hand, we do lose something; Patrick's code for figuring out -- when something has been updated but not entered relies on -- having Node point to the result of an update. SLPJ -- 27/11/92. nodeMustPointToIt _ (LFUnknown _) = True nodeMustPointToIt _ LFUnLifted = False nodeMustPointToIt _ LFLetNoEscape = False {- Note [GC recovery] ~~~~~~~~~~~~~~~~~~~~~ If we a have a local let-binding (function or thunk) let f = <body> in ... AND <body> allocates, then the heap-overflow check needs to know how to re-start the evaluation. It uses the "self" pointer to do this. So even if there are no free variables in <body>, we still make nodeMustPointToIt be True for non-top-level bindings. Why do any such bindings exist? After all, let-floating should have floated them out. Well, a clever optimiser might leave one there to avoid a space leak, deliberately recomputing a thunk. Also (and this really does happen occasionally) let-floating may make a function f smaller so it can be inlined, so now (f True) may generate a local no-fv closure. This actually happened during bootsrapping GHC itself, with f=mkRdrFunBind in TcGenDeriv.) -} ----------------------------------------------------------------------------- -- getCallMethod ----------------------------------------------------------------------------- {- The entry conventions depend on the type of closure being entered, whether or not it has free variables, and whether we're running sequentially or in parallel. Closure Node Argument Enter Characteristics Par Req'd Passing Via --------------------------------------------------------------------------- Unknown & no & yes & stack & node Known fun (>1 arg), no fvs & no & no & registers & fast entry (enough args) & slow entry (otherwise) Known fun (>1 arg), fvs & no & yes & registers & fast entry (enough args) 0 arg, no fvs \r,\s & no & no & n/a & direct entry 0 arg, no fvs \u & no & yes & n/a & node 0 arg, fvs \r,\s,selector & no & yes & n/a & node 0 arg, fvs \r,\s & no & yes & n/a & direct entry 0 arg, fvs \u & no & yes & n/a & node Unknown & yes & yes & stack & node Known fun (>1 arg), no fvs & yes & no & registers & fast entry (enough args) & slow entry (otherwise) Known fun (>1 arg), fvs & yes & yes & registers & node 0 arg, fvs \r,\s,selector & yes & yes & n/a & node 0 arg, no fvs \r,\s & yes & no & n/a & direct entry 0 arg, no fvs \u & yes & yes & n/a & node 0 arg, fvs \r,\s & yes & yes & n/a & node 0 arg, fvs \u & yes & yes & n/a & node When black-holing, single-entry closures could also be entered via node (rather than directly) to catch double-entry. -} data CallMethod = EnterIt -- No args, not a function | JumpToIt BlockId [LocalReg] -- A join point or a header of a local loop | ReturnIt -- It's a value (function, unboxed value, -- or constructor), so just return it. | SlowCall -- Unknown fun, or known fun with -- too few args. | DirectEntry -- Jump directly, with args in regs CLabel -- The code label RepArity -- Its arity getCallMethod :: DynFlags -> Name -- Function being applied -> Id -- Function Id used to chech if it can refer to -- CAF's and whether the function is tail-calling -- itself -> LambdaFormInfo -- Its info -> RepArity -- Number of available arguments -> CgLoc -- Passed in from cgIdApp so that we can -- handle let-no-escape bindings and self-recursive -- tail calls using the same data constructor, -- JumpToIt. This saves us one case branch in -- cgIdApp -> Maybe SelfLoopInfo -- can we perform a self-recursive tail call? -> CallMethod getCallMethod dflags _ id _ n_args _cg_loc (Just (self_loop_id, block_id, args)) | gopt Opt_Loopification dflags, id == self_loop_id, n_args == length args -- If these patterns match then we know that: -- * loopification optimisation is turned on -- * function is performing a self-recursive call in a tail position -- * number of parameters of the function matches functions arity. -- See Note [Self-recursive tail calls] in StgCmmExpr for more details = JumpToIt block_id args getCallMethod dflags _name _ lf_info _n_args _cg_loc _self_loop_info | nodeMustPointToIt dflags lf_info && gopt Opt_Parallel dflags = -- If we're parallel, then we must always enter via node. -- The reason is that the closure may have been -- fetched since we allocated it. EnterIt getCallMethod dflags name id (LFReEntrant _ arity _ _) n_args _cg_loc _self_loop_info | n_args == 0 = ASSERT( arity /= 0 ) ReturnIt -- No args at all | n_args < arity = SlowCall -- Not enough args | otherwise = DirectEntry (enterIdLabel dflags name (idCafInfo id)) arity getCallMethod _ _name _ LFUnLifted n_args _cg_loc _self_loop_info = ASSERT( n_args == 0 ) ReturnIt getCallMethod _ _name _ (LFCon _) n_args _cg_loc _self_loop_info = ASSERT( n_args == 0 ) ReturnIt getCallMethod dflags name id (LFThunk _ _ updatable std_form_info is_fun) n_args _cg_loc _self_loop_info | is_fun -- it *might* be a function, so we must "call" it (which is always safe) = SlowCall -- We cannot just enter it [in eval/apply, the entry code -- is the fast-entry code] -- Since is_fun is False, we are *definitely* looking at a data value | updatable || gopt Opt_Ticky dflags -- to catch double entry {- OLD: || opt_SMP I decided to remove this, because in SMP mode it doesn't matter if we enter the same thunk multiple times, so the optimisation of jumping directly to the entry code is still valid. --SDM -} = EnterIt -- even a non-updatable selector thunk can be updated by the garbage -- collector, so we must enter it. (#8817) | SelectorThunk{} <- std_form_info = EnterIt -- We used to have ASSERT( n_args == 0 ), but actually it is -- possible for the optimiser to generate -- let bot :: Int = error Int "urk" -- in (bot `cast` unsafeCoerce Int (Int -> Int)) 3 -- This happens as a result of the case-of-error transformation -- So the right thing to do is just to enter the thing | otherwise -- Jump direct to code for single-entry thunks = ASSERT( n_args == 0 ) DirectEntry (thunkEntryLabel dflags name (idCafInfo id) std_form_info updatable) 0 getCallMethod _ _name _ (LFUnknown True) _n_arg _cg_locs _self_loop_info = SlowCall -- might be a function getCallMethod _ name _ (LFUnknown False) n_args _cg_loc _self_loop_info = ASSERT2( n_args == 0, ppr name <+> ppr n_args ) EnterIt -- Not a function getCallMethod _ _name _ LFLetNoEscape _n_args (LneLoc blk_id lne_regs) _self_loop_info = JumpToIt blk_id lne_regs getCallMethod _ _ _ _ _ _ _ = panic "Unknown call method" ----------------------------------------------------------------------------- -- staticClosureRequired ----------------------------------------------------------------------------- {- staticClosureRequired is never called (hence commented out) SimonMar writes (Sept 07) It's an optimisation we used to apply at one time, I believe, but it got lost probably in the rewrite of the RTS/code generator. I left that code there to remind me to look into whether it was worth doing sometime {- Avoiding generating entries and info tables ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ At present, for every function we generate all of the following, just in case. But they aren't always all needed, as noted below: [NB1: all of this applies only to *functions*. Thunks always have closure, info table, and entry code.] [NB2: All are needed if the function is *exported*, just to play safe.] * Fast-entry code ALWAYS NEEDED * Slow-entry code Needed iff (a) we have any un-saturated calls to the function OR (b) the function is passed as an arg OR (c) we're in the parallel world and the function has free vars [Reason: in parallel world, we always enter functions with free vars via the closure.] * The function closure Needed iff (a) we have any un-saturated calls to the function OR (b) the function is passed as an arg OR (c) if the function has free vars (ie not top level) Why case (a) here? Because if the arg-satis check fails, UpdatePAP stuffs a pointer to the function closure in the PAP. [Could be changed; UpdatePAP could stuff in a code ptr instead, but doesn't seem worth it.] [NB: these conditions imply that we might need the closure without the slow-entry code. Here's how. f x y = let g w = ...x..y..w... in ...(g t)... Here we need a closure for g which contains x and y, but since the calls are all saturated we just jump to the fast entry point for g, with R1 pointing to the closure for g.] * Standard info table Needed iff (a) we have any un-saturated calls to the function OR (b) the function is passed as an arg OR (c) the function has free vars (ie not top level) NB. In the sequential world, (c) is only required so that the function closure has an info table to point to, to keep the storage manager happy. If (c) alone is true we could fake up an info table by choosing one of a standard family of info tables, whose entry code just bombs out. [NB In the parallel world (c) is needed regardless because we enter functions with free vars via the closure.] If (c) is retained, then we'll sometimes generate an info table (for storage mgr purposes) without slow-entry code. Then we need to use an error label in the info table to substitute for the absent slow entry code. -} staticClosureRequired :: Name -> StgBinderInfo -> LambdaFormInfo -> Bool staticClosureRequired binder bndr_info (LFReEntrant top_level _ _ _) -- It's a function = ASSERT( isTopLevel top_level ) -- Assumption: it's a top-level, no-free-var binding not (satCallsOnly bndr_info) staticClosureRequired binder other_binder_info other_lf_info = True -} ----------------------------------------------------------------------------- -- Data types for closure information ----------------------------------------------------------------------------- {- ClosureInfo: information about a binding We make a ClosureInfo for each let binding (both top level and not), but not bindings for data constructors: for those we build a CmmInfoTable directly (see mkDataConInfoTable). To a first approximation: ClosureInfo = (LambdaFormInfo, CmmInfoTable) A ClosureInfo has enough information a) to construct the info table itself, and build other things related to the binding (e.g. slow entry points for a function) b) to allocate a closure containing that info pointer (i.e. it knows the info table label) -} data ClosureInfo = ClosureInfo { closureName :: !Name, -- The thing bound to this closure -- we don't really need this field: it's only used in generating -- code for ticky and profiling, and we could pass the information -- around separately, but it doesn't do much harm to keep it here. closureLFInfo :: !LambdaFormInfo, -- NOTE: not an LFCon -- this tells us about what the closure contains: it's right-hand-side. -- the rest is just an unpacked CmmInfoTable. closureInfoLabel :: !CLabel, closureSMRep :: !SMRep, -- representation used by storage mgr closureProf :: !ProfilingInfo } -- | Convert from 'ClosureInfo' to 'CmmInfoTable'. mkCmmInfo :: ClosureInfo -> CmmInfoTable mkCmmInfo ClosureInfo {..} = CmmInfoTable { cit_lbl = closureInfoLabel , cit_rep = closureSMRep , cit_prof = closureProf , cit_srt = NoC_SRT } -------------------------------------- -- Building ClosureInfos -------------------------------------- mkClosureInfo :: DynFlags -> Bool -- Is static -> Id -> LambdaFormInfo -> Int -> Int -- Total and pointer words -> String -- String descriptor -> ClosureInfo mkClosureInfo dflags is_static id lf_info tot_wds ptr_wds val_descr = ClosureInfo { closureName = name , closureLFInfo = lf_info , closureInfoLabel = info_lbl -- These three fields are , closureSMRep = sm_rep -- (almost) an info table , closureProf = prof } -- (we don't have an SRT yet) where name = idName id sm_rep = mkHeapRep dflags is_static ptr_wds nonptr_wds (lfClosureType lf_info) prof = mkProfilingInfo dflags id val_descr nonptr_wds = tot_wds - ptr_wds info_lbl = mkClosureInfoTableLabel id lf_info -------------------------------------- -- Other functions over ClosureInfo -------------------------------------- -- Eager blackholing is normally disabled, but can be turned on with -- -feager-blackholing. When it is on, we replace the info pointer of -- the thunk with stg_EAGER_BLACKHOLE_info on entry. -- If we wanted to do eager blackholing with slop filling, -- we'd need to do it at the *end* of a basic block, otherwise -- we overwrite the free variables in the thunk that we still -- need. We have a patch for this from Andy Cheadle, but not -- incorporated yet. --SDM [6/2004] -- -- -- Previously, eager blackholing was enabled when ticky-ticky -- was on. But it didn't work, and it wasn't strictly necessary -- to bring back minimal ticky-ticky, so now EAGER_BLACKHOLING -- is unconditionally disabled. -- krc 1/2007 -- Static closures are never themselves black-holed. blackHoleOnEntry :: ClosureInfo -> Bool blackHoleOnEntry cl_info | isStaticRep (closureSMRep cl_info) = False -- Never black-hole a static closure | otherwise = case closureLFInfo cl_info of LFReEntrant _ _ _ _ -> False LFLetNoEscape -> False LFThunk _ _no_fvs _updatable _ _ -> True _other -> panic "blackHoleOnEntry" -- Should never happen isStaticClosure :: ClosureInfo -> Bool isStaticClosure cl_info = isStaticRep (closureSMRep cl_info) closureUpdReqd :: ClosureInfo -> Bool closureUpdReqd ClosureInfo{ closureLFInfo = lf_info } = lfUpdatable lf_info lfUpdatable :: LambdaFormInfo -> Bool lfUpdatable (LFThunk _ _ upd _ _) = upd lfUpdatable _ = False closureSingleEntry :: ClosureInfo -> Bool closureSingleEntry (ClosureInfo { closureLFInfo = LFThunk _ _ upd _ _}) = not upd closureSingleEntry _ = False closureReEntrant :: ClosureInfo -> Bool closureReEntrant (ClosureInfo { closureLFInfo = LFReEntrant _ _ _ _ }) = True closureReEntrant _ = False closureFunInfo :: ClosureInfo -> Maybe (RepArity, ArgDescr) closureFunInfo (ClosureInfo { closureLFInfo = lf_info }) = lfFunInfo lf_info lfFunInfo :: LambdaFormInfo -> Maybe (RepArity, ArgDescr) lfFunInfo (LFReEntrant _ arity _ arg_desc) = Just (arity, arg_desc) lfFunInfo _ = Nothing funTag :: DynFlags -> ClosureInfo -> DynTag funTag dflags (ClosureInfo { closureLFInfo = lf_info }) = lfDynTag dflags lf_info isToplevClosure :: ClosureInfo -> Bool isToplevClosure (ClosureInfo { closureLFInfo = lf_info }) = case lf_info of LFReEntrant TopLevel _ _ _ -> True LFThunk TopLevel _ _ _ _ -> True _other -> False -------------------------------------- -- Label generation -------------------------------------- staticClosureLabel :: ClosureInfo -> CLabel staticClosureLabel = toClosureLbl . closureInfoLabel closureSlowEntryLabel :: ClosureInfo -> CLabel closureSlowEntryLabel = toSlowEntryLbl . closureInfoLabel closureLocalEntryLabel :: DynFlags -> ClosureInfo -> CLabel closureLocalEntryLabel dflags | tablesNextToCode dflags = toInfoLbl . closureInfoLabel | otherwise = toEntryLbl . closureInfoLabel mkClosureInfoTableLabel :: Id -> LambdaFormInfo -> CLabel mkClosureInfoTableLabel id lf_info = case lf_info of LFThunk _ _ upd_flag (SelectorThunk offset) _ -> mkSelectorInfoLabel upd_flag offset LFThunk _ _ upd_flag (ApThunk arity) _ -> mkApInfoTableLabel upd_flag arity LFThunk{} -> std_mk_lbl name cafs LFReEntrant{} -> std_mk_lbl name cafs _other -> panic "closureInfoTableLabel" where name = idName id std_mk_lbl | is_local = mkLocalInfoTableLabel | otherwise = mkInfoTableLabel cafs = idCafInfo id is_local = isDataConWorkId id -- Make the _info pointer for the implicit datacon worker -- binding local. The reason we can do this is that importing -- code always either uses the _closure or _con_info. By the -- invariants in CorePrep anything else gets eta expanded. thunkEntryLabel :: DynFlags -> Name -> CafInfo -> StandardFormInfo -> Bool -> CLabel -- thunkEntryLabel is a local help function, not exported. It's used from -- getCallMethod. thunkEntryLabel dflags _thunk_id _ (ApThunk arity) upd_flag = enterApLabel dflags upd_flag arity thunkEntryLabel dflags _thunk_id _ (SelectorThunk offset) upd_flag = enterSelectorLabel dflags upd_flag offset thunkEntryLabel dflags thunk_id c _ _ = enterIdLabel dflags thunk_id c enterApLabel :: DynFlags -> Bool -> Arity -> CLabel enterApLabel dflags is_updatable arity | tablesNextToCode dflags = mkApInfoTableLabel is_updatable arity | otherwise = mkApEntryLabel is_updatable arity enterSelectorLabel :: DynFlags -> Bool -> WordOff -> CLabel enterSelectorLabel dflags upd_flag offset | tablesNextToCode dflags = mkSelectorInfoLabel upd_flag offset | otherwise = mkSelectorEntryLabel upd_flag offset enterIdLabel :: DynFlags -> Name -> CafInfo -> CLabel enterIdLabel dflags id c | tablesNextToCode dflags = mkInfoTableLabel id c | otherwise = mkEntryLabel id c -------------------------------------- -- Profiling -------------------------------------- -- Profiling requires two pieces of information to be determined for -- each closure's info table --- description and type. -- The description is stored directly in the @CClosureInfoTable@ when the -- info table is built. -- The type is determined from the type information stored with the @Id@ -- in the closure info using @closureTypeDescr@. mkProfilingInfo :: DynFlags -> Id -> String -> ProfilingInfo mkProfilingInfo dflags id val_descr | not (gopt Opt_SccProfilingOn dflags) = NoProfilingInfo | otherwise = ProfilingInfo ty_descr_w8 val_descr_w8 where ty_descr_w8 = stringToWord8s (getTyDescription (idType id)) val_descr_w8 = stringToWord8s val_descr getTyDescription :: Type -> String getTyDescription ty = case (tcSplitSigmaTy ty) of { (_, _, tau_ty) -> case tau_ty of TyVarTy _ -> "*" AppTy fun _ -> getTyDescription fun FunTy _ res -> '-' : '>' : fun_result res TyConApp tycon _ -> getOccString tycon ForAllTy _ ty -> getTyDescription ty LitTy n -> getTyLitDescription n } where fun_result (FunTy _ res) = '>' : fun_result res fun_result other = getTyDescription other getTyLitDescription :: TyLit -> String getTyLitDescription l = case l of NumTyLit n -> show n StrTyLit n -> show n -------------------------------------- -- CmmInfoTable-related things -------------------------------------- mkDataConInfoTable :: DynFlags -> DataCon -> Bool -> Int -> Int -> CmmInfoTable mkDataConInfoTable dflags data_con is_static ptr_wds nonptr_wds = CmmInfoTable { cit_lbl = info_lbl , cit_rep = sm_rep , cit_prof = prof , cit_srt = NoC_SRT } where name = dataConName data_con info_lbl | is_static = mkStaticInfoTableLabel name NoCafRefs | otherwise = mkConInfoTableLabel name NoCafRefs sm_rep = mkHeapRep dflags is_static ptr_wds nonptr_wds cl_type cl_type = Constr (dataConTagZ data_con) (dataConIdentity data_con) prof | not (gopt Opt_SccProfilingOn dflags) = NoProfilingInfo | otherwise = ProfilingInfo ty_descr val_descr ty_descr = stringToWord8s $ occNameString $ getOccName $ dataConTyCon data_con val_descr = stringToWord8s $ occNameString $ getOccName data_con -- We need a black-hole closure info to pass to @allocDynClosure@ when we -- want to allocate the black hole on entry to a CAF. cafBlackHoleInfoTable :: CmmInfoTable cafBlackHoleInfoTable = CmmInfoTable { cit_lbl = mkCAFBlackHoleInfoTableLabel , cit_rep = blackHoleRep , cit_prof = NoProfilingInfo , cit_srt = NoC_SRT } indStaticInfoTable :: CmmInfoTable indStaticInfoTable = CmmInfoTable { cit_lbl = mkIndStaticInfoLabel , cit_rep = indStaticRep , cit_prof = NoProfilingInfo , cit_srt = NoC_SRT } staticClosureNeedsLink :: Bool -> CmmInfoTable -> Bool -- A static closure needs a link field to aid the GC when traversing -- the static closure graph. But it only needs such a field if either -- a) it has an SRT -- b) it's a constructor with one or more pointer fields -- In case (b), the constructor's fields themselves play the role -- of the SRT. -- -- At this point, the cit_srt field has not been calculated (that -- happens right at the end of the Cmm pipeline), but we do have the -- VarSet of CAFs that CoreToStg attached, and if that is empty there -- will definitely not be an SRT. -- staticClosureNeedsLink has_srt CmmInfoTable{ cit_rep = smrep } | isConRep smrep = not (isStaticNoCafCon smrep) | otherwise = has_srt -- needsSRT (cit_srt info_tbl)
green-haskell/ghc
compiler/codeGen/StgCmmClosure.hs
Haskell
bsd-3-clause
37,881
module Kinding where import qualified Data.Set as Set import qualified Data.Map as Map import Core type KindSubst = Map.Map LowerName Kind class Kinded
robertkleffner/gruit
src/Kinding.hs
Haskell
mit
158
module Display (showColumns) where import Data.List(intercalate) showColumns :: Int -> Int -> ([String], [String]) -> String showColumns wrapOne wrapTwo (as', bs') = intercalate "\n" $ map joinRow $ zip (map (pad wrapOne) colOneRows) (map (pad wrapTwo) colTwoRows) where as = map (rmLineBreaks . rmLeadingWhitespace) $ concatMap (wrapText wrapOne) as' bs = map (rmLineBreaks . rmLeadingWhitespace) $ concatMap (wrapText wrapTwo) bs' rowCount = max (length as) (length bs) colOneLen = 1 + (maximum $ map length as) colTwoLen = maximum $ map length bs colOneRows = as ++ take (max 0 $ rowCount - length as) (repeat "") colTwoRows = bs ++ take (max 0 $ rowCount - length bs) (repeat "") joinRow (a, b) = a ++ b pad size s = s ++ take padding (repeat ' ') where padding = max (size - length s) 0 wrapText width s | length s <= width = [s] | otherwise = take width s : wrapText width (drop width s) rmLeadingWhitespace s = dropWhile (\c -> c `elem` " \r\n\t") s rmLineBreaks [] = [] rmLineBreaks ('\n':ss) = ' ' : rmLineBreaks ss rmLineBreaks ('\r':ss) = ' ' : rmLineBreaks ss rmLineBreaks (s:ss) = s : rmLineBreaks ss
MichaelBaker/zgy-cli
src/Display.hs
Haskell
mit
1,215
module SFML.SFResource where class SFResource a where -- | Destroy the given SFML resource. destroy :: a -> IO ()
SFML-haskell/SFML
src/SFML/SFResource.hs
Haskell
mit
130
module Y2016.M11.D08.Exercise where import Data.Aeson {-- So, last week we looked at a graph of twitter-users. NOICE! If you look at the source code that generated the graph, it's a python script that makes a request to the twitter API to get a list of the followers of the graphed account. Well. I happen to have a twitter API account and twitter application. Why don't I just access these data myself and then we can work on the raw twitter (JSON) data themselves. Indeed! So, today's Haskell exercise. In this directory, or at the URL: https://github.com/geophf/1HaskellADay/blob/master/exercises/HAD/Y2016/M11/D08/1haskfollowersids.json.gz is a gzipped list of twitter ids that follow 1HaskellADay as JSON. I was able to get this JSON data with the following REST GET query: https://api.twitter.com/1.1/followers/ids?screen_name=1HaskellADay via my (o)authenticated twitter application. Read in the JSON (after gunzipping it) and answer the below questions --} type TwitterId = Integer data Tweeps = TIds { tweeps :: [TwitterId] } deriving Show instance FromJSON Tweeps where parseJSON = undefined followers :: FilePath -> IO Tweeps followers json = undefined -- 1. How many followers does 1HaskellADay have? -- 2. What is the max TwitterID? Is it an Int-value? (ooh, tricky) -- 3. What is the min TwitterID? -- Don't answer this: -- 4. Trick question: what is 1HaskellADay's twitter ID? {-- We'll be looking at how to get screen_name from twitter id and twitter id from screen_name throughout this week, as well as looking at social networks of followers who follow follwers who ... How shall we do that? The Twitter API allows summary queries, as the JSON examined here, as well as in-depth queries, given a screen_name (from which you can obtain the twitter ID) or a twitter id (from which you can obtain the screen_name) and followers, as you saw in today's query. --}
geophf/1HaskellADay
exercises/HAD/Y2016/M11/D08/Exercise.hs
Haskell
mit
1,902
{-# LANGUAGE OverloadedStrings #-} module Lib ( withAuth ) where import Snap.Snaplet import Snap.Core import qualified Data.ByteString.Base64 as D import qualified Data.ByteString.Char8 as B import Control.Monad.Trans (liftIO) import Data.Maybe import Database.MongoDB (MongoContext(..), Database, connect, host, master) import Services.AuthenticationService import EncUtil (decryptMessage) {- | An Snap transparent handler to handle HTTP Basic authentication -} withAuth :: Handler a b () -> Handler a b () withAuth nextHandler = do rq <- getRequest let mh = getHeader "Authorization" rq let ph = parseAuthorizationHeader mh --liftIO $ print ph if isNothing ph then throwChallenge else do isValid <- liftIO $ testAuth ph if isValid then nextHandler else throwAccessDenied parseAuthorizationHeader :: Maybe B.ByteString -> Maybe (B.ByteString, B.ByteString) parseAuthorizationHeader Nothing = Nothing parseAuthorizationHeader (Just x) = case B.split ' ' x of ("Basic" : y : _) -> doParseBasicAuth y ("Token" : token : _) -> doParseAuthToken token _ -> Nothing doParseBasicAuth :: B.ByteString -> Maybe (B.ByteString, B.ByteString) doParseBasicAuth y = if B.length y == 0 then Nothing else let decodedValue = D.decode y in case decodedValue of Left e -> Nothing Right val -> case B.split ':' val of (user:pass:_) -> Just (user, pass) _ -> Nothing doParseAuthToken :: B.ByteString -> Maybe (B.ByteString, B.ByteString) doParseAuthToken token = if B.length token == 0 then Nothing else let tVal = decryptMessage token in case B.split ':' tVal of (user:pass:_) -> Just (user, pass) _ -> Nothing testAuth :: Maybe (B.ByteString, B.ByteString) -> IO Bool testAuth Nothing = return False testAuth (Just (user,pass)) = validateUser dbConfig (B.unpack user) (B.unpack pass) throwChallenge :: Handler a b () throwChallenge = do modifyResponse $ setResponseCode 401 modifyResponse $ setHeader "WWW-Authenticate" "Basic releam=heub" writeBS "" throwAccessDenied :: Handler a b () throwAccessDenied = do modifyResponse $ setResponseCode 403 writeText "Access Denied!" dbName :: Database dbName = "testAppDb" dbConfig :: IO MongoContext dbConfig = do pipe <- connect $ host "localhost" return $ MongoContext pipe master dbName
cackharot/heub
src/Lib.hs
Haskell
mit
2,410
module Main where import Lang.Cmn.Dict main :: IO () main = do dictEntries <- loadDict let wdToEntry = dictToWdDict dictEntries print $ length dictEntries
dancor/melang
src/Main/optimize-wubi.hs
Haskell
mit
169
----------------------------------------------------------------------------- -- | -- Module : Arguments -- License : MIT (see the LICENSE file) -- Maintainer : Felix Klein (klein@react.uni-saarland.de) -- -- Argument parser. -- ----------------------------------------------------------------------------- {-# LANGUAGE LambdaCase , RecordWildCards #-} ----------------------------------------------------------------------------- module Arguments ( parseArguments ) where ----------------------------------------------------------------------------- import Syfco ( Configuration(..) , WriteMode(..) , QuoteMode(..) , defaultCfg , verify , update ) import Data.Convertible ( safeConvert ) import Info ( prError ) import System.Directory ( doesFileExist ) import Control.Monad ( void , unless ) import Text.Parsec.String ( Parser ) import Text.Parsec ( parse , letter ) import Text.Parsec ( (<|>) , char , many1 , digit , alphaNum , eof ) import Text.Parsec.Token ( GenLanguageDef(..) , makeTokenParser , identifier ) import Text.Parsec.Language ( emptyDef ) ----------------------------------------------------------------------------- data Args a = None a | Single a ----------------------------------------------------------------------------- -- | Argument parser, which reads the given command line arguments to -- the internal configuration and checks whether the given -- combinations are realizable. parseArguments :: [String] -> IO Configuration parseArguments args = do c <- traverse defaultCfg args case verify c of Left err -> prError $ show err _ -> return c where traverse c = \case x:y:xr -> do r <- parseArgument c x (Just y) case r of Single c'-> traverse c' xr None c' -> traverse c' (y:xr) [x] -> do r <- parseArgument c x Nothing case r of None c' -> return c' Single c' -> return c' [] -> return c parseArgument c arg next = case arg of "-o" -> case next of Just x -> return $ Single $ c { outputFile = Just x } Nothing -> argsError "\"-o\": No output file" "--output" -> case next of Nothing -> argsError "\"--output\": No output file" _ -> parseArgument c "-o" next "-r" -> case next of Just file -> do exists <- doesFileExist file unless exists $ argsError $ "File does not exist: " ++ file fmap (update c) (readFile file) >>= \case Left err -> prError $ show err Right c' -> return $ Single c' Nothing -> argsError "\"-r\": No configuration file" "--read-config" -> case next of Nothing -> argsError "\"--read-config\": No configuration file" _ -> parseArgument c "-r" next "-w" -> case next of Just file -> return $ Single $ c { saveConfig = file : saveConfig c } Nothing -> argsError "\"-w\": Missing file path" "--write-config" -> case next of Nothing -> argsError "\"--write-config\": Missing file path" _ -> parseArgument c "-w" next "-f" -> case next of Just x -> case safeConvert x of Left err -> prError $ show err Right y -> return $ Single $ c { outputFormat = y } Nothing -> argsError "\"-f\": No format given" "--format" -> case next of Nothing -> argsError "\"--format\": No format given" _ -> parseArgument c "-f" next "-m" -> case next of Just "pretty" -> return $ Single $ c { outputMode = Pretty } Just "fully" -> return $ Single $ c { outputMode = Fully } Just x -> argsError ("Unknown mode: " ++ x) Nothing -> argsError "\"-m\": No mode given" "-q" -> case next of Just "none" -> return $ Single $ c { quoteMode = NoQuotes } Just "double" -> return $ Single $ c { quoteMode = DoubleQuotes } Just x -> argsError ("Unknown quote mode: " ++ x) Nothing -> argsError "\"-q\": No quote mode given" "--mode" -> case next of Nothing -> argsError "\"--mode\": no mode given" _ -> parseArgument c "-m" next "--quote" -> case next of Nothing -> argsError "\"--quote\": no quote mode given" _ -> parseArgument c "-q" next "-pf" -> case next of Just x -> return $ Single $ c { partFile = Just x } Nothing -> argsError "\"-pf\": No partition file" "-bd" -> case next of Just x -> return $ Single $ c { busDelimiter = x } Nothing -> argsError "\"-bd\": No delimiter given" "--bus-delimiter" -> case next of Nothing -> argsError "\"--bus-delimiter\": No delimiter given" _ -> parseArgument c "-bd" next "-ps" -> case next of Just x -> return $ Single $ c { primeSymbol = x } Nothing -> argsError "\"-ps\": No symbol replacement given" "--prime-symbol" -> case next of Just x -> return $ Single $ c { primeSymbol = x } Nothing -> argsError "\"--prime-symbol\": No symbol replacement given" "-as" -> case next of Just x -> return $ Single $ c { atSymbol = x } Nothing -> argsError "\"-as\": No symbol replacement given" "--at-symbol" -> case next of Just x -> return $ Single $ c { atSymbol = x } Nothing -> argsError "\"--at-symbol\": No symbol replacement given" "-in" -> return $ None $ c { fromStdin = True } "-os" -> case next of Just x -> case safeConvert x of Left err -> prError $ show err Right y -> return $ Single $ c { owSemantics = Just y } Nothing -> argsError "\"-os\": No semantics given" "--overwrite-semantics" -> case next of Nothing -> argsError "\"--overwrite-semantics\": No semantics given" _ -> parseArgument c "-os" next "-ot" -> case next of Just x -> case safeConvert x of Left err -> prError $ show err Right y -> return $ Single $ c { owTarget = Just y } Nothing -> argsError "\"-ot\": No target given" "--overwrite-target" -> case next of Nothing -> argsError "\"--overwrite-target\": No target given" _ -> parseArgument c "-ot" next "-op" -> case next of Just x -> case parse parameterParser "Overwrite Parameter Error" x of Left err -> prError $ show err Right y -> return $ Single $ c { owParameter = y : owParameter c } Nothing -> argsError "\"-op\": No parameter given" "--overwrite-parameter" -> case next of Nothing -> argsError "\"--overwrite-parameter\": No parameter given" _ -> parseArgument c "-op" next "-s0" -> simple $ c { simplifyWeak = True } "-s1" -> simple $ c { simplifyStrong = True } "-nnf" -> simple $ c { negNormalForm = True } "-pgi" -> simple $ c { pushGlobally = True } "-pfi" -> simple $ c { pushFinally = True } "-pxi" -> simple $ c { pushNext = True } "-pgo" -> simple $ c { pullGlobally = True } "-pfo" -> simple $ c { pullFinally = True } "-pxo" -> simple $ c { pullNext = True } "-nw" -> simple $ c { noWeak = True } "-nr" -> simple $ c { noRelease = True } "-nf" -> simple $ c { noFinally = True } "-ng" -> simple $ c { noGlobally = True } "-nd" -> simple $ c { noDerived = True } "-gr" -> simple $ (clean c) { cGR = True } "-c" -> simple $ (clean c) { check = True } "-t" -> simple $ (clean c) { pTitle = True } "-d" -> simple $ (clean c) { pDesc = True } "-s" -> simple $ (clean c) { pSemantics = True } "-g" -> simple $ (clean c) { pTarget = True } "-a" -> simple $ (clean c) { pTags = True } "-p" -> simple $ (clean c) { pParameters = True } "-ins" -> simple $ (clean c) { pInputs = True } "-outs" -> simple $ (clean c) { pOutputs = True } "-i" -> simple $ (clean c) { pInfo = True } "-v" -> simple $ (clean c) { pVersion = True } "-h" -> simple $ (clean c) { pHelp = True } "--readme" -> simple $ (clean c) { pReadme = True } "--readme.md" -> simple $ (clean c) { pReadmeMd = True } "--part-file" -> parseArgument c "-pf" next "--stdin" -> parseArgument c "-in" next "--weak-simplify" -> parseArgument c "-s0" next "--strong-simplify" -> parseArgument c "-s1" next "--negation-normal-form" -> parseArgument c "-nnf" next "--push-globally-inwards" -> parseArgument c "-pgi" next "--push-finally-inwards" -> parseArgument c "-pfi" next "--push-next-inwards" -> parseArgument c "-pni" next "--pull-globally-outwards" -> parseArgument c "-pgo" next "--pull-finally-outwards" -> parseArgument c "-pfo" next "--pull-next-outwards" -> parseArgument c "-pxo" next "--no-weak-until" -> parseArgument c "-nw" next "--no-realease" -> parseArgument c "-nr" next "--no-finally" -> parseArgument c "-nf" next "--no-globally" -> parseArgument c "-ng" next "--no-derived" -> parseArgument c "-nd" next "--generalized-reactivity" -> parseArgument c "-gr" next "--check" -> parseArgument c "-c" next "--print-title" -> parseArgument c "-t" next "--print-description" -> parseArgument c "-d" next "--print-semantics" -> parseArgument c "-s" next "--print-target" -> parseArgument c "-g" next "--print-tags" -> parseArgument c "-a" next "--print-parameters" -> parseArgument c "-p" next "--print-input-signals" -> parseArgument c "-ins" next "--print-output-signals" -> parseArgument c "-outs" next "--print-info" -> parseArgument c "-i" next "--version" -> parseArgument c "-v" next "--help" -> parseArgument c "-h" next _ -> return $ None $ c { inputFiles = arg : inputFiles c } argsError str = do prError $ "\"Error\" " ++ str clean a = a { check = False, pTitle = False, pDesc = False, pSemantics = False, pTarget = False, pParameters = False, pInfo = False, pVersion = False, pHelp = False, pReadme = False, pReadmeMd = False } simple = return . None ----------------------------------------------------------------------------- parameterParser :: Parser (String, Int) parameterParser = do name <- identifier $ makeTokenParser emptyDef { identStart = letter <|> char '_' <|> char '@' , identLetter = alphaNum <|> char '_' <|> char '@' <|> char '\'' } void $ char '=' x <- many1 digit eof return (name, read x) -----------------------------------------------------------------------------
reactive-systems/syfco
src/syfco/Arguments.hs
Haskell
mit
12,225
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} module BT.Polling where import BT.ZMQ import BT.Types import Data.Pool (Pool) import qualified System.ZMQ3 as ZMQ import Data.IORef (IORef, writeIORef) import Network.Bitcoin (BTC) import Data.ByteString as B import Data.ByteString.Char8 as BC import Control.Concurrent (threadDelay) import Control.Monad.IO.Class (liftIO) import BT.Mining pollOnce :: Pool (ZMQ.Socket ZMQ.Req) -> IORef BTC -> B.ByteString -> IO () pollOnce conn store name = do valueraw <- sendraw conn name let !value = read . BC.unpack $ valueraw :: BTC liftIO $ writeIORef store value pollOnceHex :: Pool (ZMQ.Socket ZMQ.Req) -> IORef BTC -> B.ByteString -> IO () pollOnceHex conn store name = do valueraw <- sendraw conn name let !value = hexDiffToInt $ valueraw :: BTC liftIO $ writeIORef store value poll :: PersistentConns -> IO () poll conns = do liftIO $ threadDelay 60000000 -- 60 seconds pollOnce (pool conns) (curPayout conns) "payout" pollOnceHex (pool conns) (curTarget conns) "target" poll conns
c00w/BitToll
haskell/BT/Polling.hs
Haskell
mit
1,097
{-| Module: Y2015.Util Description: Shared functions for Advent of Code Solutions. License: MIT Maintainer: @tylerjl Shared functions that support solutions to problems for the <adventofcode.com> challenges. -} module Y2015.Util ( (<&&>) , regularParse , intParser ) where import Control.Monad (liftM2) import qualified Text.Parsec as P import Text.Parsec.Char (digit) import Text.Parsec.String (Parser) -- |Combinator operator for predicates (<&&>) :: (a -> Bool) -- ^ Predicate 1 -> (a -> Bool) -- ^ Predicate 2 -> a -- ^ Predicate target -> Bool -- ^ Logical and for predicates (<&&>) = liftM2 (&&) -- |Generic parsing wrapper regularParse :: Parser a -> String -> Either P.ParseError a regularParse p = P.parse p "" -- |Generic 'Int' parser intParser :: Parser Int -- ^ Parsec parser for 'Int' types intParser = read <$> P.many1 digit
tylerjl/adventofcode
src/Y2015/Util.hs
Haskell
mit
942
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module Raw where import qualified GHCJS.TypeScript as TS import GHCJS.TypeScript (type (:|:), type (:::), type (::?)) import qualified GHCJS.Marshal as GHCJS import qualified GHCJS.Types as GHCJS import qualified Data.Typeable newtype Event = Event (GHCJS.JSRef Event) newtype HTMLElement = HTMLElement (GHCJS.JSRef HTMLElement) newtype Function = Function (GHCJS.JSRef Function) newtype HighchartsAnimation = HighchartsAnimation (GHCJS.JSRef (HighchartsAnimation)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAnimation = ('[ "duration" ::? TS.Number , "easing" ::? TS.String ]) newtype HighchartsAreaChart = HighchartsAreaChart (GHCJS.JSRef (HighchartsAreaChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAreaChart = ('[ "allowPointSelect" ::? TS.Boolean , "animation" ::? TS.Boolean , "color" ::? TS.String , "connectEnds" ::? TS.Boolean , "connectNulls" ::? TS.Boolean , "cropThreshold" ::? TS.Number , "cursor" ::? TS.String , "dashStyle" ::? TS.String , "dataLabels" ::? HighchartsDataLabels , "enableMouseTracking" ::? TS.Boolean , "events" ::? HighchartsPlotEvents , "fillColor" ::? (TS.String :|: HighchartsGradient) , "fillOpacity" ::? TS.Number , "linkedTo" ::? TS.String , "lineColor" ::? TS.String , "lineWidth" ::? TS.Number , "marker" ::? HighchartsMarker , "negativeColor" ::? TS.String , "negativeFillColor" ::? TS.String , "point" ::? TS.Obj ('[ "events" ::: HighchartsPointEvents ]) , "pointInterval" ::? TS.Number , "pointPlacement" ::? (TS.String :|: TS.Number) , "pointStart" ::? TS.Number , "selected" ::? TS.Boolean , "shadow" ::? (TS.Boolean :|: HighchartsShadow) , "showCheckbox" ::? TS.Boolean , "showInLegend" ::? TS.Boolean , "stacking" ::? TS.String , "states" ::? TS.Obj ('[ "hover" ::: HighchartsAreaStates ]) , "step" ::? TS.String , "stickyTracking" ::? TS.Boolean , "threshold" ::? TS.Number , "tooltip" ::? HighchartsTooltipOptions , "trackByArea" ::? TS.Boolean , "turboThreshold" ::? TS.Number , "visible" ::? TS.Boolean , "zIndex" ::? TS.Number ]) newtype HighchartsAreaChartSeriesOptions = HighchartsAreaChartSeriesOptions (GHCJS.JSRef (HighchartsAreaChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAreaChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsAreaChart] ('[ ]) newtype HighchartsAreaCheckboxEvent = HighchartsAreaCheckboxEvent (GHCJS.JSRef (HighchartsAreaCheckboxEvent)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAreaCheckboxEvent = TS.Extends '[Event] ('[ "checked" ::: TS.Boolean ]) newtype HighchartsAreaClickEvent = HighchartsAreaClickEvent (GHCJS.JSRef (HighchartsAreaClickEvent)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAreaClickEvent = TS.Extends '[Event] ('[ "point" ::: HighchartsPointObject ]) newtype HighchartsAreaRangeChart = HighchartsAreaRangeChart (GHCJS.JSRef (HighchartsAreaRangeChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAreaRangeChart = ('[ "allowPointSelect" ::? TS.Boolean , "animation" ::? TS.Boolean , "color" ::? TS.String , "connectNulls" ::? TS.Boolean , "cropThreshold" ::? TS.Number , "cursor" ::? TS.String , "dashStyle" ::? TS.String , "dataLabels" ::? HighchartsRangeDataLabels , "enableMouseTracking" ::? TS.Boolean , "events" ::? HighchartsPlotEvents , "fillColor" ::? (TS.String :|: HighchartsGradient) , "fillOpacity" ::? TS.Number , "lineColor" ::? TS.String , "lineWidth" ::? TS.Number , "linkedTo" ::? TS.String , "negativeColor" ::? TS.String , "negativeFillColor" ::? TS.String , "point" ::? TS.Obj ('[ "events" ::: HighchartsPointEvents ]) , "pointInterval" ::? TS.Number , "pointPlacement" ::? (TS.String :|: TS.Number) , "pointStart" ::? TS.Number , "selected" ::? TS.Boolean , "shadow" ::? (TS.Boolean :|: HighchartsShadow) , "showCheckbox" ::? TS.Boolean , "showInLegend" ::? TS.Boolean , "stacking" ::? TS.String , "states" ::? TS.Obj ('[ "hover" ::: HighchartsAreaStates ]) , "step" ::? TS.String , "stickyTracking" ::? TS.Boolean , "tooltip" ::? HighchartsTooltipOptions , "threshold" ::? TS.Number , "trackByArea" ::? TS.Boolean , "turboThreshold" ::? TS.Number , "visible" ::? TS.Boolean ]) newtype HighchartsAreaRangeChartSeriesOptions = HighchartsAreaRangeChartSeriesOptions (GHCJS.JSRef (HighchartsAreaRangeChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAreaRangeChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsAreaRangeChart] ('[ ]) newtype HighchartsAreaSplineChart = HighchartsAreaSplineChart (GHCJS.JSRef (HighchartsAreaSplineChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAreaSplineChart = TS.Extends '[HighchartsAreaChart] ('[ "connectEnds" ::? TS.Boolean ]) newtype HighchartsAreaSplineChartSeriesOptions = HighchartsAreaSplineChartSeriesOptions (GHCJS.JSRef (HighchartsAreaSplineChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAreaSplineChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsAreaSplineChart] ('[ ]) newtype HighchartsAreaSplineRangeChart = HighchartsAreaSplineRangeChart (GHCJS.JSRef (HighchartsAreaSplineRangeChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAreaSplineRangeChart = TS.Extends '[HighchartsAreaRangeChart] ('[ ]) newtype HighchartsAreaSplineRangeChartSeriesOptions = HighchartsAreaSplineRangeChartSeriesOptions (GHCJS.JSRef (HighchartsAreaSplineRangeChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAreaSplineRangeChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsAreaSplineRangeChart] ('[ ]) newtype HighchartsAreaStates = HighchartsAreaStates (GHCJS.JSRef (HighchartsAreaStates)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAreaStates = ('[ "enabled" ::? TS.Boolean , "lineWidth" ::? TS.Number , "marker" ::? HighchartsMarker ]) newtype HighchartsAxisEvent = HighchartsAxisEvent (GHCJS.JSRef (HighchartsAxisEvent)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAxisEvent = TS.Extends '[Event] ('[ "min" ::: TS.Number , "max" ::: TS.Number ]) newtype HighchartsAxisLabels = HighchartsAxisLabels (GHCJS.JSRef (HighchartsAxisLabels)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAxisLabels = ('[ "align" ::? TS.String , "enabled" ::? TS.Boolean , "formatter" ::? (TS.String) , "overflow" ::? TS.String , "rotation" ::? TS.Number , "staggerLines" ::? TS.Number , "step" ::? TS.Number , "style" ::? HighchartsCSSObject , "useHTML" ::? TS.Boolean , "x" ::? TS.Number , "y" ::? TS.Number ]) newtype HighchartsAxisObject = HighchartsAxisObject (GHCJS.JSRef (HighchartsAxisObject)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAxisObject = ('[ "addPlotBand" ::: TS.Fun (HighchartsPlotBands -> TS.Void) , "addPlotLine" ::: TS.Fun (HighchartsPlotLines -> TS.Void) , "getExtremes" ::: TS.Fun (HighchartsExtremes) , "remove" ::: TS.Fun (TS.Optional (TS.Boolean) -> TS.Void) , "removePlotBand" ::: TS.Fun (TS.String -> TS.Void) , "removePlotLine" ::: TS.Fun (TS.String -> TS.Void) , "setCategories" ::: TS.Fun ((TS.Array TS.String) -> TS.Void) , "setCategories" ::: TS.Fun ((TS.Array TS.String) -> TS.Boolean -> TS.Void) , "setExtremes" ::: TS.Fun (TS.Number -> TS.Number -> TS.Void) , "setExtremes" ::: TS.Fun (TS.Number -> TS.Number -> TS.Boolean -> TS.Void) , "setExtremes" ::: TS.Fun (TS.Number -> TS.Number -> TS.Boolean -> (TS.Boolean :|: HighchartsAnimation) -> TS.Void) , "setTitle" ::: TS.Fun (HighchartsAxisTitle -> TS.Optional (TS.Boolean) -> TS.Void) , "toPixels" ::: TS.Fun (TS.Number -> TS.Optional (TS.Boolean) -> TS.Number) , "toValue" ::: TS.Fun (TS.Number -> TS.Optional (TS.Boolean) -> TS.Number) , "update" ::: TS.Fun (HighchartsAxisOptions -> TS.Optional (TS.Boolean) -> TS.Void) ]) newtype HighchartsAxisOptions = HighchartsAxisOptions (GHCJS.JSRef (HighchartsAxisOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAxisOptions = ('[ "allowDecimals" ::? TS.Boolean , "alternateGridColor" ::? TS.String , "categories" ::? (TS.Array TS.String) , "dateTimeLabelFormats" ::? HighchartsDateTimeFormats , "endOnTick" ::? TS.Boolean , "events" ::? TS.Obj ('[ "afterSetExtremes" ::? (HighchartsAxisEvent -> TS.Void) , "setExtremes" ::? (HighchartsAxisEvent -> TS.Void) ]) , "gridLineColor" ::? TS.String , "gridLineDashStyle" ::? TS.String , "gridLineWidth" ::? TS.Number , "id" ::? TS.String , "labels" ::? HighchartsAxisLabels , "lineColor" ::? TS.String , "lineWidth" ::? TS.Number , "linkedTo" ::? TS.Number , "max" ::? TS.Number , "maxPadding" ::? TS.Number , "maxZoom" ::? TS.Number , "min" ::? TS.Number , "minPadding" ::? TS.Number , "minRange" ::? TS.Number , "minTickInterval" ::? TS.Number , "minorTickColor" ::? TS.String , "minorTickInterval" ::? (TS.Number :|: TS.String) , "minorTickLength" ::? TS.Number , "minorTickPosition" ::? TS.String , "minorTickWidth" ::? TS.Number , "offset" ::? TS.Number , "opposite" ::? TS.Boolean , "plotBands" ::? HighchartsPlotBands , "plotLines" ::? HighchartsPlotLines , "reversed" ::? TS.Boolean , "showEmpty" ::? TS.Boolean , "showFirstLabel" ::? TS.Boolean , "showLastLabel" ::? TS.Boolean , "startOfWeek" ::? TS.Number , "startOnTick" ::? TS.Boolean , "tickColor" ::? TS.String , "tickInterval" ::? TS.Number , "tickLength" ::? TS.Number , "tickPixelInterval" ::? TS.Number , "tickPosition" ::? TS.String , "tickWidth" ::? TS.Number , "tickmarkPlacement" ::? TS.String , "title" ::? HighchartsAxisTitle , "type" ::? TS.String ]) newtype HighchartsAxisTitle = HighchartsAxisTitle (GHCJS.JSRef (HighchartsAxisTitle)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsAxisTitle = ('[ "align" ::? TS.String , "margin" ::? TS.Number , "offset" ::? TS.Number , "rotation" ::? TS.Number , "style" ::? HighchartsCSSObject , "text" ::? TS.String ]) newtype HighchartsBarChart = HighchartsBarChart (GHCJS.JSRef (HighchartsBarChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsBarChart = ('[ "allowPointSelect" ::? TS.Boolean , "animation" ::? TS.Boolean , "borderColor" ::? TS.String , "borderRadius" ::? TS.Number , "borderWidth" ::? TS.Number , "color" ::? TS.String , "colorByPoint" ::? TS.Boolean , "cropThreshold" ::? TS.Number , "colors" ::? (TS.Array TS.String) , "cursor" ::? TS.String , "dataLabels" ::? HighchartsDataLabels , "depth" ::? TS.Number , "edgeColor" ::? TS.String , "edgeWidth" ::? TS.Number , "enableMouseTracking" ::? TS.Boolean , "events" ::? HighchartsPlotEvents , "groupPadding" ::? TS.Number , "groupZPadding" ::? TS.Number , "grouping" ::? TS.Boolean , "linkedTo" ::? TS.String , "minPointLength" ::? TS.Number , "negativeColor" ::? TS.String , "point" ::? TS.Obj ('[ "events" ::: HighchartsPointEvents ]) , "pointInterval" ::? TS.Number , "pointPadding" ::? TS.Number , "pointPlacement" ::? TS.String , "pointRange" ::? TS.Number , "pointStart" ::? TS.Number , "pointWidth" ::? TS.Number , "selected" ::? TS.Boolean , "shadow" ::? (TS.Boolean :|: HighchartsShadow) , "showCheckbox" ::? TS.Boolean , "showInLegend" ::? TS.Boolean , "stacking" ::? TS.String , "states" ::? TS.Obj ('[ "hover" ::: HighchartsBarStates ]) , "stickyTracking" ::? TS.Boolean , "threshold" ::? TS.Number , "tooltip" ::? HighchartsTooltipOptions , "turboThreshold" ::? TS.Number , "visible" ::? TS.Boolean ]) newtype HighchartsBarChartSeriesOptions = HighchartsBarChartSeriesOptions (GHCJS.JSRef (HighchartsBarChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsBarChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsBarChart] ('[ ]) newtype HighchartsBarStates = HighchartsBarStates (GHCJS.JSRef (HighchartsBarStates)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsBarStates = TS.Extends '[HighchartsAreaStates] ('[ "brightness" ::? TS.Number ]) newtype HighchartsBoxPlotChart = HighchartsBoxPlotChart (GHCJS.JSRef (HighchartsBoxPlotChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsBoxPlotChart = ('[ "allowPointSelect" ::? TS.Boolean , "color" ::? TS.String , "colorByPoint" ::? TS.Boolean , "colors" ::? (TS.Array TS.String) , "cursor" ::? TS.String , "depth" ::? TS.Number , "edgecolor" ::? TS.String , "edgewidth" ::? TS.Number , "enableMouseTracking" ::? TS.Boolean , "events" ::? HighchartsPlotEvents , "fillColor" ::? TS.String , "groupPadding" ::? TS.Number , "groupZPadding" ::? TS.Number , "grouping" ::? TS.Boolean , "lineWidth" ::? TS.Number , "linkedTo" ::? TS.String , "medianColor" ::? TS.String , "negativeColor" ::? TS.String , "point" ::? TS.Obj ('[ "events" ::: HighchartsPointEvents ]) , "pointInterval" ::? TS.Number , "pointPadding" ::? TS.Number , "pointPlacement" ::? (TS.String :|: TS.Number) , "pointRange" ::? TS.Number , "pointStart" ::? TS.Number , "pointWidth" ::? TS.Number , "selected" ::? TS.Boolean , "showCheckbox" ::? TS.Boolean , "showInLegend" ::? TS.Boolean , "states" ::? TS.Obj ('[ "hover" ::: HighchartsBarStates ]) , "stemColor" ::? TS.String , "stemDashStyle" ::? TS.String , "stemWidth" ::? TS.Number , "stickyTracking" ::? TS.Boolean , "tooltip" ::? HighchartsTooltipOptions , "turboThreshold" ::? TS.Number , "visible" ::? TS.Boolean , "whiskerColor" ::? TS.String , "whiskerLength" ::? (TS.Number :|: TS.String) , "whiskerWidth" ::? TS.Number ]) newtype HighchartsBoxPlotChartSeriesOptions = HighchartsBoxPlotChartSeriesOptions (GHCJS.JSRef (HighchartsBoxPlotChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsBoxPlotChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsBoxPlotChart] ('[ ]) newtype HighchartsBubbleChart = HighchartsBubbleChart (GHCJS.JSRef (HighchartsBubbleChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsBubbleChart = ('[ "allowPointSelect" ::? TS.Boolean , "animation" ::? TS.Boolean , "color" ::? TS.String , "cropThreshold" ::? TS.Number , "cursor" ::? TS.String , "dashStyle" ::? TS.String , "dataLabels" ::? HighchartsRangeDataLabels , "displayNegative" ::? TS.Boolean , "enableMouseTracking" ::? TS.Boolean , "events" ::? HighchartsPlotEvents , "lineWidth" ::? TS.Number , "linkedTo" ::? TS.String , "marker" ::? HighchartsMarker , "maxSize" ::? TS.String , "minSize" ::? TS.String , "negativeColor" ::? TS.String , "point" ::? TS.Obj ('[ "events" ::: HighchartsPointEvents ]) , "pointInterval" ::? TS.Number , "pointStart" ::? TS.Number , "selected" ::? TS.Boolean , "shadow" ::? (TS.Boolean :|: HighchartsShadow) , "showCheckbox" ::? TS.Boolean , "showInLegend" ::? TS.Boolean , "sizeBy" ::? TS.String , "states" ::? TS.Obj ('[ "hover" ::: HighchartsBarStates ]) , "stickyTracking" ::? TS.Boolean , "tooltip" ::? HighchartsTooltipOptions , "turboThreshold" ::? TS.Number , "visible" ::? TS.Boolean , "zMax" ::? TS.Number , "zMin" ::? TS.Number , "zThreshold" ::? TS.Number ]) newtype HighchartsBubbleChartSeriesOptions = HighchartsBubbleChartSeriesOptions (GHCJS.JSRef (HighchartsBubbleChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsBubbleChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsBubbleChart] ('[ ]) newtype HighchartsButton = HighchartsButton (GHCJS.JSRef (HighchartsButton)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsButton = ('[ "align" ::? TS.String , "backgroundColor" ::? (TS.String :|: HighchartsGradient) , "borderColor" ::? TS.String , "borderRadius" ::? TS.Number , "borderWidth" ::? TS.Number , "verticalAlign" ::? TS.String , "enabled" ::? TS.Boolean , "height" ::? TS.Number , "hoverBorderColor" ::? TS.String , "hoverSymbolFill" ::? TS.String , "hoverSimbolStroke" ::? TS.String , "menuItems" ::? (TS.Array HighchartsMenuItem) , "onclick" ::? (TS.Void) , "symbol" ::? TS.String , "simbolFill" ::? TS.String , "simbolSize" ::? TS.Number , "symbolStroke" ::? TS.String , "symbolStrokeWidth" ::? TS.Number , "symbolX" ::? TS.Number , "symbolY" ::? TS.Number , "width" ::? TS.Number , "x" ::? TS.Number , "y" ::? TS.Number ]) newtype HighchartsCSSObject = HighchartsCSSObject (GHCJS.JSRef (HighchartsCSSObject)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsCSSObject = ('[ "background" ::? TS.String , "border" ::? TS.String , "color" ::? TS.String , "cursor" ::? TS.String , "font" ::? TS.String , "fontSize" ::? TS.String , "fontWeight" ::? TS.String , "left" ::? TS.String , "opacity" ::? TS.Number , "padding" ::? TS.String , "position" ::? TS.String , "top" ::? TS.String ]) newtype HighchartsChart = HighchartsChart (GHCJS.JSRef (HighchartsChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsChart = ('[ TS.Constructor (HighchartsOptions -> HighchartsChartObject) , TS.Constructor (HighchartsOptions -> (HighchartsChartObject -> TS.Void) -> HighchartsChartObject) ]) newtype HighchartsChartEvents = HighchartsChartEvents (GHCJS.JSRef (HighchartsChartEvents)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsChartEvents = ('[ "addSeries" ::? (TS.Optional (Event) -> TS.Boolean) , "click" ::? (TS.Optional (Event) -> TS.Void) , "load" ::? (TS.Optional (Event) -> TS.Void) , "redraw" ::? (Event -> TS.Void) , "selection" ::? (HighchartsSelectionEvent -> TS.Void) ]) newtype HighchartsChartObject = HighchartsChartObject (GHCJS.JSRef (HighchartsChartObject)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsChartObject = ('[ "addAxis" ::: TS.Fun (HighchartsAxisOptions -> TS.Optional (TS.Boolean) -> TS.Optional (TS.Boolean) -> TS.Optional ((TS.Boolean :|: HighchartsAnimation)) -> HighchartsAxisObject) , "addSeries" ::: TS.Fun (TS.Any {- forall t. (t TS.:= HighchartsIndividualSeriesOptions) => t -> TS.Optional (TS.Boolean) -> TS.Optional ((TS.Boolean :|: HighchartsAnimation)) -> t -}) , "addSeriesAsDrilldown" ::: TS.Fun (HighchartsPointObject -> HighchartsSeriesOptions -> TS.Void) , "container" ::: HTMLElement , "destroy" ::: TS.Fun (TS.Void) , "drillUp" ::: TS.Fun (TS.Void) , "exportChart" ::: TS.Fun (TS.Void) , "exportChart" ::: TS.Fun (HighchartsExportingOptions -> TS.Void) , "exportChart" ::: TS.Fun (HighchartsExportingOptions -> HighchartsChartOptions -> TS.Void) , "get" ::: TS.Fun (TS.String -> (HighchartsAxisObject :|: (HighchartsSeriesObject :|: HighchartsPointObject))) , "getSVG" ::: TS.Fun (TS.String) , "getSVG" ::: TS.Fun (HighchartsChartOptions -> TS.String) , "getSelectedPoints" ::: TS.Fun ((TS.Array HighchartsPointObject)) , "getSelectedSeries" ::: TS.Fun ((TS.Array HighchartsSeriesObject)) , "hideLoading" ::: TS.Fun (TS.Void) , "options" ::: HighchartsChartOptions , "print" ::: TS.Fun (TS.Void) , "redraw" ::: TS.Fun (TS.Void) , "reflow" ::: TS.Fun (TS.Void) , "series" ::: (TS.Array HighchartsSeriesObject) , "setSize" ::: TS.Fun (TS.Number -> TS.Number -> TS.Void) , "setSize" ::: TS.Fun (TS.Number -> TS.Number -> TS.Boolean -> TS.Void) , "setSize" ::: TS.Fun (TS.Number -> TS.Number -> HighchartsAnimation -> TS.Void) , "setTitle" ::: TS.Fun (HighchartsTitleOptions -> TS.Void) , "setTitle" ::: TS.Fun (HighchartsTitleOptions -> HighchartsSubtitleOptions -> TS.Void) , "setTitle" ::: TS.Fun (HighchartsTitleOptions -> HighchartsSubtitleOptions -> TS.Boolean -> TS.Void) , "showLoading" ::: TS.Fun (TS.Void) , "showLoading" ::: TS.Fun (TS.String -> TS.Void) , "xAxis" ::: (TS.Array HighchartsAxisObject) , "yAxis" ::: (TS.Array HighchartsAxisObject) , "renderer" ::: HighchartsRendererObject ]) newtype HighchartsChartOptions = HighchartsChartOptions (GHCJS.JSRef (HighchartsChartOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsChartOptions = ('[ "alignTicks" ::? TS.Boolean , "animation" ::? (TS.Boolean :|: HighchartsAnimation) , "backgroundColor" ::? (TS.String :|: HighchartsGradient) , "borderColor" ::? TS.String , "borderRadius" ::? TS.Number , "borderWidth" ::? TS.Number , "className" ::? TS.String , "defaultSeriesType" ::? TS.String , "events" ::? HighchartsChartEvents , "height" ::? TS.Number , "ignoreHiddenSeries" ::? TS.Boolean , "inverted" ::? TS.Boolean , "margin" ::? (TS.Array TS.Number) , "marginBottom" ::? TS.Number , "marginLeft" ::? TS.Number , "marginRight" ::? TS.Number , "marginTop" ::? TS.Number , "plotBackGroundColor" ::? (TS.String :|: HighchartsGradient) , "plotBackGroundImage" ::? TS.String , "plotBorderColor" ::? TS.String , "plotBorderWidth" ::? TS.Number , "plotShadow" ::? (TS.Boolean :|: HighchartsShadow) , "polar" ::? TS.Boolean , "reflow" ::? TS.Boolean , "renderTo" ::? TS.Any , "resetZoomButton" ::? HighchartsChartResetZoomButton , "selectionMarkerFill" ::? TS.String , "shadow" ::? (TS.Boolean :|: HighchartsShadow) , "showAxes" ::? TS.Boolean , "spacingBottom" ::? TS.Number , "spacingLeft" ::? TS.Number , "spacingRight" ::? TS.Number , "spacingTop" ::? TS.Number , "style" ::? HighchartsCSSObject , "type" ::? TS.String , "width" ::? TS.Number , "zoomType" ::? TS.String ]) newtype HighchartsChartResetZoomButton = HighchartsChartResetZoomButton (GHCJS.JSRef (HighchartsChartResetZoomButton)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsChartResetZoomButton = ('[ "position" ::: HighchartsPosition , "relativeTo" ::? TS.String , "theme" ::? HighchartsChartResetZoomButtonTheme ]) newtype HighchartsChartResetZoomButtonTheme = HighchartsChartResetZoomButtonTheme (GHCJS.JSRef (HighchartsChartResetZoomButtonTheme)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsChartResetZoomButtonTheme = ('[ "fill" ::? TS.String , "stroke" ::? TS.String , "r" ::? TS.Number , "states" ::? TS.Any , "display" ::? TS.String ]) newtype HighchartsColumnChart = HighchartsColumnChart (GHCJS.JSRef (HighchartsColumnChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsColumnChart = TS.Extends '[HighchartsBarChart] ('[ ]) newtype HighchartsColumnChartSeriesOptions = HighchartsColumnChartSeriesOptions (GHCJS.JSRef (HighchartsColumnChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsColumnChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsColumnChart] ('[ ]) newtype HighchartsColumnRangeChart = HighchartsColumnRangeChart (GHCJS.JSRef (HighchartsColumnRangeChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsColumnRangeChart = ('[ "allowPointSelect" ::? TS.Boolean , "animation" ::? TS.Boolean , "borderColor" ::? TS.String , "borderRadius" ::? TS.Number , "borderWidth" ::? TS.Number , "color" ::? TS.String , "colorByPoint" ::? TS.Boolean , "colors" ::? (TS.Array TS.String) , "cropThreshold" ::? TS.Number , "cursor" ::? TS.String , "dataLabels" ::? HighchartsRangeDataLabels , "enableMouseTracking" ::? TS.Boolean , "events" ::? HighchartsPlotEvents , "groupPadding" ::? TS.Number , "grouping" ::? TS.Boolean , "linkedTo" ::? TS.String , "minPointLength" ::? TS.Number , "negativeColor" ::? TS.String , "point" ::? TS.Obj ('[ "events" ::: HighchartsPointEvents ]) , "pointInterval" ::? TS.Number , "pointPadding" ::? TS.Number , "pointPlacement" ::? (TS.String :|: TS.Number) , "pointRange" ::? TS.Number , "pointStart" ::? TS.Number , "pointWidth" ::? TS.Number , "selected" ::? TS.Boolean , "shadow" ::? (TS.Boolean :|: HighchartsShadow) , "showCheckbox" ::? TS.Boolean , "showInLegend" ::? TS.Boolean , "stacking" ::? TS.String , "states" ::? TS.Obj ('[ "hover" ::: HighchartsBarStates ]) , "stickyTracking" ::? TS.Boolean , "tooltip" ::? HighchartsTooltipOptions , "turboThreshold" ::? TS.Number , "visible" ::? TS.Boolean ]) newtype HighchartsColumnRangeChartSeriesOptions = HighchartsColumnRangeChartSeriesOptions (GHCJS.JSRef (HighchartsColumnRangeChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsColumnRangeChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsColumnRangeChart] ('[ ]) newtype HighchartsCreditsOptions = HighchartsCreditsOptions (GHCJS.JSRef (HighchartsCreditsOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsCreditsOptions = ('[ "enabled" ::? TS.Boolean , "href" ::? TS.String , "position" ::? HighchartsPosition , "style" ::? HighchartsCSSObject , "text" ::? TS.String ]) newtype HighchartsCrosshairObject = HighchartsCrosshairObject (GHCJS.JSRef (HighchartsCrosshairObject)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsCrosshairObject = ('[ "color" ::? TS.String , "width" ::? TS.Number , "dashStyle" ::? TS.String , "zIndex" ::? TS.Number ]) newtype HighchartsDataLabels = HighchartsDataLabels (GHCJS.JSRef (HighchartsDataLabels)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsDataLabels = ('[ "align" ::? TS.String , "backgroundColor" ::? (TS.String :|: HighchartsGradient) , "borderColor" ::? TS.String , "borderRadius" ::? TS.Number , "borderWidth" ::? TS.Number , "color" ::? TS.String , "crop" ::? TS.Boolean , "enabled" ::? TS.Boolean , "formatter" ::? (TS.Any) , "overflow" ::? TS.String , "padding" ::? TS.Number , "rotation" ::? TS.Number , "shadow" ::? (TS.Boolean :|: HighchartsShadow) , "staggerLines" ::? TS.Any , "step" ::? TS.Any , "style" ::? HighchartsCSSObject , "useHTML" ::? TS.Boolean , "verticalAlign" ::? TS.String , "x" ::? TS.Number , "y" ::? TS.Number ]) newtype HighchartsDataPoint = HighchartsDataPoint (GHCJS.JSRef (HighchartsDataPoint)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsDataPoint = ('[ "color" ::? TS.String , "dataLabels" ::? HighchartsDataLabels , "events" ::? HighchartsPointEvents , "id" ::? TS.String , "legendIndex" ::? TS.Number , "marker" ::? HighchartsMarker , "name" ::? TS.String , "sliced" ::? TS.Boolean , "x" ::? TS.Number , "y" ::? TS.Number ]) newtype HighchartsDateTimeFormats = HighchartsDateTimeFormats (GHCJS.JSRef (HighchartsDateTimeFormats)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsDateTimeFormats = ('[ "millisecond" ::? TS.String , "second" ::? TS.String , "minute" ::? TS.String , "hour" ::? TS.String , "day" ::? TS.String , "week" ::? TS.String , "month" ::? TS.String , "year" ::? TS.String ]) newtype HighchartsDial = HighchartsDial (GHCJS.JSRef (HighchartsDial)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsDial = ('[ "backgroundColor" ::? TS.String , "baseLength" ::? TS.String , "baseWidth" ::? TS.Number , "borderColor" ::? TS.String , "borderWidth" ::? TS.Number , "radius" ::? TS.String , "rearLength" ::? TS.String , "topWidth" ::? TS.Number ]) newtype HighchartsElementObject = HighchartsElementObject (GHCJS.JSRef (HighchartsElementObject)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsElementObject = ('[ "add" ::: TS.Fun (HighchartsElementObject) , "add" ::: TS.Fun (HighchartsElementObject -> HighchartsElementObject) , "animate" ::: TS.Fun (TS.Any -> TS.Optional (TS.Any) -> HighchartsElementObject) , "attr" ::: TS.Fun (TS.Any -> HighchartsElementObject) , "css" ::: TS.Fun (HighchartsCSSObject -> HighchartsElementObject) , "destroy" ::: TS.Fun (TS.Void) , "getBBox" ::: TS.Fun (TS.Obj ('[ "x" ::: TS.Number , "y" ::: TS.Number , "height" ::: TS.Number , "width" ::: TS.Number ]) ) , "on" ::: TS.Fun (TS.String -> (TS.Void) -> HighchartsElementObject) , "toFront" ::: TS.Fun (HighchartsElementObject) ]) newtype HighchartsErrorBarChart = HighchartsErrorBarChart (GHCJS.JSRef (HighchartsErrorBarChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsErrorBarChart = ('[ ]) newtype HighchartsErrorBarChartSeriesOptions = HighchartsErrorBarChartSeriesOptions (GHCJS.JSRef (HighchartsErrorBarChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsErrorBarChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsErrorBarChart] ('[ ]) newtype HighchartsExportingOptions = HighchartsExportingOptions (GHCJS.JSRef (HighchartsExportingOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsExportingOptions = ('[ "buttons" ::? TS.Obj ('[ "exportButton" ::? HighchartsButton , "printButton" ::? HighchartsButton ]) , "enableImages" ::? TS.Boolean , "enabled" ::? TS.Boolean , "filename" ::? TS.String , "type" ::? TS.String , "url" ::? TS.String , "width" ::? TS.Number ]) newtype HighchartsExtremes = HighchartsExtremes (GHCJS.JSRef (HighchartsExtremes)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsExtremes = ('[ "dataMax" ::: TS.Number , "dataMin" ::: TS.Number , "max" ::: TS.Number , "min" ::: TS.Number ]) newtype HighchartsFunnelChart = HighchartsFunnelChart (GHCJS.JSRef (HighchartsFunnelChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsFunnelChart = ('[ ]) newtype HighchartsFunnelChartSeriesOptions = HighchartsFunnelChartSeriesOptions (GHCJS.JSRef (HighchartsFunnelChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsFunnelChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsFunnelChart] ('[ ]) newtype HighchartsGaugeChart = HighchartsGaugeChart (GHCJS.JSRef (HighchartsGaugeChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsGaugeChart = ('[ "animation" ::? TS.Boolean , "color" ::? TS.String , "cursor" ::? TS.String , "datalabels" ::? HighchartsDataLabels , "dial" ::? HighchartsDial , "enableMouseTracking" ::? TS.Boolean , "events" ::? HighchartsPlotEvents , "id" ::? TS.String , "pivot" ::? HighchartsPivot , "point" ::? TS.Obj ('[ "events" ::: HighchartsPointEvents ]) , "selected" ::? TS.Boolean , "showCheckbox" ::? TS.Boolean , "showInLegend" ::? TS.Boolean , "states" ::? TS.Obj ('[ "hover" ::: HighchartsAreaStates ]) , "stickyTracking" ::? TS.Boolean , "tooltip" ::? HighchartsTooltipOptions , "visible" ::? TS.Boolean , "zIndex" ::? TS.Number ]) newtype HighchartsGaugeChartSeriesOptions = HighchartsGaugeChartSeriesOptions (GHCJS.JSRef (HighchartsGaugeChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsGaugeChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsGaugeChart] ('[ ]) newtype HighchartsGlobalObject = HighchartsGlobalObject (GHCJS.JSRef (HighchartsGlobalObject)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsGlobalObject = ('[ "Date" ::? TS.Any , "VMLRadialGradientURL" ::? TS.String , "canvasToolsURL" ::? TS.String , "timezoneOffset" ::? TS.Number , "useUTC" ::? TS.Boolean ]) newtype HighchartsGlobalOptions = HighchartsGlobalOptions (GHCJS.JSRef (HighchartsGlobalOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsGlobalOptions = TS.Extends '[HighchartsOptions] ('[ "global" ::? HighchartsGlobalObject , "lang" ::? HighchartsLangObject ]) newtype HighchartsGradient = HighchartsGradient (GHCJS.JSRef (HighchartsGradient)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsGradient = ('[ "linearGradient" ::? TS.Obj ('[ "x1" ::: TS.Number , "y1" ::: TS.Number , "x2" ::: TS.Number , "y2" ::: TS.Number ]) , "radialGradient" ::? TS.Obj ('[ "cx" ::: TS.Number , "cy" ::: TS.Number , "r" ::: TS.Number ]) , "stops" ::? (TS.Array (TS.Array TS.Any)) , "brighten" ::? TS.Fun (TS.Number -> (TS.String :|: HighchartsGradient)) , "get" ::? TS.Fun (TS.String -> TS.String) ]) newtype HighchartsHeatMapChart = HighchartsHeatMapChart (GHCJS.JSRef (HighchartsHeatMapChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsHeatMapChart = ('[ ]) newtype HighchartsHeatMapSeriesOptions = HighchartsHeatMapSeriesOptions (GHCJS.JSRef (HighchartsHeatMapSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsHeatMapSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsHeatMapChart] ('[ ]) newtype HighchartsIndividualSeriesOptions = HighchartsIndividualSeriesOptions (GHCJS.JSRef (HighchartsIndividualSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsIndividualSeriesOptions = ('[ "data" ::? ((TS.Array TS.Number) :|: ((TS.Array (TS.Number, TS.Number)) :|: (TS.Array HighchartsDataPoint))) , "id" ::? TS.String , "index" ::? TS.Number , "legendIndex" ::? TS.Number , "name" ::? TS.String , "stack" ::? TS.Any , "type" ::? TS.String , "xAxis" ::? (TS.String :|: TS.Number) , "yAxis" ::? (TS.String :|: TS.Number) ]) newtype HighchartsLabelItem = HighchartsLabelItem (GHCJS.JSRef (HighchartsLabelItem)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsLabelItem = ('[ "html" ::: TS.String , "style" ::: HighchartsCSSObject ]) newtype HighchartsLabelsOptions = HighchartsLabelsOptions (GHCJS.JSRef (HighchartsLabelsOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsLabelsOptions = ('[ "items" ::? (TS.Array HighchartsLabelItem) , "style" ::? HighchartsCSSObject ]) newtype HighchartsLangObject = HighchartsLangObject (GHCJS.JSRef (HighchartsLangObject)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsLangObject = ('[ "contextButtonTitle" ::? TS.String , "decimalPoint" ::? TS.String , "downloadJPEG" ::? TS.String , "downloadPDF" ::? TS.String , "downloadPNG" ::? TS.String , "downloadSVG" ::? TS.String , "drillUpText" ::? TS.String , "loading" ::? TS.String , "months" ::? (TS.Array TS.String) , "noData" ::? TS.String , "numericSymbols" ::? (TS.Array TS.String) , "printChart" ::? TS.String , "resetZoom" ::? TS.String , "resetZoomTitle" ::? TS.String , "shortMonths" ::? (TS.Array TS.String) , "thousandsSep" ::? TS.String , "weekdays" ::? (TS.Array TS.String) ]) newtype HighchartsLegendNavigationOptions = HighchartsLegendNavigationOptions (GHCJS.JSRef (HighchartsLegendNavigationOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsLegendNavigationOptions = ('[ "activeColor" ::? TS.String , "animation" ::? (TS.Boolean :|: HighchartsAnimation) , "arrowSize" ::? TS.Number , "inactiveColor" ::? TS.String , "style" ::? HighchartsCSSObject ]) newtype HighchartsLegendOptions = HighchartsLegendOptions (GHCJS.JSRef (HighchartsLegendOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsLegendOptions = ('[ "align" ::? TS.String , "backgroundColor" ::? (TS.String :|: HighchartsGradient) , "borderColor" ::? TS.String , "borderRadius" ::? TS.Number , "borderWidth" ::? TS.Number , "enabled" ::? TS.Boolean , "floating" ::? TS.Boolean , "itemHiddenStyle" ::? HighchartsCSSObject , "itemHoverStyle" ::? HighchartsCSSObject , "itemMarginBottom" ::? TS.Number , "itemMarginTop" ::? TS.Number , "itemStyle" ::? HighchartsCSSObject , "itemWidth" ::? TS.Number , "labelFormatter" ::? (TS.String) , "layout" ::? TS.String , "lineHeight" ::? TS.String , "margin" ::? TS.Number , "maxHeight" ::? TS.Number , "navigation" ::? HighchartsLegendNavigationOptions , "padding" ::? TS.Number , "reversed" ::? TS.Boolean , "rtl" ::? TS.Boolean , "verticalAlign" ::? TS.String , "shadow" ::? (TS.Boolean :|: HighchartsShadow) , "style" ::? HighchartsCSSObject , "symbolPadding" ::? TS.Number , "symbolWidth" ::? TS.Number , "useHTML" ::? TS.Boolean , "width" ::? TS.Number , "x" ::? TS.Number , "y" ::? TS.Number ]) newtype HighchartsLineChart = HighchartsLineChart (GHCJS.JSRef (HighchartsLineChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsLineChart = ('[ "allowPointSelect" ::? TS.Boolean , "animation" ::? TS.Boolean , "color" ::? TS.String , "connectEnds" ::? TS.Boolean , "connectNulls" ::? TS.Boolean , "cropThreshold" ::? TS.Number , "cursor" ::? TS.String , "dashStyle" ::? TS.String , "dataLabels" ::? HighchartsDataLabels , "enableMouseTracking" ::? TS.Boolean , "events" ::? HighchartsPlotEvents , "id" ::? TS.String , "lineWidth" ::? TS.Number , "marker" ::? HighchartsMarker , "point" ::? TS.Obj ('[ "events" ::: HighchartsPointEvents ]) , "pointInterval" ::? TS.Number , "pointPlacement" ::? TS.String , "pointStart" ::? TS.Number , "selected" ::? TS.Boolean , "shadow" ::? (TS.Boolean :|: HighchartsShadow) , "showCheckbox" ::? TS.Boolean , "showInLegend" ::? TS.Boolean , "stacking" ::? TS.String , "states" ::? TS.Obj ('[ "hover" ::: HighchartsAreaStates ]) , "step" ::? (TS.Boolean :|: TS.String) , "stickyTracking" ::? TS.Boolean , "tooltip" ::? HighchartsTooltipOptions , "turboThreshold" ::? TS.Number , "visible" ::? TS.Boolean , "zIndex" ::? TS.Number ]) newtype HighchartsLineChartSeriesOptions = HighchartsLineChartSeriesOptions (GHCJS.JSRef (HighchartsLineChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsLineChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsLineChart] ('[ ]) newtype HighchartsLoadingOptions = HighchartsLoadingOptions (GHCJS.JSRef (HighchartsLoadingOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsLoadingOptions = ('[ "hideDuration" ::? TS.Number , "labelStyle" ::? HighchartsCSSObject , "showDuration" ::? TS.Number , "style" ::? HighchartsCSSObject ]) newtype HighchartsMarker = HighchartsMarker (GHCJS.JSRef (HighchartsMarker)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsMarker = TS.Extends '[HighchartsMarkerState] ('[ "states" ::? TS.Obj ('[ "hover" ::? HighchartsMarkerState , "select" ::? HighchartsMarkerState ]) , "symbol" ::? TS.String ]) newtype HighchartsMarkerState = HighchartsMarkerState (GHCJS.JSRef (HighchartsMarkerState)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsMarkerState = ('[ "enabled" ::? TS.Boolean , "fillColor" ::? TS.String , "lineColor" ::? TS.String , "lineWidth" ::? TS.Number , "radius" ::? TS.Number ]) newtype HighchartsMenuItem = HighchartsMenuItem (GHCJS.JSRef (HighchartsMenuItem)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsMenuItem = ('[ "text" ::: TS.String , "onclick" ::: (TS.Void) ]) newtype HighchartsMousePlotEvents = HighchartsMousePlotEvents (GHCJS.JSRef (HighchartsMousePlotEvents)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsMousePlotEvents = ('[ "click" ::? (TS.Optional (Event) -> TS.Void) , "mouseover" ::? (TS.Optional (Event) -> TS.Void) , "mouseout" ::? (TS.Optional (Event) -> TS.Void) , "mousemove" ::? (TS.Optional (Event) -> TS.Void) ]) newtype HighchartsNavigationOptions = HighchartsNavigationOptions (GHCJS.JSRef (HighchartsNavigationOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsNavigationOptions = ('[ "buttonOptions" ::? HighchartsButton , "menuItemHoverStyle" ::? HighchartsCSSObject , "menuItemStyle" ::? HighchartsCSSObject , "menuStyle" ::? HighchartsCSSObject ]) newtype HighchartsOptions = HighchartsOptions (GHCJS.JSRef (HighchartsOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsOptions = ('[ "chart" ::? HighchartsChartOptions , "colors" ::? (TS.Array TS.String) , "credits" ::? HighchartsCreditsOptions , "data" ::? TS.Any , "drilldown" ::? TS.Any , "exporting" ::? HighchartsExportingOptions , "labels" ::? HighchartsLabelsOptions , "legend" ::? HighchartsLegendOptions , "loading" ::? HighchartsLoadingOptions , "navigation" ::? HighchartsNavigationOptions , "noData" ::? TS.Any , "pane" ::? HighchartsPaneOptions , "plotOptions" ::? HighchartsPlotOptions , "series" ::? (TS.Array HighchartsIndividualSeriesOptions) , "subtitle" ::? HighchartsSubtitleOptions , "title" ::? HighchartsTitleOptions , "tooltip" ::? HighchartsTooltipOptions , "xAxis" ::? HighchartsAxisOptions , "yAxis" ::? HighchartsAxisOptions ]) newtype HighchartsPaneBackground = HighchartsPaneBackground (GHCJS.JSRef (HighchartsPaneBackground)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPaneBackground = ('[ "backgroundColor" ::: (TS.String :|: HighchartsGradient) , "borderColor" ::? TS.String , "borderWidth" ::? TS.Number , "innerRadius" ::? TS.String , "outerRadius" ::? TS.String ]) newtype HighchartsPaneOptions = HighchartsPaneOptions (GHCJS.JSRef (HighchartsPaneOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPaneOptions = ('[ "background" ::? (TS.Array HighchartsPaneBackground) , "center" ::? ((TS.Number :|: TS.String), (TS.Number :|: TS.String)) , "endAngle" ::? TS.Number , "size" ::? (TS.Number :|: TS.String) , "startAngle" ::? TS.Number ]) newtype HighchartsPieChart = HighchartsPieChart (GHCJS.JSRef (HighchartsPieChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPieChart = ('[ "allowPointSelect" ::? TS.Boolean , "animation" ::? TS.Boolean , "borderColor" ::? TS.String , "borderWidth" ::? TS.Number , "center" ::? (TS.Array TS.String) , "color" ::? TS.String , "cursor" ::? TS.String , "dataLabels" ::? HighchartsDataLabels , "enableMouseTracking" ::? TS.Boolean , "events" ::? HighchartsPlotEvents , "id" ::? TS.String , "ignoreHiddenPoint" ::? TS.Boolean , "innerSize" ::? (TS.Number :|: TS.String) , "lineWidth" ::? TS.Number , "marker" ::? HighchartsMarker , "point" ::? TS.Obj ('[ "events" ::: HighchartsPointEvents ]) , "pointPlacement" ::? TS.String , "selected" ::? TS.Boolean , "shadow" ::? (TS.Boolean :|: HighchartsShadow) , "showInLegend" ::? TS.Boolean , "size" ::? (TS.Number :|: TS.String) , "slicedOffset" ::? TS.Number , "states" ::? TS.Obj ('[ "hover" ::: HighchartsAreaStates ]) , "stickyTracking" ::? TS.Boolean , "tooltip" ::? HighchartsTooltipOptions , "visible" ::? TS.Boolean , "zIndex" ::? TS.Number ]) newtype HighchartsPieChartSeriesOptions = HighchartsPieChartSeriesOptions (GHCJS.JSRef (HighchartsPieChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPieChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsPieChart] ('[ ]) newtype HighchartsPivot = HighchartsPivot (GHCJS.JSRef (HighchartsPivot)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPivot = ('[ "backgroundColor" ::? TS.String , "borderColor" ::? TS.String , "borderWidth" ::? TS.Number , "radius" ::? TS.Number ]) newtype HighchartsPlotBands = HighchartsPlotBands (GHCJS.JSRef (HighchartsPlotBands)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPlotBands = ('[ "color" ::? TS.String , "events" ::? HighchartsMousePlotEvents , "from" ::? TS.Number , "id" ::? TS.String , "label" ::? HighchartsPlotLabel , "to" ::? TS.Number , "zIndex" ::? TS.Number ]) newtype HighchartsPlotEvents = HighchartsPlotEvents (GHCJS.JSRef (HighchartsPlotEvents)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPlotEvents = ('[ "checkboxClick" ::? (HighchartsAreaCheckboxEvent -> TS.Boolean) , "click" ::? (HighchartsAreaClickEvent -> TS.Void) , "hide" ::? (TS.Void) , "legendItemClick" ::? (Event -> TS.Boolean) , "mouseOut" ::? (Event -> TS.Void) , "mouseOver" ::? (Event -> TS.Void) , "show" ::? (TS.Void) ]) newtype HighchartsPlotLabel = HighchartsPlotLabel (GHCJS.JSRef (HighchartsPlotLabel)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPlotLabel = ('[ "align" ::? TS.String , "rotation" ::? TS.Number , "style" ::? HighchartsCSSObject , "text" ::? TS.String , "textAlign" ::? TS.String , "x" ::? TS.Number , "y" ::? TS.Number ]) newtype HighchartsPlotLines = HighchartsPlotLines (GHCJS.JSRef (HighchartsPlotLines)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPlotLines = ('[ "color" ::? TS.String , "dashStyle" ::? TS.String , "events" ::? HighchartsMousePlotEvents , "id" ::? TS.String , "label" ::? HighchartsPlotLabel , "value" ::? TS.Number , "width" ::? TS.Number , "zIndex" ::? TS.Number ]) newtype HighchartsPlotOptions = HighchartsPlotOptions (GHCJS.JSRef (HighchartsPlotOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPlotOptions = ('[ "area" ::? HighchartsAreaChart , "arearange" ::? HighchartsAreaRangeChart , "areaspline" ::? HighchartsAreaSplineChart , "areasplinerange" ::? HighchartsAreaSplineRangeChart , "bar" ::? HighchartsBarChart , "boxplot" ::? HighchartsBoxPlotChart , "bubble" ::? HighchartsBubbleChart , "column" ::? HighchartsColumnChart , "columnrange" ::? HighchartsColumnRangeChart , "errorbar" ::? HighchartsErrorBarChart , "funnel" ::? HighchartsFunnelChart , "gauge" ::? HighchartsGaugeChart , "heatmap" ::? HighchartsHeatMapChart , "line" ::? HighchartsLineChart , "pie" ::? HighchartsPieChart , "polygon" ::? HighchartsPolygonChart , "pyramid" ::? HighchartsPyramidChart , "scatter" ::? HighchartsScatterChart , "series" ::? HighchartsSeriesChart , "solidgauge" ::? HighchartsSolidGaugeChart , "spline" ::? HighchartsSplineChart , "treemap" ::? HighchartsTreeMapChart , "waterfall" ::? HighchartsWaterFallChart ]) newtype HighchartsPlotPoint = HighchartsPlotPoint (GHCJS.JSRef (HighchartsPlotPoint)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPlotPoint = ('[ "plotX" ::: TS.Number , "plotY" ::: TS.Number ]) newtype HighchartsPointEvents = HighchartsPointEvents (GHCJS.JSRef (HighchartsPointEvents)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPointEvents = ('[ "click" ::? (Event -> TS.Boolean) , "mouseOut" ::? (Event -> TS.Void) , "mouseOver" ::? (Event -> TS.Void) , "remove" ::? (Event -> TS.Boolean) , "select" ::? (Event -> TS.Boolean) , "unselect" ::? (Event -> TS.Boolean) , "update" ::? (Event -> TS.Boolean) ]) newtype HighchartsPointObject = HighchartsPointObject (GHCJS.JSRef (HighchartsPointObject)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPointObject = ('[ "category" ::: (TS.String :|: TS.Number) , "percentage" ::: TS.Number , "remove" ::: TS.Fun (TS.Optional (TS.Boolean) -> TS.Optional ((TS.Boolean :|: HighchartsAnimation)) -> TS.Void) , "select" ::: TS.Fun (TS.Void) , "select" ::: TS.Fun (TS.Boolean -> TS.Void) , "select" ::: TS.Fun (TS.Boolean -> TS.Boolean -> TS.Void) , "selected" ::: TS.Boolean , "series" ::: HighchartsSeriesObject , "slice" ::: TS.Fun (TS.Optional (TS.Boolean) -> TS.Optional (TS.Boolean) -> TS.Optional ((TS.Boolean :|: HighchartsAnimation)) -> TS.Void) , "total" ::: TS.Number , "update" ::: TS.Fun ((TS.Number :|: ((TS.Number, TS.Number) :|: HighchartsDataPoint)) -> TS.Optional (TS.Boolean) -> TS.Optional ((TS.Boolean :|: HighchartsAnimation)) -> TS.Void) , "x" ::: TS.Number , "y" ::: TS.Number ]) newtype HighchartsPolygonChart = HighchartsPolygonChart (GHCJS.JSRef (HighchartsPolygonChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPolygonChart = ('[ ]) newtype HighchartsPolygonChartSeriesOptions = HighchartsPolygonChartSeriesOptions (GHCJS.JSRef (HighchartsPolygonChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPolygonChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsPolygonChart] ('[ ]) newtype HighchartsPosition = HighchartsPosition (GHCJS.JSRef (HighchartsPosition)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPosition = ('[ "align" ::? TS.String , "verticalAlign" ::? TS.String , "x" ::? TS.Number , "y" ::? TS.Number ]) newtype HighchartsPyramidChart = HighchartsPyramidChart (GHCJS.JSRef (HighchartsPyramidChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPyramidChart = ('[ ]) newtype HighchartsPyramidChartSeriesOptions = HighchartsPyramidChartSeriesOptions (GHCJS.JSRef (HighchartsPyramidChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsPyramidChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsPyramidChart] ('[ ]) newtype HighchartsRangeDataLabels = HighchartsRangeDataLabels (GHCJS.JSRef (HighchartsRangeDataLabels)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsRangeDataLabels = ('[ "align" ::? TS.String , "backgroundColor" ::? (TS.String :|: HighchartsGradient) , "borderColor" ::? TS.String , "borderRadius" ::? TS.Number , "borderWidth" ::? TS.Number , "color" ::? TS.String , "crop" ::? TS.Boolean , "defer" ::? TS.Boolean , "enabled" ::? TS.Boolean , "format" ::? TS.String , "formatter" ::? (TS.Any) , "inside" ::? TS.Boolean , "overflow" ::? TS.String , "padding" ::? TS.Number , "rotation" ::? TS.Number , "shadow" ::? (TS.Boolean :|: HighchartsShadow) , "style" ::? HighchartsCSSObject , "useHTML" ::? TS.Boolean , "verticalAlign" ::? TS.String , "xHigh" ::? TS.Number , "xLow" ::? TS.Number , "yHigh" ::? TS.Number , "yLow" ::? TS.Number , "zIndex" ::? TS.Number ]) newtype HighchartsRenderer = HighchartsRenderer (GHCJS.JSRef (HighchartsRenderer)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsRenderer = ('[ TS.Constructor (HTMLElement -> TS.Number -> TS.Number -> HighchartsRendererObject) ]) newtype HighchartsRendererObject = HighchartsRendererObject (GHCJS.JSRef (HighchartsRendererObject)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsRendererObject = ('[ "arc" ::: TS.Fun (TS.Number -> TS.Number -> TS.Number -> TS.Number -> TS.Number -> TS.Number -> HighchartsElementObject) , "circle" ::: TS.Fun (TS.Number -> TS.Number -> TS.Number -> HighchartsElementObject) , "g" ::: TS.Fun (TS.String -> HighchartsElementObject) , "image" ::: TS.Fun (TS.String -> TS.Number -> TS.Number -> TS.Number -> TS.Number -> HighchartsElementObject) , "path" ::: TS.Fun ((TS.Array TS.Any) -> HighchartsElementObject) , "rect" ::: TS.Fun (TS.Number -> TS.Number -> TS.Number -> TS.Number -> TS.Number -> HighchartsElementObject) , "text" ::: TS.Fun (TS.String -> TS.Number -> TS.Number -> HighchartsElementObject) ]) newtype HighchartsScatterChart = HighchartsScatterChart (GHCJS.JSRef (HighchartsScatterChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsScatterChart = ('[ "allowPointSelect" ::? TS.Boolean , "animation" ::? TS.Boolean , "color" ::? TS.String , "connectNulls" ::? TS.Boolean , "cropThreshold" ::? TS.Number , "cursor" ::? TS.String , "dashStyle" ::? TS.String , "dataLabels" ::? HighchartsDataLabels , "enableMouseTracking" ::? TS.Boolean , "events" ::? HighchartsPlotEvents , "id" ::? TS.String , "lineWidth" ::? TS.Number , "marker" ::? HighchartsMarker , "point" ::? TS.Obj ('[ "events" ::: HighchartsPointEvents ]) , "pointInterval" ::? TS.Number , "pointPlacement" ::? TS.String , "pointStart" ::? TS.Number , "selected" ::? TS.Boolean , "shadow" ::? (TS.Boolean :|: HighchartsShadow) , "showCheckbox" ::? TS.Boolean , "showInLegend" ::? TS.Boolean , "states" ::? TS.Obj ('[ "hover" ::: HighchartsAreaStates ]) , "stickyTracking" ::? TS.Boolean , "tooltip" ::? HighchartsTooltipOptions , "turboThreshold" ::? TS.Number , "visible" ::? TS.Boolean , "zIndex" ::? TS.Number ]) newtype HighchartsScatterChartSeriesOptions = HighchartsScatterChartSeriesOptions (GHCJS.JSRef (HighchartsScatterChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsScatterChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsScatterChart] ('[ ]) newtype HighchartsSelectionEvent = HighchartsSelectionEvent (GHCJS.JSRef (HighchartsSelectionEvent)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsSelectionEvent = TS.Extends '[Event] ('[ "xAxis" ::: (TS.Array HighchartsAxisOptions) , "yAxis" ::: (TS.Array HighchartsAxisOptions) ]) newtype HighchartsSeriesChart = HighchartsSeriesChart (GHCJS.JSRef (HighchartsSeriesChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsSeriesChart = ('[ "allowPointSelect" ::? TS.Boolean , "animation" ::? TS.Boolean , "color" ::? TS.String , "connectEnds" ::? TS.Boolean , "connectNulls" ::? TS.Boolean , "cropThreshold" ::? TS.Number , "cursor" ::? TS.String , "dashStyle" ::? TS.String , "dataLabels" ::? HighchartsDataLabels , "enableMouseTracking" ::? TS.Boolean , "events" ::? HighchartsPlotEvents , "lineWidth" ::? TS.Number , "marker" ::? HighchartsMarker , "point" ::? TS.Obj ('[ "events" ::: HighchartsPointEvents ]) , "pointInterval" ::? TS.Number , "pointPlacement" ::? TS.String , "pointStart" ::? TS.Number , "selected" ::? TS.Boolean , "shadow" ::? (TS.Boolean :|: HighchartsShadow) , "showCheckbox" ::? TS.Boolean , "showInLegend" ::? TS.Boolean , "stacking" ::? TS.String , "states" ::? TS.Obj ('[ "hover" ::: HighchartsAreaStates ]) , "stickyTracking" ::? TS.Boolean , "tooltip" ::? HighchartsTooltipOptions , "turboThreshold" ::? TS.Number , "visible" ::? TS.Boolean , "zIndex" ::? TS.Number ]) newtype HighchartsSeriesObject = HighchartsSeriesObject (GHCJS.JSRef (HighchartsSeriesObject)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsSeriesObject = ('[ "addPoint" ::: TS.Fun ((TS.Number :|: ((TS.Number, TS.Number) :|: HighchartsDataPoint)) -> TS.Optional (TS.Boolean) -> TS.Optional (TS.Boolean) -> TS.Optional ((TS.Boolean :|: HighchartsAnimation)) -> TS.Void) , "chart" ::: HighchartsChartObject , "data" ::: (TS.Array HighchartsPointObject) , "hide" ::: TS.Fun (TS.Void) , "name" ::: TS.String , "options" ::: HighchartsSeriesOptions , "remove" ::: TS.Fun (TS.Optional (TS.Boolean) -> TS.Void) , "select" ::: TS.Fun (TS.Optional (TS.Boolean) -> TS.Void) , "selected" ::: TS.Boolean , "setData" ::: TS.Fun (((TS.Array TS.Number) :|: ((TS.Array (TS.Array TS.Number)) :|: (TS.Array HighchartsDataPoint))) -> TS.Optional (TS.Boolean) -> TS.Optional ((TS.Boolean :|: HighchartsAnimation)) -> TS.Optional (TS.Boolean) -> TS.Void) , "setVisible" ::: TS.Fun (TS.Boolean -> TS.Optional (TS.Boolean) -> TS.Void) , "show" ::: TS.Fun (TS.Void) , "type" ::: TS.String , "update" ::: TS.Fun (HighchartsSeriesOptions -> TS.Optional (TS.Boolean) -> TS.Void) , "visible" ::: TS.Boolean , "xAxis" ::: HighchartsAxisObject , "yAxis" ::: HighchartsAxisObject ]) newtype HighchartsSeriesOptions = HighchartsSeriesOptions (GHCJS.JSRef (HighchartsSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsSeriesOptions = TS.Extends '[HighchartsSeriesChart] ('[ "type" ::? TS.String , "data" ::? ((TS.Array TS.Number) :|: ((TS.Array (TS.Array TS.Number)) :|: (TS.Array HighchartsDataPoint))) , "index" ::? TS.Number , "legendIndex" ::? TS.Number , "name" ::? TS.String , "stack" ::? (TS.String :|: TS.Number) , "xAxis" ::? (TS.String :|: TS.Number) , "yAxis" ::? (TS.String :|: TS.Number) ]) newtype HighchartsShadow = HighchartsShadow (GHCJS.JSRef (HighchartsShadow)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsShadow = ('[ "color" ::? TS.String , "offsetX" ::? TS.Number , "offsetY" ::? TS.Number , "opacity" ::? TS.Number , "width" ::? TS.Number ]) newtype HighchartsSolidGaugeChart = HighchartsSolidGaugeChart (GHCJS.JSRef (HighchartsSolidGaugeChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsSolidGaugeChart = ('[ ]) newtype HighchartsSolidGaugeChartSeriesOptions = HighchartsSolidGaugeChartSeriesOptions (GHCJS.JSRef (HighchartsSolidGaugeChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsSolidGaugeChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsSolidGaugeChart] ('[ ]) newtype HighchartsSplineChart = HighchartsSplineChart (GHCJS.JSRef (HighchartsSplineChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsSplineChart = TS.Extends '[HighchartsSeriesChart] ('[ ]) newtype HighchartsSplineChartSeriesOptions = HighchartsSplineChartSeriesOptions (GHCJS.JSRef (HighchartsSplineChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsSplineChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsSplineChart] ('[ ]) newtype HighchartsStatic = HighchartsStatic (GHCJS.JSRef (HighchartsStatic)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsStatic = ('[ "Chart" ::: HighchartsChart , "Renderer" ::: HighchartsRenderer , "Color" ::: TS.Fun ((TS.String :|: HighchartsGradient) -> (TS.String :|: HighchartsGradient)) , "dateFormat" ::: TS.Fun (TS.String -> TS.Optional (TS.Number) -> TS.Optional (TS.Boolean) -> TS.String) , "numberFormat" ::: TS.Fun (TS.Number -> TS.Optional (TS.Number) -> TS.Optional (TS.String) -> TS.Optional (TS.String) -> TS.String) , "setOptions" ::: TS.Fun (HighchartsGlobalOptions -> HighchartsOptions) , "getOptions" ::: TS.Fun (HighchartsOptions) , "map" ::: TS.Fun ((TS.Array TS.Any) -> Function -> (TS.Array TS.Any)) ]) newtype HighchartsSubtitleOptions = HighchartsSubtitleOptions (GHCJS.JSRef (HighchartsSubtitleOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsSubtitleOptions = ('[ "align" ::? TS.String , "verticalAlign" ::? TS.String , "floating" ::? TS.Boolean , "style" ::? HighchartsCSSObject , "text" ::? TS.String , "useHTML" ::? TS.Boolean , "x" ::? TS.Number , "y" ::? TS.Number ]) newtype HighchartsTitleOptions = HighchartsTitleOptions (GHCJS.JSRef (HighchartsTitleOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsTitleOptions = TS.Extends '[HighchartsSubtitleOptions] ('[ "margin" ::? TS.Number ]) newtype HighchartsTooltipOptions = HighchartsTooltipOptions (GHCJS.JSRef (HighchartsTooltipOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsTooltipOptions = ('[ "animation" ::? TS.Boolean , "backgroundColor" ::? (TS.String :|: HighchartsGradient) , "borderColor" ::? TS.String , "borderRadius" ::? TS.Number , "borderWidth" ::? TS.Number , "crosshairs" ::? (TS.Boolean :|: ((TS.Boolean, TS.Boolean) :|: (HighchartsCrosshairObject :|: (HighchartsCrosshairObject, HighchartsCrosshairObject)))) , "enabled" ::? TS.Boolean , "footerFormat" ::? TS.String , "formatter" ::? (TS.Any) , "pointFormat" ::? TS.String , "positioner" ::? (TS.Number -> TS.Number -> HighchartsPlotPoint -> TS.Obj ('[ "x" ::: TS.Number , "y" ::: TS.Number ]) ) , "shadow" ::? TS.Boolean , "shared" ::? TS.Boolean , "snap" ::? TS.Number , "style" ::? HighchartsCSSObject , "useHTML" ::? TS.Boolean , "valueDecimals" ::? TS.Number , "valuePrefix" ::? TS.String , "valueSuffix" ::? TS.String , "xDateFormat" ::? TS.String ]) newtype HighchartsTreeMapChart = HighchartsTreeMapChart (GHCJS.JSRef (HighchartsTreeMapChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsTreeMapChart = ('[ ]) newtype HighchartsTreeMapChartSeriesOptions = HighchartsTreeMapChartSeriesOptions (GHCJS.JSRef (HighchartsTreeMapChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsTreeMapChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsTreeMapChart] ('[ ]) newtype HighchartsWaterFallChart = HighchartsWaterFallChart (GHCJS.JSRef (HighchartsWaterFallChart)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsWaterFallChart = ('[ ]) newtype HighchartsWaterFallChartSeriesOptions = HighchartsWaterFallChartSeriesOptions (GHCJS.JSRef (HighchartsWaterFallChartSeriesOptions)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members HighchartsWaterFallChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsWaterFallChart] ('[ ]) newtype JQuery = JQuery (GHCJS.JSRef (JQuery)) deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef) type instance TS.Members JQuery = ('[ "highcharts" ::: TS.Fun (HighchartsChartObject) , "highcharts" ::: TS.Fun (HighchartsOptions -> JQuery) , "highcharts" ::: TS.Fun (HighchartsOptions -> (HighchartsChartObject -> TS.Void) -> JQuery) ])
mgsloan/ghcjs-typescript
examples/highcharts/Raw.hs
Haskell
mit
68,354
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.XMLHttpRequestUpload (abort, error, load, loadEnd, loadStart, progress, XMLHttpRequestUpload, castToXMLHttpRequestUpload, gTypeXMLHttpRequestUpload) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestUpload.onabort Mozilla XMLHttpRequestUpload.onabort documentation> abort :: EventName XMLHttpRequestUpload XMLHttpRequestProgressEvent abort = unsafeEventName (toJSString "abort") -- | <https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestUpload.onerror Mozilla XMLHttpRequestUpload.onerror documentation> error :: EventName XMLHttpRequestUpload XMLHttpRequestProgressEvent error = unsafeEventName (toJSString "error") -- | <https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestUpload.onload Mozilla XMLHttpRequestUpload.onload documentation> load :: EventName XMLHttpRequestUpload XMLHttpRequestProgressEvent load = unsafeEventName (toJSString "load") -- | <https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestUpload.onloadend Mozilla XMLHttpRequestUpload.onloadend documentation> loadEnd :: EventName XMLHttpRequestUpload ProgressEvent loadEnd = unsafeEventName (toJSString "loadend") -- | <https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestUpload.onloadstart Mozilla XMLHttpRequestUpload.onloadstart documentation> loadStart :: EventName XMLHttpRequestUpload ProgressEvent loadStart = unsafeEventName (toJSString "loadstart") -- | <https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestUpload.onprogress Mozilla XMLHttpRequestUpload.onprogress documentation> progress :: EventName XMLHttpRequestUpload XMLHttpRequestProgressEvent progress = unsafeEventName (toJSString "progress")
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/XMLHttpRequestUpload.hs
Haskell
mit
2,568
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TypeOperators #-} module Api (app) where import Control.Monad.Except (ExceptT) import Control.Monad.Reader (ReaderT, runReaderT) -- import Control.Monad.Reader.Class () import Data.Int (Int64) import Database.Persist.Postgresql (Entity (..), fromSqlKey, insert, selectFirst, selectList, (==.)) import Network.Wai (Application) import Servant {- ((:<|>)((:<|>)), (:~>)(Nat) , Proxy(Proxy) , Raw, Server , ServantErr, enter, serve , serveDirectory) -} import Config (App (..), Config (..)) import Models import Api.Aircraft -- | This is the function we export to run our 'AircraftAPI'. Given -- a 'Config', we return a WAI 'Application' which any WAI compliant server -- can run. aircraftApp :: Config -> Application aircraftApp cfg = serve (Proxy :: Proxy AircraftAPI) (appToServer cfg) -- | This functions tells Servant how to run the 'App' monad with our -- 'server' function. appToServer :: Config -> Server AircraftAPI appToServer cfg = enter (convertApp cfg) aircraftServer -- | This function converts our 'App' monad into the @ExceptT ServantErr -- IO@ monad that Servant's 'enter' function needs in order to run the -- application. The ':~>' type is a natural transformation, or, in -- non-category theory terms, a function that converts two type -- constructors without looking at the values in the types. convertApp :: Config -> App :~> ExceptT ServantErr IO convertApp cfg = Nat (flip runReaderT cfg . runApp) -- | Since we also want to provide a minimal front end, we need to give -- Servant a way to serve a directory with HTML and JavaScript. This -- function creates a WAI application that just serves the files out of the -- given directory. files :: Application files = serveDirectory "assets" -- | Just like a normal API type, we can use the ':<|>' combinator to unify -- two different APIs and applications. This is a powerful tool for code -- reuse and abstraction! We need to put the 'Raw' endpoint last, since it -- always succeeds. type AppAPI = AircraftAPI :<|> Raw appApi :: Proxy AppAPI appApi = Proxy -- | Finally, this function takes a configuration and runs our 'AircraftAPI' -- alongside the 'Raw' endpoint that serves all of our files. app :: Config -> Application app cfg = serve appApi (appToServer cfg :<|> files)
tdox/aircraft-service
src/Api.hs
Haskell
mit
2,746
{-# LANGUAGE ScopedTypeVariables #-} -------------------------------------------------- -------------------------------------------------- {-| Define (non-deriveable) 'Ix' instances via a (deriveable) 'Enumerate' instance. == Usage @ data A = ... instance 'Bounded' A where minBound = 'minBound_Enumerable' array_A maxBound = 'maxBound_Enumerable' array_A instance 'Enum' A where toEnum = 'toEnum_Enumerable' array_A fromEnum = 'fromEnum_Enumerable' table_A -- CAF array_A :: 'Array' Int A array_A = 'array_Enumerable' -- CAF table_A :: 'Map' A Int table_A = 'table_Enumerable' -- we must pass in <https://wiki.haskell.org/Constant_applicative_form CAF>s -- (i.e. expressions that are top-level and unconstrained), -- which will be shared between all calls to minBound/maxBound/toEnum/fromEnum. -- TODO must we? @ --TODO template-haskell See, also, the source of "Enumerate.Example". @ inRange (l,u) i == elem i (range (l,u)) range (l,u) !! index (l,u) i == i, when inRange (l,u) i map (index (l,u)) (range (l,u))) == [0..rangeSize (l,u)-1] rangeSize (l,u) == length (range (l,u)) @ -} -------------------------------------------------- -------------------------------------------------- module Enumerate.Ix ( -- * @Ix@ methods: range_Enumerable , unsafeIndex_Enumerable , inRange_Enumerable ) where -------------------------------------------------- -------------------------------------------------- import Enumerate.Prelude import Enumerate.Types import Enumerate.Enum -------------------------------------------------- -- Imports --------------------------------------- -------------------------------------------------- import qualified "containers" Data.Map as Map import "containers" Data.Map (Map) -------------------------------------------------- import qualified "containers" Data.Sequence as Seq import "containers" Data.Sequence (Seq) -------------------------------------------------- import qualified Prelude -------------------------------------------------- -- Types ----------------------------------------- -------------------------------------------------- --type BinarySearchTree a = (Int,a) -- TODO -- Data.Map -- Data.IntMap -- Data.Sequence -------------------------------------------------- -- « Ix » ---------------------------------------- -------------------------------------------------- {- | A (`Seq`-based) `range` implementation for an 'Enumerable' type. "The list of values in the subrange defined by a bounding pair." -} range_Enumerable :: forall a. (Enumerable a, Ord a) => (a,a) -> [a] range_Enumerable = range_Seq sequence_Enumerable {-# INLINEABLE range_Enumerable #-} -------------------------------------------------- {- {- | "Like 'index', but without checking that the value is in range." -} unsafeIndex_Enumerable :: forall a. (Enumerable a, Ord a) => (a,a) -> a -> Int unsafeIndex_Enumerable = _indexWith _enumerated {-# INLINEABLE unsafeIndex_Enumerable #-} -------------------------------------------------- {- | "Returns @True@ if the given subscript lies in the range defined by the bounding pair." -} inRange_Enumerable :: forall a. (Enumerable a, Ord a) => (a,a) -> a -> Bool inRange_Enumerable = _withinWith _enumerated {-# INLINEABLE inRange_Enumerable #-} -------------------------------------------------- -- Caching --------------------------------------- -------------------------------------------------- {-| Binary Search Tree for all values in a type. Efficiently find subsets of Mapping from indices (@Int@) to values (@Enumerable a => @a@). -} tree_Enumerable :: forall a. (Enumerable a) => BinarySearchTree a tree_Enumerable = tree where tree :: Tree Int a tree = Tree.listTree bounds enumerated bounds :: (Int, Int) bounds = (0, n - 1) n = intCardinality ([] :: [a]) -} -------------------------------------------------- -- Utilities ------------------------------------- -------------------------------------------------- {- | Return a `range` function, given a `Seq`uence. i.e. @range_Seq xs@ asssumes the `Seq`uence @(xs :: 'Seq' a)@ is monotonically increasing, w.r.t @('Ord' a)@ . You may call 'Seq.sort' on @xs@ to ensure this prerequisite. -} range_Seq :: forall a. (Ord a) => Seq a -> ((a,a) -> [a]) range_Seq xs = range_ where range_ :: (a,a) -> [a] range_ (i,k) = if (i <= k) then toList js else [] where js = xs & ( Seq.dropWhileL (`lessThan` i) > Seq.takeWhileL (<= k) ) {-# INLINEABLE range_Seq #-} -------------------------------------------------- {- | Return an `inRange` function, given a `Seq`uence. -} inRange_Seq :: forall a. (Ord a) => Seq a -> ((a, a) -> a -> Bool) inRange_Seq xs = inRange_ where inRange_ :: (a, a) -> a -> Bool inRange_ (i,j) x = ys where ys = _ xs {-# INLINEABLE inRange_Seq #-} -------------------------------------------------- -- Notes ----------------------------------------- -------------------------------------------------- {- from <http://hackage.haskell.org/package/base-4.12.0.0/docs/src/GHC.Arr.html#range>: {- ... Note [Inlining index] ~~~~~~~~~~~~~~~~~~~~~ We inline the 'index' operation, * Partly because it generates much faster code (although bigger); see Trac #1216 * Partly because it exposes the bounds checks to the simplifier which might help a big. If you make a per-instance index method, you may consider inlining it. Note [Double bounds-checking of index values] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When you index an array, a!x, there are two possible bounds checks we might make: (A) Check that (inRange (bounds a) x) holds. (A) is checked in the method for 'index' (B) Check that (index (bounds a) x) lies in the range 0..n, where n is the size of the underlying array (B) is checked in the top-level function (!), in safeIndex. Of course it *should* be the case that (A) holds iff (B) holds, but that is a property of the particular instances of index, bounds, and inRange, so GHC cannot guarantee it. * If you do (A) and not (B), then you might get a seg-fault, by indexing at some bizarre location. Trac #1610 * If you do (B) but not (A), you may get no complaint when you index an array out of its semantic bounds. Trac #2120 At various times we have had (A) and not (B), or (B) and not (A); both led to complaints. So now we implement *both* checks (Trac #2669). For 1-d, 2-d, and 3-d arrays of Int we have specialised instances to avoid this. Note [Out-of-bounds error messages] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The default method for 'index' generates hoplelessIndexError, because Ix doesn't have Show as a superclass. For particular base types we can do better, so we override the default method for index. -} -- Abstract these errors from the relevant index functions so that -- the guts of the function will be small enough to inline. {-# NOINLINE indexError #-} indexError :: Show a => (a,a) -> a -> String -> b indexError rng i tp = errorWithoutStackTrace (showString "Ix{" . showString tp . showString "}.index: Index " . showParen True (showsPrec 0 i) . showString " out of range " $ showParen True (showsPrec 0 rng) "") hopelessIndexError :: Int -- Try to use 'indexError' instead! hopelessIndexError = errorWithoutStackTrace "Error in array index" -} -------------------------------------------------- -- EOF ------------------------------------------- --------------------------------------------------
sboosali/enumerate
enumerate/sources/Enumerate/Ix.hs
Haskell
mit
7,847
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-webacl-action.html module Stratosphere.ResourceProperties.WAFRegionalWebACLAction where import Stratosphere.ResourceImports -- | Full data type definition for WAFRegionalWebACLAction. See -- 'wafRegionalWebACLAction' for a more convenient constructor. data WAFRegionalWebACLAction = WAFRegionalWebACLAction { _wAFRegionalWebACLActionType :: Val Text } deriving (Show, Eq) instance ToJSON WAFRegionalWebACLAction where toJSON WAFRegionalWebACLAction{..} = object $ catMaybes [ (Just . ("Type",) . toJSON) _wAFRegionalWebACLActionType ] -- | Constructor for 'WAFRegionalWebACLAction' containing required fields as -- arguments. wafRegionalWebACLAction :: Val Text -- ^ 'wafrwaclaType' -> WAFRegionalWebACLAction wafRegionalWebACLAction typearg = WAFRegionalWebACLAction { _wAFRegionalWebACLActionType = typearg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-webacl-action.html#cfn-wafregional-webacl-action-type wafrwaclaType :: Lens' WAFRegionalWebACLAction (Val Text) wafrwaclaType = lens _wAFRegionalWebACLActionType (\s a -> s { _wAFRegionalWebACLActionType = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/WAFRegionalWebACLAction.hs
Haskell
mit
1,379
--file ch6/TypeClass.hs module TypeClass where class BasicEq a where isEqual :: a -> a -> Bool isEqual x y = not (isNotEqual x y) isNotEqual :: a -> a -> Bool isNotEqual x y = not (isEqual x y) data Color = Red | Blue | Green deriving (Show, Read, Eq, Ord) instance BasicEq Color where isEqual Red Red = True isEqual Blue Blue = True isEqual Green Green = True isEqual _ _ = True type JSONError = String class JSON a where toJValue :: a -> JValue fromJValue :: JValue -> Either JSONError a instance JSON JValue where toJValue = id fromJValue = Right
Numberartificial/workflow
haskell-first-principles/src/RW/CH6/TypeClass.hs
Haskell
mit
610
module HepMC.Barcoded where import Control.Lens import Data.IntMap (IntMap) import qualified Data.IntMap as IM type BC = Int class Barcoded b where bc :: Lens' b BC instance (Barcoded a, Barcoded b) => Barcoded (Either a b) where bc = choosing bc bc liftBC :: Barcoded a => (BC -> b) -> a -> b liftBC f = f . view bc liftBC2 :: (Barcoded a, Barcoded b) => (BC -> BC -> c) -> a -> b -> c liftBC2 f a b = f (view bc a) (view bc b) withBC :: Barcoded b => b -> (BC, b) withBC b = (view bc b, b) insertBC :: Barcoded b => b -> IntMap b -> IntMap b insertBC b = IM.insert (view bc b) b deleteBC :: Barcoded b => b -> IntMap b -> IntMap b deleteBC = sans . view bc fromListBC :: Barcoded b => [b] -> IntMap b fromListBC = IM.fromList . map withBC
cspollard/HHepMC
src/HepMC/Barcoded.hs
Haskell
apache-2.0
780
{-# LANGUAGE ExistentialQuantification #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files -- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. ----------------------------------------------------------------------------- -- | -- Maintainer : bastiaan.heeren@ou.nl -- Stability : provisional -- Portability : portable (depends on ghc) -- -- References, bindings, and heterogenous environments -- ----------------------------------------------------------------------------- module Ideas.Common.Environment ( -- * Reference Ref, Reference(..), mapRef -- * Binding , Binding, makeBinding , fromBinding, showValue, getTermValue -- * Heterogeneous environment , Environment, makeEnvironment, singleBinding , HasEnvironment(..), HasRefs(..) , bindings, noBindings, (?) ) where import Control.Monad import Data.Function import Data.List import Data.Semigroup as Sem import Ideas.Common.Id import Ideas.Common.Rewriting.Term import Ideas.Common.View import Ideas.Utils.Prelude import Ideas.Utils.Typeable import qualified Data.Map as M ----------------------------------------------------------- -- Reference -- | A data type for references (without a value) data Ref a = Ref { identifier :: Id -- Identifier , printer :: a -> String -- Pretty-printer , parser :: String -> Maybe a -- Parser , refView :: View Term a -- Conversion to/from term , refType :: IsTypeable a } instance Show (Ref a) where show = showId instance Eq (Ref a) where (==) = (==) `on` getId instance HasId (Ref a) where getId = identifier changeId f d = d {identifier = f (identifier d)} instance HasTypeable Ref where getTypeable = Just . refType -- | A type class for types as references class (IsTerm a, Typeable a, Show a, Read a) => Reference a where makeRef :: IsId n => n -> Ref a makeRefList :: IsId n => n -> Ref [a] -- default implementation makeRef n = Ref (newId n) show readM termView typeable makeRefList n = Ref (newId n) show readM termView typeable instance Reference Int instance Reference Term instance Reference Char where makeRefList n = Ref (newId n) id Just variableView typeable instance Reference ShowString instance Reference a => Reference [a] where makeRef = makeRefList instance (Reference a, Reference b) => Reference (a, b) mapRef :: Typeable b => Isomorphism a b -> Ref a -> Ref b mapRef iso r = r { printer = printer r . to iso , parser = fmap (from iso) . parser r , refView = refView r >>> toView iso , refType = typeable } ----------------------------------------------------------- -- Binding data Binding = forall a . Binding (Ref a) a instance Show Binding where show a = showId a ++ "=" ++ showValue a instance Eq Binding where (==) = let f (Binding r a) = (getId r, build (refView r) a) in (==) `on` f instance HasId Binding where getId (Binding r _ ) = getId r changeId f (Binding r a) = Binding (changeId f r) a makeBinding :: Ref a -> a -> Binding makeBinding = Binding fromBinding :: Typeable a => Binding -> Maybe (Ref a, a) fromBinding (Binding r a) = liftM2 (,) (gcastFrom r r) (castFrom r a) showValue :: Binding -> String showValue (Binding r a) = printer r a getTermValue :: Binding -> Term getTermValue (Binding r a) = build (refView r) a ----------------------------------------------------------- -- Heterogeneous environment newtype Environment = Env { envMap :: M.Map Id Binding } deriving Eq instance Show Environment where show = intercalate ", " . map show . bindings instance Sem.Semigroup Environment where a <> b = Env (envMap a `mappend` envMap b) -- left has presedence instance Monoid Environment where mempty = Env mempty mappend = (<>) instance HasRefs Environment where allRefs env = [ Some ref | Binding ref _ <- bindings env ] makeEnvironment :: [Binding] -> Environment makeEnvironment xs = Env $ M.fromList [ (getId a, a) | a <- xs ] singleBinding :: Ref a -> a -> Environment singleBinding r = makeEnvironment . return . Binding r class HasEnvironment env where environment :: env -> Environment setEnvironment :: Environment -> env -> env deleteRef :: Ref a -> env -> env insertRef :: Ref a -> a -> env -> env changeRef :: Ref a -> (a -> a) -> env -> env -- default definitions deleteRef a = changeEnv (Env . M.delete (getId a) . envMap) insertRef r = let f b = Env . M.insert (getId b) b . envMap in changeEnv . f . Binding r changeRef r f env = maybe id (insertRef r . f) (r ? env) env -- local helper changeEnv :: HasEnvironment env => (Environment -> Environment) -> env -> env changeEnv f env = setEnvironment (f (environment env)) env class HasRefs a where getRefs :: a -> [Some Ref] allRefs :: a -> [Some Ref] -- with duplicates getRefIds :: a -> [Id] -- default implementation getRefIds a = [ getId r | Some r <- getRefs a] getRefs = sortBy cmp . nubBy eq . allRefs where cmp :: Some Ref -> Some Ref -> Ordering cmp (Some x) (Some y) = compareId (getId x) (getId y) eq a b = cmp a b == EQ instance HasEnvironment Environment where environment = id setEnvironment = const bindings :: HasEnvironment env => env -> [Binding] bindings = sortBy compareId . M.elems . envMap . environment noBindings :: HasEnvironment env => env -> Bool noBindings = M.null . envMap . environment (?) :: HasEnvironment env => Ref a -> env -> Maybe a ref ? env = do let m = envMap (environment env) Binding r a <- M.lookup (getId ref) m msum [ castBetween r ref a -- typed value , castFrom r a >>= parser ref -- value as string , castFrom r a >>= match (refView ref) -- value as term ]
ideas-edu/ideas
src/Ideas/Common/Environment.hs
Haskell
apache-2.0
6,216
sm y = y + 1 biggestInt,smallestInt :: Int biggestInt = maxBound smallestInt = minBound reallyBig::Integer reallyBig = 2^(2^(2^(2^2))) numDigits :: Int numDigits = length(show reallyBig) ex11 = True && False ex12 = not(False || True) ex13 = ('a' == 'a') ex14 = (16 /= 3) ex15 = (5>3) && ('p' <= 'q') ex16 = "Haskell" > "C++" --Pattern matching --Recursive function sumtorial :: Int -> Int sumtorial 0 = 0 sumtorial n = n + sumtorial (n-1) --Using Guards hailstone :: Int -> Int hailstone n | n `mod` 2 == 0 = n `div` 2 | otherwise = 3*n+1 foo :: Int -> Int foo 0 = 16 foo 1 | "Haskell" > "C++" = 3 | otherwise = 4 foo n | n < 0 = 0 | n `mod` 17 == 2 = -43 | otherwise = n + 3 isEven :: Int -> Bool isEven n |n `mod` 2 == 0 = True |otherwise = False p :: (Int, Char) p = (3,'x') sumPair :: (Int,Int) -> Int sumPair (x,y) = x + y f :: Int -> Int -> Int -> Int f x y z = x + y + z ex17 = f 3 17 8 ex18 = 1:[] ex19 = 3 : (1:[]) ex20 = 2 : 3 : 4 : [] ex21 = [2,3,4] == 2 : 3 : 4 : [] hailstoneSeq :: Int -> [Int] hailstoneSeq 1 = [1] hailstoneSeq n = n : hailstoneSeq(hailstone n) intListLength :: [Int] -> Int intListLength [] = 0 intListLength (x:xs) = 1 + intListLength xs --Takes an type of list and returns the length intListLength2 [] = 0 intListLength2 (x:xs) = 1 + intListLength2 xs sumEveryTwo :: [Int] -> [Int] sumEveryTwo [] = [] sumEveryTwo (x:[]) = [x] sumEveryTwo (x:(y:zs)) = (x+y) : sumEveryTwo zs -- The number of hailstone steps needed to reach 1 from a starting -- number. hailstoneLen :: Int -> Int hailstoneLen n = intListLength (hailstoneSeq n) - 1
hungaikev/learning-haskell
cis194/week1/intro.hs
Haskell
apache-2.0
1,695
module HSRT.Test where import HSRT import HSRT.Types import Test.QuickCheck --------------------------------------------------- -- QuickCheck testing --------------------------------------------------- -- Generate random Rays instance Arbitrary Ray where arbitrary = do p1 <- vectorOf 3 (arbitrary::Gen Double) -- A list of 3 random doubles p2 <- vectorOf 3 (arbitrary::Gen Double) -- A different list of 3 random doubles return $ Ray p1 p2 -- The idempotency fails due to floating point precision issues... --prop_normalIdempotency ray = (direction ray) /= [0,0,0] ==> (normalize . normalize) ray == (normalize . normalize . normalize) ray -- Test the length property of normalized rays. That is the length of a normalized ray is always 1. prop_lengthOfNormalizedRay ray = (direction ray) /= [0,0,0] ==> 1-fudgefactor <= _len && _len <= 1+fudgefactor where _len = ((distance [0,0,0]) . direction . normalize) ray fudgefactor = 0.0000000000001 -- Test the dot product of normalized rays, which is always 1 prop_normalizeDot p1 = (direction p1) /= [0,0,0] ==> 1-fudgefactor <= _dot && _dot <= 1+fudgefactor where np1 = normalize p1 _dot = np1 `dot` np1 fudgefactor = 0.0000000000001
brailsmt/hsrt
src/hsrt/test.hs
Haskell
apache-2.0
1,279
module Geometry where import System.Random import qualified Data.Map.Strict as M data Point = Point { pointX :: Int, pointY :: Int } deriving (Eq, Ord) type Angle = Float instance Show Point where show point = "(" ++ (show $ pointX point) ++ "," ++ (show $ pointY point) ++ ")" randomPoint width height = do x <- randomRIO (0, (width-1)) :: IO Int y <- randomRIO (0, (height-1)) :: IO Int return $ Point x y randomDinstinctPoints :: Int -> Int -> Int -> IO [Point] randomDinstinctPoints width height nPoints | (width*height) < nPoints = error "Cannot extract so many distinct points from such a map" | otherwise = randomDistinctPoints' width height nPoints [] randomDistinctPoints' width height 0 points = return points randomDistinctPoints' width height nPoints points = do point <- randomPoint width height if point `elem` points then randomDistinctPoints' width height nPoints points else randomDistinctPoints' width height (nPoints-1) (point:points) toroidalNorth width height point = let y = (pointY point) - 1 in if y < 0 then point { pointY = y + height } else point { pointY = y } toroidalSouth width height point = let y = (pointY point) + 1 in if y >= height then point { pointY = y - height } else point { pointY = y } toroidalEast width height point = let x = (pointX point) + 1 in if x >= width then point { pointY = x - width } else point { pointX = x } toroidalWest width height point = let x = (pointX point) - 1 in if x < 0 then point { pointX = x + width } else point { pointX = x } data WorldDimension = WorldDimension { worldWidth :: Int, worldHeight :: Int } type ElevationMap = M.Map Point Float getElevation :: ElevationMap -> Point -> Float getElevation elevMap point = case M.lookup point elevMap of Nothing -> error $ "Elevation map does not have point " ++ (show point) Just elev -> elev
ftomassetti/hplatetectonics
src/Geometry.hs
Haskell
apache-2.0
2,293
{-# LANGUAGE PackageImports, TypeFamilies, DataKinds, PolyKinds #-} module Propellor.Info ( osDebian, osBuntish, osArchLinux, osFreeBSD, setInfoProperty, addInfoProperty, pureInfoProperty, pureInfoProperty', askInfo, getOS, ipv4, ipv6, alias, addDNS, hostMap, aliasMap, findHost, findHostNoAlias, getAddresses, hostAddresses, ) where import Propellor.Types import Propellor.Types.Info import Propellor.Types.MetaTypes import "mtl" Control.Monad.Reader import qualified Data.Set as S import qualified Data.Map as M import Data.Maybe import Data.Monoid import Control.Applicative import Prelude -- | Adds info to a Property. -- -- The new Property will include HasInfo in its metatypes. setInfoProperty -- -Wredundant-constraints is turned off because -- this constraint appears redundant, but is actually -- crucial. :: (MetaTypes metatypes' ~ (+) HasInfo metatypes, SingI metatypes') => Property metatypes -> Info -> Property (MetaTypes metatypes') setInfoProperty (Property _ d a oldi c) newi = Property sing d a (oldi <> newi) c -- | Adds more info to a Property that already HasInfo. addInfoProperty -- -Wredundant-constraints is turned off because -- this constraint appears redundant, but is actually -- crucial. :: (IncludesInfo metatypes ~ 'True) => Property metatypes -> Info -> Property metatypes addInfoProperty (Property t d a oldi c) newi = Property t d a (oldi <> newi) c -- | Makes a property that does nothing but set some `Info`. pureInfoProperty :: (IsInfo v) => Desc -> v -> Property (HasInfo + UnixLike) pureInfoProperty desc v = pureInfoProperty' desc (toInfo v) pureInfoProperty' :: Desc -> Info -> Property (HasInfo + UnixLike) pureInfoProperty' desc i = setInfoProperty p i where p :: Property UnixLike p = property ("has " ++ desc) (return NoChange) -- | Gets a value from the host's Info. askInfo :: (IsInfo v) => Propellor v askInfo = asks (fromInfo . hostInfo) -- | Specifies that a host's operating system is Debian, -- and further indicates the suite and architecture. -- -- This provides info for other Properties, so they can act -- conditionally on the details of the OS. -- -- It also lets the type checker know that all the properties of the -- host must support Debian. -- -- > & osDebian (Stable "jessie") X86_64 osDebian :: DebianSuite -> Architecture -> Property (HasInfo + Debian) osDebian = osDebian' Linux -- Use to specify a different `DebianKernel` than the default `Linux` -- -- > & osDebian' KFreeBSD (Stable "jessie") X86_64 osDebian' :: DebianKernel -> DebianSuite -> Architecture -> Property (HasInfo + Debian) osDebian' kernel suite arch = tightenTargets $ os (System (Debian kernel suite) arch) -- | Specifies that a host's operating system is a well-known Debian -- derivative founded by a space tourist. -- -- (The actual name of this distribution is not used in Propellor per -- <http://joeyh.name/blog/entry/trademark_nonsense/>) osBuntish :: Release -> Architecture -> Property (HasInfo + Buntish) osBuntish release arch = tightenTargets $ os (System (Buntish release) arch) -- | Specifies that a host's operating system is FreeBSD -- and further indicates the release and architecture. osFreeBSD :: FreeBSDRelease -> Architecture -> Property (HasInfo + FreeBSD) osFreeBSD release arch = tightenTargets $ os (System (FreeBSD release) arch) -- | Specifies that a host's operating system is Arch Linux osArchLinux :: Architecture -> Property (HasInfo + ArchLinux) osArchLinux arch = tightenTargets $ os (System (ArchLinux) arch) os :: System -> Property (HasInfo + UnixLike) os system = pureInfoProperty ("Operating " ++ show system) (InfoVal system) -- Gets the operating system of a host, if it has been specified. getOS :: Propellor (Maybe System) getOS = fromInfoVal <$> askInfo -- | Indicate that a host has an A record in the DNS. -- -- When propellor is used to deploy a DNS server for a domain, -- the hosts in the domain are found by looking for these -- and similar properites. -- -- When propellor --spin is used to deploy a host, it checks -- if the host's IP Property matches the DNS. If the DNS is missing or -- out of date, the host will instead be contacted directly by IP address. ipv4 :: String -> Property (HasInfo + UnixLike) ipv4 = addDNS . Address . IPv4 -- | Indicate that a host has an AAAA record in the DNS. ipv6 :: String -> Property (HasInfo + UnixLike) ipv6 = addDNS . Address . IPv6 -- | Indicates another name for the host in the DNS. -- -- When the host's ipv4/ipv6 addresses are known, the alias is set up -- to use their address, rather than using a CNAME. This avoids various -- problems with CNAMEs, and also means that when multiple hosts have the -- same alias, a DNS round-robin is automatically set up. alias :: Domain -> Property (HasInfo + UnixLike) alias d = pureInfoProperty' ("alias " ++ d) $ mempty `addInfo` toAliasesInfo [d] -- A CNAME is added here, but the DNS setup code converts it to an -- IP address when that makes sense. `addInfo` (toDnsInfo $ S.singleton $ CNAME $ AbsDomain d) addDNS :: Record -> Property (HasInfo + UnixLike) addDNS r = pureInfoProperty (rdesc r) (toDnsInfo (S.singleton r)) where rdesc (CNAME d) = unwords ["alias", ddesc d] rdesc (Address (IPv4 addr)) = unwords ["ipv4", addr] rdesc (Address (IPv6 addr)) = unwords ["ipv6", addr] rdesc (MX n d) = unwords ["MX", show n, ddesc d] rdesc (NS d) = unwords ["NS", ddesc d] rdesc (TXT s) = unwords ["TXT", s] rdesc (SRV x y z d) = unwords ["SRV", show x, show y, show z, ddesc d] rdesc (SSHFP x y s) = unwords ["SSHFP", show x, show y, s] rdesc (INCLUDE f) = unwords ["$INCLUDE", f] rdesc (PTR x) = unwords ["PTR", x] ddesc (AbsDomain domain) = domain ddesc (RelDomain domain) = domain ddesc RootDomain = "@" hostMap :: [Host] -> M.Map HostName Host hostMap l = M.fromList $ zip (map hostName l) l aliasMap :: [Host] -> M.Map HostName Host aliasMap = M.fromList . concat . map (\h -> map (\aka -> (aka, h)) $ fromAliasesInfo $ fromInfo $ hostInfo h) findHost :: [Host] -> HostName -> Maybe Host findHost l hn = (findHostNoAlias l hn) <|> (findAlias l hn) findHostNoAlias :: [Host] -> HostName -> Maybe Host findHostNoAlias l hn = M.lookup hn (hostMap l) findAlias :: [Host] -> HostName -> Maybe Host findAlias l hn = M.lookup hn (aliasMap l) getAddresses :: Info -> [IPAddr] getAddresses = mapMaybe getIPAddr . S.toList . fromDnsInfo . fromInfo hostAddresses :: HostName -> [Host] -> [IPAddr] hostAddresses hn hosts = maybe [] (getAddresses . hostInfo) (findHost hosts hn)
ArchiveTeam/glowing-computing-machine
src/Propellor/Info.hs
Haskell
bsd-2-clause
6,537
module Handler.AdminBlog ( getAdminBlogR , getAdminBlogNewR , postAdminBlogNewR , getAdminBlogPostR , postAdminBlogPostR , postAdminBlogDeleteR ) where import Import import Yesod.Auth import Data.Time import System.Locale (defaultTimeLocale) -- The view showing the list of articles getAdminBlogR :: Handler RepHtml getAdminBlogR = do maid <- maybeAuthId muser <- maybeAuth -- Get the list of articles inside the database articles <- runDB $ selectList [] [Desc ArticleAdded] adminLayout $ do setTitle "Admin: Blog Posts" $(widgetFile "admin/blog") -- The form page for posting a new blog post getAdminBlogNewR :: Handler RepHtml getAdminBlogNewR = do formroute <- return $ AdminBlogNewR marticle <- return $ Nothing adminLayout $ do setTitle "Admin: New Post" $(widgetFile "admin/blogPost") -- Handling the new posted blog post postAdminBlogNewR :: Handler () postAdminBlogNewR = do title <- runInputPost $ ireq textField "form-title-field" mdContent <- runInputPost $ ireq htmlField "form-mdcontent-field" htmlContent <- runInputPost $ ireq htmlField "form-htmlcontent-field" wordCount <- runInputPost $ ireq intField "form-wordcount-field" added <- liftIO getCurrentTime author <- fmap usersEmail maybeAuth _ <- runDB $ insert $ Article title mdContent htmlContent wordCount added author 1 setMessage $ "Post Created" redirect AdminBlogR -- The form page for updating an existing blog post getAdminBlogPostR :: ArticleId -> Handler RepHtml getAdminBlogPostR articleId = do formroute <- return $ AdminBlogPostR articleId dbarticle <- runDB $ get404 articleId marticle <- return $ Just dbarticle adminLayout $ do setTitle "Admin: New Post" $(widgetFile "admin/blogPost") -- Handling the updated blog post postAdminBlogPostR :: ArticleId -> Handler () postAdminBlogPostR articleId = do title <- runInputPost $ ireq textField "form-title-field" mdContent <- runInputPost $ ireq htmlField "form-mdcontent-field" htmlContent <- runInputPost $ ireq htmlField "form-htmlcontent-field" wordCount <- runInputPost $ ireq intField "form-wordcount-field" runDB $ update articleId [ArticleTitle =. title, ArticleMdContent =. mdContent, ArticleHtmlContent =. htmlContent, ArticleWordCount =. wordCount] setMessage $ "Post Update" redirect AdminBlogR -- Handling the updated blog post postAdminBlogDeleteR :: ArticleId -> Handler () postAdminBlogDeleteR articleId = do runDB $ update articleId [ArticleVisible =. 0] setMessage $ "Post Deleted" redirect AdminBlogR
BeerAndProgramming/BeerAndProgrammingSite
Handler/AdminBlog.hs
Haskell
bsd-2-clause
2,678
-- -- Copyright 2014, General Dynamics C4 Systems -- -- This software may be distributed and modified according to the terms of -- the GNU General Public License version 2. Note that NO WARRANTY is provided. -- See "LICENSE_GPLv2.txt" for details. -- -- @TAG(GD_GPL) -- {-# LANGUAGE EmptyDataDecls, ForeignFunctionInterface, GeneralizedNewtypeDeriving #-} module SEL4.Machine.Hardware.ARM.Lyrebird where import SEL4.Machine.RegisterSet import Foreign.Ptr import Data.Ix import Data.Word(Word8) import Data.Bits data CallbackData data IRQ = TimerInterrupt deriving (Enum, Bounded, Ord, Ix, Eq, Show) newtype PAddr = PAddr { fromPAddr :: Word } deriving (Show, Eq, Ord, Bounded, Real, Enum, Integral, Num, Bits) ptrFromPAddr :: PAddr -> PPtr a ptrFromPAddr (PAddr addr) = PPtr addr addrFromPPtr :: PPtr a -> PAddr addrFromPPtr (PPtr ptr) = PAddr ptr pageColourBits :: Int pageColourBits = 0 foreign import ccall "arm_get_mem_top" getMemorySize :: Ptr CallbackData -> IO Int getMemoryRegions :: Ptr CallbackData -> IO [(PAddr, PAddr)] getMemoryRegions env = do size <- getMemorySize env return [(PAddr 0, PAddr (bit size))] getDeviceRegions :: Ptr CallbackData -> IO [(PAddr, PAddr)] getDeviceRegions _ = return [] getKernelDevices :: Ptr CallbackData -> IO [(PAddr, PPtr Word)] getKernelDevices _ = return [] maskInterrupt :: Ptr CallbackData -> Bool -> IRQ -> IO () maskInterrupt env bool _ = maskIRQCallback env bool ackInterrupt :: Ptr CallbackData -> IRQ -> IO () ackInterrupt env _ = ackIRQCallback env foreign import ccall "arm_check_interrupt" getInterruptState :: Ptr CallbackData -> IO Bool foreign import ccall "arm_mask_interrupt" maskIRQCallback :: Ptr CallbackData -> Bool -> IO () foreign import ccall "arm_ack_interrupt" ackIRQCallback :: Ptr CallbackData -> IO () getActiveIRQ :: Ptr CallbackData -> IO (Maybe IRQ) getActiveIRQ env = do timer_irq <- getInterruptState env return $ if timer_irq then Just TimerInterrupt else Nothing configureTimer :: Ptr CallbackData -> IO IRQ configureTimer _ = return TimerInterrupt resetTimer :: Ptr CallbackData -> IO () resetTimer _ = return () foreign import ccall unsafe "arm_load_word" loadWordCallback :: Ptr CallbackData -> PAddr -> IO Word foreign import ccall unsafe "arm_store_word" storeWordCallback :: Ptr CallbackData -> PAddr -> Word -> IO () foreign import ccall unsafe "arm_tlb_flush" invalidateTLBCallback :: Ptr CallbackData -> IO () foreign import ccall unsafe "arm_tlb_flush_asid" invalidateHWASIDCallback :: Ptr CallbackData -> Word8 -> IO () foreign import ccall unsafe "arm_tlb_flush_vptr" invalidateMVACallback :: Ptr CallbackData -> Word -> IO () cacheCleanMVACallback :: Ptr CallbackData -> PPtr a -> IO () cacheCleanMVACallback _cptr _mva = return () cacheCleanRangeCallback :: Ptr CallbackData -> PPtr a -> PPtr a -> IO () cacheCleanRangeCallback _cptr _vbase _vtop = return () cacheCleanCallback :: Ptr CallbackData -> IO () cacheCleanCallback _cptr = return () cacheInvalidateRangeCallback :: Ptr CallbackData -> PPtr a -> PPtr a -> IO () cacheInvalidateRangeCallback _cptr _vbase _vtop = return () foreign import ccall unsafe "arm_set_asid" setHardwareASID :: Ptr CallbackData -> Word8 -> IO () foreign import ccall unsafe "arm_set_table_root" setCurrentPD :: Ptr CallbackData -> PAddr -> IO () foreign import ccall unsafe "arm_get_ifsr" getIFSR :: Ptr CallbackData -> IO Word foreign import ccall unsafe "arm_get_dfsr" getDFSR :: Ptr CallbackData -> IO Word foreign import ccall unsafe "arm_get_far" getFAR :: Ptr CallbackData -> IO VPtr
NICTA/seL4
haskell/src/SEL4/Machine/Hardware/ARM/Lyrebird.hs
Haskell
bsd-2-clause
3,656
module Main (main) where import Test.DocTest (doctest) main :: IO () main = doctest ["-isrc","src/Hangman.hs"]
stackbuilders/hangman-off
tests/DocTests.hs
Haskell
bsd-3-clause
113
import Test.Tasty import qualified Admin import qualified Check main :: IO () main = defaultMain $ testGroup "ghc-server" [ Admin.tests , Check.tests ]
bennofs/ghc-server
tests/Main.hs
Haskell
bsd-3-clause
159
{-# LANGUAGE MultiParamTypeClasses #-} module Test.Framework.Providers.Program( Checker , testProgramRuns , testProgramOutput ) where import Data.Typeable import System.Directory import System.Exit import System.IO hiding (stdout, stderr) import System.Process hiding (runProcess) import Test.Framework.Providers.API -- |A shorthand for a possible function checking an output stream. type Checker = Maybe (String -> Bool) runCheck :: Checker -> String -> Bool runCheck Nothing _ = True runCheck (Just f) x = f x data TestCaseResult = Passed | ProgramFailed ExitCode | Timeout | CheckFailed | NotExecutable data TestCaseRunning = CheckExists | CheckRunnable | Running data TestCase = TestCase Checker Checker FilePath [FilePath] deriving (Typeable) instance Show TestCaseResult where show Passed = "OK" show (ProgramFailed c) = "Program failed: Exit code " ++ show c show Timeout = "Test timed out." show CheckFailed = "Post-run check failed" show NotExecutable = "Program not found / executable." instance Show TestCaseRunning where show CheckExists = "Checking program existence" show CheckRunnable = "Checking program is executable" show Running = "Running" instance TestResultlike TestCaseRunning TestCaseResult where testSucceeded x = case x of Passed -> True _ -> False instance Testlike TestCaseRunning TestCaseResult TestCase where testTypeName _ = "Programs" runTest topts (TestCase outCheck errCheck prog args) = runImprovingIO $ do yieldImprovement CheckExists exists <- liftIO $ doesFileExist prog if exists then do yieldImprovement CheckRunnable perms <- liftIO $ getPermissions prog if executable perms then do yieldImprovement Running runProgram topts outCheck errCheck prog args else return NotExecutable else return NotExecutable runProgram :: TestOptions' K-> Checker -> Checker -> FilePath -> [String] -> ImprovingIO i f TestCaseResult runProgram topts stdoutCheck stderrCheck prog args = do let timeout = unK (topt_timeout topts) mres <- maybeTimeoutImprovingIO timeout $ liftIO $ runProcess prog args case mres of Nothing -> return Timeout Just (ExitSuccess, stdout, stderr) | runCheck stdoutCheck stdout && runCheck stderrCheck stderr -> return Passed | otherwise -> return CheckFailed Just (x, _, _) -> return (ProgramFailed x) runProcess :: FilePath -> [String] -> IO (ExitCode, String, String) runProcess prog args = do (_,o,e,p) <- runInteractiveProcess prog args Nothing Nothing hSetBuffering o NoBuffering hSetBuffering e NoBuffering sout <- hGetContents o serr <- hGetContents e ecode <- length sout `seq` waitForProcess p return (ecode, sout, serr) -- |Test that a given program runs correctly with the given arguments. 'Runs -- correctly' is defined as running and exiting with a successful (0) error -- code. testProgramRuns :: String -> FilePath -> [String] -> Test testProgramRuns name prog args = testProgramOutput name prog args Nothing Nothing -- |Test that a given program runs correctly (exits successfully), and that -- its stdout / stderr are acceptable. testProgramOutput :: String -> FilePath -> [String] -> Checker -> Checker -> Test testProgramOutput name prog args soutCheck serrCheck = Test name (TestCase soutCheck serrCheck prog args)
acw/test-framework-program
Test/Framework/Providers/Program.hs
Haskell
bsd-3-clause
3,747
-- 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. ----------------------------------------------------------------- -- Auto-generated by regenClassifiers -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated ----------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} module Duckling.Ranking.Classifiers.PL (classifiers) where import Prelude import Duckling.Ranking.Types import qualified Data.HashMap.Strict as HashMap import Data.String classifiers :: Classifiers classifiers = HashMap.fromList [("five", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("integer (numeric)", Classifier{okData = ClassData{prior = -0.5997731097824868, unseen = -4.875197323201151, likelihoods = HashMap.fromList [("", 0.0)], n = 129}, koData = ClassData{prior = -0.7961464200320919, unseen = -4.68213122712422, likelihoods = HashMap.fromList [("", 0.0)], n = 106}}), ("exactly <time-of-day>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("<ordinal> (as hour)", -1.3862943611198906), ("<integer> (latent time-of-day)", -1.791759469228055), ("hour", -0.8754687373538999), ("<time-of-day> popo\322udniu/wieczorem/w nocy", -1.791759469228055)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("<cycle> before <time>", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("dayday", -0.6931471805599453), ("day (grain)yesterday", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("Father's Day", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<ordinal> <cycle> <time>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.258096538021482, likelihoods = HashMap.fromList [("daymonth", -2.120263536200091), ("quarteryear", -2.5257286443082556), ("third ordinalday (grain)on <date>", -2.5257286443082556), ("first ordinalweek (grain)named-month", -2.5257286443082556), ("weekmonth", -1.4271163556401458), ("ordinal (digits)quarter (grain)year", -2.5257286443082556), ("first ordinalweek (grain)intersect", -2.120263536200091), ("third ordinalday (grain)named-month", -2.5257286443082556), ("first ordinalweek (grain)on <date>", -2.120263536200091)], n = 8}, koData = ClassData{prior = -infinity, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [], n = 0}}), ("<time> <part-of-day>", Classifier{okData = ClassData{prior = -0.7810085363512795, unseen = -4.948759890378168, likelihoods = HashMap.fromList [("<ordinal> (as hour)after <time-of-day>", -3.5553480614894135), ("dayhour", -2.995732273553991), ("<ordinal> (as hour)evening|night", -2.5437471498109336), ("<ordinal> (as hour)on <date>", -4.248495242049359), ("yesterdayevening|night", -4.248495242049359), ("hourhour", -1.180442306915742), ("after <time-of-day>after <time-of-day>", -3.8430301339411947), ("until <time-of-day>morning", -3.8430301339411947), ("until <time-of-day>after <time-of-day>", -4.248495242049359), ("minutehour", -4.248495242049359), ("named-daymorning", -4.248495242049359), ("todayevening|night", -4.248495242049359), ("at <time-of-day>evening|night", -4.248495242049359), ("named-dayevening|night", -4.248495242049359), ("intersecton <date>", -4.248495242049359), ("<integer> (latent time-of-day)this <part-of-day>", -4.248495242049359), ("hh:mmon <date>", -4.248495242049359), ("<integer> (latent time-of-day)morning", -3.5553480614894135), ("at <time-of-day>on <date>", -4.248495242049359), ("intersectmorning", -3.1498829533812494), ("<integer> (latent time-of-day)evening|night", -2.995732273553991), ("from <datetime> - <datetime> (interval)morning", -4.248495242049359), ("from <time-of-day> - <time-of-day> (interval)morning", -4.248495242049359), ("on <date>morning", -4.248495242049359), ("at <time-of-day>morning", -3.8430301339411947), ("tomorrowevening|night", -3.8430301339411947)], n = 49}, koData = ClassData{prior = -0.6123858239154869, unseen = -5.0689042022202315, likelihoods = HashMap.fromList [("dayhour", -1.971552579668651), ("yearhour", -1.9271008170978172), ("year (latent)on <date>", -4.3694478524670215), ("<day-of-month> (ordinal)on <date>", -4.3694478524670215), ("<time-of-day> - <time-of-day> (interval)morning", -4.3694478524670215), ("<day-of-month> (ordinal)evening|night", -2.6646997602285962), ("by the end of <time>morning", -4.3694478524670215), ("year (latent)evening|night", -3.1166848839716534), ("hourhour", -2.760009940032921), ("after <time-of-day>after <time-of-day>", -3.963982744358857), ("<day-of-month> (ordinal)morning", -3.963982744358857), ("<day-of-month> (ordinal)after <time-of-day>", -3.270835563798912), ("until <time-of-day>morning", -3.4531571205928664), ("until <time-of-day>after <time-of-day>", -4.3694478524670215), ("about <time-of-day>after <time-of-day>", -4.3694478524670215), ("by <time>morning", -4.3694478524670215), ("<integer> (latent time-of-day)after <time-of-day>", -3.963982744358857), ("<integer> (latent time-of-day)morning", -3.676300671907076), ("secondhour", -3.1166848839716534), ("intersectmorning", -3.4531571205928664), ("year (latent)morning", -2.6646997602285962), ("year (latent)after <time-of-day>", -3.963982744358857), ("at <time-of-day>after <time-of-day>", -4.3694478524670215)], n = 58}}), ("today", Classifier{okData = ClassData{prior = -0.2876820724517809, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}, koData = ClassData{prior = -1.3862943611198906, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}}), ("mm/dd", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}, koData = ClassData{prior = -0.6931471805599453, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}}), ("at <time-of-day>", Classifier{okData = ClassData{prior = -0.14571181118139365, unseen = -4.718498871295094, likelihoods = HashMap.fromList [("<ordinal> (as hour)", -1.5740359853831845), ("<integer> (latent time-of-day)", -2.3116349285139637), ("about <time-of-day>", -4.0163830207523885), ("hh:mm", -3.6109179126442243), ("<time-of-day> rano", -2.917770732084279), ("hour", -0.8383291904044432), ("<time-of-day> popo\322udniu/wieczorem/w nocy", -2.2246235515243336), ("minute", -3.100092288878234)], n = 51}, koData = ClassData{prior = -1.9980959022258835, unseen = -3.258096538021482, likelihoods = HashMap.fromList [("<ordinal> (as hour)", -1.8325814637483102), ("<integer> (latent time-of-day)", -1.8325814637483102), ("relative minutes after|past <integer> (hour-of-day)", -2.5257286443082556), ("hour", -1.1394342831883648), ("<time-of-day> popo\322udniu/wieczorem/w nocy", -2.5257286443082556), ("minute", -2.5257286443082556)], n = 8}}), ("absorption of , after named day", Classifier{okData = ClassData{prior = 0.0, unseen = -3.891820298110627, likelihoods = HashMap.fromList [("day", -0.6931471805599453), ("named-day", -0.6931471805599453)], n = 23}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("11th ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("on <date>", Classifier{okData = ClassData{prior = -7.79615414697118e-2, unseen = -4.51085950651685, likelihoods = HashMap.fromList [("week", -2.890371757896165), ("<time> <part-of-day>", -3.8066624897703196), ("intersect", -2.0149030205422647), ("next <cycle>", -3.1135153092103742), ("named-month", -2.1972245773362196), ("half to|till|before <integer> (hour-of-day)", -3.8066624897703196), ("day", -2.70805020110221), ("afternoon", -3.1135153092103742), ("this <cycle>", -2.890371757896165), ("year", -3.1135153092103742), ("named-day", -2.890371757896165), ("hour", -2.3025850929940455), ("month", -1.666596326274049), ("minute", -3.8066624897703196), ("this <time>", -3.8066624897703196)], n = 37}, koData = ClassData{prior = -2.5902671654458267, unseen = -3.1354942159291497, likelihoods = HashMap.fromList [("noon", -1.7047480922384253), ("hour", -1.7047480922384253)], n = 3}}), ("8th ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("month (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("", 0.0)], n = 11}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<time-of-day> o'clock", Classifier{okData = ClassData{prior = -0.3184537311185346, unseen = -2.995732273553991, likelihoods = HashMap.fromList [("<ordinal> (as hour)", -0.8649974374866046), ("<integer> (latent time-of-day)", -2.2512917986064953), ("hour", -0.7472144018302211)], n = 8}, koData = ClassData{prior = -1.2992829841302609, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("<ordinal> (as hour)", -1.5040773967762742), ("<integer> (latent time-of-day)", -1.0986122886681098), ("hour", -0.8109302162163288)], n = 3}}), ("on a named-day", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("day", -0.6931471805599453), ("named-day", -0.6931471805599453)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("nth <time> <time>", Classifier{okData = ClassData{prior = -0.4989911661189879, unseen = -3.951243718581427, likelihoods = HashMap.fromList [("second ordinalnamed-dayintersect", -2.833213344056216), ("first ordinalnamed-dayon <date>", -2.833213344056216), ("daymonth", -1.4469189829363254), ("dayyear", -1.9859154836690123), ("third ordinalnamed-dayintersect", -2.833213344056216), ("third ordinalintersectyear", -2.833213344056216), ("third ordinalnamed-dayon <date>", -3.2386784521643803), ("first ordinalnamed-daynamed-month", -3.2386784521643803), ("first ordinalintersectyear", -2.833213344056216), ("first ordinalnamed-dayintersect", -2.833213344056216), ("second ordinalnamed-dayon <date>", -3.2386784521643803), ("second ordinalintersectyear", -2.833213344056216)], n = 17}, koData = ClassData{prior = -0.9343092373768334, unseen = -3.6888794541139363, likelihoods = HashMap.fromList [("third ordinalnamed-daynamed-month", -2.9704144655697013), ("first ordinalnamed-dayon <date>", -2.9704144655697013), ("daymonth", -1.717651497074333), ("14th ordinalnamed-month<integer> (latent time-of-day)", -2.5649493574615367), ("monthhour", -1.8718021769015913), ("second ordinalnamed-daynamed-month", -2.9704144655697013), ("third ordinalnamed-dayon <date>", -2.9704144655697013), ("first ordinalnamed-daynamed-month", -2.9704144655697013), ("ordinal (digits)named-month<integer> (latent time-of-day)", -2.277267285009756), ("second ordinalnamed-dayon <date>", -2.9704144655697013)], n = 11}}), ("<ordinal> (as hour)", Classifier{okData = ClassData{prior = -0.5773153650348236, unseen = -4.454347296253507, likelihoods = HashMap.fromList [("11th ordinal", -3.056356895370426), ("8th ordinal", -3.3440389678222067), ("21st ordinal no space", -3.7495040759303713), ("20th ordinal", -3.7495040759303713), ("third ordinal", -1.8035939268750578), ("16th ordinal", -3.3440389678222067), ("18th ordinal", -3.3440389678222067), ("fifth ordinal", -3.7495040759303713), ("seventh ordinal", -3.3440389678222067), ("19th ordinal", -3.3440389678222067), ("21-29th ordinal", -3.3440389678222067), ("sixth ordinal", -3.3440389678222067), ("15th ordinal", -3.3440389678222067), ("second ordinal", -2.245426679154097), ("ordinal (digits)", -2.3632097148104805), ("10th ordinal", -2.496741107435003), ("9th ordinal", -2.3632097148104805), ("23rd ordinal no space", -3.7495040759303713)], n = 64}, koData = ClassData{prior = -0.8241754429663495, unseen = -4.276666119016055, likelihoods = HashMap.fromList [("8th ordinal", -3.164067588373206), ("20th ordinal", -3.164067588373206), ("third ordinal", -2.316769727986002), ("14th ordinal", -3.164067588373206), ("13th ordinal", -3.56953269648137), ("15th ordinal", -2.8763855159214247), ("second ordinal", -2.8763855159214247), ("ordinal (digits)", -1.1716374236829996), ("first ordinal", -1.864784604242945)], n = 50}}), ("hour (grain)", Classifier{okData = ClassData{prior = -0.8472978603872037, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("", 0.0)], n = 9}, koData = ClassData{prior = -0.5596157879354228, unseen = -2.639057329615259, likelihoods = HashMap.fromList [("", 0.0)], n = 12}}), ("21st ordinal no space", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<ordinal> quarter", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("quarter", -0.916290731874155), ("third ordinalquarter (grain)", -0.916290731874155)], n = 1}, koData = ClassData{prior = -0.6931471805599453, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("ordinal (digits)quarter (grain)", -0.916290731874155), ("quarter", -0.916290731874155)], n = 1}}), ("intersect", Classifier{okData = ClassData{prior = -0.7319205664859061, unseen = -6.3473892096560105, likelihoods = HashMap.fromList [("<datetime> - <datetime> (interval)on <date>", -5.247024072160486), ("mm/dd<time-of-day> popo\322udniu/wieczorem/w nocy", -5.652489180268651), ("<hour-of-day> - <hour-of-day> (interval)on <date>", -5.247024072160486), ("named-daynamed-month", -4.736198448394496), ("<time-of-day> - <time-of-day> (interval)on <date>", -5.247024072160486), ("hourday", -3.8607297110405954), ("dayhour", -2.790288299339182), ("daymonth", -3.8607297110405954), ("<time-of-day> popo\322udniu/wieczorem/w nocyabsorption of , after named day", -4.736198448394496), ("monthyear", -3.1675825304806504), ("from <hour-of-day> - <hour-of-day> (interval)on a named-day", -5.652489180268651), ("from <time-of-day> - <time-of-day> (interval)on a named-day", -5.652489180268651), ("absorption of , after named dayintersect by \",\" 2", -5.247024072160486), ("intersecthh:mm", -5.247024072160486), ("from <datetime> - <datetime> (interval)on a named-day", -5.652489180268651), ("at <time-of-day>intersect by \",\" 2", -5.247024072160486), ("named-daylast <cycle>", -5.247024072160486), ("named-day<time-of-day> rano", -5.652489180268651), ("on a named-dayat <time-of-day>", -5.247024072160486), ("at <time-of-day>named-day", -5.247024072160486), ("at <time-of-day>on a named-day", -5.652489180268651), ("<time> <part-of-day>on a named-day", -5.247024072160486), ("on a named-day<time> <part-of-day>", -5.652489180268651), ("last <day-of-week> of <time>year", -5.652489180268651), ("today<time> <part-of-day>", -5.652489180268651), ("todayat <time-of-day>", -5.652489180268651), ("on <date>at <time-of-day>", -5.247024072160486), ("dayday", -2.978340530842122), ("on <date><time> <part-of-day>", -5.652489180268651), ("intersect by \",\"hh:mm", -4.399726211773283), ("mm/ddat <time-of-day>", -4.959341999708705), ("last <cycle> <time>year", -4.736198448394496), ("intersect<named-month> <day-of-month> (non ordinal)", -4.959341999708705), ("intersect<day-of-month> (non ordinal) <named-month>", -4.959341999708705), ("dayyear", -3.6375861597263857), ("<day-of-month>(ordinal) <named-month>year", -5.247024072160486), ("day-after-tomorrow (single-word)at <time-of-day>", -5.652489180268651), ("absorption of , after named day<day-of-month>(ordinal) <named-month>", -4.148411783492376), ("tomorrow<time-of-day> popo\322udniu/wieczorem/w nocy", -5.652489180268651), ("named-monthyear", -3.51242301677238), ("absorption of , after named day<named-month> <day-of-month> (non ordinal)", -4.26619481914876), ("tomorrowuntil <time-of-day>", -5.247024072160486), ("absorption of , after named day<day-of-month> (non ordinal) <named-month>", -4.148411783492376), ("<time-of-day> popo\322udniu/wieczorem/w nocyintersect by \",\"", -4.736198448394496), ("named-dayin <duration>", -5.652489180268651), ("last <day-of-week> <time>year", -5.247024072160486), ("<time-of-day> ranoon <date>", -5.247024072160486), ("named-dayfrom <datetime> - <datetime> (interval)", -4.959341999708705), ("named-daynext <cycle>", -4.736198448394496), ("named-dayintersect", -5.247024072160486), ("named-dayfrom <time-of-day> - <time-of-day> (interval)", -4.959341999708705), ("on <date><time-of-day> rano", -5.652489180268651), ("<time-of-day> popo\322udniu/wieczorem/w nocytomorrow", -5.652489180268651), ("from <time-of-day> - <time-of-day> (interval)on <date>", -5.652489180268651), ("at <time-of-day>intersect", -5.247024072160486), ("dayminute", -3.301113923105173), ("intersect by \",\" 2hh:mm", -4.399726211773283), ("<time-of-day> ranoon a named-day", -5.247024072160486), ("from <hour-of-day> - <hour-of-day> (interval)on <date>", -5.652489180268651), ("from <datetime> - <datetime> (interval)on <date>", -5.652489180268651), ("intersectyear", -5.247024072160486), ("on a named-day<time-of-day> rano", -5.652489180268651), ("<ordinal> <cycle> of <time>year", -5.652489180268651), ("minuteday", -2.338303175596125), ("absorption of , after named dayintersect", -5.247024072160486), ("named-dayon <date>", -4.04305126783455), ("named-day<time> <part-of-day>", -4.959341999708705), ("named-dayat <time-of-day>", -5.247024072160486), ("yearhh:mm", -5.652489180268651), ("at <time-of-day>intersect by \",\"", -5.247024072160486), ("absorption of , after named dayintersect by \",\"", -5.247024072160486), ("tomorrowexactly <time-of-day>", -4.959341999708705), ("at <time-of-day>absorption of , after named day", -5.247024072160486), ("at <time-of-day>on <date>", -5.652489180268651), ("on <date>year", -4.26619481914876), ("dayweek", -3.7065790312133373), ("<time> <part-of-day>on <date>", -5.247024072160486), ("weekyear", -4.399726211773283), ("named-day<day-of-month>(ordinal) <named-month>", -4.959341999708705), ("<ordinal> <cycle> <time>year", -5.247024072160486), ("<time-of-day> popo\322udniu/wieczorem/w nocyintersect by \",\" 2", -4.736198448394496), ("tomorrowat <time-of-day>", -5.652489180268651), ("named-daythis <cycle>", -5.247024072160486), ("tomorrow<time> <part-of-day>", -5.652489180268651), ("<time-of-day> popo\322udniu/wieczorem/w nocyintersect", -4.736198448394496), ("<named-month> <day-of-month> (ordinal)year", -5.652489180268651), ("<time-of-day> popo\322udniu/wieczorem/w nocynamed-day", -4.736198448394496), ("tomorrow<time-of-day> rano", -5.652489180268651), ("<datetime> - <datetime> (interval)on a named-day", -5.247024072160486), ("last <cycle> of <time>year", -5.247024072160486), ("<named-month> <day-of-month> (non ordinal)year", -5.652489180268651), ("<time-of-day> - <time-of-day> (interval)on a named-day", -5.247024072160486), ("<day-of-month> (non ordinal) <named-month>year", -5.247024072160486), ("<hour-of-day> - <hour-of-day> (interval)on a named-day", -5.247024072160486), ("yearminute", -5.652489180268651)], n = 215}, koData = ClassData{prior = -0.655821222947259, unseen = -6.405228458030842, likelihoods = HashMap.fromList [("<ordinal> (as hour)<named-month> <day-of-month> (non ordinal)", -4.61181472870676), ("<time-of-day> ranoby <time>", -5.304961909266705), ("intersect by \",\"named-month", -4.206349620598596), ("named-daynamed-month", -5.304961909266705), ("hourday", -2.7926562852905903), ("dayhour", -3.107737331930486), ("daymonth", -3.312531744576499), ("monthday", -5.304961909266705), ("monthyear", -4.794136285500715), ("named-month<hour-of-day> <integer> (as relative minutes)", -5.71042701737487), ("at <time-of-day>intersect by \",\" 2", -5.71042701737487), ("houryear", -3.570360853878599), ("<time> <part-of-day>until <time-of-day>", -5.304961909266705), ("<ordinal> (as hour)intersect", -3.145477659913333), ("monthhour", -4.61181472870676), ("<time> <part-of-day><time> <part-of-day>", -5.017279836814924), ("hourmonth", -2.0860860843985045), ("mm/ddat <time-of-day>", -5.71042701737487), ("hourhour", -4.794136285500715), ("<time> <part-of-day>by <time>", -5.304961909266705), ("intersectnamed-month", -3.4591352187683744), ("dayyear", -4.457664048879502), ("<time-of-day> ranoby the end of <time>", -5.304961909266705), ("year<hour-of-day> <integer> (as relative minutes)", -5.304961909266705), ("intersect by \",\" 2named-month", -4.206349620598596), ("monthminute", -5.304961909266705), ("minutemonth", -5.017279836814924), ("named-monthyear", -4.794136285500715), ("absorption of , after named daynamed-month", -4.324132656254979), ("<time-of-day> popo\322udniu/wieczorem/w nocyintersect by \",\"", -5.304961909266705), ("after <time-of-day>at <time-of-day>", -5.71042701737487), ("hh:mmby the end of <time>", -5.71042701737487), ("<ordinal> (as hour)named-month", -3.036278367948341), ("daysecond", -5.304961909266705), ("<time> <part-of-day>by the end of <time>", -5.304961909266705), ("named-month<ordinal> (as hour)", -4.794136285500715), ("<time> <part-of-day><time-of-day> rano", -5.71042701737487), ("named-dayfrom <datetime> - <datetime> (interval)", -5.71042701737487), ("named-dayintersect", -4.100989104940769), ("named-dayfrom <time-of-day> - <time-of-day> (interval)", -5.71042701737487), ("<time-of-day> rano<time> <part-of-day>", -5.304961909266705), ("at <time-of-day>intersect", -5.71042701737487), ("dayminute", -5.304961909266705), ("<named-month> <day-of-month> (non ordinal)by <time>", -5.71042701737487), ("intersecton <date>", -4.324132656254979), ("intersectyear", -3.312531744576499), ("minuteday", -3.7645168683195562), ("absorption of , after named dayintersect", -4.206349620598596), ("<ordinal> (as hour)year", -5.71042701737487), ("named-dayon <date>", -4.794136285500715), ("hh:mmon <date>", -5.304961909266705), ("absorption of , after named day<ordinal> (as hour)", -4.206349620598596), ("at <time-of-day>intersect by \",\"", -5.71042701737487), ("<named-month> <day-of-month> (non ordinal)by the end of <time>", -5.71042701737487), ("tomorrowexactly <time-of-day>", -5.71042701737487), ("hoursecond", -3.8386248404732783), ("named-month<day-of-month> (non ordinal) <named-month>", -5.304961909266705), ("named-day<ordinal> (as hour)", -5.017279836814924), ("<ordinal> (as hour)named-day", -4.206349620598596), ("named-monthrelative minutes to|till|before <integer> (hour-of-day)", -5.71042701737487), ("<named-month> <day-of-month> (non ordinal)named-month", -5.304961909266705), ("intersectintersect", -4.457664048879502), ("hh:mmon a named-day", -5.304961909266705), ("named-monthintersect", -5.71042701737487), ("<time-of-day> popo\322udniu/wieczorem/w nocyintersect by \",\" 2", -5.304961909266705), ("hh:mmby <time>", -5.71042701737487), ("tomorrowat <time-of-day>", -5.71042701737487), ("minutesecond", -5.304961909266705), ("<time-of-day> popo\322udniu/wieczorem/w nocyintersect", -5.304961909266705), ("yearminute", -5.304961909266705)], n = 232}}), ("half after|past <integer> (hour-of-day)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("<ordinal> (as hour)", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("twenty", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("20th ordinal", Classifier{okData = ClassData{prior = -1.0986122886681098, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -0.40546510810816444, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}}), ("a few", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<ordinal> <cycle> of <time>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("daymonth", -1.7047480922384253), ("first ordinalweek (grain)named-month", -1.7047480922384253), ("weekmonth", -1.2992829841302609), ("first ordinalweek (grain)intersect", -1.7047480922384253), ("third ordinalday (grain)named-month", -1.7047480922384253)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.791759469228055, likelihoods = HashMap.fromList [], n = 0}}), ("season", Classifier{okData = ClassData{prior = -1.0116009116784799, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}, koData = ClassData{prior = -0.45198512374305727, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("", 0.0)], n = 7}}), ("year (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.890371757896165, likelihoods = HashMap.fromList [("", 0.0)], n = 16}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("from <datetime> - <datetime> (interval)", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -2.833213344056216, likelihoods = HashMap.fromList [("minuteminute", -1.6739764335716716), ("<time-of-day> rano<time-of-day> rano", -2.0794415416798357), ("hh:mmhh:mm", -1.6739764335716716), ("hourhour", -1.6739764335716716), ("<time-of-day> rano<integer> (latent time-of-day)", -2.0794415416798357)], n = 4}, koData = ClassData{prior = -0.6931471805599453, unseen = -2.833213344056216, likelihoods = HashMap.fromList [("minuteminute", -1.6739764335716716), ("minutehour", -1.6739764335716716), ("hh:mmintersect", -1.6739764335716716), ("hh:mm<integer> (latent time-of-day)", -1.6739764335716716)], n = 4}}), ("from <hour-of-day> - <hour-of-day> (interval)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("minuteminute", -0.6931471805599453), ("hh:mmhh:mm", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("next <cycle>", Classifier{okData = ClassData{prior = -6.453852113757118e-2, unseen = -3.7612001156935624, likelihoods = HashMap.fromList [("week", -1.540445040947149), ("month (grain)", -3.044522437723423), ("year (grain)", -2.639057329615259), ("second", -3.044522437723423), ("week (grain)", -1.540445040947149), ("quarter", -2.3513752571634776), ("year", -2.639057329615259), ("second (grain)", -3.044522437723423), ("month", -3.044522437723423), ("quarter (grain)", -2.3513752571634776)], n = 15}, koData = ClassData{prior = -2.772588722239781, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("minute (grain)", -1.9459101490553135), ("minute", -1.9459101490553135)], n = 1}}), ("number.number hours", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("from <time-of-day> - <time-of-day> (interval)", Classifier{okData = ClassData{prior = -0.40546510810816444, unseen = -2.772588722239781, likelihoods = HashMap.fromList [("minuteminute", -1.6094379124341003), ("<time-of-day> rano<time-of-day> rano", -2.0149030205422647), ("hh:mmhh:mm", -1.6094379124341003), ("hourhour", -1.6094379124341003), ("<time-of-day> rano<integer> (latent time-of-day)", -2.0149030205422647)], n = 4}, koData = ClassData{prior = -1.0986122886681098, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("minutehour", -1.2992829841302609), ("hh:mm<integer> (latent time-of-day)", -1.2992829841302609)], n = 2}}), ("integer 21..99", Classifier{okData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("integer (numeric)integer (numeric)", 0.0)], n = 1}}), ("yyyy-mm-dd", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("year (latent)", Classifier{okData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -3.295836866004329, likelihoods = HashMap.fromList [("integer (numeric)", -8.004270767353637e-2), ("one", -2.5649493574615367)], n = 24}}), ("mm/dd/yyyy", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("", 0.0)], n = 5}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("evening|night", Classifier{okData = ClassData{prior = 0.0, unseen = -3.1780538303479458, likelihoods = HashMap.fromList [("", 0.0)], n = 22}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("third ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("", 0.0)], n = 19}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("yesterday", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<ordinal> quarter <year>", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("quarteryear", -0.6931471805599453), ("ordinal (digits)quarter (grain)year", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("hh:mm:ss", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("intersect by \",\" 2", Classifier{okData = ClassData{prior = -0.46430560813109784, unseen = -4.74493212836325, likelihoods = HashMap.fromList [("intersect by \",\"year", -4.04305126783455), ("intersect by \",\" 2intersect", -4.04305126783455), ("dayday", -1.4781019103730135), ("named-dayintersect by \",\"", -3.6375861597263857), ("intersect<named-month> <day-of-month> (non ordinal)", -3.349904087274605), ("intersect<day-of-month> (non ordinal) <named-month>", -3.349904087274605), ("dayyear", -2.9444389791664407), ("<named-month> <day-of-month> (non ordinal)intersect", -4.04305126783455), ("named-day<day-of-month> (non ordinal) <named-month>", -2.538973871058276), ("named-day<named-month> <day-of-month> (non ordinal)", -2.6567569067146595), ("intersect by \",\"intersect", -4.04305126783455), ("named-dayintersect", -3.6375861597263857), ("intersect by \",\" 2year", -4.04305126783455), ("named-dayintersect by \",\" 2", -3.6375861597263857), ("dayminute", -2.538973871058276), ("intersectyear", -4.04305126783455), ("minuteday", -2.790288299339182), ("intersectintersect", -4.04305126783455), ("named-day<day-of-month>(ordinal) <named-month>", -2.538973871058276), ("<named-month> <day-of-month> (non ordinal)year", -3.6375861597263857)], n = 44}, koData = ClassData{prior = -0.9903987040278769, unseen = -4.3694478524670215, likelihoods = HashMap.fromList [("named-daynamed-month", -2.277267285009756), ("dayhour", -1.5234954826333758), ("daymonth", -2.277267285009756), ("intersectnamed-month", -2.9704144655697013), ("minutemonth", -2.9704144655697013), ("named-dayintersect", -2.159484249353372), ("named-day<ordinal> (as hour)", -2.159484249353372)], n = 26}}), ("16th ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("quarter to|till|before <integer> (hour-of-day)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("<ordinal> (as hour)", -1.791759469228055), ("<integer> (latent time-of-day)", -1.791759469228055), ("noon", -1.3862943611198906), ("hour", -0.8754687373538999)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("<integer> (latent time-of-day)", Classifier{okData = ClassData{prior = -0.505548566665147, unseen = -3.7376696182833684, likelihoods = HashMap.fromList [("integer (numeric)", -7.598590697792199e-2), ("fifteen", -3.0204248861443626)], n = 38}, koData = ClassData{prior = -0.924258901523332, unseen = -3.367295829986474, likelihoods = HashMap.fromList [("integer (numeric)", -0.15415067982725836), ("one", -2.639057329615259), ("fifteen", -2.639057329615259)], n = 25}}), ("nth <time> of <time>", Classifier{okData = ClassData{prior = -0.5596157879354228, unseen = -2.772588722239781, likelihoods = HashMap.fromList [("second ordinalnamed-dayintersect", -2.0149030205422647), ("daymonth", -1.0986122886681098), ("third ordinalnamed-dayintersect", -2.0149030205422647), ("first ordinalnamed-daynamed-month", -2.0149030205422647), ("first ordinalnamed-dayintersect", -2.0149030205422647)], n = 4}, koData = ClassData{prior = -0.8472978603872037, unseen = -2.639057329615259, likelihoods = HashMap.fromList [("third ordinalnamed-daynamed-month", -1.8718021769015913), ("daymonth", -1.1786549963416462), ("second ordinalnamed-daynamed-month", -1.8718021769015913), ("first ordinalnamed-daynamed-month", -1.8718021769015913)], n = 3}}), ("named-month", Classifier{okData = ClassData{prior = 0.0, unseen = -4.51085950651685, likelihoods = HashMap.fromList [("", 0.0)], n = 89}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("18th ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("week (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -3.784189633918261, likelihoods = HashMap.fromList [("", 0.0)], n = 42}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("fifth ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("valentine's day", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("last <day-of-week> <time>", Classifier{okData = ClassData{prior = -0.15415067982725836, unseen = -2.9444389791664407, likelihoods = HashMap.fromList [("named-daynamed-month", -1.791759469228055), ("daymonth", -0.9444616088408514), ("named-dayintersect", -1.791759469228055), ("named-dayon <date>", -1.791759469228055)], n = 6}, koData = ClassData{prior = -1.9459101490553135, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("named-dayin <duration>", -1.3862943611198906), ("dayminute", -1.3862943611198906)], n = 1}}), ("now", Classifier{okData = ClassData{prior = -0.5108256237659907, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -0.916290731874155, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}}), ("<unit-of-duration> as a duration", Classifier{okData = ClassData{prior = -2.3608540011180215, unseen = -3.8501476017100584, likelihoods = HashMap.fromList [("week", -1.6314168191528755), ("hour (grain)", -2.7300291078209855), ("second", -2.4423470353692043), ("week (grain)", -1.6314168191528755), ("day", -3.1354942159291497), ("minute (grain)", -3.1354942159291497), ("second (grain)", -2.4423470353692043), ("hour", -2.7300291078209855), ("minute", -3.1354942159291497), ("day (grain)", -3.1354942159291497)], n = 15}, koData = ClassData{prior = -9.909090264423089e-2, unseen = -5.720311776607412, likelihoods = HashMap.fromList [("week", -2.161679639916808), ("month (grain)", -3.2321210516182215), ("hour (grain)", -2.7212954278522306), ("year (grain)", -2.8838143573500057), ("second", -2.8838143573500057), ("week (grain)", -2.161679639916808), ("day", -2.498151876538021), ("quarter", -3.5198031240700023), ("minute (grain)", -2.8838143573500057), ("year", -2.8838143573500057), ("second (grain)", -2.8838143573500057), ("hour", -2.7212954278522306), ("month", -3.2321210516182215), ("quarter (grain)", -3.5198031240700023), ("minute", -2.8838143573500057), ("day (grain)", -2.498151876538021)], n = 144}}), ("this <part-of-day>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("on <date>", -1.5040773967762742), ("evening|night", -1.0986122886681098), ("hour", -0.8109302162163288)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("christmas eve", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<day-of-month>(ordinal) <named-month>", Classifier{okData = ClassData{prior = -0.19671029424605427, unseen = -4.007333185232471, likelihoods = HashMap.fromList [("third ordinalnamed-month", -3.295836866004329), ("8th ordinalnamed-month", -2.890371757896165), ("first ordinalnamed-month", -2.890371757896165), ("15th ordinalnamed-month", -2.890371757896165), ("ordinal (digits)named-month", -1.2163953243244932), ("month", -0.8109302162163288), ("13th ordinalnamed-month", -3.295836866004329)], n = 23}, koData = ClassData{prior = -1.7227665977411035, unseen = -2.9444389791664407, likelihoods = HashMap.fromList [("14th ordinalnamed-month", -1.791759469228055), ("ordinal (digits)named-month", -1.5040773967762742), ("month", -1.0986122886681098)], n = 5}}), ("<duration> hence", Classifier{okData = ClassData{prior = -0.40546510810816444, unseen = -3.295836866004329, likelihoods = HashMap.fromList [("week", -1.3121863889661687), ("<unit-of-duration> as a duration", -1.8718021769015913), ("day", -2.159484249353372), ("year", -2.5649493574615367), ("<integer> <unit-of-duration>", -1.1786549963416462), ("month", -2.5649493574615367)], n = 10}, koData = ClassData{prior = -1.0986122886681098, unseen = -2.833213344056216, likelihoods = HashMap.fromList [("week", -2.0794415416798357), ("<unit-of-duration> as a duration", -0.9808292530117262), ("day", -1.6739764335716716), ("year", -2.0794415416798357), ("month", -2.0794415416798357)], n = 5}}), ("numbers prefix with -, negative or minus", Classifier{okData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 11}}), ("new year's eve", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("tomorrow", Classifier{okData = ClassData{prior = -0.2876820724517809, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("", 0.0)], n = 9}, koData = ClassData{prior = -1.3862943611198906, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}}), ("<cycle> after <time>", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("day (grain)tomorrow", -0.6931471805599453), ("dayday", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("Mother's Day", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("half to|till|before <integer> (hour-of-day)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("<ordinal> (as hour)", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("<time> after next", Classifier{okData = ClassData{prior = 0.0, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("named-month", -1.3862943611198906), ("day", -1.3862943611198906), ("named-day", -1.3862943611198906), ("month", -1.3862943611198906)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("two", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("", 0.0)], n = 9}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("by <time>", Classifier{okData = ClassData{prior = -infinity, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -3.58351893845611, likelihoods = HashMap.fromList [("<ordinal> (as hour)", -2.456735772821304), ("year (latent)", -2.8622008809294686), ("<integer> (latent time-of-day)", -1.9459101490553135), ("day", -2.456735772821304), ("year", -2.8622008809294686), ("hh:mm", -2.8622008809294686), ("<day-of-month> (ordinal)", -2.456735772821304), ("noon", -2.8622008809294686), ("<time-of-day> rano", -2.8622008809294686), ("hour", -1.3581234841531944), ("minute", -2.8622008809294686)], n = 12}}), ("seventh ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("half an hour", Classifier{okData = ClassData{prior = -0.2876820724517809, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -1.3862943611198906, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("one", Classifier{okData = ClassData{prior = 0.0, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("afternoon", Classifier{okData = ClassData{prior = -0.5108256237659907, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}, koData = ClassData{prior = -0.916290731874155, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}}), ("<duration> from now", Classifier{okData = ClassData{prior = -0.40546510810816444, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("second", -1.9459101490553135), ("<unit-of-duration> as a duration", -1.540445040947149), ("day", -1.9459101490553135), ("year", -1.9459101490553135), ("<integer> <unit-of-duration>", -1.540445040947149), ("minute", -1.9459101490553135)], n = 4}, koData = ClassData{prior = -1.0986122886681098, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("<unit-of-duration> as a duration", -1.2039728043259361), ("year", -1.6094379124341003), ("minute", -1.6094379124341003)], n = 2}}), ("this <cycle>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.8066624897703196, likelihoods = HashMap.fromList [("week", -1.5869650565820417), ("year (grain)", -1.9924301646902063), ("week (grain)", -1.5869650565820417), ("day", -2.6855773452501515), ("quarter", -2.3978952727983707), ("year", -1.9924301646902063), ("quarter (grain)", -2.3978952727983707), ("day (grain)", -2.6855773452501515)], n = 18}, koData = ClassData{prior = -infinity, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [], n = 0}}), ("minute (grain)", Classifier{okData = ClassData{prior = -0.3483066942682157, unseen = -2.639057329615259, likelihoods = HashMap.fromList [("", 0.0)], n = 12}, koData = ClassData{prior = -1.2237754316221157, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("", 0.0)], n = 5}}), ("last <cycle> <time>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.367295829986474, likelihoods = HashMap.fromList [("daymonth", -1.540445040947149), ("week (grain)named-month", -2.639057329615259), ("day (grain)intersect", -2.2335922215070942), ("day (grain)on <date>", -2.2335922215070942), ("weekmonth", -1.540445040947149), ("day (grain)named-month", -2.639057329615259), ("week (grain)intersect", -2.2335922215070942), ("week (grain)on <date>", -2.2335922215070942)], n = 10}, koData = ClassData{prior = -infinity, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [], n = 0}}), ("about <time-of-day>", Classifier{okData = ClassData{prior = -0.11778303565638351, unseen = -3.1780538303479458, likelihoods = HashMap.fromList [("at <time-of-day>", -2.4423470353692043), ("<ordinal> (as hour)", -1.5260563034950494), ("<integer> (latent time-of-day)", -2.03688192726104), ("hour", -0.9382696385929302), ("<time-of-day> popo\322udniu/wieczorem/w nocy", -2.4423470353692043)], n = 8}, koData = ClassData{prior = -2.1972245773362196, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("relative minutes after|past <integer> (hour-of-day)", -1.5040773967762742), ("minute", -1.5040773967762742)], n = 1}}), ("year", Classifier{okData = ClassData{prior = -0.14842000511827333, unseen = -3.295836866004329, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 25}, koData = ClassData{prior = -1.9810014688665833, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 4}}), ("last <day-of-week> of <time>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("named-daynamed-month", -1.252762968495368), ("daymonth", -0.8472978603872037), ("named-dayintersect", -1.252762968495368)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("<integer> <unit-of-duration>", Classifier{okData = ClassData{prior = -0.7404000654104909, unseen = -4.59511985013459, likelihoods = HashMap.fromList [("week", -2.2823823856765264), ("threemonth (grain)", -3.4863551900024623), ("fifteenminute (grain)", -3.891820298110627), ("a fewhour (grain)", -3.891820298110627), ("integer (numeric)day (grain)", -2.793208009442517), ("twoweek (grain)", -3.891820298110627), ("fiveday (grain)", -3.891820298110627), ("oneweek (grain)", -3.1986731175506815), ("oneminute (grain)", -3.891820298110627), ("integer (numeric)year (grain)", -3.891820298110627), ("day", -2.505525936990736), ("year", -3.1986731175506815), ("integer (numeric)week (grain)", -3.1986731175506815), ("oneday (grain)", -3.891820298110627), ("hour", -3.1986731175506815), ("month", -3.4863551900024623), ("threeweek (grain)", -3.4863551900024623), ("integer (numeric)minute (grain)", -2.793208009442517), ("minute", -2.505525936990736), ("integer (numeric)hour (grain)", -3.4863551900024623), ("twoyear (grain)", -3.4863551900024623)], n = 31}, koData = ClassData{prior = -0.6480267452794757, unseen = -4.653960350157523, likelihoods = HashMap.fromList [("week", -2.8526314299133175), ("threemonth (grain)", -3.951243718581427), ("threehour (grain)", -3.951243718581427), ("integer (numeric)day (grain)", -3.258096538021482), ("twoweek (grain)", -3.951243718581427), ("twominute (grain)", -3.951243718581427), ("second", -2.6984807500860595), ("threeday (grain)", -3.951243718581427), ("threeyear (grain)", -3.951243718581427), ("integer (numeric)second (grain)", -3.0349529867072724), ("twomonth (grain)", -3.951243718581427), ("onehour (grain)", -3.951243718581427), ("integer (numeric)year (grain)", -3.545778610473263), ("threesecond (grain)", -3.951243718581427), ("day", -2.6984807500860595), ("year", -3.0349529867072724), ("threeminute (grain)", -3.951243718581427), ("integer (numeric)week (grain)", -3.258096538021482), ("twoday (grain)", -3.951243718581427), ("hour", -2.6984807500860595), ("month", -3.258096538021482), ("threeweek (grain)", -3.951243718581427), ("integer (numeric)minute (grain)", -3.545778610473263), ("a fewday (grain)", -3.951243718581427), ("integer (numeric)month (grain)", -3.951243718581427), ("minute", -3.0349529867072724), ("twosecond (grain)", -3.951243718581427), ("integer (numeric)hour (grain)", -3.258096538021482), ("fifteenhour (grain)", -3.951243718581427), ("twoyear (grain)", -3.951243718581427)], n = 34}}), ("19th ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("thanksgiving day", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<duration> after <time>", Classifier{okData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("dayday", -0.6931471805599453), ("<unit-of-duration> as a durationtomorrow", -0.6931471805599453)], n = 1}}), ("relative minutes after|past <integer> (hour-of-day)", Classifier{okData = ClassData{prior = -0.5108256237659907, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("integer (numeric)<integer> (latent time-of-day)", -1.7047480922384253), ("fifteen<ordinal> (as hour)", -1.7047480922384253), ("hour", -1.0116009116784799), ("integer (numeric)<ordinal> (as hour)", -1.7047480922384253)], n = 3}, koData = ClassData{prior = -0.916290731874155, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("integer (numeric)noon", -1.0986122886681098), ("hour", -1.0986122886681098)], n = 2}}), ("intersect by \",\"", Classifier{okData = ClassData{prior = -0.46430560813109784, unseen = -4.74493212836325, likelihoods = HashMap.fromList [("intersect by \",\"year", -4.04305126783455), ("intersect by \",\" 2intersect", -4.04305126783455), ("dayday", -1.4781019103730135), ("named-dayintersect by \",\"", -3.6375861597263857), ("intersect<named-month> <day-of-month> (non ordinal)", -3.349904087274605), ("intersect<day-of-month> (non ordinal) <named-month>", -3.349904087274605), ("dayyear", -2.9444389791664407), ("<named-month> <day-of-month> (non ordinal)intersect", -4.04305126783455), ("named-day<day-of-month> (non ordinal) <named-month>", -2.538973871058276), ("named-day<named-month> <day-of-month> (non ordinal)", -2.6567569067146595), ("intersect by \",\"intersect", -4.04305126783455), ("named-dayintersect", -3.6375861597263857), ("intersect by \",\" 2year", -4.04305126783455), ("named-dayintersect by \",\" 2", -3.6375861597263857), ("dayminute", -2.538973871058276), ("intersectyear", -4.04305126783455), ("minuteday", -2.790288299339182), ("intersectintersect", -4.04305126783455), ("named-day<day-of-month>(ordinal) <named-month>", -2.538973871058276), ("<named-month> <day-of-month> (non ordinal)year", -3.6375861597263857)], n = 44}, koData = ClassData{prior = -0.9903987040278769, unseen = -4.3694478524670215, likelihoods = HashMap.fromList [("named-daynamed-month", -2.277267285009756), ("dayhour", -1.5234954826333758), ("daymonth", -2.277267285009756), ("intersectnamed-month", -2.9704144655697013), ("minutemonth", -2.9704144655697013), ("named-dayintersect", -2.159484249353372), ("named-day<ordinal> (as hour)", -2.159484249353372)], n = 26}}), ("hh:mm", Classifier{okData = ClassData{prior = -4.652001563489282e-2, unseen = -3.1354942159291497, likelihoods = HashMap.fromList [("", 0.0)], n = 21}, koData = ClassData{prior = -3.0910424533583156, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("quarter after|past <integer> (hour-of-day)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("<integer> (latent time-of-day)", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("14th ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("21-29th ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("second ordinal", -0.6931471805599453), ("first ordinal", -0.6931471805599453)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("named-day", Classifier{okData = ClassData{prior = 0.0, unseen = -4.584967478670572, likelihoods = HashMap.fromList [("", 0.0)], n = 96}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<duration> before <time>", Classifier{okData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("dayday", -0.6931471805599453), ("<unit-of-duration> as a durationyesterday", -0.6931471805599453)], n = 1}}), ("second (grain)", Classifier{okData = ClassData{prior = -0.9985288301111273, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("", 0.0)], n = 7}, koData = ClassData{prior = -0.4595323293784402, unseen = -2.639057329615259, likelihoods = HashMap.fromList [("", 0.0)], n = 12}}), ("13th ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("intersect by \"of\", \"from\", \"'s\"", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("named-daylast <cycle>", -0.6931471805599453), ("dayweek", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("<duration> ago", Classifier{okData = ClassData{prior = -0.40546510810816444, unseen = -3.295836866004329, likelihoods = HashMap.fromList [("week", -1.3121863889661687), ("<unit-of-duration> as a duration", -1.8718021769015913), ("day", -2.159484249353372), ("year", -2.5649493574615367), ("<integer> <unit-of-duration>", -1.1786549963416462), ("month", -2.5649493574615367)], n = 10}, koData = ClassData{prior = -1.0986122886681098, unseen = -2.833213344056216, likelihoods = HashMap.fromList [("week", -2.0794415416798357), ("<unit-of-duration> as a duration", -0.9808292530117262), ("day", -1.6739764335716716), ("year", -2.0794415416798357), ("month", -2.0794415416798357)], n = 5}}), ("last <time>", Classifier{okData = ClassData{prior = -1.6094379124341003, unseen = -2.833213344056216, likelihoods = HashMap.fromList [("day", -1.1631508098056809), ("named-day", -1.1631508098056809)], n = 4}, koData = ClassData{prior = -0.2231435513142097, unseen = -3.713572066704308, likelihoods = HashMap.fromList [("<time-of-day> o'clock", -2.5902671654458267), ("intersect", -2.3025850929940455), ("year (latent)", -2.0794415416798357), ("<integer> (latent time-of-day)", -2.0794415416798357), ("day", -1.742969305058623), ("year", -2.0794415416798357), ("named-day", -2.3025850929940455), ("hour", -1.742969305058623)], n = 16}}), ("sixth ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<day-of-month> (ordinal)", Classifier{okData = ClassData{prior = -infinity, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -3.367295829986474, likelihoods = HashMap.fromList [("11th ordinal", -2.2335922215070942), ("8th ordinal", -2.639057329615259), ("third ordinal", -2.2335922215070942), ("16th ordinal", -2.639057329615259), ("second ordinal", -1.7227665977411035), ("ordinal (digits)", -2.2335922215070942), ("10th ordinal", -1.7227665977411035), ("9th ordinal", -1.7227665977411035)], n = 20}}), ("noon", Classifier{okData = ClassData{prior = -1.791759469228055, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -0.1823215567939546, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("", 0.0)], n = 10}}), ("until <time-of-day>", Classifier{okData = ClassData{prior = -1.0986122886681098, unseen = -3.6375861597263857, likelihoods = HashMap.fromList [("<time> <part-of-day>", -2.2246235515243336), ("<ordinal> (as hour)", -2.512305623976115), ("<integer> (latent time-of-day)", -2.512305623976115), ("<time-of-day> rano", -2.512305623976115), ("hour", -1.213022639845854), ("<time-of-day> popo\322udniu/wieczorem/w nocy", -2.917770732084279)], n = 10}, koData = ClassData{prior = -0.40546510810816444, unseen = -4.060443010546419, likelihoods = HashMap.fromList [("<time> <part-of-day>", -2.2512917986064953), ("<ordinal> (as hour)", -2.9444389791664407), ("year (latent)", -2.6567569067146595), ("yesterday", -3.349904087274605), ("<integer> (latent time-of-day)", -3.349904087274605), ("day", -2.9444389791664407), ("year", -2.6567569067146595), ("hh:mm", -3.349904087274605), ("<day-of-month> (ordinal)", -3.349904087274605), ("noon", -2.9444389791664407), ("<time-of-day> rano", -3.349904087274605), ("hour", -1.3350010667323402), ("<datetime> - <datetime> (interval)", -3.349904087274605), ("<time-of-day> - <time-of-day> (interval)", -3.349904087274605), ("<hour-of-day> - <hour-of-day> (interval)", -3.349904087274605), ("minute", -3.349904087274605)], n = 20}}), ("<integer> and an half hours", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<time-of-day> rano", Classifier{okData = ClassData{prior = -0.10008345855698253, unseen = -3.828641396489095, likelihoods = HashMap.fromList [("at <time-of-day>", -2.0149030205422647), ("<ordinal> (as hour)", -2.70805020110221), ("<integer> (latent time-of-day)", -1.5040773967762742), ("hh:mm", -3.1135153092103742), ("until <time-of-day>", -2.70805020110221), ("hour", -0.8622235106038793), ("minute", -3.1135153092103742)], n = 19}, koData = ClassData{prior = -2.3513752571634776, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("<integer> (latent time-of-day)", -1.7047480922384253), ("until <time-of-day>", -1.7047480922384253), ("hour", -1.2992829841302609)], n = 2}}), ("after <duration>", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("day", -0.6931471805599453), ("<integer> <unit-of-duration>", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("decimal number", Classifier{okData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("next <time>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.2188758248682006, likelihoods = HashMap.fromList [("named-month", -2.4849066497880004), ("day", -0.8754687373538999), ("named-day", -0.8754687373538999), ("month", -2.4849066497880004)], n = 10}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("last <cycle>", Classifier{okData = ClassData{prior = -0.2876820724517809, unseen = -3.4965075614664802, likelihoods = HashMap.fromList [("week", -1.6739764335716716), ("month (grain)", -1.6739764335716716), ("year (grain)", -2.367123614131617), ("week (grain)", -1.6739764335716716), ("year", -2.367123614131617), ("month", -1.6739764335716716)], n = 12}, koData = ClassData{prior = -1.3862943611198906, unseen = -2.833213344056216, likelihoods = HashMap.fromList [("week", -1.6739764335716716), ("week (grain)", -1.6739764335716716), ("day", -1.6739764335716716), ("day (grain)", -1.6739764335716716)], n = 4}}), ("christmas", Classifier{okData = ClassData{prior = -0.40546510810816444, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -1.0986122886681098, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("next n <cycle>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.912023005428146, likelihoods = HashMap.fromList [("week", -2.793208009442517), ("threemonth (grain)", -3.1986731175506815), ("threehour (grain)", -3.1986731175506815), ("integer (numeric)day (grain)", -3.1986731175506815), ("second", -2.793208009442517), ("threeday (grain)", -3.1986731175506815), ("threeyear (grain)", -3.1986731175506815), ("integer (numeric)second (grain)", -3.1986731175506815), ("integer (numeric)year (grain)", -3.1986731175506815), ("threesecond (grain)", -3.1986731175506815), ("day", -2.505525936990736), ("year", -2.793208009442517), ("threeminute (grain)", -3.1986731175506815), ("integer (numeric)week (grain)", -3.1986731175506815), ("hour", -2.793208009442517), ("month", -3.1986731175506815), ("threeweek (grain)", -3.1986731175506815), ("integer (numeric)minute (grain)", -3.1986731175506815), ("a fewday (grain)", -3.1986731175506815), ("minute", -2.793208009442517), ("integer (numeric)hour (grain)", -3.1986731175506815)], n = 14}, koData = ClassData{prior = -infinity, unseen = -3.0910424533583156, likelihoods = HashMap.fromList [], n = 0}}), ("15th ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("", 0.0)], n = 5}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("halloween day", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("by the end of <time>", Classifier{okData = ClassData{prior = -infinity, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -3.58351893845611, likelihoods = HashMap.fromList [("<ordinal> (as hour)", -2.456735772821304), ("year (latent)", -2.8622008809294686), ("<integer> (latent time-of-day)", -1.9459101490553135), ("day", -2.456735772821304), ("year", -2.8622008809294686), ("hh:mm", -2.8622008809294686), ("<day-of-month> (ordinal)", -2.456735772821304), ("noon", -2.8622008809294686), ("<time-of-day> rano", -2.8622008809294686), ("hour", -1.3581234841531944), ("minute", -2.8622008809294686)], n = 12}}), ("in <duration>", Classifier{okData = ClassData{prior = -0.2231435513142097, unseen = -4.0943445622221, likelihoods = HashMap.fromList [("week", -2.691243082785829), ("number.number hours", -3.3843902633457743), ("second", -2.9789251552376097), ("<unit-of-duration> as a duration", -1.9980959022258835), ("day", -2.9789251552376097), ("half an hour", -3.3843902633457743), ("<integer> <unit-of-duration>", -1.5125880864441827), ("<integer> and an half hours", -3.3843902633457743), ("hour", -2.2857779746776643), ("minute", -1.5125880864441827), ("about <duration>", -2.9789251552376097)], n = 24}, koData = ClassData{prior = -1.6094379124341003, unseen = -3.1780538303479458, likelihoods = HashMap.fromList [("week", -1.749199854809259), ("second", -2.03688192726104), ("<unit-of-duration> as a duration", -1.5260563034950494), ("<integer> <unit-of-duration>", -2.03688192726104), ("minute", -2.4423470353692043)], n = 6}}), ("<datetime> - <datetime> (interval)", Classifier{okData = ClassData{prior = -1.466337068793427, unseen = -3.367295829986474, likelihoods = HashMap.fromList [("minuteminute", -1.7227665977411035), ("hh:mmhh:mm", -1.7227665977411035), ("dayday", -2.2335922215070942), ("<named-month> <day-of-month> (non ordinal)<named-month> <day-of-month> (non ordinal)", -2.2335922215070942)], n = 6}, koData = ClassData{prior = -0.262364264467491, unseen = -4.04305126783455, likelihoods = HashMap.fromList [("daymonth", -2.9267394020670396), ("about <time-of-day>noon", -3.332204510175204), ("minuteminute", -2.2335922215070942), ("<time-of-day> rano<time-of-day> rano", -3.332204510175204), ("until <time-of-day>noon", -3.332204510175204), ("hh:mmhh:mm", -3.332204510175204), ("hourhour", -1.540445040947149), ("year<hour-of-day> <integer> (as relative minutes)", -2.9267394020670396), ("after <time-of-day>noon", -2.9267394020670396), ("hh:mmintersect", -2.4159137783010487), ("at <time-of-day>noon", -3.332204510175204), ("<ordinal> (as hour)noon", -2.2335922215070942), ("<named-month> <day-of-month> (non ordinal)named-month", -2.9267394020670396), ("yearminute", -2.9267394020670396)], n = 20}}), ("second ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("", 0.0)], n = 11}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<time-of-day> popo\322udniu/wieczorem/w nocy", Classifier{okData = ClassData{prior = -1.5037877364540559e-2, unseen = -4.962844630259907, likelihoods = HashMap.fromList [("exactly <time-of-day>", -4.2626798770413155), ("at <time-of-day>", -2.4709204078132605), ("<ordinal> (as hour)", -1.5218398531161146), ("<integer> (latent time-of-day)", -2.01138807843482), ("about <time-of-day>", -4.2626798770413155), ("hh:mm", -3.857214768933151), ("until <time-of-day>", -4.2626798770413155), ("hour", -0.812692331209728), ("minute", -3.3463891451671604), ("after <time-of-day>", -3.857214768933151)], n = 66}, koData = ClassData{prior = -4.204692619390966, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("at <time-of-day>", -1.791759469228055), ("hour", -1.791759469228055)], n = 1}}), ("fifteen", Classifier{okData = ClassData{prior = 0.0, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<time-of-day> - <time-of-day> (interval)", Classifier{okData = ClassData{prior = -1.749199854809259, unseen = -3.0910424533583156, likelihoods = HashMap.fromList [("minuteminute", -1.4350845252893227), ("hh:mmhh:mm", -1.4350845252893227)], n = 4}, koData = ClassData{prior = -0.19105523676270922, unseen = -3.951243718581427, likelihoods = HashMap.fromList [("about <time-of-day>noon", -3.2386784521643803), ("relative minutes to|till|before <integer> (hour-of-day)<integer> (latent time-of-day)", -3.2386784521643803), ("minuteminute", -3.2386784521643803), ("<time-of-day> rano<time-of-day> rano", -3.2386784521643803), ("until <time-of-day>noon", -3.2386784521643803), ("hh:mmhh:mm", -3.2386784521643803), ("hourhour", -1.3668762752627892), ("minutehour", -1.9859154836690123), ("after <time-of-day>noon", -2.833213344056216), ("at <time-of-day>noon", -3.2386784521643803), ("<ordinal> (as hour)noon", -2.1400661634962708), ("<time-of-day> rano<integer> (latent time-of-day)", -3.2386784521643803), ("hh:mm<integer> (latent time-of-day)", -2.1400661634962708)], n = 19}}), ("<hour-of-day> - <hour-of-day> (interval)", Classifier{okData = ClassData{prior = -1.6094379124341003, unseen = -2.995732273553991, likelihoods = HashMap.fromList [("minuteminute", -1.3350010667323402), ("hh:mmhh:mm", -1.3350010667323402)], n = 4}, koData = ClassData{prior = -0.2231435513142097, unseen = -3.784189633918261, likelihoods = HashMap.fromList [("about <time-of-day>noon", -3.068052935133617), ("minuteminute", -3.068052935133617), ("<time-of-day> rano<time-of-day> rano", -3.068052935133617), ("until <time-of-day>noon", -3.068052935133617), ("hh:mmhh:mm", -3.068052935133617), ("hourhour", -0.9886113934537812), ("after <time-of-day>noon", -2.662587827025453), ("at <time-of-day>noon", -3.068052935133617), ("<ordinal> (as hour)noon", -1.9694406464655074), ("<integer> (latent time-of-day)noon", -2.662587827025453), ("<integer> (latent time-of-day)<ordinal> (as hour)", -2.662587827025453)], n = 16}}), ("last n <cycle>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.9889840465642745, likelihoods = HashMap.fromList [("week", -2.583997552432231), ("integer (numeric)day (grain)", -2.871679624884012), ("twoweek (grain)", -3.2771447329921766), ("twominute (grain)", -3.2771447329921766), ("second", -2.871679624884012), ("integer (numeric)second (grain)", -3.2771447329921766), ("twomonth (grain)", -3.2771447329921766), ("onehour (grain)", -3.2771447329921766), ("integer (numeric)year (grain)", -3.2771447329921766), ("day", -2.583997552432231), ("year", -2.871679624884012), ("integer (numeric)week (grain)", -2.871679624884012), ("twoday (grain)", -3.2771447329921766), ("hour", -2.871679624884012), ("month", -2.871679624884012), ("integer (numeric)minute (grain)", -3.2771447329921766), ("integer (numeric)month (grain)", -3.2771447329921766), ("minute", -2.871679624884012), ("twosecond (grain)", -3.2771447329921766), ("integer (numeric)hour (grain)", -3.2771447329921766), ("twoyear (grain)", -3.2771447329921766)], n = 16}, koData = ClassData{prior = -infinity, unseen = -3.0910424533583156, likelihoods = HashMap.fromList [], n = 0}}), ("<named-month> <day-of-month> (non ordinal)", Classifier{okData = ClassData{prior = -0.3364722366212129, unseen = -3.7612001156935624, likelihoods = HashMap.fromList [("named-monthinteger (numeric)", -0.6931471805599453), ("month", -0.6931471805599453)], n = 20}, koData = ClassData{prior = -1.252762968495368, unseen = -2.9444389791664407, likelihoods = HashMap.fromList [("named-monthinteger (numeric)", -0.6931471805599453), ("month", -0.6931471805599453)], n = 8}}), ("<day-of-month> (non ordinal) <named-month>", Classifier{okData = ClassData{prior = -0.1431008436406733, unseen = -3.367295829986474, likelihoods = HashMap.fromList [("integer (numeric)named-month", -0.6931471805599453), ("month", -0.6931471805599453)], n = 13}, koData = ClassData{prior = -2.0149030205422647, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("integer (numeric)named-month", -0.6931471805599453), ("month", -0.6931471805599453)], n = 2}}), ("this|next <day-of-week>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("day", -0.6931471805599453), ("named-day", -0.6931471805599453)], n = 9}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("three", Classifier{okData = ClassData{prior = 0.0, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("", 0.0)], n = 11}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("ordinal (digits)", Classifier{okData = ClassData{prior = 0.0, unseen = -3.4011973816621555, likelihoods = HashMap.fromList [("", 0.0)], n = 28}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("quarter (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("", 0.0)], n = 8}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("last <cycle> of <time>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("daymonth", -1.540445040947149), ("week (grain)named-month", -1.9459101490553135), ("day (grain)intersect", -1.9459101490553135), ("weekmonth", -1.540445040947149), ("day (grain)named-month", -1.9459101490553135), ("week (grain)intersect", -1.9459101490553135)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [], n = 0}}), ("<day-of-month>(ordinal) <named-month> year", Classifier{okData = ClassData{prior = 0.0, unseen = -2.9444389791664407, likelihoods = HashMap.fromList [("14th ordinalnamed-month", -1.791759469228055), ("third ordinalnamed-month", -2.1972245773362196), ("ordinal (digits)named-month", -1.2809338454620642), ("month", -0.8109302162163288)], n = 7}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("morning", Classifier{okData = ClassData{prior = -0.7731898882334817, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}, koData = ClassData{prior = -0.6190392084062235, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("", 0.0)], n = 7}}), ("relative minutes to|till|before <integer> (hour-of-day)", Classifier{okData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("integer (numeric)<integer> (latent time-of-day)", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 2}}), ("week-end", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("10th ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("after <time-of-day>", Classifier{okData = ClassData{prior = -1.4403615823901665, unseen = -3.4657359027997265, likelihoods = HashMap.fromList [("<time> <part-of-day>", -2.3353749158170367), ("<ordinal> (as hour)", -2.3353749158170367), ("afternoon", -2.0476928433652555), ("hour", -1.1314021114911006), ("<time-of-day> popo\322udniu/wieczorem/w nocy", -2.3353749158170367)], n = 9}, koData = ClassData{prior = -0.2702903297399117, unseen = -4.276666119016055, likelihoods = HashMap.fromList [("<time> <part-of-day>", -3.164067588373206), ("<ordinal> (as hour)", -2.8763855159214247), ("intersect", -3.56953269648137), ("tomorrow", -2.653241964607215), ("day", -2.316769727986002), ("afternoon", -2.653241964607215), ("<day-of-month> (ordinal)", -3.164067588373206), ("noon", -2.1832383353614793), ("hour", -1.08462604669337), ("<datetime> - <datetime> (interval)", -3.164067588373206), ("<time-of-day> - <time-of-day> (interval)", -3.164067588373206), ("<hour-of-day> - <hour-of-day> (interval)", -3.164067588373206)], n = 29}}), ("day (grain)", Classifier{okData = ClassData{prior = -0.12783337150988489, unseen = -3.1780538303479458, likelihoods = HashMap.fromList [("", 0.0)], n = 22}, koData = ClassData{prior = -2.120263536200091, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}}), ("9th ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("", 0.0)], n = 7}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("first ordinal", Classifier{okData = ClassData{prior = 0.0, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("", 0.0)], n = 10}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<month> dd-dd (interval)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("named-month", -0.6931471805599453), ("month", -0.6931471805599453)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("about <duration>", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("half an hour", -0.6931471805599453), ("minute", -0.6931471805599453)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("day-after-tomorrow (single-word)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<hour-of-day> <integer> (as relative minutes)", Classifier{okData = ClassData{prior = -1.0986122886681098, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("<ordinal> (as hour)twenty", -1.3862943611198906), ("hour", -0.9808292530117262), ("<ordinal> (as hour)fifteen", -1.3862943611198906)], n = 2}, koData = ClassData{prior = -0.40546510810816444, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("<integer> (latent time-of-day)integer (numeric)", -0.8754687373538999), ("hour", -0.8754687373538999)], n = 4}}), ("23rd ordinal no space", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("this <time>", Classifier{okData = ClassData{prior = -0.6286086594223742, unseen = -3.7612001156935624, likelihoods = HashMap.fromList [("on <date>", -3.044522437723423), ("season", -2.128231705849268), ("evening|night", -3.044522437723423), ("day", -1.252762968495368), ("named-day", -1.6582280766035324), ("hour", -1.9459101490553135), ("week-end", -2.3513752571634776)], n = 16}, koData = ClassData{prior = -0.7621400520468967, unseen = -3.6635616461296463, likelihoods = HashMap.fromList [("on <date>", -2.9444389791664407), ("evening|night", -2.9444389791664407), ("named-month", -1.2396908869280152), ("day", -2.538973871058276), ("hour", -2.538973871058276), ("month", -1.2396908869280152), ("<named-month> <day-of-month> (non ordinal)", -2.538973871058276)], n = 14}}), ("<named-month> <day-of-month> (ordinal)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("named-monthfirst ordinal", -1.791759469228055), ("named-month15th ordinal", -1.791759469228055), ("month", -0.8754687373538999), ("named-monthordinal (digits)", -1.3862943611198906)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("within <duration>", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("week", -0.6931471805599453), ("<integer> <unit-of-duration>", -0.6931471805599453)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}})]
rfranek/duckling
Duckling/Ranking/Classifiers/PL.hs
Haskell
bsd-3-clause
144,652
module TestUtil where import Test.Hspec import Util spec :: Spec spec = it "size2humanSize" $ size2humanSize . fst <$> sizeHumanSizes `shouldBe` snd <$> sizeHumanSizes where sizeHumanSizes = [ ( 0, "0B") , ( 1, "1B") , ( 125, "125B") , ( 999, "999B") , ( 1000, "1.0K") , ( 1023, "1.0K") , ( 1024, "1.0K") , ( 1025, "1.0K") , ( 2048, "2.0K") , ( 8192, "8.0K") , ( 16384, "16.0K") , ( 32768, "32.0K") , ( 65536, "64.0K") , ( 131072, "128.0K") , ( 262144, "256.0K") , ( 524288, "512.0K") , ( 1048575, "1.0M") , ( 1048576, "1.0M") , ( 2097152, "2.0M") , ( 4194304, "4.0M") , (1073741823, "1.0G") , (1073741824, "1.0G") , (1073741825, "1.0G") ]
oshyshko/adventofcode
test/TestUtil.hs
Haskell
bsd-3-clause
1,165
{-# LANGUAGE OverloadedStrings #-} module IptAdmin.EditPolicyForm.Render where import Data.Monoid import Data.String import Iptables.Types import Text.Blaze import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A editPolicyForm :: (String, String) -> Policy -> Markup editPolicyForm (tableName, chainName) policy = do case policy of ACCEPT -> mempty :: Markup DROP -> mempty a -> fromString ("Unsupported policy type: " ++ show a) H.div ! A.class_ "editForm" $ H.form ! A.id "editPolicyForm" ! A.method "post" $ do H.input ! A.type_ "hidden" ! A.name "table" ! A.value (fromString tableName) H.input ! A.type_ "hidden" ! A.name "chain" ! A.value (fromString chainName) H.table $ do H.tr $ H.td $ do let acceptRadio = H.input ! A.type_ "radio" ! A.name "policy" ! A.value "accept" case policy of ACCEPT -> acceptRadio ! A.checked "checked" _ -> acceptRadio "Accept" H.tr $ H.td $ do let dropRadio = H.input ! A.type_ "radio" ! A.name "policy" ! A.value "drop" case policy of DROP -> dropRadio ! A.checked "checked" _ -> dropRadio "Drop"
etarasov/iptadmin
src/IptAdmin/EditPolicyForm/Render.hs
Haskell
bsd-3-clause
1,476
{- OPTIONS_GHC -fplugin Brisk.Plugin #-} {- OPTIONS_GHC -fplugin-opt Brisk.Plugin:main #-} {-# LANGUAGE TemplateHaskell #-} module SpawnSym (main) where import Control.Monad (forM, foldM) import Control.Distributed.Process import Control.Distributed.BriskStatic import Control.Distributed.Process.Closure import Control.Distributed.Process.SymmetricProcess import GHC.Base.Brisk p :: ProcessId -> Process () p who = do self <- getSelfPid expect :: Process () -- return () remotable ['p] ack :: ProcessId -> Process () ack p = send p () broadCast :: SymSet ProcessId -> Process () broadCast pids = do foldM go () pids return () where go _ = ack main :: [NodeId] -> Process () main nodes = do me <- getSelfPid symSet <- spawnSymmetric nodes $ $(mkBriskClosure 'p) me broadCast symSet return ()
abakst/brisk-prelude
examples/SpawnSym.hs
Haskell
bsd-3-clause
902
{-# LANGUAGE OverloadedStrings #-} import Network.NetSpec import Network.NetSpec.Text main :: IO () main = runSpec ServerSpec { _ports = [PortNumber 5001] , _begin = (! "I'll echo anything you say.") , _loop = \[h] () -> receive h >>= \line -> case line of "bye" -> stop_ _ -> h ! line >> continue_ , _end = \h () -> h ! "Bye bye now." }
DanBurton/netspec
examples/Echo.hs
Haskell
bsd-3-clause
368
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Sky.Parsing.Invertible3.PartialType ( PartialType , PartialType' , basicType , fullAlgebraicType , partialAlgebraicType , isOfType -- shortcut "contains" for types --, contains -- re-export from NewContainer , union -- re-export from NewContainer , intersection -- re-export from NewContainer , disjunct -- re-export from NewContainer ) where import Sky.Util.NewContainer import Sky.Util.AllSet import qualified Data.Set import Data.Proxy (Proxy(..)) import Data.Data (Data, Constr, DataType, toConstr, constrType, dataTypeOf, dataTypeName, dataTypeConstrs) -- newtype PartialType a = PartialType (AllSet Data.Set.Set Constr) -- deriving (Show, Eq, Monoid, BaseContainer, Constructible, Collapseable, Intersectable, Container, ContainerMappable) type PartialType a = AllSet Data.Set.Set Constr type PartialType' = AllSet Data.Set.Set Constr instance Ord Constr where -- Required for Data.Set compare a b = compare (dataTypeName $ constrType a) (dataTypeName $ constrType b) `mappend` compare (show a) (show b) -- I don't like using "show" here, but we don't have anything else (it should be "constring") ---------------------------------------------------------------------------------------------------- basicType :: Proxy a -> PartialType a basicType _ = All fullAlgebraicType :: forall a. (Data a) => Proxy a -> PartialType a fullAlgebraicType _ = fromList $ dataTypeConstrs $ dataTypeOf (undefined :: a) partialAlgebraicType :: forall a. (Data a) => a -> PartialType a partialAlgebraicType proxy = singleton $ toConstr proxy isOfType :: forall a. (Data a) => a -> PartialType a -> Bool isOfType value typ = typ `contains` toConstr value -- class Eq t => PartialType t where -- contains :: t -> Constr -> Bool -- disjunct :: t -> t -> Bool -- union :: t -> t -> t ---------------------------------------------------------------------------------------------------- -- data PseudoType a -- = Any -- | Constrs (Set Constr) -- deriving (Show, Eq) -- instance PartialType (PseudoType a) where -- contains :: PseudoType a -> Constr -> Bool -- contains (Any) _ = True -- contains (Constrs set) = -- disjunct :: PseudoType a -> PseudoType a -> Bool -- disjunct
xicesky/sky-haskell-playground
src/Sky/Parsing/Invertible3/PartialType.hs
Haskell
bsd-3-clause
2,503
{-# language CPP #-} -- No documentation found for Chapter "PipelineShaderStageCreateFlagBits" module Vulkan.Core10.Enums.PipelineShaderStageCreateFlagBits ( PipelineShaderStageCreateFlags , PipelineShaderStageCreateFlagBits( PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT , PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT , .. ) ) where import Vulkan.Internal.Utils (enumReadPrec) import Vulkan.Internal.Utils (enumShowsPrec) import GHC.Show (showString) import Numeric (showHex) import Vulkan.Zero (Zero) import Data.Bits (Bits) import Data.Bits (FiniteBits) import Foreign.Storable (Storable) import GHC.Read (Read(readPrec)) import GHC.Show (Show(showsPrec)) import Vulkan.Core10.FundamentalTypes (Flags) type PipelineShaderStageCreateFlags = PipelineShaderStageCreateFlagBits -- | VkPipelineShaderStageCreateFlagBits - Bitmask controlling how a pipeline -- shader stage is created -- -- = Description -- -- Note -- -- If -- 'Vulkan.Extensions.VK_EXT_subgroup_size_control.PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT_EXT' -- and -- 'Vulkan.Extensions.VK_EXT_subgroup_size_control.PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT_EXT' -- are specified and -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#limits-minSubgroupSize minSubgroupSize> -- does not equal -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#limits-maxSubgroupSize maxSubgroupSize> -- and no -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#pipelines-required-subgroup-size required subgroup size> -- is specified, then the only way to guarantee that the \'X\' dimension of -- the local workgroup size is a multiple of -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-sgs SubgroupSize> -- is to make it a multiple of @maxSubgroupSize@. Under these conditions, -- you are guaranteed full subgroups but not any particular subgroup size. -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>, -- 'PipelineShaderStageCreateFlags' newtype PipelineShaderStageCreateFlagBits = PipelineShaderStageCreateFlagBits Flags deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits) -- | 'PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT' specifies that -- the subgroup sizes /must/ be launched with all invocations active in the -- compute stage. pattern PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT = PipelineShaderStageCreateFlagBits 0x00000002 -- | 'PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT' specifies -- that the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-sgs SubgroupSize> -- /may/ vary in the shader stage. pattern PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT = PipelineShaderStageCreateFlagBits 0x00000001 conNamePipelineShaderStageCreateFlagBits :: String conNamePipelineShaderStageCreateFlagBits = "PipelineShaderStageCreateFlagBits" enumPrefixPipelineShaderStageCreateFlagBits :: String enumPrefixPipelineShaderStageCreateFlagBits = "PIPELINE_SHADER_STAGE_CREATE_" showTablePipelineShaderStageCreateFlagBits :: [(PipelineShaderStageCreateFlagBits, String)] showTablePipelineShaderStageCreateFlagBits = [ (PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT , "REQUIRE_FULL_SUBGROUPS_BIT") , (PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT, "ALLOW_VARYING_SUBGROUP_SIZE_BIT") ] instance Show PipelineShaderStageCreateFlagBits where showsPrec = enumShowsPrec enumPrefixPipelineShaderStageCreateFlagBits showTablePipelineShaderStageCreateFlagBits conNamePipelineShaderStageCreateFlagBits (\(PipelineShaderStageCreateFlagBits x) -> x) (\x -> showString "0x" . showHex x) instance Read PipelineShaderStageCreateFlagBits where readPrec = enumReadPrec enumPrefixPipelineShaderStageCreateFlagBits showTablePipelineShaderStageCreateFlagBits conNamePipelineShaderStageCreateFlagBits PipelineShaderStageCreateFlagBits
expipiplus1/vulkan
src/Vulkan/Core10/Enums/PipelineShaderStageCreateFlagBits.hs
Haskell
bsd-3-clause
4,741
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, TypeSynonymInstances #-} -- | Complex Type: @extensionsType@ <http://www.topografix.com/GPX/1/1/#type_extensionsType> module Data.Geo.GPX.Type.Extensions( Extensions , extensions , runExtensions ) where import Text.XML.HXT.Arrow.Pickle import Text.XML.HXT.DOM.TypeDefs import Control.Newtype newtype Extensions = Extensions XmlTrees deriving (Eq, Show) extensions :: XmlTrees -> Extensions extensions = Extensions runExtensions :: Extensions -> XmlTrees runExtensions (Extensions t) = t instance XmlPickler Extensions where xpickle = xpWrap (Extensions, \(Extensions t) -> t) xpTrees instance Newtype Extensions XmlTrees where pack = Extensions unpack (Extensions x) = x
tonymorris/geo-gpx
src/Data/Geo/GPX/Type/Extensions.hs
Haskell
bsd-3-clause
770
{-# LANGUAGE OverloadedStrings #-} module Skywalker.RestServer (RestAPI, restOr, buildRest) where import Data.Text hiding (tail) import Data.ByteString.Lazy hiding (tail) import Network.Wai import Network.HTTP.Types.Status safeHead [] = Nothing safeHead (a:_) = Just a restOr :: Text -> Application -> Application -> Application restOr endPoint restApp backupApp req send_response = do let p = safeHead $ pathInfo req if p == Just endPoint then restApp req send_response else backupApp req send_response type RestAPI = (Text, Request -> IO ByteString) buildRest :: [RestAPI] -> Application buildRest apis req send_response = do let pm = safeHead (tail $ pathInfo req) >>= flip lookup apis case pm of Nothing -> send_response $ responseBuilder status404 [] "invalid API call" Just p -> p req >>= (send_response . responseLBS status200 [])
manyoo/skywalker
src/Skywalker/RestServer.hs
Haskell
bsd-3-clause
897
import Control.Applicative import Control.Monad.Reader import Control.Monad.State import Data.List import Data.Map (Map) import qualified Data.Map as M import System.Directory import System.FilePath import System.Environment import System.Exit import System.IO import AST import CppLexer (lexCpp) import CodeGen import TypeCheck (typecheck) import ScopeCheck (scopecheck) import Grammar (pUnit, pName, runParser, initialParserState) parse path = do input <- readFile path -- We use only the filename so that tests can run in a temporary directory -- but still produce predictable error messages. let res = lexCpp (takeFileName path) input case res of Left err -> do hPutStrLn stderr "Error in lexical analysis:" >> print err exitFailure Right tokens -> case runParser pUnit initialParserState tokens of (Right (res,_),_) -> return res (res,_rest) -> do -- TODO Flags for debug output... --putStrLn "*** Parse left residue (only 10 tokens shown):" --mapM_ print (take 10 rest) --putStrLn "*** Full token stream:" --mapM_ print (map snd tokens) let msg = case res of Left err -> err; _ -> show res hPutStrLn stderr msg exitFailure firstM :: Monad m => (a -> m (Maybe b)) -> [a] -> m (Maybe b) firstM f (x:xs) = do fx <- f x maybe (firstM f xs) (return . Just) fx firstM _ [] = return Nothing nameToPath (QualifiedName components) = joinPath components tryImportModule name path = do let modPath = addExtension (path </> nameToPath name) ".m" --printf "tryImportModule: %s: Trying %s\n" (show name) modPath e <- doesFileExist modPath if e then Just <$> parse modPath else return Nothing defaultIncludePath = ["stdlib", "tests"] type ModMap = Map Name (Unit LocE) type ModT m = ReaderT Options (StateT ModMap m) type Mod = ModT IO runMod :: Options -> ModMap -> Mod a -> IO ModMap runMod opts mods m = execStateT (runReaderT m opts) mods ifNotLoaded name m = gets (M.lookup name) >>= \res -> case res of Just modul -> return modul Nothing -> m >>= \modul -> modul <$ modify (M.insert name modul) processImport :: Name -> Mod (Unit LocE) processImport name = ifNotLoaded name $ do inc <- asks includePath res <- liftIO $ firstM (tryImportModule name) inc case res of Just unit -> do mapM_ processImport (unitImports unit) return unit Nothing -> error ("Error: Can't locate module "++show name) parseName name = case lexCpp "cmd-line" name of Left err -> hPutStrLn stderr "Error: Can't lex name:" >> print err >> exitFailure Right tokens -> case fst (runParser pName () tokens) of Left err -> hPutStrLn stderr "Error: Can't parse name:" >> print err >> exitFailure Right (name,_) -> return name data Options = Options { includePath :: [FilePath], outputPath :: FilePath } defaultOptions = Options { includePath = defaultIncludePath , outputPath = "out" } parseArgs :: [String] -> (Options, [String]) parseArgs args = (opts, mods) where opts = foldr addOption defaultOptions optargs addOption ('-':'I':path) opts = opts { includePath = path : includePath opts } addOption ('-':'o':path) opts = opts { outputPath = path } (optargs,mods) = partition ((== '-').head) args main = do (opts,mods) <- parseArgs <$> getArgs mapM_ (doMain opts <=< parseName) mods doMain opts name = do mods <- runMod opts M.empty (processImport name) process opts name mods mapMapM f m = M.fromList <$> mapM (secondM f) (M.toList m) where secondM f (a,b) = f b >>= \b' -> return (a,b') process :: Options -> Name -> ModMap -> IO () process opts name mods'' = do mods' <- mapMapM scopecheck mods'' mods <- runReaderT (typecheck name) mods' let outfile = outputPath opts </> encodeName name ++ ".ll" --mapM_ print (M.toList mods) runReaderT (printLLVM outfile name) mods
olsner/m3
Main.hs
Haskell
bsd-3-clause
3,898
module Cipher where import Data.Char import Data.List letterIndex :: Char -> Int letterIndex = (+ (-(ord 'a'))) . ord . toLower offsettedChar :: Int -> Char -> Char offsettedChar offset c = toOriginalCharCase . chr . (+ firstLetterOrd) . (`mod` numLetters) . (+ offset) . (+ (-firstLetterOrd)) . ord . toLower $ c where toOriginalCharCase = if isUpper c then toUpper else id firstLetterOrd = ord 'a' numLetters = (ord 'z' - firstLetterOrd) + 1 cipherCaesar :: String -> Int -> String cipherCaesar s offset = map (offsettedChar offset) s unCipherCaesar :: String -> Int -> String unCipherCaesar s offset = cipherCaesar s (-offset) cipherVignere :: String -> String -> String cipherVignere s password = result where (result, pass) = foldl' cipherCharWithNextPassChar ("", cycle password) s where cipherCharWithNextPassChar (result, pass) ' ' = (result ++ " ", pass) cipherCharWithNextPassChar (result, pass) c = (result ++ [offsettedChar (letterIndex . head $ pass) c], tail pass) unCipherVignere :: String -> String -> String unCipherVignere s password = result where (result, pass) = foldl' unCipherCharWithNextPassChar ("", cycle password) s where unCipherCharWithNextPassChar (result, pass) ' ' = (result ++ " ", pass) unCipherCharWithNextPassChar (result, pass) c = (result ++ [offsettedChar (-(letterIndex . head $ pass)) c], tail pass) cipherUserInput :: (String -> String) -> IO() cipherUserInput cipherFunc = do putStrLn "Type a message:" userInput <- getLine putStrLn $ "Ciphered message: " ++ cipherFunc userInput cipherCaesarUserInput :: IO() cipherCaesarUserInput = cipherUserInput (`cipherCaesar` 1) cipherVignereUserInput :: IO() cipherVignereUserInput = cipherUserInput (`cipherVignere` "password")
abhean/phffp-examples
src/Cipher.hs
Haskell
bsd-3-clause
1,795
{-# LANGUAGE ScopedTypeVariables #-} module Main where import Control.Concurrent (ThreadId, forkIO, myThreadId) import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar, readMVar) import qualified Control.Exception as E import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as C import Network.Socket hiding (recv, recvFrom, send, sendTo) import Network.Socket.ByteString import Test.Framework (Test, defaultMain, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (Assertion, (@=?)) ------------------------------------------------------------------------ serverAddr :: String serverAddr = "127.0.0.1" testMsg :: S.ByteString testMsg = C.pack "This is a test message." ------------------------------------------------------------------------ -- Tests ------------------------------------------------------------------------ -- Sending and receiving testSend :: Assertion testSend = tcpTest client server where server sock = recv sock 1024 >>= (@=?) testMsg client sock = send sock testMsg testSendAll :: Assertion testSendAll = tcpTest client server where server sock = recv sock 1024 >>= (@=?) testMsg client sock = sendAll sock testMsg testSendTo :: Assertion testSendTo = udpTest client server where server sock = recv sock 1024 >>= (@=?) testMsg client sock serverPort = do addr <- inet_addr serverAddr sendTo sock testMsg (SockAddrInet serverPort addr) testSendAllTo :: Assertion testSendAllTo = udpTest client server where server sock = recv sock 1024 >>= (@=?) testMsg client sock serverPort = do addr <- inet_addr serverAddr sendAllTo sock testMsg (SockAddrInet serverPort addr) testSendMany :: Assertion testSendMany = tcpTest client server where server sock = recv sock 1024 >>= (@=?) (S.append seg1 seg2) client sock = sendMany sock [seg1, seg2] seg1 = C.pack "This is a " seg2 = C.pack "test message." testSendManyTo :: Assertion testSendManyTo = udpTest client server where server sock = recv sock 1024 >>= (@=?) (S.append seg1 seg2) client sock serverPort = do addr <- inet_addr serverAddr sendManyTo sock [seg1, seg2] (SockAddrInet serverPort addr) seg1 = C.pack "This is a " seg2 = C.pack "test message." testRecv :: Assertion testRecv = tcpTest client server where server sock = recv sock 1024 >>= (@=?) testMsg client sock = send sock testMsg testOverFlowRecv :: Assertion testOverFlowRecv = tcpTest client server where server sock = do seg1 <- recv sock (S.length testMsg - 3) seg2 <- recv sock 1024 let msg = S.append seg1 seg2 testMsg @=? msg client sock = send sock testMsg testRecvFrom :: Assertion testRecvFrom = tcpTest client server where server sock = do (msg, _) <- recvFrom sock 1024 testMsg @=? msg client sock = do serverPort <- getPeerPort sock addr <- inet_addr serverAddr sendTo sock testMsg (SockAddrInet serverPort addr) testOverFlowRecvFrom :: Assertion testOverFlowRecvFrom = tcpTest client server where server sock = do (seg1, _) <- recvFrom sock (S.length testMsg - 3) (seg2, _) <- recvFrom sock 1024 let msg = S.append seg1 seg2 testMsg @=? msg client sock = send sock testMsg ------------------------------------------------------------------------ -- Other ------------------------------------------------------------------------ -- List of all tests basicTests :: Test basicTests = testGroup "Basic socket operations" [ -- Sending and receiving testCase "testSend" testSend , testCase "testSendAll" testSendAll , testCase "testSendTo" testSendTo , testCase "testSendAllTo" testSendAllTo , testCase "testSendMany" testSendMany , testCase "testSendManyTo" testSendManyTo , testCase "testRecv" testRecv , testCase "testOverFlowRecv" testOverFlowRecv , testCase "testRecvFrom" testRecvFrom , testCase "testOverFlowRecvFrom" testOverFlowRecvFrom ] tests :: [Test] tests = [basicTests] ------------------------------------------------------------------------ -- Test helpers -- | Returns the 'PortNumber' of the peer. Will throw an 'error' if -- used on a non-IP socket. getPeerPort :: Socket -> IO PortNumber getPeerPort sock = do sockAddr <- getPeerName sock case sockAddr of (SockAddrInet port _) -> return port (SockAddrInet6 port _ _ _) -> return port _ -> error "getPeerPort: only works with IP sockets" -- | Establish a connection between client and server and then run -- 'clientAct' and 'serverAct', in different threads. Both actions -- get passed a connected 'Socket', used for communicating between -- client and server. 'tcpTest' makes sure that the 'Socket' is -- closed after the actions have run. tcpTest :: (Socket -> IO a) -> (Socket -> IO b) -> IO () tcpTest clientAct serverAct = do portVar <- newEmptyMVar test (clientSetup portVar) clientAct (serverSetup portVar) server where clientSetup portVar = do sock <- socket AF_INET Stream defaultProtocol addr <- inet_addr serverAddr serverPort <- readMVar portVar connect sock $ SockAddrInet serverPort addr return sock serverSetup portVar = do sock <- socket AF_INET Stream defaultProtocol setSocketOption sock ReuseAddr 1 addr <- inet_addr serverAddr bindSocket sock (SockAddrInet aNY_PORT addr) listen sock 1 serverPort <- socketPort sock putMVar portVar serverPort return sock server sock = do (clientSock, _) <- accept sock serverAct clientSock sClose clientSock -- | Create an unconnected 'Socket' for sending UDP and receiving -- datagrams and then run 'clientAct' and 'serverAct'. udpTest :: (Socket -> PortNumber -> IO a) -> (Socket -> IO b) -> IO () udpTest clientAct serverAct = do portVar <- newEmptyMVar test clientSetup (client portVar) (serverSetup portVar) serverAct where clientSetup = socket AF_INET Datagram defaultProtocol client portVar sock = do serverPort <- readMVar portVar clientAct sock serverPort serverSetup portVar = do sock <- socket AF_INET Datagram defaultProtocol setSocketOption sock ReuseAddr 1 addr <- inet_addr serverAddr bindSocket sock (SockAddrInet aNY_PORT addr) serverPort <- socketPort sock putMVar portVar serverPort return sock -- | Run a client/server pair and synchronize them so that the server -- is started before the client and the specified server action is -- finished before the client closes the 'Socket'. test :: IO Socket -> (Socket -> IO b) -> IO Socket -> (Socket -> IO c) -> IO () test clientSetup clientAct serverSetup serverAct = do tid <- myThreadId barrier <- newEmptyMVar forkIO $ server barrier client tid barrier where server barrier = do E.bracket serverSetup sClose $ \sock -> do serverReady serverAct sock putMVar barrier () where -- | Signal to the client that it can proceed. serverReady = putMVar barrier () client tid barrier = do takeMVar barrier -- Transfer exceptions to the main thread. bracketWithReraise tid clientSetup sClose $ \res -> do clientAct res takeMVar barrier -- | Like 'bracket' but catches and reraises the exception in another -- thread, specified by the first argument. bracketWithReraise :: ThreadId -> IO a -> (a -> IO b) -> (a -> IO ()) -> IO () bracketWithReraise tid before after thing = E.bracket before after thing `E.catch` \ (e :: E.SomeException) -> E.throwTo tid e ------------------------------------------------------------------------ -- Test harness main :: IO () main = withSocketsDo $ defaultMain tests
jspahrsummers/network
tests/Simple.hs
Haskell
bsd-3-clause
8,034
module Zero.Bitfinex.Internal ( Ticker(..) , defaultTicker ) where import GHC.Generics (Generic) import Data.Aeson import Data.Text (Text) ------------------------------------------------------------------------------ -- ------------------------------------------------------------------------------ data Ticker = Ticker { t_mid :: Text , t_bid :: Text , t_ask :: Text , t_lastPrice :: Text , t_low :: Text , t_high :: Text , t_volume :: Text , t_timestamp :: Text } deriving (Show, Generic) defaultTicker = Ticker "0.0" "0.0" "0.0" "0.0" "0.0" "0.0" "0.0" "TIMESTAMP" instance FromJSON Ticker where parseJSON = withObject "Ticker" $ \v -> Ticker <$> v .: "mid" <*> v .: "bid" <*> v .: "ask" <*> v .: "last_price" <*> v .: "low" <*> v .: "high" <*> v .: "volume" <*> v .: "timestamp" instance ToJSON Ticker where toJSON (Ticker a1 a2 a3 a4 a5 a6 a7 a8) = object [ "mid" .= a1 , "bid" .= a2 , "ask" .= a3 , "last_price" .= a4 , "low" .= a5 , "high" .= a6 , "volume" .= a7 , "timestamp" .= a8 ]
et4te/zero
src-shared/Zero/Bitfinex/Internal.hs
Haskell
bsd-3-clause
1,140
module Opticover.Geometry.Calc.Box where import Control.Lens import Data.AEq import Opticover.Geometry.Types import Opticover.Ple pointInBox :: Box -> Point -> Bool pointInBox (Box pair) p = let (p1, p2) = unPair pair in p1 <= p && p <= p2 -- Hoping derived Ord instance do what we expect here segmentBorderBox :: Segment -> Box segmentBorderBox (Segment pair) = Box pair
s9gf4ult/opticover
src/Opticover/Geometry/Calc/Box.hs
Haskell
bsd-3-clause
381
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.PackageDescription.Parse -- Copyright : Isaac Jones 2003-2005 -- License : BSD3 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This defined parsers and partial pretty printers for the @.cabal@ format. -- Some of the complexity in this module is due to the fact that we have to be -- backwards compatible with old @.cabal@ files, so there's code to translate -- into the newer structure. module Distribution.PackageDescription.Parse ( -- * Package descriptions readPackageDescription, writePackageDescription, parsePackageDescription, showPackageDescription, -- ** Parsing ParseResult(..), FieldDescr(..), LineNo, -- ** Supplementary build information readHookedBuildInfo, parseHookedBuildInfo, writeHookedBuildInfo, showHookedBuildInfo, pkgDescrFieldDescrs, libFieldDescrs, executableFieldDescrs, binfoFieldDescrs, sourceRepoFieldDescrs, testSuiteFieldDescrs, flagFieldDescrs ) where import Data.Char (isSpace) import Data.Maybe (listToMaybe, isJust) #if __GLASGOW_HASKELL__ < 710 import Data.Monoid ( Monoid(..) ) #endif import Data.List (nub, unfoldr, partition, (\\)) import Control.Monad (liftM, foldM, when, unless, ap) #if __GLASGOW_HASKELL__ < 710 import Control.Applicative (Applicative(..)) #endif import Control.Arrow (first) import System.Directory (doesFileExist) import qualified Data.ByteString.Lazy.Char8 as BS.Char8 import Data.Typeable import Data.Data import qualified Data.Map as Map import Distribution.Text ( Text(disp, parse), display, simpleParse ) import Distribution.Compat.ReadP ((+++), option) import qualified Distribution.Compat.ReadP as Parse import Text.PrettyPrint import Distribution.ParseUtils hiding (parseFields) import Distribution.PackageDescription import Distribution.PackageDescription.Utils ( cabalBug, userBug ) import Distribution.Package ( PackageIdentifier(..), Dependency(..), packageName, packageVersion ) import Distribution.ModuleName ( ModuleName ) import Distribution.Version ( Version(Version), orLaterVersion , LowerBound(..), asVersionIntervals ) import Distribution.Verbosity (Verbosity) import Distribution.Compiler (CompilerFlavor(..)) import Distribution.PackageDescription.Configuration (parseCondition, freeVars) import Distribution.Simple.Utils ( die, dieWithLocation, warn, intercalate, lowercase, cabalVersion , withFileContents, withUTF8FileContents , writeFileAtomic, writeUTF8File ) -- ----------------------------------------------------------------------------- -- The PackageDescription type pkgDescrFieldDescrs :: [FieldDescr PackageDescription] pkgDescrFieldDescrs = [ simpleField "name" disp parse packageName (\name pkg -> pkg{package=(package pkg){pkgName=name}}) , simpleField "version" disp parse packageVersion (\ver pkg -> pkg{package=(package pkg){pkgVersion=ver}}) , simpleField "cabal-version" (either disp disp) (liftM Left parse +++ liftM Right parse) specVersionRaw (\v pkg -> pkg{specVersionRaw=v}) , simpleField "build-type" (maybe empty disp) (fmap Just parse) buildType (\t pkg -> pkg{buildType=t}) , simpleField "license" disp parseLicenseQ license (\l pkg -> pkg{license=l}) -- We have both 'license-file' and 'license-files' fields. -- Rather than declaring license-file to be deprecated, we will continue -- to allow both. The 'license-file' will continue to only allow single -- tokens, while 'license-files' allows multiple. On pretty-printing, we -- will use 'license-file' if there's just one, and use 'license-files' -- otherwise. , simpleField "license-file" showFilePath parseFilePathQ (\pkg -> case licenseFiles pkg of [x] -> x _ -> "") (\l pkg -> pkg{licenseFiles=licenseFiles pkg ++ [l]}) , listField "license-files" showFilePath parseFilePathQ (\pkg -> case licenseFiles pkg of [_] -> [] xs -> xs) (\ls pkg -> pkg{licenseFiles=ls}) , simpleField "copyright" showFreeText parseFreeText copyright (\val pkg -> pkg{copyright=val}) , simpleField "maintainer" showFreeText parseFreeText maintainer (\val pkg -> pkg{maintainer=val}) , simpleField "stability" showFreeText parseFreeText stability (\val pkg -> pkg{stability=val}) , simpleField "homepage" showFreeText parseFreeText homepage (\val pkg -> pkg{homepage=val}) , simpleField "package-url" showFreeText parseFreeText pkgUrl (\val pkg -> pkg{pkgUrl=val}) , simpleField "bug-reports" showFreeText parseFreeText bugReports (\val pkg -> pkg{bugReports=val}) , simpleField "synopsis" showFreeText parseFreeText synopsis (\val pkg -> pkg{synopsis=val}) , simpleField "description" showFreeText parseFreeText description (\val pkg -> pkg{description=val}) , simpleField "category" showFreeText parseFreeText category (\val pkg -> pkg{category=val}) , simpleField "author" showFreeText parseFreeText author (\val pkg -> pkg{author=val}) , listField "tested-with" showTestedWith parseTestedWithQ testedWith (\val pkg -> pkg{testedWith=val}) , listFieldWithSep vcat "data-files" showFilePath parseFilePathQ dataFiles (\val pkg -> pkg{dataFiles=val}) , simpleField "data-dir" showFilePath parseFilePathQ dataDir (\val pkg -> pkg{dataDir=val}) , listFieldWithSep vcat "extra-source-files" showFilePath parseFilePathQ extraSrcFiles (\val pkg -> pkg{extraSrcFiles=val}) , listFieldWithSep vcat "extra-tmp-files" showFilePath parseFilePathQ extraTmpFiles (\val pkg -> pkg{extraTmpFiles=val}) , listFieldWithSep vcat "extra-doc-files" showFilePath parseFilePathQ extraDocFiles (\val pkg -> pkg{extraDocFiles=val}) ] -- | Store any fields beginning with "x-" in the customFields field of -- a PackageDescription. All other fields will generate a warning. storeXFieldsPD :: UnrecFieldParser PackageDescription storeXFieldsPD (f@('x':'-':_),val) pkg = Just pkg{ customFieldsPD = customFieldsPD pkg ++ [(f,val)]} storeXFieldsPD _ _ = Nothing -- --------------------------------------------------------------------------- -- The Library type libFieldDescrs :: [FieldDescr Library] libFieldDescrs = [ listFieldWithSep vcat "exposed-modules" disp parseModuleNameQ exposedModules (\mods lib -> lib{exposedModules=mods}) , commaListFieldWithSep vcat "reexported-modules" disp parse reexportedModules (\mods lib -> lib{reexportedModules=mods}) , listFieldWithSep vcat "required-signatures" disp parseModuleNameQ requiredSignatures (\mods lib -> lib{requiredSignatures=mods}) , listFieldWithSep vcat "exposed-signatures" disp parseModuleNameQ exposedSignatures (\mods lib -> lib{exposedSignatures=mods}) , boolField "exposed" libExposed (\val lib -> lib{libExposed=val}) ] ++ map biToLib binfoFieldDescrs where biToLib = liftField libBuildInfo (\bi lib -> lib{libBuildInfo=bi}) storeXFieldsLib :: UnrecFieldParser Library storeXFieldsLib (f@('x':'-':_), val) l@(Library { libBuildInfo = bi }) = Just $ l {libBuildInfo = bi{ customFieldsBI = customFieldsBI bi ++ [(f,val)]}} storeXFieldsLib _ _ = Nothing -- --------------------------------------------------------------------------- -- The Executable type executableFieldDescrs :: [FieldDescr Executable] executableFieldDescrs = [ -- note ordering: configuration must come first, for -- showPackageDescription. simpleField "executable" showToken parseTokenQ exeName (\xs exe -> exe{exeName=xs}) , simpleField "main-is" showFilePath parseFilePathQ modulePath (\xs exe -> exe{modulePath=xs}) ] ++ map biToExe binfoFieldDescrs where biToExe = liftField buildInfo (\bi exe -> exe{buildInfo=bi}) storeXFieldsExe :: UnrecFieldParser Executable storeXFieldsExe (f@('x':'-':_), val) e@(Executable { buildInfo = bi }) = Just $ e {buildInfo = bi{ customFieldsBI = (f,val):customFieldsBI bi}} storeXFieldsExe _ _ = Nothing -- --------------------------------------------------------------------------- -- The TestSuite type -- | An intermediate type just used for parsing the test-suite stanza. -- After validation it is converted into the proper 'TestSuite' type. data TestSuiteStanza = TestSuiteStanza { testStanzaTestType :: Maybe TestType, testStanzaMainIs :: Maybe FilePath, testStanzaTestModule :: Maybe ModuleName, testStanzaBuildInfo :: BuildInfo } emptyTestStanza :: TestSuiteStanza emptyTestStanza = TestSuiteStanza Nothing Nothing Nothing mempty testSuiteFieldDescrs :: [FieldDescr TestSuiteStanza] testSuiteFieldDescrs = [ simpleField "type" (maybe empty disp) (fmap Just parse) testStanzaTestType (\x suite -> suite { testStanzaTestType = x }) , simpleField "main-is" (maybe empty showFilePath) (fmap Just parseFilePathQ) testStanzaMainIs (\x suite -> suite { testStanzaMainIs = x }) , simpleField "test-module" (maybe empty disp) (fmap Just parseModuleNameQ) testStanzaTestModule (\x suite -> suite { testStanzaTestModule = x }) ] ++ map biToTest binfoFieldDescrs where biToTest = liftField testStanzaBuildInfo (\bi suite -> suite { testStanzaBuildInfo = bi }) storeXFieldsTest :: UnrecFieldParser TestSuiteStanza storeXFieldsTest (f@('x':'-':_), val) t@(TestSuiteStanza { testStanzaBuildInfo = bi }) = Just $ t {testStanzaBuildInfo = bi{ customFieldsBI = (f,val):customFieldsBI bi}} storeXFieldsTest _ _ = Nothing validateTestSuite :: LineNo -> TestSuiteStanza -> ParseResult TestSuite validateTestSuite line stanza = case testStanzaTestType stanza of Nothing -> return $ emptyTestSuite { testBuildInfo = testStanzaBuildInfo stanza } Just tt@(TestTypeUnknown _ _) -> return emptyTestSuite { testInterface = TestSuiteUnsupported tt, testBuildInfo = testStanzaBuildInfo stanza } Just tt | tt `notElem` knownTestTypes -> return emptyTestSuite { testInterface = TestSuiteUnsupported tt, testBuildInfo = testStanzaBuildInfo stanza } Just tt@(TestTypeExe ver) -> case testStanzaMainIs stanza of Nothing -> syntaxError line (missingField "main-is" tt) Just file -> do when (isJust (testStanzaTestModule stanza)) $ warning (extraField "test-module" tt) return emptyTestSuite { testInterface = TestSuiteExeV10 ver file, testBuildInfo = testStanzaBuildInfo stanza } Just tt@(TestTypeLib ver) -> case testStanzaTestModule stanza of Nothing -> syntaxError line (missingField "test-module" tt) Just module_ -> do when (isJust (testStanzaMainIs stanza)) $ warning (extraField "main-is" tt) return emptyTestSuite { testInterface = TestSuiteLibV09 ver module_, testBuildInfo = testStanzaBuildInfo stanza } where missingField name tt = "The '" ++ name ++ "' field is required for the " ++ display tt ++ " test suite type." extraField name tt = "The '" ++ name ++ "' field is not used for the '" ++ display tt ++ "' test suite type." -- --------------------------------------------------------------------------- -- The Benchmark type -- | An intermediate type just used for parsing the benchmark stanza. -- After validation it is converted into the proper 'Benchmark' type. data BenchmarkStanza = BenchmarkStanza { benchmarkStanzaBenchmarkType :: Maybe BenchmarkType, benchmarkStanzaMainIs :: Maybe FilePath, benchmarkStanzaBenchmarkModule :: Maybe ModuleName, benchmarkStanzaBuildInfo :: BuildInfo } emptyBenchmarkStanza :: BenchmarkStanza emptyBenchmarkStanza = BenchmarkStanza Nothing Nothing Nothing mempty benchmarkFieldDescrs :: [FieldDescr BenchmarkStanza] benchmarkFieldDescrs = [ simpleField "type" (maybe empty disp) (fmap Just parse) benchmarkStanzaBenchmarkType (\x suite -> suite { benchmarkStanzaBenchmarkType = x }) , simpleField "main-is" (maybe empty showFilePath) (fmap Just parseFilePathQ) benchmarkStanzaMainIs (\x suite -> suite { benchmarkStanzaMainIs = x }) ] ++ map biToBenchmark binfoFieldDescrs where biToBenchmark = liftField benchmarkStanzaBuildInfo (\bi suite -> suite { benchmarkStanzaBuildInfo = bi }) storeXFieldsBenchmark :: UnrecFieldParser BenchmarkStanza storeXFieldsBenchmark (f@('x':'-':_), val) t@(BenchmarkStanza { benchmarkStanzaBuildInfo = bi }) = Just $ t {benchmarkStanzaBuildInfo = bi{ customFieldsBI = (f,val):customFieldsBI bi}} storeXFieldsBenchmark _ _ = Nothing validateBenchmark :: LineNo -> BenchmarkStanza -> ParseResult Benchmark validateBenchmark line stanza = case benchmarkStanzaBenchmarkType stanza of Nothing -> return $ emptyBenchmark { benchmarkBuildInfo = benchmarkStanzaBuildInfo stanza } Just tt@(BenchmarkTypeUnknown _ _) -> return emptyBenchmark { benchmarkInterface = BenchmarkUnsupported tt, benchmarkBuildInfo = benchmarkStanzaBuildInfo stanza } Just tt | tt `notElem` knownBenchmarkTypes -> return emptyBenchmark { benchmarkInterface = BenchmarkUnsupported tt, benchmarkBuildInfo = benchmarkStanzaBuildInfo stanza } Just tt@(BenchmarkTypeExe ver) -> case benchmarkStanzaMainIs stanza of Nothing -> syntaxError line (missingField "main-is" tt) Just file -> do when (isJust (benchmarkStanzaBenchmarkModule stanza)) $ warning (extraField "benchmark-module" tt) return emptyBenchmark { benchmarkInterface = BenchmarkExeV10 ver file, benchmarkBuildInfo = benchmarkStanzaBuildInfo stanza } where missingField name tt = "The '" ++ name ++ "' field is required for the " ++ display tt ++ " benchmark type." extraField name tt = "The '" ++ name ++ "' field is not used for the '" ++ display tt ++ "' benchmark type." -- --------------------------------------------------------------------------- -- The BuildInfo type binfoFieldDescrs :: [FieldDescr BuildInfo] binfoFieldDescrs = [ boolField "buildable" buildable (\val binfo -> binfo{buildable=val}) , commaListField "build-tools" disp parseBuildTool buildTools (\xs binfo -> binfo{buildTools=xs}) , commaListFieldWithSep vcat "build-depends" disp parse buildDependsWithRenaming setBuildDependsWithRenaming , spaceListField "cpp-options" showToken parseTokenQ' cppOptions (\val binfo -> binfo{cppOptions=val}) , spaceListField "cc-options" showToken parseTokenQ' ccOptions (\val binfo -> binfo{ccOptions=val}) , spaceListField "ld-options" showToken parseTokenQ' ldOptions (\val binfo -> binfo{ldOptions=val}) , commaListField "pkgconfig-depends" disp parsePkgconfigDependency pkgconfigDepends (\xs binfo -> binfo{pkgconfigDepends=xs}) , listField "frameworks" showToken parseTokenQ frameworks (\val binfo -> binfo{frameworks=val}) , listFieldWithSep vcat "c-sources" showFilePath parseFilePathQ cSources (\paths binfo -> binfo{cSources=paths}) , listFieldWithSep vcat "js-sources" showFilePath parseFilePathQ jsSources (\paths binfo -> binfo{jsSources=paths}) , simpleField "default-language" (maybe empty disp) (option Nothing (fmap Just parseLanguageQ)) defaultLanguage (\lang binfo -> binfo{defaultLanguage=lang}) , listField "other-languages" disp parseLanguageQ otherLanguages (\langs binfo -> binfo{otherLanguages=langs}) , listField "default-extensions" disp parseExtensionQ defaultExtensions (\exts binfo -> binfo{defaultExtensions=exts}) , listField "other-extensions" disp parseExtensionQ otherExtensions (\exts binfo -> binfo{otherExtensions=exts}) , listField "extensions" disp parseExtensionQ oldExtensions (\exts binfo -> binfo{oldExtensions=exts}) , listFieldWithSep vcat "extra-libraries" showToken parseTokenQ extraLibs (\xs binfo -> binfo{extraLibs=xs}) , listFieldWithSep vcat "extra-ghci-libraries" showToken parseTokenQ extraGHCiLibs (\xs binfo -> binfo{extraGHCiLibs=xs}) , listField "extra-lib-dirs" showFilePath parseFilePathQ extraLibDirs (\xs binfo -> binfo{extraLibDirs=xs}) , listFieldWithSep vcat "includes" showFilePath parseFilePathQ includes (\paths binfo -> binfo{includes=paths}) , listFieldWithSep vcat "install-includes" showFilePath parseFilePathQ installIncludes (\paths binfo -> binfo{installIncludes=paths}) , listField "include-dirs" showFilePath parseFilePathQ includeDirs (\paths binfo -> binfo{includeDirs=paths}) , listField "hs-source-dirs" showFilePath parseFilePathQ hsSourceDirs (\paths binfo -> binfo{hsSourceDirs=paths}) , listFieldWithSep vcat "other-modules" disp parseModuleNameQ otherModules (\val binfo -> binfo{otherModules=val}) , optsField "ghc-prof-options" GHC profOptions (\val binfo -> binfo{profOptions=val}) , optsField "ghcjs-prof-options" GHCJS profOptions (\val binfo -> binfo{profOptions=val}) , optsField "ghc-shared-options" GHC sharedOptions (\val binfo -> binfo{sharedOptions=val}) , optsField "ghcjs-shared-options" GHCJS sharedOptions (\val binfo -> binfo{sharedOptions=val}) , optsField "ghc-options" GHC options (\path binfo -> binfo{options=path}) , optsField "ghcjs-options" GHCJS options (\path binfo -> binfo{options=path}) , optsField "jhc-options" JHC options (\path binfo -> binfo{options=path}) -- NOTE: Hugs and NHC are not supported anymore, but these fields are kept -- around for backwards compatibility. , optsField "hugs-options" Hugs options (const id) , optsField "nhc98-options" NHC options (const id) ] storeXFieldsBI :: UnrecFieldParser BuildInfo storeXFieldsBI (f@('x':'-':_),val) bi = Just bi{ customFieldsBI = (f,val):customFieldsBI bi } storeXFieldsBI _ _ = Nothing ------------------------------------------------------------------------------ flagFieldDescrs :: [FieldDescr Flag] flagFieldDescrs = [ simpleField "description" showFreeText parseFreeText flagDescription (\val fl -> fl{ flagDescription = val }) , boolField "default" flagDefault (\val fl -> fl{ flagDefault = val }) , boolField "manual" flagManual (\val fl -> fl{ flagManual = val }) ] ------------------------------------------------------------------------------ sourceRepoFieldDescrs :: [FieldDescr SourceRepo] sourceRepoFieldDescrs = [ simpleField "type" (maybe empty disp) (fmap Just parse) repoType (\val repo -> repo { repoType = val }) , simpleField "location" (maybe empty showFreeText) (fmap Just parseFreeText) repoLocation (\val repo -> repo { repoLocation = val }) , simpleField "module" (maybe empty showToken) (fmap Just parseTokenQ) repoModule (\val repo -> repo { repoModule = val }) , simpleField "branch" (maybe empty showToken) (fmap Just parseTokenQ) repoBranch (\val repo -> repo { repoBranch = val }) , simpleField "tag" (maybe empty showToken) (fmap Just parseTokenQ) repoTag (\val repo -> repo { repoTag = val }) , simpleField "subdir" (maybe empty showFilePath) (fmap Just parseFilePathQ) repoSubdir (\val repo -> repo { repoSubdir = val }) ] -- --------------------------------------------------------------- -- Parsing -- | Given a parser and a filename, return the parse of the file, -- after checking if the file exists. readAndParseFile :: (FilePath -> (String -> IO a) -> IO a) -> (String -> ParseResult a) -> Verbosity -> FilePath -> IO a readAndParseFile withFileContents' parser verbosity fpath = do exists <- doesFileExist fpath unless exists (die $ "Error Parsing: file \"" ++ fpath ++ "\" doesn't exist. Cannot continue.") withFileContents' fpath $ \str -> case parser str of ParseFailed e -> do let (line, message) = locatedErrorMsg e dieWithLocation fpath line message ParseOk warnings x -> do mapM_ (warn verbosity . showPWarning fpath) $ reverse warnings return x readHookedBuildInfo :: Verbosity -> FilePath -> IO HookedBuildInfo readHookedBuildInfo = readAndParseFile withFileContents parseHookedBuildInfo -- |Parse the given package file. readPackageDescription :: Verbosity -> FilePath -> IO GenericPackageDescription readPackageDescription = readAndParseFile withUTF8FileContents parsePackageDescription stanzas :: [Field] -> [[Field]] stanzas [] = [] stanzas (f:fields) = (f:this) : stanzas rest where (this, rest) = break isStanzaHeader fields isStanzaHeader :: Field -> Bool isStanzaHeader (F _ f _) = f == "executable" isStanzaHeader _ = False ------------------------------------------------------------------------------ mapSimpleFields :: (Field -> ParseResult Field) -> [Field] -> ParseResult [Field] mapSimpleFields f = mapM walk where walk fld@F{} = f fld walk (IfBlock l c fs1 fs2) = do fs1' <- mapM walk fs1 fs2' <- mapM walk fs2 return (IfBlock l c fs1' fs2') walk (Section ln n l fs1) = do fs1' <- mapM walk fs1 return (Section ln n l fs1') -- prop_isMapM fs = mapSimpleFields return fs == return fs -- names of fields that represents dependencies, thus consrca constraintFieldNames :: [String] constraintFieldNames = ["build-depends"] -- Possible refactoring would be to have modifiers be explicit about what -- they add and define an accessor that specifies what the dependencies -- are. This way we would completely reuse the parsing knowledge from the -- field descriptor. parseConstraint :: Field -> ParseResult [DependencyWithRenaming] parseConstraint (F l n v) | n == "build-depends" = runP l n (parseCommaList parse) v parseConstraint f = userBug $ "Constraint was expected (got: " ++ show f ++ ")" {- headerFieldNames :: [String] headerFieldNames = filter (\n -> not (n `elem` constraintFieldNames)) . map fieldName $ pkgDescrFieldDescrs -} libFieldNames :: [String] libFieldNames = map fieldName libFieldDescrs ++ buildInfoNames ++ constraintFieldNames -- exeFieldNames :: [String] -- exeFieldNames = map fieldName executableFieldDescrs -- ++ buildInfoNames buildInfoNames :: [String] buildInfoNames = map fieldName binfoFieldDescrs ++ map fst deprecatedFieldsBuildInfo -- A minimal implementation of the StateT monad transformer to avoid depending -- on the 'mtl' package. newtype StT s m a = StT { runStT :: s -> m (a,s) } instance Functor f => Functor (StT s f) where fmap g (StT f) = StT $ fmap (first g) . f instance (Monad m, Functor m) => Applicative (StT s m) where pure = return (<*>) = ap instance Monad m => Monad (StT s m) where return a = StT (\s -> return (a,s)) StT f >>= g = StT $ \s -> do (a,s') <- f s runStT (g a) s' get :: Monad m => StT s m s get = StT $ \s -> return (s, s) modify :: Monad m => (s -> s) -> StT s m () modify f = StT $ \s -> return ((),f s) lift :: Monad m => m a -> StT s m a lift m = StT $ \s -> m >>= \a -> return (a,s) evalStT :: Monad m => StT s m a -> s -> m a evalStT st s = liftM fst $ runStT st s -- Our monad for parsing a list/tree of fields. -- -- The state represents the remaining fields to be processed. type PM a = StT [Field] ParseResult a -- return look-ahead field or nothing if we're at the end of the file peekField :: PM (Maybe Field) peekField = liftM listToMaybe get -- Unconditionally discard the first field in our state. Will error when it -- reaches end of file. (Yes, that's evil.) skipField :: PM () skipField = modify tail --FIXME: this should take a ByteString, not a String. We have to be able to -- decode UTF8 and handle the BOM. -- | Parses the given file into a 'GenericPackageDescription'. -- -- In Cabal 1.2 the syntax for package descriptions was changed to a format -- with sections and possibly indented property descriptions. parsePackageDescription :: String -> ParseResult GenericPackageDescription parsePackageDescription file = do -- This function is quite complex because it needs to be able to parse -- both pre-Cabal-1.2 and post-Cabal-1.2 files. Additionally, it contains -- a lot of parser-related noise since we do not want to depend on Parsec. -- -- If we detect an pre-1.2 file we implicitly convert it to post-1.2 -- style. See 'sectionizeFields' below for details about the conversion. fields0 <- readFields file `catchParseError` \err -> let tabs = findIndentTabs file in case err of -- In case of a TabsError report them all at once. TabsError tabLineNo -> reportTabsError -- but only report the ones including and following -- the one that caused the actual error [ t | t@(lineNo',_) <- tabs , lineNo' >= tabLineNo ] _ -> parseFail err let cabalVersionNeeded = head $ [ minVersionBound versionRange | Just versionRange <- [ simpleParse v | F _ "cabal-version" v <- fields0 ] ] ++ [Version [0] []] minVersionBound versionRange = case asVersionIntervals versionRange of [] -> Version [0] [] ((LowerBound version _, _):_) -> version handleFutureVersionParseFailure cabalVersionNeeded $ do let sf = sectionizeFields fields0 -- ensure 1.2 format -- figure out and warn about deprecated stuff (warnings are collected -- inside our parsing monad) fields <- mapSimpleFields deprecField sf -- Our parsing monad takes the not-yet-parsed fields as its state. -- After each successful parse we remove the field from the state -- ('skipField') and move on to the next one. -- -- Things are complicated a bit, because fields take a tree-like -- structure -- they can be sections or "if"/"else" conditionals. flip evalStT fields $ do -- The header consists of all simple fields up to the first section -- (flag, library, executable). header_fields <- getHeader [] -- Parses just the header fields and stores them in a -- 'PackageDescription'. Note that our final result is a -- 'GenericPackageDescription'; for pragmatic reasons we just store -- the partially filled-out 'PackageDescription' inside the -- 'GenericPackageDescription'. pkg <- lift $ parseFields pkgDescrFieldDescrs storeXFieldsPD emptyPackageDescription header_fields -- 'getBody' assumes that the remaining fields only consist of -- flags, lib and exe sections. (repos, flags, mlib, exes, tests, bms) <- getBody warnIfRest -- warn if getBody did not parse up to the last field. -- warn about using old/new syntax with wrong cabal-version: maybeWarnCabalVersion (not $ oldSyntax fields0) pkg checkForUndefinedFlags flags mlib exes tests return $ GenericPackageDescription pkg { sourceRepos = repos } flags mlib exes tests bms where oldSyntax = all isSimpleField reportTabsError tabs = syntaxError (fst (head tabs)) $ "Do not use tabs for indentation (use spaces instead)\n" ++ " Tabs were used at (line,column): " ++ show tabs maybeWarnCabalVersion newsyntax pkg | newsyntax && specVersion pkg < Version [1,2] [] = lift $ warning $ "A package using section syntax must specify at least\n" ++ "'cabal-version: >= 1.2'." maybeWarnCabalVersion newsyntax pkg | not newsyntax && specVersion pkg >= Version [1,2] [] = lift $ warning $ "A package using 'cabal-version: " ++ displaySpecVersion (specVersionRaw pkg) ++ "' must use section syntax. See the Cabal user guide for details." where displaySpecVersion (Left version) = display version displaySpecVersion (Right versionRange) = case asVersionIntervals versionRange of [] {- impossible -} -> display versionRange ((LowerBound version _, _):_) -> display (orLaterVersion version) maybeWarnCabalVersion _ _ = return () handleFutureVersionParseFailure cabalVersionNeeded parseBody = (unless versionOk (warning message) >> parseBody) `catchParseError` \parseError -> case parseError of TabsError _ -> parseFail parseError _ | versionOk -> parseFail parseError | otherwise -> fail message where versionOk = cabalVersionNeeded <= cabalVersion message = "This package requires at least Cabal version " ++ display cabalVersionNeeded -- "Sectionize" an old-style Cabal file. A sectionized file has: -- -- * all global fields at the beginning, followed by -- -- * all flag declarations, followed by -- -- * an optional library section, and an arbitrary number of executable -- sections (in any order). -- -- The current implementation just gathers all library-specific fields -- in a library section and wraps all executable stanzas in an executable -- section. sectionizeFields :: [Field] -> [Field] sectionizeFields fs | oldSyntax fs = let -- "build-depends" is a local field now. To be backwards -- compatible, we still allow it as a global field in old-style -- package description files and translate it to a local field by -- adding it to every non-empty section (hdr0, exes0) = break ((=="executable") . fName) fs (hdr, libfs0) = partition (not . (`elem` libFieldNames) . fName) hdr0 (deps, libfs) = partition ((== "build-depends") . fName) libfs0 exes = unfoldr toExe exes0 toExe [] = Nothing toExe (F l e n : r) | e == "executable" = let (efs, r') = break ((=="executable") . fName) r in Just (Section l "executable" n (deps ++ efs), r') toExe _ = cabalBug "unexpected input to 'toExe'" in hdr ++ (if null libfs then [] else [Section (lineNo (head libfs)) "library" "" (deps ++ libfs)]) ++ exes | otherwise = fs isSimpleField F{} = True isSimpleField _ = False -- warn if there's something at the end of the file warnIfRest :: PM () warnIfRest = do s <- get case s of [] -> return () _ -> lift $ warning "Ignoring trailing declarations." -- add line no. -- all simple fields at the beginning of the file are (considered) header -- fields getHeader :: [Field] -> PM [Field] getHeader acc = peekField >>= \mf -> case mf of Just f@F{} -> skipField >> getHeader (f:acc) _ -> return (reverse acc) -- -- body ::= { repo | flag | library | executable | test }+ -- at most one lib -- -- The body consists of an optional sequence of declarations of flags and -- an arbitrary number of executables and at most one library. getBody :: PM ([SourceRepo], [Flag] ,Maybe (CondTree ConfVar [Dependency] Library) ,[(String, CondTree ConfVar [Dependency] Executable)] ,[(String, CondTree ConfVar [Dependency] TestSuite)] ,[(String, CondTree ConfVar [Dependency] Benchmark)]) getBody = peekField >>= \mf -> case mf of Just (Section line_no sec_type sec_label sec_fields) | sec_type == "executable" -> do when (null sec_label) $ lift $ syntaxError line_no "'executable' needs one argument (the executable's name)" exename <- lift $ runP line_no "executable" parseTokenQ sec_label flds <- collectFields parseExeFields sec_fields skipField (repos, flags, lib, exes, tests, bms) <- getBody return (repos, flags, lib, (exename, flds): exes, tests, bms) | sec_type == "test-suite" -> do when (null sec_label) $ lift $ syntaxError line_no "'test-suite' needs one argument (the test suite's name)" testname <- lift $ runP line_no "test" parseTokenQ sec_label flds <- collectFields (parseTestFields line_no) sec_fields -- Check that a valid test suite type has been chosen. A type -- field may be given inside a conditional block, so we must -- check for that before complaining that a type field has not -- been given. The test suite must always have a valid type, so -- we need to check both the 'then' and 'else' blocks, though -- the blocks need not have the same type. let checkTestType ts ct = let ts' = mappend ts $ condTreeData ct -- If a conditional has only a 'then' block and no -- 'else' block, then it cannot have a valid type -- in every branch, unless the type is specified at -- a higher level in the tree. checkComponent (_, _, Nothing) = False -- If a conditional has a 'then' block and an 'else' -- block, both must specify a test type, unless the -- type is specified higher in the tree. checkComponent (_, t, Just e) = checkTestType ts' t && checkTestType ts' e -- Does the current node specify a test type? hasTestType = testInterface ts' /= testInterface emptyTestSuite components = condTreeComponents ct -- If the current level of the tree specifies a type, -- then we are done. If not, then one of the conditional -- branches below the current node must specify a type. -- Each node may have multiple immediate children; we -- only one need one to specify a type because the -- configure step uses 'mappend' to join together the -- results of flag resolution. in hasTestType || any checkComponent components if checkTestType emptyTestSuite flds then do skipField (repos, flags, lib, exes, tests, bms) <- getBody return (repos, flags, lib, exes, (testname, flds) : tests, bms) else lift $ syntaxError line_no $ "Test suite \"" ++ testname ++ "\" is missing required field \"type\" or the field " ++ "is not present in all conditional branches. The " ++ "available test types are: " ++ intercalate ", " (map display knownTestTypes) | sec_type == "benchmark" -> do when (null sec_label) $ lift $ syntaxError line_no "'benchmark' needs one argument (the benchmark's name)" benchname <- lift $ runP line_no "benchmark" parseTokenQ sec_label flds <- collectFields (parseBenchmarkFields line_no) sec_fields -- Check that a valid benchmark type has been chosen. A type -- field may be given inside a conditional block, so we must -- check for that before complaining that a type field has not -- been given. The benchmark must always have a valid type, so -- we need to check both the 'then' and 'else' blocks, though -- the blocks need not have the same type. let checkBenchmarkType ts ct = let ts' = mappend ts $ condTreeData ct -- If a conditional has only a 'then' block and no -- 'else' block, then it cannot have a valid type -- in every branch, unless the type is specified at -- a higher level in the tree. checkComponent (_, _, Nothing) = False -- If a conditional has a 'then' block and an 'else' -- block, both must specify a benchmark type, unless the -- type is specified higher in the tree. checkComponent (_, t, Just e) = checkBenchmarkType ts' t && checkBenchmarkType ts' e -- Does the current node specify a benchmark type? hasBenchmarkType = benchmarkInterface ts' /= benchmarkInterface emptyBenchmark components = condTreeComponents ct -- If the current level of the tree specifies a type, -- then we are done. If not, then one of the conditional -- branches below the current node must specify a type. -- Each node may have multiple immediate children; we -- only one need one to specify a type because the -- configure step uses 'mappend' to join together the -- results of flag resolution. in hasBenchmarkType || any checkComponent components if checkBenchmarkType emptyBenchmark flds then do skipField (repos, flags, lib, exes, tests, bms) <- getBody return (repos, flags, lib, exes, tests, (benchname, flds) : bms) else lift $ syntaxError line_no $ "Benchmark \"" ++ benchname ++ "\" is missing required field \"type\" or the field " ++ "is not present in all conditional branches. The " ++ "available benchmark types are: " ++ intercalate ", " (map display knownBenchmarkTypes) | sec_type == "library" -> do unless (null sec_label) $ lift $ syntaxError line_no "'library' expects no argument" flds <- collectFields parseLibFields sec_fields skipField (repos, flags, lib, exes, tests, bms) <- getBody when (isJust lib) $ lift $ syntaxError line_no "There can only be one library section in a package description." return (repos, flags, Just flds, exes, tests, bms) | sec_type == "flag" -> do when (null sec_label) $ lift $ syntaxError line_no "'flag' needs one argument (the flag's name)" flag <- lift $ parseFields flagFieldDescrs warnUnrec (MkFlag (FlagName (lowercase sec_label)) "" True False) sec_fields skipField (repos, flags, lib, exes, tests, bms) <- getBody return (repos, flag:flags, lib, exes, tests, bms) | sec_type == "source-repository" -> do when (null sec_label) $ lift $ syntaxError line_no $ "'source-repository' needs one argument, " ++ "the repo kind which is usually 'head' or 'this'" kind <- case simpleParse sec_label of Just kind -> return kind Nothing -> lift $ syntaxError line_no $ "could not parse repo kind: " ++ sec_label repo <- lift $ parseFields sourceRepoFieldDescrs warnUnrec SourceRepo { repoKind = kind, repoType = Nothing, repoLocation = Nothing, repoModule = Nothing, repoBranch = Nothing, repoTag = Nothing, repoSubdir = Nothing } sec_fields skipField (repos, flags, lib, exes, tests, bms) <- getBody return (repo:repos, flags, lib, exes, tests, bms) | otherwise -> do lift $ warning $ "Ignoring unknown section type: " ++ sec_type skipField getBody Just f@(F {}) -> do _ <- lift $ syntaxError (lineNo f) $ "Plain fields are not allowed in between stanzas: " ++ show f skipField getBody Just f@(IfBlock {}) -> do _ <- lift $ syntaxError (lineNo f) $ "If-blocks are not allowed in between stanzas: " ++ show f skipField getBody Nothing -> return ([], [], Nothing, [], [], []) -- Extracts all fields in a block and returns a 'CondTree'. -- -- We have to recurse down into conditionals and we treat fields that -- describe dependencies specially. collectFields :: ([Field] -> PM a) -> [Field] -> PM (CondTree ConfVar [Dependency] a) collectFields parser allflds = do let simplFlds = [ F l n v | F l n v <- allflds ] condFlds = [ f | f@IfBlock{} <- allflds ] sections = [ s | s@Section{} <- allflds ] -- Put these through the normal parsing pass too, so that we -- collect the ModRenamings let depFlds = filter isConstraint simplFlds mapM_ (\(Section l n _ _) -> lift . warning $ "Unexpected section '" ++ n ++ "' on line " ++ show l) sections a <- parser simplFlds deps <- liftM concat . mapM (lift . fmap (map dependency) . parseConstraint) $ depFlds ifs <- mapM processIfs condFlds return (CondNode a deps ifs) where isConstraint (F _ n _) = n `elem` constraintFieldNames isConstraint _ = False processIfs (IfBlock l c t e) = do cnd <- lift $ runP l "if" parseCondition c t' <- collectFields parser t e' <- case e of [] -> return Nothing es -> do fs <- collectFields parser es return (Just fs) return (cnd, t', e') processIfs _ = cabalBug "processIfs called with wrong field type" parseLibFields :: [Field] -> PM Library parseLibFields = lift . parseFields libFieldDescrs storeXFieldsLib emptyLibrary -- Note: we don't parse the "executable" field here, hence the tail hack. parseExeFields :: [Field] -> PM Executable parseExeFields = lift . parseFields (tail executableFieldDescrs) storeXFieldsExe emptyExecutable parseTestFields :: LineNo -> [Field] -> PM TestSuite parseTestFields line fields = do x <- lift $ parseFields testSuiteFieldDescrs storeXFieldsTest emptyTestStanza fields lift $ validateTestSuite line x parseBenchmarkFields :: LineNo -> [Field] -> PM Benchmark parseBenchmarkFields line fields = do x <- lift $ parseFields benchmarkFieldDescrs storeXFieldsBenchmark emptyBenchmarkStanza fields lift $ validateBenchmark line x checkForUndefinedFlags :: [Flag] -> Maybe (CondTree ConfVar [Dependency] Library) -> [(String, CondTree ConfVar [Dependency] Executable)] -> [(String, CondTree ConfVar [Dependency] TestSuite)] -> PM () checkForUndefinedFlags flags mlib exes tests = do let definedFlags = map flagName flags maybe (return ()) (checkCondTreeFlags definedFlags) mlib mapM_ (checkCondTreeFlags definedFlags . snd) exes mapM_ (checkCondTreeFlags definedFlags . snd) tests checkCondTreeFlags :: [FlagName] -> CondTree ConfVar c a -> PM () checkCondTreeFlags definedFlags ct = do let fv = nub $ freeVars ct unless (all (`elem` definedFlags) fv) $ fail $ "These flags are used without having been defined: " ++ intercalate ", " [ n | FlagName n <- fv \\ definedFlags ] -- | Parse a list of fields, given a list of field descriptions, -- a structure to accumulate the parsed fields, and a function -- that can decide what to do with fields which don't match any -- of the field descriptions. parseFields :: [FieldDescr a] -- ^ descriptions of fields we know how to -- parse -> UnrecFieldParser a -- ^ possibly do something with -- unrecognized fields -> a -- ^ accumulator -> [Field] -- ^ fields to be parsed -> ParseResult a parseFields descrs unrec ini fields = do (a, unknowns) <- foldM (parseField descrs unrec) (ini, []) fields unless (null unknowns) $ warning $ render $ text "Unknown fields:" <+> commaSep (map (\(l,u) -> u ++ " (line " ++ show l ++ ")") (reverse unknowns)) $+$ text "Fields allowed in this section:" $$ nest 4 (commaSep $ map fieldName descrs) return a where commaSep = fsep . punctuate comma . map text parseField :: [FieldDescr a] -- ^ list of parseable fields -> UnrecFieldParser a -- ^ possibly do something with -- unrecognized fields -> (a,[(Int,String)]) -- ^ accumulated result and warnings -> Field -- ^ the field to be parsed -> ParseResult (a, [(Int,String)]) parseField (FieldDescr name _ parser : fields) unrec (a, us) (F line f val) | name == f = parser line val a >>= \a' -> return (a',us) | otherwise = parseField fields unrec (a,us) (F line f val) parseField [] unrec (a,us) (F l f val) = return $ case unrec (f,val) a of -- no fields matched, see if the 'unrec' Just a' -> (a',us) -- function wants to do anything with it Nothing -> (a, (l,f):us) parseField _ _ _ _ = cabalBug "'parseField' called on a non-field" deprecatedFields :: [(String,String)] deprecatedFields = deprecatedFieldsPkgDescr ++ deprecatedFieldsBuildInfo deprecatedFieldsPkgDescr :: [(String,String)] deprecatedFieldsPkgDescr = [ ("other-files", "extra-source-files") ] deprecatedFieldsBuildInfo :: [(String,String)] deprecatedFieldsBuildInfo = [ ("hs-source-dir","hs-source-dirs") ] -- Handle deprecated fields deprecField :: Field -> ParseResult Field deprecField (F line fld val) = do fld' <- case lookup fld deprecatedFields of Nothing -> return fld Just newName -> do warning $ "The field \"" ++ fld ++ "\" is deprecated, please use \"" ++ newName ++ "\"" return newName return (F line fld' val) deprecField _ = cabalBug "'deprecField' called on a non-field" parseHookedBuildInfo :: String -> ParseResult HookedBuildInfo parseHookedBuildInfo inp = do fields <- readFields inp let ss@(mLibFields:exes) = stanzas fields mLib <- parseLib mLibFields biExes <- mapM parseExe (maybe ss (const exes) mLib) return (mLib, biExes) where parseLib :: [Field] -> ParseResult (Maybe BuildInfo) parseLib (bi@(F _ inFieldName _:_)) | lowercase inFieldName /= "executable" = liftM Just (parseBI bi) parseLib _ = return Nothing parseExe :: [Field] -> ParseResult (String, BuildInfo) parseExe (F line inFieldName mName:bi) | lowercase inFieldName == "executable" = do bis <- parseBI bi return (mName, bis) | otherwise = syntaxError line "expecting 'executable' at top of stanza" parseExe (_:_) = cabalBug "`parseExe' called on a non-field" parseExe [] = syntaxError 0 "error in parsing buildinfo file. Expected executable stanza" parseBI st = parseFields binfoFieldDescrs storeXFieldsBI emptyBuildInfo st -- --------------------------------------------------------------------------- -- Pretty printing writePackageDescription :: FilePath -> PackageDescription -> IO () writePackageDescription fpath pkg = writeUTF8File fpath (showPackageDescription pkg) --TODO: make this use section syntax -- add equivalent for GenericPackageDescription showPackageDescription :: PackageDescription -> String showPackageDescription pkg = render $ ppPackage pkg $$ ppCustomFields (customFieldsPD pkg) $$ (case library pkg of Nothing -> empty Just lib -> ppLibrary lib) $$ vcat [ space $$ ppExecutable exe | exe <- executables pkg ] where ppPackage = ppFields pkgDescrFieldDescrs ppLibrary = ppFields libFieldDescrs ppExecutable = ppFields executableFieldDescrs ppCustomFields :: [(String,String)] -> Doc ppCustomFields flds = vcat (map ppCustomField flds) ppCustomField :: (String,String) -> Doc ppCustomField (name,val) = text name <> colon <+> showFreeText val writeHookedBuildInfo :: FilePath -> HookedBuildInfo -> IO () writeHookedBuildInfo fpath = writeFileAtomic fpath . BS.Char8.pack . showHookedBuildInfo showHookedBuildInfo :: HookedBuildInfo -> String showHookedBuildInfo (mb_lib_bi, ex_bis) = render $ (case mb_lib_bi of Nothing -> empty Just bi -> ppBuildInfo bi) $$ vcat [ space $$ text "executable:" <+> text name $$ ppBuildInfo bi | (name, bi) <- ex_bis ] where ppBuildInfo bi = ppFields binfoFieldDescrs bi $$ ppCustomFields (customFieldsBI bi) -- replace all tabs used as indentation with whitespace, also return where -- tabs were found findIndentTabs :: String -> [(Int,Int)] findIndentTabs = concatMap checkLine . zip [1..] . lines where checkLine (lineno, l) = let (indent, _content) = span isSpace l tabCols = map fst . filter ((== '\t') . snd) . zip [0..] addLineNo = map (\col -> (lineno,col)) in addLineNo (tabCols indent) --test_findIndentTabs = findIndentTabs $ unlines $ -- [ "foo", " bar", " \t baz", "\t biz\t", "\t\t \t mib" ] -- | Dependencies plus module renamings. This is what users specify; however, -- renaming information is not used for dependency resolution. data DependencyWithRenaming = DependencyWithRenaming Dependency ModuleRenaming deriving (Read, Show, Eq, Typeable, Data) dependency :: DependencyWithRenaming -> Dependency dependency (DependencyWithRenaming dep _) = dep instance Text DependencyWithRenaming where disp (DependencyWithRenaming d rns) = disp d <+> disp rns parse = do d <- parse Parse.skipSpaces rns <- parse Parse.skipSpaces return (DependencyWithRenaming d rns) buildDependsWithRenaming :: BuildInfo -> [DependencyWithRenaming] buildDependsWithRenaming pkg = map (\dep@(Dependency n _) -> DependencyWithRenaming dep (Map.findWithDefault defaultRenaming n (targetBuildRenaming pkg))) (targetBuildDepends pkg) setBuildDependsWithRenaming :: [DependencyWithRenaming] -> BuildInfo -> BuildInfo setBuildDependsWithRenaming deps pkg = pkg { targetBuildDepends = map dependency deps, targetBuildRenaming = Map.fromList (map (\(DependencyWithRenaming (Dependency n _) rns) -> (n, rns)) deps) }
DavidAlphaFox/ghc
libraries/Cabal/Cabal/Distribution/PackageDescription/Parse.hs
Haskell
bsd-3-clause
54,747
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} ----------------------------------------------------------------------------- -- | -- Module : Generics.Instant.Base -- Copyright : (c) 2010, Universiteit Utrecht -- License : BSD3 -- -- Maintainer : generics@haskell.org -- Stability : experimental -- Portability : non-portable -- -- This module defines the basic representation types and the conversion -- functions 'to' and 'from'. A typical instance for a user-defined datatype -- would be: -- -- > -- Example datatype -- > data Exp = Const Int | Plus Exp Exp -- > -- > -- Auxiliary datatypes for constructor representations -- > data Const -- > data Plus -- > -- > instance Constructor Const where conName _ = "Const" -- > instance Constructor Plus where conName _ = "Plus" -- > -- > -- Representable instance -- > instance Representable Exp where -- > type Rep Exp = C Const (Var Int) :+: C Plus (Rec Exp :*: Rec Exp) -- > -- > from (Const n) = L (C (Var n)) -- > from (Plus e e') = R (C (Rec e :*: Rec e')) -- > -- > to (L (C (Var n))) = Const n -- > to (R (C (Rec e :*: Rec e'))) = Plus e e' -- ----------------------------------------------------------------------------- module Generics.Instant.Base ( Z, U(..), (:+:)(..), (:*:)(..), CEq(..), C, Var(..), Rec(..) , Constructor(..), Fixity(..), Associativity(..) , Representable(..) , X, Nat(..) ) where infixr 5 :+: infixr 6 :*: data Z data U = U deriving (Show, Read) data a :+: b = L a | R b deriving (Show, Read) data a :*: b = a :*: b deriving (Show, Read) data Var a = Var a deriving (Show, Read) data Rec a = Rec a deriving (Show, Read) data CEq c p q a where C :: a -> CEq c p p a deriving instance (Show a) => Show (CEq c p q a) deriving instance (Read a) => Read (CEq c p p a) -- Shorthand when no proofs are required type C c a = CEq c () () a -- | Class for datatypes that represent data constructors. -- For non-symbolic constructors, only 'conName' has to be defined. class Constructor c where conName :: t c p q a -> String {-# INLINE conFixity #-} conFixity :: t c p q a -> Fixity conFixity = const Prefix {-# INLINE conIsRecord #-} conIsRecord :: t c p q a -> Bool conIsRecord = const False -- | Datatype to represent the fixity of a constructor. An infix declaration -- directly corresponds to an application of 'Infix'. data Fixity = Prefix | Infix Associativity Int deriving (Eq, Show, Ord, Read) -- | Datatype to represent the associativy of a constructor. data Associativity = LeftAssociative | RightAssociative | NotAssociative deriving (Eq, Show, Ord, Read) class Representable a where type Rep a to :: Rep a -> a from :: a -> Rep a -- defaults {- type Rep a = a -- type synonyms defaults are not yet implemented! to = id from = id -} -- Type family for representing existentially-quantified variables type family X c (n :: Nat) (a :: k1) :: k2 -- Natural numbers, to be used at the type level data Nat = Ze | Su Nat
dreixel/instant-generics
src/Generics/Instant/Base.hs
Haskell
bsd-3-clause
3,468
{-# LANGUAGE LambdaCase #-} import Control.Arrow import Control.Lens import Data.Char import Data.List.Split import qualified Data.Map as M data ColorDef = ColorDef { colorName :: String, colorValue :: String } main = interact process where process = generateDefs . map processColor . tail . lines processColor = mkColorDef . (init &&& last) . words mkColorDef :: ([String], String) -> ColorDef mkColorDef = ColorDef <$> (mkVarName . fst) <*> snd mkVarName (n:ns) = map (\case '/' -> '_'; c -> c) $ n ++ concatMap upFirst ns upFirst (c:cs) = toUpper c : cs generateDefs :: [ColorDef] -> String generateDefs cs = formatColorDefs cs ++ "\n" ++ formatColorMap cs formatColorDefs cs = unlines . map mkEqn $ cs where width = maximum . map (length . colorName) $ cs mkEqn (ColorDef v c) = padded v ++ " = fromJust $ readHexColor " ++ show c padded a = a ++ (replicate (width - length a) ' ') formatColorMap cs = unlines $ [ "xkcdColorMap :: M.Map String (AlphaColour Double)" , "xkcdColorMap = M.fromList" ] ++ (map mkAssoc cs & _Cons . _2 . traverse %~ (" , "++) & _Cons . _1 %~ (" [ "++) ) ++ [ " ]" ] where mkAssoc (ColorDef n c) = "(" ++ show n ++ ", " ++ n ++ ")"
diagrams/diagrams-contrib
src/Diagrams/Color/ProcessXKCDColors.hs
Haskell
bsd-3-clause
1,426
module Deprecated.DiGraph.SampleData where import PolyGraph.Common import qualified Instances.SimpleGraph as SG import qualified SampleInstances.FirstLastWord as FL import qualified Data.HashSet as HS -- simple test data (list of pars that will serve as edges) testEdges = map(OPair) [ ("a0", "a01"), ("a0", "a02"), ("a01", "a1"), ("a02", "a1"), ("a0", "a1"), ("a1", "a11"), ("a1", "a12"), ("a11", "a2"), ("a12", "a2"), ("a1", "a2") ] -- -- notice SimpleGraph is not specialized to String type -- playTwoDiamondsSetGraph :: SG.SimpleSetDiGraph String playTwoDiamondsSetGraph = SG.SimpleGraph (HS.fromList testEdges) HS.empty playTwoDiamonds :: SG.SimpleListDiGraph String playTwoDiamonds = SG.SimpleGraph testEdges [] playFirstLastTxt:: String playFirstLastTxt = "a implies b\n" ++ "a implies c\n" ++ "b implies d\n" ++ "c implies d\n" ++ "d implies e\n" ++ "a implies f\n" playFirstLast = FL.FLWordText playFirstLastTxt
rpeszek/GraphPlay
play/Play/DiGraph/SampleData.hs
Haskell
bsd-3-clause
1,095
{-# LANGUAGE LambdaCase, PatternGuards, ViewPatterns #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Idris.Elab.Term where import Idris.AbsSyntax import Idris.AbsSyntaxTree import Idris.DSL import Idris.Delaborate import Idris.Error import Idris.ProofSearch import Idris.Output (pshow) import Idris.Core.CaseTree (SC, SC'(STerm), findCalls, findUsedArgs) import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.TT import Idris.Core.Evaluate import Idris.Core.Unify import Idris.Core.ProofTerm (getProofTerm) import Idris.Core.Typecheck (check, recheck, converts, isType) import Idris.Core.WHNF (whnf) import Idris.Coverage (buildSCG, checkDeclTotality, genClauses, recoverableCoverage, validCoverageCase) import Idris.ErrReverse (errReverse) import Idris.ElabQuasiquote (extractUnquotes) import Idris.Elab.Utils import Idris.Reflection import qualified Util.Pretty as U import Control.Applicative ((<$>)) import Control.Monad import Control.Monad.State.Strict import Data.Foldable (for_) import Data.List import qualified Data.Map as M import Data.Maybe (mapMaybe, fromMaybe, catMaybes, maybeToList) import qualified Data.Set as S import qualified Data.Text as T import Debug.Trace data ElabMode = ETyDecl | ETransLHS | ELHS | ERHS deriving Eq data ElabResult = ElabResult { resultTerm :: Term -- ^ The term resulting from elaboration , resultMetavars :: [(Name, (Int, Maybe Name, Type, [Name]))] -- ^ Information about new metavariables , resultCaseDecls :: [PDecl] -- ^ Deferred declarations as the meaning of case blocks , resultContext :: Context -- ^ The potentially extended context from new definitions , resultTyDecls :: [RDeclInstructions] -- ^ Meta-info about the new type declarations , resultHighlighting :: [(FC, OutputAnnotation)] } -- Using the elaborator, convert a term in raw syntax to a fully -- elaborated, typechecked term. -- -- If building a pattern match, we convert undeclared variables from -- holes to pattern bindings. -- Also find deferred names in the term and their types build :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> PTerm -> ElabD ElabResult build ist info emode opts fn tm = do elab ist info emode opts fn tm let tmIn = tm let inf = case lookupCtxt fn (idris_tyinfodata ist) of [TIPartial] -> True _ -> False hs <- get_holes ivs <- get_instances ptm <- get_term -- Resolve remaining type classes. Two passes - first to get the -- default Num instances, second to clean up the rest when (not pattern) $ mapM_ (\n -> when (n `elem` hs) $ do focus n g <- goal try (resolveTC' True False 10 g fn ist) (movelast n)) ivs ivs <- get_instances hs <- get_holes when (not pattern) $ mapM_ (\n -> when (n `elem` hs) $ do focus n g <- goal ptm <- get_term resolveTC' True True 10 g fn ist) ivs when (not pattern) $ solveAutos ist fn False tm <- get_term ctxt <- get_context probs <- get_probs u <- getUnifyLog hs <- get_holes when (not pattern) $ traceWhen u ("Remaining holes:\n" ++ show hs ++ "\n" ++ "Remaining problems:\n" ++ qshow probs) $ do unify_all; matchProblems True; unifyProblems when (not pattern) $ solveAutos ist fn True probs <- get_probs case probs of [] -> return () ((_,_,_,_,e,_,_):es) -> traceWhen u ("Final problems:\n" ++ qshow probs ++ "\nin\n" ++ show tm) $ if inf then return () else lift (Error e) when tydecl (do mkPat update_term liftPats update_term orderPats) EState is _ impls highlights <- getAux tt <- get_term ctxt <- get_context let (tm, ds) = runState (collectDeferred (Just fn) (map fst is) ctxt tt) [] log <- getLog if log /= "" then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights) else return (ElabResult tm ds (map snd is) ctxt impls highlights) where pattern = emode == ELHS tydecl = emode == ETyDecl mkPat = do hs <- get_holes tm <- get_term case hs of (h: hs) -> do patvar h; mkPat [] -> return () -- Build a term autogenerated as a typeclass method definition -- (Separate, so we don't go overboard resolving things that we don't -- know about yet on the LHS of a pattern def) buildTC :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> [Name] -> -- Cached names in the PTerm, before adding PAlternatives PTerm -> ElabD ElabResult buildTC ist info emode opts fn ns tm = do let tmIn = tm let inf = case lookupCtxt fn (idris_tyinfodata ist) of [TIPartial] -> True _ -> False -- set name supply to begin after highest index in tm initNextNameFrom ns elab ist info emode opts fn tm probs <- get_probs tm <- get_term case probs of [] -> return () ((_,_,_,_,e,_,_):es) -> if inf then return () else lift (Error e) dots <- get_dotterm -- 'dots' are the PHidden things which have not been solved by -- unification when (not (null dots)) $ lift (Error (CantMatch (getInferTerm tm))) EState is _ impls highlights <- getAux tt <- get_term ctxt <- get_context let (tm, ds) = runState (collectDeferred (Just fn) (map fst is) ctxt tt) [] log <- getLog if (log /= "") then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights) else return (ElabResult tm ds (map snd is) ctxt impls highlights) where pattern = emode == ELHS -- return whether arguments of the given constructor name can be -- matched on. If they're polymorphic, no, unless the type has beed made -- concrete by the time we get around to elaborating the argument. getUnmatchable :: Context -> Name -> [Bool] getUnmatchable ctxt n | isDConName n ctxt && n /= inferCon = case lookupTyExact n ctxt of Nothing -> [] Just ty -> checkArgs [] [] ty where checkArgs :: [Name] -> [[Name]] -> Type -> [Bool] checkArgs env ns (Bind n (Pi _ t _) sc) = let env' = case t of TType _ -> n : env _ -> env in checkArgs env' (intersect env (refsIn t) : ns) (instantiate (P Bound n t) sc) checkArgs env ns t = map (not . null) (reverse ns) getUnmatchable ctxt n = [] data ElabCtxt = ElabCtxt { e_inarg :: Bool, e_isfn :: Bool, -- ^ Function part of application e_guarded :: Bool, e_intype :: Bool, e_qq :: Bool, e_nomatching :: Bool -- ^ can't pattern match } initElabCtxt = ElabCtxt False False False False False False goal_polymorphic :: ElabD Bool goal_polymorphic = do ty <- goal case ty of P _ n _ -> do env <- get_env case lookup n env of Nothing -> return False _ -> return True _ -> return False -- | Returns the set of declarations we need to add to complete the -- definition (most likely case blocks to elaborate) as well as -- declarations resulting from user tactic scripts (%runElab) elab :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> PTerm -> ElabD () elab ist info emode opts fn tm = do let loglvl = opt_logLevel (idris_options ist) when (loglvl > 5) $ unifyLog True compute -- expand type synonyms, etc let fc = maybe "(unknown)" elabE initElabCtxt (elabFC info) tm -- (in argument, guarded, in type, in qquote) est <- getAux sequence_ (get_delayed_elab est) end_unify ptm <- get_term when (pattern || intransform) -- convert remaining holes to pattern vars (do update_term orderPats unify_all matchProblems False -- only the ones we matched earlier unifyProblems mkPat) where pattern = emode == ELHS intransform = emode == ETransLHS bindfree = emode == ETyDecl || emode == ELHS || emode == ETransLHS get_delayed_elab est = let ds = delayed_elab est in map snd $ sortBy (\(p1, _) (p2, _) -> compare p1 p2) ds tcgen = Dictionary `elem` opts reflection = Reflection `elem` opts isph arg = case getTm arg of Placeholder -> (True, priority arg) tm -> (False, priority arg) toElab ina arg = case getTm arg of Placeholder -> Nothing v -> Just (priority arg, elabE ina (elabFC info) v) toElab' ina arg = case getTm arg of Placeholder -> Nothing v -> Just (elabE ina (elabFC info) v) mkPat = do hs <- get_holes tm <- get_term case hs of (h: hs) -> do patvar h; mkPat [] -> return () -- | elabE elaborates an expression, possibly wrapping implicit coercions -- and forces/delays. If you make a recursive call in elab', it is -- normally correct to call elabE - the ones that don't are desugarings -- typically elabE :: ElabCtxt -> Maybe FC -> PTerm -> ElabD () elabE ina fc' t = do solved <- get_recents as <- get_autos hs <- get_holes -- If any of the autos use variables which have recently been solved, -- have another go at solving them now. mapM_ (\(a, (failc, ns)) -> if any (\n -> n `elem` solved) ns && head hs /= a then solveAuto ist fn False (a, failc) else return ()) as itm <- if not pattern then insertImpLam ina t else return t ct <- insertCoerce ina itm t' <- insertLazy ct g <- goal tm <- get_term ps <- get_probs hs <- get_holes --trace ("Elaborating " ++ show t' ++ " in " ++ show g -- ++ "\n" ++ show tm -- ++ "\nholes " ++ show hs -- ++ "\nproblems " ++ show ps -- ++ "\n-----------\n") $ --trace ("ELAB " ++ show t') $ let fc = fileFC "Force" env <- get_env handleError (forceErr t' env) (elab' ina fc' t') (elab' ina fc' (PApp fc (PRef fc [] (sUN "Force")) [pimp (sUN "t") Placeholder True, pimp (sUN "a") Placeholder True, pexp ct])) forceErr orig env (CantUnify _ (t,_) (t',_) _ _ _) | (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t), ht == txt "Lazy'" = notDelay orig forceErr orig env (CantUnify _ (t,_) (t',_) _ _ _) | (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t'), ht == txt "Lazy'" = notDelay orig forceErr orig env (InfiniteUnify _ t _) | (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t), ht == txt "Lazy'" = notDelay orig forceErr orig env (Elaborating _ _ _ t) = forceErr orig env t forceErr orig env (ElaboratingArg _ _ _ t) = forceErr orig env t forceErr orig env (At _ t) = forceErr orig env t forceErr orig env t = False notDelay t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Delay" = False notDelay _ = True local f = do e <- get_env return (f `elem` map fst e) -- | Is a constant a type? constType :: Const -> Bool constType (AType _) = True constType StrType = True constType VoidType = True constType _ = False -- "guarded" means immediately under a constructor, to help find patvars elab' :: ElabCtxt -- ^ (in an argument, guarded, in a type, in a quasiquote) -> Maybe FC -- ^ The closest FC in the syntax tree, if applicable -> PTerm -- ^ The term to elaborate -> ElabD () elab' ina fc (PNoImplicits t) = elab' ina fc t -- skip elabE step elab' ina fc (PType fc') = do apply RType [] solve highlightSource fc' (AnnType "Type" "The type of types") elab' ina fc (PUniverse u) = do apply (RUType u) []; solve -- elab' (_,_,inty) (PConstant c) -- | constType c && pattern && not reflection && not inty -- = lift $ tfail (Msg "Typecase is not allowed") elab' ina fc tm@(PConstant fc' c) | pattern && not reflection && not (e_qq ina) && not (e_intype ina) && isTypeConst c = lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm) | pattern && not reflection && not (e_qq ina) && e_nomatching ina = lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm) | otherwise = do apply (RConstant c) [] solve highlightSource fc' (AnnConst c) elab' ina fc (PQuote r) = do fill r; solve elab' ina _ (PTrue fc _) = do hnf_compute g <- goal case g of TType _ -> elab' ina (Just fc) (PRef fc [] unitTy) UType _ -> elab' ina (Just fc) (PRef fc [] unitTy) _ -> elab' ina (Just fc) (PRef fc [] unitCon) elab' ina fc (PResolveTC (FC "HACK" _ _)) -- for chasing parent classes = do g <- goal; resolveTC' False False 5 g fn ist elab' ina fc (PResolveTC fc') = do c <- getNameFrom (sMN 0 "__class") instanceArg c -- Elaborate the equality type first homogeneously, then -- heterogeneously as a fallback elab' ina _ (PApp fc (PRef _ _ n) args) | n == eqTy, [Placeholder, Placeholder, l, r] <- map getTm args = try (do tyn <- getNameFrom (sMN 0 "aqty") claim tyn RType movelast tyn elab' ina (Just fc) (PApp fc (PRef fc [] eqTy) [pimp (sUN "A") (PRef NoFC [] tyn) True, pimp (sUN "B") (PRef NoFC [] tyn) False, pexp l, pexp r])) (do atyn <- getNameFrom (sMN 0 "aqty") btyn <- getNameFrom (sMN 0 "bqty") claim atyn RType movelast atyn claim btyn RType movelast btyn elab' ina (Just fc) (PApp fc (PRef fc [] eqTy) [pimp (sUN "A") (PRef NoFC [] atyn) True, pimp (sUN "B") (PRef NoFC [] btyn) False, pexp l, pexp r])) elab' ina _ (PPair fc hls _ l r) = do hnf_compute g <- goal let (tc, _) = unApply g case g of TType _ -> elab' ina (Just fc) (PApp fc (PRef fc hls pairTy) [pexp l,pexp r]) UType _ -> elab' ina (Just fc) (PApp fc (PRef fc hls upairTy) [pexp l,pexp r]) _ -> case tc of P _ n _ | n == upairTy -> elab' ina (Just fc) (PApp fc (PRef fc hls upairCon) [pimp (sUN "A") Placeholder False, pimp (sUN "B") Placeholder False, pexp l, pexp r]) _ -> elab' ina (Just fc) (PApp fc (PRef fc hls pairCon) [pimp (sUN "A") Placeholder False, pimp (sUN "B") Placeholder False, pexp l, pexp r]) -- _ -> try' (elab' ina (Just fc) (PApp fc (PRef fc pairCon) -- [pimp (sUN "A") Placeholder False, -- pimp (sUN "B") Placeholder False, -- pexp l, pexp r])) -- (elab' ina (Just fc) (PApp fc (PRef fc upairCon) -- [pimp (sUN "A") Placeholder False, -- pimp (sUN "B") Placeholder False, -- pexp l, pexp r])) -- True elab' ina _ (PDPair fc hls p l@(PRef nfc hl n) t r) = case t of Placeholder -> do hnf_compute g <- goal case g of TType _ -> asType _ -> asValue _ -> asType where asType = elab' ina (Just fc) (PApp fc (PRef NoFC hls sigmaTy) [pexp t, pexp (PLam fc n nfc Placeholder r)]) asValue = elab' ina (Just fc) (PApp fc (PRef fc hls sigmaCon) [pimp (sMN 0 "a") t False, pimp (sMN 0 "P") Placeholder True, pexp l, pexp r]) elab' ina _ (PDPair fc hls p l t r) = elab' ina (Just fc) (PApp fc (PRef fc hls sigmaCon) [pimp (sMN 0 "a") t False, pimp (sMN 0 "P") Placeholder True, pexp l, pexp r]) elab' ina fc (PAlternative ms (ExactlyOne delayok) as) = do as_pruned <- doPrune as -- Finish the mkUniqueNames job with the pruned set, rather than -- the full set. uns <- get_usedns let as' = map (mkUniqueNames (uns ++ map snd ms) ms) as_pruned (h : hs) <- get_holes ty <- goal case as' of [] -> do hds <- mapM showHd as lift $ tfail $ NoValidAlts hds [x] -> elab' ina fc x -- If there's options, try now, and if that fails, postpone -- to later. _ -> handleError isAmbiguous (do hds <- mapM showHd as' tryAll (zip (map (elab' ina fc) as') hds)) (do movelast h delayElab 5 $ do hs <- get_holes when (h `elem` hs) $ do focus h as'' <- doPrune as' case as'' of [x] -> elab' ina fc x _ -> do hds <- mapM showHd as'' tryAll (zip (map (elab' ina fc) as'') hds)) where showHd (PApp _ (PRef _ _ (UN l)) [_, _, arg]) | l == txt "Delay" = showHd (getTm arg) showHd (PApp _ (PRef _ _ n) _) = return n showHd (PRef _ _ n) = return n showHd (PApp _ h _) = showHd h showHd x = getNameFrom (sMN 0 "_") -- We probably should do something better than this here doPrune as = do compute ty <- goal let (tc, _) = unApply (unDelay ty) env <- get_env return $ pruneByType env tc ist as unDelay t | (P _ (UN l) _, [_, arg]) <- unApply t, l == txt "Lazy'" = unDelay arg | otherwise = t isAmbiguous (CantResolveAlts _) = delayok isAmbiguous (Elaborating _ _ _ e) = isAmbiguous e isAmbiguous (ElaboratingArg _ _ _ e) = isAmbiguous e isAmbiguous (At _ e) = isAmbiguous e isAmbiguous _ = False elab' ina fc (PAlternative ms FirstSuccess as_in) = do -- finish the mkUniqueNames job uns <- get_usedns let as = map (mkUniqueNames (uns ++ map snd ms) ms) as_in trySeq as where -- if none work, take the error from the first trySeq (x : xs) = let e1 = elab' ina fc x in try' e1 (trySeq' e1 xs) True trySeq [] = fail "Nothing to try in sequence" trySeq' deferr [] = proofFail deferr trySeq' deferr (x : xs) = try' (do elab' ina fc x solveAutos ist fn False) (trySeq' deferr xs) True elab' ina fc (PAlternative ms TryImplicit (orig : alts)) = do env <- get_env compute ty <- goal let doelab = elab' ina fc orig tryCatch doelab (\err -> if recoverableErr err then -- trace ("NEED IMPLICIT! " ++ show orig ++ "\n" ++ -- show alts ++ "\n" ++ -- showQuick err) $ -- Prune the coercions so that only the ones -- with the right type to fix the error will be tried! case pruneAlts err alts env of [] -> lift $ tfail err alts' -> do try' (elab' ina fc (PAlternative ms (ExactlyOne False) alts')) (lift $ tfail err) -- take error from original if all fail True else lift $ tfail err) where recoverableErr (CantUnify _ _ _ _ _ _) = True recoverableErr (TooManyArguments _) = False recoverableErr (CantSolveGoal _ _) = False recoverableErr (CantResolveAlts _) = False recoverableErr (NoValidAlts _) = True recoverableErr (ProofSearchFail (Msg _)) = True recoverableErr (ProofSearchFail _) = False recoverableErr (ElaboratingArg _ _ _ e) = recoverableErr e recoverableErr (At _ e) = recoverableErr e recoverableErr (ElabScriptDebug _ _ _) = False recoverableErr _ = True pruneAlts (CantUnify _ (inc, _) (outc, _) _ _ _) alts env = case unApply (normalise (tt_ctxt ist) env inc) of (P (TCon _ _) n _, _) -> filter (hasArg n env) alts (Constant _, _) -> alts _ -> filter isLend alts -- special case hack for 'Borrowed' pruneAlts (ElaboratingArg _ _ _ e) alts env = pruneAlts e alts env pruneAlts (At _ e) alts env = pruneAlts e alts env pruneAlts (NoValidAlts as) alts env = alts pruneAlts err alts _ = filter isLend alts hasArg n env ap | isLend ap = True -- special case hack for 'Borrowed' hasArg n env (PApp _ (PRef _ _ a) _) = case lookupTyExact a (tt_ctxt ist) of Just ty -> let args = map snd (getArgTys (normalise (tt_ctxt ist) env ty)) in any (fnIs n) args Nothing -> False hasArg n env (PAlternative _ _ as) = any (hasArg n env) as hasArg n _ tm = False isLend (PApp _ (PRef _ _ l) _) = l == sNS (sUN "lend") ["Ownership"] isLend _ = False fnIs n ty = case unApply ty of (P _ n' _, _) -> n == n' _ -> False showQuick (CantUnify _ (l, _) (r, _) _ _ _) = show (l, r) showQuick (ElaboratingArg _ _ _ e) = showQuick e showQuick (At _ e) = showQuick e showQuick (ProofSearchFail (Msg _)) = "search fail" showQuick _ = "No chance" elab' ina _ (PPatvar fc n) | bindfree = do patvar n update_term liftPats highlightSource fc (AnnBoundName n False) -- elab' (_, _, inty) (PRef fc f) -- | isTConName f (tt_ctxt ist) && pattern && not reflection && not inty -- = lift $ tfail (Msg "Typecase is not allowed") elab' ec _ tm@(PRef fc hl n) | pattern && not reflection && not (e_qq ec) && not (e_intype ec) && isTConName n (tt_ctxt ist) = lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm) | pattern && not reflection && not (e_qq ec) && e_nomatching ec = lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm) | (pattern || intransform || (bindfree && bindable n)) && not (inparamBlock n) && not (e_qq ec) = do let ina = e_inarg ec guarded = e_guarded ec inty = e_intype ec ctxt <- get_context let defined = case lookupTy n ctxt of [] -> False _ -> True -- this is to stop us resolve type classes recursively -- trace (show (n, guarded)) $ if (tcname n && ina && not intransform) then erun fc $ do patvar n update_term liftPats highlightSource fc (AnnBoundName n False) else if (defined && not guarded) then do apply (Var n) [] annot <- findHighlight n solve highlightSource fc annot else try (do apply (Var n) [] annot <- findHighlight n solve highlightSource fc annot) (do patvar n update_term liftPats highlightSource fc (AnnBoundName n False)) where inparamBlock n = case lookupCtxtName n (inblock info) of [] -> False _ -> True bindable (NS _ _) = False bindable n = implicitable n elab' ina _ f@(PInferRef fc hls n) = elab' ina (Just fc) (PApp NoFC f []) elab' ina fc' tm@(PRef fc hls n) | pattern && not reflection && not (e_qq ina) && not (e_intype ina) && isTConName n (tt_ctxt ist) = lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm) | pattern && not reflection && not (e_qq ina) && e_nomatching ina = lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm) | otherwise = do fty <- get_type (Var n) -- check for implicits ctxt <- get_context env <- get_env let a' = insertScopedImps fc (normalise ctxt env fty) [] if null a' then erun fc $ do apply (Var n) [] hilite <- findHighlight n solve mapM_ (uncurry highlightSource) $ (fc, hilite) : map (\f -> (f, hilite)) hls else elab' ina fc' (PApp fc tm []) elab' ina _ (PLam _ _ _ _ PImpossible) = lift . tfail . Msg $ "Only pattern-matching lambdas can be impossible" elab' ina _ (PLam fc n nfc Placeholder sc) = do -- if n is a type constructor name, this makes no sense... ctxt <- get_context when (isTConName n ctxt) $ lift $ tfail (Msg $ "Can't use type constructor " ++ show n ++ " here") checkPiGoal n attack; intro (Just n); addPSname n -- okay for proof search -- trace ("------ intro " ++ show n ++ " ---- \n" ++ show ptm) elabE (ina { e_inarg = True } ) (Just fc) sc; solve highlightSource nfc (AnnBoundName n False) elab' ec _ (PLam fc n nfc ty sc) = do tyn <- getNameFrom (sMN 0 "lamty") -- if n is a type constructor name, this makes no sense... ctxt <- get_context when (isTConName n ctxt) $ lift $ tfail (Msg $ "Can't use type constructor " ++ show n ++ " here") checkPiGoal n claim tyn RType explicit tyn attack ptm <- get_term hs <- get_holes introTy (Var tyn) (Just n) addPSname n -- okay for proof search focus tyn elabE (ec { e_inarg = True, e_intype = True }) (Just fc) ty elabE (ec { e_inarg = True }) (Just fc) sc solve highlightSource nfc (AnnBoundName n False) elab' ina fc (PPi p n nfc Placeholder sc) = do attack; arg n (is_scoped p) (sMN 0 "ty") addPSname n -- okay for proof search elabE (ina { e_inarg = True, e_intype = True }) fc sc solve highlightSource nfc (AnnBoundName n False) elab' ina fc (PPi p n nfc ty sc) = do attack; tyn <- getNameFrom (sMN 0 "ty") claim tyn RType n' <- case n of MN _ _ -> unique_hole n _ -> return n forall n' (is_scoped p) (Var tyn) addPSname n' -- okay for proof search focus tyn let ec' = ina { e_inarg = True, e_intype = True } elabE ec' fc ty elabE ec' fc sc solve highlightSource nfc (AnnBoundName n False) elab' ina _ tm@(PLet fc n nfc ty val sc) = do attack ivs <- get_instances tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) explicit valn letbind n (Var tyn) (Var valn) addPSname n case ty of Placeholder -> return () _ -> do focus tyn explicit tyn elabE (ina { e_inarg = True, e_intype = True }) (Just fc) ty focus valn elabE (ina { e_inarg = True, e_intype = True }) (Just fc) val ivs' <- get_instances env <- get_env elabE (ina { e_inarg = True }) (Just fc) sc when (not (pattern || intransform)) $ mapM_ (\n -> do focus n g <- goal hs <- get_holes if all (\n -> n == tyn || not (n `elem` hs)) (freeNames g) then handleError (tcRecoverable emode) (resolveTC' True False 10 g fn ist) (movelast n) else movelast n) (ivs' \\ ivs) -- HACK: If the name leaks into its type, it may leak out of -- scope outside, so substitute in the outer scope. expandLet n (case lookup n env of Just (Let t v) -> v other -> error ("Value not a let binding: " ++ show other)) solve highlightSource nfc (AnnBoundName n False) elab' ina _ (PGoal fc r n sc) = do rty <- goal attack tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letbind n (Var tyn) (Var valn) focus valn elabE (ina { e_inarg = True, e_intype = True }) (Just fc) (PApp fc r [pexp (delab ist rty)]) env <- get_env computeLet n elabE (ina { e_inarg = True }) (Just fc) sc solve -- elab' ina fc (PLet n Placeholder -- (PApp fc r [pexp (delab ist rty)]) sc) elab' ina _ tm@(PApp fc (PInferRef _ _ f) args) = do rty <- goal ds <- get_deferred ctxt <- get_context -- make a function type a -> b -> c -> ... -> rty for the -- new function name env <- get_env argTys <- claimArgTys env args fn <- getNameFrom (sMN 0 "inf_fn") let fty = fnTy argTys rty -- trace (show (ptm, map fst argTys)) $ focus fn -- build and defer the function application attack; deferType (mkN f) fty (map fst argTys); solve -- elaborate the arguments, to unify their types. They all have to -- be explicit. mapM_ elabIArg (zip argTys args) where claimArgTys env [] = return [] claimArgTys env (arg : xs) | Just n <- localVar env (getTm arg) = do nty <- get_type (Var n) ans <- claimArgTys env xs return ((n, (False, forget nty)) : ans) claimArgTys env (_ : xs) = do an <- getNameFrom (sMN 0 "inf_argTy") aval <- getNameFrom (sMN 0 "inf_arg") claim an RType claim aval (Var an) ans <- claimArgTys env xs return ((aval, (True, (Var an))) : ans) fnTy [] ret = forget ret fnTy ((x, (_, xt)) : xs) ret = RBind x (Pi Nothing xt RType) (fnTy xs ret) localVar env (PRef _ _ x) = case lookup x env of Just _ -> Just x _ -> Nothing localVar env _ = Nothing elabIArg ((n, (True, ty)), def) = do focus n; elabE ina (Just fc) (getTm def) elabIArg _ = return () -- already done, just a name mkN n@(NS _ _) = n mkN n@(SN _) = n mkN n = case namespace info of Just xs@(_:_) -> sNS n xs _ -> n elab' ina _ (PMatchApp fc fn) = do (fn', imps) <- case lookupCtxtName fn (idris_implicits ist) of [(n, args)] -> return (n, map (const True) args) _ -> lift $ tfail (NoSuchVariable fn) ns <- match_apply (Var fn') (map (\x -> (x,0)) imps) solve -- if f is local, just do a simple_app -- FIXME: Anyone feel like refactoring this mess? - EB elab' ina topfc tm@(PApp fc (PRef ffc hls f) args_in) | pattern && not reflection && not (e_qq ina) && e_nomatching ina = lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm) | otherwise = implicitApp $ do env <- get_env ty <- goal fty <- get_type (Var f) ctxt <- get_context annot <- findHighlight f mapM_ checkKnownImplicit args_in let args = insertScopedImps fc (normalise ctxt env fty) args_in let unmatchableArgs = if pattern then getUnmatchable (tt_ctxt ist) f else [] -- trace ("BEFORE " ++ show f ++ ": " ++ show ty) $ when (pattern && not reflection && not (e_qq ina) && not (e_intype ina) && isTConName f (tt_ctxt ist)) $ lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm) -- trace (show (f, args_in, args)) $ if (f `elem` map fst env && length args == 1 && length args_in == 1) then -- simple app, as below do simple_app False (elabE (ina { e_isfn = True }) (Just fc) (PRef ffc hls f)) (elabE (ina { e_inarg = True }) (Just fc) (getTm (head args))) (show tm) solve mapM (uncurry highlightSource) $ (ffc, annot) : map (\f -> (f, annot)) hls return [] else do ivs <- get_instances ps <- get_probs -- HACK: we shouldn't resolve type classes if we're defining an instance -- function or default definition. let isinf = f == inferCon || tcname f -- if f is a type class, we need to know its arguments so that -- we can unify with them case lookupCtxt f (idris_classes ist) of [] -> return () _ -> do mapM_ setInjective (map getTm args) -- maybe more things are solvable now unifyProblems let guarded = isConName f ctxt -- trace ("args is " ++ show args) $ return () ns <- apply (Var f) (map isph args) -- trace ("ns is " ++ show ns) $ return () -- mark any type class arguments as injective when (not pattern) $ mapM_ checkIfInjective (map snd ns) unifyProblems -- try again with the new information, -- to help with disambiguation ulog <- getUnifyLog annot <- findHighlight f mapM (uncurry highlightSource) $ (ffc, annot) : map (\f -> (f, annot)) hls elabArgs ist (ina { e_inarg = e_inarg ina || not isinf }) [] fc False f (zip ns (unmatchableArgs ++ repeat False)) (f == sUN "Force") (map (\x -> getTm x) args) -- TODO: remove this False arg imp <- if (e_isfn ina) then do guess <- get_guess env <- get_env case safeForgetEnv (map fst env) guess of Nothing -> return [] Just rguess -> do gty <- get_type rguess let ty_n = normalise ctxt env gty return $ getReqImps ty_n else return [] -- Now we find out how many implicits we needed at the -- end of the application by looking at the goal again -- - Have another go, but this time add the -- implicits (can't think of a better way than this...) case imp of rs@(_:_) | not pattern -> return rs -- quit, try again _ -> do solve hs <- get_holes ivs' <- get_instances -- Attempt to resolve any type classes which have 'complete' types, -- i.e. no holes in them when (not pattern || (e_inarg ina && not tcgen && not (e_guarded ina))) $ mapM_ (\n -> do focus n g <- goal env <- get_env hs <- get_holes if all (\n -> not (n `elem` hs)) (freeNames g) then handleError (tcRecoverable emode) (resolveTC' False False 10 g fn ist) (movelast n) else movelast n) (ivs' \\ ivs) return [] where -- Run the elaborator, which returns how many implicit -- args were needed, then run it again with those args. We need -- this because we have to elaborate the whole application to -- find out whether any computations have caused more implicits -- to be needed. implicitApp :: ElabD [ImplicitInfo] -> ElabD () implicitApp elab | pattern || intransform = do elab; return () | otherwise = do s <- get imps <- elab case imps of [] -> return () es -> do put s elab' ina topfc (PAppImpl tm es) checkKnownImplicit imp | UnknownImp `elem` argopts imp = lift $ tfail $ UnknownImplicit (pname imp) f checkKnownImplicit _ = return () getReqImps (Bind x (Pi (Just i) ty _) sc) = i : getReqImps sc getReqImps _ = [] checkIfInjective n = do env <- get_env case lookup n env of Nothing -> return () Just b -> case unApply (normalise (tt_ctxt ist) env (binderTy b)) of (P _ c _, args) -> case lookupCtxtExact c (idris_classes ist) of Nothing -> return () Just ci -> -- type class, set as injective do mapM_ setinjArg (getDets 0 (class_determiners ci) args) -- maybe we can solve more things now... ulog <- getUnifyLog probs <- get_probs traceWhen ulog ("Injective now " ++ show args ++ "\n" ++ qshow probs) $ unifyProblems probs <- get_probs traceWhen ulog (qshow probs) $ return () _ -> return () setinjArg (P _ n _) = setinj n setinjArg _ = return () getDets i ds [] = [] getDets i ds (a : as) | i `elem` ds = a : getDets (i + 1) ds as | otherwise = getDets (i + 1) ds as tacTm (PTactics _) = True tacTm (PProof _) = True tacTm _ = False setInjective (PRef _ _ n) = setinj n setInjective (PApp _ (PRef _ _ n) _) = setinj n setInjective _ = return () elab' ina _ tm@(PApp fc f [arg]) = erun fc $ do simple_app (not $ headRef f) (elabE (ina { e_isfn = True }) (Just fc) f) (elabE (ina { e_inarg = True }) (Just fc) (getTm arg)) (show tm) solve where headRef (PRef _ _ _) = True headRef (PApp _ f _) = headRef f headRef (PAlternative _ _ as) = all headRef as headRef _ = False elab' ina fc (PAppImpl f es) = do appImpl (reverse es) -- not that we look... solve where appImpl [] = elab' (ina { e_isfn = False }) fc f -- e_isfn not set, so no recursive expansion of implicits appImpl (e : es) = simple_app False (appImpl es) (elab' ina fc Placeholder) (show f) elab' ina fc Placeholder = do (h : hs) <- get_holes movelast h elab' ina fc (PMetavar nfc n) = do ptm <- get_term -- When building the metavar application, leave out the unique -- names which have been used elsewhere in the term, since we -- won't be able to use them in the resulting application. let unique_used = getUniqueUsed (tt_ctxt ist) ptm let n' = metavarName (namespace info) n attack psns <- getPSnames n' <- defer unique_used n' solve highlightSource nfc (AnnName n' (Just MetavarOutput) Nothing Nothing) elab' ina fc (PProof ts) = do compute; mapM_ (runTac True ist (elabFC info) fn) ts elab' ina fc (PTactics ts) | not pattern = do mapM_ (runTac False ist fc fn) ts | otherwise = elab' ina fc Placeholder elab' ina fc (PElabError e) = lift $ tfail e elab' ina _ (PRewrite fc r sc newg) = do attack tyn <- getNameFrom (sMN 0 "rty") claim tyn RType valn <- getNameFrom (sMN 0 "rval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "_rewrite_rule") letbind letn (Var tyn) (Var valn) focus valn elab' ina (Just fc) r compute g <- goal rewrite (Var letn) g' <- goal when (g == g') $ lift $ tfail (NoRewriting g) case newg of Nothing -> elab' ina (Just fc) sc Just t -> doEquiv t sc solve where doEquiv t sc = do attack tyn <- getNameFrom (sMN 0 "ety") claim tyn RType valn <- getNameFrom (sMN 0 "eqval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "equiv_val") letbind letn (Var tyn) (Var valn) focus tyn elab' ina (Just fc) t focus valn elab' ina (Just fc) sc elab' ina (Just fc) (PRef fc [] letn) solve elab' ina _ c@(PCase fc scr opts) = do attack tyn <- getNameFrom (sMN 0 "scty") claim tyn RType valn <- getNameFrom (sMN 0 "scval") scvn <- getNameFrom (sMN 0 "scvar") claim valn (Var tyn) letbind scvn (Var tyn) (Var valn) focus valn elabE (ina { e_inarg = True }) (Just fc) scr -- Solve any remaining implicits - we need to solve as many -- as possible before making the 'case' type unifyProblems matchProblems True args <- get_env envU <- mapM (getKind args) args let namesUsedInRHS = nub $ scvn : concatMap (\(_,rhs) -> allNamesIn rhs) opts -- Drop the unique arguments used in the term already -- and in the scrutinee (since it's -- not valid to use them again anyway) -- -- Also drop unique arguments which don't appear explicitly -- in either case branch so they don't count as used -- unnecessarily (can only do this for unique things, since we -- assume they don't appear implicitly in types) ptm <- get_term let inOpts = (filter (/= scvn) (map fst args)) \\ (concatMap (\x -> allNamesIn (snd x)) opts) let argsDropped = filter (isUnique envU) (nub $ allNamesIn scr ++ inApp ptm ++ inOpts) let args' = filter (\(n, _) -> n `notElem` argsDropped) args attack cname' <- defer argsDropped (mkN (mkCaseName fc fn)) solve -- if the scrutinee is one of the 'args' in env, we should -- inspect it directly, rather than adding it as a new argument let newdef = PClauses fc [] cname' (caseBlock fc cname' scr (map (isScr scr) (reverse args')) opts) -- elaborate case updateAux (\e -> e { case_decls = (cname', newdef) : case_decls e } ) -- if we haven't got the type yet, hopefully we'll get it later! movelast tyn solve where mkCaseName fc (NS n ns) = NS (mkCaseName fc n) ns mkCaseName fc n = SN (CaseN (FC' fc) n) -- mkCaseName (UN x) = UN (x ++ "_case") -- mkCaseName (MN i x) = MN i (x ++ "_case") mkN n@(NS _ _) = n mkN n = case namespace info of Just xs@(_:_) -> sNS n xs _ -> n inApp (P _ n _) = [n] inApp (App _ f a) = inApp f ++ inApp a inApp (Bind n (Let _ v) sc) = inApp v ++ inApp sc inApp (Bind n (Guess _ v) sc) = inApp v ++ inApp sc inApp (Bind n b sc) = inApp sc inApp _ = [] isUnique envk n = case lookup n envk of Just u -> u _ -> False getKind env (n, _) = case lookup n env of Nothing -> return (n, False) -- can't happen, actually... Just b -> do ty <- get_type (forget (binderTy b)) case ty of UType UniqueType -> return (n, True) UType AllTypes -> return (n, True) _ -> return (n, False) tcName tm | (P _ n _, _) <- unApply tm = case lookupCtxt n (idris_classes ist) of [_] -> True _ -> False tcName _ = False usedIn ns (n, b) = n `elem` ns || any (\x -> x `elem` ns) (allTTNames (binderTy b)) elab' ina fc (PUnifyLog t) = do unifyLog True elab' ina fc t unifyLog False elab' ina fc (PQuasiquote t goalt) = do -- First extract the unquoted subterms, replacing them with fresh -- names in the quasiquoted term. Claim their reflections to be -- an inferred type (to support polytypic quasiquotes). finalTy <- goal (t, unq) <- extractUnquotes 0 t let unquoteNames = map fst unq mapM_ (\uqn -> claim uqn (forget finalTy)) unquoteNames -- Save the old state - we need a fresh proof state to avoid -- capturing lexically available variables in the quoted term. ctxt <- get_context datatypes <- get_datatypes saveState updatePS (const . newProof (sMN 0 "q") ctxt datatypes $ P Ref (reflm "TT") Erased) -- Re-add the unquotes, letting Idris infer the (fictional) -- types. Here, they represent the real type rather than the type -- of their reflection. mapM_ (\n -> do ty <- getNameFrom (sMN 0 "unqTy") claim ty RType movelast ty claim n (Var ty) movelast n) unquoteNames -- Determine whether there's an explicit goal type, and act accordingly -- Establish holes for the type and value of the term to be -- quasiquoted qTy <- getNameFrom (sMN 0 "qquoteTy") claim qTy RType movelast qTy qTm <- getNameFrom (sMN 0 "qquoteTm") claim qTm (Var qTy) -- Let-bind the result of elaborating the contained term, so that -- the hole doesn't disappear nTm <- getNameFrom (sMN 0 "quotedTerm") letbind nTm (Var qTy) (Var qTm) -- Fill out the goal type, if relevant case goalt of Nothing -> return () Just gTy -> do focus qTy elabE (ina { e_qq = True }) fc gTy -- Elaborate the quasiquoted term into the hole focus qTm elabE (ina { e_qq = True }) fc t end_unify -- We now have an elaborated term. Reflect it and solve the -- original goal in the original proof state, preserving highlighting env <- get_env EState _ _ _ hs <- getAux loadState updateAux (\aux -> aux { highlighting = hs }) let quoted = fmap (explicitNames . binderVal) $ lookup nTm env isRaw = case unApply (normaliseAll ctxt env finalTy) of (P _ n _, []) | n == reflm "Raw" -> True _ -> False case quoted of Just q -> do ctxt <- get_context (q', _, _) <- lift $ recheck ctxt [(uq, Lam Erased) | uq <- unquoteNames] (forget q) q if pattern then if isRaw then reflectRawQuotePattern unquoteNames (forget q') else reflectTTQuotePattern unquoteNames q' else do if isRaw then -- we forget q' instead of using q to ensure rechecking fill $ reflectRawQuote unquoteNames (forget q') else fill $ reflectTTQuote unquoteNames q' solve Nothing -> lift . tfail . Msg $ "Broken elaboration of quasiquote" -- Finally fill in the terms or patterns from the unquotes. This -- happens last so that their holes still exist while elaborating -- the main quotation. mapM_ elabUnquote unq where elabUnquote (n, tm) = do focus n elabE (ina { e_qq = False }) fc tm elab' ina fc (PUnquote t) = fail "Found unquote outside of quasiquote" elab' ina fc (PQuoteName n False nfc) = do fill $ reflectName n solve elab' ina fc (PQuoteName n True nfc) = do ctxt <- get_context env <- get_env case lookup n env of Just _ -> do fill $ reflectName n solve highlightSource nfc (AnnBoundName n False) Nothing -> case lookupNameDef n ctxt of [(n', _)] -> do fill $ reflectName n' solve highlightSource nfc (AnnName n' Nothing Nothing Nothing) [] -> lift . tfail . NoSuchVariable $ n more -> lift . tfail . CantResolveAlts $ map fst more elab' ina fc (PAs _ n t) = lift . tfail . Msg $ "@-pattern not allowed here" elab' ina fc (PHidden t) | reflection = elab' ina fc t | otherwise = do (h : hs) <- get_holes -- Dotting a hole means that either the hole or any outer -- hole (a hole outside any occurrence of it) -- must be solvable by unification as well as being filled -- in directly. -- Delay dotted things to the end, then when we elaborate them -- we can check the result against what was inferred movelast h delayElab 10 $ do focus h dotterm elab' ina fc t elab' ina fc (PRunElab fc' tm ns) = do attack n <- getNameFrom (sMN 0 "tacticScript") let scriptTy = RApp (Var (sNS (sUN "Elab") ["Elab", "Reflection", "Language"])) (Var unitTy) claim n scriptTy focus n attack -- to get an extra hole elab' ina (Just fc') tm script <- get_guess fullyElaborated script solve -- eliminate the hole. Becuase there are no references, the script is only in the binding env <- get_env runElabAction ist (maybe fc' id fc) env script ns solve elab' ina fc (PConstSugar constFC tm) = -- Here we elaborate the contained term, then calculate -- highlighting for constFC. The highlighting is the -- highlighting for the outermost constructor of the result of -- evaluating the elaborated term, if one exists (it always -- should, but better to fail gracefully for something silly -- like highlighting info). This is how implicit applications of -- fromInteger get highlighted. do saveState -- so we don't pollute the elaborated term n <- getNameFrom (sMN 0 "cstI") n' <- getNameFrom (sMN 0 "cstIhole") g <- forget <$> goal claim n' g movelast n' -- In order to intercept the elaborated value, we need to -- let-bind it. attack letbind n g (Var n') focus n' elab' ina fc tm env <- get_env ctxt <- get_context let v = fmap (normaliseAll ctxt env . finalise . binderVal) (lookup n env) loadState -- we have the highlighting - re-elaborate the value elab' ina fc tm case v of Just val -> highlightConst constFC val Nothing -> return () where highlightConst fc (P _ n _) = highlightSource fc (AnnName n Nothing Nothing Nothing) highlightConst fc (App _ f _) = highlightConst fc f highlightConst fc (Constant c) = highlightSource fc (AnnConst c) highlightConst _ _ = return () elab' ina fc x = fail $ "Unelaboratable syntactic form " ++ showTmImpls x -- delay elaboration of 't', with priority 'pri' until after everything -- else is done. -- The delayed things with lower numbered priority will be elaborated -- first. (In practice, this means delayed alternatives, then PHidden -- things.) delayElab pri t = updateAux (\e -> e { delayed_elab = delayed_elab e ++ [(pri, t)] }) isScr :: PTerm -> (Name, Binder Term) -> (Name, (Bool, Binder Term)) isScr (PRef _ _ n) (n', b) = (n', (n == n', b)) isScr _ (n', b) = (n', (False, b)) caseBlock :: FC -> Name -> PTerm -- original scrutinee -> [(Name, (Bool, Binder Term))] -> [(PTerm, PTerm)] -> [PClause] caseBlock fc n scr env opts = let args' = findScr env args = map mkarg (map getNmScr args') in map (mkClause args) opts where -- Find the variable we want as the scrutinee and mark it as -- 'True'. If the scrutinee is in the environment, match on that -- otherwise match on the new argument we're adding. findScr ((n, (True, t)) : xs) = (n, (True, t)) : scrName n xs findScr [(n, (_, t))] = [(n, (True, t))] findScr (x : xs) = x : findScr xs -- [] can't happen since scrutinee is in the environment! findScr [] = error "The impossible happened - the scrutinee was not in the environment" -- To make sure top level pattern name remains in scope, put -- it at the end of the environment scrName n [] = [] scrName n [(_, t)] = [(n, t)] scrName n (x : xs) = x : scrName n xs getNmScr (n, (s, _)) = (n, s) mkarg (n, s) = (PRef fc [] n, s) -- may be shadowed names in the new pattern - so replace the -- old ones with an _ -- Also, names which don't appear on the rhs should not be -- fixed on the lhs, or this restricts the kind of matching -- we can do to non-dependent types. mkClause args (l, r) = let args' = map (shadowed (allNamesIn l)) args args'' = map (implicitable (allNamesIn r ++ keepscrName scr)) args' lhs = PApp (getFC fc l) (PRef NoFC [] n) (map (mkLHSarg l) args'') in PClause (getFC fc l) n lhs [] r [] -- Keep scrutinee available if it's just a name (this makes -- the names in scope look better when looking at a hole on -- the rhs of a case) keepscrName (PRef _ _ n) = [n] keepscrName _ = [] mkLHSarg l (tm, True) = pexp l mkLHSarg l (tm, False) = pexp tm shadowed new (PRef _ _ n, s) | n `elem` new = (Placeholder, s) shadowed new t = t implicitable rhs (PRef _ _ n, s) | n `notElem` rhs = (Placeholder, s) implicitable rhs t = t getFC d (PApp fc _ _) = fc getFC d (PRef fc _ _) = fc getFC d (PAlternative _ _ (x:_)) = getFC d x getFC d x = d -- Fail if a term is not yet fully elaborated (e.g. if it contains -- case block functions that don't yet exist) fullyElaborated :: Term -> ElabD () fullyElaborated (P _ n _) = do EState cases _ _ _ <- getAux case lookup n cases of Nothing -> return () Just _ -> lift . tfail $ ElabScriptStaging n fullyElaborated (Bind n b body) = fullyElaborated body >> for_ b fullyElaborated fullyElaborated (App _ l r) = fullyElaborated l >> fullyElaborated r fullyElaborated (Proj t _) = fullyElaborated t fullyElaborated _ = return () insertLazy :: PTerm -> ElabD PTerm insertLazy t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Delay" = return t insertLazy t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Force" = return t insertLazy (PCoerced t) = return t insertLazy t = do ty <- goal env <- get_env let (tyh, _) = unApply (normalise (tt_ctxt ist) env ty) let tries = if pattern then [t, mkDelay env t] else [mkDelay env t, t] case tyh of P _ (UN l) _ | l == txt "Lazy'" -> return (PAlternative [] FirstSuccess tries) _ -> return t where mkDelay env (PAlternative ms b xs) = PAlternative ms b (map (mkDelay env) xs) mkDelay env t = let fc = fileFC "Delay" in addImplBound ist (map fst env) (PApp fc (PRef fc [] (sUN "Delay")) [pexp t]) -- Don't put implicit coercions around applications which are marked -- as '%noImplicit', or around case blocks, otherwise we get exponential -- blowup especially where there are errors deep in large expressions. notImplicitable (PApp _ f _) = notImplicitable f -- TMP HACK no coercing on bind (make this configurable) notImplicitable (PRef _ _ n) | [opts] <- lookupCtxt n (idris_flags ist) = NoImplicit `elem` opts notImplicitable (PAlternative _ _ as) = any notImplicitable as -- case is tricky enough without implicit coercions! If they are needed, -- they can go in the branches separately. notImplicitable (PCase _ _ _) = True notImplicitable _ = False insertScopedImps fc (Bind n (Pi im@(Just i) _ _) sc) xs | tcinstance i && not (toplevel_imp i) = pimp n (PResolveTC fc) True : insertScopedImps fc sc xs | not (toplevel_imp i) = pimp n Placeholder True : insertScopedImps fc sc xs insertScopedImps fc (Bind n (Pi _ _ _) sc) (x : xs) = x : insertScopedImps fc sc xs insertScopedImps _ _ xs = xs insertImpLam ina t = do ty <- goal env <- get_env let ty' = normalise (tt_ctxt ist) env ty addLam ty' t where -- just one level at a time addLam (Bind n (Pi (Just _) _ _) sc) t = do impn <- unique_hole n -- (sMN 0 "scoped_imp") if e_isfn ina -- apply to an implicit immediately then return (PApp emptyFC (PLam emptyFC impn NoFC Placeholder t) [pexp Placeholder]) else return (PLam emptyFC impn NoFC Placeholder t) addLam _ t = return t insertCoerce ina t@(PCase _ _ _) = return t insertCoerce ina t | notImplicitable t = return t insertCoerce ina t = do ty <- goal -- Check for possible coercions to get to the goal -- and add them as 'alternatives' env <- get_env let ty' = normalise (tt_ctxt ist) env ty let cs = getCoercionsTo ist ty' let t' = case (t, cs) of (PCoerced tm, _) -> tm (_, []) -> t (_, cs) -> PAlternative [] TryImplicit (t : map (mkCoerce env t) cs) return t' where mkCoerce env (PAlternative ms aty tms) n = PAlternative ms aty (map (\t -> mkCoerce env t n) tms) mkCoerce env t n = let fc = maybe (fileFC "Coercion") id (highestFC t) in addImplBound ist (map fst env) (PApp fc (PRef fc [] n) [pexp (PCoerced t)]) -- | Elaborate the arguments to a function elabArgs :: IState -- ^ The current Idris state -> ElabCtxt -- ^ (in an argument, guarded, in a type, in a qquote) -> [Bool] -> FC -- ^ Source location -> Bool -> Name -- ^ Name of the function being applied -> [((Name, Name), Bool)] -- ^ (Argument Name, Hole Name, unmatchable) -> Bool -- ^ under a 'force' -> [PTerm] -- ^ argument -> ElabD () elabArgs ist ina failed fc retry f [] force _ = return () elabArgs ist ina failed fc r f (((argName, holeName), unm):ns) force (t : args) = do hs <- get_holes if holeName `elem` hs then do focus holeName case t of Placeholder -> do movelast holeName elabArgs ist ina failed fc r f ns force args _ -> elabArg t else elabArgs ist ina failed fc r f ns force args where elabArg t = do -- solveAutos ist fn False now_elaborating fc f argName wrapErr f argName $ do hs <- get_holes tm <- get_term -- No coercing under an explicit Force (or it can Force/Delay -- recursively!) let elab = if force then elab' else elabE failed' <- -- trace (show (n, t, hs, tm)) $ -- traceWhen (not (null cs)) (show ty ++ "\n" ++ showImp True t) $ do focus holeName; g <- goal -- Can't pattern match on polymorphic goals poly <- goal_polymorphic ulog <- getUnifyLog traceWhen ulog ("Elaborating argument " ++ show (argName, holeName, g)) $ elab (ina { e_nomatching = unm && poly }) (Just fc) t return failed done_elaborating_arg f argName elabArgs ist ina failed fc r f ns force args wrapErr f argName action = do elabState <- get while <- elaborating_app let while' = map (\(x, y, z)-> (y, z)) while (result, newState) <- case runStateT action elabState of OK (res, newState) -> return (res, newState) Error e -> do done_elaborating_arg f argName lift (tfail (elaboratingArgErr while' e)) put newState return result elabArgs _ _ _ _ _ _ (((arg, hole), _) : _) _ [] = fail $ "Can't elaborate these args: " ++ show arg ++ " " ++ show hole -- For every alternative, look at the function at the head. Automatically resolve -- any nested alternatives where that function is also at the head pruneAlt :: [PTerm] -> [PTerm] pruneAlt xs = map prune xs where prune (PApp fc1 (PRef fc2 hls f) as) = PApp fc1 (PRef fc2 hls f) (fmap (fmap (choose f)) as) prune t = t choose f (PAlternative ms a as) = let as' = fmap (choose f) as fs = filter (headIs f) as' in case fs of [a] -> a _ -> PAlternative ms a as' choose f (PApp fc f' as) = PApp fc (choose f f') (fmap (fmap (choose f)) as) choose f t = t headIs f (PApp _ (PRef _ _ f') _) = f == f' headIs f (PApp _ f' _) = headIs f f' headIs f _ = True -- keep if it's not an application -- Rule out alternatives that don't return the same type as the head of the goal -- (If there are none left as a result, do nothing) pruneByType :: Env -> Term -> -- head of the goal IState -> [PTerm] -> [PTerm] -- if an alternative has a locally bound name at the head, take it pruneByType env t c as | Just a <- locallyBound as = [a] where locallyBound [] = Nothing locallyBound (t:ts) | Just n <- getName t, n `elem` map fst env = Just t | otherwise = locallyBound ts getName (PRef _ _ n) = Just n getName (PApp _ (PRef _ _ (UN l)) [_, _, arg]) -- ignore Delays | l == txt "Delay" = getName (getTm arg) getName (PApp _ f _) = getName f getName (PHidden t) = getName t getName _ = Nothing -- 'n' is the name at the head of the goal type pruneByType env (P _ n _) ist as -- if the goal type is polymorphic, keep everything | Nothing <- lookupTyExact n ctxt = as -- if the goal type is a ?metavariable, keep everything | Just _ <- lookup n (idris_metavars ist) = as | otherwise = let asV = filter (headIs True n) as as' = filter (headIs False n) as in case as' of [] -> asV _ -> as' where ctxt = tt_ctxt ist headIs var f (PRef _ _ f') = typeHead var f f' headIs var f (PApp _ (PRef _ _ (UN l)) [_, _, arg]) | l == txt "Delay" = headIs var f (getTm arg) headIs var f (PApp _ (PRef _ _ f') _) = typeHead var f f' headIs var f (PApp _ f' _) = headIs var f f' headIs var f (PPi _ _ _ _ sc) = headIs var f sc headIs var f (PHidden t) = headIs var f t headIs var f t = True -- keep if it's not an application typeHead var f f' = -- trace ("Trying " ++ show f' ++ " for " ++ show n) $ case lookupTyExact f' ctxt of Just ty -> case unApply (getRetTy ty) of (P _ ctyn _, _) | isConName ctyn ctxt -> ctyn == f _ -> let ty' = normalise ctxt [] ty in case unApply (getRetTy ty') of (P _ ftyn _, _) -> ftyn == f (V _, _) -> -- keep, variable -- trace ("Keeping " ++ show (f', ty') -- ++ " for " ++ show n) $ isPlausible ist var env n ty _ -> False _ -> False pruneByType _ t _ as = as -- Could the name feasibly be the return type? -- If there is a type class constraint on the return type, and no instance -- in the environment or globally for that name, then no -- Otherwise, yes -- (FIXME: This isn't complete, but I'm leaving it here and coming back -- to it later - just returns 'var' for now. EB) isPlausible :: IState -> Bool -> Env -> Name -> Type -> Bool isPlausible ist var env n ty = let (hvar, classes) = collectConstraints [] [] ty in case hvar of Nothing -> True Just rth -> var -- trace (show (rth, classes)) var where collectConstraints :: [Name] -> [(Term, [Name])] -> Type -> (Maybe Name, [(Term, [Name])]) collectConstraints env tcs (Bind n (Pi _ ty _) sc) = let tcs' = case unApply ty of (P _ c _, _) -> case lookupCtxtExact c (idris_classes ist) of Just tc -> ((ty, map fst (class_instances tc)) : tcs) Nothing -> tcs _ -> tcs in collectConstraints (n : env) tcs' sc collectConstraints env tcs t | (V i, _) <- unApply t = (Just (env !! i), tcs) | otherwise = (Nothing, tcs) -- | Use the local elab context to work out the highlighting for a name findHighlight :: Name -> ElabD OutputAnnotation findHighlight n = do ctxt <- get_context env <- get_env case lookup n env of Just _ -> return $ AnnBoundName n False Nothing -> case lookupTyExact n ctxt of Just _ -> return $ AnnName n Nothing Nothing Nothing Nothing -> lift . tfail . InternalMsg $ "Can't find name " ++ show n -- Try again to solve auto implicits solveAuto :: IState -> Name -> Bool -> (Name, [FailContext]) -> ElabD () solveAuto ist fn ambigok (n, failc) = do hs <- get_holes when (not (null hs)) $ do env <- get_env g <- goal handleError cantsolve (when (n `elem` hs) $ do focus n isg <- is_guess -- if it's a guess, we're working on it recursively, so stop when (not isg) $ proofSearch' ist True ambigok 100 True Nothing fn [] []) (lift $ Error (addLoc failc (CantSolveGoal g (map (\(n, b) -> (n, binderTy b)) env)))) return () where addLoc (FailContext fc f x : prev) err = At fc (ElaboratingArg f x (map (\(FailContext _ f' x') -> (f', x')) prev) err) addLoc _ err = err cantsolve (CantSolveGoal _ _) = True cantsolve (InternalMsg _) = True cantsolve (At _ e) = cantsolve e cantsolve (Elaborating _ _ _ e) = cantsolve e cantsolve (ElaboratingArg _ _ _ e) = cantsolve e cantsolve _ = False solveAutos :: IState -> Name -> Bool -> ElabD () solveAutos ist fn ambigok = do autos <- get_autos mapM_ (solveAuto ist fn ambigok) (map (\(n, (fc, _)) -> (n, fc)) autos) -- Return true if the given error suggests a type class failure is -- recoverable tcRecoverable :: ElabMode -> Err -> Bool tcRecoverable ERHS (CantResolve f g) = f tcRecoverable ETyDecl (CantResolve f g) = f tcRecoverable e (ElaboratingArg _ _ _ err) = tcRecoverable e err tcRecoverable e (At _ err) = tcRecoverable e err tcRecoverable _ _ = True trivial' ist = trivial (elab ist toplevel ERHS [] (sMN 0 "tac")) ist trivialHoles' psn h ist = trivialHoles psn h (elab ist toplevel ERHS [] (sMN 0 "tac")) ist proofSearch' ist rec ambigok depth prv top n psns hints = do unifyProblems proofSearch rec prv ambigok (not prv) depth (elab ist toplevel ERHS [] (sMN 0 "tac")) top n psns hints ist resolveTC' di mv depth tm n ist = resolveTC di mv depth tm n (elab ist toplevel ERHS [] (sMN 0 "tac")) ist collectDeferred :: Maybe Name -> [Name] -> Context -> Term -> State [(Name, (Int, Maybe Name, Type, [Name]))] Term collectDeferred top casenames ctxt (Bind n (GHole i psns t) app) = do ds <- get t' <- collectDeferred top casenames ctxt t when (not (n `elem` map fst ds)) $ put (ds ++ [(n, (i, top, tidyArg [] t', psns))]) collectDeferred top casenames ctxt app where -- Evaluate the top level functions in arguments, if possible, and if it's -- not a name we're immediately going to define in a case block, so that -- any immediate specialisation of the function applied to constructors -- can be done tidyArg env (Bind n b@(Pi im t k) sc) = Bind n (Pi im (tidy ctxt env t) k) (tidyArg ((n, b) : env) sc) tidyArg env t = tidy ctxt env t tidy ctxt env t = normalise ctxt env t getFn (Bind n (Lam _) t) = getFn t getFn t | (f, a) <- unApply t = f collectDeferred top ns ctxt (Bind n b t) = do b' <- cdb b t' <- collectDeferred top ns ctxt t return (Bind n b' t') where cdb (Let t v) = liftM2 Let (collectDeferred top ns ctxt t) (collectDeferred top ns ctxt v) cdb (Guess t v) = liftM2 Guess (collectDeferred top ns ctxt t) (collectDeferred top ns ctxt v) cdb b = do ty' <- collectDeferred top ns ctxt (binderTy b) return (b { binderTy = ty' }) collectDeferred top ns ctxt (App s f a) = liftM2 (App s) (collectDeferred top ns ctxt f) (collectDeferred top ns ctxt a) collectDeferred top ns ctxt t = return t case_ :: Bool -> Bool -> IState -> Name -> PTerm -> ElabD () case_ ind autoSolve ist fn tm = do attack tyn <- getNameFrom (sMN 0 "ity") claim tyn RType valn <- getNameFrom (sMN 0 "ival") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "irule") letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel ERHS [] (sMN 0 "tac") tm env <- get_env let (Just binding) = lookup letn env let val = binderVal binding if ind then induction (forget val) else casetac (forget val) when autoSolve solveAll -- | Compute the appropriate name for a top-level metavariable metavarName :: Maybe [String] -> Name -> Name metavarName _ n@(NS _ _) = n metavarName (Just (ns@(_:_))) n = sNS n ns metavarName _ n = n runElabAction :: IState -> FC -> Env -> Term -> [String] -> ElabD Term runElabAction ist fc env tm ns = do tm' <- eval tm runTacTm tm' where eval tm = do ctxt <- get_context return $ normaliseAll ctxt env (finalise tm) returnUnit = return $ P (DCon 0 0 False) unitCon (P (TCon 0 0) unitTy Erased) patvars :: [Name] -> Term -> ([Name], Term) patvars ns (Bind n (PVar t) sc) = patvars (n : ns) (instantiate (P Bound n t) sc) patvars ns tm = (ns, tm) pullVars :: (Term, Term) -> ([Name], Term, Term) pullVars (lhs, rhs) = (fst (patvars [] lhs), snd (patvars [] lhs), snd (patvars [] rhs)) -- TODO alpha-convert rhs defineFunction :: RFunDefn -> ElabD () defineFunction (RDefineFun n clauses) = do ctxt <- get_context ty <- maybe (fail "no type decl") return $ lookupTyExact n ctxt let info = CaseInfo True True False -- TODO document and figure out clauses' <- forM clauses (\case RMkFunClause lhs rhs -> do (lhs', lty) <- lift $ check ctxt [] lhs (rhs', rty) <- lift $ check ctxt [] rhs lift $ converts ctxt [] lty rty return $ Right (lhs', rhs') RMkImpossibleClause lhs -> do lhs' <- fmap fst . lift $ check ctxt [] lhs return $ Left lhs') let clauses'' = map (\case Right c -> pullVars c Left lhs -> let (ns, lhs') = patvars [] lhs' in (ns, lhs', Impossible)) clauses' ctxt'<- lift $ addCasedef n (const []) info False (STerm Erased) True False -- TODO what are these? (map snd $ getArgTys ty) [] -- TODO inaccessible types clauses' clauses'' clauses'' clauses'' clauses'' ty ctxt set_context ctxt' updateAux $ \e -> e { new_tyDecls = RClausesInstrs n clauses'' : new_tyDecls e} return () checkClosed :: Raw -> Elab' aux (Term, Type) checkClosed tm = do ctxt <- get_context (val, ty) <- lift $ check ctxt [] tm return $! (finalise val, finalise ty) -- | Do a step in the reflected elaborator monad. The input is the -- step, the output is the (reflected) term returned. runTacTm :: Term -> ElabD Term runTacTm (unApply -> tac@(P _ n _, args)) | n == tacN "Prim__Solve", [] <- args = do solve returnUnit | n == tacN "Prim__Goal", [] <- args = do hs <- get_holes case hs of (h : _) -> do t <- goal fmap fst . checkClosed $ rawPair (Var (reflm "TTName"), Var (reflm "TT")) (reflectName h, reflect t) [] -> lift . tfail . Msg $ "Elaboration is complete. There are no goals." | n == tacN "Prim__Holes", [] <- args = do hs <- get_holes fmap fst . checkClosed $ mkList (Var $ reflm "TTName") (map reflectName hs) | n == tacN "Prim__Guess", [] <- args = do g <- get_guess fmap fst . checkClosed $ reflect g | n == tacN "Prim__LookupTy", [n] <- args = do n' <- reifyTTName n ctxt <- get_context let getNameTypeAndType = \case Function ty _ -> (Ref, ty) TyDecl nt ty -> (nt, ty) Operator ty _ _ -> (Ref, ty) CaseOp _ ty _ _ _ _ -> (Ref, ty) -- Idris tuples nest to the right reflectTriple (x, y, z) = raw_apply (Var pairCon) [ Var (reflm "TTName") , raw_apply (Var pairTy) [Var (reflm "NameType"), Var (reflm "TT")] , x , raw_apply (Var pairCon) [ Var (reflm "NameType"), Var (reflm "TT") , y, z]] let defs = [ reflectTriple (reflectName n, reflectNameType nt, reflect ty) | (n, def) <- lookupNameDef n' ctxt , let (nt, ty) = getNameTypeAndType def ] fmap fst . checkClosed $ rawList (raw_apply (Var pairTy) [ Var (reflm "TTName") , raw_apply (Var pairTy) [ Var (reflm "NameType") , Var (reflm "TT")]]) defs | n == tacN "Prim__LookupDatatype", [name] <- args = do n' <- reifyTTName name datatypes <- get_datatypes ctxt <- get_context fmap fst . checkClosed $ rawList (Var (tacN "Datatype")) (map reflectDatatype (buildDatatypes ist n')) | n == tacN "Prim__LookupArgs", [name] <- args = do n' <- reifyTTName name let listTy = Var (sNS (sUN "List") ["List", "Prelude"]) listFunArg = RApp listTy (Var (tacN "FunArg")) -- Idris tuples nest to the right let reflectTriple (x, y, z) = raw_apply (Var pairCon) [ Var (reflm "TTName") , raw_apply (Var pairTy) [listFunArg, Var (reflm "Raw")] , x , raw_apply (Var pairCon) [listFunArg, Var (reflm "Raw") , y, z]] let out = [ reflectTriple (reflectName fn, reflectList (Var (tacN "FunArg")) (map reflectArg args), reflectRaw res) | (fn, pargs) <- lookupCtxtName n' (idris_implicits ist) , (args, res) <- getArgs pargs . forget <$> maybeToList (lookupTyExact fn (tt_ctxt ist)) ] fmap fst . checkClosed $ rawList (raw_apply (Var pairTy) [Var (reflm "TTName") , raw_apply (Var pairTy) [ RApp listTy (Var (tacN "FunArg")) , Var (reflm "Raw")]]) out | n == tacN "Prim__SourceLocation", [] <- args = fmap fst . checkClosed $ reflectFC fc | n == tacN "Prim__Namespace", [] <- args = fmap fst . checkClosed $ rawList (RConstant StrType) (map (RConstant . Str) ns) | n == tacN "Prim__Env", [] <- args = do env <- get_env fmap fst . checkClosed $ reflectEnv env | n == tacN "Prim__Fail", [_a, errs] <- args = do errs' <- eval errs parts <- reifyReportParts errs' lift . tfail $ ReflectionError [parts] (Msg "") | n == tacN "Prim__PureElab", [_a, tm] <- args = return tm | n == tacN "Prim__BindElab", [_a, _b, first, andThen] <- args = do first' <- eval first res <- eval =<< runTacTm first' next <- eval (App Complete andThen res) runTacTm next | n == tacN "Prim__Try", [_a, first, alt] <- args = do first' <- eval first alt' <- eval alt try' (runTacTm first') (runTacTm alt') True | n == tacN "Prim__Fill", [raw] <- args = do raw' <- reifyRaw =<< eval raw apply raw' [] returnUnit | n == tacN "Prim__Apply" || n == tacN "Prim__MatchApply" , [raw, argSpec] <- args = do raw' <- reifyRaw =<< eval raw argSpec' <- map (\b -> (b, 0)) <$> reifyList reifyBool argSpec let op = if n == tacN "Prim__Apply" then apply else match_apply ns <- op raw' argSpec' fmap fst . checkClosed $ rawList (rawPairTy (Var $ reflm "TTName") (Var $ reflm "TTName")) [ rawPair (Var $ reflm "TTName", Var $ reflm "TTName") (reflectName n1, reflectName n2) | (n1, n2) <- ns ] | n == tacN "Prim__Gensym", [hint] <- args = do hintStr <- eval hint case hintStr of Constant (Str h) -> do n <- getNameFrom (sMN 0 h) fmap fst $ get_type_val (reflectName n) _ -> fail "no hint" | n == tacN "Prim__Claim", [n, ty] <- args = do n' <- reifyTTName n ty' <- reifyRaw ty claim n' ty' returnUnit | n == tacN "Prim__Check", [env', raw] <- args = do env <- reifyEnv env' raw' <- reifyRaw =<< eval raw ctxt <- get_context (tm, ty) <- lift $ check ctxt env raw' fmap fst . checkClosed $ rawPair (Var (reflm "TT"), Var (reflm "TT")) (reflect tm, reflect ty) | n == tacN "Prim__Attack", [] <- args = do attack returnUnit | n == tacN "Prim__Rewrite", [rule] <- args = do r <- reifyRaw rule rewrite r returnUnit | n == tacN "Prim__Focus", [what] <- args = do n' <- reifyTTName what hs <- get_holes if elem n' hs then focus n' >> returnUnit else lift . tfail . Msg $ "The name " ++ show n' ++ " does not denote a hole" | n == tacN "Prim__Unfocus", [what] <- args = do n' <- reifyTTName what movelast n' returnUnit | n == tacN "Prim__Intro", [mn] <- args = do n <- case fromTTMaybe mn of Nothing -> return Nothing Just name -> fmap Just $ reifyTTName name intro n returnUnit | n == tacN "Prim__Forall", [n, ty] <- args = do n' <- reifyTTName n ty' <- reifyRaw ty forall n' Nothing ty' returnUnit | n == tacN "Prim__PatVar", [n] <- args = do n' <- reifyTTName n patvar' n' returnUnit | n == tacN "Prim__PatBind", [n] <- args = do n' <- reifyTTName n patbind n' returnUnit | n == tacN "Prim__LetBind", [n, ty, tm] <- args = do n' <- reifyTTName n ty' <- reifyRaw ty tm' <- reifyRaw tm letbind n' ty' tm' returnUnit | n == tacN "Prim__Compute", [] <- args = do compute ; returnUnit | n == tacN "Prim__Normalise", [env, tm] <- args = do env' <- reifyEnv env tm' <- reifyTT tm ctxt <- get_context let out = normaliseAll ctxt env' (finalise tm') fmap fst . checkClosed $ reflect out | n == tacN "Prim__Whnf", [tm] <- args = do tm' <- reifyTT tm ctxt <- get_context fmap fst . checkClosed . reflect $ whnf ctxt tm' | n == tacN "Prim__Converts", [env, tm1, tm2] <- args = do env' <- reifyEnv env tm1' <- reifyTT tm1 tm2' <- reifyTT tm2 ctxt <- get_context lift $ converts ctxt env' tm1' tm2' returnUnit | n == tacN "Prim__DeclareType", [decl] <- args = do (RDeclare n args res) <- reifyTyDecl decl ctxt <- get_context let mkPi arg res = RBind (argName arg) (Pi Nothing (argTy arg) (RUType AllTypes)) res rty = foldr mkPi res args (checked, ty') <- lift $ check ctxt [] rty case normaliseAll ctxt [] (finalise ty') of UType _ -> return () TType _ -> return () ty'' -> lift . tfail . InternalMsg $ show checked ++ " is not a type: it's " ++ show ty'' case lookupDefExact n ctxt of Just _ -> lift . tfail . InternalMsg $ show n ++ " is already defined." Nothing -> return () let decl = TyDecl Ref checked ctxt' = addCtxtDef n decl ctxt set_context ctxt' updateAux $ \e -> e { new_tyDecls = (RTyDeclInstrs n fc (map rFunArgToPArg args) checked) : new_tyDecls e } returnUnit | n == tacN "Prim__DefineFunction", [decl] <- args = do defn <- reifyFunDefn decl defineFunction defn returnUnit | n == tacN "Prim__AddInstance", [cls, inst] <- args = do className <- reifyTTName cls instName <- reifyTTName inst updateAux $ \e -> e { new_tyDecls = RAddInstance className instName : new_tyDecls e} returnUnit | n == tacN "Prim__IsTCName", [n] <- args = do n' <- reifyTTName n case lookupCtxtExact n' (idris_classes ist) of Just _ -> fmap fst . checkClosed $ Var (sNS (sUN "True") ["Bool", "Prelude"]) Nothing -> fmap fst . checkClosed $ Var (sNS (sUN "False") ["Bool", "Prelude"]) | n == tacN "Prim__ResolveTC", [fn] <- args = do g <- goal fn <- reifyTTName fn resolveTC' False True 100 g fn ist returnUnit | n == tacN "Prim__Search", [depth, hints] <- args = do d <- eval depth hints' <- eval hints case (d, unList hints') of (Constant (I i), Just hs) -> do actualHints <- mapM reifyTTName hs unifyProblems let psElab = elab ist toplevel ERHS [] (sMN 0 "tac") proofSearch True True False False i psElab Nothing (sMN 0 "search ") [] actualHints ist returnUnit (Constant (I _), Nothing ) -> lift . tfail . InternalMsg $ "Not a list: " ++ show hints' (_, _) -> lift . tfail . InternalMsg $ "Can't reify int " ++ show d | n == tacN "Prim__RecursiveElab", [goal, script] <- args = do goal' <- reifyRaw goal ctxt <- get_context script <- eval script (goalTT, goalTy) <- lift $ check ctxt [] goal' lift $ isType ctxt [] goalTy recH <- getNameFrom (sMN 0 "recElabHole") aux <- getAux datatypes <- get_datatypes env <- get_env (ctxt', ES (p, aux') _ _) <- do (ES (current_p, _) _ _) <- get lift $ runElab aux (do runElabAction ist fc [] script ns ctxt' <- get_context return ctxt') ((newProof recH ctxt datatypes goalTT) { nextname = nextname current_p }) set_context ctxt' let tm_out = getProofTerm (pterm p) do (ES (prf, _) s e) <- get let p' = prf { nextname = nextname p } put (ES (p', aux') s e) env' <- get_env (tm, ty, _) <- lift $ recheck ctxt' env (forget tm_out) tm_out let (tm', ty') = (reflect tm, reflect ty) fmap fst . checkClosed $ rawPair (Var $ reflm "TT", Var $ reflm "TT") (tm', ty') | n == tacN "Prim__Metavar", [n] <- args = do n' <- reifyTTName n ctxt <- get_context ptm <- get_term -- See documentation above in the elab case for PMetavar let unique_used = getUniqueUsed ctxt ptm let mvn = metavarName (Just ns) n' attack defer unique_used mvn solve returnUnit | n == tacN "Prim__Fixity", [op'] <- args = do opTm <- eval op' case opTm of Constant (Str op) -> let opChars = ":!#$%&*+./<=>?@\\^|-~" invalidOperators = [":", "=>", "->", "<-", "=", "?=", "|", "**", "==>", "\\", "%", "~", "?", "!"] fixities = idris_infixes ist in if not (all (flip elem opChars) op) || elem op invalidOperators then lift . tfail . Msg $ "'" ++ op ++ "' is not a valid operator name." else case nub [f | Fix f someOp <- fixities, someOp == op] of [] -> lift . tfail . Msg $ "No fixity found for operator '" ++ op ++ "'." [f] -> fmap fst . checkClosed $ reflectFixity f many -> lift . tfail . InternalMsg $ "Ambiguous fixity for '" ++ op ++ "'! Found " ++ show many _ -> lift . tfail . Msg $ "Not a constant string for an operator name: " ++ show opTm | n == tacN "Prim__Debug", [ty, msg] <- args = do msg' <- eval msg parts <- reifyReportParts msg debugElaborator parts runTacTm x = lift . tfail $ ElabScriptStuck x -- Running tactics directly -- if a tactic adds unification problems, return an error runTac :: Bool -> IState -> Maybe FC -> Name -> PTactic -> ElabD () runTac autoSolve ist perhapsFC fn tac = do env <- get_env g <- goal let tac' = fmap (addImplBound ist (map fst env)) tac if autoSolve then runT tac' else no_errors (runT tac') (Just (CantSolveGoal g (map (\(n, b) -> (n, binderTy b)) env))) where runT (Intro []) = do g <- goal attack; intro (bname g) where bname (Bind n _ _) = Just n bname _ = Nothing runT (Intro xs) = mapM_ (\x -> do attack; intro (Just x)) xs runT Intros = do g <- goal attack; intro (bname g) try' (runT Intros) (return ()) True where bname (Bind n _ _) = Just n bname _ = Nothing runT (Exact tm) = do elab ist toplevel ERHS [] (sMN 0 "tac") tm when autoSolve solveAll runT (MatchRefine fn) = do fnimps <- case lookupCtxtName fn (idris_implicits ist) of [] -> do a <- envArgs fn return [(fn, a)] ns -> return (map (\ (n, a) -> (n, map (const True) a)) ns) let tacs = map (\ (fn', imps) -> (match_apply (Var fn') (map (\x -> (x, 0)) imps), fn')) fnimps tryAll tacs when autoSolve solveAll where envArgs n = do e <- get_env case lookup n e of Just t -> return $ map (const False) (getArgTys (binderTy t)) _ -> return [] runT (Refine fn []) = do fnimps <- case lookupCtxtName fn (idris_implicits ist) of [] -> do a <- envArgs fn return [(fn, a)] ns -> return (map (\ (n, a) -> (n, map isImp a)) ns) let tacs = map (\ (fn', imps) -> (apply (Var fn') (map (\x -> (x, 0)) imps), fn')) fnimps tryAll tacs when autoSolve solveAll where isImp (PImp _ _ _ _ _) = True isImp _ = False envArgs n = do e <- get_env case lookup n e of Just t -> return $ map (const False) (getArgTys (binderTy t)) _ -> return [] runT (Refine fn imps) = do ns <- apply (Var fn) (map (\x -> (x,0)) imps) when autoSolve solveAll runT DoUnify = do unify_all when autoSolve solveAll runT (Claim n tm) = do tmHole <- getNameFrom (sMN 0 "newGoal") claim tmHole RType claim n (Var tmHole) focus tmHole elab ist toplevel ERHS [] (sMN 0 "tac") tm focus n runT (Equiv tm) -- let bind tm, then = do attack tyn <- getNameFrom (sMN 0 "ety") claim tyn RType valn <- getNameFrom (sMN 0 "eqval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "equiv_val") letbind letn (Var tyn) (Var valn) focus tyn elab ist toplevel ERHS [] (sMN 0 "tac") tm focus valn when autoSolve solveAll runT (Rewrite tm) -- to elaborate tm, let bind it, then rewrite by that = do attack; -- (h:_) <- get_holes tyn <- getNameFrom (sMN 0 "rty") -- start_unify h claim tyn RType valn <- getNameFrom (sMN 0 "rval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "rewrite_rule") letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel ERHS [] (sMN 0 "tac") tm rewrite (Var letn) when autoSolve solveAll runT (Induction tm) -- let bind tm, similar to the others = case_ True autoSolve ist fn tm runT (CaseTac tm) = case_ False autoSolve ist fn tm runT (LetTac n tm) = do attack tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letn <- unique_hole n letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel ERHS [] (sMN 0 "tac") tm when autoSolve solveAll runT (LetTacTy n ty tm) = do attack tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letn <- unique_hole n letbind letn (Var tyn) (Var valn) focus tyn elab ist toplevel ERHS [] (sMN 0 "tac") ty focus valn elab ist toplevel ERHS [] (sMN 0 "tac") tm when autoSolve solveAll runT Compute = compute runT Trivial = do trivial' ist; when autoSolve solveAll runT TCInstance = runT (Exact (PResolveTC emptyFC)) runT (ProofSearch rec prover depth top psns hints) = do proofSearch' ist rec False depth prover top fn psns hints when autoSolve solveAll runT (Focus n) = focus n runT Unfocus = do hs <- get_holes case hs of [] -> return () (h : _) -> movelast h runT Solve = solve runT (Try l r) = do try' (runT l) (runT r) True runT (TSeq l r) = do runT l; runT r runT (ApplyTactic tm) = do tenv <- get_env -- store the environment tgoal <- goal -- store the goal attack -- let f : List (TTName, Binder TT) -> TT -> Tactic = tm in ... script <- getNameFrom (sMN 0 "script") claim script scriptTy scriptvar <- getNameFrom (sMN 0 "scriptvar" ) letbind scriptvar scriptTy (Var script) focus script elab ist toplevel ERHS [] (sMN 0 "tac") tm (script', _) <- get_type_val (Var scriptvar) -- now that we have the script apply -- it to the reflected goal and context restac <- getNameFrom (sMN 0 "restac") claim restac tacticTy focus restac fill (raw_apply (forget script') [reflectEnv tenv, reflect tgoal]) restac' <- get_guess solve -- normalise the result in order to -- reify it ctxt <- get_context env <- get_env let tactic = normalise ctxt env restac' runReflected tactic where tacticTy = Var (reflm "Tactic") listTy = Var (sNS (sUN "List") ["List", "Prelude"]) scriptTy = (RBind (sMN 0 "__pi_arg") (Pi Nothing (RApp listTy envTupleType) RType) (RBind (sMN 1 "__pi_arg") (Pi Nothing (Var $ reflm "TT") RType) tacticTy)) runT (ByReflection tm) -- run the reflection function 'tm' on the -- goal, then apply the resulting reflected Tactic = do tgoal <- goal attack script <- getNameFrom (sMN 0 "script") claim script scriptTy scriptvar <- getNameFrom (sMN 0 "scriptvar" ) letbind scriptvar scriptTy (Var script) focus script ptm <- get_term elab ist toplevel ERHS [] (sMN 0 "tac") (PApp emptyFC tm [pexp (delabTy' ist [] tgoal True True)]) (script', _) <- get_type_val (Var scriptvar) -- now that we have the script apply -- it to the reflected goal restac <- getNameFrom (sMN 0 "restac") claim restac tacticTy focus restac fill (forget script') restac' <- get_guess solve -- normalise the result in order to -- reify it ctxt <- get_context env <- get_env let tactic = normalise ctxt env restac' runReflected tactic where tacticTy = Var (reflm "Tactic") scriptTy = tacticTy runT (Reflect v) = do attack -- let x = reflect v in ... tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "letvar") letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel ERHS [] (sMN 0 "tac") v (value, _) <- get_type_val (Var letn) ctxt <- get_context env <- get_env let value' = hnf ctxt env value runTac autoSolve ist perhapsFC fn (Exact $ PQuote (reflect value')) runT (Fill v) = do attack -- let x = fill x in ... tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "letvar") letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel ERHS [] (sMN 0 "tac") v (value, _) <- get_type_val (Var letn) ctxt <- get_context env <- get_env let value' = normalise ctxt env value rawValue <- reifyRaw value' runTac autoSolve ist perhapsFC fn (Exact $ PQuote rawValue) runT (GoalType n tac) = do g <- goal case unApply g of (P _ n' _, _) -> if nsroot n' == sUN n then runT tac else fail "Wrong goal type" _ -> fail "Wrong goal type" runT ProofState = do g <- goal return () runT Skip = return () runT (TFail err) = lift . tfail $ ReflectionError [err] (Msg "") runT SourceFC = case perhapsFC of Nothing -> lift . tfail $ Msg "There is no source location available." Just fc -> do fill $ reflectFC fc solve runT Qed = lift . tfail $ Msg "The qed command is only valid in the interactive prover" runT x = fail $ "Not implemented " ++ show x runReflected t = do t' <- reify ist t runTac autoSolve ist perhapsFC fn t' elaboratingArgErr :: [(Name, Name)] -> Err -> Err elaboratingArgErr [] err = err elaboratingArgErr ((f,x):during) err = fromMaybe err (rewrite err) where rewrite (ElaboratingArg _ _ _ _) = Nothing rewrite (ProofSearchFail e) = fmap ProofSearchFail (rewrite e) rewrite (At fc e) = fmap (At fc) (rewrite e) rewrite err = Just (ElaboratingArg f x during err) withErrorReflection :: Idris a -> Idris a withErrorReflection x = idrisCatch x (\ e -> handle e >>= ierror) where handle :: Err -> Idris Err handle e@(ReflectionError _ _) = do logLvl 3 "Skipping reflection of error reflection result" return e -- Don't do meta-reflection of errors handle e@(ReflectionFailed _ _) = do logLvl 3 "Skipping reflection of reflection failure" return e -- At and Elaborating are just plumbing - error reflection shouldn't rewrite them handle e@(At fc err) = do logLvl 3 "Reflecting body of At" err' <- handle err return (At fc err') handle e@(Elaborating what n ty err) = do logLvl 3 "Reflecting body of Elaborating" err' <- handle err return (Elaborating what n ty err') handle e@(ElaboratingArg f a prev err) = do logLvl 3 "Reflecting body of ElaboratingArg" hs <- getFnHandlers f a err' <- if null hs then handle err else applyHandlers err hs return (ElaboratingArg f a prev err') -- ProofSearchFail is an internal detail - so don't expose it handle (ProofSearchFail e) = handle e -- TODO: argument-specific error handlers go here for ElaboratingArg handle e = do ist <- getIState logLvl 2 "Starting error reflection" logLvl 5 (show e) let handlers = idris_errorhandlers ist applyHandlers e handlers getFnHandlers :: Name -> Name -> Idris [Name] getFnHandlers f arg = do ist <- getIState let funHandlers = maybe M.empty id . lookupCtxtExact f . idris_function_errorhandlers $ ist return . maybe [] S.toList . M.lookup arg $ funHandlers applyHandlers e handlers = do ist <- getIState let err = fmap (errReverse ist) e logLvl 3 $ "Using reflection handlers " ++ concat (intersperse ", " (map show handlers)) let reports = map (\n -> RApp (Var n) (reflectErr err)) handlers -- Typecheck error handlers - if this fails, then something else was wrong earlier! handlers <- case mapM (check (tt_ctxt ist) []) reports of Error e -> ierror $ ReflectionFailed "Type error while constructing reflected error" e OK hs -> return hs -- Normalize error handler terms to produce the new messages ctxt <- getContext let results = map (normalise ctxt []) (map fst handlers) logLvl 3 $ "New error message info: " ++ concat (intersperse " and " (map show results)) -- For each handler term output, either discard it if it is Nothing or reify it the Haskell equivalent let errorpartsTT = mapMaybe unList (mapMaybe fromTTMaybe results) errorparts <- case mapM (mapM reifyReportPart) errorpartsTT of Left err -> ierror err Right ok -> return ok return $ case errorparts of [] -> e parts -> ReflectionError errorparts e solveAll = try (do solve; solveAll) (return ()) -- | Do the left-over work after creating declarations in reflected -- elaborator scripts processTacticDecls :: ElabInfo -> [RDeclInstructions] -> Idris () processTacticDecls info steps = -- The order of steps is important: type declarations might -- establish metavars that later function bodies resolve. forM_ (reverse steps) $ \case RTyDeclInstrs n fc impls ty -> do logLvl 3 $ "Declaration from tactics: " ++ show n ++ " : " ++ show ty logLvl 3 $ " It has impls " ++ show impls updateIState $ \i -> i { idris_implicits = addDef n impls (idris_implicits i) } addIBC (IBCImp n) ds <- checkDef fc (\_ e -> e) [(n, (-1, Nothing, ty, []))] addIBC (IBCDef n) ctxt <- getContext case lookupDef n ctxt of (TyDecl _ _ : _) -> -- If the function isn't defined at the end of the elab script, -- then it must be added as a metavariable. This needs guarding -- to prevent overwriting case defs with a metavar, if the case -- defs come after the type decl in the same script! let ds' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, True))) ds in addDeferred ds' _ -> return () RAddInstance className instName -> do -- The type class resolution machinery relies on a special logLvl 2 $ "Adding elab script instance " ++ show instName ++ " for " ++ show className addInstance False True className instName addIBC (IBCInstance False True className instName) RClausesInstrs n cs -> do logLvl 3 $ "Pattern-matching definition from tactics: " ++ show n solveDeferred n let lhss = map (\(_, lhs, _) -> lhs) cs let fc = fileFC "elab_reflected" pmissing <- do ist <- getIState possible <- genClauses fc n lhss (map (\lhs -> delab' ist lhs True True) lhss) missing <- filterM (checkPossible n) possible return (filter (noMatch ist lhss) missing) let tot = if null pmissing then Unchecked -- still need to check recursive calls else Partial NotCovering -- missing cases implies not total setTotality n tot updateIState $ \i -> i { idris_patdefs = addDef n (cs, pmissing) $ idris_patdefs i } addIBC (IBCDef n) ctxt <- getContext case lookupDefExact n ctxt of Just (CaseOp _ _ _ _ _ cd) -> -- Here, we populate the call graph with a list of things -- we refer to, so that if they aren't total, the whole -- thing won't be. let (scargs, sc) = cases_compiletime cd (scargs', sc') = cases_runtime cd calls = findCalls sc' scargs used = findUsedArgs sc' scargs' cg = CGInfo scargs' calls [] used [] in do logLvl 2 $ "Called names in reflected elab: " ++ show cg addToCG n cg addToCalledG n (nub (map fst calls)) addIBC $ IBCCG n Just _ -> return () -- TODO throw internal error Nothing -> return () -- checkDeclTotality requires that the call graph be present -- before calling it. -- TODO: reduce code duplication with Idris.Elab.Clause buildSCG (fc, n) -- Actually run the totality checker. In the main clause -- elaborator, this is deferred until after. Here, we run it -- now to get totality information as early as possible. tot' <- checkDeclTotality (fc, n) setTotality n tot' when (tot' /= Unchecked) $ addIBC (IBCTotal n tot') where -- TODO: see if the code duplication with Idris.Elab.Clause can be -- reduced or eliminated. checkPossible :: Name -> PTerm -> Idris Bool checkPossible fname lhs_in = do ctxt <- getContext ist <- getIState let lhs = addImplPat ist lhs_in let fc = fileFC "elab_reflected_totality" let tcgen = False -- TODO: later we may support dictionary generation case elaborate ctxt (idris_datatypes ist) (sMN 0 "refPatLHS") infP initEState (erun fc (buildTC ist info ELHS [] fname (allNamesIn lhs_in) (infTerm lhs))) of OK (ElabResult lhs' _ _ _ _ _, _) -> do -- not recursively calling here, because we don't -- want to run infinitely many times let lhs_tm = orderPats (getInferTerm lhs') case recheck ctxt [] (forget lhs_tm) lhs_tm of OK _ -> return True err -> return False -- if it's a recoverable error, the case may become possible Error err -> if tcgen then return (recoverableCoverage ctxt err) else return (validCoverageCase ctxt err || recoverableCoverage ctxt err) -- TODO: Attempt to reduce/eliminate code duplication with Idris.Elab.Clause noMatch i cs tm = all (\x -> case matchClause i (delab' i x True True) tm of Right _ -> False Left _ -> True) cs
adnelson/Idris-dev
src/Idris/Elab/Term.hs
Haskell
bsd-3-clause
119,645
-- (c) The University of Glasgow, 1997-2006 {-# LANGUAGE BangPatterns, CPP, DeriveDataTypeable, MagicHash, UnboxedTuples #-} {-# OPTIONS_GHC -O -funbox-strict-fields #-} -- We always optimise this, otherwise performance of a non-optimised -- compiler is severely affected -- | -- There are two principal string types used internally by GHC: -- -- ['FastString'] -- -- * A compact, hash-consed, representation of character strings. -- * Comparison is O(1), and you can get a 'Unique.Unique' from them. -- * Generated by 'fsLit'. -- * Turn into 'Outputable.SDoc' with 'Outputable.ftext'. -- -- ['LitString'] -- -- * Just a wrapper for the @Addr#@ of a C string (@Ptr CChar@). -- * Practically no operations. -- * Outputing them is fast. -- * Generated by 'sLit'. -- * Turn into 'Outputable.SDoc' with 'Outputable.ptext' -- -- Use 'LitString' unless you want the facilities of 'FastString'. module FastString ( -- * ByteString fastStringToByteString, mkFastStringByteString, fastZStringToByteString, unsafeMkByteString, hashByteString, -- * FastZString FastZString, hPutFZS, zString, lengthFZS, -- * FastStrings FastString(..), -- not abstract, for now. -- ** Construction fsLit, mkFastString, mkFastStringBytes, mkFastStringByteList, mkFastStringForeignPtr, mkFastString#, -- ** Deconstruction unpackFS, -- :: FastString -> String bytesFS, -- :: FastString -> [Word8] -- ** Encoding zEncodeFS, -- ** Operations uniqueOfFS, lengthFS, nullFS, appendFS, headFS, tailFS, concatFS, consFS, nilFS, -- ** Outputing hPutFS, -- ** Internal getFastStringTable, hasZEncoding, -- * LitStrings LitString, -- ** Construction sLit, mkLitString#, mkLitString, -- ** Deconstruction unpackLitString, -- ** Operations lengthLS ) where #include "HsVersions.h" import Encoding import FastFunctions import Panic import Util import Control.Monad import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Internal as BS import qualified Data.ByteString.Unsafe as BS import Foreign.C import GHC.Exts import System.IO import System.IO.Unsafe ( unsafePerformIO ) import Data.Data import Data.IORef ( IORef, newIORef, readIORef, atomicModifyIORef' ) import Data.Maybe ( isJust ) import Data.Char import Data.List ( elemIndex ) import GHC.IO ( IO(..), unsafeDupablePerformIO ) import Foreign #if STAGE >= 2 import GHC.Conc.Sync (sharedCAF) #endif import GHC.Base ( unpackCString# ) #define hASH_TBL_SIZE 4091 #define hASH_TBL_SIZE_UNBOXED 4091# fastStringToByteString :: FastString -> ByteString fastStringToByteString f = fs_bs f fastZStringToByteString :: FastZString -> ByteString fastZStringToByteString (FastZString bs) = bs -- This will drop information if any character > '\xFF' unsafeMkByteString :: String -> ByteString unsafeMkByteString = BSC.pack hashByteString :: ByteString -> Int hashByteString bs = inlinePerformIO $ BS.unsafeUseAsCStringLen bs $ \(ptr, len) -> return $ hashStr (castPtr ptr) len -- ----------------------------------------------------------------------------- newtype FastZString = FastZString ByteString hPutFZS :: Handle -> FastZString -> IO () hPutFZS handle (FastZString bs) = BS.hPut handle bs zString :: FastZString -> String zString (FastZString bs) = inlinePerformIO $ BS.unsafeUseAsCStringLen bs peekCAStringLen lengthFZS :: FastZString -> Int lengthFZS (FastZString bs) = BS.length bs mkFastZStringString :: String -> FastZString mkFastZStringString str = FastZString (BSC.pack str) -- ----------------------------------------------------------------------------- {-| A 'FastString' is an array of bytes, hashed to support fast O(1) comparison. It is also associated with a character encoding, so that we know how to convert a 'FastString' to the local encoding, or to the Z-encoding used by the compiler internally. 'FastString's support a memoized conversion to the Z-encoding via zEncodeFS. -} data FastString = FastString { uniq :: {-# UNPACK #-} !Int, -- unique id n_chars :: {-# UNPACK #-} !Int, -- number of chars fs_bs :: {-# UNPACK #-} !ByteString, fs_ref :: {-# UNPACK #-} !(IORef (Maybe FastZString)) } deriving Typeable instance Eq FastString where f1 == f2 = uniq f1 == uniq f2 instance Ord FastString where -- Compares lexicographically, not by unique a <= b = case cmpFS a b of { LT -> True; EQ -> True; GT -> False } a < b = case cmpFS a b of { LT -> True; EQ -> False; GT -> False } a >= b = case cmpFS a b of { LT -> False; EQ -> True; GT -> True } a > b = case cmpFS a b of { LT -> False; EQ -> False; GT -> True } max x y | x >= y = x | otherwise = y min x y | x <= y = x | otherwise = y compare a b = cmpFS a b instance Monoid FastString where mempty = nilFS mappend = appendFS instance Show FastString where show fs = show (unpackFS fs) instance Data FastString where -- don't traverse? toConstr _ = abstractConstr "FastString" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "FastString" cmpFS :: FastString -> FastString -> Ordering cmpFS f1@(FastString u1 _ _ _) f2@(FastString u2 _ _ _) = if u1 == u2 then EQ else compare (fastStringToByteString f1) (fastStringToByteString f2) foreign import ccall unsafe "ghc_memcmp" memcmp :: Ptr a -> Ptr b -> Int -> IO Int -- ----------------------------------------------------------------------------- -- Construction {- Internally, the compiler will maintain a fast string symbol table, providing sharing and fast comparison. Creation of new @FastString@s then covertly does a lookup, re-using the @FastString@ if there was a hit. The design of the FastString hash table allows for lockless concurrent reads and updates to multiple buckets with low synchronization overhead. See Note [Updating the FastString table] on how it's updated. -} data FastStringTable = FastStringTable {-# UNPACK #-} !(IORef Int) -- the unique ID counter shared with all buckets (MutableArray# RealWorld (IORef [FastString])) -- the array of mutable buckets string_table :: FastStringTable {-# NOINLINE string_table #-} string_table = unsafePerformIO $ do uid <- newIORef 603979776 -- ord '$' * 0x01000000 tab <- IO $ \s1# -> case newArray# hASH_TBL_SIZE_UNBOXED (panic "string_table") s1# of (# s2#, arr# #) -> (# s2#, FastStringTable uid arr# #) forM_ [0.. hASH_TBL_SIZE-1] $ \i -> do bucket <- newIORef [] updTbl tab i bucket -- use the support wired into the RTS to share this CAF among all images of -- libHSghc #if STAGE < 2 return tab #else sharedCAF tab getOrSetLibHSghcFastStringTable -- from the RTS; thus we cannot use this mechanism when STAGE<2; the previous -- RTS might not have this symbol foreign import ccall unsafe "getOrSetLibHSghcFastStringTable" getOrSetLibHSghcFastStringTable :: Ptr a -> IO (Ptr a) #endif {- We include the FastString table in the `sharedCAF` mechanism because we'd like FastStrings created by a Core plugin to have the same uniques as corresponding strings created by the host compiler itself. For example, this allows plugins to lookup known names (eg `mkTcOcc "MySpecialType"`) in the GlobalRdrEnv or even re-invoke the parser. In particular, the following little sanity test was failing in a plugin prototyping safe newtype-coercions: GHC.NT.Type.NT was imported, but could not be looked up /by the plugin/. let rdrName = mkModuleName "GHC.NT.Type" `mkRdrQual` mkTcOcc "NT" putMsgS $ showSDoc dflags $ ppr $ lookupGRE_RdrName rdrName $ mg_rdr_env guts `mkTcOcc` involves the lookup (or creation) of a FastString. Since the plugin's FastString.string_table is empty, constructing the RdrName also allocates new uniques for the FastStrings "GHC.NT.Type" and "NT". These uniques are almost certainly unequal to the ones that the host compiler originally assigned to those FastStrings. Thus the lookup fails since the domain of the GlobalRdrEnv is affected by the RdrName's OccName's FastString's unique. The old `reinitializeGlobals` mechanism is enough to provide the plugin with read-access to the table, but it insufficient in the general case where the plugin may allocate FastStrings. This mutates the supply for the FastStrings' unique, and that needs to be propagated back to the compiler's instance of the global variable. Such propagation is beyond the `reinitializeGlobals` mechanism. Maintaining synchronization of the two instances of this global is rather difficult because of the uses of `unsafePerformIO` in this module. Not synchronizing them risks breaking the rather major invariant that two FastStrings with the same unique have the same string. Thus we use the lower-level `sharedCAF` mechanism that relies on Globals.c. -} lookupTbl :: FastStringTable -> Int -> IO (IORef [FastString]) lookupTbl (FastStringTable _ arr#) (I# i#) = IO $ \ s# -> readArray# arr# i# s# updTbl :: FastStringTable -> Int -> IORef [FastString] -> IO () updTbl (FastStringTable _uid arr#) (I# i#) ls = do (IO $ \ s# -> case writeArray# arr# i# ls s# of { s2# -> (# s2#, () #) }) mkFastString# :: Addr# -> FastString mkFastString# a# = mkFastStringBytes ptr (ptrStrLength ptr) where ptr = Ptr a# {- Note [Updating the FastString table] The procedure goes like this: 1. Read the relevant bucket and perform a look up of the string. 2. If it exists, return it. 3. Otherwise grab a unique ID, create a new FastString and atomically attempt to update the relevant bucket with this FastString: * Double check that the string is not in the bucket. Another thread may have inserted it while we were creating our string. * Return the existing FastString if it exists. The one we preemptively created will get GCed. * Otherwise, insert and return the string we created. -} {- Note [Double-checking the bucket] It is not necessary to check the entire bucket the second time. We only have to check the strings that are new to the bucket since the last time we read it. -} mkFastStringWith :: (Int -> IO FastString) -> Ptr Word8 -> Int -> IO FastString mkFastStringWith mk_fs !ptr !len = do let hash = hashStr ptr len bucket <- lookupTbl string_table hash ls1 <- readIORef bucket res <- bucket_match ls1 len ptr case res of Just v -> return v Nothing -> do n <- get_uid new_fs <- mk_fs n atomicModifyIORef' bucket $ \ls2 -> -- Note [Double-checking the bucket] let delta_ls = case ls1 of [] -> ls2 l:_ -> case l `elemIndex` ls2 of Nothing -> panic "mkFastStringWith" Just idx -> take idx ls2 -- NB: Might as well use inlinePerformIO, since the call to -- bucket_match doesn't perform any IO that could be floated -- out of this closure or erroneously duplicated. in case inlinePerformIO (bucket_match delta_ls len ptr) of Nothing -> (new_fs:ls2, new_fs) Just fs -> (ls2,fs) where !(FastStringTable uid _arr) = string_table get_uid = atomicModifyIORef' uid $ \n -> (n+1,n) mkFastStringBytes :: Ptr Word8 -> Int -> FastString mkFastStringBytes !ptr !len = -- NB: Might as well use unsafeDupablePerformIO, since mkFastStringWith is -- idempotent. unsafeDupablePerformIO $ mkFastStringWith (copyNewFastString ptr len) ptr len -- | Create a 'FastString' from an existing 'ForeignPtr'; the difference -- between this and 'mkFastStringBytes' is that we don't have to copy -- the bytes if the string is new to the table. mkFastStringForeignPtr :: Ptr Word8 -> ForeignPtr Word8 -> Int -> IO FastString mkFastStringForeignPtr ptr !fp len = mkFastStringWith (mkNewFastString fp ptr len) ptr len -- | Create a 'FastString' from an existing 'ForeignPtr'; the difference -- between this and 'mkFastStringBytes' is that we don't have to copy -- the bytes if the string is new to the table. mkFastStringByteString :: ByteString -> FastString mkFastStringByteString bs = inlinePerformIO $ BS.unsafeUseAsCStringLen bs $ \(ptr, len) -> do let ptr' = castPtr ptr mkFastStringWith (mkNewFastStringByteString bs ptr' len) ptr' len -- | Creates a UTF-8 encoded 'FastString' from a 'String' mkFastString :: String -> FastString mkFastString str = inlinePerformIO $ do let l = utf8EncodedLength str buf <- mallocForeignPtrBytes l withForeignPtr buf $ \ptr -> do utf8EncodeString ptr str mkFastStringForeignPtr ptr buf l -- | Creates a 'FastString' from a UTF-8 encoded @[Word8]@ mkFastStringByteList :: [Word8] -> FastString mkFastStringByteList str = inlinePerformIO $ do let l = Prelude.length str buf <- mallocForeignPtrBytes l withForeignPtr buf $ \ptr -> do pokeArray (castPtr ptr) str mkFastStringForeignPtr ptr buf l -- | Creates a Z-encoded 'FastString' from a 'String' mkZFastString :: String -> FastZString mkZFastString = mkFastZStringString bucket_match :: [FastString] -> Int -> Ptr Word8 -> IO (Maybe FastString) bucket_match [] _ _ = return Nothing bucket_match (v@(FastString _ _ bs _):ls) len ptr | len == BS.length bs = do b <- BS.unsafeUseAsCString bs $ \buf -> cmpStringPrefix ptr (castPtr buf) len if b then return (Just v) else bucket_match ls len ptr | otherwise = bucket_match ls len ptr mkNewFastString :: ForeignPtr Word8 -> Ptr Word8 -> Int -> Int -> IO FastString mkNewFastString fp ptr len uid = do ref <- newIORef Nothing n_chars <- countUTF8Chars ptr len return (FastString uid n_chars (BS.fromForeignPtr fp 0 len) ref) mkNewFastStringByteString :: ByteString -> Ptr Word8 -> Int -> Int -> IO FastString mkNewFastStringByteString bs ptr len uid = do ref <- newIORef Nothing n_chars <- countUTF8Chars ptr len return (FastString uid n_chars bs ref) copyNewFastString :: Ptr Word8 -> Int -> Int -> IO FastString copyNewFastString ptr len uid = do fp <- copyBytesToForeignPtr ptr len ref <- newIORef Nothing n_chars <- countUTF8Chars ptr len return (FastString uid n_chars (BS.fromForeignPtr fp 0 len) ref) copyBytesToForeignPtr :: Ptr Word8 -> Int -> IO (ForeignPtr Word8) copyBytesToForeignPtr ptr len = do fp <- mallocForeignPtrBytes len withForeignPtr fp $ \ptr' -> copyBytes ptr' ptr len return fp cmpStringPrefix :: Ptr Word8 -> Ptr Word8 -> Int -> IO Bool cmpStringPrefix ptr1 ptr2 len = do r <- memcmp ptr1 ptr2 len return (r == 0) hashStr :: Ptr Word8 -> Int -> Int -- use the Addr to produce a hash value between 0 & m (inclusive) hashStr (Ptr a#) (I# len#) = loop 0# 0# where loop h n | isTrue# (n ==# len#) = I# h | otherwise = loop h2 (n +# 1#) where !c = ord# (indexCharOffAddr# a# n) !h2 = (c +# (h *# 128#)) `remInt#` hASH_TBL_SIZE# -- ----------------------------------------------------------------------------- -- Operations -- | Returns the length of the 'FastString' in characters lengthFS :: FastString -> Int lengthFS f = n_chars f -- | Returns @True@ if this 'FastString' is not Z-encoded but already has -- a Z-encoding cached (used in producing stats). hasZEncoding :: FastString -> Bool hasZEncoding (FastString _ _ _ ref) = inlinePerformIO $ do m <- readIORef ref return (isJust m) -- | Returns @True@ if the 'FastString' is empty nullFS :: FastString -> Bool nullFS f = BS.null (fs_bs f) -- | Unpacks and decodes the FastString unpackFS :: FastString -> String unpackFS (FastString _ _ bs _) = inlinePerformIO $ BS.unsafeUseAsCStringLen bs $ \(ptr, len) -> utf8DecodeString (castPtr ptr) len -- | Gives the UTF-8 encoded bytes corresponding to a 'FastString' bytesFS :: FastString -> [Word8] bytesFS fs = BS.unpack $ fastStringToByteString fs -- | Returns a Z-encoded version of a 'FastString'. This might be the -- original, if it was already Z-encoded. The first time this -- function is applied to a particular 'FastString', the results are -- memoized. -- zEncodeFS :: FastString -> FastZString zEncodeFS fs@(FastString _ _ _ ref) = inlinePerformIO $ do m <- readIORef ref case m of Just zfs -> return zfs Nothing -> do atomicModifyIORef' ref $ \m' -> case m' of Nothing -> let zfs = mkZFastString (zEncodeString (unpackFS fs)) in (Just zfs, zfs) Just zfs -> (m', zfs) appendFS :: FastString -> FastString -> FastString appendFS fs1 fs2 = mkFastStringByteString $ BS.append (fastStringToByteString fs1) (fastStringToByteString fs2) concatFS :: [FastString] -> FastString concatFS ls = mkFastString (Prelude.concat (map unpackFS ls)) -- ToDo: do better headFS :: FastString -> Char headFS (FastString _ 0 _ _) = panic "headFS: Empty FastString" headFS (FastString _ _ bs _) = inlinePerformIO $ BS.unsafeUseAsCString bs $ \ptr -> return (fst (utf8DecodeChar (castPtr ptr))) tailFS :: FastString -> FastString tailFS (FastString _ 0 _ _) = panic "tailFS: Empty FastString" tailFS (FastString _ _ bs _) = inlinePerformIO $ BS.unsafeUseAsCString bs $ \ptr -> do let (_, n) = utf8DecodeChar (castPtr ptr) return $! mkFastStringByteString (BS.drop n bs) consFS :: Char -> FastString -> FastString consFS c fs = mkFastString (c : unpackFS fs) uniqueOfFS :: FastString -> Int uniqueOfFS (FastString u _ _ _) = u nilFS :: FastString nilFS = mkFastString "" -- ----------------------------------------------------------------------------- -- Stats getFastStringTable :: IO [[FastString]] getFastStringTable = do buckets <- forM [0.. hASH_TBL_SIZE-1] $ \idx -> do bucket <- lookupTbl string_table idx readIORef bucket return buckets -- ----------------------------------------------------------------------------- -- Outputting 'FastString's -- |Outputs a 'FastString' with /no decoding at all/, that is, you -- get the actual bytes in the 'FastString' written to the 'Handle'. hPutFS :: Handle -> FastString -> IO () hPutFS handle fs = BS.hPut handle $ fastStringToByteString fs -- ToDo: we'll probably want an hPutFSLocal, or something, to output -- in the current locale's encoding (for error messages and suchlike). -- ----------------------------------------------------------------------------- -- LitStrings, here for convenience only. type LitString = Ptr Word8 --Why do we recalculate length every time it's requested? --If it's commonly needed, we should perhaps have --data LitString = LitString {-#UNPACK#-}!Addr# {-#UNPACK#-}!Int# mkLitString# :: Addr# -> LitString mkLitString# a# = Ptr a# {-# INLINE mkLitString #-} mkLitString :: String -> LitString mkLitString s = unsafePerformIO (do p <- mallocBytes (length s + 1) let loop :: Int -> String -> IO () loop !n [] = pokeByteOff p n (0 :: Word8) loop n (c:cs) = do pokeByteOff p n (fromIntegral (ord c) :: Word8) loop (1+n) cs loop 0 s return p ) unpackLitString :: LitString -> String unpackLitString (Ptr p) = unpackCString# p lengthLS :: LitString -> Int lengthLS = ptrStrLength -- ----------------------------------------------------------------------------- -- under the carpet foreign import ccall unsafe "ghc_strlen" ptrStrLength :: Ptr Word8 -> Int {-# NOINLINE sLit #-} sLit :: String -> LitString sLit x = mkLitString x {-# NOINLINE fsLit #-} fsLit :: String -> FastString fsLit x = mkFastString x {-# RULES "slit" forall x . sLit (unpackCString# x) = mkLitString# x #-} {-# RULES "fslit" forall x . fsLit (unpackCString# x) = mkFastString# x #-}
tjakway/ghcjvm
compiler/utils/FastString.hs
Haskell
bsd-3-clause
20,477
module Foo where {-@ LIQUID "--no-termination" @-} {-@ LIQUID "--native" @-} {-@ foo :: {v:a | false} @-} foo = foo nat :: Int {-@ nat :: Nat @-} nat = 42
ssaavedra/liquidhaskell
tests/todo/false.hs
Haskell
bsd-3-clause
160
{-# LANGUAGE MagicHash, FlexibleInstances, MultiParamTypeClasses, TypeFamilies, PolyKinds, DataKinds, FunctionalDependencies, TypeFamilyDependencies #-} module T17541 where import GHC.Prim import GHC.Exts type family Rep rep where Rep Int = IntRep type family Unboxed rep = (urep :: TYPE (Rep rep)) | urep -> rep where Unboxed Int = Int#
sdiehl/ghc
testsuite/tests/dependent/should_fail/T17541.hs
Haskell
bsd-3-clause
450
module E4 where --Any type/data constructor name declared in this module can be renamed. --Any type variable can be renamed. --Rename type Constructor 'BTree' to 'MyBTree' data BTree a = Empty | T a (BTree a) (BTree a) deriving Show buildtree :: (Monad m, Ord a) => [a] -> m (BTree a) buildtree [] = return Empty buildtree (x:xs) = do res1 <- buildtree xs res <- insert x res1 return res insert :: (Monad m, Ord a) => a -> BTree a -> m (BTree a) insert val v2 = do case v2 of T val Empty Empty | val == val -> return Empty | otherwise -> return (T val Empty (T val Empty Empty)) T val (T val2 Empty Empty) Empty -> return Empty _ -> return v2 main :: IO () main = do (a,T val Empty Empty) <- buildtree [3,1,2] putStrLn $ show (T val Empty Empty)
SAdams601/HaRe
old/testing/asPatterns/E4.hs
Haskell
bsd-3-clause
1,008
{-# LANGUAGE TypeInType, GADTs #-} module T11811 where import Data.Kind data Test (a :: x) (b :: x) :: x -> * where K :: Test Int Bool Double
olsner/ghc
testsuite/tests/typecheck/should_compile/T11811.hs
Haskell
bsd-3-clause
147
-- Test for Trac #2188 module TH_scope where f g = [d| f :: Int f = g g :: Int g = 4 |]
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/th/TH_scope.hs
Haskell
bsd-3-clause
120
-- read.hs -- read a file import System.IO main = do withFile "song.txt" ReadMode (\handle -> do contents <- hGetContents handle putStr contents)
doylew/practice
haskell/file.hs
Haskell
mit
158
-- | -- Module : HGE2D.Time -- Copyright : (c) 2016 Martin Buck -- License : see LICENSE -- -- Containing functions to get the current time or transform times module HGE2D.Time where import HGE2D.Types import Data.Time.Clock -------------------------------------------------------------------------------- -- | Get the current time in seconds getSeconds :: IO Double getSeconds = getCurrentTime >>= return . fromRational . toRational . utctDayTime -------------------------------------------------------------------------------- -- | Transform seconds to milliseconds toMilliSeconds :: Double -> Millisecond toMilliSeconds secs = floor $ 1000 * secs
I3ck/HGE2D
src/HGE2D/Time.hs
Haskell
mit
671
-- Algorithms/Strings/Game of Thrones - I module HackerRank.Algorithms.GameOfThrones1 where import Data.Hashable (Hashable) import qualified Data.HashMap.Strict as M data Answer = YES | NO deriving (Show) mkAnswer :: Bool -> Answer mkAnswer True = YES mkAnswer False = NO freqMap :: (Hashable a, Ord a) => [a] -> M.HashMap a Int freqMap xs = freqMap_ xs M.empty freqMap_ :: (Hashable a, Ord a) => [a] -> M.HashMap a Int -> M.HashMap a Int freqMap_ [] m = m freqMap_ (x:xs) m = freqMap_ xs $ M.insertWith (+) x 1 m isSymmetric :: (Hashable a, Ord a) => [a] -> Bool isSymmetric xs = let eles = M.elems $ freqMap xs odds = filter odd eles in length odds <= 1 main :: IO () main = do s <- getLine let a = mkAnswer $ isSymmetric s print a
4e6/sandbox
haskell/HackerRank/Algorithms/GameOfThrones1.hs
Haskell
mit
791
{-# LANGUAGE RankNTypes #-} -- | @SkipList@s are comprised of a list and an index on top of it -- which makes deep indexing into the list more efficient (O(log n)). -- They achieve this by essentially memoizing the @tail@ function to -- create a balanced tree. -- -- NOTE: @SkipList@s are /amortized/ efficient, see the benchmarks for -- performance results. module Data.SkipList ( SkipList , toSkipList , lookup ) where import Prelude hiding (lookup) -- | A SkipIndex stores "pointers" into the tail of a list for efficient -- deep indexing. If you have -- SkipIndex ls i -- and the quantization is `q` then the elements of `q` are "pointers" -- into every `q`th tail of the list. For example, if `q` = 2 and -- `ls = [1,2,3,4,5,6,7]`, then the frist level of `i` contains: -- [1,2,3,4,5,6,7], [3,4,5,6,7], [5,6,7], [7] -- the next level of `i` conceptually contains: -- [1,2,3,4,5,6,7], [5,6,7] -- Note however, that these are not lists, but rather references to -- @SkipIndex@s from `i` data SkipIndex a = SkipIndex ![a] (SkipIndex (SkipIndex a)) -- | @SkipList@s are lists that support amortized efficient indexing. data SkipList a = SkipList !Int (SkipIndex a) instance Functor SkipList where fmap f (SkipList q (SkipIndex raw _)) = toSkipList q $ f <$> raw instance Foldable SkipList where foldMap f (SkipList _ (SkipIndex ls _)) = foldMap f ls -- | Convert a list to a @SkipList@. toSkipList :: Int -- ^ The step size in the index. -> [a] -- ^ The list to convert. -> SkipList a toSkipList quant = SkipList quant . toSkipIndex quant -- | Build the infinite tree of skips. toSkipIndex :: Int -> [a] -> SkipIndex a toSkipIndex quant | quant > 1 = \ ls -> let self = SkipIndex ls $ toSkipIndex quant (self : rest) rest = toSkipIndex quant <$> fastTails ls in self | otherwise = error "Can not make SkipList with quantization <= 1" where fastTails ls = dropped : fastTails dropped where dropped = drop quant ls -- | Lookup in a @SkipList@. lookup :: SkipList a -> Int -> a lookup (SkipList q (SkipIndex ls index)) i | i >= q = get q q (\ (SkipIndex a _) -> (!!) a) index i | otherwise = ls !! i -- | Get an element from a @SkipIndex@. get :: Int -- ^ The step increment in the index -> Int -- ^ The current step size -> (b -> Int -> a) -- ^ Continuation to call with the result -> SkipIndex b -- ^ The index to look in -> Int -- ^ The position to look for -> a get q stepSize kont (SkipIndex here next) n | n >= q * stepSize = get q (q*stepSize) (get q stepSize kont) next n | otherwise = kont (here !! idx) rest where idx = n `div` stepSize rest = n `mod` stepSize
gmalecha/skip-list
src/Data/SkipList.hs
Haskell
mit
2,746
-- A permutation is an ordered arrangement of objects. For example, -- 3124 is one possible permutation of the digits 1, 2, 3 and 4. If -- all of the permutations are listed numerically or alphabetically, -- we call it lexicographic order. The lexicographic permutations of -- 0, 1 and 2 are: -- 012 021 102 120 201 210 -- What is the millionth lexicographic permutation of the digits 0, 1, -- 2, 3, 4, 5, 6, 7, 8 and 9? module Euler.Problem024 ( solution , nthLexicographicPermutation , permutationCount ) where import Data.List (delete, sort) import Euler.Factorial (factorial) solution :: Int -> Int solution n = read $ nthLexicographicPermutation n "0123456789" nthLexicographicPermutation :: Ord a => Int -> [a] -> [a] nthLexicographicPermutation i as | i < 1 = error "index out of range" | (i - 1) > permutationCount as = error "index out of range" | otherwise = lexPerm (i - 1) (sort as) -- The private version of nthLexicographicPermutation. Assumes that -- the list is sorted, that the index is 0-based, and that there exist -- sufficient permutations of the list to satisfy the index. lexPerm :: Ord a => Int -> [a] -> [a] lexPerm 0 as = as lexPerm _ [] = error "permutations exhausted" lexPerm i as = a : lexPerm (i - k * step) (delete a as) where a = as !! k k = i `div` step step = permutationCount $ tail as permutationCount :: [a] -> Int permutationCount = factorial . length
whittle/euler
src/Euler/Problem024.hs
Haskell
mit
1,462
module Data.Streaming.Process.Internal ( StreamingProcessHandle (..) , InputSource (..) , OutputSink (..) ) where import Control.Concurrent.STM (TMVar) import System.Exit (ExitCode) import System.IO (Handle) import System.Process (ProcessHandle, StdStream (CreatePipe)) -- | Class for all things which can be used to provide standard input. -- -- Since 0.1.4 class InputSource a where isStdStream :: (Maybe Handle -> IO a, Maybe StdStream) instance InputSource Handle where isStdStream = (\(Just h) -> return h, Just CreatePipe) -- | Class for all things which can be used to consume standard output or -- error. -- -- Since 0.1.4 class OutputSink a where osStdStream :: (Maybe Handle -> IO a, Maybe StdStream) instance OutputSink Handle where osStdStream = (\(Just h) -> return h, Just CreatePipe) -- | Wraps up the standard @ProcessHandle@ to avoid the @waitForProcess@ -- deadlock. See the linked documentation from the module header for more -- information. -- -- Since 0.1.4 data StreamingProcessHandle = StreamingProcessHandle ProcessHandle (TMVar ExitCode) (IO ()) -- cleanup resources
fpco/streaming-commons
Data/Streaming/Process/Internal.hs
Haskell
mit
1,213
module PrintProof where import Data.IORef import Control.Monad (liftM) import NarrowingSearch import Syntax prMeta :: MMetavar a -> (a -> IO String) -> IO String prMeta m prv = do b <- readIORef $ mbind m case b of Nothing -> return $ "?" ++ show (mid m) Just v -> prv v prProof :: Int -> MetaProof -> IO String prProof ctx p = prMeta p $ \p -> case p of Intro p -> prIntro ctx p Elim hyp p -> do hyp <- prHyp ctx hyp p <- prProofElim ctx p return $ "(elim " ++ hyp ++ " " ++ p ++ ")" RAA p -> do p <- prProof (ctx + 1) p return $ "(RAA (\\#" ++ show ctx ++ "." ++ p ++ "))" prIntro :: Int -> MetaIntro -> IO String prIntro ctx p = prMeta p $ \p -> case p of OrIl p -> do p <- prProof ctx p return $ "(Or-Il " ++ p ++ ")" OrIr p -> do p <- prProof ctx p return $ "(Or-Ir " ++ p ++ ")" AndI p1 p2 -> do p1 <- prProof ctx p1 p2 <- prProof ctx p2 return $ "(And-I " ++ p1 ++ " " ++ p2 ++ ")" ExistsI f p -> do f <- prForm ctx $ Meta f p <- prProof ctx p return $ "(Exists-I " ++ f ++ " " ++ p ++ ")" ImpliesI p -> do p <- prProof (ctx + 1) p return $ "(Implies-I (\\#" ++ show ctx ++ "." ++ p ++ "))" NotI p -> do p <- prProof (ctx + 1) p return $ "(Not-I (\\#" ++ show ctx ++ "." ++ p ++ "))" ForallI p -> do p <- prProof (ctx + 1) p return $ "(Forall-I (\\#" ++ show ctx ++ "." ++ p ++ "))" TopI -> return "Top-I" EqI p -> do p <- prProofEq ctx p return $ "(=-I " ++ p ++ ")" prHyp :: Int -> MetaHyp -> IO String prHyp ctx hyp = prMeta hyp $ \(Hyp elr _) -> case elr of HVar v -> return $ "#" ++ show (ctx - v - 1) HGlob gh -> return $ "<<" ++ ghName gh ++ ">>" AC typ qf p -> do typ <- prType $ Meta typ qf <- prForm ctx $ Meta qf p <- prProof ctx p return $ "(AC " ++ typ ++ " " ++ qf ++ " " ++ p ++ ")" prProofElim :: Int -> MetaProofElim -> IO String prProofElim ctx p = prMeta p $ \p -> case p of Use p -> do p <- prProofEqSimp ctx p return $ "(use " ++ p ++ ")" ElimStep p -> prElimStep ctx p prProofEqElim :: Int -> MetaProofEqElim -> IO String prProofEqElim ctx p = prMeta p $ \p -> case p of UseEq -> return "use-eq" UseEqSym -> return "use-eq-sym" EqElimStep p -> prEqElimStep ctx p prEqElimStep :: Int -> MetaEqElimStep -> IO String prEqElimStep ctx p = prMeta p $ \p -> case p of NTEqElimStep p -> prNTElimStep (prProofEqElim ctx) ctx p prElimStep :: Int -> MetaElimStep -> IO String prElimStep ctx p = prMeta p $ \p -> case p of BotE -> return "Bot-E" NotE p -> do p <- prProof ctx p return $ "(Not-E " ++ p ++ ")" OrE p1 p2 -> do p1 <- prProof (ctx + 1) p1 p2 <- prProof (ctx + 1) p2 return $ "(Or-E " ++ p1 ++ " " ++ p2 ++ ")" NTElimStep p -> prNTElimStep (prProofElim ctx) ctx p prNTElimStep :: (a -> IO String) -> Int -> NTElimStep a -> IO String prNTElimStep pr ctx p = case p of AndEl p -> do p <- pr p return $ "(And-El " ++ p ++ ")" AndEr p -> do p <- pr p return $ "(And-Er " ++ p ++ ")" ExistsE p -> do p <- pr p return $ "(Exists-E " ++ p ++ ")" ImpliesE p1 p2 -> do p1 <- prProof ctx p1 p2 <- pr p2 return $ "(Implies-E " ++ p1 ++ " " ++ p2 ++ ")" ForallE f p -> do f <- prForm ctx $ Meta f p <- pr p return $ "(Forall-E " ++ f ++ " " ++ p ++ ")" InvBoolExtl p1 p2 -> do p1 <- prProof ctx p1 p2 <- pr p2 return $ "(inv-bool-extl " ++ p1 ++ " " ++ p2 ++ ")" InvBoolExtr p1 p2 -> do p1 <- prProof ctx p1 p2 <- pr p2 return $ "(inv-bool-extr " ++ p1 ++ " " ++ p2 ++ ")" InvFunExt f p -> do f <- prForm ctx $ Meta f p <- pr p return $ "(inv-fun-ext " ++ f ++ " " ++ p ++ ")" prProofEq :: Int -> MetaProofEq -> IO String prProofEq ctx p = prMeta p $ \p -> case p of Simp p -> prProofEqSimp ctx p Step hyp elimp simpp eqp -> do hyp <- prHyp ctx hyp elimp <- prProofEqElim ctx elimp simpp <- prProofEqSimp ctx simpp eqp <- prProofEq ctx eqp return $ "(step " ++ hyp ++ " " ++ elimp ++ " " ++ simpp ++ " " ++ eqp ++ ")" BoolExt p1 p2 -> do p1 <- prProof (ctx + 1) p1 p2 <- prProof (ctx + 1) p2 return $ "(bool-ext " ++ p1 ++ " " ++ p2 ++ ")" FunExt p -> do p <- prProofEq (ctx + 1) p return $ "(fun-ext " ++ p ++ ")" prProofEqSimp :: Int -> MetaProofEqSimp -> IO String prProofEqSimp ctx p = do os <- only_simp p case os of True -> return $ "simp-all" False -> prMeta p $ \p -> case p of SimpLam em p -> do p <- prProofEq (ctx + 1) p return $ "(simp-lam " ++ pem em ++ p ++ ")" where pem EMNone = "" pem EMLeft = "{- eta-conv lhs -} " pem EMRight = "{- eta-conv rhs -} " SimpCons c ps -> do ps <- mapM (prProofEq ctx) ps return $ "(simp-" ++ show c ++ concat (map (" " ++) ps) ++ ")" SimpApp ps -> do ps <- prProofEqs ctx ps return $ "(simp-app" ++ ps ++ ")" SimpChoice p ps -> do p <- prProofEq ctx p ps <- prProofEqs ctx ps return $ "(simp-choice " ++ p ++ ps ++ ")" prProofEqs :: Int -> MetaProofEqs -> IO String prProofEqs ctx p = prMeta p $ \p -> case p of PrEqNil -> return "" PrEqCons p ps -> do p <- prProofEq ctx p ps <- prProofEqs ctx ps return $ " " ++ p ++ ps only_simp :: MetaProofEqSimp -> IO Bool only_simp p = expandbind (Meta p) >>= \p -> case p of Meta{} -> return False NotM p -> case p of SimpLam _ p -> h p SimpCons _ ps -> do bs <- mapM h ps return $ and bs SimpApp ps -> g ps SimpChoice p ps -> do b1 <- h p b2 <- g ps return $ b1 && b2 where h p = expandbind (Meta p) >>= \p -> case p of Meta{} -> return False NotM p -> case p of Simp p -> only_simp p _ -> return False g ps = expandbind (Meta ps) >>= \ps -> case ps of Meta{} -> return False NotM p -> case p of PrEqNil -> return True PrEqCons p ps -> do b1 <- h p b2 <- g ps return $ b1 && b2 prForm :: Int -> MFormula -> IO String prForm ctx f = expandbind f >>= \f -> case f of Meta m -> return $ "?" ++ show (mid m) NotM (Lam muid t bdy) -> do t <- prType t bdy <- prForm (ctx + 1) bdy return $ "(\\#" ++ pmuid muid ++ show ctx ++ ":" ++ t ++ "." ++ bdy ++ ")" NotM (C muid c args) -> do args <- mapM (\arg -> case arg of F f -> prForm ctx f >>= \f -> return $ f T t -> prType t >>= \t -> return $ t ) args return $ "(" ++ show c ++ pmuid muid ++ concat (map (" " ++) args) ++ ")" NotM (App muid elr args) -> do args <- prArgs ctx args let pelr = case elr of Var i -> "#" ++ show (ctx - i - 1) Glob gv -> "<<" ++ gvName gv ++ ">>" return $ "(" ++ pelr ++ pmuid muid ++ args ++ ")" NotM (Choice muid typ qf args) -> do typ <- prType typ qf <- prForm ctx qf args <- prArgs ctx args return $ "(choice" ++ pmuid muid ++ " " ++ typ ++ " " ++ qf ++ args ++ ")" where pmuid _ = "" prArgs :: Int -> MArgs -> IO String prArgs ctx xs = expandbind xs >>= \xs -> case xs of Meta m -> return $ "[?" ++ show (mid m) ++ "]" NotM ArgNil -> return "" NotM (ArgCons x xs) -> do x <- prForm ctx x xs <- prArgs ctx xs return $ " " ++ x ++ xs prType :: MType -> IO String prType t = expandbind t >>= \t -> case t of Meta m -> return $ "?" ++ show (mid m) NotM (Ind i) -> return $ "$i" ++ if i >= 0 then show i else "" NotM Bool -> return "$o" NotM (Map t1 t2) -> do t1 <- prType t1 t2 <- prType t2 return $ "(" ++ t1 ++ ">" ++ t2 ++ ")" prProblem :: Problem -> IO String prProblem pr = do globvars <- mapM prGlobVar $ prGlobVars pr globhyps <- mapM prGlobHyp $ prGlobHyps pr conjs <- mapM (\(cn, form) -> prForm 0 form >>= \form -> return (cn ++ " : " ++ form)) $ prConjectures pr return $ "global variables\n" ++ unlines globvars ++ "\nglobal hypotheses\n" ++ unlines globhyps ++ "\nconjectures\n" ++ unlines conjs prGlobVar :: GlobVar -> IO String prGlobVar gv = do typ <- prType $ gvType gv return $ gvName gv ++ " : " ++ typ prGlobHyp :: GlobHyp -> IO String prGlobHyp gh = do form <- prForm 0 $ ghForm gh return $ ghName gh ++ " : " ++ form ++ " (" ++ show (ghGenCost gh) ++ ")" -- ------------------------------------ prCFormula :: Int -> CFormula -> IO String prCFormula ctx (Cl env form) = expandbind form >>= \form -> case form of Meta m -> do env <- prEnv env return $ env ++ "?" ++ show (mid m) NotM (Lam muid t bdy) -> do t <- prType t bdy <- prCFormula (ctx + 1) (Cl (Skip : env) bdy) return $ "(\\#" ++ pmuid muid ++ show ctx ++ ":" ++ t ++ "." ++ bdy ++ ")" NotM (C muid c args) -> do args <- mapM (\arg -> case arg of F f -> prCFormula ctx (Cl env f) >>= \f -> return $ f T t -> prType t >>= \t -> return $ t ) args return $ "(" ++ show c ++ pmuid muid ++ concat (map (" " ++) args) ++ ")" NotM (App muid elr args) -> do elr <- case elr of Var i -> case doclos env i of Left i -> return $ "#" ++ show (ctx - i - 1) Right form -> do form <- prCFormula ctx form return $ "{" ++ form ++ "}" Glob gv -> return $ gvName gv args <- prargs args return $ "(" ++ elr ++ pmuid muid ++ args ++ ")" NotM (Choice muid typ qf args) -> do typ <- prType typ qf <- prCFormula ctx (Cl env qf) args <- prargs args return $ "(choice" ++ pmuid muid ++ " " ++ typ ++ " " ++ qf ++ args ++ ")" where pmuid _ = "" prargs args = expandbind args >>= \args -> case args of Meta m -> do env <- prEnv env return $ env ++ "?" ++ show (mid m) NotM ArgNil -> return "" NotM (ArgCons x xs) -> do x <- prCFormula ctx (Cl env x) xs <- prargs xs return $ " " ++ x ++ xs prCFormula ctx (CApp c1 c2) = do c1 <- prCFormula ctx c1 c2 <- prCFormula ctx c2 return $ "(capp " ++ c1 ++ " " ++ c2 ++ ")" prCFormula ctx (CNot c) = do c <- prCFormula ctx c return $ "(cnot " ++ c ++ ")" prCFormula _ (CHN _) = return "<CHN>" prEnv :: Env -> IO String prEnv = g 0 where g _ [] = return "" g i (Skip : env) = g (i + 1) env g i (Sub f : env) = do env <- g (i + 1) env f <- prCFormula 0 f return $ "[@" ++ show i ++ "=" ++ f ++ "]" ++ env g i (Lift n : env) = do env <- g i env return $ "[L" ++ show n ++ "]" ++ env prCtx :: Context -> IO String prCtx ctx = g (length ctx - 1) ctx where g _ [] = return "" g i (VarExt t : ctx) = do ctx <- g (i - 1) ctx t <- prType t return $ ctx ++ "[#" ++ show i ++ ":" ++ t ++ "]" g i (HypExt f : ctx) = do ctx <- g (i - 1) ctx f <- prCFormula i f return $ ctx ++ "[#" ++ show i ++ ":" ++ f ++ "]"
frelindb/agsyHOL
PrintProof.hs
Haskell
mit
10,596
{-# LANGUAGE DeriveDataTypeable #-} module Development.Duplo.Types.Builder where import Control.Exception (Exception) import Data.Typeable (Typeable) data BuilderException = MissingGithubUserException | MissingGithubRepoException | MalformedManifestException String | MissingManifestException String | MissingTestDirectory deriving (Typeable) instance Exception BuilderException instance Show BuilderException where show MissingGithubUserException = "There must be a GitHub user." show MissingGithubRepoException = "There must be a GitHub repo." show (MalformedManifestException path) = "The manifest file `" ++ path ++ "` is not a valid duplo JSON." show (MissingManifestException path) = "`" ++ path ++ "` is expected at the current location." show MissingTestDirectory = "There must be a `tests/` directory in order to run tests."
pixbi/duplo
src/Development/Duplo/Types/Builder.hs
Haskell
mit
1,003
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Shifts.Types ( Eng(..) , Shift(..) ) where import Control.Monad (liftM) import Data.Aeson import Data.Text import Data.Time import GHC.Generics instance Ord Shift where (Shift s1 _ _) `compare` (Shift s2 _ _) = s1 `compare` s2 data Shift = Shift { _startDay :: Day , _endDay :: Day , _engOwner :: Eng } deriving (Show, Eq, ToJSON, Generic) data Eng = Eng { _initials :: Text } deriving (Show, Eq, ToJSON, Generic) parseDate :: String -> Day parseDate = parseTimeOrError True defaultTimeLocale "%Y-%m-%d" instance FromJSON Day where parseJSON (Object v) = liftM parseDate (v .: "date") parseJSON _ = fail "invalid" instance ToJSON Day where toJSON = toJSON . showGregorian
tippenein/shifts
src/Shifts/Types.hs
Haskell
mit
824
{-# LANGUAGE OverloadedStrings #-} module Main where import CoinApi import qualified CoinApi.Monadic as M import Data.Time import Control.Monad.State (liftIO) key = "73034021-0EBC-493D-8A00-E0F138111F41" asset_id_base = "BTC" asset_id_quote = "USD" symbol_id = "BITSTAMP_SPOT_BTC_USD" period_id = "1HRS" time_start = UTCTime (fromGregorian 2016 01 01) (fromIntegral 0) time_end = UTCTime (fromGregorian 2016 01 03) (fromIntegral 0) limit = 100 :: Int -- using pure interface pure :: IO () pure = do putStrLn "list_all_exchanges:" ex <- metadata_list_exchanges key case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "list_all_assets:" ex <- metadata_list_assets key case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "list_all_symbols:" ex <- metadata_list_symbols key case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "get_specific_rate:" ex <- metadata_list_symbols key case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "get_specific_rate_t:" ex <- exchange_rates_get_specific_rate_t key asset_id_base asset_id_quote time_start case ex of Right result -> print result Left err -> putStrLn err putStrLn "" putStrLn $ "get_all_current_rates:" ex <- exchange_rates_get_all_current_rates key asset_id_base case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "list_all_periods:" ex <- ohlcv_list_all_periods key case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "quotes_latest_data:" ex <- quotes_latest_data key case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "quotes_latest_data_s:" ex <- quotes_latest_data_s key symbol_id case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "quotes_latest_data_l:" ex <- quotes_latest_data_l key limit case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "quotes_latest_data_sl:" ex <- quotes_latest_data_sl key symbol_id limit case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "quotes_historical_data:" ex <- quotes_historical_data key symbol_id time_start case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "quotes_historical_data_e:" ex <- quotes_historical_data_e key symbol_id time_start time_end case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "quotes_historical_data_l:" ex <- quotes_historical_data_l key symbol_id time_start limit case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "quotes_historical_data_el:" ex <- quotes_historical_data_el key symbol_id time_start time_end limit case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "orderbooks_current_data:" ex <- orderbooks_current_data key case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "orderbooks_current_data_s:" ex <- orderbooks_current_data_s key symbol_id case ex of Right result -> print result Left err -> putStrLn err putStrLn "" putStrLn "orderbooks_latest_data:" ex <- orderbooks_latest_data key symbol_id case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "orderbooks_latest_data_l:" ex <- orderbooks_latest_data_l key symbol_id limit case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "orderbooks_historical_data:" ex <- orderbooks_historical_data key symbol_id time_start case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "orderbooks_historical_data_e:" ex <- orderbooks_historical_data_e key symbol_id time_start time_end case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "orderbooks_historical_data_l:" ex <- orderbooks_historical_data_l key symbol_id time_start limit case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" putStrLn "orderbooks_historical_data_el:" ex <- orderbooks_historical_data_el key symbol_id time_start time_end limit case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" -- using monadic interface monadic :: IO () monadic = M.withApiKey key $ do ex <- M.metadata_list_exchanges liftIO $ do putStrLn "list_all_exchanges:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.metadata_list_assets liftIO $ do putStrLn "list_all_assets:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.metadata_list_symbols liftIO $ do putStrLn "list_all_symbols:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.metadata_list_symbols liftIO $ do putStrLn "get_specific_rate:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.exchange_rates_get_specific_rate_t asset_id_base asset_id_quote time_start liftIO $ do putStrLn "get_specific_rate_t:" case ex of Right result -> print result Left err -> putStrLn err putStrLn "" ex <- M.exchange_rates_get_all_current_rates asset_id_base liftIO $ do putStrLn $ "get_all_current_rates:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.ohlcv_list_all_periods liftIO $ do putStrLn "list_all_periods:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.quotes_latest_data liftIO $ do putStrLn "quotes_latest_data:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.quotes_latest_data_s symbol_id liftIO $ do putStrLn "quotes_latest_data_s:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.quotes_latest_data_l limit liftIO $ do putStrLn "quotes_latest_data_l:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.quotes_latest_data_sl symbol_id limit liftIO $ do putStrLn "quotes_latest_data_sl:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.quotes_historical_data symbol_id time_start liftIO $ do putStrLn "quotes_historical_data:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.quotes_historical_data_e symbol_id time_start time_end liftIO $ do putStrLn "quotes_historical_data_e:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.quotes_historical_data_l symbol_id time_start limit liftIO $ do putStrLn "quotes_historical_data_l:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.quotes_historical_data_el symbol_id time_start time_end limit liftIO $ do putStrLn "quotes_historical_data_el:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.orderbooks_current_data liftIO $ do putStrLn "orderbooks_current_data:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.orderbooks_current_data_s symbol_id liftIO $ do putStrLn "orderbooks_current_data_s:" case ex of Right result -> print result Left err -> putStrLn err putStrLn "" ex <- M.orderbooks_latest_data symbol_id liftIO $ do putStrLn "orderbooks_latest_data:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.orderbooks_latest_data_l symbol_id limit liftIO $ do putStrLn "orderbooks_latest_data_l:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.orderbooks_historical_data symbol_id time_start liftIO $ do putStrLn "orderbooks_historical_data:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.orderbooks_historical_data_e symbol_id time_start time_end liftIO $ do putStrLn "orderbooks_historical_data_e:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.orderbooks_historical_data_l symbol_id time_start limit liftIO $ do putStrLn "orderbooks_historical_data_l:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" ex <- M.orderbooks_historical_data_el symbol_id time_start time_end limit liftIO $ do putStrLn "orderbooks_historical_data_el:" case ex of Right result -> mapM_ print $ take 2 result Left err -> putStrLn err putStrLn "" main = do putStrLn "Pure interface:" Main.pure putStrLn "Monadic interface:" Main.monadic
coinapi/coinapi-sdk
data-api/haskell-rest/Main.hs
Haskell
mit
11,093
{-# LANGUAGE CPP #-} module Compat where import Control.Concurrent (mkWeakThreadId, myThreadId) import Control.Exception (AsyncException (UserInterrupt), throwTo) import System.Mem.Weak (deRefWeak) #if defined(mingw32_HOST_OS) import qualified GHC.ConsoleHandler as WinSig #else import qualified System.Posix.Signals as Sig #endif installSignalHandlers :: IO () installSignalHandlers = do main_thread <- myThreadId wtid <- mkWeakThreadId main_thread let interrupt = do r <- deRefWeak wtid case r of Nothing -> return () Just t -> throwTo t UserInterrupt #if defined(mingw32_HOST_OS) let sig_handler WinSig.ControlC = interrupt sig_handler WinSig.Break = interrupt sig_handler _ = return () _ <- WinSig.installHandler (WinSig.Catch sig_handler) #else _ <- Sig.installHandler Sig.sigQUIT (Sig.Catch interrupt) Nothing _ <- Sig.installHandler Sig.sigINT (Sig.Catch interrupt) Nothing #endif return ()
unisonweb/platform
parser-typechecker/unison/Compat.hs
Haskell
mit
987
module Main where import Haste main = withElem "root" $ \root -> do img <- newElem "img" setAttr img "src" "cat.jpg" setAttr img "id" "cat" addChild img root onEvent img OnMouseOver $ \_ -> setClass img "foo" True onEvent img OnMouseOut $ setClass img "foo" False
laser/haste-experiment
demos/event-handling/event-handling.hs
Haskell
mit
289
import qualified Data.List import Kd2nTree p1 :: Point3d p1 = list2Point [3.0,-1.0,2.1] p2 :: Point3d p2 = list2Point [3.5,2.8,3.1] p3 :: Point3d p3 = list2Point [3.5,0.0,2.1] p4 :: Point3d p4 = list2Point [3.0,-1.7,3.1] p5 :: Point3d p5 = list2Point [3.0,5.1,0.0] p6 :: Point3d p6 = list2Point [1.5,8.0,1.5] p7 :: Point3d p7 = list2Point [3.3,2.8,2.5] p8 :: Point3d p8 = list2Point [4.0,5.1,3.8] p9 :: Point3d p9 = list2Point [3.1,3.8,4.8] p10 :: Point3d p10 = list2Point [1.8,1.1,-2.0] p11 :: Point3d p11 = list2Point [-100000, 0.0, 100000] enunciat :: Kd2nTree Point3d enunciat = buildIni [ ([3.0, -1.0, 2.1], [1, 3]), ([3.5, 2.8, 3.1], [1, 2]), ([3.5, 0.0, 2.1], [3]), ([3.0, -1.7, 3.1], [1, 2, 3]), ([3.0, 5.1, 0.0], [2]), ([1.5, 8.0, 1.5], [1]), ([3.3, 2.8, 2.5], [3]), ([4.0, 5.1, 3.8], [2]), ([3.1, 3.8, 4.8], [1, 3]), ([1.8, 1.1, -2.0], [1, 2])] pau :: Kd2nTree Point3d pau = buildIni [ ([0,0,0], [1]), ([-1,1,0], [1]), ([2,200,0],[1]), ([1,2,0], [1]), ([1,20,0], [1]), ([30,-20,0], [1])] empty :: Kd2nTree Point3d empty = buildIni [] equivalent1 :: Kd2nTree Point3d equivalent1 = buildIni [ ([2,3,-100.5], [2,3]), ([5,0,-10], [1]), ([-2,-2,-2], [3]) ] equivalent2 :: Kd2nTree Point3d equivalent2 = buildIni [ ([5,0,-10.0], [2,3]), ([-2,-2,-2], [1]), ([2,3,-100.5], [2]) ] antiequivalent :: Kd2nTree Point3d antiequivalent = buildIni [ ([5,0,-10.00001], [2,3]), ([-2,-2,-2], [1]), ([2,3,-100.5], [2]) ] punts :: [Point3d] punts = [p1, p2, p3, p4, p5, p6, p11, pscale 2 p11, pscale (-2) (pscale (-1) p11), nearest pau p11, nearest enunciat p11, nearest equivalent1 p11] arbres :: [Kd2nTree Point3d] arbres = [pau, enunciat, antiequivalent, equivalent1, equivalent2, empty] llistes :: [[Point3d]] llistes = [allinInterval equivalent1 p6 p8, allinInterval equivalent1 p8 p6, allinInterval enunciat (list2Point [-500, -500, -500]) (list2Point [500, 500, 500])] strings :: [String] strings = [show $ dist p1 p2, show $ allinInterval enunciat (list2Point [-500, -500, -500]) (list2Point [500,500,500])] proves :: [([Char], Bool)] proves = [ ("Igualtat punts", p1 == p1), ("Desigualtat punts", p1 /= p2), ("Dimensio punts", dim p1 == 3), ("Seleccio punts", sel 1 p1 == 3), ("Translacio punts", ptrans [1,1,1] p1 == list2Point [4,0,3.1]), ("Distancia punts", dist p1 p1 == 0 && dist2 p1 p1 == 0), ("Comprovacio empty", empty == Empty), ("Igualtat d'empty", empty == empty), ("Desigualtat empty/no empty", empty /= enunciat && enunciat /= empty), ("Igualtat no empty", enunciat == enunciat), ("Equivalencia certa directa", equivalent1 == equivalent2), ("Equivalencia certa insert", (insert equivalent1 p11 [1]) == (insert equivalent2 p11 [2,3])), ("Equivalencia certa elems", elems equivalent1 `eqList` elems equivalent2), ("Equivalencia certa translation", (translation [500,0,-1] equivalent1) == (translation [500,0,-1] equivalent2)), ("Equivalencia certa scale", (elems $ scale (-5.33) equivalent1) `eqList` (elems $ scale (-5.33) equivalent2)), ("Equivalencia certa scale 2", (scale (200) equivalent1) == (scale 200 equivalent2)), ("Equivalencia certa allInInterval", (allinInterval equivalent1 p6 p8) `eqList` (allinInterval equivalent2 p6 p8)), ("Equivalencia falsa directa", equivalent1 /= antiequivalent && equivalent2 /= antiequivalent), ("Equivalencia falsa insert", (insert equivalent1 p1 [2,3]) /= (insert equivalent2 p11 [2,3])), ("Equivalencia falsa elems", elems equivalent1 `difList` elems antiequivalent), ("Equivalencia falsa translation", (translation [500,0,1] equivalent1) /= (translation [500,0,-1] equivalent2)), ("Equivalencia falsa scale", (elems $ scale (-5.23) equivalent1) `difList` (elems $ scale (-5.33) equivalent2)), ("Equivalencia falsa scale 2", (scale (100) equivalent1) /= (scale 200 equivalent2)), ("Operacions sobre empty's 1", (insert Empty p1 [2,3]) == (insert Empty p1 [1,2])), ("Operacions sobre empty's 2", (get_all Empty) == (get_all $ foldl remove enunciat (elems enunciat))), ("Operacions sobre empty's 3", (remove Empty p1) == empty), ("Operacions sobre empty's 4", not $ (any (== True)) (map (contains Empty) (elems enunciat))), ("Operacions sobre empty's 5", null $ allinInterval empty (list2Point [-500,-500,-500]) (list2Point [500,500,500])), ("Operacions sobre empty's 6", translation [-5,0,-5] Empty == empty), ("Operacions sobre empty's 7", scale (-10.5) Empty == empty), ("Propietat conjunts1", insert enunciat p1 [2,3] == enunciat), ("Propietat conjunts2", insert enunciat p2 [2,3] == enunciat), ("Propietat conjunts3", insert enunciat p3 [1] == enunciat), ("Propietat conjunts4", insert enunciat p11 [1] /= enunciat), ("Propietat conjunts5", foldl (\e (x,y) -> insert e x y) enunciat (get_all enunciat) == enunciat), ("Propietat conjunts6", foldl (\e (x,y) -> insert e x y) equivalent1 (get_all equivalent1) == equivalent2) ] eqList l1 l2 = (length l1 == length l2) && (length l1 == length (l1 `Data.List.intersect` l2)) difList = not .: eqList where (.:) = (.).(.) printTests _ [] = do putStrLn "Fi de proves\n----------" printTests s l = do putStrLn "----------"; printTests' s l 1 where printTests' _ [] _ = do putStrLn "Fi de proves\n----------" printTests' s (x:xs) i = do putStrLn (s ++ "#" ++ (show i)) putStrLn (show x) putStrLn "" printTests' s xs (i + 1) main = do printTests "Punt " punts printTests "Arbre " arbres printTests "Llista " llistes printTests "Prova " proves if (and (map snd proves)) then do putStrLn "Proves OK!" else do putStrLn "Proves NOT ok!" mapM_ putStrLn [string ++ "\n" | string <- strings]
albertsgrc/practica-lp-kd2ntrees
Main.hs
Haskell
mit
6,316
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, InstanceSigs #-} {--# LANGUAGE DeriveDataTypeable, ScopedTypeVariables, MultiParamTypeClasses , FlexibleInstances, FunctionalDependencies #-} module TemplatesUtility (templatesSettings) where import Control.Applicative import Control.Monad import Data.EitherR import Data.List import qualified Data.Map as DM import System.Exit import System.FilePath.Posix import System.Directory import System.IO import System.Path.NameManip import System.Process import Text.Regex.PCRE import Data.ConfigFile import CompilationUtility import qualified ConfigFile import Translations import Templates import Printer import Utility data TEMPLATES_SETTINGS = TEMPLATES_SETTINGS { ts_executable :: FilePath, ts_soytojssrccompiler :: FilePath, ts_flags :: [String], ts_outputpathformat :: String, -- A format string that specifies how to build the path to each output -- file. The format string can include literal characters as well as the -- placeholders {INPUT_PREFIX}, {INPUT_DIRECTORY}, {INPUT_FILE_NAME}, -- {INPUT_FILE_NAME_NO_EXT} ts_inputs :: [FilePath], ts_src_path :: FilePath, ts_app_path :: FilePath, ts_verbose :: Bool } instance UtilitySettings TEMPLATES_SETTINGS where executable = ts_executable toStringList a = "-jar":(ts_soytojssrccompiler a):"--outputPathFormat":(ts_outputpathformat a): (concat [ts_flags a,["--srcs"],[intercalate "," $ ts_inputs a]]) utitle _ = Just "Soy template compiler" verbose = ts_verbose templatesSettings :: ConfigParser -> [FilePath] -> EitherT String IO TEMPLATES_SETTINGS templatesSettings cp inputs = TEMPLATES_SETTINGS <$> ConfigFile.getFile cp "DEFAULT" "utility.templates.executable" <*> ConfigFile.getFile cp "DEFAULT" "utility.templates.soytojssrccompiler" <*> (fmap words $ hoistEither $ ConfigFile.get cp "DEFAULT" "utility.templates.flags") <*> pure "{INPUT_DIRECTORY}/{INPUT_FILE_NAME}.TEMP" <*> pure inputs <*> (fmap dropTrailingPathSeparator $ hoistEither $ ConfigFile.get cp "DEFAULT" "src.path") <*> (fmap dropTrailingPathSeparator $ hoistEither $ ConfigFile.get cp "DEFAULT" "app.path") <*> (hoistEither $ ConfigFile.getBool cp "DEFAULT" "verbose") instance CompilationUtility TEMPLATES_SETTINGS Translations where defaultValue _ = emptyTrans failure :: UtilityResult TEMPLATES_SETTINGS -> EitherT String IO Translations failure r = do dPut [Failure] closed <- catchIO $ hIsClosed $ ur_stderr r if closed then return () else catchIO $ hGetContents (ur_stderr r) >>= putStr dPut [Ln $ "Exit code: " ++ (show $ ur_exit_code r)] throwT "TemplatesUtility failure" success :: UtilityResult TEMPLATES_SETTINGS -> EitherT String IO Translations success r = do dPut [Success] outputs <- moveOutputs (ur_compilation_args r) (ts_inputs $ ur_compilation_args r) foldM filesExtractor emptyTrans $ zip (ts_inputs $ ur_compilation_args r) outputs where moveOutputs :: TEMPLATES_SETTINGS -> [FilePath] -> EitherT String IO [FilePath] moveOutputs ts [] = return [] moveOutputs ts (f:fs) = do newName <- hoistEither $ soyToSoyJs (ts_src_path ts) (ts_app_path ts) f catchIO $ renameFile (f ++ ".TEMP") newName (:) newName <$> moveOutputs ts fs filesExtractor :: Translations -> (FilePath, FilePath) -> EitherT String IO Translations filesExtractor trans (input, output) = do local <- extractTrans input catchIO $ withFile output AppendMode $ writeTrans local return $ mergeTrans trans local
Prinhotels/goog-closure
src/TemplatesUtility.hs
Haskell
mit
3,681
<?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="ms-MY"> <title>TLS Debug | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
secdec/zap-extensions
addOns/tlsdebug/src/main/javahelp/org/zaproxy/zap/extension/tlsdebug/resources/help_ms_MY/helpset_ms_MY.hs
Haskell
apache-2.0
970
{- Copyright 2018 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} -- | -- Module : Data.MultiMap -- Copyright : (c) CodeWorld Authors 2017 -- License : Apache-2.0 -- -- Maintainer : Joachim Breitner <mail@joachim-breitner.de> -- -- A simple MultiMap. -- -- This differs from the one in the @multimap@ package by using -- 'Data.Sequence.Seq' for efficient insert-at-end and other improved speeds. -- -- Also only supports the operations required by CodeWorld for now. {-# LANGUAGE TupleSections #-} module Data.MultiMap ( MultiMap , empty , null , insertL , insertR , toList , spanAntitone , union , keys ) where import Data.Bifunctor import Data.Coerce import qualified Data.Foldable (toList) import qualified Data.Map as M import qualified Data.Sequence as S import Prelude hiding (null) newtype MultiMap k v = MM (M.Map k (S.Seq v)) deriving (Show, Eq) empty :: MultiMap k v empty = MM M.empty null :: MultiMap k v -> Bool null (MM m) = M.null m insertL :: Ord k => k -> v -> MultiMap k v -> MultiMap k v insertL k v (MM m) = MM (M.alter (Just . maybe (S.singleton v) (v S.<|)) k m) insertR :: Ord k => k -> v -> MultiMap k v -> MultiMap k v insertR k v (MM m) = MM (M.alter (Just . maybe (S.singleton v) (S.|> v)) k m) toList :: MultiMap k v -> [(k, v)] toList (MM m) = [(k, v) | (k, vs) <- M.toList m, v <- Data.Foldable.toList vs] -- TODO: replace with M.spanAntitone once containers is updated mapSpanAntitone :: (k -> Bool) -> M.Map k a -> (M.Map k a, M.Map k a) mapSpanAntitone p = bimap M.fromDistinctAscList M.fromDistinctAscList . span (p . fst) . M.toList spanAntitone :: (k -> Bool) -> MultiMap k v -> (MultiMap k v, MultiMap k v) spanAntitone p (MM m) = coerce (mapSpanAntitone p m) union :: Ord k => MultiMap k v -> MultiMap k v -> MultiMap k v union (MM m1) (MM m2) = MM (M.unionWith (S.><) m1 m2) keys :: MultiMap k v -> [k] keys (MM m) = M.keys m
tgdavies/codeworld
codeworld-prediction/src/Data/MultiMap.hs
Haskell
apache-2.0
2,493
import Data.List import Data.Char main = do line' <- fmap reverse getLine putStrLn $ "You said " ++ line' ++ " backwords!" -- fmap reverse will give "Just halb" from "Just Blah" -- getLine gives IO String and mapping it to reverse IO gnirtS kind of :)- main1 = do line' <- fmap (++ "!") getLine putStrLn $ "You said " ++ line' -- fmap does postfix "!" to everyline -- main2 = do line' <- fmap (intersperse '-' . reverse . map toUpper ) getLine putStrLn $ "You said (With beautification) : " ++ line' --Two Functor laws --fmap id = id --fmap (f . g) = fmap f . fmap g
dongarerahul/lyah
chapter11-functorApplicativeMonad/IOFunctor.hs
Haskell
apache-2.0
607
module Finance.Hqfl.Instrument.Cap ( Cap )where data Cap
cokleisli/hqfl
src/Finance/Hqfl/Instrument/Cap.hs
Haskell
apache-2.0
66
{-# LANGUAGE RankNTypes, FlexibleContexts, ScopedTypeVariables #-} {- fixing resolution. This is a large beast of a module. Sorry. updated for version 2.0.3 to match protoc's namespace resolution better updated for version 2.0.4 to differentiate Entity and E'Entity, this makes eName a total selector updated after version 2.0.5 to fix problem when package name was not specified in proto file. main calls either runStandalone or runPlugin which call loadProto or loadStandalone which both call loadProto' loadProto' uses getPackage to make packageName, loads the imports, and passes all this to makeTopLevel to get Env The "load" loop in loadProto' caches the imported TopLevel based on _filename_ files can be loaded via multiple paths but this is not important this may interact badly with absent "package" declarations that act as part of importing package need these to be "polymorphic" in the packageID somehow? Speculate: makeTopLevel knows the parent from the imports: parent with explicit package could resolve "polymorphic" imports by a recursive transformation? parent with no explicit package could do nothing. root will need default explicit package name ? or special handling in loadProto' or load* ? Then loadProto or loadStandalone both call run' which calls makeNameMaps with the Env from loadProto' makeNameMaps calls makeNameMap on each top level fdp from each TopLevel in the Global Env from loadProto' makeNameMap calls getPackage to form packageName, and unless overridden it is also used for hParent makeNameMap on the imports gets called without any special knowledge of the "parent". If root or some imports are still "polymorphic" then this is most annoying. Alternative solution: a middle step after makeTopLevel and before makeNameMaps examines and fixes all the polymorphic imports. The nameMap this computes is passed by run' to makeProtoInfo from MakeReflections The bug is being reported by main>runStandalon>loadStandalone>loadProto'>makeTopLevel>resolveFDP>fqFileDP>fqMessage>fqField>resolvePredEnv entityField uses resolveMGE instead of expectMGE and resolveEnv : this should allow field types to resolve just to MGE insteadof other field names. what about keys 'extendee' resolution to Message names only? expectM in entityField 'makeTopLevel' is the main internal entry point in this module. This is called from loadProto' which has two callers: loadProto and loadCodeGenRequest makeTopLevel uses a lazy 'myFixSE' trick and so the order of execution is not immediately clear. The environment for name resolution comes from the global' declaration which first involves using resolveFDP/runRE (E'Entity). To make things more complicated the definition of global' passes global' to (resolveFDP fdp). The resolveFDP/runRE runs all the fq* stuff (E'Entity and consumeUNO/interpretOption/resolveHere). Note that the only source of E'Error values of E'Entity are from 'unique' detecting name collisions. This global' environment gets fed back in as global'Param to form the SEnv for running the entityMsg, entityField, entityEnum, entityService functions. These clean up the parsed descriptor proto structures into dependable and fully resolved ones. The kids operator and the unZip are used to seprate and collect all the error messages, so that they can be checked for and reported as a group. ==== Problem? Nesting namespaces allows shadowing. I forget if Google's protoc allows this. Problem? When the current file being resolves has the same package name as an imported file then hprotoc will find unqualified names in the local name space and the imported name space. But if there is a name collision between the two then hprotoc will not detect this; the unqualified name will resolve to the local file and not observe the duplicate from the import. TODO: check what Google's protoc does in this case. Solution to either of the above might be to resolve to a list of successes and check for a single success. This may be too lazy. ==== aggregate option types not handled: Need to take fk and bytestring from parser and: 1) look at mVal of fk (E'Message) to understand what fields are expected (listed in mVals of this mVal). 2) lex the bytestring 3) parse the sequence of "name" ":" "value" by doing 4) find "name" in the expected list from (1) (E'Field) 5) Look at the fType of this E'Field and parse the "value", if Nothing (message/group/enum) then 6) resolve name and look at mVal 7) if enum then parse "value" as identifier or if message or group 8) recursively go to (1) and either prepend lenght (message) or append stop tag (group) 9) runPut to get the wire encoded field tag and value when Just a simple type 10) concatentanate the results of (3) to get the wire encoding for the message value Handling recursive message/groups makes this more annoying. -} -- | This huge module handles the loading and name resolution. The -- loadProto command recursively gets all the imported proto files. -- The makeNameMaps command makes the translator from proto name to -- Haskell name. Many possible errors in the proto data are caught -- and reported by these operations. -- -- hprotoc will actually resolve more unqualified imported names than Google's protoc which requires -- more qualified names. I do not have the obsessive nature to fix this. module Text.ProtocolBuffers.ProtoCompile.Resolve(loadProto,loadCodeGenRequest,makeNameMaps,getTLS,getPackageID ,Env(..),TopLevel(..),ReMap,NameMap(..),PackageID(..),LocalFP(..),CanonFP(..)) where import qualified Text.DescriptorProtos.DescriptorProto as D(DescriptorProto) import qualified Text.DescriptorProtos.DescriptorProto as D.DescriptorProto(DescriptorProto(..)) import qualified Text.DescriptorProtos.DescriptorProto.ExtensionRange as D(ExtensionRange(ExtensionRange)) import qualified Text.DescriptorProtos.DescriptorProto.ExtensionRange as D.ExtensionRange(ExtensionRange(..)) import qualified Text.DescriptorProtos.EnumDescriptorProto as D(EnumDescriptorProto(EnumDescriptorProto)) import qualified Text.DescriptorProtos.EnumDescriptorProto as D.EnumDescriptorProto(EnumDescriptorProto(..)) import qualified Text.DescriptorProtos.EnumValueDescriptorProto as D(EnumValueDescriptorProto) import qualified Text.DescriptorProtos.EnumValueDescriptorProto as D.EnumValueDescriptorProto(EnumValueDescriptorProto(..)) import qualified Text.DescriptorProtos.FieldDescriptorProto as D(FieldDescriptorProto(FieldDescriptorProto)) import qualified Text.DescriptorProtos.FieldDescriptorProto as D.FieldDescriptorProto(FieldDescriptorProto(..)) import Text.DescriptorProtos.FieldDescriptorProto.Label import qualified Text.DescriptorProtos.FieldDescriptorProto.Type as D(Type) import Text.DescriptorProtos.FieldDescriptorProto.Type as D.Type(Type(..)) import qualified Text.DescriptorProtos.FileDescriptorProto as D(FileDescriptorProto) import qualified Text.DescriptorProtos.FileDescriptorProto as D.FileDescriptorProto(FileDescriptorProto(..)) import qualified Text.DescriptorProtos.MethodDescriptorProto as D(MethodDescriptorProto) import qualified Text.DescriptorProtos.MethodDescriptorProto as D.MethodDescriptorProto(MethodDescriptorProto(..)) import qualified Text.DescriptorProtos.ServiceDescriptorProto as D(ServiceDescriptorProto) import qualified Text.DescriptorProtos.ServiceDescriptorProto as D.ServiceDescriptorProto(ServiceDescriptorProto(..)) import qualified Text.DescriptorProtos.UninterpretedOption as D(UninterpretedOption) import qualified Text.DescriptorProtos.UninterpretedOption as D.UninterpretedOption(UninterpretedOption(..)) import qualified Text.DescriptorProtos.UninterpretedOption.NamePart as D(NamePart(NamePart)) import qualified Text.DescriptorProtos.UninterpretedOption.NamePart as D.NamePart(NamePart(..)) -- import qualified Text.DescriptorProtos.EnumOptions as D(EnumOptions) import qualified Text.DescriptorProtos.EnumOptions as D.EnumOptions(EnumOptions(uninterpreted_option)) -- import qualified Text.DescriptorProtos.EnumValueOptions as D(EnumValueOptions) import qualified Text.DescriptorProtos.EnumValueOptions as D.EnumValueOptions(EnumValueOptions(uninterpreted_option)) import qualified Text.DescriptorProtos.FieldOptions as D(FieldOptions(FieldOptions)) import qualified Text.DescriptorProtos.FieldOptions as D.FieldOptions(FieldOptions(packed,uninterpreted_option)) -- import qualified Text.DescriptorProtos.FileOptions as D(FileOptions) import qualified Text.DescriptorProtos.FileOptions as D.FileOptions(FileOptions(..)) -- import qualified Text.DescriptorProtos.MessageOptions as D(MessageOptions) import qualified Text.DescriptorProtos.MessageOptions as D.MessageOptions(MessageOptions(uninterpreted_option)) -- import qualified Text.DescriptorProtos.MethodOptions as D(MethodOptions) import qualified Text.DescriptorProtos.MethodOptions as D.MethodOptions(MethodOptions(uninterpreted_option)) -- import qualified Text.DescriptorProtos.ServiceOptions as D(ServiceOptions) import qualified Text.DescriptorProtos.ServiceOptions as D.ServiceOptions(ServiceOptions(uninterpreted_option)) import qualified Text.Google.Protobuf.Compiler.CodeGeneratorRequest as CGR import Text.ProtocolBuffers.Header import Text.ProtocolBuffers.Identifiers import Text.ProtocolBuffers.Extensions import Text.ProtocolBuffers.WireMessage import Text.ProtocolBuffers.ProtoCompile.Instances import Text.ProtocolBuffers.ProtoCompile.Parser import Control.Applicative import Control.Monad.Identity import Control.Monad.State import Control.Monad.Reader import Control.Monad.Error import Control.Monad.Writer import Data.Char import Data.Ratio import Data.Ix(inRange) import Data.List(foldl',stripPrefix,isPrefixOf,isSuffixOf) import Data.Map(Map) import Data.Maybe(mapMaybe) import Data.Typeable -- import Data.Monoid() import System.Directory import qualified System.FilePath as Local(pathSeparator,splitDirectories,joinPath,combine,makeRelative) import qualified System.FilePath.Posix as Canon(pathSeparator,splitDirectories,joinPath,takeBaseName) import qualified Data.ByteString.Lazy.Char8 as LC import qualified Data.ByteString.Lazy.UTF8 as U import qualified Data.Foldable as F import qualified Data.Sequence as Seq import qualified Data.Map as M import qualified Data.Set as Set import qualified Data.Traversable as T --import Debug.Trace(trace) -- Used by err and throw indent :: String -> String indent = unlines . map (\str -> ' ':' ':str) . lines ishow :: Show a => a -> String ishow = indent . show errMsg :: String -> String errMsg s = "Text.ProtocolBuffers.ProtoCompile.Resolve fatal error encountered, message:\n"++indent s err :: forall b. String -> b err = error . errMsg throw :: (Error e, MonadError e m) => String -> m a throw s = throwError (strMsg (errMsg s)) annErr :: (MonadError String m) => String -> m a -> m a annErr s act = catchError act (\e -> throwError ("Text.ProtocolBuffers.ProtoCompile.Resolve annErr: "++s++'\n':indent e)) getJust :: (Error e,MonadError e m, Typeable a) => String -> Maybe a -> m a {-# INLINE getJust #-} getJust s ma@Nothing = throw $ "Impossible? Expected Just of type "++show (typeOf ma)++" but got nothing:\n"++indent s getJust _s (Just a) = return a defaultPackageName :: Utf8 defaultPackageName = Utf8 (LC.pack "defaultPackageName") -- The "package" name turns out to be more complicated than I anticipated (when missing). Instead -- of plain UTF8 annotate this with the PackageID newtype to force me to trace the usage. Later -- change this to track the additional complexity. --newtype PackageID a = PackageID { getPackageID :: a } deriving (Show) data PackageID a = PackageID { _getPackageID :: a } | NoPackageID { _getNoPackageID :: a } deriving (Show) instance Functor PackageID where fmap f (PackageID a) = PackageID (f a) fmap f (NoPackageID a) = NoPackageID (f a) -- Used in MakeReflections.makeProtoInfo getPackageID :: PackageID a -> a getPackageID (PackageID a) = a getPackageID (NoPackageID a) = a -- The package field of FileDescriptorProto is set in Parser.hs. -- 'getPackage' is the only direct user of this information in hprotoc. -- The convertFileToPackage was developed looking at the Java output of Google's protoc. -- In 2.0.5 this has lead to problems with the stricter import name resolution when the imported file has no package directive. -- I need a fancier way of handling this. getPackage :: D.FileDescriptorProto -> PackageID Utf8 getPackage fdp = case D.FileDescriptorProto.package fdp of Just a -> PackageID a Nothing -> case D.FileDescriptorProto.name fdp of Nothing -> NoPackageID defaultPackageName Just filename -> case convertFileToPackage filename of Nothing -> NoPackageID defaultPackageName Just name -> NoPackageID name --getPackageUtf8 :: PackageID Utf8 -> Utf8 --getPackageUtf8 (PackageID {_getPackageID=x}) = x --getPackageUtf8 (NoPackageID {_getNoPackageID=x}) = x -- LOSES PackageID vs NoPackageID 2012-09-19 checkPackageID :: PackageID Utf8 -> Either String (PackageID (Bool,[IName Utf8])) checkPackageID (PackageID a) = fmap PackageID (checkDIUtf8 a) checkPackageID (NoPackageID a) = fmap NoPackageID (checkDIUtf8 a) -- | 'convertFileToPackage' mimics what I observe protoc --java_out do to convert the file name to a -- class name. convertFileToPackage :: Utf8 -> Maybe Utf8 convertFileToPackage filename = let full = toString filename suffix = ".proto" noproto = if suffix `isSuffixOf` full then take (length full - length suffix) full else full convert :: Bool -> String -> String convert _ [] = [] convert toUp (x:xs) | inRange ('a','z') x = if toUp then toUpper x : convert False xs else x : convert False xs | inRange ('A','Z') x = x : convert False xs | inRange ('0','9') x = x : convert True xs | '_' == x = x : convert True xs | otherwise = convert True xs converted = convert True noproto leading = case converted of (x:_) | inRange ('0','9') x -> "proto_" ++ converted _ -> converted in if null leading then Nothing else (Just (fromString leading)) -- This adds a leading dot if the input is non-empty joinDot :: [IName String] -> FIName String joinDot [] = err $ "joinDot on an empty list of IName!" joinDot (x:xs) = fqAppend (promoteFI x) xs checkFI :: [(FieldId,FieldId)] -> FieldId -> Bool checkFI ers fid = any (`inRange` fid) ers getExtRanges :: D.DescriptorProto -> [(FieldId,FieldId)] getExtRanges d = concatMap check unchecked where check x@(lo,hi) | hi < lo = [] | hi<19000 || 19999<lo = [x] | otherwise = concatMap check [(lo,18999),(20000,hi)] unchecked = F.foldr ((:) . extToPair) [] (D.DescriptorProto.extension_range d) extToPair (D.ExtensionRange { D.ExtensionRange.start = start , D.ExtensionRange.end = end }) = (maybe minBound FieldId start, maybe maxBound (FieldId . pred) end) -- | By construction Env is 0 or more Local Entity namespaces followed -- by 1 or more Global TopLevel namespaces (self and imported files). -- Entities in first Global TopLevel namespace can refer to each other -- and to Entities in the list of directly imported TopLevel namespaces only. data Env = Local [IName String] EMap {- E'Message,E'Group,E'Service -} Env | Global TopLevel [TopLevel] deriving Show -- | TopLevel corresponds to all items defined in a .proto file. This -- includes the FileOptions since this will be consulted when -- generating the Haskell module names, and the imported files are only -- known through their TopLevel data. data TopLevel = TopLevel { top'Path :: FilePath , top'Package :: PackageID [IName String] , top'FDP :: Either ErrStr D.FileDescriptorProto -- resolvedFDP'd , top'mVals :: EMap } deriving Show -- | The EMap type is a local namespace attached to an entity -- -- The E'Error values come from using unique to resolse name collisions when building EMap type EMap = Map (IName String) E'Entity -- | An Entity is some concrete item in the namespace of a proto file. -- All Entity values have a leading-dot fully-qualified with the package "eName". -- The E'Message,Group,Service have EMap namespaces to inner Entity items. data Entity = E'Message { eName :: [IName String], validExtensions :: [(FieldId,FieldId)] , mVals :: EMap {- E'Message,Group,Field,Key,Enum -} } | E'Group { eName :: [IName String], mVals :: EMap {- E'Message,Group,Field,Key,Enum -} } | E'Service { eName :: [IName String], mVals :: EMap {- E'Method -} } | E'Key { eName :: [IName String], eMsg :: Either ErrStr Entity {- E'Message -} , fNumber :: FieldId, fType :: Maybe D.Type , mVal :: Maybe (Either ErrStr Entity) {- E'Message,Group,Enum -} } | E'Field { eName :: [IName String], fNumber :: FieldId, fType :: Maybe D.Type , mVal :: Maybe (Either ErrStr Entity) {- E'Message,Group,Enum -} } | E'Enum { eName :: [IName String], eVals :: Map (IName Utf8) Int32 } | E'Method { eName :: [IName String], eMsgIn,eMsgOut :: Maybe (Either ErrStr Entity) {- E'Message -} } deriving (Show) -- This type handles entity errors by storing them rather than propagating or throwing them. -- -- The E'Error values come from using unique to resolse name collisions when building EMap data E'Entity = E'Ok Entity | E'Error String [E'Entity] deriving (Show) newtype LocalFP = LocalFP { unLocalFP :: FilePath } deriving (Read,Show,Eq,Ord) newtype CanonFP = CanonFP { unCanonFP :: FilePath } deriving (Read,Show,Eq,Ord) fpLocalToCanon :: LocalFP -> CanonFP fpLocalToCanon | Canon.pathSeparator == Local.pathSeparator = CanonFP . unLocalFP | otherwise = CanonFP . Canon.joinPath . Local.splitDirectories . unLocalFP fpCanonToLocal :: CanonFP -> LocalFP fpCanonToLocal | Canon.pathSeparator == Local.pathSeparator = LocalFP . unCanonFP | otherwise = LocalFP . Local.joinPath . Canon.splitDirectories . unCanonFP -- Used to create optimal error messages allowedGlobal :: Env -> [(PackageID [IName String],[IName String])] allowedGlobal (Local _ _ env) = allowedGlobal env allowedGlobal (Global t ts) = map allowedT (t:ts) allowedT :: TopLevel -> (PackageID [IName String], [IName String]) allowedT tl = (top'Package tl,M.keys (top'mVals tl)) -- Used to create optional error messages allowedLocal :: Env -> [([IName String],[IName String])] allowedLocal (Global _t _ts) = [] allowedLocal (Local name vals env) = allowedE : allowedLocal env where allowedE :: ([IName String], [IName String]) allowedE = (name,M.keys vals) -- Create a mapping from the "official" name to the Haskell hierarchy mangled name type ReMap = Map (FIName Utf8) ProtoName data NameMap = NameMap ( PackageID (FIName Utf8) -- packageName from 'getPackage' on fdp , [MName String] -- hPrefix from command line , [MName String]) -- hParent from java_outer_classname, java_package, or 'getPackage' ReMap deriving (Show) type RE a = ReaderT Env (Either ErrStr) a data SEnv = SEnv { my'Parent :: [IName String] -- top level value is derived from PackageID , my'Env :: Env } -- , my'Template :: ProtoName } -- E'Service here is arbitrary emptyEntity :: Entity emptyEntity = E'Service [IName "emptyEntity from myFix"] mempty emptyEnv :: Env emptyEnv = Global (TopLevel "emptyEnv from myFix" (PackageID [IName "emptyEnv form myFix"]) (Left "emptyEnv: top'FDP does not exist") mempty) [] instance Show SEnv where show (SEnv p e) = "(SEnv "++show p++" ; "++ whereEnv e ++ ")" --" ; "++show (haskellPrefix t,parentModule t)++ " )" type ErrStr = String type SE a = ReaderT SEnv (Either ErrStr) a runSE :: SEnv -> SE a -> Either ErrStr a runSE sEnv m = runReaderT m sEnv fqName :: Entity -> FIName Utf8 fqName = fiFromString . joinDot . eName fiFromString :: FIName String -> FIName Utf8 fiFromString = FIName . fromString . fiName iToString :: IName Utf8 -> IName String iToString = IName . toString . iName -- Three entities provide child namespaces: E'Message, E'Group, and E'Service get'mVals'E :: E'Entity -> Maybe EMap get'mVals'E (E'Ok entity) = get'mVals entity get'mVals'E (E'Error {}) = Nothing get'mVals :: Entity -> Maybe EMap get'mVals (E'Message {mVals = x}) = Just x get'mVals (E'Group {mVals = x}) = Just x get'mVals (E'Service {mVals = x}) = Just x get'mVals _ = Nothing -- | This is a helper for resolveEnv toGlobal :: Env -> Env toGlobal (Local _ _ env) = toGlobal env toGlobal x@(Global {}) = x getTL :: Env -> TopLevel getTL (Local _ _ env) = getTL env getTL (Global tl _tls) = tl getTLS :: Env -> (TopLevel,[TopLevel]) getTLS (Local _ _ env) = getTLS env getTLS (Global tl tls) = (tl, tls) -- | This is used for resolving some UninterpretedOption names resolveHere :: Entity -> Utf8 -> RE Entity resolveHere parent nameU = do let rFail msg = throw ("Could not lookup "++show (toString nameU)++"\n"++indent msg) x <- getJust ("resolveHere: validI nameU failed for "++show nameU) (fmap iToString (validI nameU)) case get'mVals parent of Just vals -> case M.lookup x vals of Just (E'Ok entity) -> return entity Just (E'Error s _) -> rFail ("because the name resolved to an error:\n" ++ indent s) Nothing -> rFail ("because there is no such name here: "++show (eName parent)) Nothing -> rFail ("because environment has no local names:\n"++ishow (eName parent)) -- | 'resolvePredEnv' is the query operation for the Env namespace. It recognizes names beginning -- with a '.' as already being fully-qualified names. This is called from the different monads via -- resolveEnv, resolveMGE, and resolveM -- -- The returned (Right _::Entity) will never be an E'Error, which results in (Left _::ErrStr) instead resolvePredEnv :: String -> (E'Entity -> Bool) -> Utf8 -> Env -> Either ErrStr Entity resolvePredEnv userMessage accept nameU envIn = do (isGlobal,xs) <- checkDIUtf8 nameU let mResult = if isGlobal then lookupEnv (map iToString xs) (toGlobal envIn) else lookupEnv (map iToString xs) envIn case mResult of Just (E'Ok e) -> return e Just (E'Error s _es) -> throw s Nothing -> throw . unlines $ [ "resolvePredEnv: Could not lookup " ++ show nameU , "which parses as " ++ show (isGlobal,xs) , "in environment: " ++ (whereEnv envIn) , "looking for: " ++ userMessage , "allowed (local): " ++ show (allowedLocal envIn) , "allowed (global): " ++ show (allowedGlobal envIn) ] where lookupEnv :: [IName String] -> Env -> Maybe E'Entity lookupEnv xs (Global tl tls) = let findThis = lookupTopLevel main xs where main = top'Package tl in msum (map findThis (tl:tls)) lookupEnv xs (Local _ vals env) = filteredLookup vals xs <|> lookupEnv xs env lookupTopLevel :: PackageID [IName String] -> [IName String] -> TopLevel -> Maybe E'Entity lookupTopLevel main xs tl = (if matchesMain main (top'Package tl) then filteredLookup (top'mVals tl) xs else Nothing) <|> (matchPrefix (top'Package tl) xs >>= filteredLookup (top'mVals tl)) where matchesMain (PackageID {_getPackageID=a}) (PackageID {_getPackageID=b}) = a==b matchesMain (NoPackageID {}) (PackageID {}) = False -- XXX XXX XXX 2012-09-19 suspicious matchesMain (PackageID {}) (NoPackageID {}) = True matchesMain (NoPackageID {}) (NoPackageID {}) = True matchPrefix (NoPackageID {}) _ = Nothing matchPrefix (PackageID {_getPackageID=a}) ys = stripPrefix a ys filteredLookup valsIn namesIn = let lookupVals :: EMap -> [IName String] -> Maybe E'Entity lookupVals _vals [] = Nothing lookupVals vals [x] = M.lookup x vals lookupVals vals (x:xs) = do entity <- M.lookup x vals case get'mVals'E entity of Just vals' -> lookupVals vals' xs Nothing -> Nothing m'x = lookupVals valsIn namesIn in case m'x of Just entity | accept entity -> m'x _ -> Nothing -- Used in resolveRE and getType.resolveSE. Accepts all types and so commits to first hit, but -- caller may reject some types later. resolveEnv :: Utf8 -> Env -> Either ErrStr Entity resolveEnv = resolvePredEnv "Any item" (const True) -- resolveRE is the often used workhorse of the fq* family of functions resolveRE :: Utf8 -> RE Entity resolveRE nameU = lift . (resolveEnv nameU) =<< ask -- | 'getType' is used to lookup the type strings in service method records. getType :: Show a => String -> (a -> Maybe Utf8) -> a -> SE (Maybe (Either ErrStr Entity)) getType s f a = do typeU <- getJust s (f a) case parseType (toString typeU) of Just _ -> return Nothing Nothing -> do ee <- resolveSE typeU return (Just (expectMGE ee)) where -- All uses of this then apply expectMGE or expectM, so provide predicate 'skip' support. resolveSE :: Utf8 -> SE (Either ErrStr Entity) resolveSE nameU = fmap (resolveEnv nameU) (asks my'Env) -- | 'expectMGE' is used by getType and 'entityField' expectMGE :: Either ErrStr Entity -> Either ErrStr Entity expectMGE ee@(Left {}) = ee expectMGE ee@(Right e) | isMGE = ee | otherwise = throw $ "expectMGE: Name resolution failed to find a Message, Group, or Enum:\n"++ishow (eName e) -- cannot show all of "e" because this will loop and hang the hprotoc program where isMGE = case e of E'Message {} -> True E'Group {} -> True E'Enum {} -> True _ -> False -- | This is a helper for resolveEnv and (Show SEnv) for error messages whereEnv :: Env -> String whereEnv (Local name _ env) = fiName (joinDot name) ++ " in "++show (top'Path . getTL $ env) -- WAS whereEnv (Global tl _) = fiName (joinDot (getPackageID (top'Package tl))) ++ " in " ++ show (top'Path tl) whereEnv (Global tl _) = formatPackageID ++ " in " ++ show (top'Path tl) where formatPackageID = case top'Package tl of PackageID {_getPackageID=x} -> fiName (joinDot x) NoPackageID {_getNoPackageID=y} -> show y -- | 'partEither' separates the Left errors and Right success in the obvious way. partEither :: [Either a b] -> ([a],[b]) partEither [] = ([],[]) partEither (Left a:xs) = let ~(ls,rs) = partEither xs in (a:ls,rs) partEither (Right b:xs) = let ~(ls,rs) = partEither xs in (ls,b:rs) -- | The 'unique' function is used with Data.Map.fromListWithKey to detect -- name collisions and record this as E'Error entries in the map. -- -- This constructs new E'Error values unique :: IName String -> E'Entity -> E'Entity -> E'Entity unique name (E'Error _ a) (E'Error _ b) = E'Error ("Namespace collision for "++show name) (a++b) unique name (E'Error _ a) b = E'Error ("Namespace collision for "++show name) (a++[b]) unique name a (E'Error _ b) = E'Error ("Namespace collision for "++show name) (a:b) unique name a b = E'Error ("Namespace collision for "++show name) [a,b] maybeM :: Monad m => (x -> m a) -> (Maybe x) -> m (Maybe a) maybeM f mx = maybe (return Nothing) (liftM Just . f) mx -- ReaderT containing template stacked on WriterT of list of name translations stacked on error reporting type MRM a = ReaderT ProtoName (WriterT [(FIName Utf8,ProtoName)] (Either ErrStr)) a runMRM'Reader :: MRM a -> ProtoName -> WriterT [(FIName Utf8,ProtoName)] (Either ErrStr) a runMRM'Reader = runReaderT runMRM'Writer :: WriterT [(FIName Utf8,ProtoName)] (Either ErrStr) a -> Either ErrStr (a,[(FIName Utf8,ProtoName)]) runMRM'Writer = runWriterT mrmName :: String -> (a -> Maybe Utf8) -> a -> MRM ProtoName mrmName s f a = do template <- ask iSelf <- getJust s (validI =<< f a) let mSelf = mangle iSelf fqSelf = fqAppend (protobufName template) [iSelf] self = template { protobufName = fqSelf , baseName = mSelf } template' = template { protobufName = fqSelf , parentModule = parentModule template ++ [mSelf] } tell [(fqSelf,self)] return template' -- Compute the nameMap that determine how to translate from proto names to haskell names -- The loop oever makeNameMap uses the (optional) package name -- makeNameMaps is called from the run' routine in ProtoCompile.hs for both standalone and plugin use. -- hPrefix and hAs are command line controlled options. -- hPrefix is "-p MODULE --prefix=MODULE dotted Haskell MODULE name to use as a prefix (default is none); last flag used" -- hAs is "-a FILEPATH=MODULE --as=FILEPATH=MODULE assign prefix module to imported prot file: --as descriptor.proto=Text" -- Note that 'setAs' puts both the full path and the basename as keys into the association list makeNameMaps :: [MName String] -> [(CanonFP,[MName String])] -> Env -> Either ErrStr NameMap makeNameMaps hPrefix hAs env = do let getPrefix fdp = case D.FileDescriptorProto.name fdp of Nothing -> hPrefix -- really likely to be an error elsewhere since this ought to be a filename Just n -> let path = CanonFP (toString n) in case lookup path hAs of Just p -> p Nothing -> case lookup (CanonFP . Canon.takeBaseName . unCanonFP $ path) hAs of Just p -> p Nothing -> hPrefix -- this is the usual branch unless overridden on command line let (tl,tls) = getTLS env (fdp:fdps) <- mapM top'FDP (tl:tls) (NameMap tuple m) <- makeNameMap (getPrefix fdp) fdp let f (NameMap _ x) = x ms <- fmap (map f) . mapM (\y -> makeNameMap (getPrefix y) y) $ fdps let nameMap = (NameMap tuple (M.unions (m:ms))) -- trace (show nameMap) $ return nameMap -- | 'makeNameMap' conservatively checks its input. makeNameMap :: [MName String] -> D.FileDescriptorProto -> Either ErrStr NameMap makeNameMap hPrefix fdpIn = go (makeOne fdpIn) where go = fmap ((\(a,w) -> NameMap a (M.fromList w))) . runMRM'Writer makeOne fdp = do -- Create 'template' :: ProtoName using "Text.ProtocolBuffers.Identifiers" with error for baseName let rawPackage = getPackage fdp :: PackageID Utf8 _ <- lift (checkPackageID rawPackage) -- guard-like effect {- -- Previously patched way of doing this let packageName = case D.FileDescriptorProto.package fdp of Nothing -> FIName $ fromString "" Just p -> difi $ DIName p -} let packageName :: PackageID (FIName Utf8) packageName = fmap (difi . DIName) rawPackage fi'package'name = getPackageID packageName rawParent <- getJust "makeNameMap.makeOne: impossible Nothing found" . msum $ [ D.FileOptions.java_outer_classname =<< (D.FileDescriptorProto.options fdp) , D.FileOptions.java_package =<< (D.FileDescriptorProto.options fdp) , Just (getPackageID rawPackage)] diParent <- getJust ("makeNameMap.makeOne: invalid character in: "++show rawParent) (validDI rawParent) let hParent = map (mangle :: IName Utf8 -> MName String) . splitDI $ diParent template = ProtoName fi'package'name hPrefix hParent (error "makeNameMap.makeOne.template.baseName undefined") runMRM'Reader (mrmFile fdp) template return (packageName,hPrefix,hParent) -- Traversal of the named DescriptorProto types mrmFile :: D.FileDescriptorProto -> MRM () mrmFile fdp = do F.mapM_ mrmMsg (D.FileDescriptorProto.message_type fdp) F.mapM_ mrmField (D.FileDescriptorProto.extension fdp) F.mapM_ mrmEnum (D.FileDescriptorProto.enum_type fdp) F.mapM_ mrmService (D.FileDescriptorProto.service fdp) mrmMsg dp = do template <- mrmName "mrmMsg.name" D.DescriptorProto.name dp local (const template) $ do F.mapM_ mrmEnum (D.DescriptorProto.enum_type dp) F.mapM_ mrmField (D.DescriptorProto.extension dp) F.mapM_ mrmField (D.DescriptorProto.field dp) F.mapM_ mrmMsg (D.DescriptorProto.nested_type dp) mrmField fdp = mrmName "mrmField.name" D.FieldDescriptorProto.name fdp mrmEnum edp = do template <- mrmName "mrmEnum.name" D.EnumDescriptorProto.name edp local (const template) $ F.mapM_ mrmEnumValue (D.EnumDescriptorProto.value edp) mrmEnumValue evdp = mrmName "mrmEnumValue.name" D.EnumValueDescriptorProto.name evdp mrmService sdp = do template <- mrmName "mrmService.name" D.ServiceDescriptorProto.name sdp local (const template) $ F.mapM_ mrmMethod (D.ServiceDescriptorProto.method sdp) mrmMethod mdp = mrmName "mrmMethod.name" D.MethodDescriptorProto.name mdp getNames :: String -> (a -> Maybe Utf8) -> a -> SE (IName String,[IName String]) getNames errorMessage accessor record = do parent <- asks my'Parent iSelf <- fmap iToString $ getJust errorMessage (validI =<< accessor record) let names = parent ++ [ iSelf ] return (iSelf,names) descend :: [IName String] -> Entity -> SE a -> SE a descend names entity act = local mutate act where mutate (SEnv _parent env) = SEnv parent' env' where parent' = names -- cannot call eName ename, will cause <<loop>> with "getNames" -- XXX revisit env' = Local (eName entity) (mVals entity) env -- Run each element of (Seq x) as (f x) with same initial environment and state. -- Then merge the output states and sort out the failures and successes. kids :: (x -> SE (IName String,E'Entity)) -> Seq x -> SE ([ErrStr],[(IName String,E'Entity)]) kids f xs = do sEnv <- ask let ans = map (runSE sEnv) . map f . F.toList $ xs return (partEither ans) -- | 'makeTopLevel' takes a .proto file's FileDescriptorProto and the TopLevel values of its -- directly imported file and constructs the TopLevel of the FileDescriptorProto in a Global -- Environment. -- -- This goes to some lengths to be a total function with good error messages. Errors in building -- the skeleton of the namespace are detected and reported instead of returning the new 'Global' -- environment. Collisions in the namespace are only detected when the offending name is looked up, -- and will return an E'Error entity with a message and list of colliding Entity items. The -- cross-linking of Entity fields may fail and this failure is stored in the corresponding Entity. -- -- Also caught: name collisions in Enum definitions. -- -- The 'mdo' usage has been replace by modified forms of 'mfix' that will generate useful error -- values instead of calling 'error' and halting 'hprotoc'. -- -- Used from loadProto' makeTopLevel :: D.FileDescriptorProto -> PackageID [IName String] -> [TopLevel] -> Either ErrStr Env {- Global -} makeTopLevel fdp packageName imports = do filePath <- getJust "makeTopLevel.filePath" (D.FileDescriptorProto.name fdp) let -- There should be no TYPE_GROUP in the extension list here, but to be safe: isGroup = (`elem` groupNames) where groupNamesRaw = map toString . mapMaybe D.FieldDescriptorProto.type_name . filter (maybe False (TYPE_GROUP ==) . D.FieldDescriptorProto.type') $ (F.toList . D.FileDescriptorProto.extension $ fdp) groupNamesI = mapMaybe validI groupNamesRaw groupNamesDI = mapMaybe validDI groupNamesRaw -- These fully qualified names from using hprotoc as a plugin for protoc groupNames = groupNamesI ++ map (last . splitDI) groupNamesDI (bad,global) <- myFixE ("makeTopLevel myFixE",emptyEnv) $ \ global'Param -> let sEnv = SEnv (get'SEnv'root'from'PackageID packageName) global'Param in runSE sEnv $ do (bads,children) <- fmap unzip . sequence $ [ kids (entityMsg isGroup) (D.FileDescriptorProto.message_type fdp) , kids (entityField True) (D.FileDescriptorProto.extension fdp) , kids entityEnum (D.FileDescriptorProto.enum_type fdp) , kids entityService (D.FileDescriptorProto.service fdp) ] let bad' = unlines (concat bads) global' = Global (TopLevel (toString filePath) packageName (resolveFDP fdp global') (M.fromListWithKey unique (concat children))) imports return (bad',global') -- Moving this outside the myFixE reduces the cases where myFixE generates an 'error' call. when (not (null bad)) $ throw $ "makeTopLevel.bad: Some children failed for "++show filePath++"\n"++bad return global where resolveFDP :: D.FileDescriptorProto -> Env -> Either ErrStr D.FileDescriptorProto resolveFDP fdpIn env = runRE env (fqFileDP fdpIn) where runRE :: Env -> RE D.FileDescriptorProto -> Either ErrStr D.FileDescriptorProto runRE envIn m = runReaderT m envIn -- Used from makeTopLevel, from loadProto' get'SEnv'root'from'PackageID :: PackageID [IName String] -> [IName String] get'SEnv'root'from'PackageID = getPackageID -- was mPackageID before 2012-09-19 -- where -- Used from get'SEnv makeTopLevel, from loadProto' -- mPackageID :: Monoid a => PackageID a -> a -- mPackageID (PackageID {_getPackageID=x}) = x -- mPackageID (NoPackageID {}) = mempty -- Copies of mFix for use the string in (Left msg) for the error message. -- Note that the usual mfix for Either calls 'error' while this does not, -- it uses a default value passed to myFix*. myFixSE :: (String,a) -> (a -> SE (String,a)) -> SE (String,a) myFixSE s f = ReaderT $ \r -> myFixE s (\a -> runReaderT (f a) r) -- Note that f ignores the fst argument myFixE :: (String,a) -> (a -> Either ErrStr (String,a)) -> Either ErrStr (String,a) myFixE s f = let a = f (unRight a) in a where unRight (Right x) = snd x unRight (Left _msg) = snd s -- ( "Text.ProtocolBuffers.ProtoCompile.Resolve: "++fst s ++":\n" ++ indent msg -- , snd s) {- *** All the entity* functions are used by makeTopLevel and each other. If there is no error then these return (IName String,E'Entity) and this E'Entity is always E'Ok. *** -} -- Fix this to look at groupNamesDI as well as the original list of groupNamesI. This fixes a bug -- in the plug-in usage because protoc will have already resolved the type_name to a fully qualified -- name. entityMsg :: (IName String -> Bool) -> D.DescriptorProto -> SE (IName String,E'Entity) entityMsg isGroup dp = annErr ("entityMsg DescriptorProto name is "++show (D.DescriptorProto.name dp)) $ do (self,names) <- getNames "entityMsg.name" D.DescriptorProto.name dp numbers <- fmap Set.fromList . mapM (getJust "entityMsg.field.number" . D.FieldDescriptorProto.number) . F.toList . D.DescriptorProto.field $ dp when (Set.size numbers /= Seq.length (D.DescriptorProto.field dp)) $ throwError $ "entityMsg.field.number: There must be duplicate field numbers for "++show names++"\n "++show numbers let groupNamesRaw = map toString . mapMaybe D.FieldDescriptorProto.type_name . filter (maybe False (TYPE_GROUP ==) . D.FieldDescriptorProto.type') $ (F.toList . D.DescriptorProto.field $ dp) ++ (F.toList . D.DescriptorProto.extension $ dp) groupNamesI = mapMaybe validI groupNamesRaw groupNamesDI = mapMaybe validDI groupNamesRaw -- These fully qualified names from using hprotoc as a plugin for protoc groupNames = groupNamesI ++ map (last . splitDI) groupNamesDI isGroup' = (`elem` groupNames) (bad,entity) <- myFixSE ("myFixSE entityMsg",emptyEntity) $ \ entity'Param -> descend names entity'Param $ do (bads,children) <- fmap unzip . sequence $ [ kids entityEnum (D.DescriptorProto.enum_type dp) , kids (entityField True) (D.DescriptorProto.extension dp) , kids (entityField False) (D.DescriptorProto.field dp) , kids (entityMsg isGroup') (D.DescriptorProto.nested_type dp) ] let bad' = unlines (concat bads) entity' | isGroup self = E'Group names (M.fromListWithKey unique (concat children)) | otherwise = E'Message names (getExtRanges dp) (M.fromListWithKey unique (concat children)) return (bad',entity') -- Moving this outside the myFixSE reduces the cases where myFixSE uses the error-default call. when (not (null bad)) $ throwError $ "entityMsg.bad: Some children failed for "++show names++"\n"++bad return (self,E'Ok $ entity) -- Among other things, this is where ambiguous type names in the proto file are resolved into a -- Message or a Group or an Enum. entityField :: Bool -> D.FieldDescriptorProto -> SE (IName String,E'Entity) entityField isKey fdp = annErr ("entityField FieldDescriptorProto name is "++show (D.FieldDescriptorProto.name fdp)) $ do (self,names) <- getNames "entityField.name" D.FieldDescriptorProto.name fdp let isKey' = maybe False (const True) (D.FieldDescriptorProto.extendee fdp) when (isKey/=isKey') $ throwError $ "entityField: Impossible? Expected key and got field or vice-versa:\n"++ishow ((isKey,isKey'),names,fdp) number <- getJust "entityField.name" . D.FieldDescriptorProto.number $ fdp let mType = D.FieldDescriptorProto.type' fdp typeName <- maybeM resolveMGE (D.FieldDescriptorProto.type_name fdp) if isKey then do extendee <- resolveM =<< getJust "entityField.extendee" (D.FieldDescriptorProto.extendee fdp) return (self,E'Ok $ E'Key names extendee (FieldId number) mType typeName) else return (self,E'Ok $ E'Field names (FieldId number) mType typeName) where resolveMGE :: Utf8 -> SE (Either ErrStr Entity) resolveMGE nameU = fmap (resolvePredEnv "Message or Group or Enum" isMGE nameU) (asks my'Env) where isMGE (E'Ok e') = case e' of E'Message {} -> True E'Group {} -> True E'Enum {} -> True _ -> False isMGE (E'Error {}) = False -- To be used for key extendee name resolution, but not part of the official protobuf-2.1.0 update, since made official resolveM :: Utf8 -> SE (Either ErrStr Entity) resolveM nameU = fmap (resolvePredEnv "Message" isM nameU) (asks my'Env) where isM (E'Ok e') = case e' of E'Message {} -> True _ -> False isM (E'Error {}) = False entityEnum :: D.EnumDescriptorProto -> SE (IName String,E'Entity) entityEnum edp@(D.EnumDescriptorProto {D.EnumDescriptorProto.value=vs}) = do (self,names) <- getNames "entityEnum.name" D.EnumDescriptorProto.name edp values <- mapM (getJust "entityEnum.value.number" . D.EnumValueDescriptorProto.number) . F.toList $ vs {- Cannot match protoc if I enable this as a fatal check here when (Set.size (Set.fromList values) /= Seq.length vs) $ throwError $ "entityEnum.value.number: There must be duplicate enum values for "++show names++"\n "++show values -} justNames <- mapM (\v -> getJust ("entityEnum.value.name failed for "++show v) (D.EnumValueDescriptorProto.name v)) . F.toList $ vs valNames <- mapM (\n -> getJust ("validI of entityEnum.value.name failed for "++show n) (validI n)) justNames let mapping = M.fromList (zip valNames values) when (M.size mapping /= Seq.length vs) $ throwError $ "entityEnum.value.name: There must be duplicate enum names for "++show names++"\n "++show valNames descend'Enum names $ F.mapM_ entityEnumValue vs return (self,E'Ok $ E'Enum names mapping) -- discard values where entityEnumValue :: D.EnumValueDescriptorProto -> SE () entityEnumValue evdp = do -- Merely use getNames to add mangled self to ReMap state _ <- getNames "entityEnumValue.name" D.EnumValueDescriptorProto.name evdp return () descend'Enum :: [IName String] -> SE a -> SE a descend'Enum names act = local mutate act where mutate (SEnv _parent env) = SEnv names env entityService :: D.ServiceDescriptorProto -> SE (IName String,E'Entity) entityService sdp = annErr ("entityService ServiceDescriptorProto name is "++show (D.ServiceDescriptorProto.name sdp)) $ do (self,names) <- getNames "entityService.name" D.ServiceDescriptorProto.name sdp (bad,entity) <- myFixSE ("myFixSE entityService",emptyEntity) $ \ entity'Param -> descend names entity'Param $ do (badMethods',goodMethods) <- kids entityMethod (D.ServiceDescriptorProto.method sdp) let bad' = unlines badMethods' entity' = E'Service names (M.fromListWithKey unique goodMethods) return (bad',entity') -- Moving this outside the myFixSE reduces the cases where myFixSE generates an 'error' call. when (not (null bad)) $ throwError $ "entityService.badMethods: Some methods failed for "++show names++"\n"++bad return (self,E'Ok entity) entityMethod :: D.MethodDescriptorProto -> SE (IName String,E'Entity) entityMethod mdp = do (self,names) <- getNames "entityMethod.name" D.MethodDescriptorProto.name mdp inputType <- getType "entityMethod.input_type" D.MethodDescriptorProto.input_type mdp outputType <- getType "entityMethod.output_type" D.MethodDescriptorProto.output_type mdp return (self,E'Ok $ E'Method names inputType outputType) {- *** The namespace Env is used to transform the original FileDescriptorProto into a canonical FileDescriptorProto. The goal is to match the transformation done by Google's protoc program. This will allow the "front end" vs "back end" of each program to cross-couple, which will at least allow better testing of hprotoc and the new UninterpretedOption support. The UninterpretedOption fields are converted by the resolveFDP code below. These should be total functions with no 'error' or 'undefined' values possible. *** -} fqFail :: Show a => String -> a -> Entity -> RE b fqFail msg dp entity = do env <- ask throw $ unlines [ msg, "resolving: "++show dp, "in environment: "++whereEnv env, "found: "++show (eName entity) ] fqFileDP :: D.FileDescriptorProto -> RE D.FileDescriptorProto fqFileDP fdp = annErr ("fqFileDP FileDescriptorProto (name,package) is "++show (D.FileDescriptorProto.name fdp,D.FileDescriptorProto.package fdp)) $ do newMessages <- T.mapM fqMessage (D.FileDescriptorProto.message_type fdp) newEnums <- T.mapM fqEnum (D.FileDescriptorProto.enum_type fdp) newServices <- T.mapM fqService (D.FileDescriptorProto.service fdp) newKeys <- T.mapM (fqField True) (D.FileDescriptorProto.extension fdp) consumeUNO $ fdp { D.FileDescriptorProto.message_type = newMessages , D.FileDescriptorProto.enum_type = newEnums , D.FileDescriptorProto.service = newServices , D.FileDescriptorProto.extension = newKeys } fqMessage :: D.DescriptorProto -> RE D.DescriptorProto fqMessage dp = annErr ("fqMessage DescriptorProto name is "++show (D.DescriptorProto.name dp)) $ do entity <- resolveRE =<< getJust "fqMessage.name" (D.DescriptorProto.name dp) (name,vals) <- case entity of E'Message {eName=name',mVals=vals'} -> return (name',vals') E'Group {eName=name',mVals=vals'} -> return (name',vals') _ -> fqFail "fqMessage.entity: did not resolve to an E'Message or E'Group:" dp entity local (\env -> (Local name vals env)) $ do newFields <- T.mapM (fqField False) (D.DescriptorProto.field dp) newKeys <- T.mapM (fqField True) (D.DescriptorProto.extension dp) newMessages <- T.mapM fqMessage (D.DescriptorProto.nested_type dp) newEnums <- T.mapM fqEnum (D.DescriptorProto.enum_type dp) consumeUNO $ dp { D.DescriptorProto.field = newFields , D.DescriptorProto.extension = newKeys , D.DescriptorProto.nested_type = newMessages , D.DescriptorProto.enum_type = newEnums } fqService :: D.ServiceDescriptorProto -> RE D.ServiceDescriptorProto fqService sdp = annErr ("fqService ServiceDescriptorProto name is "++show (D.ServiceDescriptorProto.name sdp)) $ do entity <- resolveRE =<< getJust "fqService.name" (D.ServiceDescriptorProto.name sdp) case entity of E'Service {eName=name,mVals=vals} -> do newMethods <- local (Local name vals) $ T.mapM fqMethod (D.ServiceDescriptorProto.method sdp) consumeUNO $ sdp { D.ServiceDescriptorProto.method = newMethods } _ -> fqFail "fqService.entity: did not resolve to a service:" sdp entity fqMethod :: D.MethodDescriptorProto -> RE D.MethodDescriptorProto fqMethod mdp = do entity <- resolveRE =<< getJust "fqMethod.name" (D.MethodDescriptorProto.name mdp) case entity of E'Method {eMsgIn=msgIn,eMsgOut=msgOut} -> do mdp1 <- case msgIn of Nothing -> return mdp Just resolveIn -> do new <- fmap fqName (lift resolveIn) return (mdp {D.MethodDescriptorProto.input_type = Just (fiName new)}) mdp2 <- case msgOut of Nothing -> return mdp1 Just resolveIn -> do new <- fmap fqName (lift resolveIn) return (mdp1 {D.MethodDescriptorProto.output_type = Just (fiName new)}) consumeUNO mdp2 _ -> fqFail "fqMethod.entity: did not resolve to a Method:" mdp entity -- The field is a bit more complicated to resolve. The Key variant needs to resolve the extendee. -- The type code from Parser.hs might be Nothing and this needs to be resolved to TYPE_MESSAGE or -- TYPE_ENUM (at last!), and if it is the latter then any default value string is checked for -- validity. fqField :: Bool -> D.FieldDescriptorProto -> RE D.FieldDescriptorProto fqField isKey fdp = annErr ("fqField FieldDescriptorProto name is "++show (D.FieldDescriptorProto.name fdp)) $ do let isKey' = maybe False (const True) (D.FieldDescriptorProto.extendee fdp) when (isKey/=isKey') $ ask >>= \env -> throwError $ "fqField.isKey: Expected key and got field or vice-versa:\n"++ishow ((isKey,isKey'),whereEnv env,fdp) entity <- expectFK =<< resolveRE =<< getJust "fqField.name" (D.FieldDescriptorProto.name fdp) newExtendee <- case (isKey,entity) of (True,E'Key {eMsg=msg,fNumber=fNum}) -> do ext <- lift msg case ext of E'Message {} -> when (not (checkFI (validExtensions ext) fNum)) $ throwError $ "fqField.newExtendee: Field Number of extention key invalid:\n" ++unlines ["Number is "++show (fNumber entity) ,"Valid ranges: "++show (validExtensions ext) ,"Extendee: "++show (eName ext) ,"Descriptor: "++show fdp] _ -> fqFail "fqField.ext: Key's target is not an E'Message:" fdp ext fmap (Just . fiName . fqName) . lift . eMsg $ entity (False,E'Field {}) -> return Nothing _ -> fqFail "fqField.entity: did not resolve to expected E'Key or E'Field:" fdp entity mTypeName <- maybeM lift (mVal entity) -- "Just (Left _)" triggers a throwError here (see comment for entityField) -- Finally fully determine D.Type, (type'==Nothing) meant ambiguously TYPE_MESSAGE or TYPE_ENUM from Parser.hs -- This has gotten more verbose with the addition of verifying packed is being used properly. actualType <- case (fType entity,mTypeName) of (Just TYPE_GROUP, Just (E'Group {})) | isNotPacked fdp -> return TYPE_GROUP | otherwise -> fqFail ("fqField.actualType : This Group is invalid, you cannot pack a group field.") fdp entity (Nothing, Just (E'Message {})) | isNotPacked fdp -> return TYPE_MESSAGE | otherwise -> fqFail ("fqField.actualType : This Message is invalid, you cannot pack a message field.") fdp entity (Nothing, Just (E'Enum {})) | isNotPacked fdp -> return TYPE_ENUM | isRepeated fdp -> return TYPE_ENUM | otherwise -> fqFail ("fqField.actualType : This Enum is invalid, you cannot pack a non-repeated field.") fdp entity (Just t, Nothing) -> return t (Just TYPE_MESSAGE, Just (E'Message {})) -> return TYPE_MESSAGE (Just TYPE_ENUM, Just (E'Enum {})) -> return TYPE_ENUM (mt,me) -> fqFail ("fqField.actualType: "++show mt++" and "++show (fmap eName me)++" is invalid.") fdp entity -- Check that a default value of an TYPE_ENUM is valid case (mTypeName,D.FieldDescriptorProto.default_value fdp) of (Just ee@(E'Enum {eVals = enumVals}),Just enumVal) -> let badVal = throwError $ "fqField.default_value: Default enum value is invalid:\n" ++unlines ["Value is "++show (toString enumVal) ,"Allowed values from "++show (eName ee) ," are "++show (M.keys enumVals) ,"Descriptor: "++show fdp] in case validI enumVal of Nothing -> badVal Just iVal -> when (M.notMember iVal enumVals) badVal _ -> return () consumeUNO $ if isKey then (fdp { D.FieldDescriptorProto.extendee = newExtendee , D.FieldDescriptorProto.type' = Just actualType , D.FieldDescriptorProto.type_name = fmap (fiName . fqName) mTypeName }) else (fdp { D.FieldDescriptorProto.type' = Just actualType , D.FieldDescriptorProto.type_name = fmap (fiName . fqName) mTypeName }) where isRepeated :: D.FieldDescriptorProto -> Bool isRepeated (D.FieldDescriptorProto { D.FieldDescriptorProto.label = Just LABEL_REPEATED }) = True isRepeated _ = False isNotPacked :: D.FieldDescriptorProto -> Bool isNotPacked (D.FieldDescriptorProto { D.FieldDescriptorProto.options = Just (D.FieldOptions { D.FieldOptions.packed = Just isPacked })}) = not isPacked isNotPacked _ = True expectFK :: Entity -> RE Entity expectFK e | isFK = return e | otherwise = throwError $ "expectF: Name resolution failed to find a Field or Key:\n"++ishow (eName e) where isFK = case e of E'Field {} -> True E'Key {} -> True _ -> False fqEnum :: D.EnumDescriptorProto -> RE D.EnumDescriptorProto fqEnum edp = do entity <- resolveRE =<< getJust "fqEnum.name" (D.EnumDescriptorProto.name edp) case entity of E'Enum {} -> do evdps <- T.mapM consumeUNO (D.EnumDescriptorProto.value edp) consumeUNO $ edp { D.EnumDescriptorProto.value = evdps } _ -> fqFail "fqEnum.entity: did not resolve to an E'Enum:" edp entity {- The consumeUNO calls above hide this cut-and-pasted boilerplate between interpretOptions and the DescriptorProto type -} class ConsumeUNO a where consumeUNO :: a -> RE a instance ConsumeUNO D.EnumDescriptorProto where consumeUNO a = maybe (return a) (processOpt >=> \o -> return $ a { D.EnumDescriptorProto.options = Just o }) (D.EnumDescriptorProto.options a) where processOpt m = do m' <- interpretOptions "EnumOptions" m (D.EnumOptions.uninterpreted_option m) return (m' { D.EnumOptions.uninterpreted_option = mempty }) instance ConsumeUNO D.EnumValueDescriptorProto where consumeUNO a = maybe (return a) (processOpt >=> \o -> return $ a { D.EnumValueDescriptorProto.options = Just o }) (D.EnumValueDescriptorProto.options a) where processOpt m = do m' <- interpretOptions "EnumValueOptions" m (D.EnumValueOptions.uninterpreted_option m) return (m' { D.EnumValueOptions.uninterpreted_option = mempty }) instance ConsumeUNO D.MethodDescriptorProto where consumeUNO a = maybe (return a) (processOpt >=> \o -> return $ a { D.MethodDescriptorProto.options = Just o }) (D.MethodDescriptorProto.options a) where processOpt m = do m' <- interpretOptions "MethodOptions" m (D.MethodOptions.uninterpreted_option m) return (m' { D.MethodOptions.uninterpreted_option = mempty }) instance ConsumeUNO D.ServiceDescriptorProto where consumeUNO a = maybe (return a) (processOpt >=> \o -> return $ a { D.ServiceDescriptorProto.options = Just o }) (D.ServiceDescriptorProto.options a) where processOpt m = do m' <- interpretOptions "ServiceOptions" m (D.ServiceOptions.uninterpreted_option m) return (m' { D.ServiceOptions.uninterpreted_option = mempty }) instance ConsumeUNO D.FieldDescriptorProto where consumeUNO a = maybe (return a) (processOpt >=> \o -> return $ a { D.FieldDescriptorProto.options = Just o }) (D.FieldDescriptorProto.options a) where processOpt m = do m' <- interpretOptions "FieldOptions" m (D.FieldOptions.uninterpreted_option m) return (m' { D.FieldOptions.uninterpreted_option = mempty }) instance ConsumeUNO D.FileDescriptorProto where consumeUNO a = maybe (return a) (processOpt >=> \o -> return $ a { D.FileDescriptorProto.options = Just o }) (D.FileDescriptorProto.options a) where processOpt m = do m' <- interpretOptions "FileOptions" m (D.FileOptions.uninterpreted_option m) return (m' { D.FileOptions.uninterpreted_option = mempty }) instance ConsumeUNO D.DescriptorProto where consumeUNO a = maybe (return a) (processOpt >=> \o -> return $ a { D.DescriptorProto.options = Just o }) (D.DescriptorProto.options a) where processOpt m = do m' <- interpretOptions "MessageOptions" m (D.MessageOptions.uninterpreted_option m) return (m' { D.MessageOptions.uninterpreted_option = mempty }) {- The boilerplate above feeds interpretOptions to do the real work -} -- 'interpretOptions' is used by the 'consumeUNO' instances -- This prepends the ["google","protobuf"] and updates all the options into the ExtField of msg interpretOptions :: ExtendMessage msg => String -> msg -> Seq D.UninterpretedOption -> RE msg interpretOptions name msg unos = do name' <- getJust ("interpretOptions: invalid name "++show name) (validI name) ios <- mapM (interpretOption [IName "google",IName "protobuf",name']) . F.toList $ unos let (ExtField ef) = getExtField msg ef' = foldl' (\m (k,v) -> seq v $ M.insertWithKey mergeWires k v m) ef ios mergeWires _k (ExtFromWire newData) (ExtFromWire oldData) = ExtFromWire (mappend oldData newData) {- mergeWires k (ExtFromWire wt1 newData) (ExtFromWire wt2 oldData) = if wt1 /= wt2 then err $ "interpretOptions.mergeWires : ExtFromWire WireType mismatch while storing new options in extension fields: " ++ show (name,k,(wt1,wt2)) else ExtFromWire wt2 (mappend oldData newData) -} mergeWires k a b = err $ "interpretOptions.mergeWires : impossible case\n"++show (k,a,b) msg' = seq ef' (putExtField (ExtField ef') msg) return msg' -- 'interpretOption' is called by 'interpretOptions' -- The 'interpretOption' function is quite long because there are two things going on. -- The first is the actual type must be retrieved from the UninterpretedOption and encoded. -- The second is that messages/groups holding messages/groups ... holding the above must wrap this. -- Both of the above might come from extension keys or from field names. -- And as usual, there are many ways thing could conceivable go wrong or be out of bounds. -- -- The first parameter must be a name such as ["google","protobuf","FieldOption"] interpretOption :: [IName String] -> D.UninterpretedOption -> RE (FieldId,ExtFieldValue) interpretOption optName uno = case F.toList (D.UninterpretedOption.name uno) of [] -> iFail $ "Empty name_part" (part:parts) -> go Nothing optName part parts where iFail :: String -> RE a -- needed by ghc-7.0.2 iFail msg = do env <- ask throw $ unlines [ "interpretOption: Failed to handle UninterpretedOption for: "++show optName , " environment: "++whereEnv env , " value: "++show uno , " message: "++msg ] -- This takes care of an intermediate message or group type go :: Maybe Entity {- E'Message E'Group -} -> [IName String] -> D.NamePart -> [D.NamePart] -> RE (FieldId,ExtFieldValue) go mParent names (D.NamePart { D.NamePart.name_part = name , D.NamePart.is_extension = isKey }) (next:rest) = do -- get entity (Field or Key) and the TYPE_* -- fk will ceratinly be E'Field or E'Key (fk,entity) <- if not isKey then case mParent of Nothing -> iFail $ "Cannot resolve local (is_extension False) name, no parent; expected (key)." Just parent -> do entity'field <- resolveHere parent name case entity'field of (E'Field {}) -> case mVal entity'field of Nothing -> iFail $ "Intermediate entry E'Field is of basic type, not E'Message or E'Group: "++show (names,eName entity'field) Just val -> lift val >>= \e -> return (entity'field,e) _ -> iFail $ "Name "++show (toString name)++" was resolved but was not an E'Field: "++show (eName entity'field) else do entity'key <- resolveRE name case entity'key of (E'Key {eMsg=msg}) -> do extendee <- lift msg when (eName extendee /= names) $ iFail $ "Intermediate entry E'Key extends wrong type: "++show (names,eName extendee) case mVal entity'key of Nothing-> iFail $ "Intermediate entry E'Key is of basic type, not E'Message or E'Group: "++show (names,eName entity'key) Just val -> lift val >>= \e -> return (entity'key,e) _ -> iFail $ "Name "++show (toString name)++" was resolved but was not an E'Key: "++show (eName entity'key) t <- case entity of E'Message {} -> return TYPE_MESSAGE E'Group {} -> return TYPE_GROUP _ -> iFail $ "Intermediate entry is not an E'Message or E'Group: "++show (eName entity) -- recursive call to get inner result (fid',ExtFromWire raw') <- go (Just entity) (eName entity) next rest -- wrap old tag + inner result with outer info let tag@(WireTag tag') = mkWireTag fid' wt' (EP wt' bs') = Seq.index raw' 0 let fid = fNumber fk -- safe by construction of fk wt = toWireType (FieldType (fromEnum t)) bs = runPut $ case t of TYPE_MESSAGE -> do putSize (size'WireTag tag + LC.length bs') putVarUInt tag' putLazyByteString bs' TYPE_GROUP -> do putVarUInt tag' putLazyByteString bs' putVarUInt (succ (getWireTag (mkWireTag fid wt))) _ -> fail $ "bug! raw with type "++show t++" should be impossible" return (fid,ExtFromWire (Seq.singleton (EP wt bs))) -- This takes care of the acutal value of the option, which must be a basic type go mParent names (D.NamePart { D.NamePart.name_part = name , D.NamePart.is_extension = isKey }) [] = do -- get entity (Field or Key) and the TYPE_* fk <- if isKey then resolveRE name else case mParent of Just parent -> resolveHere parent name Nothing -> iFail $ "Cannot resolve local (is_extension False) name, no parent; expected (key)." case fk of E'Field {} | not isKey -> return () E'Key {} | isKey -> do ext <- lift (eMsg fk) when (eName ext /= names) $ iFail $ "Last entry E'Key extends wrong type: "++show (names,eName ext) _ -> iFail $ "Last entity was resolved but was not an E'Field or E'Key: "++show fk t <- case (fType fk) of Nothing -> return TYPE_ENUM -- XXX not a good assumption with aggregate types !!!! This also covers groups and messages. Just TYPE_GROUP -> iFail $ "Last entry was a TYPE_GROUP instead of concrete value type" -- impossible Just TYPE_MESSAGE -> {- impossible -} iFail $ "Last entry was a TYPE_MESSAGE instead of concrete value type" -- impossible Just typeCode -> return typeCode -- Need to define a polymorphic 'done' to convert actual data type to its wire encoding let done :: Wire v => v -> RE (FieldId,ExtFieldValue) done v = let ft = FieldType (fromEnum t) wt = toWireType ft fid = fNumber fk in return (fid,ExtFromWire (Seq.singleton (EP wt (runPut (wirePut ft v))))) -- The actual type and value fed to 'done' depends on the values 't' and 'uno': case t of TYPE_ENUM -> -- Now must also also handle Message and Group case (mVal fk,D.UninterpretedOption.identifier_value uno,D.UninterpretedOption.aggregate_value uno) of (Just (Right (E'Enum {eVals=enumVals})),Just enumVal,_) -> case validI enumVal of Nothing -> iFail $ "invalid D.UninterpretedOption.identifier_value: "++show enumVal Just enumIVal -> case M.lookup enumIVal enumVals of Nothing -> iFail $ "enumVal lookup failed: "++show (enumIVal,M.keys enumVals) Just val -> done (fromEnum val) -- fromEnum :: Int32 -> Int (Just (Right (E'Enum {})),Nothing,_) -> iFail $ "No identifer_value value to lookup in E'Enum" (Just (Right (E'Message {})),_,Nothing) -> iFail "Expected aggregate syntax to set a message option" (Just (Right (E'Message {})),_,Just aggVal) -> iFail $ "\n\n\ \=========================================================================================\n\ \Google's 2.4.0 aggregate syntax for message options is not yet supported, value would be:\n\ \=========================================================================================\n" ++ show aggVal (Just (Right (E'Group {})),_,Nothing) -> iFail "Expected aggregate syntax to set a group option (impossible?)" (Just (Right (E'Group {})),_,Just aggVal) -> iFail $ "\n\n\ \=========================================================================================\n\ \Google's 2.4.0 aggregate syntax for message options is not yet supported, value would be:\n\ \=========================================================================================\n" ++ show aggVal (me,_,_) -> iFail $ "Expected Just E'Enum or E'Message or E'Group, got:\n"++show me TYPE_STRING -> do bs <- getJust "UninterpretedOption.string_value" (D.UninterpretedOption.string_value uno) maybe (done (Utf8 bs)) (\i -> iFail $ "Invalid utf8 in string_value at index: "++show i) (isValidUTF8 bs) TYPE_BYTES -> done =<< getJust "UninterpretedOption.string_value" (D.UninterpretedOption.string_value uno) TYPE_BOOL -> done =<< bVal TYPE_DOUBLE -> done =<< dVal TYPE_FLOAT -> done =<< asFloat =<< dVal TYPE_INT64 -> done =<< (iVal :: RE Int64) TYPE_SFIXED64 -> done =<< (iVal :: RE Int64) TYPE_SINT64 -> done =<< (iVal :: RE Int64) TYPE_UINT64 -> done =<< (iVal :: RE Word64) TYPE_FIXED64 -> done =<< (iVal :: RE Word64) TYPE_INT32 -> done =<< (iVal :: RE Int32) TYPE_SFIXED32 -> done =<< (iVal :: RE Int32) TYPE_SINT32 -> done =<< (iVal :: RE Int32) TYPE_UINT32 -> done =<< (iVal :: RE Word32) TYPE_FIXED32 -> done =<< (iVal :: RE Word32) _ -> iFail $ "bug! go with type "++show t++" should be impossible" -- Machinery needed by the final call of go bVal :: RE Bool bVal = let true = Utf8 (U.fromString "true") false = Utf8 (U.fromString "false") in case D.UninterpretedOption.identifier_value uno of Just s | s == true -> return True | s == false -> return False _ -> iFail "Expected 'true' or 'false' identifier_value" dVal :: RE Double dVal = case (D.UninterpretedOption.negative_int_value uno ,D.UninterpretedOption.positive_int_value uno ,D.UninterpretedOption.double_value uno) of (_,_,Just d) -> return d (_,Just p,_) -> return (fromIntegral p) (Just n,_,_) -> return (fromIntegral n) _ -> iFail "No numeric value" asFloat :: Double -> RE Float asFloat d = let fmax :: Ratio Integer fmax = (2-(1%2)^(23::Int)) * (2^(127::Int)) d' = toRational d in if (negate fmax <= d') && (d' <= fmax) then return (fromRational d') else iFail $ "Double out of range for Float: "++show d rangeCheck :: forall a. (Bounded a,Integral a) => Integer -> RE a rangeCheck i = let r = (toInteger (minBound ::a),toInteger (maxBound :: a)) in if inRange r i then return (fromInteger i) else iFail $ "Constant out of range: "++show (r,i) asInt :: Double -> RE Integer asInt x = let (a,b) = properFraction x in if b==0 then return a else iFail $ "Double value not an integer: "++show x iVal :: (Bounded y, Integral y) => RE y iVal = case (D.UninterpretedOption.negative_int_value uno ,D.UninterpretedOption.positive_int_value uno ,D.UninterpretedOption.double_value uno) of (_,Just p,_) -> rangeCheck (toInteger p) (Just n,_,_) -> rangeCheck (toInteger n) (_,_,Just d) -> rangeCheck =<< asInt d _ -> iFail "No numeric value" -- | 'findFile' looks through the current and import directories to find the target file on the system. -- It also converts the relative path to a standard form to use as the name of the FileDescriptorProto. findFile :: [LocalFP] -> LocalFP -> IO (Maybe (LocalFP,CanonFP)) -- absolute and canonical parts findFile paths (LocalFP target) = test paths where test [] = return Nothing test (LocalFP path:rest) = do let fullname = Local.combine path target found <- doesFileExist fullname -- stop at first hit if not found then test rest else do truepath <- canonicalizePath path truefile <- canonicalizePath fullname if truepath `isPrefixOf` truefile then do let rel = fpLocalToCanon (LocalFP (Local.makeRelative truepath truefile)) return (Just (LocalFP truefile,rel)) else fail $ "file found but it is not below path, cannot make canonical name:\n path: " ++show truepath++"\n file: "++show truefile -- | Given a path, tries to find and parse a FileDescriptorProto -- corresponding to it; returns also a canonicalised path. type DescriptorReader m = (Monad m) => LocalFP -> m (D.FileDescriptorProto, LocalFP) loadProto' :: (Functor r,Monad r) => DescriptorReader r -> LocalFP -> r (Env,[D.FileDescriptorProto]) loadProto' fdpReader protoFile = goState (load Set.empty protoFile) where goState act = do (env,m) <- runStateT act mempty let fromRight (Right x) = x fromRight (Left s) = error $ "loadProto failed to resolve a FileDescriptorProto: "++s return (env,map (fromRight . top'FDP . fst . getTLS) (M.elems m)) load parentsIn file = do built <- get when (Set.member file parentsIn) (loadFailed file (unlines ["imports failed: recursive loop detected" ,unlines . map show . M.assocs $ built,show parentsIn])) case M.lookup file built of -- check memorized results Just result -> return result Nothing -> do (parsed'fdp, canonicalFile) <- lift $ fdpReader file let rawPackage = getPackage parsed'fdp packageName <- either (loadFailed canonicalFile . show) (return . fmap (map iToString . snd)) -- 2012-09-19 suspicious (checkPackageID rawPackage) {- -- OLD before 2012-09-19 packageName <- either (loadFailed canonicalFile . show) (return . PackageID . map iToString . snd) -- 2012-09-19 suspicious (checkPackageID rawPackage) -} {- -- previously patched solution packageName <- case D.FileDescriptorProto.package parsed'fdp of Nothing -> return [] Just p -> either (loadFailed canonicalFile . show) (return . map iToString . snd) $ (checkDIUtf8 p) -} let parents = Set.insert file parentsIn importList = map (fpCanonToLocal . CanonFP . toString) . F.toList . D.FileDescriptorProto.dependency $ parsed'fdp imports <- mapM (fmap getTL . load parents) importList let eEnv = makeTopLevel parsed'fdp packageName imports -- makeTopLevel is the "internal entry point" of Resolve.hs -- Stricly force these two value to report errors here global'env <- either (loadFailed file) return eEnv _ <- either (loadFailed file) return (top'FDP . getTL $ global'env) modify (M.insert file global'env) -- add to memorized results return global'env loadFailed :: (Monad m) => LocalFP -> String -> m a loadFailed f msg = fail . unlines $ ["Parsing proto:",show (unLocalFP f),"has failed with message",msg] -- | Given a list of paths to search, loads proto files by -- looking for them in the file system. loadProto :: [LocalFP] -> LocalFP -> IO (Env,[D.FileDescriptorProto]) loadProto protoDirs protoFile = loadProto' findAndParseSource protoFile where findAndParseSource :: DescriptorReader IO findAndParseSource file = do mayToRead <- liftIO $ findFile protoDirs file case mayToRead of Nothing -> loadFailed file (unlines (["loading failed, could not find file: "++show (unLocalFP file) ,"Searched paths were:"] ++ map ((" "++).show.unLocalFP) protoDirs)) Just (toRead,relpath) -> do protoContents <- liftIO $ do putStrLn ("Loading filepath: "++show (unLocalFP toRead)) LC.readFile (unLocalFP toRead) parsed'fdp <- either (loadFailed toRead . show) return $ (parseProto (unCanonFP relpath) protoContents) return (parsed'fdp, toRead) loadCodeGenRequest :: CGR.CodeGeneratorRequest -> LocalFP -> (Env,[D.FileDescriptorProto]) loadCodeGenRequest req protoFile = runIdentity $ loadProto' lookUpParsedSource protoFile where lookUpParsedSource :: DescriptorReader Identity lookUpParsedSource file = case M.lookup file fdpsByName of Just result -> return (result, file) Nothing -> loadFailed file ("Request refers to file: "++show (unLocalFP file) ++" but it was not supplied in the request.") fdpsByName = M.fromList . map keyByName . F.toList . CGR.proto_file $ req keyByName fdp = (fdpName fdp, fdp) fdpName = LocalFP . maybe "" (LC.unpack . utf8) . D.FileDescriptorProto.name -- wart: descend should take (eName,eMvals) not Entity -- wart: myFix* obviously implements a WriterT by hand. Implement as WriterT ?
edahlgren/protocol-buffers
hprotoc/Text/ProtocolBuffers/ProtoCompile/Resolve.hs
Haskell
apache-2.0
78,001
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses, FlexibleInstances, UndecidableInstances, RebindableSyntax, DataKinds, TypeOperators, PolyKinds, FlexibleContexts, ConstraintKinds, IncoherentInstances, GADTs #-} module Control.Effect.State (Set(..), get, put, State(..), (:->)(..), (:!)(..), Eff(..), Action(..), Var(..), union, UnionS, Reads(..), Writes(..), Unionable, Sortable, SetLike, StateSet, --- may not want to export these IntersectR, Update, Sort, Split) where import Control.Effect import Data.Type.Set hiding (Unionable, union, SetLike, Nub, Nubable(..)) import qualified Data.Type.Set as Set --import Data.Type.Map (Mapping(..), Var(..)) import Prelude hiding (Monad(..),reads) import GHC.TypeLits {-| Provides an effect-parameterised version of the state monad, which gives an effect system for stateful computations with annotations that are sets of variable-type-action triples. -} {-| Distinguish reads, writes, and read-writes -} data Eff = R | W | RW {-| Provides a wrapper for effect actions -} data Action (s :: Eff) = Eff instance Show (Action R) where show _ = "R" instance Show (Action W) where show _ = "W" instance Show (Action RW) where show _ = "RW" infixl 2 :-> data (k :: Symbol) :-> (v :: *) = (Var k) :-> v data Var (k :: Symbol) where Var :: Var k {- Some special defaults for some common names -} X :: Var "x" Y :: Var "y" Z :: Var "z" instance (Show (Var k), Show v) => Show (k :-> v) where show (k :-> v) = "(" ++ show k ++ " :-> " ++ show v ++ ")" instance Show (Var "x") where show X = "x" show Var = "Var" instance Show (Var "y") where show Y = "y" show Var = "Var" instance Show (Var "z") where show Z = "z" show Var = "Var" instance Show (Var v) where show _ = "Var" {-| Symbol comparison -} type instance Cmp (v :-> a) (u :-> b) = CmpSymbol v u {-| Describes an effect action 's' on a value of type 'a' -} --data EffMapping a (s :: Eff) = a :! (Action s) data a :! (s :: Eff) = a :! (Action s) instance (Show (Action f), Show a) => Show (a :! f) where show (a :! f) = show a ++ " ! " ++ show f infixl 3 :! type SetLike s = Nub (Sort s) type UnionS s t = Nub (Sort (s :++ t)) type Unionable s t = (Sortable (s :++ t), Nubable (Sort (s :++ t)) (Nub (Sort (s :++ t))), Split s t (Union s t)) {-| Union operation for state effects -} union :: (Unionable s t) => Set s -> Set t -> Set (UnionS s t) union s t = nub (quicksort (append s t)) {-| Type-level remove duplicates from a type-level list and turn different sorts into 'RW'| -} type family Nub t where Nub '[] = '[] Nub '[e] = '[e] Nub (e ': e ': as) = Nub (e ': as) Nub ((k :-> a :! s) ': (k :-> a :! t) ': as) = Nub ((k :-> a :! RW) ': as) Nub (e ': f ': as) = e ': Nub (f ': as) {-| Value-level remove duplicates from a type-level list and turn different sorts into 'RW'| -} class Nubable t v where nub :: Set t -> Set v instance Nubable '[] '[] where nub Empty = Empty instance Nubable '[e] '[e] where nub (Ext e Empty) = (Ext e Empty) instance Nubable ((k :-> b :! s) ': as) as' => Nubable ((k :-> a :! s) ': (k :-> b :! s) ': as) as' where nub (Ext _ (Ext x xs)) = nub (Ext x xs) instance Nubable ((k :-> a :! RW) ': as) as' => Nubable ((k :-> a :! s) ': (k :-> a :! t) ': as) as' where nub (Ext _ (Ext (k :-> (a :! _)) xs)) = nub (Ext (k :-> (a :! (Eff::(Action RW)))) xs) instance Nubable ((j :-> b :! t) ': as) as' => Nubable ((k :-> a :! s) ': (j :-> b :! t) ': as) ((k :-> a :! s) ': as') where nub (Ext (k :-> (a :! s)) (Ext (j :-> (b :! t)) xs)) = Ext (k :-> (a :! s)) (nub (Ext (j :-> (b :! t)) xs)) {-| Update reads, that is any writes are pushed into reads, a bit like intersection -} class Update s t where update :: Set s -> Set t instance Update xs '[] where update _ = Empty instance Update '[e] '[e] where update s = s {- instance Update ((v :-> b :! R) ': as) as' => Update ((v :-> a :! s) ': (v :-> b :! s) ': as) as' where update (Ext _ (Ext (v :-> (b :! _)) xs)) = update (Ext (v :-> (b :! (Eff::(Action R)))) xs) -} instance Update ((v :-> a :! R) ': as) as' => Update ((v :-> a :! W) ': (v :-> b :! R) ': as) as' where update (Ext (v :-> (a :! _)) (Ext _ xs)) = update (Ext (v :-> (a :! (Eff::(Action R)))) xs) instance Update ((u :-> b :! s) ': as) as' => Update ((v :-> a :! W) ': (u :-> b :! s) ': as) as' where update (Ext _ (Ext e xs)) = update (Ext e xs) instance Update ((u :-> b :! s) ': as) as' => Update ((v :-> a :! R) ': (u :-> b :! s) ': as) ((v :-> a :! R) ': as') where update (Ext e (Ext e' xs)) = Ext e $ update (Ext e' xs) type IntersectR s t = (Sortable (s :++ t), Update (Sort (s :++ t)) t) {-| Intersects a set of write effects and a set of read effects, updating any read effects with any corresponding write value -} intersectR :: (Reads t ~ t, Writes s ~ s, IsSet s, IsSet t, IntersectR s t) => Set s -> Set t -> Set t intersectR s t = update (quicksort (append s t)) {-| Parametric effect state monad -} data State s a = State { runState :: Set (Reads s) -> (a, Set (Writes s)) } {-| Calculate just the reader effects -} type family Reads t where Reads '[] = '[] Reads ((k :-> a :! R) ': xs) = (k :-> a :! R) ': (Reads xs) Reads ((k :-> a :! RW) ': xs) = (k :-> a :! R) ': (Reads xs) Reads ((k :-> a :! W) ': xs) = Reads xs {-| Calculate just the writer effects -} type family Writes t where Writes '[] = '[] Writes ((k :-> a :! W) ': xs) = (k :-> a :! W) ': (Writes xs) Writes ((k :-> a :! RW) ': xs) = (k :-> a :! W) ': (Writes xs) Writes ((k :-> a :! R) ': xs) = Writes xs {-| Read from a variable 'v' of type 'a'. Raise a read effect. -} get :: Var v -> State '[v :-> a :! R] a get _ = State $ \(Ext (v :-> (a :! _)) Empty) -> (a, Empty) {-| Write to a variable 'v' with a value of type 'a'. Raises a write effect -} put :: Var v -> a -> State '[v :-> a :! W] () put _ a = State $ \Empty -> ((), Ext (Var :-> a :! Eff) Empty) {-| Captures what it means to be a set of state effects -} type StateSet f = (StateSetProperties f, StateSetProperties (Reads f), StateSetProperties (Writes f)) type StateSetProperties f = (IntersectR f '[], IntersectR '[] f, UnionS f '[] ~ f, Split f '[] f, UnionS '[] f ~ f, Split '[] f f, UnionS f f ~ f, Split f f f, Unionable f '[], Unionable '[] f) -- Indexed monad instance instance Effect State where type Inv State s t = (IsSet s, IsSet (Reads s), IsSet (Writes s), IsSet t, IsSet (Reads t), IsSet (Writes t), Reads (Reads t) ~ Reads t, Writes (Writes s) ~ Writes s, Split (Reads s) (Reads t) (Reads (UnionS s t)), Unionable (Writes s) (Writes t), IntersectR (Writes s) (Reads t), Writes (UnionS s t) ~ UnionS (Writes s) (Writes t)) {-| Pure state effect is the empty state -} type Unit State = '[] {-| Combine state effects via specialised union (which combines R and W effects on the same variable into RW effects -} type Plus State s t = UnionS s t return x = State $ \Empty -> (x, Empty) (State e) >>= k = State $ \st -> let (sR, tR) = split st (a, sW) = e sR (b, tW) = (runState $ k a) (sW `intersectR` tR) in (b, sW `union` tW) {- instance (Split s t (Union s t), Sub s t) => Subeffect State s t where sub (State e) = IxR $ \st -> let (s, t) = split st _ = ReflP p t in e s -}
dorchard/effect-monad
src/Control/Effect/State.hs
Haskell
bsd-2-clause
8,221
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.PhoneNumber.AR.Corpus ( corpus , negativeCorpus ) where import Prelude import Data.String import Duckling.Locale import Duckling.PhoneNumber.Types import Duckling.Resolve import Duckling.Testing.Types corpus :: Corpus corpus = (testContext { locale = makeLocale AR Nothing }, testOptions, allExamples) negativeCorpus :: NegativeCorpus negativeCorpus = (testContext, testOptions, xs) where xs = [ "١٢٣٤٥" , "١٢٣٤٥٦٧٨٩٠١٢٣٤٥٦٧٧٧٧٧٧" , "١٢٣٤٥٦٧٨٩٠١٢٣٤٥٦" ] -- Tests include both unicode characters and equivalent unicode decimal code -- representation because the Arabic phone number regex is constructed with -- unicode decimal form. allExamples :: [Example] allExamples = concat [ examples (PhoneNumberValue "6507018887") [ "٦٥٠٧٠١٨٨٨٧" , "\1638\1637\1632\1639\1632\1633\1640\1640\1640\1639" , "٦٥٠ ٧٠١ ٨٨٨٧" , "\1638\1637\1632 \1639\1632\1633 \1640\1640\1640\1639" , "٦٥٠-٧٠١-٨٨٨٧" , "\1638\1637\1632-\1639\1632\1633-\1640\1640\1640\1639" ] , examples (PhoneNumberValue "(+1) 6507018887") [ "+١ ٦٥٠٧٠١٨٨٨٧" , "+\1633 \1638\1637\1632\1639\1632\1633\1640\1640\1640\1639" , "(+١)٦٥٠٧٠١٨٨٨٧" , "(+\1633)\1638\1637\1632\1639\1632\1633\1640\1640\1640\1639" , "(+١) ٦٥٠ - ٧٠١ ٨٨٨٧" , "(+\1633) \1638\1637\1632 - \1639\1632\1633 \1640\1640\1640\1639" ] , examples (PhoneNumberValue "(+33) 146647998") [ "+٣٣ ١ ٤٦٦٤٧٩٩٨" , "+\1635\1635 \1633 \1636\1638\1638\1636\1639\1641\1641\1640" ] , examples (PhoneNumberValue "0620702220") [ "٠٦ ٢٠٧٠ ٢٢٢٠" ] , examples (PhoneNumberValue "6507018887 ext 897") [ "٦٥٠٧٠١٨٨٨٧ ext ٨٩٧" , "٦٥٠٧٠١٨٨٨٧ x ٨٩٧" , "٦٥٠٧٠١٨٨٨٧ ext. ٨٩٧" ] , examples (PhoneNumberValue "6507018887 ext 897") [ "٦٥٠٧٠١٨٨٨٧ فرعي ٨٩٧" ] , examples (PhoneNumberValue "(+1) 2025550121") [ "+١-٢٠٢-٥٥٥-٠١٢١" , "+١ ٢٠٢.٥٥٥.٠١٢١" ] , examples (PhoneNumberValue "4866827") [ "٤.٨.٦.٦.٨.٢.٧" ] , examples (PhoneNumberValue "(+55) 19992842606") [ "(+٥٥) ١٩٩٩٢٨٤٢٦٠٦" ] ]
facebookincubator/duckling
Duckling/PhoneNumber/AR/Corpus.hs
Haskell
bsd-3-clause
2,919
{-# OPTIONS -fglasgow-exts #-} module GisServer.Data.Common ( LexicalLevel, lexLevel , fieldTermChar, fieldTerm , recordTermChar, recordTerm , getStringN, getStringEncoded, getStringTill , getInt, getIntN ) where import Data.Binary import Data.Binary.Get import Data.Char import Int import qualified Data.Bits as Bits import qualified Data.ByteString.Lazy as B import Test.QuickCheck import Data.Text as T import qualified Data.Encoding as E import Data.Encoding.ASCII import Data.Encoding.UTF16 import Data.Encoding.ISO88591 data LexicalLevel = LexLevel0 | LexLevel1 | LexLevel2 deriving (Eq, Show, Ord, Enum) lexLevel :: Int -> LexicalLevel lexLevel = toEnum fieldTermChar = '\RS' fieldTerm :: Word8 fieldTerm = fromIntegral $ ord fieldTermChar recordTermChar = '\US' recordTerm :: Word8 recordTerm = fromIntegral $ ord recordTermChar getStringTill :: LexicalLevel -> Get String getStringTill l = getStringTill' l fieldTerm getStringTill' l c = undefined --getStringTill = getStringTill' LexLevel0 --getStringTill' l c = do -- c' <- fmap (word8char l) get -- if (c' == c) -- then do return [c'] -- else do cs <- getStringTill' l c -- return $ c:cs getIntN :: Int -> Get Int getIntN n = fmap read $ getStringN LexLevel0 n getStringN l n = fmap (getStringEncoded l) $ getLazyByteString $ fromIntegral n getStringEncoded LexLevel0 = E.decodeLazyByteString ASCII getStringEncoded LexLevel1 = E.decodeLazyByteString ISO88591 getStringEncoded LexLevel2 = E.decodeLazyByteString UTF16LE getInt :: Bool -> Int -> Get Int getInt s 4 = if (s) then do v <- fmap decomplement2 getWord32le return $ negate $ fromIntegral v else fmap fromIntegral getWord32le prop_readInt8 :: Int8 -> Bool prop_readInt8 i = let bs = encode i decode = runGet (getInt True 1) bs in decode == fromIntegral i complement2 :: (Bits.Bits t) => t -> t complement2 x = 1 + Bits.complement x decomplement2 :: (Bits.Bits t) => t -> t decomplement2 x = Bits.complement $ x - 1 instance Arbitrary Word64 where arbitrary = arbitrarySizedIntegral instance Arbitrary Int8 where arbitrary = arbitrarySizedIntegral prop_complement2 :: Word64 -> Bool prop_complement2 x = x == decomplement2 (complement2 x)
alios/gisserver
GisServer/Data/Common.hs
Haskell
bsd-3-clause
2,485
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} -- | Github API: http://developer.github.com/v3/oauth/ module Main where import Control.Monad (mzero) import Data.Aeson import qualified Data.ByteString as BS import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import Network.HTTP.Conduit import URI.ByteString import URI.ByteString.QQ import Network.OAuth.OAuth2 import Keys main :: IO () main = do let state = "testGithubApi" print $ serializeURIRef' $ appendQueryParams [("state", state)] $ authorizationUrl githubKey putStrLn "visit the url and paste code here: " code <- getLine mgr <- newManager tlsManagerSettings let (url, body) = accessTokenUrl githubKey $ ExchangeToken $ T.pack $ code token <- doJSONPostRequest mgr githubKey url (body ++ [("state", state)]) print (token :: OAuth2Result OAuth2Token) case token of Right at -> userInfo mgr (accessToken at) >>= print Left _ -> putStrLn "no access token found yet" -- | Test API: user -- userInfo :: Manager -> AccessToken -> IO (OAuth2Result GithubUser) userInfo mgr token = authGetJSON mgr token [uri|https://api.github.com/user|] data GithubUser = GithubUser { gid :: Integer , gname :: Text } deriving (Show, Eq) instance FromJSON GithubUser where parseJSON (Object o) = GithubUser <$> o .: "id" <*> o .: "name" parseJSON _ = mzero sToBS :: String -> BS.ByteString sToBS = T.encodeUtf8 . T.pack
reactormonk/hoauth2
example/Github/test.hs
Haskell
bsd-3-clause
1,761
{-# OPTIONS -fno-implicit-prelude #-} ----------------------------------------------------------------------------- -- | -- Module : Data.HashTable -- Copyright : (c) The University of Glasgow 2003 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : provisional -- Portability : portable -- -- An implementation of extensible hash tables, as described in -- Per-Ake Larson, /Dynamic Hash Tables/, CACM 31(4), April 1988, -- pp. 446--457. The implementation is also derived from the one -- in GHC's runtime system (@ghc\/rts\/Hash.{c,h}@). -- ----------------------------------------------------------------------------- module Data.HashTable ( -- * Basic hash table operations HashTable, new, insert, delete, lookup, -- * Converting to and from lists fromList, toList, -- * Hash functions -- $hash_functions hashInt, hashString, prime, -- * Diagnostics longestChain ) where -- This module is imported by Data.Dynamic, which is pretty low down in the -- module hierarchy, so don't import "high-level" modules import Prelude hiding ( lookup ) import Data.Tuple ( fst ) import Data.Bits import Data.Maybe import Data.List ( maximumBy, filter, length, concat ) import Data.Int ( Int32 ) import Data.Char ( ord ) import Data.IORef ( IORef, newIORef, readIORef, writeIORef ) import Hugs.IOArray ( IOArray, newIOArray, readIOArray, writeIOArray, unsafeReadIOArray, unsafeWriteIOArray ) import Control.Monad ( when, mapM, sequence_ ) ----------------------------------------------------------------------- myReadArray :: IOArray Int32 a -> Int32 -> IO a myWriteArray :: IOArray Int32 a -> Int32 -> a -> IO () myReadArray arr i = unsafeReadIOArray arr (fromIntegral i) myWriteArray arr i x = unsafeWriteIOArray arr (fromIntegral i) x -- | A hash table mapping keys of type @key@ to values of type @val@. -- -- The implementation will grow the hash table as necessary, trying to -- maintain a reasonable average load per bucket in the table. -- newtype HashTable key val = HashTable (IORef (HT key val)) -- TODO: the IORef should really be an MVar. data HT key val = HT { split :: !Int32, -- Next bucket to split when expanding max_bucket :: !Int32, -- Max bucket of smaller table mask1 :: !Int32, -- Mask for doing the mod of h_1 (smaller table) mask2 :: !Int32, -- Mask for doing the mod of h_2 (larger table) kcount :: !Int32, -- Number of keys bcount :: !Int32, -- Number of buckets dir :: !(IOArray Int32 (IOArray Int32 [(key,val)])), hash_fn :: key -> Int32, cmp :: key -> key -> Bool } {- ALTERNATIVE IMPLEMENTATION: This works out slightly slower, because there's a tradeoff between allocating a complete new HT structure each time a modification is made (in the version above), and allocating new Int32s each time one of them is modified, as below. Using FastMutInt instead of IORef Int32 helps, but yields an implementation which has about the same performance as the version above (and is more complex). data HashTable key val = HashTable { split :: !(IORef Int32), -- Next bucket to split when expanding max_bucket :: !(IORef Int32), -- Max bucket of smaller table mask1 :: !(IORef Int32), -- Mask for doing the mod of h_1 (smaller table) mask2 :: !(IORef Int32), -- Mask for doing the mod of h_2 (larger table) kcount :: !(IORef Int32), -- Number of keys bcount :: !(IORef Int32), -- Number of buckets dir :: !(IOArray Int32 (IOArray Int32 [(key,val)])), hash_fn :: key -> Int32, cmp :: key -> key -> Bool } -} -- ----------------------------------------------------------------------------- -- Sample hash functions -- $hash_functions -- -- This implementation of hash tables uses the low-order /n/ bits of the hash -- value for a key, where /n/ varies as the hash table grows. A good hash -- function therefore will give an even distribution regardless of /n/. -- -- If your keyspace is integrals such that the low-order bits between -- keys are highly variable, then you could get away with using 'id' -- as the hash function. -- -- We provide some sample hash functions for 'Int' and 'String' below. -- | A sample hash function for 'Int', implemented as simply @(x `mod` P)@ -- where P is a suitable prime (currently 1500007). Should give -- reasonable results for most distributions of 'Int' values, except -- when the keys are all multiples of the prime! -- hashInt :: Int -> Int32 hashInt = (`rem` prime) . fromIntegral -- | A sample hash function for 'String's. The implementation is: -- -- > hashString = fromIntegral . foldr f 0 -- > where f c m = ord c + (m * 128) `rem` 1500007 -- -- which seems to give reasonable results. -- hashString :: String -> Int32 hashString = fromIntegral . foldr f 0 where f c m = ord c + (m * 128) `rem` fromIntegral prime -- | A prime larger than the maximum hash table size prime :: Int32 prime = 1500007 -- ----------------------------------------------------------------------------- -- Parameters sEGMENT_SIZE = 1024 :: Int32 -- Size of a single hash table segment sEGMENT_SHIFT = 10 :: Int -- derived sEGMENT_MASK = 0x3ff :: Int32 -- derived dIR_SIZE = 1024 :: Int32 -- Size of the segment directory -- Maximum hash table size is sEGMENT_SIZE * dIR_SIZE hLOAD = 4 :: Int32 -- Maximum average load of a single hash bucket -- ----------------------------------------------------------------------------- -- Creating a new hash table -- | Creates a new hash table new :: (key -> key -> Bool) -- ^ An equality comparison on keys -> (key -> Int32) -- ^ A hash function on keys -> IO (HashTable key val) -- ^ Returns: an empty hash table new cmp hash_fn = do -- make a new hash table with a single, empty, segment dir <- newIOArray (0,dIR_SIZE) undefined segment <- newIOArray (0,sEGMENT_SIZE-1) [] myWriteArray dir 0 segment let split = 0 max = sEGMENT_SIZE mask1 = (sEGMENT_SIZE - 1) mask2 = (2 * sEGMENT_SIZE - 1) kcount = 0 bcount = sEGMENT_SIZE ht = HT { dir=dir, split=split, max_bucket=max, mask1=mask1, mask2=mask2, kcount=kcount, bcount=bcount, hash_fn=hash_fn, cmp=cmp } table <- newIORef ht return (HashTable table) -- ----------------------------------------------------------------------------- -- Inserting a key\/value pair into the hash table -- | Inserts an key\/value mapping into the hash table. insert :: HashTable key val -> key -> val -> IO () insert (HashTable ref) key val = do table@HT{ kcount=k, bcount=b, dir=dir } <- readIORef ref let table1 = table{ kcount = k+1 } table2 <- if (k > hLOAD * b) then expandHashTable table1 else return table1 writeIORef ref table2 (segment_index,segment_offset) <- tableLocation table key segment <- myReadArray dir segment_index bucket <- myReadArray segment segment_offset myWriteArray segment segment_offset ((key,val):bucket) return () bucketIndex :: HT key val -> key -> IO Int32 bucketIndex HT{ hash_fn=hash_fn, split=split, mask1=mask1, mask2=mask2 } key = do let h = fromIntegral (hash_fn key) small_bucket = h .&. mask1 large_bucket = h .&. mask2 -- if small_bucket < split then return large_bucket else return small_bucket tableLocation :: HT key val -> key -> IO (Int32,Int32) tableLocation table key = do bucket_index <- bucketIndex table key let segment_index = bucket_index `shiftR` sEGMENT_SHIFT segment_offset = bucket_index .&. sEGMENT_MASK -- return (segment_index,segment_offset) expandHashTable :: HT key val -> IO (HT key val) expandHashTable table@HT{ dir=dir, split=split, max_bucket=max, mask2=mask2 } = do let oldsegment = split `shiftR` sEGMENT_SHIFT oldindex = split .&. sEGMENT_MASK newbucket = max + split newsegment = newbucket `shiftR` sEGMENT_SHIFT newindex = newbucket .&. sEGMENT_MASK -- when (newindex == 0) $ do segment <- newIOArray (0,sEGMENT_SIZE-1) [] myWriteArray dir newsegment segment -- let table' = if (split+1) < max then table{ split = split+1 } -- we've expanded all the buckets in this table, so start from -- the beginning again. else table{ split = 0, max_bucket = max * 2, mask1 = mask2, mask2 = mask2 `shiftL` 1 .|. 1 } let split_bucket old new [] = do segment <- myReadArray dir oldsegment myWriteArray segment oldindex old segment <- myReadArray dir newsegment myWriteArray segment newindex new split_bucket old new ((k,v):xs) = do h <- bucketIndex table' k if h == newbucket then split_bucket old ((k,v):new) xs else split_bucket ((k,v):old) new xs -- segment <- myReadArray dir oldsegment bucket <- myReadArray segment oldindex split_bucket [] [] bucket return table' -- ----------------------------------------------------------------------------- -- Deleting a mapping from the hash table -- | Remove an entry from the hash table. delete :: HashTable key val -> key -> IO () delete (HashTable ref) key = do table@HT{ dir=dir, cmp=cmp } <- readIORef ref (segment_index,segment_offset) <- tableLocation table key segment <- myReadArray dir segment_index bucket <- myReadArray segment segment_offset myWriteArray segment segment_offset (filter (not.(key `cmp`).fst) bucket) return () -- ----------------------------------------------------------------------------- -- Looking up an entry in the hash table -- | Looks up the value of a key in the hash table. lookup :: HashTable key val -> key -> IO (Maybe val) lookup (HashTable ref) key = do table@HT{ dir=dir, cmp=cmp } <- readIORef ref (segment_index,segment_offset) <- tableLocation table key segment <- myReadArray dir segment_index bucket <- myReadArray segment segment_offset case [ val | (key',val) <- bucket, cmp key key' ] of [] -> return Nothing (v:_) -> return (Just v) -- ----------------------------------------------------------------------------- -- Converting to/from lists -- | Convert a list of key\/value pairs into a hash table. Equality on keys -- is taken from the Eq instance for the key type. -- fromList :: Eq key => (key -> Int32) -> [(key,val)] -> IO (HashTable key val) fromList hash_fn list = do table <- new (==) hash_fn sequence_ [ insert table k v | (k,v) <- list ] return table -- | Converts a hash table to a list of key\/value pairs. -- toList :: HashTable key val -> IO [(key,val)] toList (HashTable ref) = do HT{ dir=dir, max_bucket=max, split=split } <- readIORef ref -- let max_segment = (max + split - 1) `quot` sEGMENT_SIZE -- segments <- mapM (segmentContents dir) [0 .. max_segment] return (concat segments) where segmentContents dir seg_index = do segment <- myReadArray dir seg_index bs <- mapM (myReadArray segment) [0 .. sEGMENT_SIZE-1] return (concat bs) -- ----------------------------------------------------------------------------- -- Diagnostics -- | This function is useful for determining whether your hash function -- is working well for your data set. It returns the longest chain -- of key\/value pairs in the hash table for which all the keys hash to -- the same bucket. If this chain is particularly long (say, longer -- than 10 elements), then it might be a good idea to try a different -- hash function. -- longestChain :: HashTable key val -> IO [(key,val)] longestChain (HashTable ref) = do HT{ dir=dir, max_bucket=max, split=split } <- readIORef ref -- let max_segment = (max + split - 1) `quot` sEGMENT_SIZE -- --trace ("maxChainLength: max = " ++ show max ++ ", split = " ++ show split ++ ", max_segment = " ++ show max_segment) $ do segments <- mapM (segmentMaxChainLength dir) [0 .. max_segment] return (maximumBy lengthCmp segments) where segmentMaxChainLength dir seg_index = do segment <- myReadArray dir seg_index bs <- mapM (myReadArray segment) [0 .. sEGMENT_SIZE-1] return (maximumBy lengthCmp bs) lengthCmp x y = length x `compare` length y
OS2World/DEV-UTIL-HUGS
libraries/Data/HashTable.hs
Haskell
bsd-3-clause
12,055
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE LambdaCase #-} module Zodiac.Cli.TSRP.Env( tsrpParamsFromEnv ) where import Control.Monad.IO.Class (liftIO) import Data.ByteString (ByteString) import qualified Data.Text as T import qualified Data.Text.Encoding as T import P import System.Environment (lookupEnv) import System.IO (IO) import X.Control.Monad.Trans.Either (EitherT, left) import Zodiac.Raw import Zodiac.Cli.TSRP.Data import Zodiac.Cli.TSRP.Error tsrpParamsFromEnv :: EitherT TSRPError IO TSRPParams tsrpParamsFromEnv = do sk <- getEnvParam "TSRP_SECRET_KEY" >>= (parseParam "symmetric key" parseTSRPKey) kid <- getEnvParam "TSRP_KEY_ID" >>= (parseParam "key ID" parseKeyId) pure $ TSRPParams sk kid parseParam :: Text -> (ByteString -> Maybe' a) -> Text -> EitherT TSRPError IO a parseParam var f t = maybe' (left . TSRPParamError $ InvalidParam var t) pure $ (f . T.encodeUtf8) t getEnvParam :: Text -> EitherT TSRPError IO Text getEnvParam var = liftIO (lookupEnv (T.unpack var)) >>= \case Nothing -> left . TSRPParamError $ MissingRequiredParam var Just val -> pure $ T.pack val
ambiata/zodiac
zodiac-cli/src/Zodiac/Cli/TSRP/Env.hs
Haskell
bsd-3-clause
1,276
{-# LANGUAGE OverloadedStrings #-} module Data.Conduit.Succinct.JsonSpec (spec) where import Control.Monad.Trans.Resource (MonadThrow) import Data.ByteString import Data.Conduit import Data.Conduit.Succinct.Json import Data.Int import Data.Succinct import Test.Hspec import Data.Conduit.Tokenize.Attoparsec import Data.Conduit.Tokenize.Attoparsec.Offset import Data.Json.Token markerToBits :: [Int64] -> [Bool] markerToBits ms = runListConduit ms (markerToByteString =$= byteStringToBits) jsonToBits :: [ByteString] -> [Bool] jsonToBits json = runListConduit json $ textToJsonToken =$= jsonToken2Markers =$= markerToByteString =$= byteStringToBits jsonToMarkerBS :: [ByteString] -> [ByteString] jsonToMarkerBS json = runListConduit json $ textToJsonToken =$= jsonToken2Markers =$= markerToByteString jsonToMarkers :: [ByteString] -> [Int64] jsonToMarkers json = runListConduit json $ textToJsonToken =$= jsonToken2Markers jsonToken2Markers2 :: [(ParseDelta Offset, JsonToken)] -> [Int64] jsonToken2Markers2 json = runListConduit json $ jsonToken2Markers identity :: Monad m => Conduit i m i identity = do ma <- await case ma of Just a -> yield a Nothing -> return () spec :: Spec spec = describe "Data.Conduit.Succinct.JsonSpec" $ do it "No markers should produce no bits" $ markerToBits [] `shouldBe` [] it "One marker < 8 should produce one byte with one bit set" $ do markerToBits [0] `shouldBe` stringToBits "10000000" markerToBits [1] `shouldBe` stringToBits "01000000" markerToBits [2] `shouldBe` stringToBits "00100000" markerToBits [3] `shouldBe` stringToBits "00010000" markerToBits [4] `shouldBe` stringToBits "00001000" markerToBits [5] `shouldBe` stringToBits "00000100" markerToBits [6] `shouldBe` stringToBits "00000010" markerToBits [7] `shouldBe` stringToBits "00000001" it "One 8 <= marker < 16 should produce one byte empty byte and another byte with one bit set" $ do markerToBits [ 8] `shouldBe` stringToBits "00000000 10000000" markerToBits [ 9] `shouldBe` stringToBits "00000000 01000000" markerToBits [10] `shouldBe` stringToBits "00000000 00100000" markerToBits [11] `shouldBe` stringToBits "00000000 00010000" markerToBits [12] `shouldBe` stringToBits "00000000 00001000" markerToBits [13] `shouldBe` stringToBits "00000000 00000100" markerToBits [14] `shouldBe` stringToBits "00000000 00000010" markerToBits [15] `shouldBe` stringToBits "00000000 00000001" it "All markers 0 .. 7 should produce one full byte" $ markerToBits [0, 1, 2, 3, 4, 5, 6, 7] `shouldBe` stringToBits "11111111" it "All markers 0 .. 7 except 1 should produce one almost full byte" $ do markerToBits [1, 2, 3, 4, 5, 6, 7] `shouldBe` stringToBits "01111111" markerToBits [0, 2, 3, 4, 5, 6, 7] `shouldBe` stringToBits "10111111" markerToBits [0, 1, 3, 4, 5, 6, 7] `shouldBe` stringToBits "11011111" markerToBits [0, 1, 2, 4, 5, 6, 7] `shouldBe` stringToBits "11101111" markerToBits [0, 1, 2, 3, 5, 6, 7] `shouldBe` stringToBits "11110111" markerToBits [0, 1, 2, 3, 4, 6, 7] `shouldBe` stringToBits "11111011" markerToBits [0, 1, 2, 3, 4, 5, 7] `shouldBe` stringToBits "11111101" markerToBits [0, 1, 2, 3, 4, 5, 6] `shouldBe` stringToBits "11111110" it "All markers 0 .. 8 should produce one almost full byte and one near empty byte" $ markerToBits [0, 1, 2, 3, 4, 5, 6, 7, 8] `shouldBe` stringToBits "11111111 10000000" it "Matching bits for bytes" $ runListConduit [pack [0x80], pack [0xff], pack [0x01]] byteStringToBits `shouldBe` stringToBits "00000001 11111111 10000000" it "Every interesting token should produce a marker" $ jsonToken2Markers2 [ (ParseDelta (Offset 0) (Offset 1), JsonTokenBraceL), (ParseDelta (Offset 1) (Offset 2), JsonTokenBraceL), (ParseDelta (Offset 2) (Offset 3), JsonTokenBraceR), (ParseDelta (Offset 3) (Offset 4), JsonTokenBraceR)] `shouldBe` [0, 1, 2, 3] describe "When converting Json to tokens to markers to bits" $ do it "Empty Json should produce no bits" $ jsonToBits [""] `shouldBe` [] it "Spaces and newlines should produce no bits" $ jsonToBits [" \n \r \t "] `shouldBe` [] it "number at beginning should produce one bit" $ jsonToBits ["1234 "] `shouldBe` stringToBits "10000000" it "false at beginning should produce one bit" $ jsonToBits ["false "] `shouldBe` stringToBits "10000000" it "true at beginning should produce one bit" $ jsonToBits ["true "] `shouldBe` stringToBits "10000000" it "string at beginning should produce one bit" $ jsonToBits ["\"hello\" "] `shouldBe` stringToBits "10000000" it "left brace at beginning should produce one bit" $ jsonToBits ["{ "] `shouldBe` stringToBits "10000000" it "right brace at beginning should produce one bit" $ jsonToBits ["} "] `shouldBe` stringToBits "10000000" it "left bracket at beginning should produce one bit" $ jsonToBits ["[ "] `shouldBe` stringToBits "10000000" it "right bracket at beginning should produce one bit" $ jsonToBits ["] "] `shouldBe` stringToBits "10000000" it "right bracket at beginning should produce one bit" $ jsonToBits [": "] `shouldBe` stringToBits "10000000" it "right bracket at beginning should produce one bit" $ jsonToBits [", "] `shouldBe` stringToBits "10000000" it "Four consecutive braces should produce four bits" $ jsonToBits ["{{}}"] `shouldBe` stringToBits "11110000" it "Four spread out braces should produce four spread out bits" $ jsonToBits [" { { } } "] `shouldBe` stringToBits "01010101"
haskell-works/conduit-succinct-json
test/Data/Conduit/Succinct/JsonSpec.hs
Haskell
bsd-3-clause
5,764
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.ARB.CullDistance -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.ARB.CullDistance ( -- * Extension Support glGetARBCullDistance, gl_ARB_cull_distance, -- * Enums pattern GL_MAX_COMBINED_CLIP_AND_CULL_DISTANCES, pattern GL_MAX_CULL_DISTANCES ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens
haskell-opengl/OpenGLRaw
src/Graphics/GL/ARB/CullDistance.hs
Haskell
bsd-3-clause
699
{-# OPTIONS -XDeriveDataTypeable #-} -- this program imput numbers and calculate their factorials. The workflow control a record all the inputs and outputs -- so that when the program restart, all the previous results are shown. -- if the program abort by a runtime error or a power failure, the program will still work -- enter 0 for exit and finalize the workflow (all the intermediate data will be erased) -- enter any alphanumeric character for aborting and then re-start. module Main where import Control.Workflow import Data.Typeable import Data.Binary import Data.RefSerialize import Data.Maybe fact 0 =1 fact n= n * fact (n-1) -- now the workflow versión data Fact= Fact Integer Integer deriving (Typeable, Read, Show) instance Binary Fact where put (Fact n v)= put n >> put v get= do n <- get v <- get return $ Fact n v instance Serialize Fact where showp= showpBinary readp= readpBinary factorials = do all <- getAll let lfacts = mapMaybe safeFromIDyn all :: [Fact] unsafeIOtoWF $ putStrLn "Factorials calculated so far:" unsafeIOtoWF $ mapM (\fct -> print fct) lfacts factLoop (Fact 0 1) where factLoop fct= do nf <- plift $ do -- plift == step putStrLn "give me a number if you enter a letter or 0, the program will abort. Then, please restart to see how the program continues" str<- getLine let n= read str :: Integer -- if you enter alphanumeric characters the program will abort. please restart let fct= fact n print fct return $ Fact n fct case nf of Fact 0 _ -> do unsafeIOtoWF $ print "bye" return (Fact 0 0) _ -> factLoop nf main = exec1 "factorials" factorials
agocorona/Workflow
Demos/fact.hs
Haskell
bsd-3-clause
1,741
module FillingJars ( getlines, startjars ) where getlines :: Int -> IO Integer getlines m | m <= 0 = do return 0 | otherwise = do x_temp <- getLine let x_t = words x_temp let a = read $ x_t!!0 :: Integer let b = read $ x_t!!1 :: Integer let k = read $ x_t!!2 :: Integer total <- getlines (m-1) let ret = total + (b - a + 1)*k return ret startjars :: Int -> IO () startjars cnt | cnt <= 0 = putStrLn "" | otherwise = do x_temp <- getLine let x_t = words x_temp let n = read $ x_t!!0 :: Integer let m = read $ x_t!!1 :: Int total <- getlines m let t = total `div` n print t
zuoqin/hackerrank
src/FillingJars.hs
Haskell
bsd-3-clause
741
module Module3.Task17 where -- system code coins :: (Ord a, Num a) => [a] coins = [2, 3, 7] -- solution code change :: (Ord a, Num a) => a -> [[a]] change 0 = [[]] change s = [coin:ch | coin <- coins, coin <= s, ch <- (change $ s - coin)]
dstarcev/stepic-haskell
src/Module3/Task17.hs
Haskell
bsd-3-clause
241
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module CommandLine (readOptions) where import Control.Applicative ((<$>), (<*>)) import Control.Arrow (first) import Control.Monad (unless) import Data.Maybe (fromMaybe) import System.Console.GetOpt (getOpt, ArgOrder(..), OptDescr(..), ArgDescr(..)) import System.Exit (exitFailure) import Network (PortID(..), PortNumber) import Network.PeyoTLS.ReadFile ( CertSecretKey, readKey, readCertificateChain, readCertificateStore) import Network.PeyoTLS.Server (CipherSuite(..), KeyExchange(..), BulkEncryption(..)) import qualified Data.X509 as X509 import qualified Data.X509.CertificateStore as X509 readOptions :: [String] -> IO ( PortID, [CipherSuite], (CertSecretKey, X509.CertificateChain), (CertSecretKey, X509.CertificateChain), Maybe X509.CertificateStore, FilePath ) readOptions args = do let (os, as, es) = getOpt Permute options args unless (null es) $ mapM_ putStr es >> exitFailure unless (null as) $ putStrLn ("naked args: " ++ show as) >> exitFailure opts <- either ((>> exitFailure) . putStr) return $ construct os let prt = PortNumber 443 `fromMaybe` optPort opts css = maybe id (drop . fromEnum) (optLevel opts) cipherSuites td = "test" `fromMaybe` optTestDirectory opts rkf = "localhost.key" `fromMaybe` optRsaKeyFile opts rcf = "localhost.crt" `fromMaybe` optRsaCertFile opts ekf = "localhost_ecdsa.key" `fromMaybe` optEcKeyFile opts ecf = "localhost_ecdsa.cert" `fromMaybe` optEcCertFile opts rsa <- (,) <$> readKey rkf <*> readCertificateChain rcf ec <- (,) <$> readKey ekf <*> readCertificateChain ecf mcs <- if optDisableClientCert opts then return Nothing else Just <$> readCertificateStore ["cacert.pem"] return (prt, css, rsa, ec, mcs, td) data Options = Options { optPort :: Maybe PortID, optLevel :: Maybe CipherSuiteLevel, optRsaKeyFile :: Maybe FilePath, optRsaCertFile :: Maybe FilePath, optEcKeyFile :: Maybe FilePath, optEcCertFile :: Maybe FilePath, optDisableClientCert :: Bool, optTestDirectory :: Maybe FilePath } deriving Show nullOptions :: Options nullOptions = Options { optPort = Nothing, optLevel = Nothing, optRsaKeyFile = Nothing, optRsaCertFile = Nothing, optEcKeyFile = Nothing, optEcCertFile = Nothing, optDisableClientCert = False, optTestDirectory = Nothing } construct :: [Option] -> Either String Options construct [] = return nullOptions construct (o : os) = do c <- construct os case o of OptPort p -> ck (optPort c) >> return c { optPort = Just p } OptDisableClientCert -> if optDisableClientCert c then Left "CommandLine.construct: duplicated -d options\n" else return c { optDisableClientCert = True } OptLevel (NoLevel l) -> Left $ "CommandLine.construct: no such level " ++ show l ++ "\n" OptLevel csl -> ck (optLevel c) >> return c { optLevel = Just csl } OptTestDirectory td -> ck (optTestDirectory c) >> return c { optTestDirectory = Just td } OptRsaKeyFile kf -> ck (optRsaKeyFile c) >> return c { optRsaKeyFile = Just kf } OptRsaCertFile cf -> ck (optRsaCertFile c) >> return c { optRsaCertFile = Just cf } OptEcKeyFile ekf -> ck (optEcKeyFile c) >> return c { optEcKeyFile = Just ekf } OptEcCertFile ecf -> ck (optEcCertFile c) >> return c { optEcCertFile = Just ecf } where ck :: Show a => Maybe a -> Either String () ck = maybe (Right ()) (Left . ("Can't set: already " ++) . (++ "\n") . show) data Option = OptPort PortID | OptLevel CipherSuiteLevel | OptRsaKeyFile FilePath | OptRsaCertFile FilePath | OptEcKeyFile FilePath | OptEcCertFile FilePath | OptDisableClientCert | OptTestDirectory FilePath deriving (Show, Eq) options :: [OptDescr Option] options = [ Option "p" ["port"] (ReqArg (OptPort . PortNumber . read) "port number") "set port number", Option "l" ["level"] (ReqArg (OptLevel . readCipherSuiteLevel) "cipher suite level") "set cipher suite level", Option "k" ["rsa-key-file"] (ReqArg OptRsaKeyFile "RSA key file") "set RSA key file", Option "c" ["rsa-cert-file"] (ReqArg OptRsaCertFile "RSA cert file") "set RSA cert file", Option "K" ["ecdsa-key-file"] (ReqArg OptEcKeyFile "ECDSA key file") "set ECDSA key file", Option "C" ["ecdsa-cert-file"] (ReqArg OptEcCertFile "ECDSA cert file") "set ECDSA cert file", Option "d" ["disable-client-cert"] (NoArg OptDisableClientCert) "disable client certification", Option "t" ["test-directory"] (ReqArg OptTestDirectory "test directory") "set test directory" ] instance Read PortNumber where readsPrec n = map (first (fromIntegral :: Int -> PortNumber)) . readsPrec n data CipherSuiteLevel = ToEcdsa256 | ToEcdsa | ToEcdhe256 | ToEcdhe | ToDhe256 | ToDhe | ToRsa256 | ToRsa | NoLevel String deriving (Show, Eq) instance Enum CipherSuiteLevel where toEnum 0 = ToEcdsa256 toEnum 1 = ToEcdsa toEnum 2 = ToEcdhe256 toEnum 3 = ToEcdhe toEnum 4 = ToDhe256 toEnum 5 = ToDhe toEnum 6 = ToRsa256 toEnum 7 = ToRsa toEnum _ = NoLevel "" fromEnum ToEcdsa256 = 0 fromEnum ToEcdsa = 1 fromEnum ToEcdhe256 = 2 fromEnum ToEcdhe = 3 fromEnum ToDhe256 = 4 fromEnum ToDhe = 5 fromEnum ToRsa256 = 6 fromEnum ToRsa = 7 fromEnum (NoLevel _) = 8 readCipherSuiteLevel :: String -> CipherSuiteLevel readCipherSuiteLevel "ecdsa256" = ToEcdsa256 readCipherSuiteLevel "ecdsa" = ToEcdsa readCipherSuiteLevel "ecdhe256" = ToEcdhe256 readCipherSuiteLevel "ecdhe" = ToEcdhe readCipherSuiteLevel "dhe256" = ToDhe256 readCipherSuiteLevel "dhe" = ToDhe readCipherSuiteLevel "rsa256" = ToRsa256 readCipherSuiteLevel "rsa" = ToRsa readCipherSuiteLevel l = NoLevel l cipherSuites :: [CipherSuite] cipherSuites = [ CipherSuite ECDHE_ECDSA AES_128_CBC_SHA256, CipherSuite ECDHE_ECDSA AES_128_CBC_SHA, CipherSuite ECDHE_RSA AES_128_CBC_SHA256, CipherSuite ECDHE_RSA AES_128_CBC_SHA, CipherSuite DHE_RSA AES_128_CBC_SHA256, CipherSuite DHE_RSA AES_128_CBC_SHA, CipherSuite RSA AES_128_CBC_SHA256, CipherSuite RSA AES_128_CBC_SHA ]
YoshikuniJujo/forest
subprojects/tls-analysis/server/CommandLine.hs
Haskell
bsd-3-clause
5,968
{-# LANGUAGE CPP #-} -- | HPACK(<https://tools.ietf.org/html/rfc7541>) encoding and decoding a header list. module Network.HPACK ( -- * Encoding and decoding encodeHeader , decodeHeader -- * Encoding and decoding with token , encodeTokenHeader , decodeTokenHeader -- * DynamicTable , DynamicTable , defaultDynamicTableSize , newDynamicTableForEncoding , newDynamicTableForDecoding , withDynamicTableForEncoding , withDynamicTableForDecoding , setLimitForEncoding -- * Strategy for encoding , CompressionAlgo(..) , EncodeStrategy(..) , defaultEncodeStrategy -- * Errors , DecodeError(..) , BufferOverrun(..) -- * Headers , HeaderList , Header , HeaderName , HeaderValue , TokenHeaderList , TokenHeader -- * Value table , ValueTable , HeaderTable , getHeaderValue , toHeaderTable -- * Basic types , Size , Index , Buffer , BufferSize -- * Re-exports , original , foldedCase , mk ) where #if __GLASGOW_HASKELL__ < 709 import Control.Applicative ((<$>)) #endif import Data.CaseInsensitive import Network.HPACK.HeaderBlock import Network.HPACK.Table import Network.HPACK.Types -- | Default dynamic table size. -- The value is 4,096 bytes: an array has 128 entries. -- -- >>> defaultDynamicTableSize -- 4096 defaultDynamicTableSize :: Int defaultDynamicTableSize = 4096
kazu-yamamoto/http2
Network/HPACK.hs
Haskell
bsd-3-clause
1,358
module Main (main) where import qualified Data.ByteString as B --import Language.C import Language.CIL import System.Environment --import Compile --import Verify version = "0.2.0" main :: IO () main = do args <- getArgs case args of [] -> help (a:_) | elem a ["help", "-h", "--help", "-help"] -> help | elem a ["version", "-v", "--version"] -> putStrLn $ "afv " ++ version ["example"] -> example ["header"] -> header ["verify", file] -> do a <- if file == "-" then B.getContents else B.readFile file let cil = parseCIL (if file == "-" then "stdin" else file) a print cil --model <- compile $ parse (if file == "-" then "stdin" else file) a --verify "yices" 20 model _ -> help header :: IO () header = do putStrLn "writing AFV header file (afv.h) ..." writeFile "afv.h" $ unlines [ "#ifndef AFV" , "#include <assert.h>" , "#define assume assert" , "#endif" ] example :: IO () example = do header putStrLn "writing example design (example.c) ..." putStrLn "verify with: afv verify -k 15 example.c" writeFile "example.c" $ unlines [ "// Provides assert and assume functions." , "#include \"afv.h\"" , "" , "// Periodic function for verification. Implements a simple rolling counter." , "void example () {" , "" , " // The rolling counter." , " static int counter = 0;" , "" , " // Assertions." , " GreaterThanOrEqualTo0: assert(counter >= 0); // The 'counter' must always be greater than or equal to 0." , " LessThan10: assert(counter < 10); // The 'counter' must always be less than 10." , "" , " // Implementation 1." , " if (counter == 10)" , " counter = 0;" , " else" , " counter++;" , "" , " // Implementation 2." , " // if (counter == 9)" , " // counter = 0;" , " // else" , " // counter = counter + 1;" , "" , " // Implementation 3." , " // if (counter >= 9)" , " // counter = 0;" , " // else" , " // counter++;" , "" , " // Implementation 4." , " // if (counter >= 9 || counter < 0)" , " // counter = 0;" , " // else" , " // counter++;" , "" , " // Implementation 5." , " // counter = (counter + 1) % 10;" , "" , "}" , "" , "void main() {" , " while (1) example();" , "}" , "" ] help :: IO () help = putStrLn $ unlines [ "" , "NAME" , " afv - Atom Formal Verifier" , "" , "VERSION" , " " ++ version , "" , "SYNOPSIS" , " afv verify ( <file> | - )" , " afv header" , " afv example" , "" , "DESCRIPTION" , " Afv performs bounded model checking and k-induction on C code with a signle infinite loop." , " Requires GCC for C preprocessing and the Yices SMT solver." , "" , "COMMANDS" , " verify ( <file> | - )" , " Runs verification on a C preprocessed file (CPP) or from stdin." , "" , " header" , " Writes AFV's header file (afv.h), which provides the 'assert' and 'assume' functions." , "" , " example" , " Writes an example design (example.c). Verify with:" , " afv verify -k 15 example.c" , "" ]
tomahawkins/afv
src/AFV.hs
Haskell
bsd-3-clause
3,244
{-# LANGUAGE CPP #-} module Feldspar.IO.Frontend ( module Feldspar.IO.Frontend , ExternalCompilerOpts (..) , defaultExtCompilerOpts ) where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative #endif import Data.Ix import Data.Monoid import Data.Proxy import Text.Printf (PrintfArg) import qualified Control.Monad.Operational.Higher as Imp import Language.Embedded.Imperative.CMD (FileCMD (..)) import Language.Embedded.Imperative.Frontend.General import qualified Language.Embedded.Imperative as Imp import qualified Language.Embedded.Imperative.CMD as Imp import Language.Embedded.Backend.C (ExternalCompilerOpts (..), defaultExtCompilerOpts) import qualified Language.Embedded.Backend.C as Imp import Feldspar (Type, Data, WordN (..)) import Feldspar.Compiler.FromImperative (feldsparCIncludes) import Feldspar.IO.CMD deriving instance PrintfArg WordN -- TODO Should go into feldspar-language deriving instance Read WordN -- TODO Should go into feldspar-language deriving instance Formattable WordN -- TODO Should go into feldspar-compiler-shim -- | Program monad newtype Program a = Program {unProgram :: Imp.Program FeldCMD a} deriving (Functor, Applicative, Monad) -------------------------------------------------------------------------------- -- * References -------------------------------------------------------------------------------- -- | Create an uninitialized reference newRef :: Type a => Program (Ref a) newRef = Program Imp.newRef -- | Create an initialized reference initRef :: Type a => Data a -> Program (Ref a) initRef = Program . Imp.initRef -- | Get the contents of a reference getRef :: Type a => Ref a -> Program (Data a) getRef = Program . Imp.getRef -- | Set the contents of a reference setRef :: Type a => Ref a -> Data a -> Program () setRef r = Program . Imp.setRef r -- | Modify the contents of reference modifyRef :: Type a => Ref a -> (Data a -> Data a) -> Program () modifyRef r f = Program $ Imp.modifyRef r f -- | Freeze the contents of reference (only safe if the reference is not updated -- as long as the resulting value is alive) unsafeFreezeRef :: Type a => Ref a -> Program (Data a) unsafeFreezeRef = Program . Imp.unsafeFreezeRef -- | Compute and share a value. Like 'share' but using the 'Program' monad -- instead of a higher-order interface. shareVal :: Type a => Data a -> Program (Data a) shareVal a = initRef a >>= unsafeFreezeRef -------------------------------------------------------------------------------- -- * Arrays -------------------------------------------------------------------------------- -- | Create an uninitialized array newArr :: (Type a, Type i, Integral i, Ix i) => Data i -> Program (Arr i a) newArr n = Program $ Imp.newArr n -- | Get an element of an array getArr :: (Type a, Type i, Integral i, Ix i) => Data i -> Arr i a -> Program (Data a) getArr i arr = Program $ Imp.getArr i arr -- | Set an element of an array setArr :: (Type a, Type i, Integral i, Ix i) => Data i -> Data a -> Arr i a -> Program () setArr i a arr = Program $ Imp.setArr i a arr -- | Copy the contents of an array to another array. The number of elements to -- copy must not be greater than the number of allocated elements in either -- array. copyArr :: (Type a, Type i, Integral i, Ix i) => Arr i a -- ^ Destination -> Arr i a -- ^ Source -> Data i -- ^ Number of elements -> Program () copyArr arr1 arr2 len = Program $ Imp.copyArr arr1 arr2 len thawArr :: (Type a, Num n, Ix n) => Data [a] -> Program (Arr n a) thawArr = Program . Imp.singleInj . ThawArr unsafeThawArr :: (Type a, Num n, Ix n) => Data [a] -> Program (Arr n a) unsafeThawArr = Program . Imp.singleInj . UnsafeThawArr freezeArr :: (Type a, Num n, Ix n) => Arr n a -> Data n -> Program (Data [a]) freezeArr a n = Program $ Imp.singleInj $ FreezeArr a n -------------------------------------------------------------------------------- -- * Control flow -------------------------------------------------------------------------------- -- | Conditional statement iff :: Data Bool -- ^ Condition -> Program () -- ^ True branch -> Program () -- ^ False branch -> Program () iff b t f = Program $ Imp.iff b (unProgram t) (unProgram f) -- | Conditional statement that returns an expression ifE :: Type a => Data Bool -- ^ Condition -> Program (Data a) -- ^ True branch -> Program (Data a) -- ^ False branch -> Program (Data a) ifE b t f = Program $ Imp.ifE b (unProgram t) (unProgram f) -- | For loop for :: (Integral n, Type n) => IxRange (Data n) -- ^ Index range -> (Data n -> Program ()) -- ^ Loop body -> Program () for range body = Program $ Imp.for range (unProgram . body) -- | While loop while :: Program (Data Bool) -- ^ Continue condition -> Program () -- ^ Loop body -> Program () while b t = Program $ Imp.while (unProgram b) (unProgram t) -- | Assertion assert :: Data Bool -- ^ Expression that should be true -> String -- ^ Message in case of failure -> Program () assert cond msg = Program $ Imp.assert cond msg -- | Break out from a loop break :: Program () break = Program Imp.break -------------------------------------------------------------------------------- -- * File handling -------------------------------------------------------------------------------- -- | Open a file fopen :: FilePath -> IOMode -> Program Handle fopen file = Program . Imp.fopen file -- | Close a file fclose :: Handle -> Program () fclose = Program . Imp.fclose -- | Check for end of file feof :: Handle -> Program (Data Bool) feof = Program . Imp.feof class PrintfType r where fprf :: Handle -> String -> [Imp.PrintfArg Data] -> r instance (a ~ ()) => PrintfType (Program a) where fprf h form as = Program $ Imp.singleE $ FPrintf h form (reverse as) instance (Formattable a, Type a, PrintfType r) => PrintfType (Data a -> r) where fprf h form as = \a -> fprf h form (Imp.PrintfArg a : as) -- | Print to a handle. Accepts a variable number of arguments. fprintf :: PrintfType r => Handle -> String -> r fprintf h format = fprf h format [] -- | Put a single value to a handle fput :: (Formattable a, Type a) => Handle -> String -- Prefix -> Data a -- Expression to print -> String -- Suffix -> Program () fput h pre a post = Program $ Imp.fput h pre a post -- | Get a single value from a handle fget :: (Formattable a, Type a) => Handle -> Program (Data a) fget = Program . Imp.fget -- | Print to @stdout@. Accepts a variable number of arguments. printf :: PrintfType r => String -> r printf = fprintf Imp.stdout -------------------------------------------------------------------------------- -- * Abstract objects -------------------------------------------------------------------------------- newObject :: String -- ^ Object type -> Program Object newObject = Program . Imp.newObject initObject :: String -- ^ Function name -> String -- ^ Object type -> [FunArg Data] -- ^ Arguments -> Program Object initObject fun ty args = Program $ Imp.initObject fun ty args initUObject :: String -- ^ Function name -> String -- ^ Object type -> [FunArg Data] -- ^ Arguments -> Program Object initUObject fun ty args = Program $ Imp.initUObject fun ty args -------------------------------------------------------------------------------- -- * External function calls (C-specific) -------------------------------------------------------------------------------- -- | Add an @#include@ statement to the generated code addInclude :: String -> Program () addInclude = Program . Imp.addInclude -- | Add a global definition to the generated code -- -- Can be used conveniently as follows: -- -- > {-# LANGUAGE QuasiQuotes #-} -- > -- > import Feldspar.IO -- > -- > prog = do -- > ... -- > addDefinition myCFunction -- > ... -- > where -- > myCFunction = [cedecl| -- > void my_C_function( ... ) -- > { -- > // C code -- > // goes here -- > } -- > |] addDefinition :: Definition -> Program () addDefinition = Program . Imp.addDefinition -- | Declare an external function addExternFun :: forall proxy res . Type res => String -- ^ Function name -> proxy res -- ^ Proxy for expression and result type -> [FunArg Data] -- ^ Arguments (only used to determine types) -> Program () addExternFun fun res args = Program $ Imp.addExternFun fun res' args where res' = Proxy :: Proxy (Data res) -- | Declare an external procedure addExternProc :: String -- ^ Procedure name -> [FunArg Data] -- ^ Arguments (only used to determine types) -> Program () addExternProc proc args = Program $ Imp.addExternProc proc args -- | Call a function callFun :: Type a => String -- ^ Function name -> [FunArg Data] -- ^ Arguments -> Program (Data a) callFun fun as = Program $ Imp.callFun fun as -- | Call a procedure callProc :: String -- ^ Function name -> [FunArg Data] -- ^ Arguments -> Program () callProc fun as = Program $ Imp.callProc fun as -- | Declare and call an external function externFun :: Type res => String -- ^ Procedure name -> [FunArg Data] -- ^ Arguments -> Program (Data res) externFun fun args = Program $ Imp.externFun fun args -- | Declare and call an external procedure externProc :: String -- ^ Procedure name -> [FunArg Data] -- ^ Arguments -> Program () externProc proc args = Program $ Imp.externProc proc args -- | Get current time as number of seconds passed today getTime :: Program (Data Double) getTime = Program Imp.getTime strArg :: String -> FunArg Data strArg = Imp.strArg valArg :: Type a => Data a -> FunArg Data valArg = Imp.valArg refArg :: Type a => Ref a -> FunArg Data refArg = Imp.refArg arrArg :: Type a => Arr n a -> FunArg Data arrArg = Imp.arrArg objArg :: Object -> FunArg Data objArg = Imp.objArg addr :: FunArg Data -> FunArg Data addr = Imp.addr -------------------------------------------------------------------------------- -- * Back ends -------------------------------------------------------------------------------- -- | Interpret a program in the 'IO' monad runIO :: Program a -> IO a runIO = Imp.runIO . unProgram -- | Like 'runIO' but with explicit input/output connected to @stdin@/@stdout@ captureIO :: Program a -- ^ Program to run -> String -- ^ Faked @stdin@ -> IO String -- ^ Captured @stdout@ captureIO = Imp.captureIO . unProgram -- | Compile a program to C code represented as a string. To compile the -- resulting C code, use something like -- -- > gcc -std=c99 -Ipath/to/feldspar-compiler/lib/Feldspar/C YOURPROGRAM.c -- -- For programs that make use of the primitives in "Feldspar.Concurrent", some -- extra flags are needed: -- -- > gcc -std=c99 -Ipath/to/feldspar-compiler/lib/Feldspar/C -Ipath/to/imperative-edsl/include path/to/imperative-edsl/csrc/chan.c -lpthread YOURPROGRAM.c compile :: Program a -> String compile = Imp.compile . unProgram -- | Compile a program to C code and print it on the screen. To compile the -- resulting C code, use something like -- -- > gcc -std=c99 -Ipath/to/feldspar-compiler/lib/Feldspar/C YOURPROGRAM.c -- -- For programs that make use of the primitives in "Feldspar.Concurrent", some -- extra flags are needed: -- -- > gcc -std=c99 -Ipath/to/feldspar-compiler/lib/Feldspar/C -Ipath/to/imperative-edsl/include path/to/imperative-edsl/csrc/chan.c -lpthread YOURPROGRAM.c icompile :: Program a -> IO () icompile = putStrLn . compile addFeldsparCIncludes :: ExternalCompilerOpts -> IO ExternalCompilerOpts addFeldsparCIncludes opts = do feldLib <- feldsparCIncludes return $ opts <> mempty { externalFlagsPre = ["-I" ++ feldLib] } -- | Generate C code and use GCC to check that it compiles (no linking) compileAndCheck' :: ExternalCompilerOpts -> Program a -> IO () compileAndCheck' opts prog = do opts' <- addFeldsparCIncludes opts Imp.compileAndCheck' opts' (unProgram prog) -- | Generate C code and use GCC to check that it compiles (no linking) compileAndCheck :: Program a -> IO () compileAndCheck = compileAndCheck' mempty -- | Generate C code, use GCC to compile it, and run the resulting executable runCompiled' :: ExternalCompilerOpts -> Program a -> IO () runCompiled' opts prog = do opts' <- addFeldsparCIncludes opts Imp.runCompiled' opts' (unProgram prog) -- | Generate C code, use GCC to compile it, and run the resulting executable runCompiled :: Program a -> IO () runCompiled = runCompiled' mempty -- | Like 'runCompiled'' but with explicit input/output connected to -- @stdin@/@stdout@ captureCompiled' :: ExternalCompilerOpts -> Program a -- ^ Program to run -> String -- ^ Input to send to @stdin@ -> IO String -- ^ Result from @stdout@ captureCompiled' opts prog inp = do opts' <- addFeldsparCIncludes opts Imp.captureCompiled' opts' (unProgram prog) inp -- | Like 'runCompiled' but with explicit input/output connected to -- @stdin@/@stdout@ captureCompiled :: Program a -- ^ Program to run -> String -- ^ Input to send to @stdin@ -> IO String -- ^ Result from @stdout@ captureCompiled = captureCompiled' mempty -- | Compare the content written to 'stdout' from interpretation in 'IO' and -- from running the compiled C code compareCompiled' :: ExternalCompilerOpts -> Program a -- ^ Program to run -> String -- ^ Input to send to @stdin@ -> IO () compareCompiled' opts prog inp = do opts' <- addFeldsparCIncludes opts Imp.compareCompiled' opts' (unProgram prog) inp -- | Compare the content written to 'stdout' from interpretation in 'IO' and -- from running the compiled C code compareCompiled :: Program a -- ^ Program to run -> String -- ^ Input to send to @stdin@ -> IO () compareCompiled = compareCompiled' mempty
emilaxelsson/feldspar-io
src/Feldspar/IO/Frontend.hs
Haskell
bsd-3-clause
14,031
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} -- | -- Module: $HEADER$ -- Description: Data type that represents name of a SCM (Source Code -- Management) tool. -- Copyright: (c) 2016 Peter Trško -- License: BSD3 -- -- Maintainer: peter.trsko@gmail.com -- Stability: experimental -- Portability: GHC specific language extensions. -- -- Data type that represents name of a SCM (Source Code Management) tool. module YX.Type.DbConnection ( DbConnection(..) , withSQLiteConn ) where import Data.Function (($)) import GHC.Generics (Generic) import qualified Database.SQLite.Simple as SQLite (Connection) -- | YX stores its global data about existing projects in a database. This data -- type wraps lower level connection for more type safety. newtype DbConnection = DbConnection SQLite.Connection deriving (Generic) -- | Use 'DbConnection' as a SQLite Simple 'SQLite.Connection'. -- -- Example: -- -- @ -- 'withSQLiteConn' conn $ \\c -> -- SQLite.query_ c \"SELECT * FROM InterestingTable;\" -- @ withSQLiteConn :: DbConnection -> (SQLite.Connection -> a) -> a withSQLiteConn (DbConnection c) = ($ c)
trskop/yx
src/YX/Type/DbConnection.hs
Haskell
bsd-3-clause
1,177
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} module VarEnv ( -- * Var, Id and TyVar environments (maps) VarEnv, IdEnv, TyVarEnv, CoVarEnv, TyCoVarEnv, -- ** Manipulating these environments emptyVarEnv, unitVarEnv, mkVarEnv, mkVarEnv_Directly, elemVarEnv, disjointVarEnv, extendVarEnv, extendVarEnv_C, extendVarEnv_Acc, extendVarEnv_Directly, extendVarEnvList, plusVarEnv, plusVarEnv_C, plusVarEnv_CD, plusMaybeVarEnv_C, plusVarEnvList, alterVarEnv, delVarEnvList, delVarEnv, delVarEnv_Directly, minusVarEnv, intersectsVarEnv, lookupVarEnv, lookupVarEnv_NF, lookupWithDefaultVarEnv, mapVarEnv, zipVarEnv, modifyVarEnv, modifyVarEnv_Directly, isEmptyVarEnv, elemVarEnvByKey, lookupVarEnv_Directly, filterVarEnv, filterVarEnv_Directly, restrictVarEnv, partitionVarEnv, -- * Deterministic Var environments (maps) DVarEnv, DIdEnv, DTyVarEnv, -- ** Manipulating these environments emptyDVarEnv, mkDVarEnv, dVarEnvElts, extendDVarEnv, extendDVarEnv_C, extendDVarEnvList, lookupDVarEnv, elemDVarEnv, isEmptyDVarEnv, foldDVarEnv, mapDVarEnv, filterDVarEnv, modifyDVarEnv, alterDVarEnv, plusDVarEnv, plusDVarEnv_C, unitDVarEnv, delDVarEnv, delDVarEnvList, minusDVarEnv, partitionDVarEnv, anyDVarEnv, -- * The InScopeSet type InScopeSet, -- ** Operations on InScopeSets emptyInScopeSet, mkInScopeSet, delInScopeSet, extendInScopeSet, extendInScopeSetList, extendInScopeSetSet, getInScopeVars, lookupInScope, lookupInScope_Directly, unionInScope, elemInScopeSet, uniqAway, varSetInScope, unsafeGetFreshLocalUnique, -- * The RnEnv2 type RnEnv2, -- ** Operations on RnEnv2s mkRnEnv2, rnBndr2, rnBndrs2, rnBndr2_var, rnOccL, rnOccR, inRnEnvL, inRnEnvR, rnOccL_maybe, rnOccR_maybe, rnBndrL, rnBndrR, nukeRnEnvL, nukeRnEnvR, rnSwap, delBndrL, delBndrR, delBndrsL, delBndrsR, addRnInScopeSet, rnEtaL, rnEtaR, rnInScope, rnInScopeSet, lookupRnInScope, rnEnvL, rnEnvR, -- * TidyEnv and its operation TidyEnv, emptyTidyEnv, mkEmptyTidyEnv, delTidyEnvList ) where import GhcPrelude import qualified Data.IntMap.Strict as IntMap -- TODO: Move this to UniqFM import OccName import Name import Var import VarSet import UniqSet import UniqFM import UniqDFM import Unique import Util import Maybes import Outputable {- ************************************************************************ * * In-scope sets * * ************************************************************************ -} -- | A set of variables that are in scope at some point -- "Secrets of the Glasgow Haskell Compiler inliner" Section 3.2 provides -- the motivation for this abstraction. newtype InScopeSet = InScope VarSet -- Note [Lookups in in-scope set] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- We store a VarSet here, but we use this for lookups rather than just -- membership tests. Typically the InScopeSet contains the canonical -- version of the variable (e.g. with an informative unfolding), so this -- lookup is useful (see, for instance, Note [In-scope set as a -- substitution]). instance Outputable InScopeSet where ppr (InScope s) = text "InScope" <+> braces (fsep (map (ppr . Var.varName) (nonDetEltsUniqSet s))) -- It's OK to use nonDetEltsUniqSet here because it's -- only for pretty printing -- In-scope sets get big, and with -dppr-debug -- the output is overwhelming emptyInScopeSet :: InScopeSet emptyInScopeSet = InScope emptyVarSet getInScopeVars :: InScopeSet -> VarSet getInScopeVars (InScope vs) = vs mkInScopeSet :: VarSet -> InScopeSet mkInScopeSet in_scope = InScope in_scope extendInScopeSet :: InScopeSet -> Var -> InScopeSet extendInScopeSet (InScope in_scope) v = InScope (extendVarSet in_scope v) extendInScopeSetList :: InScopeSet -> [Var] -> InScopeSet extendInScopeSetList (InScope in_scope) vs = InScope $ foldl' extendVarSet in_scope vs extendInScopeSetSet :: InScopeSet -> VarSet -> InScopeSet extendInScopeSetSet (InScope in_scope) vs = InScope (in_scope `unionVarSet` vs) delInScopeSet :: InScopeSet -> Var -> InScopeSet delInScopeSet (InScope in_scope) v = InScope (in_scope `delVarSet` v) elemInScopeSet :: Var -> InScopeSet -> Bool elemInScopeSet v (InScope in_scope) = v `elemVarSet` in_scope -- | Look up a variable the 'InScopeSet'. This lets you map from -- the variable's identity (unique) to its full value. lookupInScope :: InScopeSet -> Var -> Maybe Var lookupInScope (InScope in_scope) v = lookupVarSet in_scope v lookupInScope_Directly :: InScopeSet -> Unique -> Maybe Var lookupInScope_Directly (InScope in_scope) uniq = lookupVarSet_Directly in_scope uniq unionInScope :: InScopeSet -> InScopeSet -> InScopeSet unionInScope (InScope s1) (InScope s2) = InScope (s1 `unionVarSet` s2) varSetInScope :: VarSet -> InScopeSet -> Bool varSetInScope vars (InScope s1) = vars `subVarSet` s1 {- Note [Local uniques] ~~~~~~~~~~~~~~~~~~~~ Sometimes one must create conjure up a unique which is unique in a particular context (but not necessarily globally unique). For instance, one might need to create a fresh local identifier which does not shadow any of the locally in-scope variables. For this we purpose we provide 'uniqAway'. 'uniqAway' is implemented in terms of the 'unsafeGetFreshLocalUnique' operation, which generates an unclaimed 'Unique' from an 'InScopeSet'. To ensure that we do not conflict with uniques allocated by future allocations from 'UniqSupply's, Uniques generated by 'unsafeGetFreshLocalUnique' are allocated into a dedicated region of the unique space (namely the X tag). Note that one must be quite carefully when using uniques generated in this way since they are only locally unique. In particular, two successive calls to 'uniqAway' on the same 'InScopeSet' will produce the same unique. -} -- | @uniqAway in_scope v@ finds a unique that is not used in the -- in-scope set, and gives that to v. See Note [Local uniques]. uniqAway :: InScopeSet -> Var -> Var -- It starts with v's current unique, of course, in the hope that it won't -- have to change, and thereafter uses the successor to the last derived unique -- found in the in-scope set. uniqAway in_scope var | var `elemInScopeSet` in_scope = uniqAway' in_scope var -- Make a new one | otherwise = var -- Nothing to do uniqAway' :: InScopeSet -> Var -> Var -- This one *always* makes up a new variable uniqAway' in_scope var = setVarUnique var (unsafeGetFreshLocalUnique in_scope) -- | @unsafeGetFreshUnique in_scope@ finds a unique that is not in-scope in the -- given 'InScopeSet'. This must be used very carefully since one can very easily -- introduce non-unique 'Unique's this way. See Note [Local uniques]. unsafeGetFreshLocalUnique :: InScopeSet -> Unique unsafeGetFreshLocalUnique (InScope set) | Just (uniq,_) <- IntMap.lookupLT (getKey maxLocalUnique) (ufmToIntMap $ getUniqSet set) , let uniq' = mkLocalUnique uniq , not $ uniq' `ltUnique` minLocalUnique = incrUnique uniq' | otherwise = minLocalUnique {- ************************************************************************ * * Dual renaming * * ************************************************************************ -} -- | Rename Environment 2 -- -- When we are comparing (or matching) types or terms, we are faced with -- \"going under\" corresponding binders. E.g. when comparing: -- -- > \x. e1 ~ \y. e2 -- -- Basically we want to rename [@x@ -> @y@] or [@y@ -> @x@], but there are lots of -- things we must be careful of. In particular, @x@ might be free in @e2@, or -- y in @e1@. So the idea is that we come up with a fresh binder that is free -- in neither, and rename @x@ and @y@ respectively. That means we must maintain: -- -- 1. A renaming for the left-hand expression -- -- 2. A renaming for the right-hand expressions -- -- 3. An in-scope set -- -- Furthermore, when matching, we want to be able to have an 'occurs check', -- to prevent: -- -- > \x. f ~ \y. y -- -- matching with [@f@ -> @y@]. So for each expression we want to know that set of -- locally-bound variables. That is precisely the domain of the mappings 1. -- and 2., but we must ensure that we always extend the mappings as we go in. -- -- All of this information is bundled up in the 'RnEnv2' data RnEnv2 = RV2 { envL :: VarEnv Var -- Renaming for Left term , envR :: VarEnv Var -- Renaming for Right term , in_scope :: InScopeSet } -- In scope in left or right terms -- The renamings envL and envR are *guaranteed* to contain a binding -- for every variable bound as we go into the term, even if it is not -- renamed. That way we can ask what variables are locally bound -- (inRnEnvL, inRnEnvR) mkRnEnv2 :: InScopeSet -> RnEnv2 mkRnEnv2 vars = RV2 { envL = emptyVarEnv , envR = emptyVarEnv , in_scope = vars } addRnInScopeSet :: RnEnv2 -> VarSet -> RnEnv2 addRnInScopeSet env vs | isEmptyVarSet vs = env | otherwise = env { in_scope = extendInScopeSetSet (in_scope env) vs } rnInScope :: Var -> RnEnv2 -> Bool rnInScope x env = x `elemInScopeSet` in_scope env rnInScopeSet :: RnEnv2 -> InScopeSet rnInScopeSet = in_scope -- | Retrieve the left mapping rnEnvL :: RnEnv2 -> VarEnv Var rnEnvL = envL -- | Retrieve the right mapping rnEnvR :: RnEnv2 -> VarEnv Var rnEnvR = envR rnBndrs2 :: RnEnv2 -> [Var] -> [Var] -> RnEnv2 -- ^ Applies 'rnBndr2' to several variables: the two variable lists must be of equal length rnBndrs2 env bsL bsR = foldl2 rnBndr2 env bsL bsR rnBndr2 :: RnEnv2 -> Var -> Var -> RnEnv2 -- ^ @rnBndr2 env bL bR@ goes under a binder @bL@ in the Left term, -- and binder @bR@ in the Right term. -- It finds a new binder, @new_b@, -- and returns an environment mapping @bL -> new_b@ and @bR -> new_b@ rnBndr2 env bL bR = fst $ rnBndr2_var env bL bR rnBndr2_var :: RnEnv2 -> Var -> Var -> (RnEnv2, Var) -- ^ Similar to 'rnBndr2' but returns the new variable as well as the -- new environment rnBndr2_var (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bL bR = (RV2 { envL = extendVarEnv envL bL new_b -- See Note , envR = extendVarEnv envR bR new_b -- [Rebinding] , in_scope = extendInScopeSet in_scope new_b }, new_b) where -- Find a new binder not in scope in either term new_b | not (bL `elemInScopeSet` in_scope) = bL | not (bR `elemInScopeSet` in_scope) = bR | otherwise = uniqAway' in_scope bL -- Note [Rebinding] -- If the new var is the same as the old one, note that -- the extendVarEnv *deletes* any current renaming -- E.g. (\x. \x. ...) ~ (\y. \z. ...) -- -- Inside \x \y { [x->y], [y->y], {y} } -- \x \z { [x->x], [y->y, z->x], {y,x} } rnBndrL :: RnEnv2 -> Var -> (RnEnv2, Var) -- ^ Similar to 'rnBndr2' but used when there's a binder on the left -- side only. rnBndrL (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bL = (RV2 { envL = extendVarEnv envL bL new_b , envR = envR , in_scope = extendInScopeSet in_scope new_b }, new_b) where new_b = uniqAway in_scope bL rnBndrR :: RnEnv2 -> Var -> (RnEnv2, Var) -- ^ Similar to 'rnBndr2' but used when there's a binder on the right -- side only. rnBndrR (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bR = (RV2 { envR = extendVarEnv envR bR new_b , envL = envL , in_scope = extendInScopeSet in_scope new_b }, new_b) where new_b = uniqAway in_scope bR rnEtaL :: RnEnv2 -> Var -> (RnEnv2, Var) -- ^ Similar to 'rnBndrL' but used for eta expansion -- See Note [Eta expansion] rnEtaL (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bL = (RV2 { envL = extendVarEnv envL bL new_b , envR = extendVarEnv envR new_b new_b -- Note [Eta expansion] , in_scope = extendInScopeSet in_scope new_b }, new_b) where new_b = uniqAway in_scope bL rnEtaR :: RnEnv2 -> Var -> (RnEnv2, Var) -- ^ Similar to 'rnBndr2' but used for eta expansion -- See Note [Eta expansion] rnEtaR (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bR = (RV2 { envL = extendVarEnv envL new_b new_b -- Note [Eta expansion] , envR = extendVarEnv envR bR new_b , in_scope = extendInScopeSet in_scope new_b }, new_b) where new_b = uniqAway in_scope bR delBndrL, delBndrR :: RnEnv2 -> Var -> RnEnv2 delBndrL rn@(RV2 { envL = env, in_scope = in_scope }) v = rn { envL = env `delVarEnv` v, in_scope = in_scope `extendInScopeSet` v } delBndrR rn@(RV2 { envR = env, in_scope = in_scope }) v = rn { envR = env `delVarEnv` v, in_scope = in_scope `extendInScopeSet` v } delBndrsL, delBndrsR :: RnEnv2 -> [Var] -> RnEnv2 delBndrsL rn@(RV2 { envL = env, in_scope = in_scope }) v = rn { envL = env `delVarEnvList` v, in_scope = in_scope `extendInScopeSetList` v } delBndrsR rn@(RV2 { envR = env, in_scope = in_scope }) v = rn { envR = env `delVarEnvList` v, in_scope = in_scope `extendInScopeSetList` v } rnOccL, rnOccR :: RnEnv2 -> Var -> Var -- ^ Look up the renaming of an occurrence in the left or right term rnOccL (RV2 { envL = env }) v = lookupVarEnv env v `orElse` v rnOccR (RV2 { envR = env }) v = lookupVarEnv env v `orElse` v rnOccL_maybe, rnOccR_maybe :: RnEnv2 -> Var -> Maybe Var -- ^ Look up the renaming of an occurrence in the left or right term rnOccL_maybe (RV2 { envL = env }) v = lookupVarEnv env v rnOccR_maybe (RV2 { envR = env }) v = lookupVarEnv env v inRnEnvL, inRnEnvR :: RnEnv2 -> Var -> Bool -- ^ Tells whether a variable is locally bound inRnEnvL (RV2 { envL = env }) v = v `elemVarEnv` env inRnEnvR (RV2 { envR = env }) v = v `elemVarEnv` env lookupRnInScope :: RnEnv2 -> Var -> Var lookupRnInScope env v = lookupInScope (in_scope env) v `orElse` v nukeRnEnvL, nukeRnEnvR :: RnEnv2 -> RnEnv2 -- ^ Wipe the left or right side renaming nukeRnEnvL env = env { envL = emptyVarEnv } nukeRnEnvR env = env { envR = emptyVarEnv } rnSwap :: RnEnv2 -> RnEnv2 -- ^ swap the meaning of left and right rnSwap (RV2 { envL = envL, envR = envR, in_scope = in_scope }) = RV2 { envL = envR, envR = envL, in_scope = in_scope } {- Note [Eta expansion] ~~~~~~~~~~~~~~~~~~~~ When matching (\x.M) ~ N we rename x to x' with, where x' is not in scope in either term. Then we want to behave as if we'd seen (\x'.M) ~ (\x'.N x') Since x' isn't in scope in N, the form (\x'. N x') doesn't capture any variables in N. But we must nevertheless extend the envR with a binding [x' -> x'], to support the occurs check. For example, if we don't do this, we can get silly matches like forall a. (\y.a) ~ v succeeding with [a -> v y], which is bogus of course. ************************************************************************ * * Tidying * * ************************************************************************ -} -- | Tidy Environment -- -- When tidying up print names, we keep a mapping of in-scope occ-names -- (the 'TidyOccEnv') and a Var-to-Var of the current renamings type TidyEnv = (TidyOccEnv, VarEnv Var) emptyTidyEnv :: TidyEnv emptyTidyEnv = (emptyTidyOccEnv, emptyVarEnv) mkEmptyTidyEnv :: TidyOccEnv -> TidyEnv mkEmptyTidyEnv occ_env = (occ_env, emptyVarEnv) delTidyEnvList :: TidyEnv -> [Var] -> TidyEnv delTidyEnvList (occ_env, var_env) vs = (occ_env', var_env') where occ_env' = occ_env `delTidyOccEnvList` map (occNameFS . getOccName) vs var_env' = var_env `delVarEnvList` vs {- ************************************************************************ * * \subsection{@VarEnv@s} * * ************************************************************************ -} -- | Variable Environment type VarEnv elt = UniqFM elt -- | Identifier Environment type IdEnv elt = VarEnv elt -- | Type Variable Environment type TyVarEnv elt = VarEnv elt -- | Type or Coercion Variable Environment type TyCoVarEnv elt = VarEnv elt -- | Coercion Variable Environment type CoVarEnv elt = VarEnv elt emptyVarEnv :: VarEnv a mkVarEnv :: [(Var, a)] -> VarEnv a mkVarEnv_Directly :: [(Unique, a)] -> VarEnv a zipVarEnv :: [Var] -> [a] -> VarEnv a unitVarEnv :: Var -> a -> VarEnv a alterVarEnv :: (Maybe a -> Maybe a) -> VarEnv a -> Var -> VarEnv a extendVarEnv :: VarEnv a -> Var -> a -> VarEnv a extendVarEnv_C :: (a->a->a) -> VarEnv a -> Var -> a -> VarEnv a extendVarEnv_Acc :: (a->b->b) -> (a->b) -> VarEnv b -> Var -> a -> VarEnv b extendVarEnv_Directly :: VarEnv a -> Unique -> a -> VarEnv a plusVarEnv :: VarEnv a -> VarEnv a -> VarEnv a plusVarEnvList :: [VarEnv a] -> VarEnv a extendVarEnvList :: VarEnv a -> [(Var, a)] -> VarEnv a lookupVarEnv_Directly :: VarEnv a -> Unique -> Maybe a filterVarEnv_Directly :: (Unique -> a -> Bool) -> VarEnv a -> VarEnv a delVarEnv_Directly :: VarEnv a -> Unique -> VarEnv a partitionVarEnv :: (a -> Bool) -> VarEnv a -> (VarEnv a, VarEnv a) restrictVarEnv :: VarEnv a -> VarSet -> VarEnv a delVarEnvList :: VarEnv a -> [Var] -> VarEnv a delVarEnv :: VarEnv a -> Var -> VarEnv a minusVarEnv :: VarEnv a -> VarEnv b -> VarEnv a intersectsVarEnv :: VarEnv a -> VarEnv a -> Bool plusVarEnv_C :: (a -> a -> a) -> VarEnv a -> VarEnv a -> VarEnv a plusVarEnv_CD :: (a -> a -> a) -> VarEnv a -> a -> VarEnv a -> a -> VarEnv a plusMaybeVarEnv_C :: (a -> a -> Maybe a) -> VarEnv a -> VarEnv a -> VarEnv a mapVarEnv :: (a -> b) -> VarEnv a -> VarEnv b modifyVarEnv :: (a -> a) -> VarEnv a -> Var -> VarEnv a isEmptyVarEnv :: VarEnv a -> Bool lookupVarEnv :: VarEnv a -> Var -> Maybe a filterVarEnv :: (a -> Bool) -> VarEnv a -> VarEnv a lookupVarEnv_NF :: VarEnv a -> Var -> a lookupWithDefaultVarEnv :: VarEnv a -> a -> Var -> a elemVarEnv :: Var -> VarEnv a -> Bool elemVarEnvByKey :: Unique -> VarEnv a -> Bool disjointVarEnv :: VarEnv a -> VarEnv a -> Bool elemVarEnv = elemUFM elemVarEnvByKey = elemUFM_Directly disjointVarEnv = disjointUFM alterVarEnv = alterUFM extendVarEnv = addToUFM extendVarEnv_C = addToUFM_C extendVarEnv_Acc = addToUFM_Acc extendVarEnv_Directly = addToUFM_Directly extendVarEnvList = addListToUFM plusVarEnv_C = plusUFM_C plusVarEnv_CD = plusUFM_CD plusMaybeVarEnv_C = plusMaybeUFM_C delVarEnvList = delListFromUFM delVarEnv = delFromUFM minusVarEnv = minusUFM intersectsVarEnv e1 e2 = not (isEmptyVarEnv (e1 `intersectUFM` e2)) plusVarEnv = plusUFM plusVarEnvList = plusUFMList lookupVarEnv = lookupUFM filterVarEnv = filterUFM lookupWithDefaultVarEnv = lookupWithDefaultUFM mapVarEnv = mapUFM mkVarEnv = listToUFM mkVarEnv_Directly= listToUFM_Directly emptyVarEnv = emptyUFM unitVarEnv = unitUFM isEmptyVarEnv = isNullUFM lookupVarEnv_Directly = lookupUFM_Directly filterVarEnv_Directly = filterUFM_Directly delVarEnv_Directly = delFromUFM_Directly partitionVarEnv = partitionUFM restrictVarEnv env vs = filterVarEnv_Directly keep env where keep u _ = u `elemVarSetByKey` vs zipVarEnv tyvars tys = mkVarEnv (zipEqual "zipVarEnv" tyvars tys) lookupVarEnv_NF env id = case lookupVarEnv env id of Just xx -> xx Nothing -> panic "lookupVarEnv_NF: Nothing" {- @modifyVarEnv@: Look up a thing in the VarEnv, then mash it with the modify function, and put it back. -} modifyVarEnv mangle_fn env key = case (lookupVarEnv env key) of Nothing -> env Just xx -> extendVarEnv env key (mangle_fn xx) modifyVarEnv_Directly :: (a -> a) -> UniqFM a -> Unique -> UniqFM a modifyVarEnv_Directly mangle_fn env key = case (lookupUFM_Directly env key) of Nothing -> env Just xx -> addToUFM_Directly env key (mangle_fn xx) -- Deterministic VarEnv -- See Note [Deterministic UniqFM] in UniqDFM for explanation why we need -- DVarEnv. -- | Deterministic Variable Environment type DVarEnv elt = UniqDFM elt -- | Deterministic Identifier Environment type DIdEnv elt = DVarEnv elt -- | Deterministic Type Variable Environment type DTyVarEnv elt = DVarEnv elt emptyDVarEnv :: DVarEnv a emptyDVarEnv = emptyUDFM dVarEnvElts :: DVarEnv a -> [a] dVarEnvElts = eltsUDFM mkDVarEnv :: [(Var, a)] -> DVarEnv a mkDVarEnv = listToUDFM extendDVarEnv :: DVarEnv a -> Var -> a -> DVarEnv a extendDVarEnv = addToUDFM minusDVarEnv :: DVarEnv a -> DVarEnv a' -> DVarEnv a minusDVarEnv = minusUDFM lookupDVarEnv :: DVarEnv a -> Var -> Maybe a lookupDVarEnv = lookupUDFM foldDVarEnv :: (a -> b -> b) -> b -> DVarEnv a -> b foldDVarEnv = foldUDFM mapDVarEnv :: (a -> b) -> DVarEnv a -> DVarEnv b mapDVarEnv = mapUDFM filterDVarEnv :: (a -> Bool) -> DVarEnv a -> DVarEnv a filterDVarEnv = filterUDFM alterDVarEnv :: (Maybe a -> Maybe a) -> DVarEnv a -> Var -> DVarEnv a alterDVarEnv = alterUDFM plusDVarEnv :: DVarEnv a -> DVarEnv a -> DVarEnv a plusDVarEnv = plusUDFM plusDVarEnv_C :: (a -> a -> a) -> DVarEnv a -> DVarEnv a -> DVarEnv a plusDVarEnv_C = plusUDFM_C unitDVarEnv :: Var -> a -> DVarEnv a unitDVarEnv = unitUDFM delDVarEnv :: DVarEnv a -> Var -> DVarEnv a delDVarEnv = delFromUDFM delDVarEnvList :: DVarEnv a -> [Var] -> DVarEnv a delDVarEnvList = delListFromUDFM isEmptyDVarEnv :: DVarEnv a -> Bool isEmptyDVarEnv = isNullUDFM elemDVarEnv :: Var -> DVarEnv a -> Bool elemDVarEnv = elemUDFM extendDVarEnv_C :: (a -> a -> a) -> DVarEnv a -> Var -> a -> DVarEnv a extendDVarEnv_C = addToUDFM_C modifyDVarEnv :: (a -> a) -> DVarEnv a -> Var -> DVarEnv a modifyDVarEnv mangle_fn env key = case (lookupDVarEnv env key) of Nothing -> env Just xx -> extendDVarEnv env key (mangle_fn xx) partitionDVarEnv :: (a -> Bool) -> DVarEnv a -> (DVarEnv a, DVarEnv a) partitionDVarEnv = partitionUDFM extendDVarEnvList :: DVarEnv a -> [(Var, a)] -> DVarEnv a extendDVarEnvList = addListToUDFM anyDVarEnv :: (a -> Bool) -> DVarEnv a -> Bool anyDVarEnv = anyUDFM
sdiehl/ghc
compiler/basicTypes/VarEnv.hs
Haskell
bsd-3-clause
23,220