code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} module React.Flux.Mui.GridList.GridTile where import Protolude import Data.Aeson import Data.Aeson.Casing import Data.String (String) import React.Flux import React.Flux.Mui.Types import React.Flux.Mui.Util data GridTile = GridTile { gridTileActionPosition :: !(Maybe (MuiSymbolEnum '[ "left", "right"])) , gridTileCols :: !(Maybe Integer) , gridTileRows :: !(Maybe Integer) , gridTileTitleBackground :: !(Maybe Text) , gridTileTitlePosition :: !(Maybe (MuiSymbolEnum '[ "top", "bottom"])) } deriving (Generic, Show) instance ToJSON GridTile where toJSON = genericToJSON $ aesonDrop (length ("GridTile" :: String)) camelCase defGridTile :: GridTile defGridTile = GridTile { gridTileActionPosition = Just (MuiSymbolEnum (Proxy :: Proxy "right")) , gridTileCols = Just 1 , gridTileRows = Just 1 , gridTileTitleBackground = Just ("rgba(0, 0, 0, 0.4)") , gridTileTitlePosition = Just (MuiSymbolEnum (Proxy :: Proxy "bottom")) } gridTile_ :: GridTile -> [PropertyOrHandler handler] -> ReactElementM handler () -> ReactElementM handler () gridTile_ args props = foreign_ "GridTile" (fromMaybe [] (toProps args) ++ props)
pbogdan/react-flux-mui
react-flux-mui/src/React/Flux/Mui/GridList/GridTile.hs
bsd-3-clause
1,256
0
15
200
364
203
161
45
1
{-# LANGUAGE CPP #-} module Test.Unit.UserStory ( tests ) where import Control.Monad.Trans (lift) import qualified Data.Map as Map import Prelude hiding (log) import Data.Time.Clock import Bead.Controller.ServiceContext import Bead.Controller.UserStories as U import Bead.Domain.Entities as E hiding (name, uid) import Bead.Domain.Relationships (TCCreation(..)) import Bead.Domain.Shared.Evaluation import Test.HUnit hiding (Test(..), test) import Test.Tasty.HUnit (testCase) import Test.Tasty.TestSet import Test.Model.UserStory -- * Tests tests = group "User Stories" $ do test initPersist test register test loginAndLogout test courseTest test courseAndGroupAssignmentTest #ifndef SSO test saveAndLoadUserReg #endif test cleanUpPersist initPersist = testCase "Initalizing persistence layer" $ Test.Model.UserStory.initPersistent cleanUpPersist = testCase "Cleaning up persistence" $ Test.Model.UserStory.cleanUpPersistent #ifndef SSO saveAndLoadUserReg = testCase "Save and load user reg data" $ do userStoryTestContext $ do let now = utcTimeConstant let u = UserRegistration "username" "[email protected]" "Family Name" "token" now key <- registrationStory $ U.createUserReg u u' <- registrationStory $ U.loadUserReg key lift $ assertBool "Saved and load user registration differs" (u' == u) #endif register = testCase "User registration" $ do userStoryTestContext $ do adminStory $ createUser student loginAndLogout = testCase "Login And Logout" $ do c <- context (_,state) <- runStory c UserNotLoggedIn $ login (Username "student") "token" assertUserState state student (_,state) <- runStory c state $ logout case state of UserState {} -> error "User is remained logged in" UserNotLoggedIn -> return () Registration -> error "Registration state is returned" TestAgent -> error "TestAgent state is returned" courseTest = testCase "Create Course" $ do c <- context let r = E.Course { courseName = "Functional programming" , courseDesc = "Everything about FP" , courseTestScriptType = TestScriptSimple } (k,state) <- runStory c adminUserState $ createCourse r assertUserState state adminUser (ks,state) <- runStory c adminUserState $ selectCourses (\_ _ -> True) assertUserState state adminUser assertBool "Create course key is not found" (elem k $ map fst ks) ((r',_),state) <- runStory c adminUserState $ U.loadCourse k assertUserState state adminUser assertBool "Loaded course differs from the created one" (r' == r) return () courseAndGroupAssignmentTest = testCase "Course and group assignments" $ do str <- getCurrentTime end <- getCurrentTime let ca = Assignment "cname" "cexercise" emptyAspects str end binaryConfig ga = Assignment "gname" "gexercise" emptyAspects str end (percentageConfig 0.3) c1 = E.Course "FP" "FP-DESC" TestScriptSimple c2 = E.Course "MA" "MA-DESC" TestScriptZipped g1 = E.Group "G1" "G1-DESC" g2 = E.Group "G2" "G2-DESC" adminUsername = E.Username "admin" groupAdminUsr = E.Username "groupadmin" student2Username = E.Username "student2" userStoryTestContext $ do adminStory $ do createUser adminUser createUser groupAdminUser createUser student2 (ck2,gk1,gk2,a2) <- userStory adminUsername $ do ck1 <- createCourse c1 ck2 <- createCourse c2 U.createCourseAdmin adminUsername ck1 U.createCourseAdmin adminUsername ck2 gk1 <- createGroup ck1 g1 gk2 <- createGroup ck2 g2 U.createGroupAdmin groupAdminUsr gk1 U.createGroupAdmin groupAdminUsr gk2 a2 <- createCourseAssignment ck2 ca NoCreation return (ck2,gk1,gk2,a2) (a1,as) <- userStory groupAdminUsr $ do a1 <- createGroupAssignment gk1 ga NoCreation subscribeToGroup gk1 subscribeToGroup gk2 as <- fmap (toList . Map.map snd) userAssignments return (a1,as) let as' = map trd as lift $ assertBool "Assignment does not found in the assignment list" ([a1,a2] == as' || [a2,a1] == as') (uc,ug) <- userStory student2Username $ do subscribeToGroup gk2 uc <- U.isUserInCourse ck2 ug <- attendedGroups return (uc,ug) lift $ assertBool "User is not registered in course" (uc == True) lift $ assertBool "User is not registered in group" (elem gk2 (map trd ug)) where toList = concat . map snd . Map.toList -- * Helpers trd :: (a,b,c) -> a trd (a,_,_) = a utcTimeConstant :: UTCTime utcTimeConstant = read "2015-08-27 17:08:58 UTC"
andorp/bead
test/Test/Unit/UserStory.hs
bsd-3-clause
4,689
0
20
1,061
1,340
663
677
111
4
module Main where import Numeric.LinearAlgebra import Numeric.Morpheus a = matrix 5 [ 71, 11, 3, -9, -7, 21, -7, -2, 23, 11, -11, 32, 53, -49, 37, 1, -24, 78, 90, 17 ] main :: IO () main = do putStrLn "\nNumeric.Morpheus.MatrixReduce functions: " putStr "sum of elements of rows: " print $ rowSum a putStr "product of elements of rows: " print $ rowPredicate (*) a putStr "max values of columns: " print $ fst $ columnMaxIndex a putStr "indices of max values of columns: " print $ snd $ columnMaxIndex a putStrLn "\n\nNumeric.Morpheus.Activation functions: " putStrLn "\nSigmoid:" disp 3 (sigmoid a) putStrLn "ReLu:" disp 3 (relu a) putStrLn "ReLu gradient:" disp 3 (reluGradient a) putStrLn "\n\nNumeric.Morpheus.Statistics functions: " putStrLn "\nColumn Means:" let colmeans = columnMean a print colmeans putStrLn "Column Standard Deviations: " print (columnStddev_m colmeans a)
Alexander-Ignatyev/morpheus
hmatrix-morpheus/examples/Main.hs
bsd-3-clause
958
0
10
215
311
147
164
32
1
{-# LANGUAGE FlexibleInstances, GeneralizedNewtypeDeriving#-} module Fibon.Analyse.Metrics ( MemSize(..) , ExecTime(..) , Estimate(..) , ConfidenceInterval(..) , Measurement(..) , Metric(..) , PerfData(..) , pprPerfData , RawPerf(..) , NormPerf(..) , BasicPerf(..) , mkPointEstimate , rawPerfToDouble , normPerfToDouble ) where import Data.Word import Fibon.Analyse.Statistics import Text.Printf newtype MemSize = MemSize {fromMemSize :: Word64} deriving(Eq, Read, Show, Num, Real, Enum, Ord, Integral) newtype ExecTime = ExecTime {fromExecTime :: Double} deriving(Eq, Read, Show, Num, Real, Enum, Ord) data Measurement a = Single a | Interval (Estimate a) deriving (Read, Show) mkPointEstimate :: (Num b) => (b -> a) -> a -> Estimate a mkPointEstimate toA a = Estimate { ePoint = a , eStddev = toA 0 , eSize = 1 , eCI = Nothing } class Metric a where perf :: a -> Maybe RawPerf instance Metric (Measurement ExecTime) where perf (Single m) = Just (RawTime (mkPointEstimate ExecTime m)) perf (Interval e) = Just (RawTime e) instance Metric (Measurement MemSize) where perf (Single m) = Just (RawSize (mkPointEstimate MemSize m)) perf (Interval e) = Just (RawSize e) instance Metric a => Metric (Maybe a) where --perf = fmap perf perf Nothing = Nothing perf (Just x) = perf x data PerfData = NoResult | Basic BasicPerf | Summary Summary BasicPerf deriving(Read, Show) data BasicPerf = Raw RawPerf | Norm NormPerf deriving(Read, Show) data RawPerf = RawTime (Estimate ExecTime) | RawSize (Estimate MemSize) deriving(Read, Show) data NormPerf = Percent (Estimate Double) -- ^ (ref / base) * 100 | Ratio (Estimate Double) -- ^ (base / ref) deriving(Read, Show) pprPerfData :: Bool -> PerfData -> String pprPerfData _ NoResult = "--" pprPerfData u (Basic b) = pprBasicPerf u b pprPerfData u (Summary _ s) = pprBasicPerf u s pprBasicPerf :: Bool -> BasicPerf -> String pprBasicPerf u (Raw r) = pprRawPerf u r pprBasicPerf u (Norm n) = pprNormPerf u n pprNormPerf :: Bool -> NormPerf -> String pprNormPerf u (Percent d) = printf "%0.2f%s" ((ePoint d) - 100) (pprUnit u "%") pprNormPerf _ (Ratio d) = printf "%0.2f" (ePoint d) pprRawPerf :: Bool -> RawPerf -> String pprRawPerf u (RawTime t) = printf "%0.2f%s" ((fromExecTime . ePoint) t) (pprUnit u "s") pprRawPerf u (RawSize s) = printf "%0d%s" (round (fromIntegral ((fromMemSize . ePoint) s) / 1000 :: Double)::Word64) (pprUnit u "k") {- pprRawPerf u (RawTimeInterval e) = printf "%0.2f%s" ((fromExecTime . ePoint) e) (pprPlusMinus e fromExecTime) (pprUnit u "s") pprRawPerf u (RawSizeInterval e) = printf "%d%s%s" ((fromMemSize . ePoint) e) (pprPlusMinus e fromMemSize) (pprUnit u "k") pprPlusMinus :: Real b => Estimate a -> (a -> b) -> String pprPlusMinus e f = printf "%c%0.2d" (chr 0xB1) ((realToFrac spread)::Double) where spread = abs ((f . ePoint) e) - ((f . eLowerBound) e) pprSummaryPerf :: Bool -> SummaryPerf -> String pprSummaryPerf u (GeoMean n) = pprBasicPerf u n pprSummaryPerf u (ArithMean r) = pprBasicPerf u r -} pprUnit :: Bool -> String -> String pprUnit True s = s pprUnit _ _ = "" rawPerfToDouble :: RawPerf -> Double rawPerfToDouble (RawTime t) = (fromExecTime . ePoint) t rawPerfToDouble (RawSize s) = (fromIntegral . fromMemSize . ePoint) s normPerfToDouble :: NormPerf -> Double normPerfToDouble (Percent p) = ePoint p normPerfToDouble (Ratio r) = ePoint r
dmpots/fibon
tools/fibon-analyse/Fibon/Analyse/Metrics.hs
bsd-3-clause
3,714
0
14
914
1,105
592
513
89
1
module Text.Highlighting.Illuminate ( tokenize , Lexer(..) , lexers , lexerByName , lexerByFilename , module Text.Highlighting.Illuminate.Format ) where import Data.Char (toLower) import Data.List (find) import Data.Sequence (singleton) import System.FilePath import System.FilePath.GlobPattern import Text.Highlighting.Illuminate.Types import Text.Highlighting.Illuminate.Format import qualified Text.Highlighting.Illuminate.Alex as Alex import qualified Text.Highlighting.Illuminate.BibTeX as BibTeX import qualified Text.Highlighting.Illuminate.C as C import qualified Text.Highlighting.Illuminate.Cabal as Cabal import qualified Text.Highlighting.Illuminate.CPlusPlus as CPlusPlus import qualified Text.Highlighting.Illuminate.CSharp as CSharp import qualified Text.Highlighting.Illuminate.CSS as CSS import qualified Text.Highlighting.Illuminate.D as D import qualified Text.Highlighting.Illuminate.Diff as Diff import qualified Text.Highlighting.Illuminate.Haskell as Haskell import qualified Text.Highlighting.Illuminate.HTML as HTML import qualified Text.Highlighting.Illuminate.Java as Java import qualified Text.Highlighting.Illuminate.Javascript as Javascript import qualified Text.Highlighting.Illuminate.LiterateHaskell as LiterateHaskell import qualified Text.Highlighting.Illuminate.Python as Python import qualified Text.Highlighting.Illuminate.RHTML as RHTML import qualified Text.Highlighting.Illuminate.RXML as RXML import qualified Text.Highlighting.Illuminate.Ruby as Ruby import qualified Text.Highlighting.Illuminate.Sh as Sh import qualified Text.Highlighting.Illuminate.TeX as TeX import qualified Text.Highlighting.Illuminate.XML as XML -- | Tokenize a string, returning either an error or a sequence -- of tokens. If the first argument is @Just@ a lexer, use -- the lexer to tokenize. If @Nothing@, return a single @Plain@ -- token with the whole source. 'tokenize' is designed to be -- used with 'lexerByName' or 'lexerByFilename': for example, -- -- > tokenize (lexerByName "Haskell") input -- tokenize :: Maybe Lexer -> String -> Either String Tokens tokenize (Just lexer) source = scan lexer source tokenize Nothing source = Right $ singleton $ (Plain, source) -- | Matches a lexer by name or alias (case-insensitive). lexerByName :: String -> Maybe Lexer lexerByName s = find matchName lexers where matchName l = map toLower s `elem` (map toLower (name l) : aliases l) -- | Matches a lexer by the filename of the source file. lexerByFilename :: String -> Maybe Lexer lexerByFilename s = find matchFilename lexers where matchFilename l = any (\glob -> takeFileName s ~~ glob) (filenames l) lexers :: [Lexer] lexers = [ Alex.lexer , BibTeX.lexer , C.lexer , Cabal.lexer , CPlusPlus.lexer , CSharp.lexer , CSS.lexer , D.lexer , Diff.lexer , Haskell.lexer , HTML.lexer , Java.lexer , Javascript.lexer , LiterateHaskell.lexer , Python.lexer , Ruby.lexer , RHTML.lexer , RXML.lexer , Sh.lexer , TeX.lexer , XML.lexer ]
jgm/illuminate
Text/Highlighting/Illuminate.hs
bsd-3-clause
3,200
0
12
606
623
405
218
66
1
{-# LANGUAGE OverloadedStrings #-} module Test.Complex.Query (specComplexQuery) where import Test.Hspec import Test.Data.Entity import Complex.Entity import Complex.Query specComplexQuery :: Spec specComplexQuery = do describe "Entity Class" $ do context "with valid one" $ do it "returns the table name" $ do entityId (entityDef UserRef) `shouldBe` "user" --it "returns the column name" $ do -- express UserId `shouldBe` "id" -- express UserEmail `shouldBe` "email" -- express UserPassword `shouldBe` "password" -- express UserStatus `shouldBe` "status" -- express UserCreatedAt `shouldBe` "created_at" -- express UserUpdatedAt `shouldBe` "updated_at" --it " list" $ do -- fields <- return [ UserId, UserEmail, UserPassword, UserStatus, UserCreatedAt, UserUpdatedAt ] -- select' fields `shouldBe` " SELECT id, email, password, status, created_at, updated_at" --it "express SQL" $ do -- join <- return [] -- base <- return SQLBase { baseId = "t1", baseEntity = (entityDef UserEntity), baseJoin = join } -- ps <- return [ SQLProjection { projectionId = "c1", projectionField = (fieldDef UserId) } -- , SQLProjection { projectionId = "c2", projectionField = (fieldDef UserEmail) } -- , SQLProjection { projectionId = "c3", projectionField = (fieldDef UserPassword) } -- , SQLProjection { projectionId = "c4", projectionField = (fieldDef UserStatus) } -- , SQLProjection { projectionId = "c5", projectionField = (fieldDef UserCreatedAt) } -- , SQLProjection { projectionId = "c6", projectionField = (fieldDef UserUpdatedAt) } -- ] -- cs <- return [] -- os <- return [] -- expressSQL base ps cs `shouldBe` " SELECT id, email, password, status, created_at, updated_at" --it " list" $ do -- f <- return SQLProjection { projectionId = "c4", projectionField = (fieldDef UserStatus) } -- express SQLCondition { conditionField = f, conditionOperation = (.<), conditionValue = "AAA" } `shouldBe` "AA" -- UserEntity >:< [] `shouldBe` " FROM user"
yulii/complex
test/Test/Complex/Query.hs
bsd-3-clause
2,277
0
19
624
119
76
43
12
1
{-# LANGUAGE ForeignFunctionInterface #-} ------------------------------------------------------------------------------- -- | -- Copyright : (c) 2015 Michael Carpenter -- License : BSD3 -- Maintainer : Michael Carpenter <[email protected]> -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------- module Sound.Csound.GeneralIO ( csoundGetOutputName, csoundSetOutput, csoundSetInput, csoundSetMIDIInput, csoundSetMIDIFileInput, csoundSetMIDIOutput, csoundSetMIDIFileOutput, csoundSetFileOpenCallback ) where -- | External Imports import Control.Monad.IO.Class import Foreign.Ptr import Foreign.C.Types -- | Internal Imports import Sound.Csound.Types foreign import ccall "csound.h csoundGetOutputName" csoundGetOutputName' :: Ptr () -> IO (Ptr CChar) foreign import ccall "csound.h csoundSetOutput" csoundSetOutput' :: Ptr () -> Ptr CChar -> Ptr CChar -> Ptr CChar -> IO () foreign import ccall "csound.h csoundSetInput" csoundSetInput' :: Ptr () -> Ptr CChar -> IO () foreign import ccall "csound.h csoundSetMIDIInput" csoundSetMIDIInput' :: Ptr () -> Ptr CChar -> IO () foreign import ccall "csound.h csoundSetMIDIFileInput" csoundSetMIDIFileInput' :: Ptr () -> Ptr CChar -> IO () foreign import ccall "csound.h csoundSetMIDIOutput" csoundSetMIDIOutput' :: Ptr () -> Ptr CChar -> IO () foreign import ccall "csound.h csoundSetMIDIFileOutput" csoundSetMIDIFileOutput' :: Ptr () -> Ptr CChar -> IO () foreign import ccall "csound.h csoundSetFileOpenCallback" csoundSetFileOpenCallback' :: Ptr () -> CsoundFileOpenCallback -> IO () csoundGetOutputName :: MonadIO m => Ptr () -> m (Ptr CChar) csoundGetOutputName csnd = liftIO (csoundGetOutputName' csnd) csoundSetOutput :: MonadIO m => Ptr () -> Ptr CChar -> Ptr CChar -> Ptr CChar -> m () csoundSetOutput cs_ptr c_name c_type c_format = liftIO (csoundSetOutput' cs_ptr c_name c_type c_format) csoundSetInput :: MonadIO m => Ptr () -> Ptr CChar -> m () csoundSetInput csnd name = liftIO (csoundSetInput' csnd name) csoundSetMIDIInput :: MonadIO m => Ptr () -> Ptr CChar -> m () csoundSetMIDIInput csnd name = liftIO (csoundSetMIDIInput' csnd name) csoundSetMIDIFileInput :: MonadIO m => Ptr () -> Ptr CChar -> m () csoundSetMIDIFileInput csnd name = liftIO (csoundSetMIDIFileInput' csnd name) csoundSetMIDIOutput :: MonadIO m => Ptr () -> Ptr CChar -> m () csoundSetMIDIOutput csnd name = liftIO (csoundSetMIDIOutput' csnd name) csoundSetMIDIFileOutput :: MonadIO m => Ptr () -> Ptr CChar -> m () csoundSetMIDIFileOutput csnd name = liftIO (csoundSetMIDIFileOutput' csnd name) csoundSetFileOpenCallback :: MonadIO m => Ptr () -> CsoundFileOpenCallback -> m () csoundSetFileOpenCallback csnd funPtr = liftIO (csoundSetFileOpenCallback' csnd funPtr)
oldmanmike/CsoundRaw
src/Sound/Csound/GeneralIO.hs
bsd-3-clause
2,841
0
11
416
785
388
397
38
1
{-# LANGUAGE Safe #-} {- arch-tag: ConfigParser lexer support Copyright (C) 2004, 2008 John Goerzen <[email protected]> Copyright (C) 2015-2016 David Farrell <[email protected]> -} {- | Module : Polar.ConfigFile.Lexer Copyright : Copyright (C) 2004, 2008 John Goerzen, 2015-2016 David Farrell License : BSD3 Maintainer : David Farrell <[email protected]> Stability : unstable Portability : portable Lexer support for "Polar.ConfigFile". This module is not intended to be used directly by your programs. Copyright (C) 2004, 2008 John Goerzen \<jgoerzen\@complete.org\>, 2015-2016 David Farrell \<shokku.ra\@gmail.com\>. -} module Polar.ConfigFile.Lexer ( -- -- * Temporary for testing --comment_chars, eol, optionsep, whitespace_chars, comment_line, --empty_line, sectheader_chars, sectheader, oname_chars, value_chars, --extension_line, optionkey, optionvalue, optionpair loken, CPTok(..), GeneralizedToken, GeneralizedTokenParser, togtok ) where import Text.ParserCombinators.Parsec import Polar.ConfigFile.Utils data CPTok = IGNOREDATA | NEWSECTION String | NEWSECTION_EOF String | EXTENSIONLINE String | NEWOPTION (String, String) deriving (Eq, Show, Ord) comment_chars :: CharParser st Char comment_chars = oneOf "#;" eol :: GenParser Char st String eol = string "\n" <|> string "\r\n" <|> string "\r" <?> "End of line" eoleof :: GenParser Char st () eoleof = eof <|> do {eol; return ()} optionsep :: GenParser Char st Char optionsep = oneOf ":=" <?> "option separator" whitespace_chars :: GenParser Char st Char whitespace_chars = oneOf " \t" <?> "whitespace" comment_line :: GenParser Char st () comment_line = do skipMany whitespace_chars comment_chars <?> "start of comment" (many $ noneOf "\r\n") <?> "content of comment" eoleof eolstuff :: GenParser Char st () eolstuff = (try comment_line) <|> (try empty_line) empty_line :: GenParser Char st () empty_line = do many whitespace_chars eoleof <?> "empty line" sectheader_chars :: CharParser st Char sectheader_chars = noneOf "]\r\n" sectheader :: GenParser Char st String sectheader = do char '[' sname <- many1 $ sectheader_chars char ']' eolstuff return sname <?> "start of section" oname_chars :: CharParser st Char oname_chars = noneOf ":=\r\n" value_chars :: CharParser st Char value_chars = noneOf "\r\n" extension_line :: GenParser Char st String extension_line = do many1 whitespace_chars c1 <- noneOf "\r\n#;" remainder <- many value_chars eolstuff return (c1 : remainder) optionkey, optionvalue :: GenParser Char st String optionkey = many1 oname_chars optionvalue = many value_chars optionpair :: GenParser Char st (String, String) optionpair = do key <- optionkey value <- option "" $ do { optionsep; optionvalue } eolstuff return (key, value) <?> "key/value option" iloken :: Parser (GeneralizedToken CPTok) iloken = -- Ignore these things try (do {comment_line; togtok $ IGNOREDATA}) <|> try (do {empty_line; togtok $ IGNOREDATA}) -- Real stuff <|> (do {sname <- sectheader; togtok $ NEWSECTION sname}) <|> try (do {extension <- extension_line; togtok $ EXTENSIONLINE extension}) <|> try (do {pair <- optionpair; togtok $ NEWOPTION pair}) -- <?> "Invalid syntax in configuration file" loken :: Parser [GeneralizedToken CPTok] loken = do x <- manyTill iloken eof return $ filter (\y -> snd y /= IGNOREDATA) x
polar-engine/polar-configfile
src/Polar/ConfigFile/Lexer.hs
bsd-3-clause
3,812
0
13
988
832
424
408
75
1
-- This supports all the operations of the other ones, but it uses -- a typical matrix representation. {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE ScopedTypeVariables #-} module Data.Sparse.ReferenceMatrix (RefMatrix ,toSparseBitM ,sparseSet ,Data.Sparse.ReferenceMatrix.getCol ,Data.Sparse.ReferenceMatrix.fromList ,(*|) ,(!!!) ,isSet ,Data.Sparse.ReferenceMatrix.nrows ,Data.Sparse.ReferenceMatrix.ncols ,zero ) where import qualified Data.Set as S import Data.Set (Set) import qualified Data.Matrix as M import Data.Matrix (Matrix) import qualified Data.Vector.Unboxed as U import Data.Coerce import Data.List (lookup) import Data.Bit import Data.Maybe (catMaybes) type V a = U.Vector a newtype RefMatrix a = RefMatrix (Matrix a) deriving (Functor) toSparseBitM :: Matrix Bool -> RefMatrix Bit toSparseBitM = fmap toBit . coerce getCol :: U.Unbox a => Int -> RefMatrix a -> V a getCol c = U.convert . M.getCol c . coerce fromList :: Num a => Int -> Int -> [((Int, Int), a)] -> RefMatrix a fromList r c a = coerce $ M.matrix r c (`defLookup` a) where defLookup x y = case lookup x y of Just r -> r _ -> 0 (*|) :: (Eq a, Show a, Num a, U.Unbox a) => RefMatrix Bit -> V a -> V Bool (*|) mat vec = U.fromList (map (fromBit . go) [1..nrows mat]) where go r = U.sum $ U.ifilter (\c _ -> mat !!! (r, c+1) == 1) vec {-# INLINE go #-} {-# INLINE (*|) #-} (!!!) :: (Num a, Eq a) => RefMatrix a -> (Int, Int) -> a m !!! coords = coerce m M.! coords isSet :: RefMatrix Bit -> (Int, Int) -> Bool isSet m coords = m !!! coords == 1 sparseSet :: RefMatrix Bit -> Set (Int, Int) sparseSet m = S.fromList (catMaybes (go <$> [1..nrows m] <*> [1..ncols m])) where go r c | m !!! (r, c) == 1 = Just (r, c) | otherwise = Nothing nrows, ncols :: RefMatrix a -> Int nrows = M.nrows . (coerce :: RefMatrix b -> Matrix b) ncols = M.ncols . (coerce :: RefMatrix b -> Matrix b) zero :: forall a. Num a => Int -> Int -> RefMatrix a zero r c = coerce (M.zero r c :: Matrix a) fromBit :: (Num a, Eq a, Show a) => a -> Bool fromBit 0 = False fromBit 1 = True fromBit n = error $ "fromBit: " ++ show n toBit :: Num a => Bool -> a toBit False = 0 toBit True = 1
ku-fpg/ecc-ldpc
src/Data/Sparse/ReferenceMatrix.hs
bsd-3-clause
2,294
0
14
547
946
512
434
66
2
{-# LANGUAGE CPP, DeriveFunctor, ViewPatterns, BangPatterns #-} {-# OPTIONS_GHC -Wno-incomplete-record-updates #-} module TcFlatten( FlattenMode(..), flatten, flattenKind, flattenArgsNom, rewriteTyVar, unflattenWanteds ) where #include "HsVersions.h" import GhcPrelude import TcRnTypes import TyCoPpr ( pprTyVar ) import Constraint import Predicate import TcType import Type import TcEvidence import TyCon import TyCoRep -- performs delicate algorithm on types import Coercion import Var import VarSet import VarEnv import Outputable import TcSMonad as TcS import BasicTypes( SwapFlag(..) ) import Util import Bag import Control.Monad import MonadUtils ( zipWith3M ) import Data.Foldable ( foldrM ) import Control.Arrow ( first ) {- Note [The flattening story] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * A CFunEqCan is either of form [G] <F xis> : F xis ~ fsk -- fsk is a FlatSkolTv [W] x : F xis ~ fmv -- fmv is a FlatMetaTv where x is the witness variable xis are function-free fsk/fmv is a flatten skolem; it is always untouchable (level 0) * CFunEqCans can have any flavour: [G], [W], [WD] or [D] * KEY INSIGHTS: - A given flatten-skolem, fsk, is known a-priori to be equal to F xis (the LHS), with <F xis> evidence. The fsk is still a unification variable, but it is "owned" by its CFunEqCan, and is filled in (unflattened) only by unflattenGivens. - A unification flatten-skolem, fmv, stands for the as-yet-unknown type to which (F xis) will eventually reduce. It is filled in - All fsk/fmv variables are "untouchable". To make it simple to test, we simply give them TcLevel=0. This means that in a CTyVarEq, say, fmv ~ Int we NEVER unify fmv. - A unification flatten-skolem, fmv, ONLY gets unified when either a) The CFunEqCan takes a step, using an axiom b) By unflattenWanteds They are never unified in any other form of equality. For example [W] ffmv ~ Int is stuck; it does not unify with fmv. * We *never* substitute in the RHS (i.e. the fsk/fmv) of a CFunEqCan. That would destroy the invariant about the shape of a CFunEqCan, and it would risk wanted/wanted interactions. The only way we learn information about fsk is when the CFunEqCan takes a step. However we *do* substitute in the LHS of a CFunEqCan (else it would never get to fire!) * Unflattening: - We unflatten Givens when leaving their scope (see unflattenGivens) - We unflatten Wanteds at the end of each attempt to simplify the wanteds; see unflattenWanteds, called from solveSimpleWanteds. * Ownership of fsk/fmv. Each canonical [G], [W], or [WD] CFunEqCan x : F xis ~ fsk/fmv "owns" a distinct evidence variable x, and flatten-skolem fsk/fmv. Why? We make a fresh fsk/fmv when the constraint is born; and we never rewrite the RHS of a CFunEqCan. In contrast a [D] CFunEqCan /shares/ its fmv with its partner [W], but does not "own" it. If we reduce a [D] F Int ~ fmv, where say type instance F Int = ty, then we don't discharge fmv := ty. Rather we simply generate [D] fmv ~ ty (in TcInteract.reduce_top_fun_eq, and dischargeFmv) * Inert set invariant: if F xis1 ~ fsk1, F xis2 ~ fsk2 then xis1 /= xis2 i.e. at most one CFunEqCan with a particular LHS * Function applications can occur in the RHS of a CTyEqCan. No reason not allow this, and it reduces the amount of flattening that must occur. * Flattening a type (F xis): - If we are flattening in a Wanted/Derived constraint then create new [W] x : F xis ~ fmv else create new [G] x : F xis ~ fsk with fresh evidence variable x and flatten-skolem fsk/fmv - Add it to the work list - Replace (F xis) with fsk/fmv in the type you are flattening - You can also add the CFunEqCan to the "flat cache", which simply keeps track of all the function applications you have flattened. - If (F xis) is in the cache already, just use its fsk/fmv and evidence x, and emit nothing. - No need to substitute in the flat-cache. It's not the end of the world if we start with, say (F alpha ~ fmv1) and (F Int ~ fmv2) and then find alpha := Int. Athat will simply give rise to fmv1 := fmv2 via [Interacting rule] below * Canonicalising a CFunEqCan [G/W] x : F xis ~ fsk/fmv - Flatten xis (to substitute any tyvars; there are already no functions) cos :: xis ~ flat_xis - New wanted x2 :: F flat_xis ~ fsk/fmv - Add new wanted to flat cache - Discharge x = F cos ; x2 * [Interacting rule] (inert) [W] x1 : F tys ~ fmv1 (work item) [W] x2 : F tys ~ fmv2 Just solve one from the other: x2 := x1 fmv2 := fmv1 This just unites the two fsks into one. Always solve given from wanted if poss. * For top-level reductions, see Note [Top-level reductions for type functions] in TcInteract Why given-fsks, alone, doesn't work ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Could we get away with only flatten meta-tyvars, with no flatten-skolems? No. [W] w : alpha ~ [F alpha Int] ---> flatten w = ...w'... [W] w' : alpha ~ [fsk] [G] <F alpha Int> : F alpha Int ~ fsk --> unify (no occurs check) alpha := [fsk] But since fsk = F alpha Int, this is really an occurs check error. If that is all we know about alpha, we will succeed in constraint solving, producing a program with an infinite type. Even if we did finally get (g : fsk ~ Bool) by solving (F alpha Int ~ fsk) using axiom, zonking would not see it, so (x::alpha) sitting in the tree will get zonked to an infinite type. (Zonking always only does refl stuff.) Why flatten-meta-vars, alone doesn't work ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Look at Simple13, with unification-fmvs only [G] g : a ~ [F a] ---> Flatten given g' = g;[x] [G] g' : a ~ [fmv] [W] x : F a ~ fmv --> subst a in x g' = g;[x] x = F g' ; x2 [W] x2 : F [fmv] ~ fmv And now we have an evidence cycle between g' and x! If we used a given instead (ie current story) [G] g : a ~ [F a] ---> Flatten given g' = g;[x] [G] g' : a ~ [fsk] [G] <F a> : F a ~ fsk ---> Substitute for a [G] g' : a ~ [fsk] [G] F (sym g'); <F a> : F [fsk] ~ fsk Why is it right to treat fmv's differently to ordinary unification vars? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ f :: forall a. a -> a -> Bool g :: F Int -> F Int -> Bool Consider f (x:Int) (y:Bool) This gives alpha~Int, alpha~Bool. There is an inconsistency, but really only one error. SherLoc may tell you which location is most likely, based on other occurrences of alpha. Consider g (x:Int) (y:Bool) Here we get (F Int ~ Int, F Int ~ Bool), which flattens to (fmv ~ Int, fmv ~ Bool) But there are really TWO separate errors. ** We must not complain about Int~Bool. ** Moreover these two errors could arise in entirely unrelated parts of the code. (In the alpha case, there must be *some* connection (eg v:alpha in common envt).) Note [Unflattening can force the solver to iterate] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Look at #10340: type family Any :: * -- No instances get :: MonadState s m => m s instance MonadState s (State s) where ... foo :: State Any Any foo = get For 'foo' we instantiate 'get' at types mm ss [WD] MonadState ss mm, [WD] mm ss ~ State Any Any Flatten, and decompose [WD] MonadState ss mm, [WD] Any ~ fmv [WD] mm ~ State fmv, [WD] fmv ~ ss Unify mm := State fmv: [WD] MonadState ss (State fmv) [WD] Any ~ fmv, [WD] fmv ~ ss Now we are stuck; the instance does not match!! So unflatten: fmv := Any ss := Any (*) [WD] MonadState Any (State Any) The unification (*) represents progress, so we must do a second round of solving; this time it succeeds. This is done by the 'go' loop in solveSimpleWanteds. This story does not feel right but it's the best I can do; and the iteration only happens in pretty obscure circumstances. ************************************************************************ * * * Examples Here is a long series of examples I had to work through * * ************************************************************************ Simple20 ~~~~~~~~ axiom F [a] = [F a] [G] F [a] ~ a --> [G] fsk ~ a [G] [F a] ~ fsk (nc) --> [G] F a ~ fsk2 [G] fsk ~ [fsk2] [G] fsk ~ a --> [G] F a ~ fsk2 [G] a ~ [fsk2] [G] fsk ~ a ---------------------------------------- indexed-types/should_compile/T44984 [W] H (F Bool) ~ H alpha [W] alpha ~ F Bool --> F Bool ~ fmv0 H fmv0 ~ fmv1 H alpha ~ fmv2 fmv1 ~ fmv2 fmv0 ~ alpha flatten ~~~~~~~ fmv0 := F Bool fmv1 := H (F Bool) fmv2 := H alpha alpha := F Bool plus fmv1 ~ fmv2 But these two are equal under the above assumptions. Solve by Refl. --- under plan B, namely solve fmv1:=fmv2 eagerly --- [W] H (F Bool) ~ H alpha [W] alpha ~ F Bool --> F Bool ~ fmv0 H fmv0 ~ fmv1 H alpha ~ fmv2 fmv1 ~ fmv2 fmv0 ~ alpha --> F Bool ~ fmv0 H fmv0 ~ fmv1 H alpha ~ fmv2 fmv2 := fmv1 fmv0 ~ alpha flatten fmv0 := F Bool fmv1 := H fmv0 = H (F Bool) retain H alpha ~ fmv2 because fmv2 has been filled alpha := F Bool ---------------------------- indexed-types/should_failt/T4179 after solving [W] fmv_1 ~ fmv_2 [W] A3 (FCon x) ~ fmv_1 (CFunEqCan) [W] A3 (x (aoa -> fmv_2)) ~ fmv_2 (CFunEqCan) ---------------------------------------- indexed-types/should_fail/T7729a a) [W] BasePrimMonad (Rand m) ~ m1 b) [W] tt m1 ~ BasePrimMonad (Rand m) ---> process (b) first BasePrimMonad (Ramd m) ~ fmv_atH fmv_atH ~ tt m1 ---> now process (a) m1 ~ s_atH ~ tt m1 -- An obscure occurs check ---------------------------------------- typecheck/TcTypeNatSimple Original constraint [W] x + y ~ x + alpha (non-canonical) ==> [W] x + y ~ fmv1 (CFunEqCan) [W] x + alpha ~ fmv2 (CFuneqCan) [W] fmv1 ~ fmv2 (CTyEqCan) (sigh) ---------------------------------------- indexed-types/should_fail/GADTwrong1 [G] Const a ~ () ==> flatten [G] fsk ~ () work item: Const a ~ fsk ==> fire top rule [G] fsk ~ () work item fsk ~ () Surely the work item should rewrite to () ~ ()? Well, maybe not; it'a very special case. More generally, our givens look like F a ~ Int, where (F a) is not reducible. ---------------------------------------- indexed_types/should_fail/T8227: Why using a different can-rewrite rule in CFunEqCan heads does not work. Assuming NOT rewriting wanteds with wanteds Inert: [W] fsk_aBh ~ fmv_aBk -> fmv_aBk [W] fmv_aBk ~ fsk_aBh [G] Scalar fsk_aBg ~ fsk_aBh [G] V a ~ f_aBg Worklist includes [W] Scalar fmv_aBi ~ fmv_aBk fmv_aBi, fmv_aBk are flatten unification variables Work item: [W] V fsk_aBh ~ fmv_aBi Note that the inert wanteds are cyclic, because we do not rewrite wanteds with wanteds. Then we go into a loop when normalise the work-item, because we use rewriteOrSame on the argument of V. Conclusion: Don't make canRewrite context specific; instead use [W] a ~ ty to rewrite a wanted iff 'a' is a unification variable. ---------------------------------------- Here is a somewhat similar case: type family G a :: * blah :: (G a ~ Bool, Eq (G a)) => a -> a blah = error "urk" foo x = blah x For foo we get [W] Eq (G a), G a ~ Bool Flattening [W] G a ~ fmv, Eq fmv, fmv ~ Bool We can't simplify away the Eq Bool unless we substitute for fmv. Maybe that doesn't matter: we would still be left with unsolved G a ~ Bool. -------------------------- #9318 has a very simple program leading to [W] F Int ~ Int [W] F Int ~ Bool We don't want to get "Error Int~Bool". But if fmv's can rewrite wanteds, we will [W] fmv ~ Int [W] fmv ~ Bool ---> [W] Int ~ Bool ************************************************************************ * * * FlattenEnv & FlatM * The flattening environment & monad * * ************************************************************************ -} type FlatWorkListRef = TcRef [Ct] -- See Note [The flattening work list] data FlattenEnv = FE { fe_mode :: !FlattenMode , fe_loc :: CtLoc -- See Note [Flattener CtLoc] -- unbanged because it's bogus in rewriteTyVar , fe_flavour :: !CtFlavour , fe_eq_rel :: !EqRel -- See Note [Flattener EqRels] , fe_work :: !FlatWorkListRef } -- See Note [The flattening work list] data FlattenMode -- Postcondition for all three: inert wrt the type substitution = FM_FlattenAll -- Postcondition: function-free | FM_SubstOnly -- See Note [Flattening under a forall] -- | FM_Avoid TcTyVar Bool -- See Note [Lazy flattening] -- -- Postcondition: -- -- * tyvar is only mentioned in result under a rigid path -- -- e.g. [a] is ok, but F a won't happen -- -- * If flat_top is True, top level is not a function application -- -- (but under type constructors is ok e.g. [F a]) instance Outputable FlattenMode where ppr FM_FlattenAll = text "FM_FlattenAll" ppr FM_SubstOnly = text "FM_SubstOnly" eqFlattenMode :: FlattenMode -> FlattenMode -> Bool eqFlattenMode FM_FlattenAll FM_FlattenAll = True eqFlattenMode FM_SubstOnly FM_SubstOnly = True -- FM_Avoid tv1 b1 `eq` FM_Avoid tv2 b2 = tv1 == tv2 && b1 == b2 eqFlattenMode _ _ = False -- | The 'FlatM' monad is a wrapper around 'TcS' with the following -- extra capabilities: (1) it offers access to a 'FlattenEnv'; -- and (2) it maintains the flattening worklist. -- See Note [The flattening work list]. newtype FlatM a = FlatM { runFlatM :: FlattenEnv -> TcS a } deriving (Functor) instance Monad FlatM where m >>= k = FlatM $ \env -> do { a <- runFlatM m env ; runFlatM (k a) env } instance Applicative FlatM where pure x = FlatM $ const (pure x) (<*>) = ap liftTcS :: TcS a -> FlatM a liftTcS thing_inside = FlatM $ const thing_inside emitFlatWork :: Ct -> FlatM () -- See Note [The flattening work list] emitFlatWork ct = FlatM $ \env -> updTcRef (fe_work env) (ct :) -- convenient wrapper when you have a CtEvidence describing -- the flattening operation runFlattenCtEv :: FlattenMode -> CtEvidence -> FlatM a -> TcS a runFlattenCtEv mode ev = runFlatten mode (ctEvLoc ev) (ctEvFlavour ev) (ctEvEqRel ev) -- Run thing_inside (which does flattening), and put all -- the work it generates onto the main work list -- See Note [The flattening work list] runFlatten :: FlattenMode -> CtLoc -> CtFlavour -> EqRel -> FlatM a -> TcS a runFlatten mode loc flav eq_rel thing_inside = do { flat_ref <- newTcRef [] ; let fmode = FE { fe_mode = mode , fe_loc = bumpCtLocDepth loc -- See Note [Flatten when discharging CFunEqCan] , fe_flavour = flav , fe_eq_rel = eq_rel , fe_work = flat_ref } ; res <- runFlatM thing_inside fmode ; new_flats <- readTcRef flat_ref ; updWorkListTcS (add_flats new_flats) ; return res } where add_flats new_flats wl = wl { wl_funeqs = add_funeqs new_flats (wl_funeqs wl) } add_funeqs [] wl = wl add_funeqs (f:fs) wl = add_funeqs fs (f:wl) -- add_funeqs fs ws = reverse fs ++ ws -- e.g. add_funeqs [f1,f2,f3] [w1,w2,w3,w4] -- = [f3,f2,f1,w1,w2,w3,w4] traceFlat :: String -> SDoc -> FlatM () traceFlat herald doc = liftTcS $ traceTcS herald doc getFlatEnvField :: (FlattenEnv -> a) -> FlatM a getFlatEnvField accessor = FlatM $ \env -> return (accessor env) getEqRel :: FlatM EqRel getEqRel = getFlatEnvField fe_eq_rel getRole :: FlatM Role getRole = eqRelRole <$> getEqRel getFlavour :: FlatM CtFlavour getFlavour = getFlatEnvField fe_flavour getFlavourRole :: FlatM CtFlavourRole getFlavourRole = do { flavour <- getFlavour ; eq_rel <- getEqRel ; return (flavour, eq_rel) } getMode :: FlatM FlattenMode getMode = getFlatEnvField fe_mode getLoc :: FlatM CtLoc getLoc = getFlatEnvField fe_loc checkStackDepth :: Type -> FlatM () checkStackDepth ty = do { loc <- getLoc ; liftTcS $ checkReductionDepth loc ty } -- | Change the 'EqRel' in a 'FlatM'. setEqRel :: EqRel -> FlatM a -> FlatM a setEqRel new_eq_rel thing_inside = FlatM $ \env -> if new_eq_rel == fe_eq_rel env then runFlatM thing_inside env else runFlatM thing_inside (env { fe_eq_rel = new_eq_rel }) -- | Change the 'FlattenMode' in a 'FlattenEnv'. setMode :: FlattenMode -> FlatM a -> FlatM a setMode new_mode thing_inside = FlatM $ \env -> if new_mode `eqFlattenMode` fe_mode env then runFlatM thing_inside env else runFlatM thing_inside (env { fe_mode = new_mode }) -- | Make sure that flattening actually produces a coercion (in other -- words, make sure our flavour is not Derived) -- Note [No derived kind equalities] noBogusCoercions :: FlatM a -> FlatM a noBogusCoercions thing_inside = FlatM $ \env -> -- No new thunk is made if the flavour hasn't changed (note the bang). let !env' = case fe_flavour env of Derived -> env { fe_flavour = Wanted WDeriv } _ -> env in runFlatM thing_inside env' bumpDepth :: FlatM a -> FlatM a bumpDepth (FlatM thing_inside) = FlatM $ \env -> do -- bumpDepth can be called a lot during flattening so we force the -- new env to avoid accumulating thunks. { let !env' = env { fe_loc = bumpCtLocDepth (fe_loc env) } ; thing_inside env' } {- Note [The flattening work list] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The "flattening work list", held in the fe_work field of FlattenEnv, is a list of CFunEqCans generated during flattening. The key idea is this. Consider flattening (Eq (F (G Int) (H Bool)): * The flattener recursively calls itself on sub-terms before building the main term, so it will encounter the terms in order G Int H Bool F (G Int) (H Bool) flattening to sub-goals w1: G Int ~ fuv0 w2: H Bool ~ fuv1 w3: F fuv0 fuv1 ~ fuv2 * Processing w3 first is BAD, because we can't reduce i t,so it'll get put into the inert set, and later kicked out when w1, w2 are solved. In #9872 this led to inert sets containing hundreds of suspended calls. * So we want to process w1, w2 first. * So you might think that we should just use a FIFO deque for the work-list, so that putting adding goals in order w1,w2,w3 would mean we processed w1 first. * BUT suppose we have 'type instance G Int = H Char'. Then processing w1 leads to a new goal w4: H Char ~ fuv0 We do NOT want to put that on the far end of a deque! Instead we want to put it at the *front* of the work-list so that we continue to work on it. So the work-list structure is this: * The wl_funeqs (in TcS) is a LIFO stack; we push new goals (such as w4) on top (extendWorkListFunEq), and take new work from the top (selectWorkItem). * When flattening, emitFlatWork pushes new flattening goals (like w1,w2,w3) onto the flattening work list, fe_work, another push-down stack. * When we finish flattening, we *reverse* the fe_work stack onto the wl_funeqs stack (which brings w1 to the top). The function runFlatten initialises the fe_work stack, and reverses it onto wl_fun_eqs at the end. Note [Flattener EqRels] ~~~~~~~~~~~~~~~~~~~~~~~ When flattening, we need to know which equality relation -- nominal or representation -- we should be respecting. The only difference is that we rewrite variables by representational equalities when fe_eq_rel is ReprEq, and that we unwrap newtypes when flattening w.r.t. representational equality. Note [Flattener CtLoc] ~~~~~~~~~~~~~~~~~~~~~~ The flattener does eager type-family reduction. Type families might loop, and we don't want GHC to do so. A natural solution is to have a bounded depth to these processes. A central difficulty is that such a solution isn't quite compositional. For example, say it takes F Int 10 steps to get to Bool. How many steps does it take to get from F Int -> F Int to Bool -> Bool? 10? 20? What about getting from Const Char (F Int) to Char? 11? 1? Hard to know and hard to track. So, we punt, essentially. We store a CtLoc in the FlattenEnv and just update the environment when recurring. In the TyConApp case, where there may be multiple type families to flatten, we just copy the current CtLoc into each branch. If any branch hits the stack limit, then the whole thing fails. A consequence of this is that setting the stack limits appropriately will be essentially impossible. So, the official recommendation if a stack limit is hit is to disable the check entirely. Otherwise, there will be baffling, unpredictable errors. Note [Lazy flattening] ~~~~~~~~~~~~~~~~~~~~~~ The idea of FM_Avoid mode is to flatten less aggressively. If we have a ~ [F Int] there seems to be no great merit in lifting out (F Int). But if it was a ~ [G a Int] then we *do* want to lift it out, in case (G a Int) reduces to Bool, say, which gets rid of the occurs-check problem. (For the flat_top Bool, see comments above and at call sites.) HOWEVER, the lazy flattening actually seems to make type inference go *slower*, not faster. perf/compiler/T3064 is a case in point; it gets *dramatically* worse with FM_Avoid. I think it may be because floating the types out means we normalise them, and that often makes them smaller and perhaps allows more re-use of previously solved goals. But to be honest I'm not absolutely certain, so I am leaving FM_Avoid in the code base. What I'm removing is the unique place where it is *used*, namely in TcCanonical.canEqTyVar. See also Note [Conservative unification check] in TcUnify, which gives other examples where lazy flattening caused problems. Bottom line: FM_Avoid is unused for now (Nov 14). Note: T5321Fun got faster when I disabled FM_Avoid T5837 did too, but it's pathological anyway Note [Phantoms in the flattener] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have data Proxy p = Proxy and we're flattening (Proxy ty) w.r.t. ReprEq. Then, we know that `ty` is really irrelevant -- it will be ignored when solving for representational equality later on. So, we omit flattening `ty` entirely. This may violate the expectation of "xi"s for a bit, but the canonicaliser will soon throw out the phantoms when decomposing a TyConApp. (Or, the canonicaliser will emit an insoluble, in which case the unflattened version yields a better error message anyway.) Note [No derived kind equalities] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A kind-level coercion can appear in types, via mkCastTy. So, whenever we are generating a coercion in a dependent context (in other words, in a kind) we need to make sure that our flavour is never Derived (as Derived constraints have no evidence). The noBogusCoercions function changes the flavour from Derived just for this purpose. -} {- ********************************************************************* * * * Externally callable flattening functions * * * * They are all wrapped in runFlatten, so their * * flattening work gets put into the work list * * * ********************************************************************* Note [rewriteTyVar] ~~~~~~~~~~~~~~~~~~~~~~ Suppose we have an injective function F and inert_funeqs: F t1 ~ fsk1 F t2 ~ fsk2 inert_eqs: fsk1 ~ [a] a ~ Int fsk2 ~ [Int] We never rewrite the RHS (cc_fsk) of a CFunEqCan. But we /do/ want to get the [D] t1 ~ t2 from the injectiveness of F. So we flatten cc_fsk of CFunEqCans when trying to find derived equalities arising from injectivity. -} -- | See Note [Flattening]. -- If (xi, co) <- flatten mode ev ty, then co :: xi ~r ty -- where r is the role in @ev@. If @mode@ is 'FM_FlattenAll', -- then 'xi' is almost function-free (Note [Almost function-free] -- in TcRnTypes). flatten :: FlattenMode -> CtEvidence -> TcType -> TcS (Xi, TcCoercion) flatten mode ev ty = do { traceTcS "flatten {" (ppr mode <+> ppr ty) ; (ty', co) <- runFlattenCtEv mode ev (flatten_one ty) ; traceTcS "flatten }" (ppr ty') ; return (ty', co) } -- Apply the inert set as an *inert generalised substitution* to -- a variable, zonking along the way. -- See Note [inert_eqs: the inert equalities] in TcSMonad. -- Equivalently, this flattens the variable with respect to NomEq -- in a Derived constraint. (Why Derived? Because Derived allows the -- most about of rewriting.) Returns no coercion, because we're -- using Derived constraints. -- See Note [rewriteTyVar] rewriteTyVar :: TcTyVar -> TcS TcType rewriteTyVar tv = do { traceTcS "rewriteTyVar {" (ppr tv) ; (ty, _) <- runFlatten FM_SubstOnly fake_loc Derived NomEq $ flattenTyVar tv ; traceTcS "rewriteTyVar }" (ppr ty) ; return ty } where fake_loc = pprPanic "rewriteTyVar used a CtLoc" (ppr tv) -- specialized to flattening kinds: never Derived, always Nominal -- See Note [No derived kind equalities] -- See Note [Flattening] flattenKind :: CtLoc -> CtFlavour -> TcType -> TcS (Xi, TcCoercionN) flattenKind loc flav ty = do { traceTcS "flattenKind {" (ppr flav <+> ppr ty) ; let flav' = case flav of Derived -> Wanted WDeriv -- the WDeriv/WOnly choice matters not _ -> flav ; (ty', co) <- runFlatten FM_FlattenAll loc flav' NomEq (flatten_one ty) ; traceTcS "flattenKind }" (ppr ty' $$ ppr co) -- co is never a panic ; return (ty', co) } -- See Note [Flattening] flattenArgsNom :: CtEvidence -> TyCon -> [TcType] -> TcS ([Xi], [TcCoercion], TcCoercionN) -- Externally-callable, hence runFlatten -- Flatten a vector of types all at once; in fact they are -- always the arguments of type family or class, so -- ctEvFlavour ev = Nominal -- and we want to flatten all at nominal role -- The kind passed in is the kind of the type family or class, call it T -- The last coercion returned has type (tcTypeKind(T xis) ~N tcTypeKind(T tys)) -- -- For Derived constraints the returned coercion may be undefined -- because flattening may use a Derived equality ([D] a ~ ty) flattenArgsNom ev tc tys = do { traceTcS "flatten_args {" (vcat (map ppr tys)) ; (tys', cos, kind_co) <- runFlattenCtEv FM_FlattenAll ev (flatten_args_tc tc (repeat Nominal) tys) ; traceTcS "flatten }" (vcat (map ppr tys')) ; return (tys', cos, kind_co) } {- ********************************************************************* * * * The main flattening functions * * ********************************************************************* -} {- Note [Flattening] ~~~~~~~~~~~~~~~~~~~~ flatten ty ==> (xi, co) where xi has no type functions, unless they appear under ForAlls has no skolems that are mapped in the inert set has no filled-in metavariables co :: xi ~ ty Key invariants: (F0) co :: xi ~ zonk(ty) (F1) tcTypeKind(xi) succeeds and returns a fully zonked kind (F2) tcTypeKind(xi) `eqType` zonk(tcTypeKind(ty)) Note that it is flatten's job to flatten *every type function it sees*. flatten is only called on *arguments* to type functions, by canEqGiven. Flattening also: * zonks, removing any metavariables, and * applies the substitution embodied in the inert set The result of flattening is *almost function-free*. See Note [Almost function-free] in TcRnTypes. Because flattening zonks and the returned coercion ("co" above) is also zonked, it's possible that (co :: xi ~ ty) isn't quite true. So, instead, we can rely on this fact: (F0) co :: xi ~ zonk(ty) Note that the left-hand type of co is *always* precisely xi. The right-hand type may or may not be ty, however: if ty has unzonked filled-in metavariables, then the right-hand type of co will be the zonked version of ty. It is for this reason that we occasionally have to explicitly zonk, when (co :: xi ~ ty) is important even before we zonk the whole program. For example, see the FTRNotFollowed case in flattenTyVar. Why have these invariants on flattening? Because we sometimes use tcTypeKind during canonicalisation, and we want this kind to be zonked (e.g., see TcCanonical.canEqTyVar). Flattening is always homogeneous. That is, the kind of the result of flattening is always the same as the kind of the input, modulo zonking. More formally: (F2) tcTypeKind(xi) `eqType` zonk(tcTypeKind(ty)) This invariant means that the kind of a flattened type might not itself be flat. Recall that in comments we use alpha[flat = ty] to represent a flattening skolem variable alpha which has been generated to stand in for ty. ----- Example of flattening a constraint: ------ flatten (List (F (G Int))) ==> (xi, cc) where xi = List alpha cc = { G Int ~ beta[flat = G Int], F beta ~ alpha[flat = F beta] } Here * alpha and beta are 'flattening skolem variables'. * All the constraints in cc are 'given', and all their coercion terms are the identity. NB: Flattening Skolems only occur in canonical constraints, which are never zonked, so we don't need to worry about zonking doing accidental unflattening. Note that we prefer to leave type synonyms unexpanded when possible, so when the flattener encounters one, it first asks whether its transitive expansion contains any type function applications. If so, it expands the synonym and proceeds; if not, it simply returns the unexpanded synonym. Note [flatten_args performance] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In programs with lots of type-level evaluation, flatten_args becomes part of a tight loop. For example, see test perf/compiler/T9872a, which calls flatten_args a whopping 7,106,808 times. It is thus important that flatten_args be efficient. Performance testing showed that the current implementation is indeed efficient. It's critically important that zipWithAndUnzipM be specialized to TcS, and it's also quite helpful to actually `inline` it. On test T9872a, here are the allocation stats (Dec 16, 2014): * Unspecialized, uninlined: 8,472,613,440 bytes allocated in the heap * Specialized, uninlined: 6,639,253,488 bytes allocated in the heap * Specialized, inlined: 6,281,539,792 bytes allocated in the heap To improve performance even further, flatten_args_nom is split off from flatten_args, as nominal equality is the common case. This would be natural to write using mapAndUnzipM, but even inlined, that function is not as performant as a hand-written loop. * mapAndUnzipM, inlined: 7,463,047,432 bytes allocated in the heap * hand-written recursion: 5,848,602,848 bytes allocated in the heap If you make any change here, pay close attention to the T9872{a,b,c} tests and T5321Fun. If we need to make this yet more performant, a possible way forward is to duplicate the flattener code for the nominal case, and make that case faster. This doesn't seem quite worth it, yet. Note [flatten_exact_fam_app_fully performance] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The refactor of GRefl seems to cause performance trouble for T9872x: the allocation of flatten_exact_fam_app_fully_performance increased. See note [Generalized reflexive coercion] in TyCoRep for more information about GRefl and #15192 for the current state. The explicit pattern match in homogenise_result helps with T9872a, b, c. Still, it increases the expected allocation of T9872d by ~2%. TODO: a step-by-step replay of the refactor to analyze the performance. -} {-# INLINE flatten_args_tc #-} flatten_args_tc :: TyCon -- T -> [Role] -- Role r -> [Type] -- Arg types [t1,..,tn] -> FlatM ( [Xi] -- List of flattened args [x1,..,xn] -- 1-1 corresp with [t1,..,tn] , [Coercion] -- List of arg coercions [co1,..,con] -- 1-1 corresp with [t1,..,tn] -- coi :: xi ~r ti , CoercionN) -- Result coercion, rco -- rco : (T t1..tn) ~N (T (x1 |> co1) .. (xn |> con)) flatten_args_tc tc = flatten_args all_bndrs any_named_bndrs inner_ki emptyVarSet -- NB: TyCon kinds are always closed where (bndrs, named) = ty_con_binders_ty_binders' (tyConBinders tc) -- it's possible that the result kind has arrows (for, e.g., a type family) -- so we must split it (inner_bndrs, inner_ki, inner_named) = split_pi_tys' (tyConResKind tc) !all_bndrs = bndrs `chkAppend` inner_bndrs !any_named_bndrs = named || inner_named -- NB: Those bangs there drop allocations in T9872{a,c,d} by 8%. {-# INLINE flatten_args #-} flatten_args :: [TyCoBinder] -> Bool -- Binders, and True iff any of them are -- named. -> Kind -> TcTyCoVarSet -- function kind; kind's free vars -> [Role] -> [Type] -- these are in 1-to-1 correspondence -> FlatM ([Xi], [Coercion], CoercionN) -- Coercions :: Xi ~ Type, at roles given -- Third coercion :: tcTypeKind(fun xis) ~N tcTypeKind(fun tys) -- That is, the third coercion relates the kind of some function (whose kind is -- passed as the first parameter) instantiated at xis to the kind of that -- function instantiated at the tys. This is useful in keeping flattening -- homoegeneous. The list of roles must be at least as long as the list of -- types. flatten_args orig_binders any_named_bndrs orig_inner_ki orig_fvs orig_roles orig_tys = if any_named_bndrs then flatten_args_slow orig_binders orig_inner_ki orig_fvs orig_roles orig_tys else flatten_args_fast orig_binders orig_inner_ki orig_roles orig_tys {-# INLINE flatten_args_fast #-} -- | fast path flatten_args, in which none of the binders are named and -- therefore we can avoid tracking a lifting context. -- There are many bang patterns in here. It's been observed that they -- greatly improve performance of an optimized build. -- The T9872 test cases are good witnesses of this fact. flatten_args_fast :: [TyCoBinder] -> Kind -> [Role] -> [Type] -> FlatM ([Xi], [Coercion], CoercionN) flatten_args_fast orig_binders orig_inner_ki orig_roles orig_tys = fmap finish (iterate orig_tys orig_roles orig_binders) where iterate :: [Type] -> [Role] -> [TyCoBinder] -> FlatM ([Xi], [Coercion], [TyCoBinder]) iterate (ty:tys) (role:roles) (_:binders) = do (xi, co) <- go role ty (xis, cos, binders) <- iterate tys roles binders pure (xi : xis, co : cos, binders) iterate [] _ binders = pure ([], [], binders) iterate _ _ _ = pprPanic "flatten_args wandered into deeper water than usual" (vcat []) -- This debug information is commented out because leaving it in -- causes a ~2% increase in allocations in T9872{a,c,d}. {- (vcat [ppr orig_binders, ppr orig_inner_ki, ppr (take 10 orig_roles), -- often infinite! ppr orig_tys]) -} {-# INLINE go #-} go :: Role -> Type -> FlatM (Xi, Coercion) go role ty = case role of -- In the slow path we bind the Xi and Coercion from the recursive -- call and then use it such -- -- let kind_co = mkTcSymCo $ mkReflCo Nominal (tyBinderType binder) -- casted_xi = xi `mkCastTy` kind_co -- casted_co = xi |> kind_co ~r xi ; co -- -- but this isn't necessary: -- mkTcSymCo (Refl a b) = Refl a b, -- mkCastTy x (Refl _ _) = x -- mkTcGReflLeftCo _ ty (Refl _ _) `mkTransCo` co = co -- -- Also, no need to check isAnonTyCoBinder or isNamedBinder, since -- we've already established that they're all anonymous. Nominal -> setEqRel NomEq $ flatten_one ty Representational -> setEqRel ReprEq $ flatten_one ty Phantom -> -- See Note [Phantoms in the flattener] do { ty <- liftTcS $ zonkTcType ty ; return (ty, mkReflCo Phantom ty) } {-# INLINE finish #-} finish :: ([Xi], [Coercion], [TyCoBinder]) -> ([Xi], [Coercion], CoercionN) finish (xis, cos, binders) = (xis, cos, kind_co) where final_kind = mkPiTys binders orig_inner_ki kind_co = mkNomReflCo final_kind {-# INLINE flatten_args_slow #-} -- | Slow path, compared to flatten_args_fast, because this one must track -- a lifting context. flatten_args_slow :: [TyCoBinder] -> Kind -> TcTyCoVarSet -> [Role] -> [Type] -> FlatM ([Xi], [Coercion], CoercionN) flatten_args_slow binders inner_ki fvs roles tys -- Arguments used dependently must be flattened with proper coercions, but -- we're not guaranteed to get a proper coercion when flattening with the -- "Derived" flavour. So we must call noBogusCoercions when flattening arguments -- corresponding to binders that are dependent. However, we might legitimately -- have *more* arguments than binders, in the case that the inner_ki is a variable -- that gets instantiated with a Π-type. We conservatively choose not to produce -- bogus coercions for these, too. Note that this might miss an opportunity for -- a Derived rewriting a Derived. The solution would be to generate evidence for -- Deriveds, thus avoiding this whole noBogusCoercions idea. See also -- Note [No derived kind equalities] = do { flattened_args <- zipWith3M fl (map isNamedBinder binders ++ repeat True) roles tys ; return (simplifyArgsWorker binders inner_ki fvs roles flattened_args) } where {-# INLINE fl #-} fl :: Bool -- must we ensure to produce a real coercion here? -- see comment at top of function -> Role -> Type -> FlatM (Xi, Coercion) fl True r ty = noBogusCoercions $ fl1 r ty fl False r ty = fl1 r ty {-# INLINE fl1 #-} fl1 :: Role -> Type -> FlatM (Xi, Coercion) fl1 Nominal ty = setEqRel NomEq $ flatten_one ty fl1 Representational ty = setEqRel ReprEq $ flatten_one ty fl1 Phantom ty -- See Note [Phantoms in the flattener] = do { ty <- liftTcS $ zonkTcType ty ; return (ty, mkReflCo Phantom ty) } ------------------ flatten_one :: TcType -> FlatM (Xi, Coercion) -- Flatten a type to get rid of type function applications, returning -- the new type-function-free type, and a collection of new equality -- constraints. See Note [Flattening] for more detail. -- -- Postcondition: Coercion :: Xi ~ TcType -- The role on the result coercion matches the EqRel in the FlattenEnv flatten_one xi@(LitTy {}) = do { role <- getRole ; return (xi, mkReflCo role xi) } flatten_one (TyVarTy tv) = flattenTyVar tv flatten_one (AppTy ty1 ty2) = flatten_app_tys ty1 [ty2] flatten_one (TyConApp tc tys) -- Expand type synonyms that mention type families -- on the RHS; see Note [Flattening synonyms] | Just (tenv, rhs, tys') <- expandSynTyCon_maybe tc tys , let expanded_ty = mkAppTys (substTy (mkTvSubstPrs tenv) rhs) tys' = do { mode <- getMode ; case mode of FM_FlattenAll | not (isFamFreeTyCon tc) -> flatten_one expanded_ty _ -> flatten_ty_con_app tc tys } -- Otherwise, it's a type function application, and we have to -- flatten it away as well, and generate a new given equality constraint -- between the application and a newly generated flattening skolem variable. | isTypeFamilyTyCon tc = flatten_fam_app tc tys -- For * a normal data type application -- * data family application -- we just recursively flatten the arguments. | otherwise -- FM_Avoid stuff commented out; see Note [Lazy flattening] -- , let fmode' = case fmode of -- Switch off the flat_top bit in FM_Avoid -- FE { fe_mode = FM_Avoid tv _ } -- -> fmode { fe_mode = FM_Avoid tv False } -- _ -> fmode = flatten_ty_con_app tc tys flatten_one ty@(FunTy _ ty1 ty2) = do { (xi1,co1) <- flatten_one ty1 ; (xi2,co2) <- flatten_one ty2 ; role <- getRole ; return (ty { ft_arg = xi1, ft_res = xi2 } , mkFunCo role co1 co2) } flatten_one ty@(ForAllTy {}) -- TODO (RAE): This is inadequate, as it doesn't flatten the kind of -- the bound tyvar. Doing so will require carrying around a substitution -- and the usual substTyVarBndr-like silliness. Argh. -- We allow for-alls when, but only when, no type function -- applications inside the forall involve the bound type variables. = do { let (bndrs, rho) = tcSplitForAllVarBndrs ty tvs = binderVars bndrs ; (rho', co) <- setMode FM_SubstOnly $ flatten_one rho -- Substitute only under a forall -- See Note [Flattening under a forall] ; return (mkForAllTys bndrs rho', mkHomoForAllCos tvs co) } flatten_one (CastTy ty g) = do { (xi, co) <- flatten_one ty ; (g', _) <- flatten_co g ; role <- getRole ; return (mkCastTy xi g', castCoercionKind co role xi ty g' g) } flatten_one (CoercionTy co) = first mkCoercionTy <$> flatten_co co -- | "Flatten" a coercion. Really, just zonk it so we can uphold -- (F1) of Note [Flattening] flatten_co :: Coercion -> FlatM (Coercion, Coercion) flatten_co co = do { co <- liftTcS $ zonkCo co ; env_role <- getRole ; let co' = mkTcReflCo env_role (mkCoercionTy co) ; return (co, co') } -- flatten (nested) AppTys flatten_app_tys :: Type -> [Type] -> FlatM (Xi, Coercion) -- commoning up nested applications allows us to look up the function's kind -- only once. Without commoning up like this, we would spend a quadratic amount -- of time looking up functions' types flatten_app_tys (AppTy ty1 ty2) tys = flatten_app_tys ty1 (ty2:tys) flatten_app_tys fun_ty arg_tys = do { (fun_xi, fun_co) <- flatten_one fun_ty ; flatten_app_ty_args fun_xi fun_co arg_tys } -- Given a flattened function (with the coercion produced by flattening) and -- a bunch of unflattened arguments, flatten the arguments and apply. -- The coercion argument's role matches the role stored in the FlatM monad. -- -- The bang patterns used here were observed to improve performance. If you -- wish to remove them, be sure to check for regeressions in allocations. flatten_app_ty_args :: Xi -> Coercion -> [Type] -> FlatM (Xi, Coercion) flatten_app_ty_args fun_xi fun_co [] -- this will be a common case when called from flatten_fam_app, so shortcut = return (fun_xi, fun_co) flatten_app_ty_args fun_xi fun_co arg_tys = do { (xi, co, kind_co) <- case tcSplitTyConApp_maybe fun_xi of Just (tc, xis) -> do { let tc_roles = tyConRolesRepresentational tc arg_roles = dropList xis tc_roles ; (arg_xis, arg_cos, kind_co) <- flatten_vector (tcTypeKind fun_xi) arg_roles arg_tys -- Here, we have fun_co :: T xi1 xi2 ~ ty -- and we need to apply fun_co to the arg_cos. The problem is -- that using mkAppCo is wrong because that function expects -- its second coercion to be Nominal, and the arg_cos might -- not be. The solution is to use transitivity: -- T <xi1> <xi2> arg_cos ;; fun_co <arg_tys> ; eq_rel <- getEqRel ; let app_xi = mkTyConApp tc (xis ++ arg_xis) app_co = case eq_rel of NomEq -> mkAppCos fun_co arg_cos ReprEq -> mkTcTyConAppCo Representational tc (zipWith mkReflCo tc_roles xis ++ arg_cos) `mkTcTransCo` mkAppCos fun_co (map mkNomReflCo arg_tys) ; return (app_xi, app_co, kind_co) } Nothing -> do { (arg_xis, arg_cos, kind_co) <- flatten_vector (tcTypeKind fun_xi) (repeat Nominal) arg_tys ; let arg_xi = mkAppTys fun_xi arg_xis arg_co = mkAppCos fun_co arg_cos ; return (arg_xi, arg_co, kind_co) } ; role <- getRole ; return (homogenise_result xi co role kind_co) } flatten_ty_con_app :: TyCon -> [TcType] -> FlatM (Xi, Coercion) flatten_ty_con_app tc tys = do { role <- getRole ; (xis, cos, kind_co) <- flatten_args_tc tc (tyConRolesX role tc) tys ; let tyconapp_xi = mkTyConApp tc xis tyconapp_co = mkTyConAppCo role tc cos ; return (homogenise_result tyconapp_xi tyconapp_co role kind_co) } -- Make the result of flattening homogeneous (Note [Flattening] (F2)) homogenise_result :: Xi -- a flattened type -> Coercion -- :: xi ~r original ty -> Role -- r -> CoercionN -- kind_co :: tcTypeKind(xi) ~N tcTypeKind(ty) -> (Xi, Coercion) -- (xi |> kind_co, (xi |> kind_co) -- ~r original ty) homogenise_result xi co r kind_co -- the explicit pattern match here improves the performance of T9872a, b, c by -- ~2% | isGReflCo kind_co = (xi `mkCastTy` kind_co, co) | otherwise = (xi `mkCastTy` kind_co , (mkSymCo $ GRefl r xi (MCo kind_co)) `mkTransCo` co) {-# INLINE homogenise_result #-} -- Flatten a vector (list of arguments). flatten_vector :: Kind -- of the function being applied to these arguments -> [Role] -- If we're flatten w.r.t. ReprEq, what roles do the -- args have? -> [Type] -- the args to flatten -> FlatM ([Xi], [Coercion], CoercionN) flatten_vector ki roles tys = do { eq_rel <- getEqRel ; case eq_rel of NomEq -> flatten_args bndrs any_named_bndrs inner_ki fvs (repeat Nominal) tys ReprEq -> flatten_args bndrs any_named_bndrs inner_ki fvs roles tys } where (bndrs, inner_ki, any_named_bndrs) = split_pi_tys' ki fvs = tyCoVarsOfType ki {-# INLINE flatten_vector #-} {- Note [Flattening synonyms] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Not expanding synonyms aggressively improves error messages, and keeps types smaller. But we need to take care. Suppose type T a = a -> a and we want to flatten the type (T (F a)). Then we can safely flatten the (F a) to a skolem, and return (T fsk). We don't need to expand the synonym. This works because TcTyConAppCo can deal with synonyms (unlike TyConAppCo), see Note [TcCoercions] in TcEvidence. But (#8979) for type T a = (F a, a) where F is a type function we must expand the synonym in (say) T Int, to expose the type function to the flattener. Note [Flattening under a forall] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Under a forall, we (a) MUST apply the inert substitution (b) MUST NOT flatten type family applications Hence FMSubstOnly. For (a) consider c ~ a, a ~ T (forall b. (b, [c])) If we don't apply the c~a substitution to the second constraint we won't see the occurs-check error. For (b) consider (a ~ forall b. F a b), we don't want to flatten to (a ~ forall b.fsk, F a b ~ fsk) because now the 'b' has escaped its scope. We'd have to flatten to (a ~ forall b. fsk b, forall b. F a b ~ fsk b) and we have not begun to think about how to make that work! ************************************************************************ * * Flattening a type-family application * * ************************************************************************ -} flatten_fam_app :: TyCon -> [TcType] -> FlatM (Xi, Coercion) -- flatten_fam_app can be over-saturated -- flatten_exact_fam_app is exactly saturated -- flatten_exact_fam_app_fully lifts out the application to top level -- Postcondition: Coercion :: Xi ~ F tys flatten_fam_app tc tys -- Can be over-saturated = ASSERT2( tys `lengthAtLeast` tyConArity tc , ppr tc $$ ppr (tyConArity tc) $$ ppr tys) do { mode <- getMode ; case mode of { FM_SubstOnly -> flatten_ty_con_app tc tys ; FM_FlattenAll -> -- Type functions are saturated -- The type function might be *over* saturated -- in which case the remaining arguments should -- be dealt with by AppTys do { let (tys1, tys_rest) = splitAt (tyConArity tc) tys ; (xi1, co1) <- flatten_exact_fam_app_fully tc tys1 -- co1 :: xi1 ~ F tys1 ; flatten_app_ty_args xi1 co1 tys_rest } } } -- the [TcType] exactly saturate the TyCon -- See note [flatten_exact_fam_app_fully performance] flatten_exact_fam_app_fully :: TyCon -> [TcType] -> FlatM (Xi, Coercion) flatten_exact_fam_app_fully tc tys -- See Note [Reduce type family applications eagerly] -- the following tcTypeKind should never be evaluated, as it's just used in -- casting, and casts by refl are dropped = do { mOut <- try_to_reduce_nocache tc tys ; case mOut of Just out -> pure out Nothing -> do { -- First, flatten the arguments ; (xis, cos, kind_co) <- setEqRel NomEq $ -- just do this once, instead of for -- each arg flatten_args_tc tc (repeat Nominal) tys -- kind_co :: tcTypeKind(F xis) ~N tcTypeKind(F tys) ; eq_rel <- getEqRel ; cur_flav <- getFlavour ; let role = eqRelRole eq_rel ret_co = mkTyConAppCo role tc cos -- ret_co :: F xis ~ F tys; might be heterogeneous -- Now, look in the cache ; mb_ct <- liftTcS $ lookupFlatCache tc xis ; case mb_ct of Just (co, rhs_ty, flav) -- co :: F xis ~ fsk -- flav is [G] or [WD] -- See Note [Type family equations] in TcSMonad | (NotSwapped, _) <- flav `funEqCanDischargeF` cur_flav -> -- Usable hit in the flat-cache do { traceFlat "flatten/flat-cache hit" $ (ppr tc <+> ppr xis $$ ppr rhs_ty) ; (fsk_xi, fsk_co) <- flatten_one rhs_ty -- The fsk may already have been unified, so -- flatten it -- fsk_co :: fsk_xi ~ fsk ; let xi = fsk_xi `mkCastTy` kind_co co' = mkTcCoherenceLeftCo role fsk_xi kind_co fsk_co `mkTransCo` maybeTcSubCo eq_rel (mkSymCo co) `mkTransCo` ret_co ; return (xi, co') } -- :: fsk_xi ~ F xis -- Try to reduce the family application right now -- See Note [Reduce type family applications eagerly] _ -> do { mOut <- try_to_reduce tc xis kind_co (`mkTransCo` ret_co) ; case mOut of Just out -> pure out Nothing -> do { loc <- getLoc ; (ev, co, fsk) <- liftTcS $ newFlattenSkolem cur_flav loc tc xis -- The new constraint (F xis ~ fsk) is not -- necessarily inert (e.g. the LHS may be a -- redex) so we must put it in the work list ; let ct = CFunEqCan { cc_ev = ev , cc_fun = tc , cc_tyargs = xis , cc_fsk = fsk } ; emitFlatWork ct ; traceFlat "flatten/flat-cache miss" $ (ppr tc <+> ppr xis $$ ppr fsk $$ ppr ev) -- NB: fsk's kind is already flattened because -- the xis are flattened ; let fsk_ty = mkTyVarTy fsk xi = fsk_ty `mkCastTy` kind_co co' = mkTcCoherenceLeftCo role fsk_ty kind_co (maybeTcSubCo eq_rel (mkSymCo co)) `mkTransCo` ret_co ; return (xi, co') } } } } where -- try_to_reduce and try_to_reduce_nocache (below) could be unified into -- a more general definition, but it was observed that separating them -- gives better performance (lower allocation numbers in T9872x). try_to_reduce :: TyCon -- F, family tycon -> [Type] -- args, not necessarily flattened -> CoercionN -- kind_co :: tcTypeKind(F args) ~N -- tcTypeKind(F orig_args) -- where -- orig_args is what was passed to the outer -- function -> ( Coercion -- :: (xi |> kind_co) ~ F args -> Coercion ) -- what to return from outer function -> FlatM (Maybe (Xi, Coercion)) try_to_reduce tc tys kind_co update_co = do { checkStackDepth (mkTyConApp tc tys) ; mb_match <- liftTcS $ matchFam tc tys ; case mb_match of -- NB: norm_co will always be homogeneous. All type families -- are homogeneous. Just (norm_co, norm_ty) -> do { traceFlat "Eager T.F. reduction success" $ vcat [ ppr tc, ppr tys, ppr norm_ty , ppr norm_co <+> dcolon <+> ppr (coercionKind norm_co) ] ; (xi, final_co) <- bumpDepth $ flatten_one norm_ty ; eq_rel <- getEqRel ; let co = maybeTcSubCo eq_rel norm_co `mkTransCo` mkSymCo final_co ; flavour <- getFlavour -- NB: only extend cache with nominal equalities ; when (eq_rel == NomEq) $ liftTcS $ extendFlatCache tc tys ( co, xi, flavour ) ; let role = eqRelRole eq_rel xi' = xi `mkCastTy` kind_co co' = update_co $ mkTcCoherenceLeftCo role xi kind_co (mkSymCo co) ; return $ Just (xi', co') } Nothing -> pure Nothing } try_to_reduce_nocache :: TyCon -- F, family tycon -> [Type] -- args, not necessarily flattened -> FlatM (Maybe (Xi, Coercion)) try_to_reduce_nocache tc tys = do { checkStackDepth (mkTyConApp tc tys) ; mb_match <- liftTcS $ matchFam tc tys ; case mb_match of -- NB: norm_co will always be homogeneous. All type families -- are homogeneous. Just (norm_co, norm_ty) -> do { (xi, final_co) <- bumpDepth $ flatten_one norm_ty ; eq_rel <- getEqRel ; let co = mkSymCo (maybeTcSubCo eq_rel norm_co `mkTransCo` mkSymCo final_co) ; return $ Just (xi, co) } Nothing -> pure Nothing } {- Note [Reduce type family applications eagerly] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we come across a type-family application like (Append (Cons x Nil) t), then, rather than flattening to a skolem etc, we may as well just reduce it on the spot to (Cons x t). This saves a lot of intermediate steps. Examples that are helped are tests T9872, and T5321Fun. Performance testing indicates that it's best to try this *twice*, once before flattening arguments and once after flattening arguments. Adding the extra reduction attempt before flattening arguments cut the allocation amounts for the T9872{a,b,c} tests by half. An example of where the early reduction appears helpful: type family Last x where Last '[x] = x Last (h ': t) = Last t workitem: (x ~ Last '[1,2,3,4,5,6]) Flattening the argument never gets us anywhere, but trying to flatten it at every step is quadratic in the length of the list. Reducing more eagerly makes simplifying the right-hand type linear in its length. Testing also indicated that the early reduction should *not* use the flat-cache, but that the later reduction *should*. (Although the effect was not large.) Hence the Bool argument to try_to_reduce. To me (SLPJ) this seems odd; I get that eager reduction usually succeeds; and if don't use the cache for eager reduction, we will miss most of the opportunities for using it at all. More exploration would be good here. At the end, once we've got a flat rhs, we extend the flatten-cache to record the result. Doing so can save lots of work when the same redex shows up more than once. Note that we record the link from the redex all the way to its *final* value, not just the single step reduction. Interestingly, using the flat-cache for the first reduction resulted in an increase in allocations of about 3% for the four T9872x tests. However, using the flat-cache in the later reduction is a similar gain. I (Richard E) don't currently (Dec '14) have any knowledge as to *why* these facts are true. ************************************************************************ * * Flattening a type variable * * ********************************************************************* -} -- | The result of flattening a tyvar "one step". data FlattenTvResult = FTRNotFollowed -- ^ The inert set doesn't make the tyvar equal to anything else | FTRFollowed TcType Coercion -- ^ The tyvar flattens to a not-necessarily flat other type. -- co :: new type ~r old type, where the role is determined by -- the FlattenEnv flattenTyVar :: TyVar -> FlatM (Xi, Coercion) flattenTyVar tv = do { mb_yes <- flatten_tyvar1 tv ; case mb_yes of FTRFollowed ty1 co1 -- Recur -> do { (ty2, co2) <- flatten_one ty1 -- ; traceFlat "flattenTyVar2" (ppr tv $$ ppr ty2) ; return (ty2, co2 `mkTransCo` co1) } FTRNotFollowed -- Done, but make sure the kind is zonked -- Note [Flattening] invariant (F0) and (F1) -> do { tv' <- liftTcS $ updateTyVarKindM zonkTcType tv ; role <- getRole ; let ty' = mkTyVarTy tv' ; return (ty', mkTcReflCo role ty') } } flatten_tyvar1 :: TcTyVar -> FlatM FlattenTvResult -- "Flattening" a type variable means to apply the substitution to it -- Specifically, look up the tyvar in -- * the internal MetaTyVar box -- * the inerts -- See also the documentation for FlattenTvResult flatten_tyvar1 tv = do { mb_ty <- liftTcS $ isFilledMetaTyVar_maybe tv ; case mb_ty of Just ty -> do { traceFlat "Following filled tyvar" (ppr tv <+> equals <+> ppr ty) ; role <- getRole ; return (FTRFollowed ty (mkReflCo role ty)) } ; Nothing -> do { traceFlat "Unfilled tyvar" (pprTyVar tv) ; fr <- getFlavourRole ; flatten_tyvar2 tv fr } } flatten_tyvar2 :: TcTyVar -> CtFlavourRole -> FlatM FlattenTvResult -- The tyvar is not a filled-in meta-tyvar -- Try in the inert equalities -- See Definition [Applying a generalised substitution] in TcSMonad -- See Note [Stability of flattening] in TcSMonad flatten_tyvar2 tv fr@(_, eq_rel) = do { ieqs <- liftTcS $ getInertEqs ; mode <- getMode ; case lookupDVarEnv ieqs tv of Just (ct:_) -- If the first doesn't work, -- the subsequent ones won't either | CTyEqCan { cc_ev = ctev, cc_tyvar = tv , cc_rhs = rhs_ty, cc_eq_rel = ct_eq_rel } <- ct , let ct_fr = (ctEvFlavour ctev, ct_eq_rel) , ct_fr `eqCanRewriteFR` fr -- This is THE key call of eqCanRewriteFR -> do { traceFlat "Following inert tyvar" (ppr mode <+> ppr tv <+> equals <+> ppr rhs_ty $$ ppr ctev) ; let rewrite_co1 = mkSymCo (ctEvCoercion ctev) rewrite_co = case (ct_eq_rel, eq_rel) of (ReprEq, _rel) -> ASSERT( _rel == ReprEq ) -- if this ASSERT fails, then -- eqCanRewriteFR answered incorrectly rewrite_co1 (NomEq, NomEq) -> rewrite_co1 (NomEq, ReprEq) -> mkSubCo rewrite_co1 ; return (FTRFollowed rhs_ty rewrite_co) } -- NB: ct is Derived then fmode must be also, hence -- we are not going to touch the returned coercion -- so ctEvCoercion is fine. _other -> return FTRNotFollowed } {- Note [An alternative story for the inert substitution] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (This entire note is just background, left here in case we ever want to return the previous state of affairs) We used (GHC 7.8) to have this story for the inert substitution inert_eqs * 'a' is not in fvs(ty) * They are *inert* in the weaker sense that there is no infinite chain of (i1 `eqCanRewrite` i2), (i2 `eqCanRewrite` i3), etc This means that flattening must be recursive, but it does allow [G] a ~ [b] [G] b ~ Maybe c This avoids "saturating" the Givens, which can save a modest amount of work. It is easy to implement, in TcInteract.kick_out, by only kicking out an inert only if (a) the work item can rewrite the inert AND (b) the inert cannot rewrite the work item This is significantly harder to think about. It can save a LOT of work in occurs-check cases, but we don't care about them much. #5837 is an example; all the constraints here are Givens [G] a ~ TF (a,Int) --> work TF (a,Int) ~ fsk inert fsk ~ a ---> work fsk ~ (TF a, TF Int) inert fsk ~ a ---> work a ~ (TF a, TF Int) inert fsk ~ a ---> (attempting to flatten (TF a) so that it does not mention a work TF a ~ fsk2 inert a ~ (fsk2, TF Int) inert fsk ~ (fsk2, TF Int) ---> (substitute for a) work TF (fsk2, TF Int) ~ fsk2 inert a ~ (fsk2, TF Int) inert fsk ~ (fsk2, TF Int) ---> (top-level reduction, re-orient) work fsk2 ~ (TF fsk2, TF Int) inert a ~ (fsk2, TF Int) inert fsk ~ (fsk2, TF Int) ---> (attempt to flatten (TF fsk2) to get rid of fsk2 work TF fsk2 ~ fsk3 work fsk2 ~ (fsk3, TF Int) inert a ~ (fsk2, TF Int) inert fsk ~ (fsk2, TF Int) ---> work TF fsk2 ~ fsk3 inert fsk2 ~ (fsk3, TF Int) inert a ~ ((fsk3, TF Int), TF Int) inert fsk ~ ((fsk3, TF Int), TF Int) Because the incoming given rewrites all the inert givens, we get more and more duplication in the inert set. But this really only happens in pathological casee, so we don't care. ************************************************************************ * * Unflattening * * ************************************************************************ An unflattening example: [W] F a ~ alpha flattens to [W] F a ~ fmv (CFunEqCan) [W] fmv ~ alpha (CTyEqCan) We must solve both! -} unflattenWanteds :: Cts -> Cts -> TcS Cts unflattenWanteds tv_eqs funeqs = do { tclvl <- getTcLevel ; traceTcS "Unflattening" $ braces $ vcat [ text "Funeqs =" <+> pprCts funeqs , text "Tv eqs =" <+> pprCts tv_eqs ] -- Step 1: unflatten the CFunEqCans, except if that causes an occurs check -- Occurs check: consider [W] alpha ~ [F alpha] -- ==> (flatten) [W] F alpha ~ fmv, [W] alpha ~ [fmv] -- ==> (unify) [W] F [fmv] ~ fmv -- See Note [Unflatten using funeqs first] ; funeqs <- foldrM unflatten_funeq emptyCts funeqs ; traceTcS "Unflattening 1" $ braces (pprCts funeqs) -- Step 2: unify the tv_eqs, if possible ; tv_eqs <- foldrM (unflatten_eq tclvl) emptyCts tv_eqs ; traceTcS "Unflattening 2" $ braces (pprCts tv_eqs) -- Step 3: fill any remaining fmvs with fresh unification variables ; funeqs <- mapBagM finalise_funeq funeqs ; traceTcS "Unflattening 3" $ braces (pprCts funeqs) -- Step 4: remove any tv_eqs that look like ty ~ ty ; tv_eqs <- foldrM finalise_eq emptyCts tv_eqs ; let all_flat = tv_eqs `andCts` funeqs ; traceTcS "Unflattening done" $ braces (pprCts all_flat) ; return all_flat } where ---------------- unflatten_funeq :: Ct -> Cts -> TcS Cts unflatten_funeq ct@(CFunEqCan { cc_fun = tc, cc_tyargs = xis , cc_fsk = fmv, cc_ev = ev }) rest = do { -- fmv should be an un-filled flatten meta-tv; -- we now fix its final value by filling it, being careful -- to observe the occurs check. Zonking will eliminate it -- altogether in due course rhs' <- zonkTcType (mkTyConApp tc xis) ; case occCheckExpand [fmv] rhs' of Just rhs'' -- Normal case: fill the tyvar -> do { setReflEvidence ev NomEq rhs'' ; unflattenFmv fmv rhs'' ; return rest } Nothing -> -- Occurs check return (ct `consCts` rest) } unflatten_funeq other_ct _ = pprPanic "unflatten_funeq" (ppr other_ct) ---------------- finalise_funeq :: Ct -> TcS Ct finalise_funeq (CFunEqCan { cc_fsk = fmv, cc_ev = ev }) = do { demoteUnfilledFmv fmv ; return (mkNonCanonical ev) } finalise_funeq ct = pprPanic "finalise_funeq" (ppr ct) ---------------- unflatten_eq :: TcLevel -> Ct -> Cts -> TcS Cts unflatten_eq tclvl ct@(CTyEqCan { cc_ev = ev, cc_tyvar = tv , cc_rhs = rhs, cc_eq_rel = eq_rel }) rest | NomEq <- eq_rel -- See Note [Do not unify representational equalities] -- in TcInteract , isFmvTyVar tv -- Previously these fmvs were untouchable, -- but now they are touchable -- NB: unlike unflattenFmv, filling a fmv here /does/ -- bump the unification count; it is "improvement" -- Note [Unflattening can force the solver to iterate] = ASSERT2( tyVarKind tv `eqType` tcTypeKind rhs, ppr ct ) -- CTyEqCan invariant should ensure this is true do { is_filled <- isFilledMetaTyVar tv ; elim <- case is_filled of False -> do { traceTcS "unflatten_eq 2" (ppr ct) ; tryFill ev tv rhs } True -> do { traceTcS "unflatten_eq 3" (ppr ct) ; try_fill_rhs ev tclvl tv rhs } ; if elim then do { setReflEvidence ev eq_rel (mkTyVarTy tv) ; return rest } else return (ct `consCts` rest) } | otherwise = return (ct `consCts` rest) unflatten_eq _ ct _ = pprPanic "unflatten_irred" (ppr ct) ---------------- try_fill_rhs ev tclvl lhs_tv rhs -- Constraint is lhs_tv ~ rhs_tv, -- and lhs_tv is filled, so try RHS | Just (rhs_tv, co) <- getCastedTyVar_maybe rhs -- co :: kind(rhs_tv) ~ kind(lhs_tv) , isFmvTyVar rhs_tv || (isTouchableMetaTyVar tclvl rhs_tv && not (isTyVarTyVar rhs_tv)) -- LHS is a filled fmv, and so is a type -- family application, which a TyVarTv should -- not unify with = do { is_filled <- isFilledMetaTyVar rhs_tv ; if is_filled then return False else tryFill ev rhs_tv (mkTyVarTy lhs_tv `mkCastTy` mkSymCo co) } | otherwise = return False ---------------- finalise_eq :: Ct -> Cts -> TcS Cts finalise_eq (CTyEqCan { cc_ev = ev, cc_tyvar = tv , cc_rhs = rhs, cc_eq_rel = eq_rel }) rest | isFmvTyVar tv = do { ty1 <- zonkTcTyVar tv ; rhs' <- zonkTcType rhs ; if ty1 `tcEqType` rhs' then do { setReflEvidence ev eq_rel rhs' ; return rest } else return (mkNonCanonical ev `consCts` rest) } | otherwise = return (mkNonCanonical ev `consCts` rest) finalise_eq ct _ = pprPanic "finalise_irred" (ppr ct) tryFill :: CtEvidence -> TcTyVar -> TcType -> TcS Bool -- (tryFill tv rhs ev) assumes 'tv' is an /un-filled/ MetaTv -- If tv does not appear in 'rhs', it set tv := rhs, -- binds the evidence (which should be a CtWanted) to Refl<rhs> -- and return True. Otherwise returns False tryFill ev tv rhs = ASSERT2( not (isGiven ev), ppr ev ) do { rhs' <- zonkTcType rhs ; case () of _ | Just tv' <- tcGetTyVar_maybe rhs' , tv == tv' -- tv == rhs -> return True _ | Just rhs'' <- occCheckExpand [tv] rhs' -> do { -- Fill the tyvar unifyTyVar tv rhs'' ; return True } _ | otherwise -- Occurs check -> return False } setReflEvidence :: CtEvidence -> EqRel -> TcType -> TcS () setReflEvidence ev eq_rel rhs = setEvBindIfWanted ev (evCoercion refl_co) where refl_co = mkTcReflCo (eqRelRole eq_rel) rhs {- Note [Unflatten using funeqs first] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [W] G a ~ Int [W] F (G a) ~ G a do not want to end up with [W] F Int ~ Int because that might actually hold! Better to end up with the two above unsolved constraints. The flat form will be G a ~ fmv1 (CFunEqCan) F fmv1 ~ fmv2 (CFunEqCan) fmv1 ~ Int (CTyEqCan) fmv1 ~ fmv2 (CTyEqCan) Flatten using the fun-eqs first. -} -- | Like 'splitPiTys'' but comes with a 'Bool' which is 'True' iff there is at -- least one named binder. split_pi_tys' :: Type -> ([TyCoBinder], Type, Bool) split_pi_tys' ty = split ty ty where split orig_ty ty | Just ty' <- coreView ty = split orig_ty ty' split _ (ForAllTy b res) = let (bs, ty, _) = split res res in (Named b : bs, ty, True) split _ (FunTy { ft_af = af, ft_arg = arg, ft_res = res }) = let (bs, ty, named) = split res res in (Anon af arg : bs, ty, named) split orig_ty _ = ([], orig_ty, False) {-# INLINE split_pi_tys' #-} -- | Like 'tyConBindersTyCoBinders' but you also get a 'Bool' which is true iff -- there is at least one named binder. ty_con_binders_ty_binders' :: [TyConBinder] -> ([TyCoBinder], Bool) ty_con_binders_ty_binders' = foldr go ([], False) where go (Bndr tv (NamedTCB vis)) (bndrs, _) = (Named (Bndr tv vis) : bndrs, True) go (Bndr tv (AnonTCB af)) (bndrs, n) = (Anon af (tyVarKind tv) : bndrs, n) {-# INLINE go #-} {-# INLINE ty_con_binders_ty_binders' #-}
sdiehl/ghc
compiler/typecheck/TcFlatten.hs
bsd-3-clause
75,031
127
31
23,373
8,003
4,361
3,642
-1
-1
{-# LANGUAGE NoImplicitPrelude #-} module Protocol.ROC.PointTypes.PointType7 where import Data.ByteString (ByteString) import Data.Binary.Get (getByteString, getWord8, getWord16le, Get) import Data.Word (Word8,Word16) import Prelude (($), return, Bool, Eq, Float, Read, Show) import Protocol.ROC.Float (getIeeeFloat32) import Protocol.ROC.Utils (anyButNull,getTLP) data PointType7 = PointType7 { pointType7PointTag :: !PointType7PointTag ,pointType7Latitude :: !PointType7Latitude ,pointType7Elevation :: !PointType7Elevation ,pointType7CalcMethod :: !PointType7CalcMethod ,pointType7AGAConfig :: !PointType7AGAConfig ,pointType7SpecificGravity :: !PointType7SpecificGravity ,pointType7HeatingValue :: !PointType7HeatingValue ,pointType7GravityAcceleration :: !PointType7GravityAcceleration ,pointType7ScanPeriod :: !PointType7ScanPeriod ,pointType7PipeDiameter :: !PointType7PipeDiameter ,pointType7OrificeDiameter :: !PointType7OrificeDiameter ,pointType7OrificeTemp :: !PointType7OrificeTemp ,pointType7OrificeMaterial :: !PointType7OrificeMaterial ,pointType7MeterRunPntDesc :: !PointType7MeterRunPntDesc ,pointType7AlarmCode :: !PointType7AlarmCode ,pointType7LowAlarmFlow :: !PointType7LowAlarmFlow ,pointType7HighAlarmFlow :: !PointType7HighAlarmFlow ,pointType7Viscosity :: !PointType7Viscosity ,pointType7SpecificHeatRatio :: !PointType7SpecificHeatRatio ,pointType7ContactBasePress :: !PointType7ContactBasePress ,pointType7ContactBaseTemp :: !PointType7ContactBaseTemp ,pointType7LowDPCutoffMeterFactor :: !PointType7LowDPCutoffMeterFactor ,pointType7UserCorrectionFactor :: !PointType7UserCorrectionFactor ,pointType7Nitrogen :: !PointType7Nitrogen ,pointType7CarbonDioxide :: !PointType7CarbonDioxide ,pointType7HydrogenSulfide :: !PointType7HydrogenSulfide ,pointType7Water :: !PointType7Water ,pointType7Helium :: !PointType7Helium ,pointType7Methane :: !PointType7Methane ,pointType7Ethane :: !PointType7Ethane ,pointType7Propane :: !PointType7Propane ,pointType7nButane :: !PointType7nButane ,pointType7iButane :: !PointType7iButane ,pointType7nPentane :: !PointType7nPentane ,pointType7iPentane :: !PointType7iPentane ,pointType7nHexane :: !PointType7nHexane ,pointType7nHeptane :: !PointType7nHeptane ,pointType7nOctane :: !PointType7nOctane ,pointType7nNonane :: !PointType7nNonane ,pointType7nDecane :: !PointType7nDecane ,pointType7Oxygen :: !PointType7Oxygen ,pointType7CarbonMonoxide :: !PointType7CarbonMonoxide ,pointType7Hydrogen :: !PointType7Hydrogen ,pointType7CalcUnits :: !PointType7CalcUnits ,pointType7EnableStackDP :: !PointType7EnableStackDP ,pointType7LowDPInput :: !PointType7LowDPInput ,pointType7DPInputOrificeFRInput :: !PointType7DPInputOrificeFRInput ,pointType7StaticPressInput :: !PointType7StaticPressInput ,pointType7TempInput :: !PointType7TempInput ,pointType7LowDPStpnt :: !PointType7LowDPStpnt ,pointType7HighDPStpnt :: !PointType7HighDPStpnt ,pointType7MeterValueDP :: !PointType7MeterValueDP ,pointType7StaticFlowingPressValue :: !PointType7StaticFlowingPressValue ,pointType7FlowingTempValue :: !PointType7FlowingTempValue } deriving (Read,Eq, Show) type PointType7PointTag = ByteString type PointType7Latitude = Float type PointType7Elevation = Float type PointType7CalcMethod = Word8 type PointType7AGAConfig = Word8 type PointType7SpecificGravity = Float type PointType7HeatingValue = Float type PointType7GravityAcceleration = Float type PointType7ScanPeriod = Word16 type PointType7PipeDiameter = Float type PointType7OrificeDiameter = Float type PointType7OrificeTemp = Float type PointType7OrificeMaterial = Word8 type PointType7MeterRunPntDesc = ByteString type PointType7AlarmCode = Word8 type PointType7LowAlarmFlow = Float type PointType7HighAlarmFlow = Float type PointType7Viscosity = Float type PointType7SpecificHeatRatio = Float type PointType7ContactBasePress = Float type PointType7ContactBaseTemp = Float type PointType7LowDPCutoffMeterFactor = Float type PointType7UserCorrectionFactor = Float type PointType7Nitrogen = Float type PointType7CarbonDioxide = Float type PointType7HydrogenSulfide = Float type PointType7Water = Float type PointType7Helium = Float type PointType7Methane = Float type PointType7Ethane = Float type PointType7Propane = Float type PointType7nButane = Float type PointType7iButane = Float type PointType7nPentane = Float type PointType7iPentane = Float type PointType7nHexane = Float type PointType7nHeptane = Float type PointType7nOctane = Float type PointType7nNonane = Float type PointType7nDecane = Float type PointType7Oxygen = Float type PointType7CarbonMonoxide = Float type PointType7Hydrogen = Float type PointType7CalcUnits = Word8 type PointType7EnableStackDP = Bool type PointType7LowDPInput = [Word8] type PointType7DPInputOrificeFRInput = [Word8] type PointType7StaticPressInput = [Word8] type PointType7TempInput = [Word8] type PointType7LowDPStpnt = Float type PointType7HighDPStpnt = Float type PointType7MeterValueDP = Float type PointType7StaticFlowingPressValue = Float type PointType7FlowingTempValue = Float pointType7Parser :: Get PointType7 pointType7Parser = do pointId <- getByteString 10 latitude <- getIeeeFloat32 elevation <- getIeeeFloat32 calcMethod <- getWord8 agaCFG <- getWord8 specificGravity <- getIeeeFloat32 heatingValue <- getIeeeFloat32 gravityAccel <- getIeeeFloat32 scanPeriod <- getWord16le pipeDiam <- getIeeeFloat32 orificeDiam <- getIeeeFloat32 orificeMeasuredTemp <- getIeeeFloat32 orificeMat <- getWord8 mtrRunPntDesc <- getByteString 30 alarmCode <- getWord8 lowAlarm <- getIeeeFloat32 highAlarm <- getIeeeFloat32 viscosity <- getIeeeFloat32 specificHeatRatio <- getIeeeFloat32 contactBasePress <- getIeeeFloat32 contactBaseTemp <- getIeeeFloat32 lowDPCutoffMeterFactor <- getIeeeFloat32 userCorrectionFactor <- getIeeeFloat32 nitrogen <- getIeeeFloat32 carbonDioxide <- getIeeeFloat32 hydrogenSulfide <- getIeeeFloat32 water <- getIeeeFloat32 helium <- getIeeeFloat32 methane <- getIeeeFloat32 ethane <- getIeeeFloat32 propane <- getIeeeFloat32 nButane <- getIeeeFloat32 iButane <- getIeeeFloat32 nPentane <- getIeeeFloat32 iPentane <- getIeeeFloat32 nHexane <- getIeeeFloat32 nHeptane <- getIeeeFloat32 nOctane <- getIeeeFloat32 nNonane <- getIeeeFloat32 nDecane <- getIeeeFloat32 oxygen <- getIeeeFloat32 carbonMonoxide <- getIeeeFloat32 hydrogen <- getIeeeFloat32 calcUnits <- getWord8 enableStackedDP <- anyButNull lowDPInput <- getTLP dpInputFRInput <- getTLP staticPressInput <- getTLP tempPressInput <-getTLP lowDPStpnt <- getIeeeFloat32 highDPStpnt <- getIeeeFloat32 meterValueDPUncorrectedFR <- getIeeeFloat32 staticFlowingPressValue <- getIeeeFloat32 flowingTempValue <- getIeeeFloat32 return $ PointType7 pointId latitude elevation calcMethod agaCFG specificGravity heatingValue gravityAccel scanPeriod pipeDiam orificeDiam orificeMeasuredTemp orificeMat mtrRunPntDesc alarmCode lowAlarm highAlarm viscosity specificHeatRatio contactBasePress contactBaseTemp lowDPCutoffMeterFactor userCorrectionFactor nitrogen carbonDioxide hydrogenSulfide water helium methane ethane propane nButane iButane nPentane iPentane nHexane nHeptane nOctane nNonane nDecane oxygen carbonMonoxide hydrogen calcUnits enableStackedDP lowDPInput dpInputFRInput staticPressInput tempPressInput lowDPStpnt highDPStpnt meterValueDPUncorrectedFR staticFlowingPressValue flowingTempValue
plow-technologies/roc-translator
src/Protocol/ROC/PointTypes/PointType7.hs
bsd-3-clause
10,923
0
9
4,252
1,356
750
606
295
1
module TwoBufferQueue where import Control.Monad.State.Strict import Data.Maybe( isNothing ) import Interface( MsgSourceType(..) ) type MsgParams = () type MsgSource a = TBQ a data TBQ a = TBQ { _in :: Maybe a, _out :: Maybe a } deriving (Show, Eq) instance Functor TBQ where fmap f (TBQ i o) = TBQ (fmap f i) (fmap f o) sourceType :: MsgSourceType sourceType = TwoBufferQueue init :: TBQ a init = TBQ Nothing Nothing canGenerate :: MsgParams -> TBQ a -> Bool canGenerate () = isNothing . _in storeGenerate' :: a -> TBQ a -> TBQ a storeGenerate' i' (TBQ Nothing o) = TBQ (Just i') o storeGenerate' _ _ = error "Called storeGenerate' with non-empty IN cell" storeGenerate :: a -> State (TBQ a) () storeGenerate = modify . storeGenerate' getTransmit :: TBQ a -> Maybe a getTransmit = _out shiftTransmit' :: TBQ a -> TBQ a shiftTransmit' (TBQ i _o) = TBQ Nothing i shiftTransmit :: State (TBQ a) () shiftTransmit = modify shiftTransmit' tickDelays :: (a -> a) -> State (TBQ a) () tickDelays tick = modify $ fmap tick dropMsg :: State (TBQ a) () dropMsg = modify dropMsg' where dropMsg' (TBQ i _o) = TBQ i Nothing
ownclo/alohas
src/TwoBufferQueue.hs
bsd-3-clause
1,167
0
9
258
462
239
223
34
1
{-# LANGUAGE RankNTypes, OverloadedStrings #-} module Protocol.ROC.ROCConfig where import System.Hardware.Serialport import Data.Word import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LB import Protocol.ROC.PointTypes type StrictByteString = BS.ByteString type LazyByteString = LB.ByteString type BlockNumber = Word8 type RocAddress = [Word8] data RocConfig = RocConfig { rocConfigPort :: FilePath ,rocConfigRocAddress :: RocAddress ,rocConfigHostAddress :: RocAddress ,rocCommSpeed :: CommSpeed ,rocLogin :: String ,rocPassword :: Word16 } data FullyDefinedPointType cfg pn rt pt pc sp rp = FDPT { fdptROCType :: rt ,fdptPointTypeID :: pt ,fdptParameterCount :: pc ,fdptStartParameter :: sp ,fdptRxProtocol :: (cfg -> pn -> pt -> pc -> sp -> rp) } type ROCType = Word8 type PointTypeID a = PointTypes a type PointNumber = Word8 type ParameterCount = Word type StartParameter = Word8 type ParameterNumber = Word8 type DefaultPointType = FullyDefinedPointType RocConfig PointNumber ROCType (PointTypes ()) ParameterCount StartParameter (IO BS.ByteString)
plow-technologies/roc-translator
src/Protocol/ROC/ROCConfig.hs
bsd-3-clause
2,036
0
14
1,093
264
168
96
29
0
module MaybeHero.Utils ( reverseAndExpandTuple , lowerCaseWords , maybeToEither , headMaybe , firstValue ) where import qualified Data.Map as Map import qualified Data.Char as C import qualified Data.Maybe as Maybe import qualified Data.Either as Either expandSynonyms :: Ord b => [(a, [b])] -> [(b, a)] expandSynonyms xs = [(b, a) | (a, bs) <- xs, b <- bs] reverseAndExpandTuple :: Ord b => [(a, [b])] -> Map.Map b a reverseAndExpandTuple = Map.fromList . expandSynonyms toLower :: String -> String toLower str = map C.toLower str lowerCaseWords :: [String] -> [String] lowerCaseWords wrds = map toLower wrds maybeToEither :: a -> Maybe b -> Either a b maybeToEither left maybeRight = Maybe.maybe (Left left) Right maybeRight headMaybe :: [a] -> Maybe a headMaybe [] = Nothing headMaybe (x:xs) = Just x firstValue :: [Maybe a] -> Maybe a firstValue [] = Nothing firstValue (x:xs) = if Maybe.isJust x then x else firstValue xs
gtrogers/maybe-hero
src/MaybeHero/Utils.hs
bsd-3-clause
940
0
9
164
377
209
168
27
2
{-# OPTIONS_GHC -fno-warn-missing-signatures #-} module Main where import Wyas.Parser import Wyas.Evaluator import Wyas.Types import Wyas.Error import Test.Tasty import Test.Tasty.HUnit import Data.Ratio ((%)) import Data.Complex (Complex((:+))) import Data.Vector (fromList) testTypeParsing = testGroup "type parsing tests" [ testCase "parse decimal point number" $ (extractValue . readExpr) "3" @?= Number 3 , testCase "parse floating point number" $ (extractValue . readExpr) "42.0" @?= Float 42.0 , testCase "parse rational number" $ (extractValue . readExpr) "3/4" @?= (Ratio $ 3 % 4) , testCase "parse complex number (decimal)" $ (extractValue . readExpr) "3+1i" @?= (Complex $ 3.0 :+ 1.0) , testCase "parse complex number (floating)" $ (extractValue . readExpr) "3.0+1.0i" @?= (Complex $ 3.0 :+ 1.0) , testCase "parse number (binary prefix)" $ (extractValue . readExpr) "#b1000" @?= Number 8 , testCase "parse number (hex prefix)" $ (extractValue . readExpr) "#xFF" @?= Number 255 , testCase "parse number (oct prefix)" $ (extractValue . readExpr) "#o7" @?= Number 7 , testCase "parse char" $ (extractValue . readExpr) "#\\a" @?= Character 'a' , testCase "parse space char" $ (extractValue . readExpr) "#\\ " @?= Character ' ' , testCase "parse special newline char" $ (extractValue . readExpr) "#\\newline" @?= Character '\n' , testCase "parse special space char" $ (extractValue . readExpr) "#\\space" @?= Character ' ' , testCase "parse string" $ (extractValue . readExpr) "\"test 123\"" @?= String "test 123" , testCase "parse escaped quote in string" $ (extractValue . readExpr) "\"\\\"\"" @?= String "\"" , testCase "parse quote in string" $ (extractValue . readExpr) "\"test \\\"123\\\" test\"" @?= String "test \"123\" test" , testCase "parse backslash in string" $ (extractValue . readExpr) "\"te\\\\st\"" @?= String "te\\st" , testCase "parse newline in string" $ (extractValue . readExpr) "\"te\nst\"" @?= String "te\nst" , testCase "parse atom" $ (extractValue . readExpr) "test_func123" @?= Atom "test_func123" , testCase "parse bool (true)" $ (extractValue . readExpr) "#t" @?= Bool True , testCase "parse bool (false)" $ (extractValue . readExpr) "#f" @?= Bool False ] testListParsing = testGroup "list parsing tests" [ testCase "parse simple list" $ (extractValue . readExpr) "(a b)" @?= List [Atom "a", Atom "b"] , testCase "parse nested list" $ (extractValue . readExpr) "(a (b) c)" @?= List [Atom "a", List [Atom "b"], Atom "c"] , testCase "parse dotted list" $ (extractValue . readExpr) "(a (b . c) d)" @?= List [Atom "a", DottedList [(Atom "b")] (Atom "c"), Atom "d"] , testCase "parse quoted dotted" $ (extractValue . readExpr) "(a '(b (c . d)) e)" @?= List [Atom "a", List [Atom "quote", List [Atom "b", DottedList [(Atom "c")] (Atom "d")]], Atom "e"] , testCase "parse quasiquoted list" $ (extractValue . readExpr) "`(a (b c))" @?= List [Atom "quasiquote", List [Atom "a", List [Atom "b", Atom "c"]]] , testCase "parse quasiquoted list (unquote)" $ (extractValue . readExpr) "`(a ,(b c) d)" @?= List [Atom "quasiquote", List [Atom "a", List [Atom "unquote", List [Atom "b", Atom "c"]], Atom "d"]] , testCase "parse vector" $ (extractValue . readExpr) "#(1 a 3)" @?= Vector (fromList [Number 1, Atom "a", Number 3]) ] testEvaluation = testGroup "evaluation tests" [ testCase "simple addition" $ extractValue (readExpr "(+ 2 2)" >>= eval) @?= Number 4 , testCase "negative number" $ extractValue (readExpr "(+ 2 (-4 1))" >>= eval) @?= Number 2 , testCase "nested calls" $ extractValue (readExpr "(+ 2 (- 4 1))" >>= eval) @?= Number 5 , testCase "chained calls" $ extractValue (readExpr "(- (+ 4 6 3) 3 5 2)" >>= eval) @?= Number 3 , testCase "check symbol?" $ extractValue (readExpr "(symbol? test)" >>= eval) @?= Bool True , testCase "check number?" $ extractValue (readExpr "(number? 3)" >>= eval) @?= Bool True , testCase "check string?" $ extractValue (readExpr "(string? \"test\")" >>= eval) @?= Bool True , testCase "symbol to string" $ extractValue (readExpr "(symbol->string test)" >>= eval) @?= String "test" ] testBinop = testGroup "evaluate binops" [ testCase "less than (numbers)" $ extractValue (readExpr "(< 2 3)" >>= eval) @?= Bool True , testCase "greater than (numbers)" $ extractValue (readExpr "(> 2 3)" >>= eval) @?= Bool False , testCase "greater or equal than (numbers)" $ extractValue (readExpr "(>= 3 3)" >>= eval) @?= Bool True , testCase "string equality" $ extractValue (readExpr "(string=? \"test\" \"test\")" >>= eval) @?= Bool True , testCase "less than (strings)" $ extractValue (readExpr "(string<? \"abc\" \"bba\")" >>= eval) @?= Bool True , testCase "equal on lists" $ extractValue (readExpr "(equal? \'(1 \"2\") \'(1 2))" >>= eval) @?= Bool True ] tests :: TestTree tests = testGroup "Parser Tests" [ testTypeParsing , testListParsing , testEvaluation , testBinop ] main = defaultMain tests
grtlr/wyas
test/MainTestSuite.hs
bsd-3-clause
6,105
0
17
2,008
1,566
773
793
159
1
{-# OPTIONS_HADDOCK hide #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.Texturing.TexParameter -- Copyright : (c) Sven Panne 2002-2013 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- This is a purely internal module for getting\/setting texture parameters. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.Texturing.TexParameter ( TexParameter(..), texParami, texParamf, texParamC4f, getTexParameteri ) where import Foreign.Marshal.Alloc import Foreign.Marshal.Utils import Foreign.Ptr import Foreign.Storable import Graphics.Rendering.OpenGL.GL.PeekPoke import Graphics.Rendering.OpenGL.GL.StateVar import Graphics.Rendering.OpenGL.GL.Texturing.TextureTarget import Graphics.Rendering.OpenGL.GL.VertexSpec import Graphics.Rendering.OpenGL.Raw -------------------------------------------------------------------------------- data TexParameter = TextureMinFilter | TextureMagFilter | TextureWrapS | TextureWrapT | TextureWrapR | TextureBorderColor | TextureMinLOD | TextureMaxLOD | TextureBaseLevel | TextureMaxLevel | TexturePriority | TextureMaxAnisotropy | TextureCompare | TextureCompareOperator | TextureCompareFailValue | GenerateMipmap | TextureCompareMode | TextureCompareFunc | DepthTextureMode | TextureLODBias | TextureResident marshalTexParameter :: TexParameter -> GLenum marshalTexParameter x = case x of TextureMinFilter -> gl_TEXTURE_MIN_FILTER TextureMagFilter -> gl_TEXTURE_MAG_FILTER TextureWrapS -> gl_TEXTURE_WRAP_S TextureWrapT -> gl_TEXTURE_WRAP_T TextureWrapR -> gl_TEXTURE_WRAP_R TextureBorderColor -> gl_TEXTURE_BORDER_COLOR TextureMinLOD -> gl_TEXTURE_MIN_LOD TextureMaxLOD -> gl_TEXTURE_MAX_LOD TextureBaseLevel -> gl_TEXTURE_BASE_LEVEL TextureMaxLevel -> gl_TEXTURE_MAX_LEVEL TexturePriority -> gl_TEXTURE_PRIORITY TextureMaxAnisotropy -> gl_TEXTURE_MAX_ANISOTROPY_EXT TextureCompare -> gl_TEXTURE_COMPARE_SGIX TextureCompareOperator -> gl_TEXTURE_COMPARE_OPERATOR_SGIX TextureCompareFailValue -> gl_TEXTURE_COMPARE_FAIL_VALUE_ARB GenerateMipmap -> gl_GENERATE_MIPMAP TextureCompareMode -> gl_TEXTURE_COMPARE_MODE TextureCompareFunc -> gl_TEXTURE_COMPARE_FUNC DepthTextureMode -> gl_DEPTH_TEXTURE_MODE TextureLODBias -> gl_TEXTURE_LOD_BIAS TextureResident -> gl_TEXTURE_RESIDENT -------------------------------------------------------------------------------- texParameter :: ParameterizedTextureTarget t => (GLenum -> GLenum -> b -> IO ()) -> (a -> (b -> IO ()) -> IO ()) -> t -> TexParameter -> a -> IO () texParameter glTexParameter marshalAct t p x = marshalAct x $ glTexParameter (marshalParameterizedTextureTarget t) (marshalTexParameter p) -------------------------------------------------------------------------------- getTexParameter :: (Storable b, ParameterizedTextureTarget t) => (GLenum -> GLenum -> Ptr b -> IO ()) -> (b -> a) -> t -> TexParameter -> IO a getTexParameter glGetTexParameter unmarshal t p = alloca $ \buf -> do glGetTexParameter (marshalParameterizedTextureTarget t) (marshalTexParameter p) buf peek1 unmarshal buf -------------------------------------------------------------------------------- m2a :: (a -> b) -> a -> (b -> IO ()) -> IO () m2a marshal x act = act (marshal x) texParami :: ParameterizedTextureTarget t => (GLint -> a) -> (a -> GLint) -> TexParameter -> t -> StateVar a texParami unmarshal marshal p t = makeStateVar (getTexParameter glGetTexParameteriv unmarshal t p) (texParameter glTexParameteri (m2a marshal) t p) texParamf :: ParameterizedTextureTarget t => (GLfloat -> a) -> (a -> GLfloat) -> TexParameter -> t -> StateVar a texParamf unmarshal marshal p t = makeStateVar (getTexParameter glGetTexParameterfv unmarshal t p) (texParameter glTexParameterf (m2a marshal) t p) texParamC4f :: ParameterizedTextureTarget t => TexParameter -> t -> StateVar (Color4 GLfloat) texParamC4f p t = makeStateVar (getTexParameter glGetTexParameterC4f id t p) (texParameter glTexParameterC4f with t p) glTexParameterC4f :: GLenum -> GLenum -> Ptr (Color4 GLfloat) -> IO () glTexParameterC4f target pname ptr = glTexParameterfv target pname (castPtr ptr) glGetTexParameterC4f :: GLenum -> GLenum -> Ptr (Color4 GLfloat) -> IO () glGetTexParameterC4f target pname ptr = glGetTexParameterfv target pname (castPtr ptr) getTexParameteri :: ParameterizedTextureTarget t => (GLint -> a) -> t -> TexParameter -> IO a getTexParameteri = getTexParameter glGetTexParameteriv
hesiod/OpenGL
src/Graphics/Rendering/OpenGL/GL/Texturing/TexParameter.hs
bsd-3-clause
4,919
0
14
841
1,044
556
488
97
21
-- head {{{ {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Eval.Types where -- }}} -- import {{{ import qualified Data.Map as Map ------------- import Prelude(($), (.), (+), String, Bool(..), Int, Either(..), Integer, IO,) import Data.Maybe (maybe,) import Data.List (concatMap, (++), repeat, take,) import Text.Show (Show(..), ) import Control.Monad.Error -- }}} -- ErrorT {{{ data EvalError = EE String deriving Show instance Error EvalError where noMsg = EE "EE ?!" strMsg = EE type TError = Either EvalError type IOTError = ErrorT EvalError IO liftThrows :: TError a -> IOTError a liftThrows (Left err) = throwError err liftThrows (Right val) = return val -- }}} -- DataInfo {{{ type DataID = String type Location = String type DataSize = Integer data DataInfo = DataInfo DataID DataSize Location deriving Show -- }}} -- StrMap a {{{ type StrMap a = Map.Map String a type DataSet = StrMap DataInfo -- aka. "DS" -- }}} -- binding {{{ type Prim = Env -> IOTError DataSet type Pred = Env -> IOTError Bool data Binding = Expr Expr | Data DataSet | Prim Prim | Pred Pred instance Show Binding where show (Expr expr) = show expr show (Data ds) = show ds show (Prim _) = "Prim" show (Pred _) = "Pred" type BindingMap = StrMap Binding -- }}} -- PrimData* {{{ type PrimData1 = DataSet -> IOTError DataSet type PrimData2 = DataSet -> PrimData1 type PrimData3 = DataSet -> PrimData2 type PrimDataN = [DataSet] -> IOTError DataSet type PredData1 = DataSet -> IOTError Bool type PredData2 = DataSet -> PredData1 type PredData3 = DataSet -> PredData2 type PredDataN = [DataSet] -> IOTError Bool -- lookup DS {{{ lookupDS :: String -> Env -> TError DataSet lookupDS p env = envGet p env >>= xDS where xDS :: Binding -> TError DataSet xDS b = case b of Data ds -> return ds _ -> throwError noMsg lookupDSIO :: String -> Env -> IOTError DataSet lookupDSIO p env = liftThrows $ lookupDS p env -- }}} --primDS* {{{ primDS1 :: String -> PrimData1 -> Prim primDS1 p1 f = \env -> lookupDSIO p1 env >>= f primDS2 :: String -> String -> PrimData2 -> Prim primDS2 p1 p2 f = \env -> do ds1 <- lookupDSIO p1 env ds2 <- lookupDSIO p2 env f ds1 ds2 primDS3 :: String -> String -> String -> PrimData3 -> Prim primDS3 p1 p2 p3 f = \env -> do ds1 <- lookupDSIO p1 env ds2 <- lookupDSIO p2 env ds3 <- lookupDSIO p3 env f ds1 ds2 ds3 primDSN :: [String] -> PrimDataN -> Prim primDSN strList f = \env -> do dsList <- mapM (\p -> lookupDSIO p env) strList f dsList -- }}} --predDS* {{{ predDS1 :: String -> PredData1 -> Pred predDS1 p1 f = \env -> lookupDSIO p1 env >>= f predDS2 :: String -> String -> PredData2 -> Pred predDS2 p1 p2 f = \env -> do ds1 <- lookupDSIO p1 env ds2 <- lookupDSIO p2 env f ds1 ds2 predDS3 :: String -> String -> String -> PredData3 -> Pred predDS3 p1 p2 p3 f = \env -> do ds1 <- lookupDSIO p1 env ds2 <- lookupDSIO p2 env ds3 <- lookupDSIO p3 env f ds1 ds2 ds3 predDSN :: [String] -> PredDataN -> Pred predDSN strList f = \env -> do dsList <- mapM (\p -> lookupDSIO p env) strList f dsList -- }}} -- }}} -- Expr {{{ data Expr = Ref String -- reference to data | Lambda [String] Expr -- lambda a b | Begin [Expr] -- do a b c ... | Par [Expr] -- parallel-do a b c ... collects all result | Apply String [String] -- a = b (c,d,e ...) | If Expr Expr Expr -- if a then b else c | Let [(String, Expr)] Expr -- let (a = b, c = d, ...) in c -- Terminator. -- Ref -> Ref (name of data-set) -- Lambda -> Lambda (some Expr) -- Non-terminator. -- Begin -> return (result of last block) -- Par -> return collection of [Expr]'s result -- Apply -> return result -- If -> Expr-True or Expr-False -- Let -> add bindings to env, then return's the body -- show Expr {{{ showD :: Int -> String showD d = take d $ repeat ' ' showExpr :: Int -> Expr -> String showExpr _ (Ref str) = "`" ++ str showExpr d (Lambda _ expr) = "\\ * ->\n" ++ showD (d + 1) ++ (showExpr (d + 1) expr) showExpr d (Begin exprL) = "-->\n" ++ concatMap (\e -> showD (d + 1) ++ showExpr (d + 1) e ++ "\n") exprL showExpr d (Par exprL) = "|->\n" ++ concatMap (\e -> showD (d + 1) ++ showExpr (d + 1) e ++ "\n") exprL showExpr _ (Apply name params) = name ++ show params showExpr d (If pred y n) = "IF (" ++ show pred ++ ")\n" ++ showD (d + 1) ++ showExpr (d + 1) y ++ "\n" ++ showD (d + 1) ++ showExpr (d + 1) n ++ "\n" showExpr d (Let bindL body) = "Let\n" ++ concatMap (\(s,e) -> showD (d + 1) ++ show s ++ " <- " ++ showExpr (d + 1) e ++ "\n") bindL ++ showD d ++ "IN\n" ++ showD (d + 1) ++ showExpr (d + 1) body instance Show Expr where show = showExpr 2 -- }}} -- }}} -- Env {{{ type Env = BindingMap envGet :: String -> Env -> TError Binding envGet name bindmap = maybe (throwError noMsg) return $ Map.lookup name bindmap envGetIO :: String -> Env -> IOTError Binding envGetIO name env = liftThrows $ envGet name env envPut :: String -> Binding -> Env -> Env envPut name binding bmap = Map.insert name binding bmap -- }}} data Eval = Eval { evalEnv :: Env, evalExpr :: Expr } -- vim:fdm=marker
wuxb45/eval
Eval/Types.hs
bsd-3-clause
5,242
0
19
1,275
1,884
1,002
882
131
2
module PlayFair where import Data.Char import Data.List import Data.List.HT import Data.List.Split import qualified Data.Map as M type Key = M.Map (Int, Int) Char process :: String -> String process = replace "J" "I" . map toUpper . filter isLetter key :: String -> Key key = M.fromList . concat . zipWith (\y -> zipWith (\x c -> ((x, y), c)) [0..]) [0..] . chunk 5 . (`union` delete 'J' ['A'..'Z']) . nub . process bigram :: Key -> Int -> Char -> Char -> String bigram k dir c1 c2 | y1 == y2 = get (x1 + dir, y1) : [get (x2 + dir, y2)] | x1 == x2 = get (x1, y1 + dir) : [get (x2, y2 + dir)] | otherwise = get (x2, y1) : [get (x1, y2)] where (x1, y1) = head . M.keys $ M.filter (== c1) k (x2, y2) = head . M.keys $ M.filter (== c2) k get (x,y) = k M.! (mod x 5, mod y 5) encode' :: Key -> String -> String encode' _ [] = [] encode' k [x] = encode' k (x : "X") encode' k (x:y:xs) | x == y = encode' k [x] ++ encode' k (y:xs) | otherwise = bigram k 1 x y ++ encode' k xs decode' :: Key -> String -> String decode' k = concatMap (\[x,y] -> bigram k (-1) x y) . chunk 2 playFairEncode :: String -> String -> String encode k = encode' (key k) . process playFairDecode :: String -> String -> String decode k = decode' (key k) . process {- main :: IO () main = do print $ encode "PLAYFAIR" "PROGRAMMING PRAXIS" print $ decode "PLAYFAIR" "LIVOBLKZEDOELIYWCN" -}
abhinav-mehta/CipherSolver
src/PlayFair.hs
bsd-3-clause
1,471
0
17
402
715
379
336
32
1
module Network.API.Builder.Routes ( Route(..) , URLPiece , URLParam , (=.) , routeURL ) where import Control.Arrow ((***)) import Data.Monoid ((<>)) import Data.Text (Text) import qualified Data.Text as T import qualified Network.HTTP.Base as HTTP (urlEncodeVars) import qualified Network.HTTP.Types.Method as HTTP import Network.API.Builder.Query -- | Alias for @Text@ to store the URL fragments for each @Route@. type URLPiece = Text -- | Alias to @(Text, Maybe Text)@ used to store each query that gets -- tacked onto the request. type URLParam = [(Text, Text)] -- | Convenience function for building @URLParam@s. Right-hand argument must -- have a @ToQuery@ instance so it can be converted to the appropriate -- representation in a query string. Query values do not need to be -- escaped. -- -- >>> "api_type" =. ("json" :: Text) -- ("api_type", Just "json") (=.) :: ToQuery a => Text -> a -> [(Text, Text)] k =. v = toQuery k v -- | Main type for routes in the API. Used to represent the URL minus the actual -- endpoint URL as well as the query string and the HTTP method used to communicate -- with the server. data Route = Route { urlPieces :: [URLPiece] , urlParams :: [URLParam] , httpMethod :: HTTP.Method } deriving (Show, Read, Eq) -- | Converts a Route to a URL. Drops any @Nothing@ values from the query, separates the -- fragments with "/" and tacks them onto the end of the base URL. routeURL :: Text -- ^ base URL for the @Route@ (you can usually get this from the @Builder@) -> Route -- ^ the @Route@ to process -> Text -- ^ the finalized URL as a @Text@ routeURL baseURL (Route fs ps _) = baseURL <> firstSep <> path <> querySep <> buildParams ps where firstSep = if null fs then T.empty else "/" path = T.intercalate "/" fs querySep = if null ps then T.empty else "?" buildParams :: [URLParam] -> Text buildParams = T.pack . HTTP.urlEncodeVars . concatMap (map (T.unpack *** T.unpack))
eryx67/api-builder
src/Network/API/Builder/Routes.hs
bsd-3-clause
2,013
0
11
438
391
239
152
31
3
{-# LANGUAGE ScopedTypeVariables, PatternGuards #-} {-# OPTIONS -fno-warn-orphans #-} -- | A schedule of commands that should be run at a certain time. module HCron.Schedule -- * Time Periods ( second, minute, hour, day -- * When , When (..) , WhenModifier (..) -- * Events , EventName , Event (..) , earliestEventToStartAt , eventCouldStartAt -- * Schedules , Schedule (..) , makeSchedule , lookupEventOfSchedule , lookupCommandOfSchedule , adjustEventOfSchedule , eventsOfSchedule) where import Data.Time import Data.List import Data.Function import Data.Maybe import Control.Monad import Data.Map (Map) import qualified Data.Map as Map instance Read NominalDiffTime where readsPrec n str = let [(secs :: Double, rest)] = readsPrec n str in case rest of 's' : rest' -> [(fromRational $ toRational secs, rest')] _ -> [] second, minute, hour, day :: NominalDiffTime second = 1 minute = 60 hour = 60 * minute day = 24 * hour -- When ------------------------------------------------------------------------------------------- -- | When to invoke some event. data When -- | Just keep doing it. = Always -- | Don't do it, ever. | Never -- | Do it some time after we last started it. | Every NominalDiffTime -- | Do it some time after it last finished. | After NominalDiffTime -- | Do it each day at this time. The ''days'' are UTC days, not local ones. | Daily TimeOfDay deriving (Read, Show, Eq) -- | Modifier to when. data WhenModifier -- | If the event hasn't been invoked before then do it immediately -- when we start the cron process. = Immediate -- | Wait until after this time before doing it first. | WaitUntil UTCTime deriving (Read, Show, Eq) -- Event ------------------------------------------------------------------------------------------ type EventName = String -- | Records when an event should start, and when it last ran. data Event = Event { -- | A unique name for this event. -- Used when writing the schedule to a file. eventName :: EventName -- | When to run the command. , eventWhen :: When -- | Modifier to the previous. , eventWhenModifier :: Maybe WhenModifier -- | When the event was last started, if any. , eventLastStarted :: Maybe UTCTime -- | When the event last finished, if any. , eventLastEnded :: Maybe UTCTime } deriving (Read, Show, Eq) -- | Given the current time and a list of events, determine which one should be started now. -- If several events are avaliable then take the one with the earliest start time. earliestEventToStartAt :: UTCTime -> [Event] -> Maybe Event earliestEventToStartAt curTime events = let eventsStartable = filter (eventCouldStartAt curTime) events eventsSorted = sortBy (compare `on` eventLastStarted) eventsStartable in listToMaybe eventsSorted -- | Given the current time, decide whether an event could be started. -- If the `WhenModifier` is `Immediate` this always returns true. -- The `SkipFirst` modifier is ignored, as this is handled separately. eventCouldStartAt :: UTCTime -> Event -> Bool eventCouldStartAt curTime event -- If the event has never started or ended, and is marked as immediate, -- then start it right away. | Nothing <- eventLastStarted event , Nothing <- eventLastEnded event , Just Immediate <- eventWhenModifier event = True -- If the current end time is before the start time, then the most -- recent iteration is still running, so don't start it again. | Just lastStarted <- eventLastStarted event , Just lastEnded <- eventLastEnded event , lastEnded < lastStarted = False -- Keep waiting if there's a seconday wait modifier. | Just (WaitUntil waitTime) <- eventWhenModifier event , curTime < waitTime = False -- Otherwise we have to look at the real schedule. | otherwise = case eventWhen event of Always -> True Never -> False Every diffTime -> maybe True (\lastTime -> (curTime `diffUTCTime` lastTime ) > diffTime) (eventLastStarted event) After diffTime -> maybe True (\lastTime -> (curTime `diffUTCTime` lastTime ) > diffTime) (eventLastEnded event) Daily timeOfDay -- If it's been less than a day since we last started it, then don't do it yet. | Just lastStarted <- eventLastStarted event , (curTime `diffUTCTime` lastStarted) < day -> False | otherwise -> let -- If we were going to run it today, this is when it would be. startTimeToday = curTime { utctDayTime = timeOfDayToTime timeOfDay } -- If it's after that time then quit fooling around.. in curTime > startTimeToday -- Schedule --------------------------------------------------------------------------------------- -- | Map of event names to their details and build commands. data Schedule cmd = Schedule (Map EventName (Event, cmd)) -- | Get the list of events in a schedule, ignoring the build commands. eventsOfSchedule :: Schedule cmd -> [Event] eventsOfSchedule (Schedule sched) = map fst $ Map.elems sched -- | A nice way to produce a schedule. makeSchedule :: [(EventName, When, Maybe WhenModifier, cmd)] -> Schedule cmd makeSchedule tuples = let makeSched (name, whn, mMod, cmd) = (name, (Event name whn mMod Nothing Nothing, cmd)) in Schedule $ Map.fromList $ map makeSched tuples -- | Given an event name, lookup the associated event from a schedule. lookupEventOfSchedule :: EventName -> Schedule cmd -> Maybe Event lookupEventOfSchedule name (Schedule sched) = liftM fst $ Map.lookup name sched -- | Given an event name, lookup the associated build command from a schedule. lookupCommandOfSchedule :: EventName -> Schedule cmd -> Maybe cmd lookupCommandOfSchedule name (Schedule sched) = liftM snd $ Map.lookup name sched -- | Given a new version of an event, update any matching event in the schedule. -- If the event not already there then return the original schedule. adjustEventOfSchedule :: Event -> Schedule cmd -> Schedule cmd adjustEventOfSchedule event (Schedule sched) = Schedule $ Map.adjust (\(_, build) -> (event, build)) (eventName event) sched
tbk303/hcron
HCron/Schedule.hs
bsd-3-clause
6,084
78
16
1,179
1,240
679
561
116
5
{- - Hacq (c) 2013 NEC Laboratories America, Inc. All rights reserved. - - This file is part of Hacq. - Hacq is distributed under the 3-clause BSD license. - See the LICENSE file for more details. -} {-# LANGUAGE FlexibleContexts #-} module Control.Monad.Quantum.CircuitBuilder ( CircuitBuilder, runCircuitBuilder, evalCircuitBuilder, evalCircuitBuilder_, execCircuitBuilder, buildCircuit) where import Control.Monad.Quantum.Base.CircuitBuilder import Control.Monad.Quantum.Toffoli.ToStandard import Control.Monad.Quantum.Control import Data.Quantum.Circuit.Class (Wire, IsCircuit) import Data.Quantum.Circuit.Invert (CircuitInvert) import Data.Quantum.Circuit.MinimizeWireIndices type CircuitBuilder c = QuantumControlT Wire (ToffoliToStandardT Wire (CircuitBuilderBase c)) runCircuitBuilder :: CircuitBuilder c a -> [Wire] -> Integer -> (a, Integer, c) runCircuitBuilder m ctrls nextWireIndex = runCircuitBuilderBase (runToffoliToStandardT $ runQuantumControlT m ctrls) nextWireIndex evalCircuitBuilder :: IsCircuit g Wire c => CircuitBuilder c a -> [Wire] -> Integer -> (a, c) evalCircuitBuilder m ctrls nextWireIndex = evalCircuitBuilderBase (runToffoliToStandardT $ runQuantumControlT m ctrls) nextWireIndex evalCircuitBuilder_ :: IsCircuit g Wire c => CircuitBuilder c a -> [Wire] -> Integer -> c evalCircuitBuilder_ m ctrls nextWireIndex = evalCircuitBuilderBase_ (runToffoliToStandardT $ runQuantumControlT m ctrls) nextWireIndex execCircuitBuilder :: IsCircuit g Wire c => CircuitBuilder c a -> [Wire] -> Integer -> (Integer, c) execCircuitBuilder m ctrls nextWireIndex = execCircuitBuilderBase (runToffoliToStandardT $ runQuantumControlT m ctrls) nextWireIndex buildCircuit :: IsCircuit g Wire c => CircuitBuilder (CircuitInvert (MinimizeWireIndices c)) a -> c buildCircuit m = buildCircuitBase $ runToffoliToStandardT $ runQuantumControlT m []
ti1024/hacq
src/Control/Monad/Quantum/CircuitBuilder.hs
bsd-3-clause
1,899
0
11
256
443
241
202
26
1
-- Copyright : (C) 2009 Corey O'Connor -- License : BSD-style (see the file LICENSE) module Bind.Marshal.SerAction ( module Bind.Marshal.SerAction.Dynamic , module Bind.Marshal.SerAction.Static , module Bind.Marshal.SerAction.Storable ) where import Bind.Marshal.Prelude import Bind.Marshal.SerAction.Dynamic import Bind.Marshal.SerAction.Static import Bind.Marshal.SerAction.Storable
coreyoconnor/bind-marshal
src/Bind/Marshal/SerAction.hs
bsd-3-clause
492
0
5
143
62
45
17
7
0
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ExplicitForAll #-} module Main where import Control.Monad import Data.Typeable import Control.Concurrent (forkIO) import Reflex.Dom import Reflex.Dom.Class import Control.Monad.IO.Class import Data.Function import Interp (eat) main :: IO () main = mainWidget myWidget myWidget :: MonadWidget t m => m () myWidget = el "div" $ do txtIn :: TextInput t <- textInput def buttonEv :: Event t () <- button "Submit" let textEv :: Event t String = tagDyn (_textInput_value txtIn) buttonEv textDyn :: Dynamic t String <- holdDyn "enter something" textEv el "div" $ do el "h2" $ text "input:" dynText textDyn el "div" $ do el "h2" $ text "type sig:" tyEv :: Event t String <- asyncMapIO f textEv tyDyn :: Dynamic t String <- holdDyn "(type signature)" tyEv dynText tyDyn return () return () f :: String -> IO String f x = fmap g (eat $ x) where g (Left e) = show e g (Right str) = str -- utils infixl 1 <&> (<&>) :: (Functor f) => f a -> (a -> b) -> f b (<&>) = flip fmap -- From https://github.com/reflex-frp/reflex-dom/pull/11/files asyncMapIO :: (MonadWidget t m) => (a -> IO b) -> Event t a -> m (Event t b) asyncMapIO f event = performEventAsync eActions where eActions = fmap (forkApply f) event forkApply f val callback = liftIO . void . forkIO $ f val >>= callback say :: (MonadIO m) => String -> m () say = liftIO . putStrLn
sleexyz/typegrams
client/Main.hs
bsd-3-clause
1,622
0
13
468
575
281
294
43
2
-- -- HTTP client for use with io-streams -- -- Copyright © 2012-2013 Operational Dynamics Consulting, Pty Ltd -- -- The code in this file, and the program it is a part of, is made -- available to you by its authors as open source software: you can -- redistribute it and/or modify it under a BSD licence. -- {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS -fno-warn-unused-imports #-} module Snippet where import Blaze.ByteString.Builder (Builder) import qualified Blaze.ByteString.Builder as Builder import Control.Exception (bracket) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as S import System.IO.Streams (InputStream, OutputStream, stdout) import qualified System.IO.Streams as Streams -- Obviously don't need all those imports, but useful for experimenting import Network.Http.Client main :: IO () main = do c <- openConnection "kernel.operationaldynamics.com" 58080 q <- buildRequest $ do http GET "/time" setAccept "text/plain" sendRequest c q emptyBody receiveResponse c debugHandler closeConnection c
afcowie/pipes-http
tests/BasicSnippet.hs
bsd-3-clause
1,090
0
11
189
173
102
71
20
1
-- -- Chapter 10. -- module C'10 where import Test.QuickCheck import E'10'37 import E'10'36 import E'10'35 import E'10'34 import E'10'33 import E'10'32 import E'10'31 import E'10'30 import E'10'29 import E'10'28 import E'10'27 import E'10'26 import E'10'25 import E'10'24 import E'10'23 import E'10'22 import E'10'21 import E'10'20 import E'10'19 import E'10'18 import E'10'17 import E'10'16 import E'10'15 import E'10'14 import E'10'13 import E'10'12 import E'10'11 import E'10'10 import E'10''9 import E'10''8 import E'10''7 import E'10''6 import E'10''5 import E'10''4 import E'10''3 import E'10''2 import E'10''1
pascal-knodel/haskell-craft
_/links/C'10.hs
mit
623
0
4
90
123
83
40
39
0
{- emacs2nix - Generate Nix expressions for Emacs packages Copyright (C) 2016 Thomas Tuegel This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. -} {-# LANGUAGE OverloadedStrings #-} module Distribution.Nix.Builtin (optionalBuiltins) where import qualified Data.Set as S import Data.Text (Text) import Nix.Expr optionalBuiltins :: Text -> (Text, Maybe NExpr) optionalBuiltins dep | S.member dep builtin = (dep, Just (mkSym "null")) | otherwise = (dep, Nothing) where builtin = S.fromList [ "allout", "allout-widgets" , "ansi-color" , "antlr-mode" , "artist" , "bs" , "cedet" , "cfengine" , "chart" , "checkdoc" , "cl-lib" , "cwarn" , "delim-col" , "dunnet" , "ebnf2ps" , "ede" , "ediff" , "edmacro" , "eieio", "eieio-core" , "epg" , "erc" , "ert" , "eshell" , "feedmail" , "find-cmd" , "finder" , "flymake" , "foldout" , "footnote" , "gamegrid" , "gnus" , "hippie-exp" , "htmlfontify" , "icalendar" , "idlwave" , "image-dired" , "info-xref" , "inversion" , "isearchb" , "js", "json" , "linum" , "master" , "md4" , "meta-mode" , "mh-e" , "mixal-mode" , "newsticker" , "ntlm" , "package" , "printing" , "ps-mode" , "ps-print" , "pulse" , "python" , "regi" , "remember" , "repeat" , "ruby-mode" , "ruler-mode" , "savehist" , "semantic" , "sh-script" , "sql" , "srecode" , "tabulated-list" , "tetris" , "thingatpt" , "tildify" , "timeclock" , "url" , "vera-mode" , "viper" , "wdired" , "whitespace" , "woman" ]
mdorman/emacs2nix
src/Distribution/Nix/Builtin.hs
gpl-3.0
3,033
0
9
1,382
349
220
129
84
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.Support.Waiters -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.AWS.Support.Waiters where import Network.AWS.Prelude import Network.AWS.Support.Types import Network.AWS.Waiter
fmapfmapfmap/amazonka
amazonka-support/gen/Network/AWS/Support/Waiters.hs
mpl-2.0
624
0
4
122
39
31
8
7
0
{-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.DynamoDB -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Amazon DynamoDB -- -- __Overview__ -- -- This is the Amazon DynamoDB API Reference. This guide provides -- descriptions and samples of the low-level DynamoDB API. For information -- about DynamoDB application development, see the -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ Amazon DynamoDB Developer Guide>. -- -- Instead of making the requests to the low-level DynamoDB API directly -- from your application, we recommend that you use the AWS Software -- Development Kits (SDKs). The easy-to-use libraries in the AWS SDKs make -- it unnecessary to call the low-level DynamoDB API directly from your -- application. The libraries take care of request authentication, -- serialization, and connection management. For more information, see -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/UsingAWSSDK.html Using the AWS SDKs with DynamoDB> -- in the /Amazon DynamoDB Developer Guide/. -- -- If you decide to code against the low-level DynamoDB API directly, you -- will need to write the necessary code to authenticate your requests. For -- more information on signing your requests, see -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/API.html Using the DynamoDB API> -- in the /Amazon DynamoDB Developer Guide/. -- -- The following are short descriptions of each low-level API action, -- organized by function. -- -- __Managing Tables__ -- -- - /CreateTable/ - Creates a table with user-specified provisioned -- throughput settings. You must designate one attribute as the hash -- primary key for the table; you can optionally designate a second -- attribute as the range primary key. DynamoDB creates indexes on -- these key attributes for fast data access. Optionally, you can -- create one or more secondary indexes, which provide fast data access -- using non-key attributes. -- -- - /DescribeTable/ - Returns metadata for a table, such as table size, -- status, and index information. -- -- - /UpdateTable/ - Modifies the provisioned throughput settings for a -- table. Optionally, you can modify the provisioned throughput -- settings for global secondary indexes on the table. -- -- - /ListTables/ - Returns a list of all tables associated with the -- current AWS account and endpoint. -- -- - /DeleteTable/ - Deletes a table and all of its indexes. -- -- For conceptual information about managing tables, see -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.html Working with Tables> -- in the /Amazon DynamoDB Developer Guide/. -- -- __Reading Data__ -- -- - /GetItem/ - Returns a set of attributes for the item that has a -- given primary key. By default, /GetItem/ performs an eventually -- consistent read; however, applications can request a strongly -- consistent read instead. -- -- - /BatchGetItem/ - Performs multiple /GetItem/ requests for data items -- using their primary keys, from one table or multiple tables. The -- response from /BatchGetItem/ has a size limit of 16 MB and returns a -- maximum of 100 items. Both eventually consistent and strongly -- consistent reads can be used. -- -- - /Query/ - Returns one or more items from a table or a secondary -- index. You must provide a specific hash key value. You can narrow -- the scope of the query using comparison operators against a range -- key value, or on the index key. /Query/ supports either eventual or -- strong consistency. A single response has a size limit of 1 MB. -- -- - /Scan/ - Reads every item in a table; the result set is eventually -- consistent. You can limit the number of items returned by filtering -- the data attributes, using conditional expressions. /Scan/ can be -- used to enable ad-hoc querying of a table against non-key -- attributes; however, since this is a full table scan without using -- an index, /Scan/ should not be used for any application query use -- case that requires predictable performance. -- -- For conceptual information about reading data, see -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html Working with Items> -- and -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html Query and Scan Operations> -- in the /Amazon DynamoDB Developer Guide/. -- -- __Modifying Data__ -- -- - /PutItem/ - Creates a new item, or replaces an existing item with a -- new item (including all the attributes). By default, if an item in -- the table already exists with the same primary key, the new item -- completely replaces the existing item. You can use conditional -- operators to replace an item only if its attribute values match -- certain conditions, or to insert a new item only if that item -- doesn\'t already exist. -- -- - /UpdateItem/ - Modifies the attributes of an existing item. You can -- also use conditional operators to perform an update only if the -- item\'s attribute values match certain conditions. -- -- - /DeleteItem/ - Deletes an item in a table by primary key. You can -- use conditional operators to perform a delete an item only if the -- item\'s attribute values match certain conditions. -- -- - /BatchWriteItem/ - Performs multiple /PutItem/ and /DeleteItem/ -- requests across multiple tables in a single request. A failure of -- any request(s) in the batch will not cause the entire -- /BatchWriteItem/ operation to fail. Supports batches of up to 25 -- items to put or delete, with a maximum total request size of 16 MB. -- -- For conceptual information about modifying data, see -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html Working with Items> -- and -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html Query and Scan Operations> -- in the /Amazon DynamoDB Developer Guide/. -- -- /See:/ <http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/Welcome.html AWS API Reference> module Network.AWS.DynamoDB ( -- * Service Configuration dynamoDB -- * Errors -- $errors -- ** ProvisionedThroughputExceededException , _ProvisionedThroughputExceededException -- ** ConditionalCheckFailedException , _ConditionalCheckFailedException -- ** ItemCollectionSizeLimitExceededException , _ItemCollectionSizeLimitExceededException -- ** InternalServerError , _InternalServerError -- ** ResourceNotFoundException , _ResourceNotFoundException -- ** LimitExceededException , _LimitExceededException -- ** ResourceInUseException , _ResourceInUseException -- * Waiters -- $waiters -- ** TableNotExists , tableNotExists -- ** TableExists , tableExists -- * Operations -- $operations -- ** PutItem , module Network.AWS.DynamoDB.PutItem -- ** DeleteItem , module Network.AWS.DynamoDB.DeleteItem -- ** UpdateItem , module Network.AWS.DynamoDB.UpdateItem -- ** DeleteTable , module Network.AWS.DynamoDB.DeleteTable -- ** UpdateTable , module Network.AWS.DynamoDB.UpdateTable -- ** BatchGetItem , module Network.AWS.DynamoDB.BatchGetItem -- ** DescribeTable , module Network.AWS.DynamoDB.DescribeTable -- ** GetItem , module Network.AWS.DynamoDB.GetItem -- ** BatchWriteItem , module Network.AWS.DynamoDB.BatchWriteItem -- ** ListTables (Paginated) , module Network.AWS.DynamoDB.ListTables -- ** Scan (Paginated) , module Network.AWS.DynamoDB.Scan -- ** Query (Paginated) , module Network.AWS.DynamoDB.Query -- ** CreateTable , module Network.AWS.DynamoDB.CreateTable -- * Types -- ** AttributeAction , AttributeAction (..) -- ** ComparisonOperator , ComparisonOperator (..) -- ** ConditionalOperator , ConditionalOperator (..) -- ** IndexStatus , IndexStatus (..) -- ** KeyType , KeyType (..) -- ** ProjectionType , ProjectionType (..) -- ** ReturnConsumedCapacity , ReturnConsumedCapacity (..) -- ** ReturnItemCollectionMetrics , ReturnItemCollectionMetrics (..) -- ** ReturnValue , ReturnValue (..) -- ** ScalarAttributeType , ScalarAttributeType (..) -- ** Select , Select (..) -- ** StreamViewType , StreamViewType (..) -- ** TableStatus , TableStatus (..) -- ** AttributeDefinition , AttributeDefinition , attributeDefinition , adAttributeName , adAttributeType -- ** AttributeValue , AttributeValue , attributeValue , avL , avNS , avM , avNULL , avN , avBS , avB , avSS , avS , avBOOL -- ** AttributeValueUpdate , AttributeValueUpdate , attributeValueUpdate , avuValue , avuAction -- ** Capacity , Capacity , capacity , cCapacityUnits -- ** Condition , Condition , condition , cAttributeValueList , cComparisonOperator -- ** ConsumedCapacity , ConsumedCapacity , consumedCapacity , ccGlobalSecondaryIndexes , ccCapacityUnits , ccLocalSecondaryIndexes , ccTable , ccTableName -- ** CreateGlobalSecondaryIndexAction , CreateGlobalSecondaryIndexAction , createGlobalSecondaryIndexAction , cgsiaIndexName , cgsiaKeySchema , cgsiaProjection , cgsiaProvisionedThroughput -- ** DeleteGlobalSecondaryIndexAction , DeleteGlobalSecondaryIndexAction , deleteGlobalSecondaryIndexAction , dgsiaIndexName -- ** DeleteRequest , DeleteRequest , deleteRequest , drKey -- ** ExpectedAttributeValue , ExpectedAttributeValue , expectedAttributeValue , eavAttributeValueList , eavExists , eavValue , eavComparisonOperator -- ** GlobalSecondaryIndex , GlobalSecondaryIndex , globalSecondaryIndex , gsiIndexName , gsiKeySchema , gsiProjection , gsiProvisionedThroughput -- ** GlobalSecondaryIndexDescription , GlobalSecondaryIndexDescription , globalSecondaryIndexDescription , gsidBackfilling , gsidIndexSizeBytes , gsidIndexStatus , gsidProvisionedThroughput , gsidIndexARN , gsidKeySchema , gsidProjection , gsidItemCount , gsidIndexName -- ** GlobalSecondaryIndexUpdate , GlobalSecondaryIndexUpdate , globalSecondaryIndexUpdate , gsiuCreate , gsiuDelete , gsiuUpdate -- ** ItemCollectionMetrics , ItemCollectionMetrics , itemCollectionMetrics , icmItemCollectionKey , icmSizeEstimateRangeGB -- ** KeySchemaElement , KeySchemaElement , keySchemaElement , kseAttributeName , kseKeyType -- ** KeysAndAttributes , KeysAndAttributes , keysAndAttributes , kaaProjectionExpression , kaaAttributesToGet , kaaExpressionAttributeNames , kaaConsistentRead , kaaKeys -- ** LocalSecondaryIndex , LocalSecondaryIndex , localSecondaryIndex , lsiIndexName , lsiKeySchema , lsiProjection -- ** LocalSecondaryIndexDescription , LocalSecondaryIndexDescription , localSecondaryIndexDescription , lsidIndexSizeBytes , lsidIndexARN , lsidKeySchema , lsidProjection , lsidItemCount , lsidIndexName -- ** Projection , Projection , projection , pProjectionType , pNonKeyAttributes -- ** ProvisionedThroughput , ProvisionedThroughput , provisionedThroughput , ptReadCapacityUnits , ptWriteCapacityUnits -- ** ProvisionedThroughputDescription , ProvisionedThroughputDescription , provisionedThroughputDescription , ptdReadCapacityUnits , ptdLastDecreaseDateTime , ptdWriteCapacityUnits , ptdNumberOfDecreasesToday , ptdLastIncreaseDateTime -- ** PutRequest , PutRequest , putRequest , prItem -- ** StreamSpecification , StreamSpecification , streamSpecification , ssStreamViewType , ssStreamEnabled -- ** TableDescription , TableDescription , tableDescription , tdTableSizeBytes , tdAttributeDefinitions , tdLatestStreamARN , tdProvisionedThroughput , tdTableStatus , tdTableARN , tdKeySchema , tdGlobalSecondaryIndexes , tdLatestStreamLabel , tdLocalSecondaryIndexes , tdCreationDateTime , tdItemCount , tdTableName , tdStreamSpecification -- ** UpdateGlobalSecondaryIndexAction , UpdateGlobalSecondaryIndexAction , updateGlobalSecondaryIndexAction , ugsiaIndexName , ugsiaProvisionedThroughput -- ** WriteRequest , WriteRequest , writeRequest , wrDeleteRequest , wrPutRequest ) where import Network.AWS.DynamoDB.BatchGetItem import Network.AWS.DynamoDB.BatchWriteItem import Network.AWS.DynamoDB.CreateTable import Network.AWS.DynamoDB.DeleteItem import Network.AWS.DynamoDB.DeleteTable import Network.AWS.DynamoDB.DescribeTable import Network.AWS.DynamoDB.GetItem import Network.AWS.DynamoDB.ListTables import Network.AWS.DynamoDB.PutItem import Network.AWS.DynamoDB.Query import Network.AWS.DynamoDB.Scan import Network.AWS.DynamoDB.Types import Network.AWS.DynamoDB.UpdateItem import Network.AWS.DynamoDB.UpdateTable import Network.AWS.DynamoDB.Waiters {- $errors Error matchers are designed for use with the functions provided by <http://hackage.haskell.org/package/lens/docs/Control-Exception-Lens.html Control.Exception.Lens>. This allows catching (and rethrowing) service specific errors returned by 'DynamoDB'. -} {- $operations Some AWS operations return results that are incomplete and require subsequent requests in order to obtain the entire result set. The process of sending subsequent requests to continue where a previous request left off is called pagination. For example, the 'ListObjects' operation of Amazon S3 returns up to 1000 objects at a time, and you must send subsequent requests with the appropriate Marker in order to retrieve the next page of results. Operations that have an 'AWSPager' instance can transparently perform subsequent requests, correctly setting Markers and other request facets to iterate through the entire result set of a truncated API operation. Operations which support this have an additional note in the documentation. Many operations have the ability to filter results on the server side. See the individual operation parameters for details. -} {- $waiters Waiters poll by repeatedly sending a request until some remote success condition configured by the 'Wait' specification is fulfilled. The 'Wait' specification determines how many attempts should be made, in addition to delay and retry strategies. -}
fmapfmapfmap/amazonka
amazonka-dynamodb/gen/Network/AWS/DynamoDB.hs
mpl-2.0
15,383
0
5
3,234
983
740
243
203
0
module Data.TypedGraph.Subgraph (subgraphs, inducedSubgraphs) where import qualified Data.Graphs as G import qualified Data.Graphs.Morphism as GM import Data.TypedGraph import Data.TypedGraph.Morphism as TGM hiding (createEdgeOnDomain, createNodeOnDomain) -- | Generates all subgraphs of a typed graph. subgraphs :: TypedGraph a b -> [TypedGraph a b] subgraphs g = subEdges where emptyGraph = GM.empty G.empty (typeGraph g) listNodesToAdd = [(n, nt) | (Node n _, nt) <- nodes g] subNodes = decisionTreeNodes listNodesToAdd emptyGraph listEdgesToAdd = [ (e, srcId, tgtId, et) | (Edge e srcId tgtId _, et) <- edges g ] subEdges = concatMap (decisionTreeEdges listEdgesToAdd) subNodes -- | Considering /m : X -> Y/, -- generates all subgraphs of /Y/ containing the graph /X/ via m. inducedSubgraphs :: TypedGraphMorphism a b -> [TypedGraphMorphism a b] inducedSubgraphs m = map (makeInclusion (TGM.domainGraph m)) subEdges where g = TGM.codomainGraph m listNodesToAdd = [(n, extractNodeType g n) | n <- orphanTypedNodeIds m] subNodes = decisionTreeNodes listNodesToAdd (TGM.domainGraph m) listEdgesToAdd = [(edgeId e, sourceId e, targetId e, extractEdgeType g (edgeId e)) | e <- orphanTypedEdges m] subEdges = concatMap (decisionTreeEdges listEdgesToAdd) subNodes decisionTreeNodes :: [(NodeId,NodeId)] -> TypedGraph a b -> [TypedGraph a b] decisionTreeNodes [] g = [g] decisionTreeNodes ((n,tp):ns) g = decisionTreeNodes ns g ++ decisionTreeNodes ns added where added = GM.createNodeOnDomain n tp g decisionTreeEdges :: [(EdgeId,NodeId,NodeId,EdgeId)] -> TypedGraph a b -> [TypedGraph a b] decisionTreeEdges [] g = [g] decisionTreeEdges ((e,s,t,tp):es) g = decisionTreeEdges es g ++ if isNodeOf g s && isNodeOf g t then decisionTreeEdges es added else [] where added = GM.createEdgeOnDomain e s t tp g
Verites/verigraph
src/library/Data/TypedGraph/Subgraph.hs
apache-2.0
1,986
0
11
443
639
345
294
33
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PackageImports #-} module Main (main) where import Criterion.Main import Prelude () import Prelude.Compat import Data.Foldable (toList) import qualified "aeson" Data.Aeson as A import qualified "aeson-benchmarks" Data.Aeson as B import qualified Data.Sequence as S import qualified Data.Vector as V import qualified Data.Vector.Unboxed as U ------------------------------------------------------------------------------- -- List ------------------------------------------------------------------------------- newtype L f = L { getL :: f Int } instance Foldable f => B.ToJSON (L f) where toJSON = error "do not use this" toEncoding = B.toEncoding . toList . getL instance Foldable f => A.ToJSON (L f) where toJSON = error "do not use this" toEncoding = A.toEncoding . toList . getL ------------------------------------------------------------------------------- -- Foldable ------------------------------------------------------------------------------- newtype F f = F { getF :: f Int } instance Foldable f => B.ToJSON (F f) where toJSON = error "do not use this" toEncoding = B.foldable . getF instance Foldable f => A.ToJSON (F f) where toJSON = error "do not use this" toEncoding = A.foldable . getF ------------------------------------------------------------------------------- -- Values ------------------------------------------------------------------------------- valueList :: [Int] valueList = [1..1000] valueSeq :: S.Seq Int valueSeq = S.fromList valueList valueVector :: V.Vector Int valueVector = V.fromList valueList valueUVector :: U.Vector Int valueUVector = U.fromList valueList ------------------------------------------------------------------------------- -- Main ------------------------------------------------------------------------------- benchEncodeA :: A.ToJSON a => String -> a -> Benchmark benchEncodeA name val = bench ("A " ++ name) $ nf A.encode val benchEncodeB :: B.ToJSON a => String -> a -> Benchmark benchEncodeB name val = bench ("B " ++ name) $ nf B.encode val main :: IO () main = defaultMain [ bgroup "encode" [ bgroup "List" [ benchEncodeB "-" valueList , benchEncodeB "L" $ L valueList , benchEncodeB "F" $ F valueList , benchEncodeA "-" valueList , benchEncodeA "L" $ L valueList , benchEncodeA "F" $ F valueList ] , bgroup "Seq" [ benchEncodeB "-" valueSeq , benchEncodeB "L" $ L valueSeq , benchEncodeB "F" $ F valueSeq , benchEncodeA "-" valueSeq , benchEncodeA "L" $ L valueSeq , benchEncodeA "F" $ F valueSeq ] , bgroup "Vector" [ benchEncodeB "-" valueVector , benchEncodeB "L" $ L valueVector , benchEncodeB "F" $ F valueVector , benchEncodeA "-" valueVector , benchEncodeA "L" $ L valueVector , benchEncodeA "F" $ F valueVector ] , bgroup "Vector.Unboxed" [ benchEncodeB "-" valueUVector , benchEncodeA "-" valueUVector ] ] ]
tolysz/prepare-ghcjs
spec-lts8/aeson/benchmarks/AesonFoldable.hs
bsd-3-clause
3,288
0
12
841
764
405
359
75
1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Sandbox.Timestamp -- Maintainer : [email protected] -- Portability : portable -- -- Timestamp file handling (for add-source dependencies). ----------------------------------------------------------------------------- module Distribution.Client.Sandbox.Timestamp ( AddSourceTimestamp, withAddTimestamps, withUpdateTimestamps, maybeAddCompilerTimestampRecord, listModifiedDeps, removeTimestamps, -- * For testing TimestampFileRecord, readTimestampFile, writeTimestampFile ) where import Control.Monad (filterM, forM, when) import Data.Char (isSpace) import Data.List (partition) import System.Directory (renameFile) import System.FilePath ((<.>), (</>)) import qualified Data.Map as M import Distribution.Compiler (CompilerId) import Distribution.Simple.Utils (debug, die, warn) import Distribution.System (Platform) import Distribution.Text (display) import Distribution.Verbosity (Verbosity) import Distribution.Client.SrcDist (allPackageSourceFiles) import Distribution.Client.Sandbox.Index (ListIgnoredBuildTreeRefs (ListIgnored), RefTypesToList(OnlyLinks) ,listBuildTreeRefs) import Distribution.Compat.Exception (catchIO) import Distribution.Client.Compat.Time (ModTime, getCurTime, getModTime, posixSecondsToModTime) -- | Timestamp of an add-source dependency. type AddSourceTimestamp = (FilePath, ModTime) -- | Timestamp file record - a string identifying the compiler & platform plus a -- list of add-source timestamps. type TimestampFileRecord = (String, [AddSourceTimestamp]) timestampRecordKey :: CompilerId -> Platform -> String timestampRecordKey compId platform = display platform ++ "-" ++ display compId -- | The 'add-source-timestamps' file keeps the timestamps of all add-source -- dependencies. It is initially populated by 'sandbox add-source' and kept -- current by 'reinstallAddSourceDeps' and 'configure -w'. The user can install -- add-source deps manually with 'cabal install' after having edited them, so we -- can err on the side of caution sometimes. -- FIXME: We should keep this info in the index file, together with build tree -- refs. timestampFileName :: FilePath timestampFileName = "add-source-timestamps" -- | Read the timestamp file. Exits with error if the timestamp file is -- corrupted. Returns an empty list if the file doesn't exist. readTimestampFile :: FilePath -> IO [TimestampFileRecord] readTimestampFile timestampFile = do timestampString <- readFile timestampFile `catchIO` \_ -> return "[]" case reads timestampString of [(version, s)] | version == (2::Int) -> case reads s of [(timestamps, s')] | all isSpace s' -> return timestamps _ -> dieCorrupted | otherwise -> dieWrongFormat -- Old format (timestamps are POSIX seconds). Convert to new format. [] -> case reads timestampString of [(timestamps, s)] | all isSpace s -> do let timestamps' = map (\(i, ts) -> (i, map (\(p, t) -> (p, posixSecondsToModTime t)) ts)) timestamps writeTimestampFile timestampFile timestamps' return timestamps' _ -> dieCorrupted _ -> dieCorrupted where dieWrongFormat = die $ wrongFormat ++ deleteAndRecreate dieCorrupted = die $ corrupted ++ deleteAndRecreate wrongFormat = "The timestamps file is in the wrong format." corrupted = "The timestamps file is corrupted." deleteAndRecreate = " Please delete and recreate the sandbox." -- | Write the timestamp file, atomically. writeTimestampFile :: FilePath -> [TimestampFileRecord] -> IO () writeTimestampFile timestampFile timestamps = do writeFile timestampTmpFile "2\n" -- version appendFile timestampTmpFile (show timestamps ++ "\n") renameFile timestampTmpFile timestampFile where timestampTmpFile = timestampFile <.> "tmp" -- | Read, process and write the timestamp file in one go. withTimestampFile :: FilePath -> ([TimestampFileRecord] -> IO [TimestampFileRecord]) -> IO () withTimestampFile sandboxDir process = do let timestampFile = sandboxDir </> timestampFileName timestampRecords <- readTimestampFile timestampFile >>= process writeTimestampFile timestampFile timestampRecords -- | Given a list of 'AddSourceTimestamp's, a list of paths to add-source deps -- we've added and an initial timestamp, add an 'AddSourceTimestamp' to the list -- for each path. If a timestamp for a given path already exists in the list, -- update it. addTimestamps :: ModTime -> [AddSourceTimestamp] -> [FilePath] -> [AddSourceTimestamp] addTimestamps initial timestamps newPaths = [ (p, initial) | p <- newPaths ] ++ oldTimestamps where (oldTimestamps, _toBeUpdated) = partition (\(path, _) -> path `notElem` newPaths) timestamps -- | Given a list of 'AddSourceTimestamp's, a list of paths to add-source deps -- we've reinstalled and a new timestamp value, update the timestamp value for -- the deps in the list. If there are new paths in the list, ignore them. updateTimestamps :: [AddSourceTimestamp] -> [FilePath] -> ModTime -> [AddSourceTimestamp] updateTimestamps timestamps pathsToUpdate newTimestamp = foldr updateTimestamp [] timestamps where updateTimestamp t@(path, _oldTimestamp) rest | path `elem` pathsToUpdate = (path, newTimestamp) : rest | otherwise = t : rest -- | Given a list of 'TimestampFileRecord's and a list of paths to add-source -- deps we've removed, remove those deps from the list. removeTimestamps' :: [AddSourceTimestamp] -> [FilePath] -> [AddSourceTimestamp] removeTimestamps' l pathsToRemove = foldr removeTimestamp [] l where removeTimestamp t@(path, _oldTimestamp) rest = if path `elem` pathsToRemove then rest else t : rest -- | If a timestamp record for this compiler doesn't exist, add a new one. maybeAddCompilerTimestampRecord :: Verbosity -> FilePath -> FilePath -> CompilerId -> Platform -> IO () maybeAddCompilerTimestampRecord verbosity sandboxDir indexFile compId platform = do let key = timestampRecordKey compId platform withTimestampFile sandboxDir $ \timestampRecords -> do case lookup key timestampRecords of Just _ -> return timestampRecords Nothing -> do buildTreeRefs <- listBuildTreeRefs verbosity ListIgnored OnlyLinks indexFile now <- getCurTime let timestamps = map (\p -> (p, now)) buildTreeRefs return $ (key, timestamps):timestampRecords -- | Given an IO action that returns a list of build tree refs, add those -- build tree refs to the timestamps file (for all compilers). withAddTimestamps :: FilePath -> IO [FilePath] -> IO () withAddTimestamps sandboxDir act = do let initialTimestamp = minBound withActionOnAllTimestamps (addTimestamps initialTimestamp) sandboxDir act -- | Given a list of build tree refs, remove those -- build tree refs from the timestamps file (for all compilers). removeTimestamps :: FilePath -> [FilePath] -> IO () removeTimestamps idxFile = withActionOnAllTimestamps removeTimestamps' idxFile . return -- | Given an IO action that returns a list of build tree refs, update the -- timestamps of the returned build tree refs to the current time (only for the -- given compiler & platform). withUpdateTimestamps :: FilePath -> CompilerId -> Platform ->([AddSourceTimestamp] -> IO [FilePath]) -> IO () withUpdateTimestamps = withActionOnCompilerTimestamps updateTimestamps -- | Helper for implementing 'withAddTimestamps' and -- 'withRemoveTimestamps'. Runs a given action on the list of -- 'AddSourceTimestamp's for all compilers, applies 'f' to the result and then -- updates the timestamp file. The IO action is run only once. withActionOnAllTimestamps :: ([AddSourceTimestamp] -> [FilePath] -> [AddSourceTimestamp]) -> FilePath -> IO [FilePath] -> IO () withActionOnAllTimestamps f sandboxDir act = withTimestampFile sandboxDir $ \timestampRecords -> do paths <- act return [(key, f timestamps paths) | (key, timestamps) <- timestampRecords] -- | Helper for implementing 'withUpdateTimestamps'. Runs a given action on the -- list of 'AddSourceTimestamp's for this compiler, applies 'f' to the result -- and then updates the timestamp file record. The IO action is run only once. withActionOnCompilerTimestamps :: ([AddSourceTimestamp] -> [FilePath] -> ModTime -> [AddSourceTimestamp]) -> FilePath -> CompilerId -> Platform -> ([AddSourceTimestamp] -> IO [FilePath]) -> IO () withActionOnCompilerTimestamps f sandboxDir compId platform act = do let needle = timestampRecordKey compId platform withTimestampFile sandboxDir $ \timestampRecords -> do timestampRecords' <- forM timestampRecords $ \r@(key, timestamps) -> if key == needle then do paths <- act timestamps now <- getCurTime return (key, f timestamps paths now) else return r return timestampRecords' -- | Has this dependency been modified since we have last looked at it? isDepModified :: Verbosity -> ModTime -> AddSourceTimestamp -> IO Bool isDepModified verbosity now (packageDir, timestamp) = do debug verbosity ("Checking whether the dependency is modified: " ++ packageDir) depSources <- allPackageSourceFiles verbosity packageDir go depSources where go [] = return False go (dep0:rest) = do -- FIXME: What if the clock jumps backwards at any point? For now we only -- print a warning. let dep = packageDir </> dep0 modTime <- getModTime dep when (modTime > now) $ warn verbosity $ "File '" ++ dep ++ "' has a modification time that is in the future." if modTime >= timestamp then do debug verbosity ("Dependency has a modified source file: " ++ dep) return True else go rest -- | List all modified dependencies. listModifiedDeps :: Verbosity -> FilePath -> CompilerId -> Platform -> M.Map FilePath a -- ^ The set of all installed add-source deps. -> IO [FilePath] listModifiedDeps verbosity sandboxDir compId platform installedDepsMap = do timestampRecords <- readTimestampFile (sandboxDir </> timestampFileName) let needle = timestampRecordKey compId platform timestamps <- maybe noTimestampRecord return (lookup needle timestampRecords) now <- getCurTime fmap (map fst) . filterM (isDepModified verbosity now) . filter (\ts -> fst ts `M.member` installedDepsMap) $ timestamps where noTimestampRecord = die $ "Сouldn't find a timestamp record for the given " ++ "compiler/platform pair. " ++ "Please report this on the Cabal bug tracker: " ++ "https://github.com/haskell/cabal/issues/new ."
tolysz/prepare-ghcjs
spec-lts8/cabal/cabal-install/Distribution/Client/Sandbox/Timestamp.hs
bsd-3-clause
12,082
0
27
3,309
2,131
1,138
993
180
5
{-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Futhark.Representation.AST.Syntax.CoreTests ( tests ) where import Control.Applicative import Test.HUnit hiding (Test) import Test.Framework import Test.Framework.Providers.HUnit import Test.QuickCheck import Prelude import Language.Futhark.CoreTests () import Futhark.Representation.PrimitiveTests() import Futhark.Representation.AST.Syntax.Core import Futhark.Representation.AST.Pretty tests :: [Test] tests = subShapeTests subShapeTests :: [Test] subShapeTests = [ shape [free 1, free 2] `isSubShapeOf` shape [free 1, free 2] , shape [free 1, free 3] `isNotSubShapeOf` shape [free 1, free 2] , shape [free 1] `isNotSubShapeOf` shape [free 1, free 2] , shape [free 1, free 2] `isSubShapeOf` shape [free 1, Ext 3] , shape [Ext 1, Ext 2] `isNotSubShapeOf` shape [Ext 1, Ext 1] , shape [Ext 1, Ext 1] `isSubShapeOf` shape [Ext 1, Ext 2] ] where shape :: [ExtDimSize] -> ExtShape shape = ExtShape free :: Int -> ExtDimSize free = Free . Constant . IntValue . Int32Value . fromIntegral isSubShapeOf shape1 shape2 = subShapeTest shape1 shape2 True isNotSubShapeOf shape1 shape2 = subShapeTest shape1 shape2 False subShapeTest :: ExtShape -> ExtShape -> Bool -> Test subShapeTest shape1 shape2 expected = testCase ("subshapeOf " ++ pretty shape1 ++ " " ++ pretty shape2 ++ " == " ++ show expected) $ shape1 `subShapeOf` shape2 @?= expected instance Arbitrary NoUniqueness where arbitrary = pure NoUniqueness instance (Arbitrary shape, Arbitrary u) => Arbitrary (TypeBase shape u) where arbitrary = oneof [ Prim <$> arbitrary , Array <$> arbitrary <*> arbitrary <*> arbitrary ] instance Arbitrary Value where arbitrary = PrimVal <$> arbitrary instance Arbitrary Ident where arbitrary = Ident <$> arbitrary <*> arbitrary instance Arbitrary Rank where arbitrary = Rank <$> elements [1..9] instance Arbitrary Shape where arbitrary = Shape <$> map intconst <$> listOf1 (elements [1..9]) where intconst = Constant . IntValue . Int32Value
CulpaBS/wbBach
tests/Futhark/Representation/AST/Syntax/CoreTests.hs
bsd-3-clause
2,228
0
17
507
693
373
320
53
1
module C where name :: String name = "Samantha"
sdiehl/ghc
testsuite/tests/driver/T16511/C.hs
bsd-3-clause
49
0
4
10
14
9
5
3
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeSynonymInstances #-} module IHaskell.Display.Widgets.String.Text ( -- * The Text Widget TextWidget, -- * Constructor mkTextWidget) where -- To keep `cabal repl` happy when running from the ihaskell repo import Prelude import Control.Monad (when) import Data.Aeson import qualified Data.HashMap.Strict as Map import Data.IORef (newIORef) import Data.Vinyl (Rec(..), (<+>)) import IHaskell.Display import IHaskell.Eval.Widgets import IHaskell.IPython.Message.UUID as U import IHaskell.Display.Widgets.Types import IHaskell.Display.Widgets.Common -- | A 'TextWidget' represents a Text widget from IPython.html.widgets. type TextWidget = IPythonWidget TextType -- | Create a new Text widget mkTextWidget :: IO TextWidget mkTextWidget = do -- Default properties, with a random uuid uuid <- U.random let strWidget = defaultStringWidget "TextView" txtWidget = (SubmitHandler =:: return ()) :& (ChangeHandler =:: return ()) :& RNil widgetState = WidgetState $ strWidget <+> txtWidget stateIO <- newIORef widgetState let widget = IPythonWidget uuid stateIO -- Open a comm for this widget, and store it in the kernel state widgetSendOpen widget $ toJSON widgetState -- Return the widget return widget instance IHaskellDisplay TextWidget where display b = do widgetSendView b return $ Display [] instance IHaskellWidget TextWidget where getCommUUID = uuid -- Two possibilities: 1. content -> event -> "submit" 2. sync_data -> value -> <new_value> comm tw (Object dict1) _ = case Map.lookup "sync_data" dict1 of Just (Object dict2) -> case Map.lookup "value" dict2 of Just (String val) -> setField' tw StringValue val >> triggerChange tw Nothing -> return () Nothing -> case Map.lookup "content" dict1 of Just (Object dict2) -> case Map.lookup "event" dict2 of Just (String event) -> when (event == "submit") $ triggerSubmit tw Nothing -> return () Nothing -> return ()
artuuge/IHaskell
ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/String/Text.hs
mit
2,290
0
18
596
495
261
234
48
1
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-} {-# LANGUAGE FlexibleInstances, FlexibleContexts #-} -- #1781 -- This one should really succeed, because 'plus' can only -- be called with a = Int->Int, but the old fundep story -- certainly made it fail, and so that's what we expect for now -- We may become more liberal later module ShouldCompile where class E a b | a -> b, b -> a instance E a a plus :: (E a (Int -> Int)) => Int -> a plus x y = x + y
sdiehl/ghc
testsuite/tests/typecheck/should_compile/FD1.hs
bsd-3-clause
473
0
8
95
81
48
33
-1
-1
----------------------------------------------------------------------------- -- | -- Module : XMonad.Doc.Configuring -- Copyright : (C) 2007 Don Stewart and Andrea Rossato -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : unstable -- Portability : portable -- -- This is a brief tutorial that will teach you how to create a -- basic xmonad configuration. -- -- For more detailed instructions on extending xmonad with the -- xmonad-contrib library, see "XMonad.Doc.Extending". -- ----------------------------------------------------------------------------- module XMonad.Doc.Configuring ( -- * Configuring xmonad -- $configure -- * A simple example -- $example -- * Checking whether your xmonad.hs is correct -- $check -- * Loading your configuration -- $load ) where -------------------------------------------------------------------------------- -- -- Configuring Xmonad -- -------------------------------------------------------------------------------- {- $configure #Configuring_xmonad# xmonad can be configured by creating and editing the Haskell file: > ~/.xmonad/xmonad.hs If this file does not exist, xmonad will simply use default settings; if it does exist, xmonad will use whatever settings you specify. Note that this file can contain arbitrary Haskell code, which means that you have quite a lot of flexibility in configuring xmonad. HISTORICAL NOTE regarding upgrading from versions (< 0.5) of xmonad or using old documentation: xmonad-0.5 delivered a major change in the way xmonad is configured. Prior to version 0.5, configuring xmonad required editing a source file called Config.hs, manually recompiling xmonad, and then restarting. From version 0.5 onwards, however, you should NOT edit this file or manually compile with ghc --make. All you have to do is edit xmonad.hs and restart with @mod-q@; xmonad does the recompiling itself. The format of the configuration file also changed with version 0.5; enabling simpler and much shorter xmonad.hs files that only require listing those settings which are different from the defaults. While the complicated template.hs (man/xmonad.hs) files listing all default settings are still provided for reference, once you wish to make substantial changes to your configuration, the template.hs style configuration is not recommended. It is fine to use top-level definitions to organize your xmonad.hs, but wherever possible it is better to leave out settings that simply duplicate defaults. -} {- $example #A_simple_example# Here is a basic example, which starts with the default xmonad configuration and overrides the border width, default terminal, and some colours: > -- > -- An example, simple ~/.xmonad/xmonad.hs file. > -- It overrides a few basic settings, reusing all the other defaults. > -- > > import XMonad > > main = xmonad $ def > { borderWidth = 2 > , terminal = "urxvt" > , normalBorderColor = "#cccccc" > , focusedBorderColor = "#cd8b00" } This will run \'xmonad\', the window manager, with your settings passed as arguments. Overriding default settings like this (using \"record update syntax\"), will yield the shortest config file, as you only have to describe values that differ from the defaults. As an alternative, you can copy the template @xmonad.hs@ file (found either in the @man@ directory, if you have the xmonad source, or on the xmonad wiki config archive at <http://haskell.org/haskellwiki/Xmonad/Config_archive>) into your @~\/.xmonad\/@ directory. This template file contains all the default settings spelled out, and you should be able to simply change the ones you would like to change. To see what fields can be customized beyond the ones in the example above, the definition of the 'XMonad.Core.XConfig' data structure can be found in "XMonad.Core". -} {- $check #Checking_whether_your_xmonad.hs_is_correct# After changing your configuration, it is a good idea to check that it is syntactically and type correct. You can do this easily by using an xmonad flag: > $ xmonad --recompile > $ If there is no output, your xmonad.hs has no errors. If there are errors, they will be printed to the console. Patch them up and try again. Note, however, that if you skip this step and try restarting xmonad with errors in your xmonad.hs, it's not the end of the world; xmonad will simply display a window showing the errors and continue with the previous configuration settings. (This assumes that you have the \'xmessage\' utility installed; you probably do.) -} {- $load #Loading_your_configuration# To get xmonad to use your new settings, type @mod-q@. (Remember, the mod key is \'alt\' by default, but you can configure it to be something else, such as your Windows key if you have one.) xmonad will attempt to compile this file, and run it. If everything goes well, xmonad will seamlessly restart itself with the new settings, keeping all your windows, layouts, etc. intact. (If you change anything related to your layouts, you may need to hit @mod-shift-space@ after restarting to see the changes take effect.) If something goes wrong, the previous (default) settings will be used. Note this requires that GHC and xmonad are in the @$PATH@ in the environment from which xmonad is started. -}
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Doc/Configuring.hs
bsd-2-clause
5,387
0
3
963
44
41
3
2
0
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Traversable -- Copyright : Conor McBride and Ross Paterson 2005 -- License : BSD-style (see the LICENSE file in the distribution) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Class of data structures that can be traversed from left to right, -- performing an action on each element. -- -- See also -- -- * \"Applicative Programming with Effects\", -- by Conor McBride and Ross Paterson, -- /Journal of Functional Programming/ 18:1 (2008) 1-13, online at -- <http://www.soi.city.ac.uk/~ross/papers/Applicative.html>. -- -- * \"The Essence of the Iterator Pattern\", -- by Jeremy Gibbons and Bruno Oliveira, -- in /Mathematically-Structured Functional Programming/, 2006, online at -- <http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator>. -- -- * \"An Investigation of the Laws of Traversals\", -- by Mauro Jaskelioff and Ondrej Rypacek, -- in /Mathematically-Structured Functional Programming/, 2012, online at -- <http://arxiv.org/pdf/1202.2919>. -- ----------------------------------------------------------------------------- module Data.Traversable ( -- * The 'Traversable' class Traversable(..), -- * Utility functions for, forM, mapAccumL, mapAccumR, -- * General definitions for superclass methods fmapDefault, foldMapDefault, ) where import Control.Applicative ( Const(..) ) import Data.Either ( Either(..) ) import Data.Foldable ( Foldable ) import Data.Functor import Data.Proxy ( Proxy(..) ) import GHC.Arr import GHC.Base ( Applicative(..), Monad(..), Monoid, Maybe(..), ($), (.), id, flip ) import qualified GHC.Base as Monad ( mapM ) import qualified GHC.List as List ( foldr ) -- | Functors representing data structures that can be traversed from -- left to right. -- -- A definition of 'traverse' must satisfy the following laws: -- -- [/naturality/] -- @t . 'traverse' f = 'traverse' (t . f)@ -- for every applicative transformation @t@ -- -- [/identity/] -- @'traverse' Identity = Identity@ -- -- [/composition/] -- @'traverse' (Compose . 'fmap' g . f) = Compose . 'fmap' ('traverse' g) . 'traverse' f@ -- -- A definition of 'sequenceA' must satisfy the following laws: -- -- [/naturality/] -- @t . 'sequenceA' = 'sequenceA' . 'fmap' t@ -- for every applicative transformation @t@ -- -- [/identity/] -- @'sequenceA' . 'fmap' Identity = Identity@ -- -- [/composition/] -- @'sequenceA' . 'fmap' Compose = Compose . 'fmap' 'sequenceA' . 'sequenceA'@ -- -- where an /applicative transformation/ is a function -- -- @t :: (Applicative f, Applicative g) => f a -> g a@ -- -- preserving the 'Applicative' operations, i.e. -- -- * @t ('pure' x) = 'pure' x@ -- -- * @t (x '<*>' y) = t x '<*>' t y@ -- -- and the identity functor @Identity@ and composition of functors @Compose@ -- are defined as -- -- > newtype Identity a = Identity a -- > -- > instance Functor Identity where -- > fmap f (Identity x) = Identity (f x) -- > -- > instance Applicative Indentity where -- > pure x = Identity x -- > Identity f <*> Identity x = Identity (f x) -- > -- > newtype Compose f g a = Compose (f (g a)) -- > -- > instance (Functor f, Functor g) => Functor (Compose f g) where -- > fmap f (Compose x) = Compose (fmap (fmap f) x) -- > -- > instance (Applicative f, Applicative g) => Applicative (Compose f g) where -- > pure x = Compose (pure (pure x)) -- > Compose f <*> Compose x = Compose ((<*>) <$> f <*> x) -- -- (The naturality law is implied by parametricity.) -- -- Instances are similar to 'Functor', e.g. given a data type -- -- > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a) -- -- a suitable instance would be -- -- > instance Traversable Tree where -- > traverse f Empty = pure Empty -- > traverse f (Leaf x) = Leaf <$> f x -- > traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r -- -- This is suitable even for abstract types, as the laws for '<*>' -- imply a form of associativity. -- -- The superclass instances should satisfy the following: -- -- * In the 'Functor' instance, 'fmap' should be equivalent to traversal -- with the identity applicative functor ('fmapDefault'). -- -- * In the 'Foldable' instance, 'Data.Foldable.foldMap' should be -- equivalent to traversal with a constant applicative functor -- ('foldMapDefault'). -- class (Functor t, Foldable t) => Traversable t where {-# MINIMAL traverse | sequenceA #-} -- | Map each element of a structure to an action, evaluate these -- these actions from left to right, and collect the results. -- actions from left to right, and collect the results. For a -- version that ignores the results see 'Data.Foldable.traverse_'. traverse :: Applicative f => (a -> f b) -> t a -> f (t b) traverse f = sequenceA . fmap f -- | Evaluate each action in the structure from left to right, and -- and collect the results. For a version that ignores the results -- see 'Data.Foldable.sequenceA_'. sequenceA :: Applicative f => t (f a) -> f (t a) sequenceA = traverse id -- | Map each element of a structure to a monadic action, evaluate -- these actions from left to right, and collect the results. For -- a version that ignores the results see 'Data.Foldable.mapM_'. mapM :: Monad m => (a -> m b) -> t a -> m (t b) mapM = traverse -- | Evaluate each monadic action in the structure from left to -- right, and collect the results. For a version that ignores the -- results see 'Data.Foldable.sequence_'. sequence :: Monad m => t (m a) -> m (t a) sequence = sequenceA -- instances for Prelude types instance Traversable Maybe where traverse _ Nothing = pure Nothing traverse f (Just x) = Just <$> f x instance Traversable [] where {-# INLINE traverse #-} -- so that traverse can fuse traverse f = List.foldr cons_f (pure []) where cons_f x ys = (:) <$> f x <*> ys mapM = Monad.mapM instance Traversable (Either a) where traverse _ (Left x) = pure (Left x) traverse f (Right y) = Right <$> f y instance Traversable ((,) a) where traverse f (x, y) = (,) x <$> f y instance Ix i => Traversable (Array i) where traverse f arr = listArray (bounds arr) `fmap` traverse f (elems arr) instance Traversable Proxy where traverse _ _ = pure Proxy {-# INLINE traverse #-} sequenceA _ = pure Proxy {-# INLINE sequenceA #-} mapM _ _ = return Proxy {-# INLINE mapM #-} sequence _ = return Proxy {-# INLINE sequence #-} instance Traversable (Const m) where traverse _ (Const m) = pure $ Const m -- general functions -- | 'for' is 'traverse' with its arguments flipped. For a version -- that ignores the results see 'Data.Foldable.for_'. for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b) {-# INLINE for #-} for = flip traverse -- | 'forM' is 'mapM' with its arguments flipped. For a version that -- ignores the results see 'Data.Foldable.forM_'. forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) {-# INLINE forM #-} forM = flip mapM -- left-to-right state transformer newtype StateL s a = StateL { runStateL :: s -> (s, a) } instance Functor (StateL s) where fmap f (StateL k) = StateL $ \ s -> let (s', v) = k s in (s', f v) instance Applicative (StateL s) where pure x = StateL (\ s -> (s, x)) StateL kf <*> StateL kv = StateL $ \ s -> let (s', f) = kf s (s'', v) = kv s' in (s'', f v) -- |The 'mapAccumL' function behaves like a combination of 'fmap' -- and 'foldl'; it applies a function to each element of a structure, -- passing an accumulating parameter from left to right, and returning -- a final value of this accumulator together with the new structure. mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) mapAccumL f s t = runStateL (traverse (StateL . flip f) t) s -- right-to-left state transformer newtype StateR s a = StateR { runStateR :: s -> (s, a) } instance Functor (StateR s) where fmap f (StateR k) = StateR $ \ s -> let (s', v) = k s in (s', f v) instance Applicative (StateR s) where pure x = StateR (\ s -> (s, x)) StateR kf <*> StateR kv = StateR $ \ s -> let (s', v) = kv s (s'', f) = kf s' in (s'', f v) -- |The 'mapAccumR' function behaves like a combination of 'fmap' -- and 'foldr'; it applies a function to each element of a structure, -- passing an accumulating parameter from right to left, and returning -- a final value of this accumulator together with the new structure. mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) mapAccumR f s t = runStateR (traverse (StateR . flip f) t) s -- | This function may be used as a value for `fmap` in a `Functor` -- instance, provided that 'traverse' is defined. (Using -- `fmapDefault` with a `Traversable` instance defined only by -- 'sequenceA' will result in infinite recursion.) fmapDefault :: Traversable t => (a -> b) -> t a -> t b {-# INLINE fmapDefault #-} fmapDefault f = getId . traverse (Id . f) -- | This function may be used as a value for `Data.Foldable.foldMap` -- in a `Foldable` instance. foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m foldMapDefault f = getConst . traverse (Const . f) -- local instances newtype Id a = Id { getId :: a } instance Functor Id where fmap f (Id x) = Id (f x) instance Applicative Id where pure = Id Id f <*> Id x = Id (f x)
beni55/haste-compiler
libraries/ghc-7.10/base/Data/Traversable.hs
bsd-3-clause
9,748
0
12
2,170
1,811
1,025
786
95
1
-------------------------------------------------------------------------------- -- (c) Tsitsimpis Ilias, 2011-2012 -- -- A description of the platform we're compiling for -- Used by the native code generator -- -------------------------------------------------------------------------------- module Platform ( Platform(..), Arch(..), OS(..), defaultTmpDir ) where #include "config.h" -- | Contains enough information for the native code generator to emit -- code for this platform data Platform = Platform { platformArch :: Arch , platformOS :: OS } -- | Architectures that the native code generator knows about data Arch = ArchX86 | ArchX86_64 deriving (Show, Eq) -- | Operationg systems that the native code generator knows about -- Having OSUnknown should produce a sensible default, but no promises data OS = OSLinux | OSUnknown deriving (Show, Eq) -- | Default TEMPDIR depending on platform defaultTmpDir :: String defaultTmpDir | HOST_PLATFORM == "i386-unknown-cygwin32" = "/C/TEMP" | HOST_PLATFORM == "i386-unknown-mingw32" = "/C/TEMP" | otherwise = "/tmp"
iliastsi/gac
src/codeGen/Platform.hs
mit
1,173
0
8
251
149
92
57
22
1
module Modules.CapsQuotes (initializeCapsQuotes) where import Text.Parsers.IRC import Network.IRC.SevenInch import Network.Socket import Network.BSD import Text.Regex.Posix import System.IO import Control.Concurrent.STM import Control.Concurrent.STM.TChan (TChan) import System.Random --PubMsg Command IrcUser Channel String isCapsQuotes :: IrcMsg -> Bool isCapsQuotes (PubMsg PRIVMSG _ _ msg) = msg =~ "^[^a-z]*[A-Z]+[^a-z]*$" :: Bool isCapsQuotes _ = False capsQuotesHandler :: TVar [String] -> TChan String -> IrcMsg -> SocketHandler -> IO () capsQuotesHandler quoteRef chan (PubMsg _ (IrcUser nick _ _) c msg) cb = if nick == "lrts" then cb else do quotes <- atomically $ readTVar quoteRef index <- getStdRandom $ randomR (0, (length quotes) - 1) let response = quotes !! index atomically $ writeTVar quoteRef $ quotes ++ [msg] atomically $ sendCmd chan PRIVMSG [channelToString c, response] cb newQuotes :: IO (TVar [String]) newQuotes = newTVarIO ["ANGRY FISH"] initializeCapsQuotes :: IO (MsgHandler) initializeCapsQuotes = do quotes <- newQuotes return (isCapsQuotes, capsQuotesHandler quotes)
bigs/7inch
src/Modules/CapsQuotes.hs
mit
1,140
0
14
185
365
192
173
29
2
{-# LANGUAGE GADTs #-} module Dama.Parser.AST ( Program , Decl(PDecl, FDecl) , ExprR(ExprRVar, ExprRC) , ExprRC(ExprRCons, AppR, ChainR) , Expr(ExprIdent, App, Chain, LeftSection, RightSection) , Ident(Ident) , AltList((:+), (:+:)) ) where import Dama.Location type Program = [Decl] data Decl = PDecl ExprR Expr | FDecl Ident [ExprR] Expr deriving Show data ExprR = ExprRVar Ident | ExprRC ExprRC deriving Show data ExprRC = ExprRCons Ident | AppR ExprRC ExprR | ChainR (AltList ExprR Ident ExprR) deriving Show data Expr = ExprIdent Ident | App Expr Expr | Chain (AltList Expr Ident Expr) | LeftSection (AltList Expr Ident Ident) | RightSection (AltList Ident Expr Expr) deriving Show data Ident = Ident Location String deriving Show data AltList a b c where (:+:) :: (b ~ c) => a -> b -> AltList a b c (:+) :: a -> AltList b a c -> AltList a b c infixr 5 :+ infixr 5 :+: instance (Show a, Show b, Show c) => Show (AltList a b c) where showsPrec n (x :+: y) = showParen (n > 5) $ showsPrec 6 x . (" :+: " ++) . showsPrec 6 y showsPrec n (x :+ xs) = showParen (n > 5) $ showsPrec 6 x . (" :+ " ++) . showsPrec 5 xs
tysonzero/dama
src/Dama/Parser/AST.hs
mit
1,241
0
11
339
468
276
192
54
0
module Parse (parseFile) where import Control.Monad (liftM) import Text.Parsec import Text.Parsec.String import Types source :: Parser Src source = (string "in" >> return SrcIn) <|> (string "null" >> return SrcNull) <|> (string "a" >> return SrcA) <|> liftM SrcInt vmint <|> liftM SrcCPU cpunum dest :: Parser Dest dest = (string "out" >> return DestOut) <|> (string "a" >> return DestA) <|> (string "null" >> return DestNull) <|> liftM DestCPU cpunum nat :: Parser Int nat = read <$> many1 digit cpunum :: Parser CPUNum cpunum = char '#' >> nat <?> "cpu number" vmint :: Parser VMInt vmint = do symbol <- oneOf "+-" n <- nat return $ (if symbol == '+' then 1 else -1) * n instruction :: Parser Instruction instruction = (string "mov" >> skipMany1 space >> (MOV <$> (source <* skipMany space) <*> (char ',' >> skipMany space *> dest))) <|> try (string "swp" >> return SWP) <|> try (string "sav" >> return SAV) <|> try (string "add" >> skipMany1 space >> (ADD <$> source)) <|> try (string "sub" >> skipMany1 space >> (SUB <$> source)) <|> try (string "jmp" >> skipMany1 space >> (JMP <$> vmint)) <|> try (string "jez" >> skipMany1 space >> (JEZ <$> vmint)) <|> try (string "jnz" >> skipMany1 space >> (JNZ <$> vmint)) <|> try (string "jgz" >> skipMany1 space >> (JGZ <$> vmint)) <|> try (string "jlz" >> skipMany1 space >> (JLZ <$> vmint)) <?> "instruction" lineWithOptionalComment :: Parser a -> Parser a lineWithOptionalComment p = p <* skipMany space <* optional comment <* endOfLine where comment = char '~' >> skipMany (noneOf "\r\n") program :: Parser Program program = Program <$> lineWithOptionalComment cpunum <*> many (lineWithOptionalComment instruction) parseFile :: String -> IO (Either ParseError [Program]) parseFile = parseFromFile (many1 program <* eof)
purcell/vm5294
src/Parse.hs
mit
2,050
0
22
576
749
368
381
45
2
-- ------------------------------------------------------------------------------------- -- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved. -- For email, run on linux (perl v5.8.5): -- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"' -- ------------------------------------------------------------------------------------- import Data.List import Data.Ord solveProblem :: [(Int, Int)] -> [Int] solveProblem = map fst . sortBy (comparing snd) . zip [1..] . reverse . foldl' (\acc (t, d) -> (t+d):acc) [] main :: IO () main = do ip <- getContents let tds = map ((\[t, d] -> (t, d)) . map read . words). tail . lines $ ip let ans = solveProblem tds putStrLn $ unwords . map show $ ans
cbrghostrider/Hacking
HackerRank/Algorithms/Greedy/jimAndTheOrders.hs
mit
785
0
19
147
220
117
103
10
1
{-# LANGUAGE QuasiQuotes, TypeFamilies #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} module Yesod.Auth.Token ( -- * Plugin authToken , YesodAuthToken (..) , TokenCreds (..) -- * Routes , loginR -- * Types , Token -- * Others , tokenCreds ) where import Network.Mail.Mime (randomString) import Yesod.Auth import System.Random import qualified Data.Text as TS import Data.Text (Text) import Yesod.Core import qualified Yesod.Auth.Message as Msg import Yesod.Form loginR :: AuthRoute loginR = PluginR "token" ["token_login"] type Token = Text -- | Data used to identify the user data TokenCreds site = TokenCreds { tokenCredsAuthId :: AuthId site , tokenCredsContent :: Token } class ( YesodAuth site , PathPiece (AuthTokenId site) , (RenderMessage site Msg.AuthMessage) ) => YesodAuthToken site where type AuthTokenId site -- | TODO setUserToken :: AuthTokenId site -> Token -> HandlerT site IO () -- | TODO getTokenCreds :: Token -> HandlerT site IO (Maybe (TokenCreds site)) -- | Generate a random alphanumeric token. randomToken :: site -> IO Token randomToken _ = newStdGen >>= return . TS.pack . fst . randomString len where len = 32 authToken :: YesodAuthToken m => AuthPlugin m authToken = AuthPlugin "token" dispatch $ \tm -> [whamlet| $newline never <form method=post action=@{tm loginR}> <table> <tr> <th> Token <td> <input type=text name=token> <tr> <td colspan=2> <button type=submit .btn .btn-success> _{Msg.LoginTitle} |] where dispatch "POST" ["token_login"] = postLoginR >>= sendResponse dispatch _ _ = notFound postLoginR :: YesodAuthToken master => HandlerT Auth (HandlerT master IO) TypedContent postLoginR = do token <- lift . runInputPost $ ireq textField "token" mCreds <- lift $ getTokenCreds token case mCreds of Just (TokenCreds _uid _token) -> lift $ setCredsRedirect $ tokenCreds token Nothing -> loginErrorMessageI LoginR Msg.InvalidLogin tokenCreds :: YesodAuth master => Text -> Creds master tokenCreds token = Creds "token" token []
axel-angel/yesod-auth-token
src/Yesod/Auth/Token.hs
mit
2,324
0
12
630
517
283
234
52
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} module Nauva.NJS ( FID(..), unFID , createF , F(..) , FE , FRA, FRD , Value(..) ) where import Data.Function import qualified Data.Aeson as A import qualified Data.Aeson.Types as A import Data.Text (Text) import qualified Data.Text as T import Data.ByteString.Lazy (toStrict) import Crypto.MAC.SipHash (SipHash(..), SipKey(..)) import qualified Crypto.MAC.SipHash as SH -------------------------------------------------------------------------------- -- | 'NJS' is a JavaScript function which is run in the browser. The function -- can take a number of arguments (depending on in which context it runs), and -- may construct values which are piped back into the Haskell code. -- -- 'NJS' functions are untyped, meaning that Haskell allows you to construct -- arbitrary functions which won't typecheck. For that reason you shouldn't -- deal with 'NJS' directly and instaed use the supplied smart consturctors for -- the newtype wrappers which are defined further below. data F = F { fId :: !FID , fConstructors :: ![Text] -- ^ Action constructors which are used by the function body. , fArguments :: ![Text] -- ^ Arguments which the function body requires. , fBody :: !Text -- ^ JavaScript code of the function body. This string is passed to -- @new Function(…)@. } instance Eq F where (==) = (==) `on` fId instance A.ToJSON F where toJSON f = A.object [ "id" A..= fId f , "constructors" A..= fConstructors f , "arguments" A..= fArguments f , "body" A..= fBody f ] createF :: [Text] -> [Text] -> Text -> F createF constructors arguments body = F { fId = hash $ A.toJSON [A.toJSON constructors, A.toJSON arguments, A.toJSON body] , fConstructors = constructors , fArguments = arguments , fBody = body } where hash = FID . T.pack . show . unSipHash . SH.hash sipKey . toStrict . A.encode sipKey = SipKey 0 1 unSipHash (SipHash x) = x -------------------------------------------------------------------------------- -- | FID - Function ID -- -- The 'FID' is used to uniquely identify NJS function expressions. The -- constructor is private, only a smart constructor ('mkFID') is exported. -- 'mkFID' ensures that the 'FID' is globally unique. newtype FID = FID Text deriving (Eq) instance A.ToJSON FID where toJSON = A.toJSON . unFID -- Q: Why is this exported? A: So we can implement the ToJSVal instance. unFID :: FID -> Text unFID (FID x) = x -- | Type synonym for a function which implements an event handler. type FE ev a = F -- | A function which is called whenever a ref is attached to a component. type FRA el a = F -- | Function (when) Ref (is) Detach(ed). You don't get the element which was -- detached. This means you can't really add the same ref handler to multiple -- components. type FRD a = F -------------------------------------------------------------------------------- class Value a where parseValue :: A.Value -> A.Parser a instance Value () where parseValue _ = pure () -- A.parseJSON instance Value Int where parseValue = A.parseJSON instance Value Float where parseValue = A.parseJSON instance Value Text where parseValue = A.parseJSON instance (Value a, Value b) => Value (a,b) where parseValue v = do list <- A.parseJSON v case list of [a,b] -> (,) <$> parseValue a <*> parseValue b _ -> fail "(,)"
wereHamster/nauva
pkg/hs/nauva/src/Nauva/NJS.hs
mit
3,651
0
13
908
719
418
301
72
1
-- Directions Reduction -- http://www.codewars.com/kata/550f22f4d758534c1100025a/ module Codewars.Kata.Reduction where import Codewars.Kata.Reduction.Direction -- data Direction = North | East | West | South deriving (Eq) dirReduce :: [Direction] -> [Direction] dirReduce = foldr reduce [] where reduce North (South:xs) = xs reduce South (North:xs) = xs reduce East (West:xs) = xs reduce West (East:xs) = xs reduce x xs = x:xs
gafiatulin/codewars
src/5 kyu/Reduction.hs
mit
474
0
9
106
128
72
56
9
5
{-# LANGUAGE DoAndIfThenElse #-} module Python where import System.Directory import System.FilePath import System.FilePath.Find import System.IO import Functions -- initiate a haskell project ideInitPython :: IDEState -> IO (IDEState) ideInitPython state = do exists <- projectExists if exists then do putStrLn "Project already exists" return state else do thisDirectory <- getCurrentDirectory withFile ".project" WriteMode (\file -> do hPutStrLn file "Type: python" pythonFiles <- getRecursivePythonFiles hPutStrLn file $ "Files: " ++ show (map (makeRelative thisDirectory) pythonFiles) ) return state -- get all the haskell files in the current and subdirectories getRecursivePythonFiles :: IO [FilePath] getRecursivePythonFiles = find always (extension ==? ".py") =<< getCurrentDirectory -- compile command for haskell -- TODO: remove and use haskell.project file when I can get aeson ideCompilePython :: IO () ideCompilePython = putStrLn "No need to compile python files" -- make command for haskell -- TODO: remove and use haskell.project file when I can get aeson ideMakePython :: IO () ideMakePython = putStrLn "No need to compile python files" getMainFilePython :: String -> [FilePath] -> FilePath getMainFilePython _ _ = ""
jonathanmcelroy/commandLineIDE
Python.hs
mit
1,341
0
20
281
259
133
126
28
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ViewPatterns #-} module Unison.CommandLine.InputPatterns where import Unison.Prelude import qualified Control.Lens.Cons as Cons import Data.Bifunctor (first) import Data.List (intercalate, isPrefixOf) import Data.List.Extra (nubOrdOn) import qualified System.Console.Haskeline.Completion as Completion import System.Console.Haskeline.Completion (Completion(Completion)) import Unison.Codebase (Codebase) import Unison.Codebase.Editor.Input (Input) import qualified Unison.Codebase.SyncMode as SyncMode import Unison.CommandLine.InputPattern ( ArgumentType(..) , InputPattern(InputPattern) , IsOptional(..) ) import Unison.CommandLine import Unison.Util.Monoid (intercalateMap) import qualified Data.Map as Map import qualified Data.Set as Set import qualified Data.Text as Text import qualified Text.Megaparsec as P import qualified Unison.Codebase.Branch as Branch import qualified Unison.Codebase.Editor.Input as Input import qualified Unison.Codebase.Path as Path import qualified Unison.CommandLine.InputPattern as I import qualified Unison.HashQualified as HQ import qualified Unison.HashQualified' as HQ' import qualified Unison.Name as Name import Unison.Name ( Name ) import qualified Unison.Names2 as Names import qualified Unison.Util.ColorText as CT import qualified Unison.Util.Pretty as P import qualified Unison.Util.Relation as R import qualified Unison.Codebase.Editor.SlurpResult as SR import qualified Unison.Codebase.Editor.UriParser as UriParser import Unison.Codebase.Editor.RemoteRepo (ReadRemoteNamespace, WriteRemotePath, WriteRepo) import qualified Unison.Codebase.Editor.RemoteRepo as RemoteRepo import Data.Tuple.Extra (uncurry3) showPatternHelp :: InputPattern -> P.Pretty CT.ColorText showPatternHelp i = P.lines [ P.bold (fromString $ I.patternName i) <> fromString (if not . null $ I.aliases i then " (or " <> intercalate ", " (I.aliases i) <> ")" else ""), P.wrap $ I.help i ] patternName :: InputPattern -> P.Pretty P.ColorText patternName = fromString . I.patternName -- `example list ["foo", "bar"]` (haskell) becomes `list foo bar` (pretty) makeExample, makeExampleNoBackticks :: InputPattern -> [P.Pretty CT.ColorText] -> P.Pretty CT.ColorText makeExample p args = P.group . backtick $ makeExampleNoBackticks p args makeExampleNoBackticks p args = P.group $ intercalateMap " " id (P.nonEmpty $ fromString (I.patternName p) : args) makeExample' :: InputPattern -> P.Pretty CT.ColorText makeExample' p = makeExample p [] makeExampleEOS :: InputPattern -> [P.Pretty CT.ColorText] -> P.Pretty CT.ColorText makeExampleEOS p args = P.group $ backtick (intercalateMap " " id (P.nonEmpty $ fromString (I.patternName p) : args)) <> "." helpFor :: InputPattern -> Either (P.Pretty CT.ColorText) Input helpFor p = I.parse help [I.patternName p] mergeBuiltins :: InputPattern mergeBuiltins = InputPattern "builtins.merge" [] [] "Adds the builtins to `builtins.` in the current namespace (excluding `io` and misc)." (const . pure $ Input.MergeBuiltinsI) mergeIOBuiltins :: InputPattern mergeIOBuiltins = InputPattern "builtins.mergeio" [] [] "Adds all the builtins to `builtins.` in the current namespace, including `io` and misc." (const . pure $ Input.MergeIOBuiltinsI) updateBuiltins :: InputPattern updateBuiltins = InputPattern "builtins.update" [] [] ( "Adds all the builtins that are missing from this namespace, " <> "and deprecate the ones that don't exist in this version of Unison." ) (const . pure $ Input.UpdateBuiltinsI) todo :: InputPattern todo = InputPattern "todo" [] [(Optional, patchArg), (Optional, pathArg)] (P.wrapColumn2 [ ( makeExample' todo , "lists the refactor work remaining in the default patch for the current" <> " namespace." ) , ( makeExample todo ["<patch>"] , "lists the refactor work remaining in the given patch in the current " <> "namespace." ) , ( makeExample todo ["<patch>", "[path]"] , "lists the refactor work remaining in the given patch in given namespace." ) ] ) (\case patchStr : ws -> mapLeft (warn . fromString) $ do patch <- Path.parseSplit' Path.definitionNameSegment patchStr branch <- case ws of [] -> pure Path.relativeEmpty' [pathStr] -> Path.parsePath' pathStr _ -> Left "`todo` just takes a patch and one optional namespace" Right $ Input.TodoI (Just patch) branch [] -> Right $ Input.TodoI Nothing Path.relativeEmpty' ) load :: InputPattern load = InputPattern "load" [] [(Optional, noCompletions)] (P.wrapColumn2 [ ( makeExample' load , "parses, typechecks, and evaluates the most recent scratch file." ) , (makeExample load ["<scratch file>"] , "parses, typechecks, and evaluates the given scratch file." ) ] ) (\case [] -> pure $ Input.LoadI Nothing [file] -> pure $ Input.LoadI . Just $ file _ -> Left (I.help load)) add :: InputPattern add = InputPattern "add" [] [(ZeroPlus, noCompletions)] ("`add` adds to the codebase all the definitions from the most recently " <> "typechecked file." ) $ \ws -> case traverse HQ'.fromString ws of Just ws -> pure $ Input.AddI ws Nothing -> Left . warn . P.lines . fmap fromString . ("I don't know what these refer to:\n" :) $ collectNothings HQ'.fromString ws previewAdd :: InputPattern previewAdd = InputPattern "add.preview" [] [(ZeroPlus, noCompletions)] ("`add.preview` previews additions to the codebase from the most recently " <> "typechecked file. This command only displays cached typechecking " <> "results. Use `load` to reparse & typecheck the file if the context " <> "has changed." ) $ \ws -> case traverse HQ'.fromString ws of Just ws -> pure $ Input.PreviewAddI ws Nothing -> Left . warn . P.lines . fmap fromString . ("I don't know what these refer to:\n" :) $ collectNothings HQ'.fromString ws update :: InputPattern update = InputPattern "update" [] [(Optional, patchArg) ,(ZeroPlus, noCompletions)] (P.wrap (makeExample' update <> "works like" <> P.group (makeExample' add <> ",") <> "except that if a definition in the file has the same name as an" <> "existing definition, the name gets updated to point to the new" <> "definition. If the old definition has any dependents, `update` will" <> "add those dependents to a refactoring session, specified by an" <> "optional patch.") <> P.wrapColumn2 [ (makeExample' update , "adds all definitions in the .u file, noting replacements in the" <> "default patch for the current namespace.") , (makeExample update ["<patch>"] , "adds all definitions in the .u file, noting replacements in the" <> "specified patch.") , (makeExample update ["<patch>", "foo", "bar"] , "adds `foo`, `bar`, and their dependents from the .u file, noting" <> "any replacements into the specified patch.") ] ) (\case patchStr : ws -> do patch <- first fromString $ Path.parseSplit' Path.definitionNameSegment patchStr case traverse HQ'.fromString ws of Just ws -> Right $ Input.UpdateI (Just patch) ws Nothing -> Left . warn . P.lines . fmap fromString . ("I don't know what these refer to:\n" :) $ collectNothings HQ'.fromString ws [] -> Right $ Input.UpdateI Nothing [] ) previewUpdate :: InputPattern previewUpdate = InputPattern "update.preview" [] [(ZeroPlus, noCompletions)] ("`update.preview` previews updates to the codebase from the most " <> "recently typechecked file. This command only displays cached " <> "typechecking results. Use `load` to reparse & typecheck the file if " <> "the context has changed." ) $ \ws -> case traverse HQ'.fromString ws of Just ws -> pure $ Input.PreviewUpdateI ws Nothing -> Left . warn . P.lines . fmap fromString . ("I don't know what these refer to:\n" :) $ collectNothings HQ'.fromString ws patch :: InputPattern patch = InputPattern "patch" [] [(Required, patchArg), (Optional, pathArg)] ( P.wrap $ makeExample' patch <> "rewrites any definitions that depend on " <> "definitions with type-preserving edits to use the updated versions of" <> "these dependencies." ) (\case patchStr : ws -> first fromString $ do patch <- Path.parseSplit' Path.definitionNameSegment patchStr branch <- case ws of [pathStr] -> Path.parsePath' pathStr _ -> pure Path.relativeEmpty' pure $ Input.PropagatePatchI patch branch [] -> Left $ warn $ makeExample' patch <> "takes a patch and an optional namespace." ) view :: InputPattern view = InputPattern "view" [] [(OnePlus, definitionQueryArg)] "`view foo` prints the definition of `foo`." ( fmap (Input.ShowDefinitionI Input.ConsoleLocation) . traverse parseHashQualifiedName ) display :: InputPattern display = InputPattern "display" [] [(Required, definitionQueryArg)] "`display foo` prints a rendered version of the term `foo`." (\case [s] -> Input.DisplayI Input.ConsoleLocation <$> parseHashQualifiedName s _ -> Left (I.help display) ) displayTo :: InputPattern displayTo = InputPattern "display.to" [] [(Required, noCompletions), (Required, definitionQueryArg)] ( P.wrap $ makeExample displayTo ["<filename>", "foo"] <> "prints a rendered version of the term `foo` to the given file." ) (\case [file, s] -> Input.DisplayI (Input.FileLocation file) <$> parseHashQualifiedName s _ -> Left (I.help displayTo) ) docs :: InputPattern docs = InputPattern "docs" [] [(Required, definitionQueryArg)] "`docs foo` shows documentation for the definition `foo`." (\case [s] -> first fromString $ Input.DocsI <$> Path.parseHQSplit' s _ -> Left (I.help docs)) ui :: InputPattern ui = InputPattern "ui" [] [] "`ui` opens the Codebase UI in the default browser." (const $ pure Input.UiI) undo :: InputPattern undo = InputPattern "undo" [] [] "`undo` reverts the most recent change to the codebase." (const $ pure Input.UndoI) viewByPrefix :: InputPattern viewByPrefix = InputPattern "view.recursive" [] [(OnePlus, definitionQueryArg)] "`view.recursive Foo` prints the definitions of `Foo` and `Foo.blah`." ( fmap (Input.ShowDefinitionByPrefixI Input.ConsoleLocation) . traverse parseHashQualifiedName ) find :: InputPattern find = InputPattern "find" [] [(ZeroPlus, fuzzyDefinitionQueryArg)] (P.wrapColumn2 [ ("`find`", "lists all definitions in the current namespace.") , ( "`find foo`" , "lists all definitions with a name similar to 'foo' in the current " <> "namespace." ) , ( "`find foo bar`" , "lists all definitions with a name similar to 'foo' or 'bar' in the " <> "current namespace." ) ] ) (pure . Input.SearchByNameI False False) findShallow :: InputPattern findShallow = InputPattern "list" ["ls"] [(Optional, pathArg)] (P.wrapColumn2 [ ("`list`", "lists definitions and namespaces at the current level of the current namespace.") , ( "`list foo`", "lists the 'foo' namespace." ) , ( "`list .foo`", "lists the '.foo' namespace." ) ] ) (\case [] -> pure $ Input.FindShallowI Path.relativeEmpty' [path] -> first fromString $ do p <- Path.parsePath' path pure $ Input.FindShallowI p _ -> Left (I.help findShallow) ) findVerbose :: InputPattern findVerbose = InputPattern "find.verbose" ["list.verbose", "ls.verbose"] [(ZeroPlus, fuzzyDefinitionQueryArg)] ( "`find.verbose` searches for definitions like `find`, but includes hashes " <> "and aliases in the results." ) (pure . Input.SearchByNameI True False) findPatch :: InputPattern findPatch = InputPattern "find.patch" ["list.patch", "ls.patch"] [] (P.wrapColumn2 [("`find.patch`", "lists all patches in the current namespace.")] ) (pure . const Input.FindPatchI) renameTerm :: InputPattern renameTerm = InputPattern "move.term" ["rename.term"] [(Required, exactDefinitionTermQueryArg) ,(Required, newNameArg)] "`move.term foo bar` renames `foo` to `bar`." (\case [oldName, newName] -> first fromString $ do src <- Path.parseHQSplit' oldName target <- Path.parseSplit' Path.definitionNameSegment newName pure $ Input.MoveTermI src target _ -> Left . P.warnCallout $ P.wrap "`rename.term` takes two arguments, like `rename.term oldname newname`.") renameType :: InputPattern renameType = InputPattern "move.type" ["rename.type"] [(Required, exactDefinitionTypeQueryArg) ,(Required, newNameArg)] "`move.type foo bar` renames `foo` to `bar`." (\case [oldName, newName] -> first fromString $ do src <- Path.parseHQSplit' oldName target <- Path.parseSplit' Path.definitionNameSegment newName pure $ Input.MoveTypeI src target _ -> Left . P.warnCallout $ P.wrap "`rename.type` takes two arguments, like `rename.type oldname newname`.") delete :: InputPattern delete = InputPattern "delete" [] [(OnePlus, definitionQueryArg)] "`delete foo` removes the term or type name `foo` from the namespace." (\case [query] -> first fromString $ do p <- Path.parseHQSplit' query pure $ Input.DeleteI p _ -> Left . P.warnCallout $ P.wrap "`delete` takes an argument, like `delete name`." ) deleteTerm :: InputPattern deleteTerm = InputPattern "delete.term" [] [(OnePlus, exactDefinitionTermQueryArg)] "`delete.term foo` removes the term name `foo` from the namespace." (\case [query] -> first fromString $ do p <- Path.parseHQSplit' query pure $ Input.DeleteTermI p _ -> Left . P.warnCallout $ P.wrap "`delete.term` takes an argument, like `delete.term name`." ) deleteType :: InputPattern deleteType = InputPattern "delete.type" [] [(OnePlus, exactDefinitionTypeQueryArg)] "`delete.type foo` removes the type name `foo` from the namespace." (\case [query] -> first fromString $ do p <- Path.parseHQSplit' query pure $ Input.DeleteTypeI p _ -> Left . P.warnCallout $ P.wrap "`delete.type` takes an argument, like `delete.type name`." ) deleteTermReplacementCommand :: String deleteTermReplacementCommand = "delete.term-replacement" deleteTypeReplacementCommand :: String deleteTypeReplacementCommand = "delete.type-replacement" deleteReplacement :: Bool -> InputPattern deleteReplacement isTerm = InputPattern commandName [] [(Required, if isTerm then exactDefinitionTermQueryArg else exactDefinitionTypeQueryArg), (Optional, patchArg)] ( P.string $ commandName <> " <foo> <patch>` removes any edit of the " <> str <> " `foo` from the patch `patch`, " <> "or from the default patch if none is specified. Note that `foo` refers to the " <> "original name for the " <> str <> " - not the one in place after the edit." ) (\case query : patch -> do patch <- first fromString . traverse (Path.parseSplit' Path.definitionNameSegment) $ listToMaybe patch q <- parseHashQualifiedName query pure $ input q patch _ -> Left . P.warnCallout . P.wrapString $ commandName <> " needs arguments. See `help " <> commandName <> "`." ) where input = if isTerm then Input.RemoveTermReplacementI else Input.RemoveTypeReplacementI str = if isTerm then "term" else "type" commandName = if isTerm then deleteTermReplacementCommand else deleteTypeReplacementCommand deleteTermReplacement :: InputPattern deleteTermReplacement = deleteReplacement True deleteTypeReplacement :: InputPattern deleteTypeReplacement = deleteReplacement False parseHashQualifiedName :: String -> Either (P.Pretty CT.ColorText) (HQ.HashQualified Name) parseHashQualifiedName s = maybe ( Left . P.warnCallout . P.wrap $ P.string s <> " is not a well-formed name, hash, or hash-qualified name. " <> "I expected something like `foo`, `#abc123`, or `foo#abc123`." ) Right $ HQ.fromString s aliasTerm :: InputPattern aliasTerm = InputPattern "alias.term" [] [(Required, exactDefinitionTermQueryArg), (Required, newNameArg)] "`alias.term foo bar` introduces `bar` with the same definition as `foo`." (\case [oldName, newName] -> first fromString $ do source <- Path.parseShortHashOrHQSplit' oldName target <- Path.parseSplit' Path.definitionNameSegment newName pure $ Input.AliasTermI source target _ -> Left . warn $ P.wrap "`alias.term` takes two arguments, like `alias.term oldname newname`." ) aliasType :: InputPattern aliasType = InputPattern "alias.type" [] [(Required, exactDefinitionTypeQueryArg), (Required, newNameArg)] "`alias.type Foo Bar` introduces `Bar` with the same definition as `Foo`." (\case [oldName, newName] -> first fromString $ do source <- Path.parseShortHashOrHQSplit' oldName target <- Path.parseSplit' Path.definitionNameSegment newName pure $ Input.AliasTypeI source target _ -> Left . warn $ P.wrap "`alias.type` takes two arguments, like `alias.type oldname newname`." ) aliasMany :: InputPattern aliasMany = InputPattern "alias.many" ["copy"] [(Required, definitionQueryArg), (OnePlus, exactDefinitionOrPathArg)] (P.group . P.lines $ [ P.wrap $ P.group (makeExample aliasMany ["<relative1>", "[relative2...]", "<namespace>"]) <> "creates aliases `relative1`, `relative2`, ... in the namespace `namespace`." , P.wrap $ P.group (makeExample aliasMany ["foo.foo", "bar.bar", ".quux"]) <> "creates aliases `.quux.foo.foo` and `.quux.bar.bar`." ]) (\case srcs@(_:_) Cons.:> dest -> first fromString $ do sourceDefinitions <- traverse Path.parseHQSplit srcs destNamespace <- Path.parsePath' dest pure $ Input.AliasManyI sourceDefinitions destNamespace _ -> Left (I.help aliasMany) ) cd :: InputPattern cd = InputPattern "namespace" ["cd", "j"] [(Required, pathArg)] (P.wrapColumn2 [ (makeExample cd ["foo.bar"], "descends into foo.bar from the current namespace.") , (makeExample cd [".cat.dog"], "sets the current namespace to the abolute namespace .cat.dog.") ]) (\case [p] -> first fromString $ do p <- Path.parsePath' p pure . Input.SwitchBranchI $ p _ -> Left (I.help cd) ) back :: InputPattern back = InputPattern "back" ["popd"] [] (P.wrapColumn2 [ (makeExample back [], "undoes the last" <> makeExample' cd <> "command.") ]) (\case [] -> pure Input.PopBranchI _ -> Left (I.help cd) ) deleteBranch :: InputPattern deleteBranch = InputPattern "delete.namespace" [] [(Required, pathArg)] "`delete.namespace <foo>` deletes the namespace `foo`" (\case ["."] -> first fromString . pure $ Input.DeleteBranchI Nothing [p] -> first fromString $ do p <- Path.parseSplit' Path.definitionNameSegment p pure . Input.DeleteBranchI $ Just p _ -> Left (I.help deleteBranch) ) deletePatch :: InputPattern deletePatch = InputPattern "delete.patch" [] [(Required, patchArg)] "`delete.patch <foo>` deletes the patch `foo`" (\case [p] -> first fromString $ do p <- Path.parseSplit' Path.definitionNameSegment p pure . Input.DeletePatchI $ p _ -> Left (I.help deletePatch) ) movePatch :: String -> String -> Either (P.Pretty CT.ColorText) Input movePatch src dest = first fromString $ do src <- Path.parseSplit' Path.definitionNameSegment src dest <- Path.parseSplit' Path.definitionNameSegment dest pure $ Input.MovePatchI src dest copyPatch' :: String -> String -> Either (P.Pretty CT.ColorText) Input copyPatch' src dest = first fromString $ do src <- Path.parseSplit' Path.definitionNameSegment src dest <- Path.parseSplit' Path.definitionNameSegment dest pure $ Input.CopyPatchI src dest copyPatch :: InputPattern copyPatch = InputPattern "copy.patch" [] [(Required, patchArg), (Required, newNameArg)] "`copy.patch foo bar` copies the patch `foo` to `bar`." (\case [src, dest] -> copyPatch' src dest _ -> Left (I.help copyPatch) ) renamePatch :: InputPattern renamePatch = InputPattern "move.patch" ["rename.patch"] [(Required, patchArg), (Required, newNameArg)] "`move.patch foo bar` renames the patch `foo` to `bar`." (\case [src, dest] -> movePatch src dest _ -> Left (I.help renamePatch) ) renameBranch :: InputPattern renameBranch = InputPattern "move.namespace" ["rename.namespace"] [(Required, pathArg), (Required, newNameArg)] "`move.namespace foo bar` renames the path `bar` to `foo`." (\case [".", dest] -> first fromString $ do dest <- Path.parseSplit' Path.definitionNameSegment dest pure $ Input.MoveBranchI Nothing dest [src, dest] -> first fromString $ do src <- Path.parseSplit' Path.definitionNameSegment src dest <- Path.parseSplit' Path.definitionNameSegment dest pure $ Input.MoveBranchI (Just src) dest _ -> Left (I.help renameBranch) ) history :: InputPattern history = InputPattern "history" [] [(Optional, pathArg)] (P.wrapColumn2 [ (makeExample history [], "Shows the history of the current path."), (makeExample history [".foo"], "Shows history of the path .foo."), (makeExample history ["#9dndk3kbsk13nbpeu"], "Shows the history of the namespace with the given hash." <> "The full hash must be provided.") ]) (\case [src] -> first fromString $ do p <- Input.parseBranchId src pure $ Input.HistoryI (Just 10) (Just 10) p [] -> pure $ Input.HistoryI (Just 10) (Just 10) (Right Path.currentPath) _ -> Left (I.help history) ) forkLocal :: InputPattern forkLocal = InputPattern "fork" ["copy.namespace"] [(Required, pathArg) ,(Required, newNameArg)] (makeExample forkLocal ["src", "dest"] <> "creates the namespace `dest` as a copy of `src`.") (\case [src, dest] -> first fromString $ do src <- Input.parseBranchId src dest <- Path.parsePath' dest pure $ Input.ForkLocalBranchI src dest _ -> Left (I.help forkLocal) ) resetRoot :: InputPattern resetRoot = InputPattern "reset-root" [] [(Required, pathArg)] (P.wrapColumn2 [ (makeExample resetRoot [".foo"], "Reset the root namespace (along with its history) to that of the `.foo` namespace."), (makeExample resetRoot ["#9dndk3kbsk13nbpeu"], "Reset the root namespace (along with its history) to that of the namespace with hash `#9dndk3kbsk13nbpeu`.") ]) (\case [src] -> first fromString $ do src <- Input.parseBranchId src pure $ Input.ResetRootI src _ -> Left (I.help resetRoot)) pull :: InputPattern pull = InputPattern "pull" [] [(Optional, gitUrlArg), (Optional, pathArg)] (P.lines [ P.wrap "The `pull` command merges a remote namespace into a local namespace." , "" , P.wrapColumn2 [ ( "`pull remote local`" , "merges the remote namespace `remote`" <>"into the local namespace `local`." ) , ( "`pull remote`" , "merges the remote namespace `remote`" <>"into the current namespace") , ( "`pull`" , "merges the remote namespace configured in `.unisonConfig`" <> "with the key `GitUrl.ns` where `ns` is the current namespace," <> "into the current namespace") ] , "" , P.wrap "where `remote` is a git repository, optionally followed by `:`" <> "and an absolute remote path, such as:" , P.indentN 2 . P.lines $ [P.backticked "https://github.com/org/repo" ,P.backticked "https://github.com/org/repo:.some.remote.path" ] ] ) (\case [] -> Right $ Input.PullRemoteBranchI Nothing Path.relativeEmpty' SyncMode.ShortCircuit [url] -> do ns <- parseUri "url" url Right $ Input.PullRemoteBranchI (Just ns) Path.relativeEmpty' SyncMode.ShortCircuit [url, path] -> do ns <- parseUri "url" url p <- first fromString $ Path.parsePath' path Right $ Input.PullRemoteBranchI (Just ns) p SyncMode.ShortCircuit _ -> Left (I.help pull) ) pullExhaustive :: InputPattern pullExhaustive = InputPattern "debug.pull-exhaustive" [] [(Required, gitUrlArg), (Optional, pathArg)] (P.lines [ P.wrap $ "The " <> makeExample' pullExhaustive <> "command can be used in place of" <> makeExample' pull <> "to complete namespaces" <> "which were pulled incompletely due to a bug in UCM" <> "versions M1l and earlier. It may be extra slow!" ] ) (\case [] -> Right $ Input.PullRemoteBranchI Nothing Path.relativeEmpty' SyncMode.Complete [url] -> do ns <- parseUri "url" url Right $ Input.PullRemoteBranchI (Just ns) Path.relativeEmpty' SyncMode.Complete [url, path] -> do ns <- parseUri "url" url p <- first fromString $ Path.parsePath' path Right $ Input.PullRemoteBranchI (Just ns) p SyncMode.Complete _ -> Left (I.help pull) ) push :: InputPattern push = InputPattern "push" [] [(Required, gitUrlArg), (Optional, pathArg)] (P.lines [ P.wrap "The `push` command merges a local namespace into a remote namespace." , "" , P.wrapColumn2 [ ( "`push remote local`" , "merges the contents of the local namespace `local`" <> "into the remote namespace `remote`." ) , ( "`push remote`" , "publishes the current namespace into the remote namespace `remote`") , ( "`push`" , "publishes the current namespace" <> "into the remote namespace configured in `.unisonConfig`" <> "with the key `GitUrl.ns` where `ns` is the current namespace") ] , "" , P.wrap "where `remote` is a git repository, optionally followed by `:`" <> "and an absolute remote path, such as:" , P.indentN 2 . P.lines $ [P.backticked "https://github.com/org/repo" ,P.backticked "https://github.com/org/repo:.some.remote.path" ] ] ) (\case [] -> Right $ Input.PushRemoteBranchI Nothing Path.relativeEmpty' SyncMode.ShortCircuit url : rest -> do (repo, path) <- parsePushPath "url" url p <- case rest of [] -> Right Path.relativeEmpty' [path] -> first fromString $ Path.parsePath' path _ -> Left (I.help push) Right $ Input.PushRemoteBranchI (Just (repo, path)) p SyncMode.ShortCircuit ) pushExhaustive :: InputPattern pushExhaustive = InputPattern "debug.push-exhaustive" [] [(Required, gitUrlArg), (Optional, pathArg)] (P.lines [ P.wrap $ "The " <> makeExample' pushExhaustive <> "command can be used in place of" <> makeExample' push <> "to repair remote namespaces" <> "which were pushed incompletely due to a bug in UCM" <> "versions M1l and earlier. It may be extra slow!" ] ) (\case [] -> Right $ Input.PushRemoteBranchI Nothing Path.relativeEmpty' SyncMode.Complete url : rest -> do (repo, path) <- parsePushPath "url" url p <- case rest of [] -> Right Path.relativeEmpty' [path] -> first fromString $ Path.parsePath' path _ -> Left (I.help push) Right $ Input.PushRemoteBranchI (Just (repo, path)) p SyncMode.Complete ) createPullRequest :: InputPattern createPullRequest = InputPattern "pull-request.create" ["pr.create"] [(Required, gitUrlArg), (Required, gitUrlArg), (Optional, pathArg)] (P.group $ P.lines [ P.wrap $ makeExample createPullRequest ["base", "head"] <> "will generate a request to merge the remote repo `head`" <> "into the remote repo `base`." , "" , "example: " <> makeExampleNoBackticks createPullRequest ["https://github.com/unisonweb/base:.trunk", "https://github.com/me/unison:.prs.base._myFeature" ] ]) (\case [baseUrl, headUrl] -> do baseRepo <- parseUri "baseRepo" baseUrl headRepo <- parseUri "headRepo" headUrl pure $ Input.CreatePullRequestI baseRepo headRepo _ -> Left (I.help createPullRequest) ) loadPullRequest :: InputPattern loadPullRequest = InputPattern "pull-request.load" ["pr.load"] [(Required, gitUrlArg), (Required, gitUrlArg), (Optional, pathArg)] (P.lines [P.wrap $ makeExample loadPullRequest ["base", "head"] <> "will load a pull request for merging the remote repo `head` into the" <> "remote repo `base`, staging each in the current namespace" <> "(so make yourself a clean spot to work first)." ,P.wrap $ makeExample loadPullRequest ["base", "head", "dest"] <> "will load a pull request for merging the remote repo `head` into the" <> "remote repo `base`, staging each in `dest`, which must be empty." ]) (\case [baseUrl, headUrl] -> do baseRepo <- parseUri "baseRepo" baseUrl headRepo <- parseUri "topicRepo" headUrl pure $ Input.LoadPullRequestI baseRepo headRepo Path.relativeEmpty' [baseUrl, headUrl, dest] -> do baseRepo <- parseUri "baseRepo" baseUrl headRepo <- parseUri "topicRepo" headUrl destPath <- first fromString $ Path.parsePath' dest pure $ Input.LoadPullRequestI baseRepo headRepo destPath _ -> Left (I.help loadPullRequest) ) parseUri :: String -> String -> Either (P.Pretty P.ColorText) ReadRemoteNamespace parseUri label input = do first (fromString . show) -- turn any parsing errors into a Pretty. (P.parse UriParser.repoPath label (Text.pack input)) parseWriteRepo :: String -> String -> Either (P.Pretty P.ColorText) WriteRepo parseWriteRepo label input = do first (fromString . show) -- turn any parsing errors into a Pretty. (P.parse UriParser.writeRepo label (Text.pack input)) parsePushPath :: String -> String -> Either (P.Pretty P.ColorText) WriteRemotePath parsePushPath label input = do first (fromString . show) -- turn any parsing errors into a Pretty. (P.parse UriParser.writeRepoPath label (Text.pack input)) squashMerge :: InputPattern squashMerge = InputPattern "merge.squash" ["squash"] [(Required, pathArg), (Required, pathArg)] (P.wrap $ makeExample squashMerge ["src","dest"] <> "merges `src` namespace into `dest`," <> "discarding the history of `src` in the process." <> "The resulting `dest` will have (at most) 1" <> "additional history entry.") (\case [src, dest] -> first fromString $ do src <- Path.parsePath' src dest <- Path.parsePath' dest pure $ Input.MergeLocalBranchI src dest Branch.SquashMerge _ -> Left (I.help squashMerge) ) mergeLocal :: InputPattern mergeLocal = InputPattern "merge" [] [(Required, pathArg) ,(Optional, pathArg)] (P.column2 [ ("`merge src`", "merges `src` namespace into the current namespace"), ("`merge src dest`", "merges `src` namespace into the `dest` namespace")]) (\case [src] -> first fromString $ do src <- Path.parsePath' src pure $ Input.MergeLocalBranchI src Path.relativeEmpty' Branch.RegularMerge [src, dest] -> first fromString $ do src <- Path.parsePath' src dest <- Path.parsePath' dest pure $ Input.MergeLocalBranchI src dest Branch.RegularMerge _ -> Left (I.help mergeLocal) ) diffNamespace :: InputPattern diffNamespace = InputPattern "diff.namespace" [] [(Required, pathArg), (Optional, pathArg)] (P.column2 [ ( "`diff.namespace before after`" , P.wrap "shows how the namespace `after` differs from the namespace `before`" ) , ( "`diff.namespace before`" , P.wrap "shows how the current namespace differs from the namespace `before`" ) ] ) (\case [before, after] -> first fromString $ do before <- Path.parsePath' before after <- Path.parsePath' after pure $ Input.DiffNamespaceI before after [before] -> first fromString $ do before <- Path.parsePath' before pure $ Input.DiffNamespaceI before Path.currentPath _ -> Left $ I.help diffNamespace ) previewMergeLocal :: InputPattern previewMergeLocal = InputPattern "merge.preview" [] [(Required, pathArg), (Optional, pathArg)] (P.column2 [ ( "`merge.preview src`" , "shows how the current namespace will change after a `merge src`." ) , ( "`merge.preview src dest`" , "shows how `dest` namespace will change after a `merge src dest`." ) ] ) (\case [src] -> first fromString $ do src <- Path.parsePath' src pure $ Input.PreviewMergeLocalBranchI src Path.relativeEmpty' [src, dest] -> first fromString $ do src <- Path.parsePath' src dest <- Path.parsePath' dest pure $ Input.PreviewMergeLocalBranchI src dest _ -> Left (I.help previewMergeLocal) ) replaceEdit :: ( HQ.HashQualified Name -> HQ.HashQualified Name -> Maybe Input.PatchPath -> Input ) -> InputPattern replaceEdit f = self where self = InputPattern "replace" [] [ (Required, definitionQueryArg) , (Required, definitionQueryArg) , (Optional, patchArg) ] (P.wrapColumn2 [ ( makeExample self ["<from>", "<to>", "<patch>"] , "Replace the term/type <from> in the given patch with the term/type <to>." ) , ( makeExample self ["<from>", "<to>"] , "Replace the term/type <from> with <to> in the default patch." ) ] ) (\case source : target : patch -> do patch <- first fromString <$> traverse (Path.parseSplit' Path.definitionNameSegment) $ listToMaybe patch sourcehq <- parseHashQualifiedName source targethq <- parseHashQualifiedName target pure $ f sourcehq targethq patch _ -> Left $ I.help self ) replace :: InputPattern replace = replaceEdit Input.ReplaceI viewReflog :: InputPattern viewReflog = InputPattern "reflog" [] [] "`reflog` lists the changes that have affected the root namespace" (\case [] -> pure Input.ShowReflogI _ -> Left . warn . P.string $ I.patternName viewReflog ++ " doesn't take any arguments.") edit :: InputPattern edit = InputPattern "edit" [] [(OnePlus, definitionQueryArg)] ( "`edit foo` prepends the definition of `foo` to the top of the most " <> "recently saved file." ) ( fmap (Input.ShowDefinitionI Input.LatestFileLocation) . traverse parseHashQualifiedName ) topicNameArg :: ArgumentType topicNameArg = ArgumentType "topic" $ \q _ _ _ -> pure (exactComplete q $ Map.keys helpTopicsMap) helpTopics :: InputPattern helpTopics = InputPattern "help-topics" ["help-topic"] [(Optional, topicNameArg)] ( "`help-topics` lists all topics and `help-topics <topic>` shows an explanation of that topic." ) (\case [] -> Left topics [topic] -> case Map.lookup topic helpTopicsMap of Nothing -> Left . warn $ "I don't know of that topic. Try `help-topics`." Just t -> Left t _ -> Left $ warn "Use `help-topics <topic>` or `help-topics`." ) where topics = P.callout "🌻" $ P.lines [ "Here's a list of topics I can tell you more about: ", "", P.indentN 2 $ P.sep "\n" (P.string <$> Map.keys helpTopicsMap), "", aside "Example" "use `help filestatus` to learn more about that topic." ] helpTopicsMap :: Map String (P.Pretty P.ColorText) helpTopicsMap = Map.fromList [ ("testcache", testCacheMsg), ("filestatus", fileStatusMsg), ("messages.disallowedAbsolute", disallowedAbsoluteMsg), ("namespaces", pathnamesMsg) ] where blankline = ("","") fileStatusMsg = P.callout "📓" . P.lines $ [ P.wrap $ "Here's a list of possible status messages you might see" <> "for definitions in a .u file.", "", P.wrapColumn2 [ (P.bold $ SR.prettyStatus SR.Collision, "A definition with the same name as an existing definition. Doing" <> "`update` instead of `add` will turn this failure into a successful" <> "update."), blankline, (P.bold $ SR.prettyStatus SR.Conflicted, "A definition with the same name as an existing definition." <> "Resolving the conflict and then trying an `update` again will" <> "turn this into a successful update."), blankline, (P.bold $ SR.prettyStatus SR.TermExistingConstructorCollision, "A definition with the same name as an existing constructor for " <> "some data type. Rename your definition or the data type before" <> "trying again to `add` or `update`."), blankline, (P.bold $ SR.prettyStatus SR.ConstructorExistingTermCollision, "A type defined in the file has a constructor that's named the" <> "same as an existing term. Rename that term or your constructor" <> "before trying again to `add` or `update`."), blankline, (P.bold $ SR.prettyStatus SR.BlockedDependency, "This definition was blocked because it dependended on " <> "a definition with a failed status."), blankline, (P.bold $ SR.prettyStatus SR.ExtraDefinition, "This definition was added because it was a dependency of" <> "a definition explicitly selected.") ] ] testCacheMsg = P.callout "🎈" . P.lines $ [ P.wrap $ "Unison caches the results of " <> P.blue "test>" <> "watch expressions. Since these expressions are pure and" <> "always yield the same result when evaluated, there's no need" <> "to run them more than once!", "", P.wrap $ "A test is rerun only if it has changed, or if one" <> "of the definitions it depends on has changed." ] pathnamesMsg = P.callout "\129488" . P.lines $ [ P.wrap $ "There are two kinds of namespaces," <> P.group (P.blue "absolute" <> ",") <> "such as" <> P.group ("(" <> P.blue ".foo.bar") <> "or" <> P.group (P.blue ".base.math.+" <> ")") <> "and" <> P.group (P.green "relative" <> ",") <> "such as" <> P.group ("(" <> P.green "math.sqrt") <> "or" <> P.group (P.green "util.List.++" <> ")."), "", P.wrap $ "Relative names are converted to absolute names by prepending the current namespace." <> "For example, if your Unison prompt reads:", "", P.indentN 2 $ P.blue ".foo.bar>", "", "and your .u file looks like:", "", P.indentN 2 $ P.green "x" <> " = 41", "", P.wrap $ "then doing an" <> P.blue "add" <> "will create the definition with the absolute name" <> P.group (P.blue ".foo.bar.x" <> " = 41"), "", P.wrap $ "and you can refer to" <> P.green "x" <> "by its absolute name " <> P.blue ".foo.bar.x" <> "elsewhere" <> "in your code. For instance:", "", P.indentN 2 $ "answerToLifeTheUniverseAndEverything = " <> P.blue ".foo.bar.x" <> " + 1" ] disallowedAbsoluteMsg = P.callout "\129302" . P.lines $ [ P.wrap $ "Although I can understand absolute (ex: .foo.bar) or" <> "relative (ex: util.math.sqrt) references to existing definitions" <> P.group ("(" <> P.blue "help namespaces") <> "to learn more)," <> "I can't yet handle giving new definitions with absolute names in a .u file.", "", P.wrap $ "As a workaround, you can give definitions with a relative name" <> "temporarily (like `exports.blah.foo`) and then use `move.*` " <> "or `merge` commands to move stuff around afterwards." ] help :: InputPattern help = InputPattern "help" ["?"] [(Optional, commandNameArg)] "`help` shows general help and `help <cmd>` shows help for one command." (\case [] -> Left $ intercalateMap "\n\n" showPatternHelp (sortOn I.patternName validInputs) [isHelp -> Just msg] -> Left msg [cmd] -> case Map.lookup cmd commandsByName of Nothing -> Left . warn $ "I don't know of that command. Try `help`." Just pat -> Left $ showPatternHelp pat _ -> Left $ warn "Use `help <cmd>` or `help`.") where commandsByName = Map.fromList [ (n, i) | i <- validInputs, n <- I.patternName i : I.aliases i ] isHelp s = Map.lookup s helpTopicsMap quit :: InputPattern quit = InputPattern "quit" ["exit", ":q"] [] "Exits the Unison command line interface." (\case [] -> pure Input.QuitI _ -> Left "Use `quit`, `exit`, or <Ctrl-D> to quit." ) viewPatch :: InputPattern viewPatch = InputPattern "view.patch" [] [(Required, patchArg)] (P.wrapColumn2 [ ( makeExample' viewPatch , "Lists all the edits in the default patch." ) , ( makeExample viewPatch ["<patch>"] , "Lists all the edits in the given patch." ) ] ) (\case [] -> Right $ Input.ListEditsI Nothing [patchStr] -> mapLeft fromString $ do patch <- Path.parseSplit' Path.definitionNameSegment patchStr Right $ Input.ListEditsI (Just patch) _ -> Left $ warn "`view.patch` takes a patch and that's it." ) link :: InputPattern link = InputPattern "link" [] [(Required, definitionQueryArg), (OnePlus, definitionQueryArg)] (fromString $ concat [ "`link metadata defn` creates a link to `metadata` from `defn`. " , "Use `links defn` or `links defn <type>` to view outgoing links, " , "and `unlink metadata defn` to remove a link. The `defn` can be either the " , "name of a term or type, multiple such names, or a range like `1-4` " , "for a range of definitions listed by a prior `find` command." ] ) (\case md : defs -> first fromString $ do md <- case HQ.fromString md of Nothing -> Left "Invalid hash qualified identifier for metadata." Just hq -> pure hq defs <- traverse Path.parseHQSplit' defs Right $ Input.LinkI md defs _ -> Left (I.help link) ) links :: InputPattern links = InputPattern "links" [] [(Required, definitionQueryArg), (Optional, definitionQueryArg)] (P.column2 [ (makeExample links ["defn"], "shows all outgoing links from `defn`."), (makeExample links ["defn", "<type>"], "shows all links of the given type.") ]) (\case src : rest -> first fromString $ do src <- Path.parseHQSplit' src let ty = case rest of [] -> Nothing _ -> Just $ unwords rest in Right $ Input.LinksI src ty _ -> Left (I.help links) ) unlink :: InputPattern unlink = InputPattern "unlink" ["delete.link"] [(Required, definitionQueryArg), (OnePlus, definitionQueryArg)] (fromString $ concat [ "`unlink metadata defn` removes a link to `metadata` from `defn`." , "The `defn` can be either the " , "name of a term or type, multiple such names, or a range like `1-4` " , "for a range of definitions listed by a prior `find` command." ]) (\case md : defs -> first fromString $ do md <- case HQ.fromString md of Nothing -> Left "Invalid hash qualified identifier for metadata." Just hq -> pure hq defs <- traverse Path.parseHQSplit' defs Right $ Input.UnlinkI md defs _ -> Left (I.help unlink) ) names :: InputPattern names = InputPattern "names" [] [(Required, definitionQueryArg)] "`names foo` shows the hash and all known names for `foo`." (\case [thing] -> case HQ.fromString thing of Just hq -> Right $ Input.NamesI hq Nothing -> Left $ "I was looking for one of these forms: " <> P.blue "foo .foo.bar foo#abc #abcde .foo.bar#asdf" _ -> Left (I.help names) ) dependents, dependencies :: InputPattern dependents = InputPattern "dependents" [] [] "List the dependents of the specified definition." (\case [thing] -> fmap Input.ListDependentsI $ parseHashQualifiedName thing _ -> Left (I.help dependents)) dependencies = InputPattern "dependencies" [] [] "List the dependencies of the specified definition." (\case [thing] -> fmap Input.ListDependenciesI $ parseHashQualifiedName thing _ -> Left (I.help dependencies)) debugNumberedArgs :: InputPattern debugNumberedArgs = InputPattern "debug.numberedArgs" [] [] "Dump the contents of the numbered args state." (const $ Right Input.DebugNumberedArgsI) debugBranchHistory :: InputPattern debugBranchHistory = InputPattern "debug.history" [] [(Optional, noCompletions)] "Dump codebase history, compatible with bit-booster.com/graph.html" (const $ Right Input.DebugBranchHistoryI) debugFileHashes :: InputPattern debugFileHashes = InputPattern "debug.file" [] [] "View details about the most recent succesfully typechecked file." (const $ Right Input.DebugTypecheckedUnisonFileI) debugDumpNamespace :: InputPattern debugDumpNamespace = InputPattern "debug.dump-namespace" [] [(Required, noCompletions)] "Dump the namespace to a text file" (const $ Right Input.DebugDumpNamespacesI) debugDumpNamespaceSimple :: InputPattern debugDumpNamespaceSimple = InputPattern "debug.dump-namespace-simple" [] [(Required, noCompletions)] "Dump the namespace to a text file" (const $ Right Input.DebugDumpNamespaceSimpleI) debugClearWatchCache :: InputPattern debugClearWatchCache = InputPattern "debug.clear-cache" [] [(Required, noCompletions)] "Clear the watch expression cache" (const $ Right Input.DebugClearWatchI) test :: InputPattern test = InputPattern "test" [] [] "`test` runs unit tests for the current branch." (const $ pure $ Input.TestI True True) execute :: InputPattern execute = InputPattern "run" [] [] (P.wrapColumn2 [ ( "`run mymain`" , "Runs `!mymain`, where `mymain` is searched for in the most recent" <> "typechecked file, or in the codebase." ) ] ) (\case [w] -> pure . Input.ExecuteI $ w _ -> Left $ showPatternHelp execute ) ioTest :: InputPattern ioTest = InputPattern "io.test" [] [] (P.wrapColumn2 [ ( "`io.test mytest`" , "Runs `!mytest`, where `mytest` is searched for in the most recent" <> "typechecked file, or in the codebase." ) ] ) (\case [thing] -> fmap Input.IOTestI $ parseHashQualifiedName thing _ -> Left $ showPatternHelp ioTest ) createAuthor :: InputPattern createAuthor = InputPattern "create.author" [] [(Required, noCompletions), (Required, noCompletions)] (makeExample createAuthor ["alicecoder", "\"Alice McGee\""] <> "creates" <> backtick "alicecoder" <> "values in" <> backtick "metadata.authors" <> "and" <> backtickEOS "metadata.copyrightHolders") (\case symbolStr : authorStr@(_:_) -> first fromString $ do symbol <- Path.definitionNameSegment symbolStr -- let's have a real parser in not too long let author :: Text author = Text.pack $ case (unwords authorStr) of quoted@('"':_) -> (init . tail) quoted bare -> bare pure $ Input.CreateAuthorI symbol author _ -> Left $ showPatternHelp createAuthor ) validInputs :: [InputPattern] validInputs = [ help , helpTopics , load , add , previewAdd , update , previewUpdate , delete , forkLocal , mergeLocal , squashMerge , previewMergeLocal , diffNamespace , names , push , pull , pushExhaustive , pullExhaustive , createPullRequest , loadPullRequest , cd , back , deleteBranch , renameBranch , deletePatch , renamePatch , copyPatch , find , findShallow , findVerbose , view , display , displayTo , ui , docs , findPatch , viewPatch , undo , history , edit , renameTerm , deleteTerm , aliasTerm , renameType , deleteType , aliasType , aliasMany , todo , patch , link , unlink , links , createAuthor , replace , deleteTermReplacement , deleteTypeReplacement , test , ioTest , execute , viewReflog , resetRoot , quit , updateBuiltins , mergeBuiltins , mergeIOBuiltins , dependents, dependencies , debugNumberedArgs , debugBranchHistory , debugFileHashes , debugDumpNamespace , debugDumpNamespaceSimple , debugClearWatchCache ] commandNames :: [String] commandNames = validInputs >>= \i -> I.patternName i : I.aliases i commandNameArg :: ArgumentType commandNameArg = ArgumentType "command" $ \q _ _ _ -> pure (exactComplete q (commandNames <> Map.keys helpTopicsMap)) exactDefinitionOrPathArg :: ArgumentType exactDefinitionOrPathArg = ArgumentType "definition or path" $ bothCompletors (bothCompletors (termCompletor exactComplete) (typeCompletor exactComplete)) (pathCompletor exactComplete (Set.map Path.toText . Branch.deepPaths)) fuzzyDefinitionQueryArg :: ArgumentType fuzzyDefinitionQueryArg = -- todo: improve this ArgumentType "fuzzy definition query" $ bothCompletors (termCompletor fuzzyComplete) (typeCompletor fuzzyComplete) definitionQueryArg :: ArgumentType definitionQueryArg = fuzzyDefinitionQueryArg { typeName = "definition query" } exactDefinitionTypeQueryArg :: ArgumentType exactDefinitionTypeQueryArg = ArgumentType "term definition query" $ typeCompletor exactComplete exactDefinitionTermQueryArg :: ArgumentType exactDefinitionTermQueryArg = ArgumentType "term definition query" $ termCompletor exactComplete typeCompletor :: Applicative m => (String -> [String] -> [Completion]) -> String -> Codebase m v a -> Branch.Branch m -> Path.Absolute -> m [Completion] typeCompletor filterQuery = pathCompletor filterQuery go where go = Set.map HQ'.toText . R.dom . Names.types . Names.names0ToNames . Branch.toNames0 termCompletor :: Applicative m => (String -> [String] -> [Completion]) -> String -> Codebase m v a -> Branch.Branch m -> Path.Absolute -> m [Completion] termCompletor filterQuery = pathCompletor filterQuery go where go = Set.map HQ'.toText . R.dom . Names.terms . Names.names0ToNames . Branch.toNames0 patchArg :: ArgumentType patchArg = ArgumentType "patch" $ pathCompletor exactComplete (Set.map Name.toText . Map.keysSet . Branch.deepEdits) bothCompletors :: (Monad m) => (String -> t2 -> t3 -> t4 -> m [Completion]) -> (String -> t2 -> t3 -> t4 -> m [Completion]) -> String -> t2 -> t3 -> t4 -> m [Completion] bothCompletors c1 c2 q code b currentPath = do suggestions1 <- c1 q code b currentPath suggestions2 <- c2 q code b currentPath pure . fixupCompletion q . nubOrdOn Completion.display $ suggestions1 ++ suggestions2 pathCompletor :: Applicative f => (String -> [String] -> [Completion]) -> (Branch.Branch0 m -> Set Text) -> String -> codebase -> Branch.Branch m -> Path.Absolute -> f [Completion] pathCompletor filterQuery getNames query _code b p = let b0root = Branch.head b b0local = Branch.getAt0 (Path.unabsolute p) b0root -- todo: if these sets are huge, maybe trim results in pure . filterQuery query . map Text.unpack $ toList (getNames b0local) ++ if "." `isPrefixOf` query then map ("." <>) (toList (getNames b0root)) else [] pathArg :: ArgumentType pathArg = ArgumentType "namespace" $ pathCompletor exactComplete (Set.map Path.toText . Branch.deepPaths) newNameArg :: ArgumentType newNameArg = ArgumentType "new-name" $ pathCompletor prefixIncomplete (Set.map ((<> ".") . Path.toText) . Branch.deepPaths) noCompletions :: ArgumentType noCompletions = ArgumentType "word" I.noSuggestions -- Arya: I could imagine completions coming from previous git pulls gitUrlArg :: ArgumentType gitUrlArg = ArgumentType "git-url" $ \input _ _ _ -> case input of "gh" -> complete "https://github.com/" "gl" -> complete "https://gitlab.com/" "bb" -> complete "https://bitbucket.com/" "ghs" -> complete "[email protected]:" "gls" -> complete "[email protected]:" "bbs" -> complete "[email protected]:" _ -> pure [] where complete s = pure [Completion s s False] collectNothings :: (a -> Maybe b) -> [a] -> [a] collectNothings f as = [ a | (Nothing, a) <- map f as `zip` as ] patternFromInput :: Input -> InputPattern patternFromInput = \case Input.PushRemoteBranchI _ _ SyncMode.ShortCircuit -> push Input.PushRemoteBranchI _ _ SyncMode.Complete -> pushExhaustive Input.PullRemoteBranchI _ _ SyncMode.ShortCircuit -> pull Input.PullRemoteBranchI _ _ SyncMode.Complete -> pushExhaustive _ -> error "todo: finish this function" inputStringFromInput :: IsString s => Input -> P.Pretty s inputStringFromInput = \case i@(Input.PushRemoteBranchI rh p' _) -> (P.string . I.patternName $ patternFromInput i) <> (" " <> maybe mempty (P.text . uncurry RemoteRepo.printHead) rh) <> " " <> P.shown p' i@(Input.PullRemoteBranchI ns p' _) -> (P.string . I.patternName $ patternFromInput i) <> (" " <> maybe mempty (P.text . uncurry3 RemoteRepo.printNamespace) ns) <> " " <> P.shown p' _ -> error "todo: finish this function"
unisonweb/platform
parser-typechecker/src/Unison/CommandLine/InputPatterns.hs
mit
54,074
0
24
12,792
13,394
6,980
6,414
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE ScopedTypeVariables #-} import qualified PersistentTest import qualified RenameTest import qualified DataTypeTest import qualified EmptyEntityTest import qualified HtmlTest import qualified EmbedTest import qualified EmbedOrderTest import qualified LargeNumberTest import qualified MaxLenTest import qualified Recursive import qualified SumTypeTest import qualified UniqueTest import qualified MigrationTest import qualified MigrationOnlyTest import qualified PersistUniqueTest import qualified CompositeTest import qualified PrimaryTest import qualified CustomPersistFieldTest import Test.Hspec (hspec) import Test.Hspec.Runner import Init import System.Exit import Control.Monad (unless, when) import Filesystem (isFile, removeFile) import Filesystem.Path.CurrentOS (fromText) import Control.Monad.Trans.Resource (runResourceT) import Control.Exception (handle, IOException) #ifdef WITH_NOSQL #else import Database.Persist.Sql (printMigration, runMigrationUnsafe) setup migration = do printMigration migration runMigrationUnsafe migration #endif toExitCode :: Bool -> ExitCode toExitCode True = ExitSuccess toExitCode False = ExitFailure 1 main :: IO () main = do #ifndef WITH_NOSQL handle (\(_ :: IOException) -> return ()) $ removeFile $ fromText sqlite_database runConn $ do mapM_ setup [ PersistentTest.testMigrate , PersistentTest.noPrefixMigrate , EmbedTest.embedMigrate , EmbedOrderTest.embedOrderMigrate , LargeNumberTest.numberMigrate , UniqueTest.uniqueMigrate , MaxLenTest.maxlenMigrate , Recursive.recursiveMigrate , CompositeTest.compositeMigrate , MigrationTest.migrationMigrate , PersistUniqueTest.migration , RenameTest.migration , CustomPersistFieldTest.customFieldMigrate # ifndef WITH_MYSQL , PrimaryTest.migration # endif ] PersistentTest.cleanDB #endif hspec $ do RenameTest.specs DataTypeTest.specs HtmlTest.specs EmbedTest.specs EmbedOrderTest.specs LargeNumberTest.specs UniqueTest.specs MaxLenTest.specs Recursive.specs SumTypeTest.specs MigrationOnlyTest.specs PersistentTest.specs EmptyEntityTest.specs CompositeTest.specs PersistUniqueTest.specs PrimaryTest.specs CustomPersistFieldTest.specs #ifndef WITH_NOSQL MigrationTest.specs #endif
mkscrg/persistent
persistent-test/test/main.hs
mit
2,399
0
13
401
435
247
188
76
1
{-# LANGUAGE RecordWildCards #-} module BillboardTechnique ( BillboardTechnique (..) , initBillboardTechnique , setBillboardTechniqueVP , setBillboardTechniqueColorUnit , setBillboardCameraPosition , enableBillboardTechnique ) where import Graphics.GLUtil import Graphics.Rendering.OpenGL import Hogldev.Technique data BillboardTechnique = BillboardTechnique { lProgram :: !Program , lVPLocation :: !UniformLocation , lCameraPos :: !UniformLocation , lColorMapLoc :: !UniformLocation } deriving Show initBillboardTechnique :: IO BillboardTechnique initBillboardTechnique = do program <- createProgram addShader program "tutorial27/billboard.vs" VertexShader addShader program "tutorial27/billboard.fs" FragmentShader addShader program "tutorial27/billboard.gs" GeometryShader finalize program wvpLoc <- getUniformLocation program "gVP" cameraPosLoc <- getUniformLocation program "gCameraPos" colorMapLoc <- getUniformLocation program "gColorMap" return BillboardTechnique { lProgram = program , lVPLocation = wvpLoc , lCameraPos = cameraPosLoc , lColorMapLoc = colorMapLoc } setBillboardTechniqueVP :: BillboardTechnique -> [[GLfloat]] -> IO () setBillboardTechniqueVP BillboardTechnique{..} mat = uniformMat lVPLocation $= mat setBillboardCameraPosition :: BillboardTechnique -> Vector3 GLfloat -> IO () setBillboardCameraPosition BillboardTechnique{..} (Vector3 x y z) = uniformVec lCameraPos $= [x, y, z] setBillboardTechniqueColorUnit :: BillboardTechnique -> GLint -> IO () setBillboardTechniqueColorUnit BillboardTechnique{..} textureUnit = uniformScalar lColorMapLoc $= textureUnit enableBillboardTechnique :: BillboardTechnique -> IO () enableBillboardTechnique BillboardTechnique{..} = enableTechnique lProgram
triplepointfive/hogldev
tutorial27/BillboardTechnique.hs
mit
1,900
0
9
353
391
202
189
52
1
-- | A concrete monad transformer that is an instance of -- 'Centrinel.Control.Monad.Class.RegionResult' {-# language GeneralizedNewtypeDeriving #-} module Centrinel.Control.Monad.InferenceResult ( InferenceResultT (..) , runInferenceResultT ) where import Control.Monad.Reader (runReaderT, ReaderT, asks) import qualified Control.Monad.Trans.Reader as Reader import Control.Monad.Trans.Class (MonadTrans(..)) import qualified Data.Map as Map import qualified Language.C.Data.Ident as C import qualified Language.C.Analysis.SemRep as C import qualified Language.C.Analysis.TravMonad as CM import Language.C.Analysis.TravMonad.Instances () import Centrinel.Control.Monad.Class.RegionResult import Centrinel.Region.Region (RegionScheme(..)) import Centrinel.RegionInferenceResult (RegionInferenceResult) import Data.Assoc newtype InferenceResultT m a = InferenceResultT { unInferenceResultT :: ReaderT (Map.Map C.Ident C.TypeDef, RegionInferenceResult) m a } deriving (Functor, Applicative, Monad) instance CM.MonadCError m => CM.MonadCError (InferenceResultT m) where throwTravError = InferenceResultT . lift . CM.throwTravError catchTravError (InferenceResultT c) handler = InferenceResultT (CM.catchTravError c (unInferenceResultT . handler)) recordError = InferenceResultT . lift . CM.recordError getErrors = InferenceResultT $ lift $ CM.getErrors instance CM.MonadName m => CM.MonadName (InferenceResultT m) where genName = lift CM.genName instance CM.MonadSymtab m => CM.MonadSymtab (InferenceResultT m) where getDefTable = lift CM.getDefTable withDefTable = lift . CM.withDefTable instance Monad m => RegionResultMonad (InferenceResultT m) where rrStructTagRegion sr = InferenceResultT $ asks (certain . Map.lookup sr . Data.Assoc.getAssocMap . snd) where certain Nothing = PolyRS certain (Just a) = a rrLookupTypedef ident = InferenceResultT $ asks (certain . Map.lookup ident . fst) where certain Nothing = error "cannot get Nothing from rrLookupTypedef" certain (Just a) = a instance CM.MonadTrav m => CM.MonadTrav (InferenceResultT m) where handleDecl = lift . CM.handleDecl instance MonadTrans InferenceResultT where lift = InferenceResultT . lift runInferenceResultT :: InferenceResultT m a -> Map.Map C.Ident C.TypeDef -> RegionInferenceResult -> m a runInferenceResultT comp = curry (runReaderT (unInferenceResultT comp))
lambdageek/use-c
src/Centrinel/Control/Monad/InferenceResult.hs
mit
2,414
0
13
343
647
359
288
41
1
{-# language QuasiQuotes #-} module Physics.Orbit.Metrology where import Data.Metrology import Data.Metrology.TH import Data.Units.SI.Parser declareDimension "PlaneAngleHyperbolic" declareCanonicalUnit "RadianHyperbolic" [t| PlaneAngleHyperbolic |] (Just "rdh") type instance DefaultUnitOfDim PlaneAngleHyperbolic = RadianHyperbolic type Quantity u = MkQu_ULN u 'DefaultLCSU -- | A measure in seconds. type Time = Quantity [si|s|] -- | A measure in meters. type Distance = Quantity [si| m |] -- | A measure in meters per second. type Speed = Quantity [si| m s^-1 |] -- | A measure in kilograms. type Mass = Quantity [si| kg |] -- | A measure in radians. type Angle = Quantity [si| rad |] -- | A measure in radians (hyperbolic) type AngleH = Quantity RadianHyperbolic -- | A unitless measure. type Unitless = Quantity [si||]
expipiplus1/orbit
src/Physics/Orbit/Metrology.hs
mit
874
0
7
173
170
111
59
-1
-1
-- test with genpath.hs -- base on code for chapter10 (learn_chapter10.hs) import Data.List main = do contents <- getContents let threes = groupsOf 3 (map read $ lines contents) roadSystem = map (\[a,b,c] -> Section a b c) threes path = optimalPath roadSystem pathString = concat $ map (show . fst) path pathPrice = sum $ map snd path putStrLn $ "The best path to take is: " ++ show pathString putStrLn $ "The price is " ++ show pathPrice data Section = Section { getA :: Int, getB :: Int, getC :: Int } deriving (Show) type RoadSystem = [Section] data Label = A | B | C deriving (Show, Eq) type Path = [(Label, Int)] groupsOf :: Int -> [a] -> [[a]] groupsOf 0 _ = undefined groupsOf _ [] = [] groupsOf n xs = take n xs : groupsOf n (drop n xs) roadStep :: (Path, Path) -> Section -> (Path, Path) roadStep (pathA, pathB) (Section a b c) = let priceA = sum $ map snd pathA priceB = sum $ map snd pathB forwardPriceToA = priceA + a crossPriceToA = priceB + b + c forwardPriceToB = priceB + b crossPriceToB = priceA + a + c newPathToA = if forwardPriceToA <= crossPriceToA then (A,a):pathA else (C,c):(B,b):pathB newPathToB = if forwardPriceToB <= crossPriceToB then (B,b):pathB else (C,c):(A,a):pathA in (newPathToA, newPathToB) optimalPath :: RoadSystem -> Path optimalPath roadSystem = let (bestAPath, bestBPath) = foldl roadStep ([],[]) roadSystem in if sum (map snd bestAPath) <= sum (map snd bestBPath) then reverse bestAPath else reverse bestBPath
feliposz/learning-stuff
haskell/heathrow.hs
mit
1,699
0
13
506
633
342
291
39
3
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.SVGExternalResourcesRequired (js_getExternalResourcesRequired, getExternalResourcesRequired, SVGExternalResourcesRequired, castToSVGExternalResourcesRequired, gTypeSVGExternalResourcesRequired) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"externalResourcesRequired\"]" js_getExternalResourcesRequired :: JSRef SVGExternalResourcesRequired -> IO (JSRef SVGAnimatedBoolean) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGExternalResourcesRequired.externalResourcesRequired Mozilla SVGExternalResourcesRequired.externalResourcesRequired documentation> getExternalResourcesRequired :: (MonadIO m) => SVGExternalResourcesRequired -> m (Maybe SVGAnimatedBoolean) getExternalResourcesRequired self = liftIO ((js_getExternalResourcesRequired (unSVGExternalResourcesRequired self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/SVGExternalResourcesRequired.hs
mit
1,791
6
11
265
377
238
139
30
1
-- Copyright 2016 Peter Beard -- Distributed under the GNU GPL v2. For full terms, see the LICENSE file. -- Find the sum of all the multiples of 3 or 5 below 1000. main = putStrLn $ "To run the solution to a specific problem, run 'cabal run problem-xxx'"
PeterBeard/project-euler
haskell/src/main.hs
gpl-2.0
256
0
5
50
13
8
5
1
1
-- 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? import Data.List (permutations, sort,delete) psort :: [Integer] psort = concat . take 1 . drop 999999 . sort $ permutations [0..9] -- alternatively answer :: [Integer] answer = (!! 999999) $ sort $ permutations [0..9] integerAnswer :: Integer integerAnswer = read $ concatMap show answer main :: IO () main = print integerAnswer -- The Haskell Wiki has this implementation which is clever but that I don't quite get yet. -- It is also fast. Like really fast. fac :: Int -> Int fac n = product [1..n] perms :: Eq a => [a] -> Int -> [a] perms [] _= [] perms xs n= x : perms (delete x xs) (mod n m) where m = fac $ length xs - 1 y = div n m x = xs!!y problem24 :: String problem24 = perms "0123456789" 999999
ciderpunx/project_euler_in_haskell
euler024.hs
gpl-2.0
1,160
0
9
259
290
156
134
19
1
{- Code Generation This file is part of AEx. Copyright (C) 2016 Jeffrey Sharp AEx is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AEx is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with AEx. If not, see <http://www.gnu.org/licenses/>. -} module Aex.CodeGen where import Aex.Scope -- TODO data Context = Context { scope :: Scope --, out :: Output }
sharpjs/haskell-learning
src/Aex/CodeGen.hs
gpl-3.0
860
0
8
219
29
19
10
4
0
import XMonad import XMonad.Hooks.DynamicLog import XMonad.Hooks.ManageDocks import XMonad.Util.Run(spawnPipe) import XMonad.Util.EZConfig(additionalKeys) import System.IO import XMonad.Layout.NoBorders import XMonad.Layout.Grid import XMonad.Layout.Tabbed import XMonad.Layout.ThreeColumns import XMonad.Layout.PerWorkspace (onWorkspace) import XMonad.Hooks.EwmhDesktops import XMonad.Hooks.ManageDocks import XMonad.Hooks.SetWMName import XMonad.Hooks.ManageHelpers import XMonad.Hooks.ICCCMFocus import XMonad.StackSet hiding (workspaces) import XMonad.Actions.SpawnOn import XMonad.Actions.CopyWindow import XMonad.Prompt import XMonad.Prompt.Man import XMonad.Prompt.RunOrRaise import Data.List import Data.Monoid import Control.Concurrent import Data.Ratio ((%)) myModMask = mod4Mask -- rebind Mod to Super key myTerminal = "xterm" myBorderWidth = 1 focusColor = "red" textColor = "#000000" lightTextColor = "yellow" backgroundColor = "red" lightBackgroundColor = "white" myUrgentColor = "red" myNormalBorderColor = "green" myFocusedBorderColor = "magenta" myWorkspaces = [ "1:smart" , "2:smart" , "3:smart" , "4:exact" , "5:exact" , "6:exact" , "7:all" , "8:all" , "9:all" , "0:all" , "+:full" ] myLayoutHook = onWorkspace "1:smart" smartLayout $ onWorkspace "2:smart" smartLayout $ onWorkspace "3:smart" smartLayout $ onWorkspace "4:exact" dividebytwoLayout $ onWorkspace "5:exact" dividebytwoLayout $ onWorkspace "6:exact" dividebytwoLayout $ onWorkspace "+:full" fullLayout $ layouts where layouts = smartBorders $ avoidStrutsOn [] $ layoutHook defaultConfig ||| Grid ||| ThreeCol 1 (3/100) (1/2) smartLayout = smartBorders $ avoidStrutsOn [] $ Tall 1 (3/100) (50/100) ||| Full chatLayout = smartBorders $ avoidStruts $ ThreeCol 1 (3/100) (3/100) dividebytwoLayout = smartBorders $ avoidStruts $ Grid fullLayout = smartBorders $ noBorders $ Full myManageHook = (composeAll . concat $ [[isFullscreen --> doFullFloat , className =? "Xmessage" --> doCenterFloat , className =? "XCalc" --> doCenterFloat , className =? "Zenity" --> doCenterFloat , className =? "Xfce4-notifyd" --> doIgnore , className =? "stalonetray" --> doIgnore , className =? "VirtualBox" --> doShift "+:full" , className =? "Pidgin" --> doF (shift "3:chat") , title =? "Save As..." --> doCenterFloat , title =? "Save File" --> doCenterFloat , title =? "Buddy List" --> doF (shift "3:chat") ]]) <+> myFloats <+> manageDocks <+> manageHook defaultConfig myFloats = composeAll . concat $ [[ fmap (c `isInfixOf`) className --> doFloat | c <- myFloats ] ,[ fmap (t `isInfixOf`) title --> doFloat | t <- myOtherFloats ] ] where myFloats = [ "TopLevelShell" , "Blender:Render" , "gimp" , "Gimp" ] myOtherFloats = ["Scope" , "Editor" , "Simulink Library Browser" , "Figure" , "Blender:Render" , "Chess" ] myLogHook xmproc = dynamicLogWithPP $ xmobarPP { ppOutput = hPutStrLn xmproc , ppTitle = xmobarColor lightTextColor "" , ppCurrent = xmobarColor focusColor "" , ppVisible = xmobarColor lightTextColor "" , ppHiddenNoWindows = xmobarColor lightBackgroundColor "" , ppUrgent = xmobarColor myUrgentColor "" , ppSep = " :: " , ppWsSep = " " } myKeys = [ ((myModMask, xK_p), spawn "exe=`~/bin/pydmenu.py` && eval \"exec $exe\"") , ((myModMask .|. shiftMask, xK_l), spawn "slock") , ((myModMask .|. shiftMask, xK_s), sendMessage ToggleStruts) , ((myModMask .|. shiftMask, xK_p), startupPrograms) , ((myModMask .|. shiftMask, xK_m), spawn "bash ~/bin/laptopDock.sh") , ((myModMask, xK_d), spawn "emacs --daemon") , ((myModMask, xK_z), spawn "emacsclient -c") , ((myModMask .|. shiftMask, xK_d), spawn "if ! pkill trayer; then trayer; fi") , ((controlMask, xK_Print), spawn "scrot -s") , ((0, xK_Print), spawn "scrot") , ((0, 0x1008FF11), spawn "amixer set Master 2- && mplayer /usr/share/sounds/freedesktop/stereo/audio-volume-change.oga") -- XF86XK_AudioLowerVolume , ((0, 0x1008FF13), spawn "amixer set Master 2+ && mplayer /usr/share/sounds/freedesktop/stereo/audio-volume-change.oga") -- XF86XK_AudioRaiseVolume , ((0, 0x1008FF12), spawn "amixer set Master toggle && amixer set PCM unmute && mplayer /usr/share/sounds/freedesktop/stereo/audio-volume-change.oga") -- XF86XK_AudioMute ] ++ [((m .|. myModMask, k), windows $ f i) | (i, k) <- zip myWorkspaces [xK_1, xK_2, xK_3, xK_4, xK_5, xK_6, xK_7, xK_8, xK_9, xK_0, xK_plus] , (f, m) <- [(greedyView, 0), (shift, shiftMask)] ] -- NOTE: this is for two things: a) switch from w,e,r to q,w,e for screen selection, and b) swap screens 'locations' if necessary ++ [((m .|. myModMask, k), screenWorkspace sc >>= flip whenJust (windows . f)) -- Replace 'mod1Mask' with your mod key of choice. | (k, sc) <- zip [xK_w, xK_e, xK_r] [1,2,0] -- was [0..] *** change to match your screen order ***, mod-{w,e,r} changed to mod-{q,w,e} *** TODO: map xK_q to somehere! , (f, m) <- [(view, 0), (shift, shiftMask)] ] -- FIXME: this does not work for some reason startupPrograms = do spawnOn "1:smart" "xterm" spawnOn "1:smart" "xterm" spawnOn "2:smart" "emacs" main = do xmproc <- spawnPipe "xmobar ~/.xmonad/xmobar" xmonad $ defaultConfig { terminal = myTerminal , manageHook = myManageHook , layoutHook = myLayoutHook , borderWidth = myBorderWidth , focusedBorderColor = myFocusedBorderColor , normalBorderColor = myNormalBorderColor , modMask = myModMask , logHook = myLogHook xmproc >> ewmhDesktopsLogHook >> setWMName "LG3D" >> takeTopFocus , workspaces = myWorkspaces } `additionalKeys` myKeys
borjatarraso/LIPT
legacyconf/xmonad/xmonad.hs
gpl-3.0
6,789
0
15
2,104
1,486
859
627
152
1
-- Types module. -- By Gregory W. Schwartz -- {- | Collects all application specific types. Used here for Text. -} {-# LANGUAGE OverloadedStrings #-} module Data.Fasta.ByteString.Types where -- Built-in import qualified Data.ByteString.Char8 as B import qualified Data.Map as M -- Algebraic data FastaSequence = FastaSequence { fastaHeader :: B.ByteString , fastaSeq :: B.ByteString } deriving (Eq, Ord, Show) -- Basic type Codon = B.ByteString type AA = Char type Clone = FastaSequence type Germline = FastaSequence -- Advanced -- | A clone is a collection of sequences derived from a germline with -- a specific identifier type CloneMap = M.Map (Int, Germline) [Clone] -- Classes class ShowFasta a where showFasta :: a -> B.ByteString -- Instances instance ShowFasta FastaSequence where showFasta FastaSequence {fastaHeader = x, fastaSeq = y} = B.concat [ ">" , x , "\n" , y ]
GregorySchwartz/fasta
src/Data/Fasta/ByteString/Types.hs
gpl-3.0
1,193
0
9
454
194
122
72
19
0
module TweetParsers where import Data.Aeson.Types import Data.Time.Format (readTime, parseTime) import Control.Applicative import Data.Time.LocalTime (LocalTime) import Control.Monad import Data.Text import System.Locale (defaultTimeLocale) import Debug.Trace data TweetUrl = TweetUrl { expandedUrl :: String , url :: String , indices :: [Integer] , displayUrl :: String } deriving (Eq, Show) data TweetEntities = TweetEntities { urls :: [TweetUrl] } deriving (Eq, Show) data TimelineEntry = TimelineEntry { favorited :: Bool , truncated :: Bool , createdAt :: LocalTime , idStr :: String , entities :: !TweetEntities , text :: !String } deriving (Eq, Show) instance FromJSON TweetEntities where parseJSON (Object v) = TweetEntities <$> v .: "urls" parseJSON _ = mzero instance FromJSON TweetUrl where parseJSON (Object v) = TweetUrl <$> v .: "expanded_url" <*> v .: "url" <*> v .: "indices" <*> v .: "display_url" parseJSON _ = mzero instance FromJSON LocalTime where parseJSON = withText "LocalTime" $ \t -> case parseTime defaultTimeLocale "%a %b %d %T %z %Y" (unpack t) of Just d -> pure d _ -> fail "coudn't parse twitter date" instance FromJSON TimelineEntry where parseJSON (Object v) = TimelineEntry <$> v .: "favorited" <*> v .: "truncated" <*> v .: "created_at" <*> v .: "id_str" <*> v .: "entities" <*> v .: "text" parseJSON _ = mzero type Timeline = [TimelineEntry]
mkawalec/twitterbot
src/TweetParsers.hs
gpl-3.0
2,196
0
17
1,031
449
247
202
52
0
{- Trabalho 2 Resp.: Rodrigo Ferreira Guimarães Disc.: Linguaguem de Programação Orie.: Rodrigo Bonifácio Func.: Expansão da linguaguem F4LAE, que já implementa avaliação outermost, para comportar a Lazy Evaluation de forma completa, ou seja, com a estratégia de compartilhamento. -} module F6LAE where -- Módulos necessários para a construção deste módulo import Prelude {- Traduções semânticas simples e úteis para o desenvolvimento do módulo -} type Nome = String type ArgFormal = String type ID = String type Nivel = Integer type Cod = Integer cod_Tipo = 1 cod_Exp = 2 cod_Ref = 3 cod_Func = 4 nivelInit = 0 -- Caracterização das Funções Nomeada data Func = Func Nome ArgFormal Exp deriving (Show, Eq) -- Lista de Funções Nomeadas na linguagem desenvolvida type Funcs = [Func] {- Caracterização dos Tipos reconhecidos na linguagem ★ Números, restritos a inteiros; ★ Booleanos (true, false); ★ Funções (seta '->'); ★ Não identificado. -} data Tipo = TInt | TBool | TFunc Tipo Tipo | TError deriving (Show, Eq) {- Caracterização da sintaxe abstrata da linguaguem, com as seguintes expressões: ★ Números Inteiros; ★ Expressão lógica; ★ Operações Aritméticas: + Adição; + Subtração. ★ Operações Lógicas: + And; + Or; + Not. ★ Referência a uma Expressão; ★ Atribuição de uma Expressão; ★ Execução de uma Função Nomeada; ★ Desenvolvimento Função Anônima; ★ Execução de uma Função Anônima; ★ Execução condicional, controlada pelo 0. -} data Exp = Num Integer | Bool Bool | Add Exp Exp | Sub Exp Exp | And Exp Exp | Or Exp Exp | Not Exp | Ref ID | Let ID Exp Exp | App Nome Exp | Lambda (ArgFormal, Tipo) Exp | AppLambda Exp Exp | IfZero Exp Exp Exp deriving (Show, Eq) {- Caracterização dos Valores aceitos como resultado das operações realizadas: ★ Números Inteiros; ★ Booleanos; ★ Expressões postergadas. -} data Valor = NumV Integer | BoolV Bool | ExpV Exp deriving (Show, Eq) {- Traduções semânticas de tuplas e de listas úteis para o desenvolvimento deste módulo -} type PesqReg = (ID, Nivel) type RetPesqReg = (Valor, Nivel) type RetPesqTipo = (Tipo, Nivel) type CelReg = (ID, Valor, Nivel) type Registros = [CelReg] type CelTipo = (ID, Tipo, Nivel) type Tipos = [CelTipo] type RetAvaliar = (Valor, Registros) type RetTipos = (Tipo, Tipos) -- Interpretador da linguagem interp :: Exp -> Registros -> Funcs -> Valor interp e1 subPst funcs | (tipoE1 == TError) = error $ "\n" ++ msgErro e1 cod_Tipo ++ "\n" | otherwise = fst $ avaliar e1 subPst funcs nivelInit where tipoE1 = fst $ checkTipo e1 (reg2tipo subPst funcs) funcs nivelInit {- Determinação do valor de uma expressão aprovada para a interpretação -} avaliar :: Exp -> Registros -> Funcs -> Nivel -> RetAvaliar avaliar (Num num) reg _ _ = (NumV num, reg) avaliar (Bool bool) reg _ _ = (BoolV bool, reg) avaliar (Add esq dir) reg funcs nvl = binOp (+) esq dir reg funcs nvl avaliar (Sub esq dir) reg funcs nvl = binOp (-) esq dir reg funcs nvl avaliar (And esq dir) reg funcs nvl = if (valEsq == BoolV True) && (valDir == BoolV True) then (BoolV True, snd $ avaDir2) else (BoolV False, snd $ avaDir2) where avaEsq = avaliar esq reg funcs nvl avaDir = avaliar dir (snd $ avaEsq) funcs nvl vEsq = fst $ avaEsq vDir = fst $ avaDir rDir = snd $ avaDir avaEsq2 = reduzir vEsq rDir funcs nvl valEsq = fst $ avaEsq2 avaDir2 = reduzir vDir rDir funcs nvl valDir = fst $ avaDir2 avaliar (Or esq dir) reg funcs nvl = if (valEsq == BoolV True) || (valDir == BoolV True) then (BoolV True, snd $ avaDir2) else (BoolV False, snd $ avaDir2) where avaEsq = avaliar esq reg funcs nvl avaDir = avaliar dir (snd $ avaEsq) funcs nvl vEsq = fst $ avaEsq vDir = fst $ avaDir rDir = snd $ avaDir avaEsq2 = reduzir vEsq rDir funcs nvl valEsq = fst $ avaEsq2 avaDir2 = reduzir vDir rDir funcs nvl valDir = fst $ avaDir2 avaliar (Not e) reg funcs nvl = if (valE == BoolV True) then (BoolV False, snd $ avaE2) else (BoolV True, snd $ avaE2) where avaE = avaliar e reg funcs nvl vE = fst $ avaE rE = snd $ avaE avaE2 = reduzir vE rE funcs nvl valE = fst $ avaE2 avaliar (Ref var) reg funcs nvl = let val = buscarReg (var, nvl) reg in case val of (Nothing) -> error $ msgErro (Ref var) cod_Ref ++ show (reg) ++ " nvl: " ++ show(nvl) (Just (valReg, nvlReg)) -> (valor, novoReg) where valExp = v2e valReg retorno = avaliar valExp reg funcs nvlReg valExp2 = fst $ retorno regExp = snd $ retorno retorno2 = reduzir valExp2 regExp funcs nvlReg valor = fst $ retorno2 novoReg = atuReg (var, valor, nvl) (snd $ retorno2) avaliar (Let var atri corpo) reg funcs nvl = avaliar corpo novoReg funcs novonvl where novoReg = (var, ExpV atri, nvl):reg novonvl = (nvl + 1) avaliar (App nome arg) reg funcs nvl = let fun = buscarFunc nome funcs in case fun of (Nothing) -> error $ msgErro (Ref nome) cod_Func (Just (Func nomeReg argF corpo)) -> avaliar corpo novoReg funcs novonvl where novoReg = (argF, ExpV arg, nvl):reg novonvl = nvl + 1 avaliar e@(Lambda (var, t) corpo) reg funcs nvl = (ExpV e, reg) avaliar (AppLambda expLmd arg) reg funcs nvl = case expLmd of (Lambda (var, _) corpo) -> avaliar corpo novoReg funcs nvl where valor = avaliar arg reg funcs nvl novoReg = (var, fst $ valor, nvl):(snd $ valor) avaliar (IfZero cond ladoPos ladoNeg) reg funcs nvl = let analisar = reduzir valor novoReg funcs nvl in let condValor = fst $ analisar in if (condValor == NumV 0) then avaliar ladoPos (snd $ analisar) funcs nvl else avaliar ladoNeg (snd $ analisar) funcs nvl where avaliado = avaliar cond reg funcs nvl valor = fst $ avaliado novoReg = snd $ avaliado {- Verificação do tipo de uma expressão candidata a ser interpretada, caso tenha um tipo definido consistente a mesma poderá ser avaliada, enfim -} checkTipo :: Exp -> Tipos -> Funcs -> Nivel -> RetTipos checkTipo (Num _) tipos _ _ = (TInt, tipos) checkTipo (Bool _) tipos _ _ = (TBool, tipos) checkTipo (Add esq dir) tipos funcs nvl = if (tEsq == TInt) && (tDir == TInt) then (TInt, snd $ checkDir) else (TError, snd $ checkDir) where checkEsq = checkTipo esq tipos funcs nvl tEsq = fst $ checkEsq checkDir = checkTipo dir (snd $ checkEsq) funcs nvl tDir = fst $ checkDir checkTipo (Sub esq dir) tipos funcs nvl = if (tEsq == TInt) && (tDir == TInt) then (TInt, snd $ checkDir) else (TError, snd $ checkDir) where checkEsq = checkTipo esq tipos funcs nvl tEsq = fst $ checkEsq checkDir = checkTipo dir (snd $ checkEsq) funcs nvl tDir = fst $ checkDir checkTipo (And esq dir) tipos funcs nvl = if (tEsq == TBool) && (tDir == TBool) then (TBool, snd $ checkDir) else (TError, snd $ checkDir) where checkEsq = checkTipo esq tipos funcs nvl tEsq = fst $ checkEsq checkDir = checkTipo dir (snd $ checkEsq) funcs nvl tDir = fst $ checkDir checkTipo (Or esq dir) tipos funcs nvl = if (tEsq == TBool) && (tDir == TBool) then (TBool, snd $ checkDir) else (TError, snd $ checkDir) where checkEsq = checkTipo esq tipos funcs nvl tEsq = fst $ checkEsq checkDir = checkTipo dir (snd $ checkEsq) funcs nvl tDir = fst $ checkDir checkTipo (Not e) tipos funcs nvl = if ((fst $ checkExp) == TBool) then (TBool, snd $ checkExp) else (TError, snd $ checkExp) where checkExp = checkTipo e tipos funcs nvl checkTipo (Ref var) tipos funcs nvl = let val = buscarTipo (var, nvl) tipos in case val of (Nothing) -> (TError, tipos) (Just (tReg, _)) -> (tReg, tipos) checkTipo (Let var atri corpo) tipos funcs nvl = checkTipo corpo novoTipo funcs novonvl where tipoAtri = fst $ checkTipo atri tipos funcs nvl novoTipo = (var, tipoAtri, nvl):tipos novonvl = nvl + 1 checkTipo (App nome arg) tipos funcs nvl = let fun = buscarFunc nome funcs in case fun of (Nothing) -> (TError, tipos) (Just (Func nomeReg argF corpo)) -> checkTipo corpo novoReg funcs novonvl where tipoArg = fst $ checkTipo arg tipos funcs nvl novoReg = (argF, tipoArg, nvl):tipos novonvl = nvl + 1 checkTipo (Lambda (var, t) corpo) tipos funcs nvl = if (tCorpo /= TError) then (TFunc t tCorpo, snd $ checkCorpo) else (TError, snd $ checkCorpo) where novoTipo = (var, t, nvl):tipos novonvl = nvl + 1 checkCorpo = checkTipo corpo novoTipo funcs novonvl tCorpo = fst $ checkCorpo checkTipo (AppLambda expLmd arg) tipos funcs nvl = let checkExp = checkTipo expLmd tipos funcs nvl in case checkExp of (TError, _) -> (TError, tipos) (TFunc t1 t2, tipos1) -> let checkArg = checkTipo arg tipos1 funcs nvl in if ((fst $ checkArg) == t1) then (t2, snd $ checkArg) else (TError, snd $ checkArg) checkTipo (IfZero cond ladoPos ladoNeg) tipos funcs nvl = if ((tCond == TInt) && (tLP == tLN)) then (tLP, snd $ checkLN) else (TError, snd $ checkCond) where checkCond = checkTipo cond tipos funcs nvl tCond = fst $ checkCond checkLP = checkTipo ladoPos (snd $ checkCond) funcs nvl checkLN = checkTipo ladoNeg (snd $ checkLP) funcs nvl tLP = fst $ checkLP tLN = fst $ checkLN -- Operação aplicável a dois argumentos inteiros binOp :: (Integer -> Integer -> Integer) -> Exp -> Exp -> Registros -> Funcs -> Nivel -> RetAvaliar binOp op e1 e2 reg funcs nvl = (NumV (op n1 n2), snd $ reduz2) where avaE1 = avaliar e1 reg funcs nvl avaE2 = avaliar e2 (snd $ avaE1) funcs nvl regE2 = snd $ avaE2 reduz1 = reduzir (fst $ avaE1) (regE2) funcs nvl reduz2 = reduzir (fst $ avaE2) (snd $ reduz1) funcs nvl (NumV n1) = fst $ reduz1 (NumV n2) = fst $ reduz2 -- Reduzir Valores complexos aos tipos básicos: número ou bool reduzir :: Valor -> Registros -> Funcs -> Nivel -> RetAvaliar reduzir num@(NumV n) reg _ _ = (num, reg) reduzir bool@(BoolV b) reg _ _ = (bool, reg) reduzir (ExpV e) reg funcs nvl = reduzir valor novoReg funcs nvl where avaliado = avaliar e reg funcs nvl valor = fst $ avaliado novoReg = snd $ avaliado -- Atualizador de registro na pilha de compartilhamento atuReg :: CelReg -> Registros -> Registros atuReg _ [] = [] atuReg (i1, v1, n1) ((i2, v2, n2):rabo) = if (i1 == i2) && (n1 >= n2) then ent:rabo else cab:(atuReg ent rabo) where ent = (i1, v1, n2) cab = (i2, v2, n2) {- Busca de um dado Valor e seu Nível de origem, conhecendo-se seu identificador e seu nível atual, no registro de valores cadastrados -} buscarReg :: PesqReg -> Registros -> Maybe RetPesqReg buscarReg _ [] = Nothing buscarReg ent@(i1, n1) ((iReg, vReg, nReg):rabo) = if (i1 == iReg) && (n1 >= nReg) then Just (vReg, nReg) else buscarReg ent rabo {- Busca de uma Função Nomeada, conhecendo-se o seu nome, no registro das funções nomeadas -} buscarFunc :: Nome -> Funcs -> Maybe Func buscarFunc _ [] = Nothing buscarFunc f (fun@(Func n a b):fs) | f == n = Just fun | otherwise = buscarFunc f fs {- Busca de um dado Tipo e seu Nìvel de origem, conhecendo-se o seu identificador e seu nível atual, no registro de tipos cadastrados -} buscarTipo :: PesqReg -> Tipos -> Maybe RetPesqTipo buscarTipo _ [] = Nothing buscarTipo ent@(i1, n1) ((iReg, tReg, nReg):rabo) = if (i1 == iReg) && (n1 >= nReg) then Just (tReg, nReg) else buscarTipo ent rabo -- Conversão de um Valor para uma Expressão v2e :: Valor -> Exp v2e (NumV num) = (Num num) v2e (BoolV num) = (Bool num) v2e (ExpV e1) = e1 -- Transformação de um registro de expressões para o de tipos reg2tipo :: Registros -> Funcs -> Tipos reg2tipo [] _ = [] reg2tipo ((i, val, nvl):regs) funcs = (i, tVal, nvl):(reg2tipo regs funcs) where e = v2e val tVal = fst $ checkTipo e [] funcs nvl {- Mensagem de Erro Padrão na avaliação de tipo de uma expressão -} msgErro :: Exp -> Cod -> String msgErro e1 cod | (cod == cod_Tipo) = "Tipo inconsistente em: " ++ show(e1) | (cod == cod_Ref) = "Variavel não encontrada: " ++ show(e1) ++ " em " -- | (cod == cod_Exp) = "Chegou outro tipo" | (cod == cod_Func) = "Função não encontrada: " ++ show (e1) | otherwise = "Erro não catalogado"
rodrigofegui/UnB
2017.2/Linguagens de Programação/Trab 2_Ver 2/F6LAE.hs
gpl-3.0
15,534
0
16
6,012
4,264
2,300
1,964
265
12
-- | Representations of mathematical 2D shapes. module Graphics.Forensics.Shape ( -- * Shape Shape(..) , rectangle , circle -- * Paths , PathCommand(..) , pathVectors , allPathVectors -- * Properties , area , bounds , center ) where import Data.Vect import Data.Vect.Float.Instances () {-| Some geometrical 2-dimensional 'Shape'. The shape should be assumed to be located at the origin of the coordinate system, but it does not neccessarily have to be positioned in such a way that its center is at the origin. -} data Shape = -- | A rectangle with its lower corner at the origin Rectangle { rectangleSize :: Vec2 } | -- | A circle centered on the origin Circle { circleRadius :: Float } | -- | A freeform path with arbitrary offsets from the origin Path { pathCommands :: [PathCommand] } deriving (Show, Eq) rectangle :: Float -> Float -> Shape rectangle w h = Rectangle (Vec2 w h) circle :: Float -> Shape circle = Circle -- | A command indicating a continuation of a shape data PathCommand = MoveTo Vec2 -- ^ \"Lift the pen\" and put it at the pos | LineTo Vec2 -- ^ Draw a line | QuadTo Vec2 Vec2 -- ^ Draw a quadratic curve | CubicTo Vec2 Vec2 Vec2 -- ^ Draw a cubic spline | Close -- ^ Create a line to the starting position deriving (Show, Eq) -- | If the specified 'PathCommand' has dominant position vectors, -- returns those vectors. pathVectors :: PathCommand -> [Vec2] pathVectors (MoveTo v) = [v] pathVectors (LineTo v) = [v] pathVectors (QuadTo v1 v2) = [v1, v2] pathVectors (CubicTo v1 v2 v3) = [v1, v2, v3] pathVectors Close = [] -- | Converts a sequence of 'PathCommand's into the corresponding -- position vectors. allPathVectors :: [PathCommand] -> [Vec2] allPathVectors = concatMap pathVectors -- | The approximate area of a shape. area :: Shape -> Float area (Circle r) = pi * r * r area (Rectangle v) = _1 v * _2 v area (Path cmds) = abs $ foldr (uncurry polyArea) 0 consecVects where consecVects = vects `zip` tail vects vects = allPathVectors cmds polyArea curr next acc = (_1 curr * _2 next - _1 curr * _2 next) / 2 + acc -- | The approximate bounding vector, covering the size of the whole shape bounds :: Shape -> Vec2 bounds (Rectangle v) = v bounds (Circle r) = Vec2 (2 * r) (2 * r) bounds (Path cmds) = Vec2 x y where x = abs $ maximum xs - minimum xs y = abs $ maximum ys - minimum ys xs = map _1 vecs ys = map _2 vecs vecs = allPathVectors cmds -- | The offset to the center of the shape center :: Shape -> Vec2 center (Rectangle v) = scalarMul 0.5 v center (Circle _) = zero center (Path cmds) = Vec2 x y where x = avg $ map _1 vecs y = avg $ map _2 vecs vecs = allPathVectors cmds avg l = sum l / fromIntegral (length l)
Purview/purview
src/Graphics/Forensics/Shape.hs
gpl-3.0
2,991
0
13
848
774
420
354
68
1
-- (C) Copyright Chris Banks 2011-2012 -- This file is part of The Continuous Pi-calculus Workbench (CPiWB). -- CPiWB is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- CPiWB is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with CPiWB. If not, see <http://www.gnu.org/licenses/>. module CPi.Plot (plotTimeSeries, plotTimeSeriesFiltered, plotTimeSeriesToFile, plotTimeSeriesToFileFiltered, phasePlot2 ) where import Graphics.Rendering.Chart import Graphics.Rendering.Chart.Gtk import Data.Colour.Names import Data.Colour.SRGB import Data.Colour import Data.Accessor import qualified Control.Exception as X import qualified Numeric.LinearAlgebra as LA import CPi.Lib -- Takes data from the ODE solver and plots them plotTimeSeries :: LA.Vector Double -> LA.Matrix Double -> [Species] -> IO () plotTimeSeries ts soln ss = plot (LA.toList ts) (zip (map pretty ss) (map LA.toList (LA.toColumns soln))) -- Plots the data to a PDF file plotTimeSeriesToFile :: LA.Vector Double -> LA.Matrix Double -> [Species] -> String -> IO () plotTimeSeriesToFile ts soln ss file = plotToFile (LA.toList ts) (zip (map pretty ss) (map LA.toList (LA.toColumns soln))) file -- Only plots selected species plotTimeSeriesFiltered :: LA.Vector Double -> LA.Matrix Double -> [Species] -> [Species] -> IO () plotTimeSeriesFiltered ts soln ss ss' = plot (LA.toList ts) (filter (\(s,_)-> s `elem` (map specName ss')) (zip (map specName ss) (map LA.toList (LA.toColumns soln)))) -- Only plots selected species to a PDF file plotTimeSeriesToFileFiltered :: LA.Vector Double -> LA.Matrix Double -> [Species] -> [Species] -> String -> IO () plotTimeSeriesToFileFiltered ts soln ss ss' file = plotToFile (LA.toList ts) (filter (\(s,_)-> s `elem` (map specName ss')) (zip (map pretty ss) (map LA.toList (LA.toColumns soln)))) file -- Plots the time series in a GTK window plot :: [Double] -> [(String,[Double])] -> IO () plot ts dims = renderableToWindow (toRenderable (layout ts dims)) 640 480 -- Plots the time series to a file plotToFile :: [Double] -> [(String,[Double])] -> String -> IO () plotToFile ts dims file = renderableToPDFFile (toRenderable (layout ts dims)) 842 595 file -- gets a plot layout with plots for each dimension layout ts dims = layout1_plots ^= plots ts (colours (length dims)) dims $ -- layout1_legend ^= Nothing $ {-remove to add legend-} defaultLayout1 -- gets the plots for each dimension plots :: [Double] -> [AlphaColour Double] -> [(String,[Double])] -> [Either (Plot Double Double) b] plots _ _ [] = [] plots ts (colour:cs) ((lbl,pts):dims) = (Left $ toPlot $ plot_lines_style ^= solidLine 1 colour $ plot_lines_values ^= [zip ts pts] $ plot_lines_title ^= lbl $ defaultPlotLines ) : plots ts cs dims plots _ [] _ = X.throw $ CpiException "CPi.Plot.plots: Run out of colours!" --------------- -- Phase plots: --------------- -- a plot of two dimensions: phasePlot2 :: LA.Vector Double -> LA.Matrix Double -> [Species] -> (Species,Species) -> IO () phasePlot2 ts soln ss ss' = plotPhase (filter (\(s,_)-> (s == (specName (fst ss'))) || s == (specName (snd ss'))) (zip (map specName ss) (map LA.toList (LA.toColumns soln)))) plotPhase dims = renderableToWindow (toRenderable (layout2phase dims)) 640 480 plotphase pts = Left $ toPlot $ plot_lines_values ^= [pts] $ plot_lines_style ^= solidLine 1 (opaque blue) $ defaultPlotLines layout2phase dims = layout1_plots ^= [plotphase $ zip (snd (dims!!0)) (snd (dims!!1))] -- $ layout1_bottom_axis ^: laxis_generate ^= autoScaledLogAxis defaultLogAxis $ layout1_bottom_axis ^: laxis_title ^= "["++fst (dims!!0)++"]" -- $ layout1_left_axis ^: laxis_generate ^= autoScaledLogAxis defaultLogAxis $ layout1_left_axis ^: laxis_title ^= "["++fst (dims!!1)++"]" $ defaultLayout1 ------------------- -- gives n visually distinct colours -- algorithm taken from the MATLAB 'varycolor' function -- by Daniel Helmick: http://j.mp/xowLV2 colours :: Int -> [AlphaColour Double] colours n | n<=0 = [] | n==1 = [clr 0 1 0] | n==2 = [clr 0 1 0,clr 0 1 1] | n==3 = [clr 0 1 0,clr 0 1 1,clr 0 0 1] | n==4 = [clr 0 1 0,clr 0 1 1,clr 0 0 1,clr 1 0 1] | n==5 = [clr 0 1 0,clr 0 1 1,clr 0 0 1,clr 1 0 1,clr 1 0 0] | n==6 = [clr 0 1 0,clr 0 1 1,clr 0 0 1,clr 1 0 1,clr 1 0 0,clr 0 0 0] | otherwise = sec 1 ++ sec 2 ++ sec 3 ++ sec 4 ++ sec 5 where s = fromIntegral(n `div` 5) e = fromIntegral(n `mod` 5) f x y | x<=y = 1.0 | otherwise = 0.0 g x = [1..(s+(f x e))] sec x | x==1 = [clr 0 1 ((m-1)/(s+(f x e)-1)) | m<-g x] | x==2 = [clr 0 ((s+(f x e)-m)/(s+(f x e))) 1 | m<-[1..(s+(f x e))]] | x==3 = [clr (m/(s+(f x e))) 0 1 | m<-[1..(s+(f x e))]] | x==4 = [clr 1 0 ((s+(f x e)-m)/(s+(f x e))) | m<-[1..(s+(f x e))]] | x==5 = [clr ((s+(f x e)-m)/(s+(f x e))) 0 0 | m<-[1..(s+(f x e))]] | otherwise = undefined clr :: Double -> Double -> Double -> AlphaColour Double clr r g b = opaque(sRGB r g b) {-- test data testT = [0.0,0.1..2500.0]::[Double] testD1 = [0,0.1..2500]::[Double] testD2 = [x*x|x<-[0,0.1..2500]]::[Double] testPlot1 = plot_lines_style ^= solidLine 1 (opaque $ sRGB 0.5 0.5 1) $ plot_lines_values ^= [zip testT testD1] $ plot_lines_title ^= "test1" $ defaultPlotLines testPlot2 = plot_lines_style ^= solidLine 1 (opaque red) $ plot_lines_values ^= [zip testT testD2] $ plot_lines_title ^= "test2" $ defaultPlotLines testLayout = layout1_title ^= "Test graph!" $ layout1_plots ^= [Left (toPlot testPlot1), Left (toPlot testPlot2)] $ defaultLayout1 testPlot = renderableToWindow (toRenderable testLayout) 640 480 -}
chrisbanks/cpiwb
CPi/Plot.hs
gpl-3.0
6,642
0
23
1,709
2,225
1,158
1,067
104
1
{-# LANGUAGE ScopedTypeVariables #-} data MyRecord = forall a b . ( Loooooooooooooooooooooooooooooooong a , Loooooooooooooooooooooooooooooooong b ) => MyConstructor { foo, foo2 :: loooooooooooooooooooooooooooooooong -> loooooooooooooooooooooooooooooooong , bar :: a , bazz :: b } deriving Show
lspitzner/brittany
data/Test56.hs
agpl-3.0
357
0
9
101
59
36
23
-1
-1
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft } func :: asd -> Either a b
lspitzner/brittany
data/Test371.hs
agpl-3.0
140
0
6
18
16
8
8
1
0
-- ReaderT instances --instance MonadTrans (ReaderT r) where -- lift :: m a -> ReaderT r m a -- lift = ReaderT . const
dmp1ce/Haskell-Programming-Exercises
Chapter 26/ReaderT Instances.hs
unlicense
121
0
2
26
6
5
1
1
0
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Lib where import Dhall data User = User { homeDirectory :: Text , privateKeyFile :: Text , publicKeyFile :: Text } deriving (Eq, Generic, Show) instance Interpret User dmain :: IO () dmain = do x <- input auto "./config/top.dhall" print (x :: [User]) {- :set -XOverloadedStrings import Dhall import Data.Text x <- input auto "./config/makeUser.dhall" :: IO (Dhall.Text -> User) -}
haroldcarr/learn-haskell-coq-ml-etc
haskell/playpen/dhall/src/Lib.hs
unlicense
478
0
9
95
101
57
44
14
1
-- Slides for the Continuation Tutorial -- September 23, 2011 -- Toukyou, Japan. module ContTutorial where -- * Continuations are effects, and so we have to use monads -- * The familiar Cont monad from the Monad transformer library -- It is actually the monad of delimited control, as we shall see import Control.Monad import Control.Applicative -- Let's see for simple expressions -- Our earlier example in OCaml: -- * reset (3 + shift (\k -> 5*2)) - 1 -- we have to use monads, and have to write the -- expression in the monadic style -- * The translation is mechanical t1 = liftM2 (-) (reset (liftM2 (+) (return 3) (shift (\k -> liftM2 (*) (return 5) (return 2))))) (return 1) -- * it does look like scheme, doesn't it? -- What is that return? -- Lesson: the type can tell us a lot about the expression: -- after all, a type is an approximation of the expression's -- behavior, which tell us what an expression is without -- running it. Can you guess what liftM2 does? -- Now, what is the type of t1? What does it tell? -- How to run: t1r = runC t1 -- 9 -- * The expression t1 looks ugly, even to a Schemer. -- We can write it better: t1' = liftM2 (-) (reset (liftM2 (+) (return 3) (shift (\k -> return (5*2))))) (return 1) t1'r = runC t1' -- * What did I do? How to justify what I just did? -- An instance of the so-called monad law. -- We can do more simplifications, this time syntactic infixl 6 -!,+! infixl 7 *! (-!),(+!),(*!) :: (Num a, Monad m) => m a -> m a -> m a (-!) = liftM2 (-) (+!) = liftM2 (+) (*!) = liftM2 (*) t12 = reset (return 3 +! shift (\k -> return (5*2))) -! return 1 t12r = runC t12 -- 9 -- We can even remove return and so make the code look -- just like the OCaml code. Doing it is left as a homework. -- We won't do that however. -- * Explicitness in pursuit of insight is no vice. -- More examples -- * (3) fst (reset (fun () -> let x = [] in (x, x))) -- We see that `let' corresponds to `do' t13 = liftM fst (reset $ do x <- shift (\k -> return ("hi","bye")) return (x,x)) t13r = runC t13 -- (1) 5 * reset (fun () -> [] + 3 * 4) -- (2) reset (fun () -> if [] then "hello" else "hi") ^ " world" -- (3) fst (reset (fun () -> let x = [] in (x, x))) -- (4) string_length (reset (fun () -> "x" ^ string_of_int [])) -- *// -- * Rather than extracting a continuation as a function, -- * and then applying to something, we apply it right away. t2 = reset (return 3 +! shift (\k -> return (k (5*2)))) -! return 1 t2r = runC t2 -- 12 -- We can apply the captured continuation more than once within -- the same expression: t3 :: Cont Int Int t3 = reset (return 2 *! shift(\k -> return $ k (k 10))) +! return 1 t3r = runC t3 -- 41 -- * // -- It is time now to introduce the continuation monad and -- show how shift and reset are written in it. newtype Cont w a = Cont{runCont :: (a -> w) -> w} instance Monad (Cont w) where return x = Cont (\k -> k x) Cont m >>= f = Cont (\k -> m (\v -> runCont (f v) k)) instance Functor (Cont w) where fmap f (Cont m) = Cont (\k -> m (k . f)) instance Applicative (Cont w) where pure = return m <*> a = m >>= \h -> fmap h a runC :: Cont w w -> w runC m = runCont m id reset :: Cont a a -> Cont w a reset = return . runC shift :: ((a -> w) -> Cont w w) -> Cont w a shift f = Cont (runC . f) -- * // -- * The big question: is this correct? -- The results seem to be expected so far, -- and in the agreement with OchaCaml. How to make sure they always -- agree? To be certain, we need to say what is the specification -- for shift/reset, and demonstrate that our implementation satisfies -- the specification. -- * Specification: so-called bubble-up semantics -- which was the original semantics of delimited control (prompt/control) -- introduced by Felleisen. That bubble-up semantics was re-discovered -- for the so-called lambda-mu calculus, which is the calculus -- for classical logic. -- shift introduces a bubble -- * shift body --> 泡 id body -- The bubble propagates: -- * (泡 k body) + e1 --> 泡 (\x -> (k x) + e1) body -- * (泡 k body) e1 --> 泡 (\x -> (k x) e1) body -- * f (泡 k body) --> 泡 (\x -> f (k x)) body -- * if (泡 k body) then e1 else e2 --> -- * 泡 (\x -> if (k x) then e1 else e2) body -- reset pricks (eliminates) the bubble -- * reset (泡 k body) --> reset (body (\x -> reset (k x))) -- * reset value --> value -- The bubble-up semantics helps in practice, too: see -- the end of this file. -- * eta-expand shift -- to make the bubble representation explicit shift' body = Cont (\k -> runC (body (\u -> runCont (return u) k))) -- Here is the representation of the bubble: 泡 ctx body = Cont (\k -> runC (body (\u -> runCont (ctx u) k))) -- * // -- * Let us demonstrate that the propagation of the Cont bubble -- * through the application matches the specification: -- * (泡 k body) e1 --> 泡 (\x -> (k x) e1) body proof1 body ctx e = 泡 ctx body <*> e === 泡 ctx body >>= \h -> (fmap h e) === Cont (\ks -> runC (body (\u -> runCont (ctx u) ks))) >>= \h -> (fmap h e) === Cont (\k -> (\ks -> runC (body (\u -> runCont (ctx u) ks))) (\v -> runCont ((\h -> (fmap h e)) v) k)) === Cont (\k -> (\ks -> runC (body (\u -> runCont (ctx u) ks))) (\v -> runCont (fmap v e) k)) === Cont (\k -> runC (body (\u -> runCont (ctx u) (\v -> runCont (fmap v e) k))) ) -- an inner expression is almost the same as -- let g = (\v -> fmap v e) in -- ctx u >>= g === -- Cont (\k1 -> runCont (ctx u) (\v -> runCont (g v) k1)) -- modulo the replacement of k1 with k === Cont (\k -> runC (body (\u -> runCont (ctx u >>= \v -> fmap v e) k))) === let ctx' u = ctx u >>= \v -> fmap v e in Cont (\k -> runC (body (\u -> runCont (ctx' u) k))) === let ctx' u = ctx u >>= \v -> fmap v e in 泡 (\u -> ctx u >>= \v -> fmap v e) body === 泡 (\u -> ctx u <*> e) body -- * To remind the specification rule: -- * (泡 k body) e1 --> 泡 (\x -> (k x) e1) body -- * The result matches the specification. -- * The other bubble-propagation rules can be checked -- * similarly. -- * // -- Our equational proof was written in Haskell! -- It was not mechanically checked. But at least it is well-typed. -- GHC (at present) cannot verify that -- each step in the proof is valid; we need a real theorem prover for -- that. However GHC does verify that the premise is well-typed -- and each step in the proof is type preserving. -- GHC thus already catches many silly errors during equational -- re-writing: mis-substitutions tend to break type preservation. infixl 0 === -- `Propositional equality' -- It should really be proven than `computed'. Therefore, -- the computation below is trivial (===) :: a -> a -> a (===) = const -- * Let us check that the Cont bubble elimination matches -- * the specification: -- * reset (泡 ctx body) --> reset (body (\x -> reset (ctx x))) proof2 body ctx = reset (泡 ctx body) === reset (Cont (\k -> runC (body (\u -> runCont (ctx u) k)))) === return (runC (Cont (\k -> runC (body (\u -> runCont (ctx u) k))))) === return ((\k -> runC (body (\u -> runCont (ctx u) k))) id) === return (runC (body (\u -> runCont (ctx u) id))) === reset (body (\u -> runCont (ctx u) id)) === reset (body (\u -> runC (ctx u))) -- * If the k were of the type a -> Cont w a, we would have -- * added return, and noticed that return . runC === reset -- The continuation captured by shift is a pure -- function (that is, has no effects), we make this -- fact explicit in its type. -- We now demonstrate that the Cont monad reset when applied -- to a value returns the value: -- * reset value --> value proof3 v = reset (return v) === reset (Cont (\k -> k v)) === return (runC (Cont (\k -> k v))) === return ((\k -> k v) id) === return v -- If determining the result of t3 in your head was difficult, -- let us show how the bubble-up semantics helps. -- The bubble-up semantics makes determining the result of t3 -- a pure mechanical operation. t3r' = runC (reset (return 2 *! shift(\k -> return $ k (k 10))) +! return 1) -- shift introduces the bubble === runC (reset (return 2 *! 泡 return (\k -> return $ k (k 10))) +! return 1) -- the bubble propagates up and devours `return 2 *!' === runC (reset (泡 (\x -> return 2 *! return x) (\k -> return $ k (k 10))) +! return 1) -- simplifying using the monad law === runC (reset (泡 (\x -> return (2 * x)) (\k -> return $ k (k 10))) +! return 1) -- reset pricks the bubble === runC (reset ((\k -> return $ k (k 10)) (\x -> runC (return (2 * x)))) +! return 1) -- runC . return === id === runC (reset ((\k -> return $ k (k 10)) (\x -> 2 * x)) +! return 1) -- beta-reduction === runC (reset (return 40) +! return 1) -- reset of a value === runC (return 40 +! return 1) -- monad law (addition of pure expressions) === runC (return 41) === 41
jmgimeno/haskell-playground
src/Continuations/ContTutorial.hs
unlicense
8,980
18
27
2,138
2,444
1,314
1,130
-1
-1
module Gigasecond where -- http://exercism.io/exercises/haskell/gigasecond -- original question: -- One billion seconds... Find out the exact second you were born (if you can). -- Figure out when you will turn (or perhaps when you did turn?) one billion seconds old. Then go mark your calendar. -- http://two-wrongs.com/haskell-time-library-tutorial import Data.Time.Clock fromDay :: UTCTime -> UTCTime fromDay = addUTCTime (1000000000 :: NominalDiffTime)
prt2121/haskell-practice
exercism/gigasecond/Gigasecond.hs
apache-2.0
459
0
6
63
38
25
13
4
1
module Main where import Test.Framework (defaultMain, testGroup) import Test.Framework.Providers.QuickCheck2 main :: IO () main = defaultMain tests qsort :: Ord a => [a] -> [a] qsort [] = [] qsort (x:xs) = qsort lhs ++ [x] ++ qsort rhs where lhs = filter (< x) xs rhs = filter (>= x) xs prop_idempotent :: Ord a => [a] -> Bool prop_idempotent xs = qsort (qsort xs) == qsort xs tests = [ testGroup "qsort" [ testProperty "should be idempotent" (prop_idempotent :: [Integer] -> Bool) ] ]
songpp/my-haskell-playground
tests/Tests.hs
apache-2.0
569
0
11
169
215
116
99
15
1
module Valuation where import Data.List import Data.Maybe {- Project: Disjunctive Frame Unifier Simon Pauw, 2013 -} {- Explanation 1) Basic concepts Formal definitions The unfication mechanisms deals with two types of unifications: Assignments: var x has value a (x,a) Constraints: var x and var y refer to the same value (x,y) The assignment is the result of assigning a specific value to a feature in the language system (i.e. case="nominative") The constraint is the result of equating two features (i.e. np.referent==determiner.referent) Formally: -The constraint (Var,Var) defines an equivalence class over the variables. so for all x,y,z it holds that: 1) (x,x), 2) (x,y) -> (y,x), and 3) (x,y) and (y,z) -> (x,z) -The assignment (Var, Val) is unique for an equivalence class. So for all values a and all variables x and y: 1) (x,a) and (x,y) -> (y,a) and 2) (x,a) and (y,b) -> a = b For efficiency the variables are unique integer values. 2) DisjunctiveFrames Often language can attribute multiple possible assignments to features. For example the english pos 'have': (Example 1) (tense="present", number="singular", person="first") or (tense="present", number="singular", person="second") or (tense="present", number="plural", person="first") or (tense="present", number="plural", person="second") or (tense="present", number="plural", person="third") Which can be summarized as: (Example 2) [(tense="present")] and [(number="singular", person="first") or (number="singular", person="second") or (number="plural")] - Essentially (number="singular", person="first") is a list of features that belong together, which is called a ConjunctiveFrame (CF) - Then, the disjunction [(number="singular", person="first") or (number="singular", person="second") or (number="plural")] is simply a disjunctive list of competing CFs, called a DisjunctiveFrame (DF) - The whole meaning of Example 2 can be represented as a conjunctive list of (DFs) called a ValutationAssignmentFrame (VAF) All possible valuations can be gotten by computing the cartesian product of all DisjunctiveFrames E.g.: [(tense="present")] (X) [(number="singular", person="first"),(number="singular", person="second"),...]= [tense="present", number="singular", person="first"],[tense="present", number="singular", person="second"],... Such an expansian grows exponentially with the amount of disjunctive frames. The key to the present algorithm is exactly to not to expand. Essential to the algorithm is to keep assignments and constraints separted. By garenteeing that the DF can only contain assignments, we can efficiently compute (polynomially instead of exponentially) the effects of adding new information to the valuation. 3) Algorithm Two operations can add information to a Valuation: - addConstraints - addDF The notion of compatibility is essential for understanding these operations - Two assignments are NOT compatible if they relate variables of the same class to different values (x,a) and (y,a) and (x,y), otherwise they are compatible. - Two CFs are compatible if all their assignments are mutually compatible. - a CF (cf1) is compatible with a DF if the DF contains at least one CF (cf2) that is compatible with cf1. - The operation removeIncompatibleCFs takes two DFs (df1 and df2) and removes all CFs in df1 that are not compatible with df2. It returns the modified df1. Everytime we modify a DF we need to check the inpact on the other DFs. - The operation pullDFs takes a token DF and a list of DFs and 1) finds all that are effected by removeIncompatibleCFs (dfs_affected), 2) applies the operation removeIncompatibleCFs to dfs_affected and 3) creates a queue of dfs_affected to which we can recursively apply pullDFs again by using processDFsQueue The last step is needed since the modification of any of the DFs in dfs_affected can have consquences for the remaining DFs Now the two functions are quite simple: - addConstraints 1) adds a number of variable constraints (x, y) to the Valuation. For very constraint (x,y), if (x,y) was already know, nothing happens if (x,y) is not know, the class of variables X of x and the class Y of y are united so that the equivalence relation is maintained (y, y'), (x, x') -> (y',x') This might require the modification of some of the DFs (any pair of assignments (x',a) (y',b), a/=b is now invalidated) 2) the modified DFs are enqueued 3) the function processDFsQueue is called to recursively compute the consquences of the modifications - addDF 1) adds a DF to a queue 2) processDFsQueue calls pullDFs to see if this DF requires the modification of any of the existing DFs, if so, pullDFs recursively computes the consquences For efficiency, the structure is dynamically updated to maintain variable consitency: 1 Every variable class has a canonical member (the smallest value - variables are integers, remember). 2 Every assignment all DFs in the valuation only use the canonical variable. 3 Every time two variable classes are united (e.g. [1,4,7] and [9,20]) a substitution (e.g. 1<-9) is applied to maintain 2) (This is much more efficient then checking for variable equiality all the time.) -} {- ******* Main ******* -} type Var = Int type Val = String -- VarPartitions register variable equilities (contraints) ValutationAssignmentFrame registers the assigments. data Valuation = Valuation VarPartition ValutationAssignmentFrame | INVALID deriving (Show) addDF :: DisjunctiveFrame -> Valuation -> Valuation addDF dF (Valuation varPartition vAF) = let vars = getVarsVAF vAF substitutions = getSubstitutions vars varPartition updatedDF = applySubsititutionsDF substitutions dF in if updatedDF == [] then INVALID else let (_,resultingVAF) = processDFsQueue ([updatedDF],vAF) in if (elem [] resultingVAF) then INVALID else (Valuation varPartition (resolveSingletonDFs resultingVAF)) addConstraints :: [Constraint] -> Valuation -> Valuation addConstraints crs (Valuation partition vAF) = let (substitutions, newPartition) = addConstraintsAndComputeSubstitutions crs partition maybeVAF = applySubstitutions substitutions vAF in if (isJust maybeVAF) then Valuation newPartition (fromJust maybeVAF) else INVALID {- ******* ValutationAssignments ******* -} type ValutationAssignmentFrame = [DisjunctiveFrame] {- ******* ValutationAssignmentFrame ******* -} applySubstitutions :: [(Var, Var)] -> ValutationAssignmentFrame -> Maybe ValutationAssignmentFrame applySubstitutions subs vAF = let processResult = processSubstitutions subs vAF (_, resultingVAF) = processDFsQueue processResult in if (elem [] resultingVAF) then Nothing else Just (resolveSingletonDFs resultingVAF) processSubstitutions :: [(Var, Var)] -> ValutationAssignmentFrame -> (ValutationAssignmentFrame, ValutationAssignmentFrame) processSubstitutions subs vAF = let (affectedAF, nonAffectedAF) = partitionDFsForVars (map (\(x,_) -> x) subs) vAF in ((applySubsititutionsVA subs affectedAF), nonAffectedAF) partitionDFsForVars :: [Var] -> ValutationAssignmentFrame -> (ValutationAssignmentFrame, ValutationAssignmentFrame) partitionDFsForVars vars = partition (affectedByVarsDF vars) processDFsQueue :: (ValutationAssignmentFrame, ValutationAssignmentFrame) -> (ValutationAssignmentFrame, ValutationAssignmentFrame) processDFsQueue ([], vAF) = ([], vAF) processDFsQueue ((headQueue:tailQueue), vAF) = let reducedDF = selfReduction (selfReduction headQueue vAF) tailQueue (newQueue, newVAF) = pullDFs reducedDF (tailQueue, vAF) in processDFsQueue (newQueue, reducedDF:newVAF) pullDFs :: DisjunctiveFrame -> (ValutationAssignmentFrame, ValutationAssignmentFrame) -> (ValutationAssignmentFrame, ValutationAssignmentFrame) pullDFs _ ([], []) = ([], []) pullDFs referenceDF (modifiedDF:tailModifiedDFs, []) = let (newTail, _) = pullDFs referenceDF (tailModifiedDFs,[]) in ((removeIncompatibleCFs modifiedDF referenceDF):newTail, []) pullDFs referenceDF (modifiedDFs, (nonModifiedDF:tailModifiedDFs)) = let touchedDF = removeIncompatibleCFs nonModifiedDF referenceDF (newModifiedDFs, newTail) = pullDFs referenceDF (modifiedDFs, tailModifiedDFs) in if (length touchedDF) == (length nonModifiedDF) then (newModifiedDFs, (touchedDF:newTail)) else ((touchedDF:newModifiedDFs), newTail) selfReduction :: DisjunctiveFrame -> ValutationAssignmentFrame -> DisjunctiveFrame selfReduction modifiableDF [] = modifiableDF selfReduction modifiableDF (referenceDF:tail) = selfReduction (removeIncompatibleCFs modifiableDF referenceDF) tail applySubsititutionsVA :: [(Var, Var)] -> ValutationAssignmentFrame -> ValutationAssignmentFrame applySubsititutionsVA subs = map (applySubsititutionsDF subs) resolveSingletonDFs :: ValutationAssignmentFrame -> ValutationAssignmentFrame resolveSingletonDFs vAF = let (singletonDFs, rest) = partition singleton vAF in if (singletonDFs == []) then rest else (mergeSingletonDFs singletonDFs):rest getVarsVAF :: ValutationAssignmentFrame -> [Var] getVarsVAF dF = nub $ concat $ map getVarsDF dF {- ******* DisjunctiveFrame ******* -} type DisjunctiveFrame = [ConjunctiveFrame] removeIncompatibleCFs :: DisjunctiveFrame -> DisjunctiveFrame -> DisjunctiveFrame removeIncompatibleCFs modifiableFrame referenceFrame = filter (compatibleCFwDF referenceFrame) modifiableFrame compatibleCFwDF :: DisjunctiveFrame -> ConjunctiveFrame -> Bool compatibleCFwDF referenceDFrame cFrame = any (compatibleCFs cFrame) referenceDFrame affectedByVarsDF :: [Var] -> DisjunctiveFrame -> Bool affectedByVarsDF vars = any (affectedByVarsCF vars) applySubsititutionsDF :: [(Var, Var)] -> DisjunctiveFrame -> DisjunctiveFrame applySubsititutionsDF subs df = filter consistentCF $ map (applySubsititutionsCF subs) df mergeSingletonDFs :: [DisjunctiveFrame] -> DisjunctiveFrame mergeSingletonDFs list = foldl1 mergeTwoSingletonDFs list mergeTwoSingletonDFs :: DisjunctiveFrame -> DisjunctiveFrame -> DisjunctiveFrame mergeTwoSingletonDFs [cf1] [cf2] = [mergeTwoCFs cf1 cf2] mergeTwoSingletonDFs [] [] = error "Trying to merge non singleton DFs" getVarsDF :: DisjunctiveFrame -> [Var] getVarsDF dF = nub $ concat $ map getVarsCF dF {- ******* ConjunctiveFrame ******* -} type ConjunctiveFrame = [Assignment] consistentCF :: ConjunctiveFrame -> Bool consistentCF = not.(hasDuplicates fst) compatibleCFs :: ConjunctiveFrame -> ConjunctiveFrame -> Bool compatibleCFs [] _ = True compatibleCFs _ [] = True compatibleCFs (x:xs) (y:ys) = (compatibleAssignments x y) && (compatibleCFs xs (y:ys)) && (compatibleCFs (x:xs) ys) affectedByVarsCF :: [Var] -> ConjunctiveFrame -> Bool affectedByVarsCF vars = any (affectedByVarsAssignment vars) applySubsititutionsCF :: [(Var, Var)] -> ConjunctiveFrame -> ConjunctiveFrame applySubsititutionsCF subs cF = nub $ map (applySubsititutionsAssignment subs) cF mergeTwoCFs :: ConjunctiveFrame -> ConjunctiveFrame -> ConjunctiveFrame mergeTwoCFs cf1 cf2 | compatibleCFs cf1 cf2 = nub $ cf1 ++ cf2 | otherwise = error "Trying to merge non compatible CFs" getVarsCF :: ConjunctiveFrame -> [Var] getVarsCF cF = nub $ map fst cF hasDuplicates :: (Eq b) => (a->b) -> [a] -> Bool hasDuplicates _ [] = False hasDuplicates _ [_] = False hasDuplicates fun (x:xs) = (elemKey fun (fun x) xs) || (hasDuplicates fun xs) elemKey :: (Eq b) => (a -> b) -> b -> [a] -> Bool elemKey _ _ [] = False elemKey fun elt (x:xs) = (elt == (fun x)) || (elemKey fun elt xs) {- ******* Assignment ******* -} type Assignment = (Var, Val) affectedByVarsAssignment :: [Var] -> Assignment -> Bool affectedByVarsAssignment vars (var, _) = elem var vars applySubsititutionsAssignment :: [(Var, Var)] -> Assignment -> Assignment applySubsititutionsAssignment [] a = a applySubsititutionsAssignment ((oldVar,newVar):tail) (var, val) | oldVar == var = (newVar, val) | otherwise = applySubsititutionsAssignment tail (var, val) compatibleAssignments :: Assignment -> Assignment -> Bool compatibleAssignments (var1, val1) (var2, val2) | var1 == var2 = val1 == val2 | otherwise = True {- ******* VarPartition ******* -} type VarClass = [Var] type VarPartition = [VarClass] type Constraint = (Var, Var) consistentVarPartition :: VarPartition -> Bool consistentVarPartition vP = let allVars = concat vP in (length allVars) == (length (nub allVars)) --check that partitions do not have overlapp varClass :: Var -> VarPartition -> VarClass varClass var [] = var:[] varClass var (x:tail) | elem var x = x | otherwise = varClass var tail canonicalVar :: Var -> VarPartition -> Var canonicalVar x p = minimum $ varClass x p canonicalConstraint :: Constraint -> VarPartition -> Constraint canonicalConstraint (var1, var2) partition = let cvar1 = canonicalVar var1 partition cvar2 = canonicalVar var2 partition in ((max cvar1 cvar2), (min cvar1 cvar2)) addressedBy :: Constraint -> VarClass -> Bool addressedBy (var1, var2) c = (elem var1 c) || (elem var2 c) addConstraint :: Constraint -> VarPartition -> VarPartition addConstraint (var1, var2) p | (canonicalVar var1 p) == (canonicalVar var2 p) = p | otherwise = let (varPartition, restPartition) = partition (addressedBy (var1, var2)) p in ((varClass var1 varPartition) ++ (varClass var2 varPartition)):restPartition addConstraintsAndComputeSubstitutions :: [Constraint] -> VarPartition -> ([(Var,Var)], VarPartition) addConstraintsAndComputeSubstitutions crs partition = let vars = (extractVars crs) newPartition = cascade addConstraint crs partition substitutions = (filter (\(a,b) -> a/=b) (nub (map (\x -> ((canonicalVar x partition), (canonicalVar x newPartition))) vars))) in (substitutions, newPartition) extractVars :: [Constraint] -> [Var] extractVars []=[] extractVars ((a,b):tail) = a:b:(extractVars tail) getSubstitutions :: [Var] -> VarPartition -> [(Var, Var)] getSubstitutions vars vp = getSubstitutions' (nub vars) vp getSubstitutions' :: [Var] -> VarPartition -> [(Var, Var)] getSubstitutions' [] _ = [] getSubstitutions' (var:varTail) vp = let cvar = canonicalVar var vp in if cvar == var then getSubstitutions' varTail vp else (var,cvar):(getSubstitutions' varTail vp) {- ******* Auxiliary functions ******* -} mergeSingletons :: [[a]] -> [[a]] mergeSingletons list = let (singletons, rest) = partition singleton list in (concat singletons):rest singleton :: [a] -> Bool singleton [_] = True singleton _ = False cascade :: (b->a->a) -> [b] -> a -> a cascade _ [] arg = arg cascade fun (x:xs) arg = cascade fun xs (fun x arg) {- testcases: :{ processDFsQueue ([[[(1,102)]]], [[[(1,101),(2,102)], [(2,103)]], [[(2,102),(3,103)], [(3,104)]], [[(3,103),(4,104)], [(4,105)]]]) :} :{ processDFsQueue ( [[[(1,102),(4,104)],[(1,102),(4,105)]]], [[[(1,101),(2,102)], [(2,103)]], [[(2,102),(3,103)], [(3,104)]], [[(3,103),(4,104)], [(4,105)]]]) :} :{ processDFsQueue ([[[(1,102)]]], [[[(1,101),(2,102)], [(2,103)]], [[(2,102),(3,103)], [(3,104)]], [[(3,103),(4,104)], [(4,105),(1,102)]]]) :} addDF [[(3,103)]] $ addDF [[(1,101),(2,102)]] $ Valuation [] [] -> Valuation [] [[[(3,101),(1,101),(2,102)]]] addConstraints [(5,3)] $ Valuation [] [[[(3,101),(1,101),(2,102)]]] -> Valuation [[5,3]] [[[(3,101),(1,101),(2,102)]]] addConstraints [(1,3)] $ Valuation [[5,3]] [[[(3,101),(1,101),(2,102)]]] -> Valuation [[1,5,3]] [[[(1,101),(2,102)]]] addConstraints [(1,2)] $ Valuation [[5,3]] [[[(3,101),(1,101),(2,102)]]] -> INVALID addConstraints [(9,2)] $ Valuation [] [[[(1,101),(2,102)], [(2,103)]], [[(2,102),(3,103)], [(3,104)]], [[(3,103),(4,104)], [(4,105)]]] -> Valuation [[9,2]] [[[(1,101),(2,102)],[(2,103)]],[[(2,102),(3,103)],[(3,104)]],[[(3,103),(4,104)],[(4,105)]]] addConstraints [(1,2)] $ Valuation [] [[[(1,101),(2,102)], [(2,103)]], [[(2,102),(3,103)], [(3,104)]], [[(3,103),(4,104)], [(4,105)]]] -> Valuation [[1,2]] [[[(4,105),(3,104),(1,103)]]] addConstraints [(1,2)] $ Valuation [] [[[(1,101),(2,102)], [(2,103)]], [[(2,102),(3,103)], [(3,104)]], [[(3,103),(4,104)], [(1,102)]]] -> INVALID addConstraints [(1,10)] $ addDF [[(1,101),(2,102)],[(2,103)]] $ addDF [[(10,110),(15,115)]] $ Valuation [] [] -}
simonpauw/pcg
system/Valuation.hs
apache-2.0
16,520
11
19
2,705
3,058
1,633
1,425
189
3
{-| A description of the operations that can be performed on nodes and columns. -} module Spark.Core.Internal.OpStructures where import Data.Text as T import Data.Aeson(Value, Value(Null), FromJSON, ToJSON, toJSON) import Data.Aeson.Types(typeMismatch) import qualified Data.Aeson as A import Data.Vector(Vector) import Spark.Core.StructuresInternal import Spark.Core.Internal.TypesStructures(DataType, SQLType, SQLType(unSQLType)) {-| The name of a SQL function. It is one of the predefined SQL functions available in Spark. -} type SqlFunctionName = T.Text {-| The classpath of a UDAF. -} type UdafClassName = T.Text {-| The name of an operator defined in Karps. -} type OperatorName = T.Text {-| A path in the Hadoop File System (HDFS). These paths are usually not created by the user directly. -} data HdfsPath = HdfsPath Text deriving (Eq, Show, Ord) {-| A stamp that defines some notion of uniqueness of the data source. The general contract is that: - stamps can be extracted fast (no need to scan the whole dataset) - if the data gets changed, the stamp will change. Stamps are used for performing aggressing operation caching, so it is better to conservatively update stamps if one is unsure about the freshness of the dataset. For regular files, stamps are computed using the file system time stamps. -} data DataInputStamp = DataInputStamp Text deriving (Eq, Show) {-| The invariant respected by a transform. Depending on the value of the invariant, different optimizations may be available. -} data TransformInvariant = -- | This operator has no special property. It may depend on -- the partitioning layout, the number of partitions, the order -- of elements in the partitions, etc. -- This sort of operator is unwelcome in Karps... Opaque -- | This operator respects the canonical partition order, but may -- not have the same number of elements. -- For example, this could be a flatMap on an RDD (filter, etc.). -- This operator can be used locally with the signature a -> [a] | PartitioningInvariant -- | The strongest invariant. It respects the canonical partition order -- and it outputs the same number of elements. -- This is typically a map. -- This operator can be used locally with the signature a -> a | DirectPartitioningInvariant -- | The dynamic value of locality. -- There is still a tag on it, but it can be easily dropped. data Locality = -- | The data associated to this node is local. It can be materialized -- and accessed by the user. Local -- | The data associated to this node is distributed or not accessible -- locally. It cannot be accessed by the user. | Distributed deriving (Show, Eq) -- ********* PHYSICAL OPERATORS *********** -- These structures declare some operations that correspond to operations found -- in Spark itself, or in the surrounding libraries. -- | An operator defined by default in the release of Karps. -- All other physical operators can be converted to a standard operators. data StandardOperator = StandardOperator { soName :: !OperatorName, soOutputType :: !DataType, soExtra :: !Value } deriving (Eq, Show) -- | A scala method of a singleton object. data ScalaStaticFunctionApplication = ScalaStaticFunctionApplication { sfaObjectName :: !T.Text, sfaMethodName :: !T.Text -- TODO add the input and output types? } -- | The different kinds of column operations that are understood by the -- backend. -- -- These operations describe the physical operations on columns as supported -- by Spark SQL. They can operate on column -> column, column -> row, row->row. -- Of course, not all operators are valid for each configuration. data ColOp = -- | A projection onto a single column -- An extraction is always direct. ColExtraction !FieldPath -- | A function of other columns. -- In this case, the other columns may matter -- TODO(kps) add if this function is partition invariant. -- It should be the case most of the time. | ColFunction !SqlFunctionName !(Vector ColOp) -- | A constant defined for each element. -- The type should be the same as for the column -- A literal is always direct | ColLit !DataType !Value -- | A structure. | ColStruct !(Vector TransformField) deriving (Eq, Show) -- | A field in a structure. data TransformField = TransformField { tfName :: !FieldName, tfValue :: !ColOp } deriving (Eq, Show) -- | The content of a structured transform. data StructuredTransform = InnerOp !ColOp | InnerStruct !(Vector TransformField) deriving (Eq, Show) {-| When applying a UDAF, determines if it should only perform the algebraic portion of the UDAF (initialize+update+merge), or if it also performs the final, non-algebraic step. -} data UdafApplication = Algebraic | Complete deriving (Eq, Show) data AggOp = -- The name of the UDAF and the field path to apply it onto. AggUdaf !UdafApplication !UdafClassName !FieldPath -- A column function that can be applied (sum, max, etc.) | AggFunction !SqlFunctionName !(Vector FieldPath) | AggStruct !(Vector AggField) deriving (Eq, Show) {-| A field in the resulting aggregation transform. -} data AggField = AggField { afName :: !FieldName, afValue :: !AggOp } deriving (Eq, Show) {-| -} data AggTransform = OpaqueAggTransform !StandardOperator | InnerAggOp !AggOp deriving (Eq, Show) {-| The representation of a semi-group law in Spark. This is the basic law used in universal aggregators. It is a function on observables that must respect the following laws: f :: X -> X -> X commutative associative A neutral element is not required for the semi-group laws. However, if used in the context of a universal aggregator, such an element implicitly exists and corresponds to the empty dataset. -} data SemiGroupOperator = -- | A standard operator that happens to respect the semi-group laws. OpaqueSemiGroupLaw !StandardOperator -- | The merging portion of a UDAF | UdafSemiGroupOperator !UdafClassName -- | A SQL operator that happens to respect the semi-group laws. | ColumnSemiGroupLaw !SqlFunctionName deriving (Eq, Show) -- ********* DATASET OPERATORS ************ -- These describe Dataset -> Dataset transforms. data DatasetTransformDesc = DSScalaStaticFunction !ScalaStaticFunctionApplication | DSStructuredTransform !ColOp | DSOperator !StandardOperator -- ****** OBSERVABLE OPERATORS ******* -- These operators describe Observable -> Observable transforms -- **** AGGREGATION OPERATORS ***** -- The different types of aggregators -- The low-level description of a -- The name of the aggregator is the name of the -- Dataset -> Local data transform data UniversalAggregatorOp = UniversalAggregatorOp { uaoMergeType :: !DataType, uaoInitialOuter :: !AggTransform, uaoMergeBuffer :: !SemiGroupOperator } deriving (Eq, Show) data NodeOp2 = -- empty -> local NodeLocalLiteral !DataType !Value -- empty -> distributed | NodeDistributedLiteral !DataType !(Vector Value) -- distributed -> local | NodeStructuredAggregation !AggOp !(Maybe UniversalAggregatorOp) -- distributed -> distributed or local -> local | NodeStructuredTransform2 !Locality !ColOp -- [distributed, local] -> [local, distributed] opaque | NodeOpaqueTransform !Locality StandardOperator deriving (Eq, Show) {-| A pointer to a node that is assumed to be already computed. -} data Pointer = Pointer { pointerComputation :: !ComputationID, pointerPath :: !NodePath } deriving (Eq, Show) {- A node operation. A description of all the operations between nodes. These are the low-level, physical operations that Spark implements. Each node operation is associated with: - a locality - an operation name (implicit or explicit) - a data type - a representation in JSON Additionally, some operations are associated with algebraic invariants to enable programmatic transformations. -} -- TODO: way too many different ops. Restructure into a few fundamental ops with -- options. data NodeOp = -- | An operation between local nodes: [Observable] -> Observable NodeLocalOp StandardOperator -- | An observable literal | NodeLocalLit !DataType !Value -- | A special join that broadcasts a value along a dataset. | NodeBroadcastJoin -- | Some aggregator that does not respect any particular invariant. | NodeOpaqueAggregator StandardOperator -- It implicicty expects a dataframe with 2 fields: -- - the first field is used as a key -- - the second field is passed to the reducer | NodeGroupedReduction !AggOp | NodeReduction !AggTransform -- TODO: remove these -- | A universal aggregator. | NodeAggregatorReduction UniversalAggregatorOp | NodeAggregatorLocalReduction UniversalAggregatorOp -- | A structured transform, performed either on a local node or a -- distributed node. | NodeStructuredTransform !ColOp -- | A distributed dataset (with no partition information) | NodeDistributedLit !DataType !(Vector Value) -- | An opaque distributed operator. | NodeDistributedOp StandardOperator | NodePointer Pointer deriving (Eq, Show) -- | Makes a standard operator with no extra value makeOperator :: T.Text -> SQLType a -> StandardOperator makeOperator txt sqlt = StandardOperator { soName = txt, soOutputType = unSQLType sqlt, soExtra = Null } instance ToJSON HdfsPath where toJSON (HdfsPath p) = toJSON p instance ToJSON DataInputStamp where toJSON (DataInputStamp p) = toJSON p instance FromJSON HdfsPath where parseJSON (A.String p) = return (HdfsPath p) parseJSON x = typeMismatch "HdfsPath" x instance FromJSON DataInputStamp where parseJSON (A.String p) = return (DataInputStamp p) parseJSON x = typeMismatch "DataInputStamp" x
krapsh/kraps-haskell
src/Spark/Core/Internal/OpStructures.hs
apache-2.0
9,819
0
10
1,847
1,103
637
466
213
1
-- http://www.codewars.com/kata/53dc54212259ed3d4f00071c module Sum where import Prelude hiding (sum) sum :: Num a => [a] -> a sum = foldl (+) 0
Bodigrim/katas
src/haskell/8-Sum-Arrays.hs
bsd-2-clause
145
0
7
22
45
27
18
4
1
import Test.Framework (defaultMainWithArgs) import Tests.Parse main :: IO () main = defaultMainWithArgs [ parseTests ] ["--color"]
binarybana/grn-pathways
tests/tests.hs
bsd-2-clause
158
0
6
43
42
23
19
5
1
{-# LANGUAGE CPP, NamedFieldPuns, NondecreasingIndentation, BangPatterns, MultiWayIf #-} {-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-} ----------------------------------------------------------------------------- -- -- GHC Driver -- -- (c) The University of Glasgow 2005 -- ----------------------------------------------------------------------------- module DriverPipeline ( -- Run a series of compilation steps in a pipeline, for a -- collection of source files. oneShot, compileFile, -- Interfaces for the batch-mode driver linkBinary, -- Interfaces for the compilation manager (interpreted/batch-mode) preprocess, compileOne, compileOne', link, -- Exports for hooks to override runPhase and link PhasePlus(..), CompPipeline(..), PipeEnv(..), PipeState(..), phaseOutputFilename, getOutputFilename, getPipeState, getPipeEnv, hscPostBackendPhase, getLocation, setModLocation, setDynFlags, runPhase, exeFileName, maybeCreateManifest, doCpp, linkingNeeded, checkLinkInfo, writeInterfaceOnlyMode ) where #include <ghcplatform.h> #include "HsVersions.h" import GhcPrelude import PipelineMonad import Packages import HeaderInfo import DriverPhases import SysTools import SysTools.ExtraObj import HscMain import Finder import HscTypes hiding ( Hsc ) import Outputable import Module import ErrUtils import DynFlags import Panic import Util import StringBuffer ( hGetStringBuffer, hPutStringBuffer ) import BasicTypes ( SuccessFlag(..) ) import Maybes ( expectJust ) import SrcLoc import LlvmCodeGen ( llvmFixupAsm, llvmVersionList ) import MonadUtils import GHC.Platform import TcRnTypes import ToolSettings import Hooks import qualified GHC.LanguageExtensions as LangExt import FileCleanup import Ar import Bag ( unitBag ) import FastString ( mkFastString ) import GHC.Iface.Utils ( mkFullIface ) import UpdateCafInfos ( updateModDetailsCafInfos ) import Exception import System.Directory import System.FilePath import System.IO import Control.Monad import Data.List ( isInfixOf, intercalate ) import Data.Maybe import Data.Version import Data.Either ( partitionEithers ) import Data.Time ( UTCTime ) -- --------------------------------------------------------------------------- -- Pre-process -- | Just preprocess a file, put the result in a temp. file (used by the -- compilation manager during the summary phase). -- -- We return the augmented DynFlags, because they contain the result -- of slurping in the OPTIONS pragmas preprocess :: HscEnv -> FilePath -- ^ input filename -> Maybe InputFileBuffer -- ^ optional buffer to use instead of reading the input file -> Maybe Phase -- ^ starting phase -> IO (Either ErrorMessages (DynFlags, FilePath)) preprocess hsc_env input_fn mb_input_buf mb_phase = handleSourceError (\err -> return (Left (srcErrorMessages err))) $ ghandle handler $ fmap Right $ do MASSERT2(isJust mb_phase || isHaskellSrcFilename input_fn, text input_fn) (dflags, fp, mb_iface) <- runPipeline anyHsc hsc_env (input_fn, mb_input_buf, fmap RealPhase mb_phase) Nothing -- We keep the processed file for the whole session to save on -- duplicated work in ghci. (Temporary TFL_GhcSession) Nothing{-no ModLocation-} []{-no foreign objects-} -- We stop before Hsc phase so we shouldn't generate an interface MASSERT(isNothing mb_iface) return (dflags, fp) where srcspan = srcLocSpan $ mkSrcLoc (mkFastString input_fn) 1 1 handler (ProgramError msg) = return $ Left $ unitBag $ mkPlainErrMsg (hsc_dflags hsc_env) srcspan $ text msg handler ex = throwGhcExceptionIO ex -- --------------------------------------------------------------------------- -- | Compile -- -- Compile a single module, under the control of the compilation manager. -- -- This is the interface between the compilation manager and the -- compiler proper (hsc), where we deal with tedious details like -- reading the OPTIONS pragma from the source file, converting the -- C or assembly that GHC produces into an object file, and compiling -- FFI stub files. -- -- NB. No old interface can also mean that the source has changed. compileOne :: HscEnv -> ModSummary -- ^ summary for module being compiled -> Int -- ^ module N ... -> Int -- ^ ... of M -> Maybe ModIface -- ^ old interface, if we have one -> Maybe Linkable -- ^ old linkable, if we have one -> SourceModified -> IO HomeModInfo -- ^ the complete HomeModInfo, if successful compileOne = compileOne' Nothing (Just batchMsg) compileOne' :: Maybe TcGblEnv -> Maybe Messager -> HscEnv -> ModSummary -- ^ summary for module being compiled -> Int -- ^ module N ... -> Int -- ^ ... of M -> Maybe ModIface -- ^ old interface, if we have one -> Maybe Linkable -- ^ old linkable, if we have one -> SourceModified -> IO HomeModInfo -- ^ the complete HomeModInfo, if successful compileOne' m_tc_result mHscMessage hsc_env0 summary mod_index nmods mb_old_iface mb_old_linkable source_modified0 = do debugTraceMsg dflags1 2 (text "compile: input file" <+> text input_fnpp) -- Run the pipeline up to codeGen (so everything up to, but not including, STG) (status, plugin_dflags) <- hscIncrementalCompile always_do_basic_recompilation_check m_tc_result mHscMessage hsc_env summary source_modified mb_old_iface (mod_index, nmods) let flags = hsc_dflags hsc_env0 in do unless (gopt Opt_KeepHiFiles flags) $ addFilesToClean flags TFL_CurrentModule $ [ml_hi_file $ ms_location summary] unless (gopt Opt_KeepOFiles flags) $ addFilesToClean flags TFL_GhcSession $ [ml_obj_file $ ms_location summary] -- Use an HscEnv with DynFlags updated with the plugin info (returned from -- hscIncrementalCompile) let hsc_env' = hsc_env{ hsc_dflags = plugin_dflags } case (status, hsc_lang) of (HscUpToDate iface hmi_details, _) -> -- TODO recomp014 triggers this assert. What's going on?! -- ASSERT( isJust mb_old_linkable || isNoLink (ghcLink dflags) ) return $! HomeModInfo iface hmi_details mb_old_linkable (HscNotGeneratingCode iface hmi_details, HscNothing) -> let mb_linkable = if isHsBootOrSig src_flavour then Nothing -- TODO: Questionable. else Just (LM (ms_hs_date summary) this_mod []) in return $! HomeModInfo iface hmi_details mb_linkable (HscNotGeneratingCode _ _, _) -> panic "compileOne HscNotGeneratingCode" (_, HscNothing) -> panic "compileOne HscNothing" (HscUpdateBoot iface hmi_details, HscInterpreted) -> do return $! HomeModInfo iface hmi_details Nothing (HscUpdateBoot iface hmi_details, _) -> do touchObjectFile dflags object_filename return $! HomeModInfo iface hmi_details Nothing (HscUpdateSig iface hmi_details, HscInterpreted) -> do let !linkable = LM (ms_hs_date summary) this_mod [] return $! HomeModInfo iface hmi_details (Just linkable) (HscUpdateSig iface hmi_details, _) -> do output_fn <- getOutputFilename next_phase (Temporary TFL_CurrentModule) basename dflags next_phase (Just location) -- #10660: Use the pipeline instead of calling -- compileEmptyStub directly, so -dynamic-too gets -- handled properly _ <- runPipeline StopLn hsc_env' (output_fn, Nothing, Just (HscOut src_flavour mod_name (HscUpdateSig iface hmi_details))) (Just basename) Persistent (Just location) [] o_time <- getModificationUTCTime object_filename let !linkable = LM o_time this_mod [DotO object_filename] return $! HomeModInfo iface hmi_details (Just linkable) (HscRecomp { hscs_guts = cgguts, hscs_mod_location = mod_location, hscs_mod_details = hmi_details, hscs_partial_iface = partial_iface, hscs_old_iface_hash = mb_old_iface_hash, hscs_iface_dflags = iface_dflags }, HscInterpreted) -> do -- In interpreted mode the regular codeGen backend is not run so we -- generate a interface without codeGen info. final_iface <- mkFullIface hsc_env'{hsc_dflags=iface_dflags} partial_iface Nothing liftIO $ hscMaybeWriteIface dflags final_iface mb_old_iface_hash (ms_location summary) (hasStub, comp_bc, spt_entries) <- hscInteractive hsc_env' cgguts mod_location stub_o <- case hasStub of Nothing -> return [] Just stub_c -> do stub_o <- compileStub hsc_env' stub_c return [DotO stub_o] let hs_unlinked = [BCOs comp_bc spt_entries] unlinked_time = ms_hs_date summary -- Why do we use the timestamp of the source file here, -- rather than the current time? This works better in -- the case where the local clock is out of sync -- with the filesystem's clock. It's just as accurate: -- if the source is modified, then the linkable will -- be out of date. let !linkable = LM unlinked_time (ms_mod summary) (hs_unlinked ++ stub_o) return $! HomeModInfo final_iface hmi_details (Just linkable) (HscRecomp{}, _) -> do output_fn <- getOutputFilename next_phase (Temporary TFL_CurrentModule) basename dflags next_phase (Just location) -- We're in --make mode: finish the compilation pipeline. (_, _, Just (iface, details)) <- runPipeline StopLn hsc_env' (output_fn, Nothing, Just (HscOut src_flavour mod_name status)) (Just basename) Persistent (Just location) [] -- The object filename comes from the ModLocation o_time <- getModificationUTCTime object_filename let !linkable = LM o_time this_mod [DotO object_filename] return $! HomeModInfo iface details (Just linkable) where dflags0 = ms_hspp_opts summary this_mod = ms_mod summary location = ms_location summary input_fn = expectJust "compile:hs" (ml_hs_file location) input_fnpp = ms_hspp_file summary mod_graph = hsc_mod_graph hsc_env0 needsLinker = needsTemplateHaskellOrQQ mod_graph isDynWay = any (== WayDyn) (ways dflags0) isProfWay = any (== WayProf) (ways dflags0) internalInterpreter = not (gopt Opt_ExternalInterpreter dflags0) src_flavour = ms_hsc_src summary mod_name = ms_mod_name summary next_phase = hscPostBackendPhase src_flavour hsc_lang object_filename = ml_obj_file location -- #8180 - when using TemplateHaskell, switch on -dynamic-too so -- the linker can correctly load the object files. This isn't necessary -- when using -fexternal-interpreter. dflags1 = if dynamicGhc && internalInterpreter && not isDynWay && not isProfWay && needsLinker then gopt_set dflags0 Opt_BuildDynamicToo else dflags0 -- #16331 - when no "internal interpreter" is available but we -- need to process some TemplateHaskell or QuasiQuotes, we automatically -- turn on -fexternal-interpreter. dflags2 = if not internalInterpreter && needsLinker then gopt_set dflags1 Opt_ExternalInterpreter else dflags1 basename = dropExtension input_fn -- We add the directory in which the .hs files resides) to the import -- path. This is needed when we try to compile the .hc file later, if it -- imports a _stub.h file that we created here. current_dir = takeDirectory basename old_paths = includePaths dflags2 !prevailing_dflags = hsc_dflags hsc_env0 dflags = dflags2 { includePaths = addQuoteInclude old_paths [current_dir] , log_action = log_action prevailing_dflags } -- use the prevailing log_action / log_finaliser, -- not the one cached in the summary. This is so -- that we can change the log_action without having -- to re-summarize all the source files. hsc_env = hsc_env0 {hsc_dflags = dflags} -- Figure out what lang we're generating hsc_lang = hscTarget dflags -- -fforce-recomp should also work with --make force_recomp = gopt Opt_ForceRecomp dflags source_modified | force_recomp = SourceModified | otherwise = source_modified0 always_do_basic_recompilation_check = case hsc_lang of HscInterpreted -> True _ -> False ----------------------------------------------------------------------------- -- stub .h and .c files (for foreign export support), and cc files. -- The _stub.c file is derived from the haskell source file, possibly taking -- into account the -stubdir option. -- -- The object file created by compiling the _stub.c file is put into a -- temporary file, which will be later combined with the main .o file -- (see the MergeForeigns phase). -- -- Moreover, we also let the user emit arbitrary C/C++/ObjC/ObjC++ files -- from TH, that are then compiled and linked to the module. This is -- useful to implement facilities such as inline-c. compileForeign :: HscEnv -> ForeignSrcLang -> FilePath -> IO FilePath compileForeign _ RawObject object_file = return object_file compileForeign hsc_env lang stub_c = do let phase = case lang of LangC -> Cc LangCxx -> Ccxx LangObjc -> Cobjc LangObjcxx -> Cobjcxx LangAsm -> As True -- allow CPP RawObject -> panic "compileForeign: should be unreachable" (_, stub_o, _) <- runPipeline StopLn hsc_env (stub_c, Nothing, Just (RealPhase phase)) Nothing (Temporary TFL_GhcSession) Nothing{-no ModLocation-} [] return stub_o compileStub :: HscEnv -> FilePath -> IO FilePath compileStub hsc_env stub_c = compileForeign hsc_env LangC stub_c compileEmptyStub :: DynFlags -> HscEnv -> FilePath -> ModLocation -> ModuleName -> IO () compileEmptyStub dflags hsc_env basename location mod_name = do -- To maintain the invariant that every Haskell file -- compiles to object code, we make an empty (but -- valid) stub object file for signatures. However, -- we make sure this object file has a unique symbol, -- so that ranlib on OS X doesn't complain, see -- https://gitlab.haskell.org/ghc/ghc/issues/12673 -- and https://github.com/haskell/cabal/issues/2257 empty_stub <- newTempName dflags TFL_CurrentModule "c" let src = text "int" <+> ppr (mkModule (thisPackage dflags) mod_name) <+> text "= 0;" writeFile empty_stub (showSDoc dflags (pprCode CStyle src)) _ <- runPipeline StopLn hsc_env (empty_stub, Nothing, Nothing) (Just basename) Persistent (Just location) [] return () -- --------------------------------------------------------------------------- -- Link link :: GhcLink -- interactive or batch -> DynFlags -- dynamic flags -> Bool -- attempt linking in batch mode? -> HomePackageTable -- what to link -> IO SuccessFlag -- For the moment, in the batch linker, we don't bother to tell doLink -- which packages to link -- it just tries all that are available. -- batch_attempt_linking should only be *looked at* in batch mode. It -- should only be True if the upsweep was successful and someone -- exports main, i.e., we have good reason to believe that linking -- will succeed. link ghcLink dflags = lookupHook linkHook l dflags ghcLink dflags where l LinkInMemory _ _ _ = if platformMisc_ghcWithInterpreter $ platformMisc dflags then -- Not Linking...(demand linker will do the job) return Succeeded else panicBadLink LinkInMemory l NoLink _ _ _ = return Succeeded l LinkBinary dflags batch_attempt_linking hpt = link' dflags batch_attempt_linking hpt l LinkStaticLib dflags batch_attempt_linking hpt = link' dflags batch_attempt_linking hpt l LinkDynLib dflags batch_attempt_linking hpt = link' dflags batch_attempt_linking hpt panicBadLink :: GhcLink -> a panicBadLink other = panic ("link: GHC not built to link this way: " ++ show other) link' :: DynFlags -- dynamic flags -> Bool -- attempt linking in batch mode? -> HomePackageTable -- what to link -> IO SuccessFlag link' dflags batch_attempt_linking hpt | batch_attempt_linking = do let staticLink = case ghcLink dflags of LinkStaticLib -> True _ -> False home_mod_infos = eltsHpt hpt -- the packages we depend on pkg_deps = concatMap (map fst . dep_pkgs . mi_deps . hm_iface) home_mod_infos -- the linkables to link linkables = map (expectJust "link".hm_linkable) home_mod_infos debugTraceMsg dflags 3 (text "link: linkables are ..." $$ vcat (map ppr linkables)) -- check for the -no-link flag if isNoLink (ghcLink dflags) then do debugTraceMsg dflags 3 (text "link(batch): linking omitted (-c flag given).") return Succeeded else do let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us) obj_files = concatMap getOfiles linkables exe_file = exeFileName staticLink dflags linking_needed <- linkingNeeded dflags staticLink linkables pkg_deps if not (gopt Opt_ForceRecomp dflags) && not linking_needed then do debugTraceMsg dflags 2 (text exe_file <+> text "is up to date, linking not required.") return Succeeded else do compilationProgressMsg dflags ("Linking " ++ exe_file ++ " ...") -- Don't showPass in Batch mode; doLink will do that for us. let link = case ghcLink dflags of LinkBinary -> linkBinary LinkStaticLib -> linkStaticLib LinkDynLib -> linkDynLibCheck other -> panicBadLink other link dflags obj_files pkg_deps debugTraceMsg dflags 3 (text "link: done") -- linkBinary only returns if it succeeds return Succeeded | otherwise = do debugTraceMsg dflags 3 (text "link(batch): upsweep (partially) failed OR" $$ text " Main.main not exported; not linking.") return Succeeded linkingNeeded :: DynFlags -> Bool -> [Linkable] -> [InstalledUnitId] -> IO Bool linkingNeeded dflags staticLink linkables pkg_deps = do -- if the modification time on the executable is later than the -- modification times on all of the objects and libraries, then omit -- linking (unless the -fforce-recomp flag was given). let exe_file = exeFileName staticLink dflags e_exe_time <- tryIO $ getModificationUTCTime exe_file case e_exe_time of Left _ -> return True Right t -> do -- first check object files and extra_ld_inputs let extra_ld_inputs = [ f | FileOption _ f <- ldInputs dflags ] e_extra_times <- mapM (tryIO . getModificationUTCTime) extra_ld_inputs let (errs,extra_times) = partitionEithers e_extra_times let obj_times = map linkableTime linkables ++ extra_times if not (null errs) || any (t <) obj_times then return True else do -- next, check libraries. XXX this only checks Haskell libraries, -- not extra_libraries or -l things from the command line. let pkg_hslibs = [ (collectLibraryPaths dflags [c], lib) | Just c <- map (lookupInstalledPackage dflags) pkg_deps, lib <- packageHsLibs dflags c ] pkg_libfiles <- mapM (uncurry (findHSLib dflags)) pkg_hslibs if any isNothing pkg_libfiles then return True else do e_lib_times <- mapM (tryIO . getModificationUTCTime) (catMaybes pkg_libfiles) let (lib_errs,lib_times) = partitionEithers e_lib_times if not (null lib_errs) || any (t <) lib_times then return True else checkLinkInfo dflags pkg_deps exe_file findHSLib :: DynFlags -> [String] -> String -> IO (Maybe FilePath) findHSLib dflags dirs lib = do let batch_lib_file = if WayDyn `notElem` ways dflags then "lib" ++ lib <.> "a" else mkSOName (targetPlatform dflags) lib found <- filterM doesFileExist (map (</> batch_lib_file) dirs) case found of [] -> return Nothing (x:_) -> return (Just x) -- ----------------------------------------------------------------------------- -- Compile files in one-shot mode. oneShot :: HscEnv -> Phase -> [(String, Maybe Phase)] -> IO () oneShot hsc_env stop_phase srcs = do o_files <- mapM (compileFile hsc_env stop_phase) srcs doLink (hsc_dflags hsc_env) stop_phase o_files compileFile :: HscEnv -> Phase -> (FilePath, Maybe Phase) -> IO FilePath compileFile hsc_env stop_phase (src, mb_phase) = do exists <- doesFileExist src when (not exists) $ throwGhcExceptionIO (CmdLineError ("does not exist: " ++ src)) let dflags = hsc_dflags hsc_env mb_o_file = outputFile dflags ghc_link = ghcLink dflags -- Set by -c or -no-link -- When linking, the -o argument refers to the linker's output. -- otherwise, we use it as the name for the pipeline's output. output -- If we are doing -fno-code, then act as if the output is -- 'Temporary'. This stops GHC trying to copy files to their -- final location. | HscNothing <- hscTarget dflags = Temporary TFL_CurrentModule | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent -- -o foo applies to linker | isJust mb_o_file = SpecificFile -- -o foo applies to the file we are compiling now | otherwise = Persistent ( _, out_file, _) <- runPipeline stop_phase hsc_env (src, Nothing, fmap RealPhase mb_phase) Nothing output Nothing{-no ModLocation-} [] return out_file doLink :: DynFlags -> Phase -> [FilePath] -> IO () doLink dflags stop_phase o_files | not (isStopLn stop_phase) = return () -- We stopped before the linking phase | otherwise = case ghcLink dflags of NoLink -> return () LinkBinary -> linkBinary dflags o_files [] LinkStaticLib -> linkStaticLib dflags o_files [] LinkDynLib -> linkDynLibCheck dflags o_files [] other -> panicBadLink other -- --------------------------------------------------------------------------- -- | Run a compilation pipeline, consisting of multiple phases. -- -- This is the interface to the compilation pipeline, which runs -- a series of compilation steps on a single source file, specifying -- at which stage to stop. -- -- The DynFlags can be modified by phases in the pipeline (eg. by -- OPTIONS_GHC pragmas), and the changes affect later phases in the -- pipeline. runPipeline :: Phase -- ^ When to stop -> HscEnv -- ^ Compilation environment -> (FilePath, Maybe InputFileBuffer, Maybe PhasePlus) -- ^ Pipeline input file name, optional -- buffer and maybe -x suffix -> Maybe FilePath -- ^ original basename (if different from ^^^) -> PipelineOutput -- ^ Output filename -> Maybe ModLocation -- ^ A ModLocation, if this is a Haskell module -> [FilePath] -- ^ foreign objects -> IO (DynFlags, FilePath, Maybe (ModIface, ModDetails)) -- ^ (final flags, output filename, interface) runPipeline stop_phase hsc_env0 (input_fn, mb_input_buf, mb_phase) mb_basename output maybe_loc foreign_os = do let dflags0 = hsc_dflags hsc_env0 -- Decide where dump files should go based on the pipeline output dflags = dflags0 { dumpPrefix = Just (basename ++ ".") } hsc_env = hsc_env0 {hsc_dflags = dflags} (input_basename, suffix) = splitExtension input_fn suffix' = drop 1 suffix -- strip off the . basename | Just b <- mb_basename = b | otherwise = input_basename -- If we were given a -x flag, then use that phase to start from start_phase = fromMaybe (RealPhase (startPhase suffix')) mb_phase isHaskell (RealPhase (Unlit _)) = True isHaskell (RealPhase (Cpp _)) = True isHaskell (RealPhase (HsPp _)) = True isHaskell (RealPhase (Hsc _)) = True isHaskell (HscOut {}) = True isHaskell _ = False isHaskellishFile = isHaskell start_phase env = PipeEnv{ stop_phase, src_filename = input_fn, src_basename = basename, src_suffix = suffix', output_spec = output } when (isBackpackishSuffix suffix') $ throwGhcExceptionIO (UsageError ("use --backpack to process " ++ input_fn)) -- We want to catch cases of "you can't get there from here" before -- we start the pipeline, because otherwise it will just run off the -- end. let happensBefore' = happensBefore dflags case start_phase of RealPhase start_phase' -> -- See Note [Partial ordering on phases] -- Not the same as: (stop_phase `happensBefore` start_phase') when (not (start_phase' `happensBefore'` stop_phase || start_phase' `eqPhase` stop_phase)) $ throwGhcExceptionIO (UsageError ("cannot compile this file to desired target: " ++ input_fn)) HscOut {} -> return () -- Write input buffer to temp file if requested input_fn' <- case (start_phase, mb_input_buf) of (RealPhase real_start_phase, Just input_buf) -> do let suffix = phaseInputExt real_start_phase fn <- newTempName dflags TFL_CurrentModule suffix hdl <- openBinaryFile fn WriteMode -- Add a LINE pragma so reported source locations will -- mention the real input file, not this temp file. hPutStrLn hdl $ "{-# LINE 1 \""++ input_fn ++ "\"#-}" hPutStringBuffer hdl input_buf hClose hdl return fn (_, _) -> return input_fn debugTraceMsg dflags 4 (text "Running the pipeline") r <- runPipeline' start_phase hsc_env env input_fn' maybe_loc foreign_os -- If we are compiling a Haskell module, and doing -- -dynamic-too, but couldn't do the -dynamic-too fast -- path, then rerun the pipeline for the dyn way let dflags = hsc_dflags hsc_env -- NB: Currently disabled on Windows (ref #7134, #8228, and #5987) when (not $ platformOS (targetPlatform dflags) == OSMinGW32) $ do when isHaskellishFile $ whenCannotGenerateDynamicToo dflags $ do debugTraceMsg dflags 4 (text "Running the pipeline again for -dynamic-too") let dflags' = dynamicTooMkDynamicDynFlags dflags hsc_env' <- newHscEnv dflags' _ <- runPipeline' start_phase hsc_env' env input_fn' maybe_loc foreign_os return () return r runPipeline' :: PhasePlus -- ^ When to start -> HscEnv -- ^ Compilation environment -> PipeEnv -> FilePath -- ^ Input filename -> Maybe ModLocation -- ^ A ModLocation, if this is a Haskell module -> [FilePath] -- ^ foreign objects, if we have one -> IO (DynFlags, FilePath, Maybe (ModIface, ModDetails)) -- ^ (final flags, output filename, interface) runPipeline' start_phase hsc_env env input_fn maybe_loc foreign_os = do -- Execute the pipeline... let state = PipeState{ hsc_env, maybe_loc, foreign_os = foreign_os, iface = Nothing } (pipe_state, fp) <- evalP (pipeLoop start_phase input_fn) env state return (pipeStateDynFlags pipe_state, fp, pipeStateModIface pipe_state) -- --------------------------------------------------------------------------- -- outer pipeline loop -- | pipeLoop runs phases until we reach the stop phase pipeLoop :: PhasePlus -> FilePath -> CompPipeline FilePath pipeLoop phase input_fn = do env <- getPipeEnv dflags <- getDynFlags -- See Note [Partial ordering on phases] let happensBefore' = happensBefore dflags stopPhase = stop_phase env case phase of RealPhase realPhase | realPhase `eqPhase` stopPhase -- All done -> -- Sometimes, a compilation phase doesn't actually generate any output -- (eg. the CPP phase when -fcpp is not turned on). If we end on this -- stage, but we wanted to keep the output, then we have to explicitly -- copy the file, remembering to prepend a {-# LINE #-} pragma so that -- further compilation stages can tell what the original filename was. case output_spec env of Temporary _ -> return input_fn output -> do pst <- getPipeState final_fn <- liftIO $ getOutputFilename stopPhase output (src_basename env) dflags stopPhase (maybe_loc pst) when (final_fn /= input_fn) $ do let msg = ("Copying `" ++ input_fn ++"' to `" ++ final_fn ++ "'") line_prag = Just ("{-# LINE 1 \"" ++ src_filename env ++ "\" #-}\n") liftIO $ copyWithHeader dflags msg line_prag input_fn final_fn return final_fn | not (realPhase `happensBefore'` stopPhase) -- Something has gone wrong. We'll try to cover all the cases when -- this could happen, so if we reach here it is a panic. -- eg. it might happen if the -C flag is used on a source file that -- has {-# OPTIONS -fasm #-}. -> panic ("pipeLoop: at phase " ++ show realPhase ++ " but I wanted to stop at phase " ++ show stopPhase) _ -> do liftIO $ debugTraceMsg dflags 4 (text "Running phase" <+> ppr phase) (next_phase, output_fn) <- runHookedPhase phase input_fn dflags case phase of HscOut {} -> do -- We don't pass Opt_BuildDynamicToo to the backend -- in DynFlags. -- Instead it's run twice with flags accordingly set -- per run. let noDynToo = pipeLoop next_phase output_fn let dynToo = do setDynFlags $ gopt_unset dflags Opt_BuildDynamicToo r <- pipeLoop next_phase output_fn setDynFlags $ dynamicTooMkDynamicDynFlags dflags -- TODO shouldn't ignore result: _ <- pipeLoop phase input_fn return r ifGeneratingDynamicToo dflags dynToo noDynToo _ -> pipeLoop next_phase output_fn runHookedPhase :: PhasePlus -> FilePath -> DynFlags -> CompPipeline (PhasePlus, FilePath) runHookedPhase pp input dflags = lookupHook runPhaseHook runPhase dflags pp input dflags -- ----------------------------------------------------------------------------- -- In each phase, we need to know into what filename to generate the -- output. All the logic about which filenames we generate output -- into is embodied in the following function. -- | Computes the next output filename after we run @next_phase@. -- Like 'getOutputFilename', but it operates in the 'CompPipeline' monad -- (which specifies all of the ambient information.) phaseOutputFilename :: Phase{-next phase-} -> CompPipeline FilePath phaseOutputFilename next_phase = do PipeEnv{stop_phase, src_basename, output_spec} <- getPipeEnv PipeState{maybe_loc, hsc_env} <- getPipeState let dflags = hsc_dflags hsc_env liftIO $ getOutputFilename stop_phase output_spec src_basename dflags next_phase maybe_loc -- | Computes the next output filename for something in the compilation -- pipeline. This is controlled by several variables: -- -- 1. 'Phase': the last phase to be run (e.g. 'stopPhase'). This -- is used to tell if we're in the last phase or not, because -- in that case flags like @-o@ may be important. -- 2. 'PipelineOutput': is this intended to be a 'Temporary' or -- 'Persistent' build output? Temporary files just go in -- a fresh temporary name. -- 3. 'String': what was the basename of the original input file? -- 4. 'DynFlags': the obvious thing -- 5. 'Phase': the phase we want to determine the output filename of. -- 6. @Maybe ModLocation@: the 'ModLocation' of the module we're -- compiling; this can be used to override the default output -- of an object file. (TODO: do we actually need this?) getOutputFilename :: Phase -> PipelineOutput -> String -> DynFlags -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath getOutputFilename stop_phase output basename dflags next_phase maybe_location | is_last_phase, Persistent <- output = persistent_fn | is_last_phase, SpecificFile <- output = case outputFile dflags of Just f -> return f Nothing -> panic "SpecificFile: No filename" | keep_this_output = persistent_fn | Temporary lifetime <- output = newTempName dflags lifetime suffix | otherwise = newTempName dflags TFL_CurrentModule suffix where hcsuf = hcSuf dflags odir = objectDir dflags osuf = objectSuf dflags keep_hc = gopt Opt_KeepHcFiles dflags keep_hscpp = gopt Opt_KeepHscppFiles dflags keep_s = gopt Opt_KeepSFiles dflags keep_bc = gopt Opt_KeepLlvmFiles dflags myPhaseInputExt HCc = hcsuf myPhaseInputExt MergeForeign = osuf myPhaseInputExt StopLn = osuf myPhaseInputExt other = phaseInputExt other is_last_phase = next_phase `eqPhase` stop_phase -- sometimes, we keep output from intermediate stages keep_this_output = case next_phase of As _ | keep_s -> True LlvmOpt | keep_bc -> True HCc | keep_hc -> True HsPp _ | keep_hscpp -> True -- See #10869 _other -> False suffix = myPhaseInputExt next_phase -- persistent object files get put in odir persistent_fn | StopLn <- next_phase = return odir_persistent | otherwise = return persistent persistent = basename <.> suffix odir_persistent | Just loc <- maybe_location = ml_obj_file loc | Just d <- odir = d </> persistent | otherwise = persistent -- | The fast LLVM Pipeline skips the mangler and assembler, -- emitting object code directly from llc. -- -- slow: opt -> llc -> .s -> mangler -> as -> .o -- fast: opt -> llc -> .o -- -- hidden flag: -ffast-llvm -- -- if keep-s-files is specified, we need to go through -- the slow pipeline (Kavon Farvardin requested this). fastLlvmPipeline :: DynFlags -> Bool fastLlvmPipeline dflags = not (gopt Opt_KeepSFiles dflags) && gopt Opt_FastLlvm dflags -- | LLVM Options. These are flags to be passed to opt and llc, to ensure -- consistency we list them in pairs, so that they form groups. llvmOptions :: DynFlags -> [(String, String)] -- ^ pairs of (opt, llc) arguments llvmOptions dflags = [("-enable-tbaa -tbaa", "-enable-tbaa") | gopt Opt_LlvmTBAA dflags ] ++ [("-relocation-model=" ++ rmodel ,"-relocation-model=" ++ rmodel) | not (null rmodel)] ++ [("-stack-alignment=" ++ (show align) ,"-stack-alignment=" ++ (show align)) | align > 0 ] ++ [("", "-filetype=obj") | fastLlvmPipeline dflags ] -- Additional llc flags ++ [("", "-mcpu=" ++ mcpu) | not (null mcpu) , not (any (isInfixOf "-mcpu") (getOpts dflags opt_lc)) ] ++ [("", "-mattr=" ++ attrs) | not (null attrs) ] where target = platformMisc_llvmTarget $ platformMisc dflags Just (LlvmTarget _ mcpu mattr) = lookup target (llvmTargets $ llvmConfig dflags) -- Relocation models rmodel | gopt Opt_PIC dflags = "pic" | positionIndependent dflags = "pic" | WayDyn `elem` ways dflags = "dynamic-no-pic" | otherwise = "static" align :: Int align = case platformArch (targetPlatform dflags) of ArchX86_64 | isAvxEnabled dflags -> 32 _ -> 0 attrs :: String attrs = intercalate "," $ mattr ++ ["+sse42" | isSse4_2Enabled dflags ] ++ ["+sse2" | isSse2Enabled dflags ] ++ ["+sse" | isSseEnabled dflags ] ++ ["+avx512f" | isAvx512fEnabled dflags ] ++ ["+avx2" | isAvx2Enabled dflags ] ++ ["+avx" | isAvxEnabled dflags ] ++ ["+avx512cd"| isAvx512cdEnabled dflags ] ++ ["+avx512er"| isAvx512erEnabled dflags ] ++ ["+avx512pf"| isAvx512pfEnabled dflags ] ++ ["+bmi" | isBmiEnabled dflags ] ++ ["+bmi2" | isBmi2Enabled dflags ] -- ----------------------------------------------------------------------------- -- | Each phase in the pipeline returns the next phase to execute, and the -- name of the file in which the output was placed. -- -- We must do things dynamically this way, because we often don't know -- what the rest of the phases will be until part-way through the -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning -- of a source file can change the latter stages of the pipeline from -- taking the LLVM route to using the native code generator. -- runPhase :: PhasePlus -- ^ Run this phase -> FilePath -- ^ name of the input file -> DynFlags -- ^ for convenience, we pass the current dflags in -> CompPipeline (PhasePlus, -- next phase to run FilePath) -- output filename -- Invariant: the output filename always contains the output -- Interesting case: Hsc when there is no recompilation to do -- Then the output filename is still a .o file ------------------------------------------------------------------------------- -- Unlit phase runPhase (RealPhase (Unlit sf)) input_fn dflags = do output_fn <- phaseOutputFilename (Cpp sf) let flags = [ -- The -h option passes the file name for unlit to -- put in a #line directive SysTools.Option "-h" -- See Note [Don't normalise input filenames]. , SysTools.Option $ escape input_fn , SysTools.FileOption "" input_fn , SysTools.FileOption "" output_fn ] liftIO $ SysTools.runUnlit dflags flags return (RealPhase (Cpp sf), output_fn) where -- escape the characters \, ", and ', but don't try to escape -- Unicode or anything else (so we don't use Util.charToC -- here). If we get this wrong, then in -- Coverage.isGoodTickSrcSpan where we check that the filename in -- a SrcLoc is the same as the source filenaame, the two will -- look bogusly different. See test: -- libraries/hpc/tests/function/subdir/tough2.hs escape ('\\':cs) = '\\':'\\': escape cs escape ('\"':cs) = '\\':'\"': escape cs escape ('\'':cs) = '\\':'\'': escape cs escape (c:cs) = c : escape cs escape [] = [] ------------------------------------------------------------------------------- -- Cpp phase : (a) gets OPTIONS out of file -- (b) runs cpp if necessary runPhase (RealPhase (Cpp sf)) input_fn dflags0 = do src_opts <- liftIO $ getOptionsFromFile dflags0 input_fn (dflags1, unhandled_flags, warns) <- liftIO $ parseDynamicFilePragma dflags0 src_opts setDynFlags dflags1 liftIO $ checkProcessArgsResult dflags1 unhandled_flags if not (xopt LangExt.Cpp dflags1) then do -- we have to be careful to emit warnings only once. unless (gopt Opt_Pp dflags1) $ liftIO $ handleFlagWarnings dflags1 warns -- no need to preprocess CPP, just pass input file along -- to the next phase of the pipeline. return (RealPhase (HsPp sf), input_fn) else do output_fn <- phaseOutputFilename (HsPp sf) liftIO $ doCpp dflags1 True{-raw-} input_fn output_fn -- re-read the pragmas now that we've preprocessed the file -- See #2464,#3457 src_opts <- liftIO $ getOptionsFromFile dflags0 output_fn (dflags2, unhandled_flags, warns) <- liftIO $ parseDynamicFilePragma dflags0 src_opts liftIO $ checkProcessArgsResult dflags2 unhandled_flags unless (gopt Opt_Pp dflags2) $ liftIO $ handleFlagWarnings dflags2 warns -- the HsPp pass below will emit warnings setDynFlags dflags2 return (RealPhase (HsPp sf), output_fn) ------------------------------------------------------------------------------- -- HsPp phase runPhase (RealPhase (HsPp sf)) input_fn dflags = do if not (gopt Opt_Pp dflags) then -- no need to preprocess, just pass input file along -- to the next phase of the pipeline. return (RealPhase (Hsc sf), input_fn) else do PipeEnv{src_basename, src_suffix} <- getPipeEnv let orig_fn = src_basename <.> src_suffix output_fn <- phaseOutputFilename (Hsc sf) liftIO $ SysTools.runPp dflags ( [ SysTools.Option orig_fn , SysTools.Option input_fn , SysTools.FileOption "" output_fn ] ) -- re-read pragmas now that we've parsed the file (see #3674) src_opts <- liftIO $ getOptionsFromFile dflags output_fn (dflags1, unhandled_flags, warns) <- liftIO $ parseDynamicFilePragma dflags src_opts setDynFlags dflags1 liftIO $ checkProcessArgsResult dflags1 unhandled_flags liftIO $ handleFlagWarnings dflags1 warns return (RealPhase (Hsc sf), output_fn) ----------------------------------------------------------------------------- -- Hsc phase -- Compilation of a single module, in "legacy" mode (_not_ under -- the direction of the compilation manager). runPhase (RealPhase (Hsc src_flavour)) input_fn dflags0 = do -- normal Hsc mode, not mkdependHS PipeEnv{ stop_phase=stop, src_basename=basename, src_suffix=suff } <- getPipeEnv -- we add the current directory (i.e. the directory in which -- the .hs files resides) to the include path, since this is -- what gcc does, and it's probably what you want. let current_dir = takeDirectory basename new_includes = addQuoteInclude paths [current_dir] paths = includePaths dflags0 dflags = dflags0 { includePaths = new_includes } setDynFlags dflags -- gather the imports and module name (hspp_buf,mod_name,imps,src_imps) <- liftIO $ do do buf <- hGetStringBuffer input_fn eimps <- getImports dflags buf input_fn (basename <.> suff) case eimps of Left errs -> throwErrors errs Right (src_imps,imps,L _ mod_name) -> return (Just buf, mod_name, imps, src_imps) -- Take -o into account if present -- Very like -ohi, but we must *only* do this if we aren't linking -- (If we're linking then the -o applies to the linked thing, not to -- the object file for one module.) -- Note the nasty duplication with the same computation in compileFile above location <- getLocation src_flavour mod_name let o_file = ml_obj_file location -- The real object file hi_file = ml_hi_file location hie_file = ml_hie_file location dest_file | writeInterfaceOnlyMode dflags = hi_file | otherwise = o_file -- Figure out if the source has changed, for recompilation avoidance. -- -- Setting source_unchanged to True means that M.o (or M.hie) seems -- to be up to date wrt M.hs; so no need to recompile unless imports have -- changed (which the compiler itself figures out). -- Setting source_unchanged to False tells the compiler that M.o is out of -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless. src_timestamp <- liftIO $ getModificationUTCTime (basename <.> suff) source_unchanged <- liftIO $ if not (isStopLn stop) -- SourceModified unconditionally if -- (a) recompilation checker is off, or -- (b) we aren't going all the way to .o file (e.g. ghc -S) then return SourceModified -- Otherwise look at file modification dates else do dest_file_mod <- sourceModified dest_file src_timestamp hie_file_mod <- if gopt Opt_WriteHie dflags then sourceModified hie_file src_timestamp else pure False if dest_file_mod || hie_file_mod then return SourceModified else return SourceUnmodified PipeState{hsc_env=hsc_env'} <- getPipeState -- Tell the finder cache about this module mod <- liftIO $ addHomeModuleToFinder hsc_env' mod_name location -- Make the ModSummary to hand to hscMain let mod_summary = ModSummary { ms_mod = mod, ms_hsc_src = src_flavour, ms_hspp_file = input_fn, ms_hspp_opts = dflags, ms_hspp_buf = hspp_buf, ms_location = location, ms_hs_date = src_timestamp, ms_obj_date = Nothing, ms_parsed_mod = Nothing, ms_iface_date = Nothing, ms_hie_date = Nothing, ms_textual_imps = imps, ms_srcimps = src_imps } -- run the compiler! let msg hsc_env _ what _ = oneShotMsg hsc_env what (result, plugin_dflags) <- liftIO $ hscIncrementalCompile True Nothing (Just msg) hsc_env' mod_summary source_unchanged Nothing (1,1) -- In the rest of the pipeline use the dflags with plugin info setDynFlags plugin_dflags return (HscOut src_flavour mod_name result, panic "HscOut doesn't have an input filename") runPhase (HscOut src_flavour mod_name result) _ dflags = do location <- getLocation src_flavour mod_name setModLocation location let o_file = ml_obj_file location -- The real object file hsc_lang = hscTarget dflags next_phase = hscPostBackendPhase src_flavour hsc_lang case result of HscNotGeneratingCode _ _ -> return (RealPhase StopLn, panic "No output filename from Hsc when no-code") HscUpToDate _ _ -> do liftIO $ touchObjectFile dflags o_file -- The .o file must have a later modification date -- than the source file (else we wouldn't get Nothing) -- but we touch it anyway, to keep 'make' happy (we think). return (RealPhase StopLn, o_file) HscUpdateBoot _ _ -> do -- In the case of hs-boot files, generate a dummy .o-boot -- stamp file for the benefit of Make liftIO $ touchObjectFile dflags o_file return (RealPhase StopLn, o_file) HscUpdateSig _ _ -> do -- We need to create a REAL but empty .o file -- because we are going to attempt to put it in a library PipeState{hsc_env=hsc_env'} <- getPipeState let input_fn = expectJust "runPhase" (ml_hs_file location) basename = dropExtension input_fn liftIO $ compileEmptyStub dflags hsc_env' basename location mod_name return (RealPhase StopLn, o_file) HscRecomp { hscs_guts = cgguts, hscs_mod_location = mod_location, hscs_mod_details = mod_details, hscs_partial_iface = partial_iface, hscs_old_iface_hash = mb_old_iface_hash, hscs_iface_dflags = iface_dflags } -> do output_fn <- phaseOutputFilename next_phase PipeState{hsc_env=hsc_env'} <- getPipeState (outputFilename, mStub, foreign_files, caf_infos) <- liftIO $ hscGenHardCode hsc_env' cgguts mod_location output_fn final_iface <- liftIO (mkFullIface hsc_env'{hsc_dflags=iface_dflags} partial_iface (Just caf_infos)) let final_mod_details = {-# SCC updateModDetailsCafInfos #-} updateModDetailsCafInfos caf_infos mod_details setIface final_iface final_mod_details -- See Note [Writing interface files] let if_dflags = dflags `gopt_unset` Opt_BuildDynamicToo liftIO $ hscMaybeWriteIface if_dflags final_iface mb_old_iface_hash mod_location stub_o <- liftIO (mapM (compileStub hsc_env') mStub) foreign_os <- liftIO $ mapM (uncurry (compileForeign hsc_env')) foreign_files setForeignOs (maybe [] return stub_o ++ foreign_os) return (RealPhase next_phase, outputFilename) ----------------------------------------------------------------------------- -- Cmm phase runPhase (RealPhase CmmCpp) input_fn dflags = do output_fn <- phaseOutputFilename Cmm liftIO $ doCpp dflags False{-not raw-} input_fn output_fn return (RealPhase Cmm, output_fn) runPhase (RealPhase Cmm) input_fn dflags = do let hsc_lang = hscTarget dflags let next_phase = hscPostBackendPhase HsSrcFile hsc_lang output_fn <- phaseOutputFilename next_phase PipeState{hsc_env} <- getPipeState liftIO $ hscCompileCmmFile hsc_env input_fn output_fn return (RealPhase next_phase, output_fn) ----------------------------------------------------------------------------- -- Cc phase runPhase (RealPhase cc_phase) input_fn dflags | any (cc_phase `eqPhase`) [Cc, Ccxx, HCc, Cobjc, Cobjcxx] = do let platform = targetPlatform dflags hcc = cc_phase `eqPhase` HCc let cmdline_include_paths = includePaths dflags -- HC files have the dependent packages stamped into them pkgs <- if hcc then liftIO $ getHCFilePackages input_fn else return [] -- add package include paths even if we're just compiling .c -- files; this is the Value Add(TM) that using ghc instead of -- gcc gives you :) pkg_include_dirs <- liftIO $ getPackageIncludePath dflags pkgs let include_paths_global = foldr (\ x xs -> ("-I" ++ x) : xs) [] (includePathsGlobal cmdline_include_paths ++ pkg_include_dirs) let include_paths_quote = foldr (\ x xs -> ("-iquote" ++ x) : xs) [] (includePathsQuote cmdline_include_paths) let include_paths = include_paths_quote ++ include_paths_global -- pass -D or -optP to preprocessor when compiling foreign C files -- (#16737). Doing it in this way is simpler and also enable the C -- compiler to perform preprocessing and parsing in a single pass, -- but it may introduce inconsistency if a different pgm_P is specified. let more_preprocessor_opts = concat [ ["-Xpreprocessor", i] | not hcc , i <- getOpts dflags opt_P ] let gcc_extra_viac_flags = extraGccViaCFlags dflags let pic_c_flags = picCCOpts dflags let verbFlags = getVerbFlags dflags -- cc-options are not passed when compiling .hc files. Our -- hc code doesn't not #include any header files anyway, so these -- options aren't necessary. pkg_extra_cc_opts <- liftIO $ if hcc then return [] else getPackageExtraCcOpts dflags pkgs framework_paths <- if platformUsesFrameworks platform then do pkgFrameworkPaths <- liftIO $ getPackageFrameworkPath dflags pkgs let cmdlineFrameworkPaths = frameworkPaths dflags return $ map ("-F"++) (cmdlineFrameworkPaths ++ pkgFrameworkPaths) else return [] let cc_opt | optLevel dflags >= 2 = [ "-O2" ] | optLevel dflags >= 1 = [ "-O" ] | otherwise = [] -- Decide next phase let next_phase = As False output_fn <- phaseOutputFilename next_phase let more_hcc_opts = -- on x86 the floating point regs have greater precision -- than a double, which leads to unpredictable results. -- By default, we turn this off with -ffloat-store unless -- the user specified -fexcess-precision. (if platformArch platform == ArchX86 && not (gopt Opt_ExcessPrecision dflags) then [ "-ffloat-store" ] else []) ++ -- gcc's -fstrict-aliasing allows two accesses to memory -- to be considered non-aliasing if they have different types. -- This interacts badly with the C code we generate, which is -- very weakly typed, being derived from C--. ["-fno-strict-aliasing"] ghcVersionH <- liftIO $ getGhcVersionPathName dflags liftIO $ SysTools.runCc (phaseForeignLanguage cc_phase) dflags ( [ SysTools.FileOption "" input_fn , SysTools.Option "-o" , SysTools.FileOption "" output_fn ] ++ map SysTools.Option ( pic_c_flags -- Stub files generated for foreign exports references the runIO_closure -- and runNonIO_closure symbols, which are defined in the base package. -- These symbols are imported into the stub.c file via RtsAPI.h, and the -- way we do the import depends on whether we're currently compiling -- the base package or not. ++ (if platformOS platform == OSMinGW32 && thisPackage dflags == baseUnitId then [ "-DCOMPILING_BASE_PACKAGE" ] else []) -- We only support SparcV9 and better because V8 lacks an atomic CAS -- instruction. Note that the user can still override this -- (e.g., -mcpu=ultrasparc) as GCC picks the "best" -mcpu flag -- regardless of the ordering. -- -- This is a temporary hack. See #2872, commit -- 5bd3072ac30216a505151601884ac88bf404c9f2 ++ (if platformArch platform == ArchSPARC then ["-mcpu=v9"] else []) -- GCC 4.6+ doesn't like -Wimplicit when compiling C++. ++ (if (cc_phase /= Ccxx && cc_phase /= Cobjcxx) then ["-Wimplicit"] else []) ++ (if hcc then gcc_extra_viac_flags ++ more_hcc_opts else []) ++ verbFlags ++ [ "-S" ] ++ cc_opt ++ [ "-include", ghcVersionH ] ++ framework_paths ++ include_paths ++ more_preprocessor_opts ++ pkg_extra_cc_opts )) return (RealPhase next_phase, output_fn) ----------------------------------------------------------------------------- -- As, SpitAs phase : Assembler -- This is for calling the assembler on a regular assembly file runPhase (RealPhase (As with_cpp)) input_fn dflags = do -- LLVM from version 3.0 onwards doesn't support the OS X system -- assembler, so we use clang as the assembler instead. (#5636) let as_prog | hscTarget dflags == HscLlvm && platformOS (targetPlatform dflags) == OSDarwin = SysTools.runClang | otherwise = SysTools.runAs let cmdline_include_paths = includePaths dflags let pic_c_flags = picCCOpts dflags next_phase <- maybeMergeForeign output_fn <- phaseOutputFilename next_phase -- we create directories for the object file, because it -- might be a hierarchical module. liftIO $ createDirectoryIfMissing True (takeDirectory output_fn) ccInfo <- liftIO $ getCompilerInfo dflags let global_includes = [ SysTools.Option ("-I" ++ p) | p <- includePathsGlobal cmdline_include_paths ] let local_includes = [ SysTools.Option ("-iquote" ++ p) | p <- includePathsQuote cmdline_include_paths ] let runAssembler inputFilename outputFilename = liftIO $ do withAtomicRename outputFilename $ \temp_outputFilename -> do as_prog dflags (local_includes ++ global_includes -- See Note [-fPIC for assembler] ++ map SysTools.Option pic_c_flags -- See Note [Produce big objects on Windows] ++ [ SysTools.Option "-Wa,-mbig-obj" | platformOS (targetPlatform dflags) == OSMinGW32 , not $ target32Bit (targetPlatform dflags) ] -- We only support SparcV9 and better because V8 lacks an atomic CAS -- instruction so we have to make sure that the assembler accepts the -- instruction set. Note that the user can still override this -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag -- regardless of the ordering. -- -- This is a temporary hack. ++ (if platformArch (targetPlatform dflags) == ArchSPARC then [SysTools.Option "-mcpu=v9"] else []) ++ (if any (ccInfo ==) [Clang, AppleClang, AppleClang51] then [SysTools.Option "-Qunused-arguments"] else []) ++ [ SysTools.Option "-x" , if with_cpp then SysTools.Option "assembler-with-cpp" else SysTools.Option "assembler" , SysTools.Option "-c" , SysTools.FileOption "" inputFilename , SysTools.Option "-o" , SysTools.FileOption "" temp_outputFilename ]) liftIO $ debugTraceMsg dflags 4 (text "Running the assembler") runAssembler input_fn output_fn return (RealPhase next_phase, output_fn) ----------------------------------------------------------------------------- -- LlvmOpt phase runPhase (RealPhase LlvmOpt) input_fn dflags = do output_fn <- phaseOutputFilename LlvmLlc liftIO $ SysTools.runLlvmOpt dflags ( optFlag ++ defaultOptions ++ [ SysTools.FileOption "" input_fn , SysTools.Option "-o" , SysTools.FileOption "" output_fn] ) return (RealPhase LlvmLlc, output_fn) where -- we always (unless -optlo specified) run Opt since we rely on it to -- fix up some pretty big deficiencies in the code we generate optIdx = max 0 $ min 2 $ optLevel dflags -- ensure we're in [0,2] llvmOpts = case lookup optIdx $ llvmPasses $ llvmConfig dflags of Just passes -> passes Nothing -> panic ("runPhase LlvmOpt: llvm-passes file " ++ "is missing passes for level " ++ show optIdx) -- don't specify anything if user has specified commands. We do this -- for opt but not llc since opt is very specifically for optimisation -- passes only, so if the user is passing us extra options we assume -- they know what they are doing and don't get in the way. optFlag = if null (getOpts dflags opt_lo) then map SysTools.Option $ words llvmOpts else [] defaultOptions = map SysTools.Option . concat . fmap words . fst $ unzip (llvmOptions dflags) ----------------------------------------------------------------------------- -- LlvmLlc phase runPhase (RealPhase LlvmLlc) input_fn dflags = do next_phase <- if | fastLlvmPipeline dflags -> maybeMergeForeign -- hidden debugging flag '-dno-llvm-mangler' to skip mangling | gopt Opt_NoLlvmMangler dflags -> return (As False) | otherwise -> return LlvmMangle output_fn <- phaseOutputFilename next_phase liftIO $ SysTools.runLlvmLlc dflags ( optFlag ++ defaultOptions ++ [ SysTools.FileOption "" input_fn , SysTools.Option "-o" , SysTools.FileOption "" output_fn ] ) return (RealPhase next_phase, output_fn) where -- Note [Clamping of llc optimizations] -- -- See #13724 -- -- we clamp the llc optimization between [1,2]. This is because passing -O0 -- to llc 3.9 or llc 4.0, the naive register allocator can fail with -- -- Error while trying to spill R1 from class GPR: Cannot scavenge register -- without an emergency spill slot! -- -- Observed at least with target 'arm-unknown-linux-gnueabihf'. -- -- -- With LLVM4, llc -O3 crashes when ghc-stage1 tries to compile -- rts/HeapStackCheck.cmm -- -- llc -O3 '-mtriple=arm-unknown-linux-gnueabihf' -enable-tbaa /var/folders/fv/xqjrpfj516n5xq_m_ljpsjx00000gn/T/ghc33674_0/ghc_6.bc -o /var/folders/fv/xqjrpfj516n5xq_m_ljpsjx00000gn/T/ghc33674_0/ghc_7.lm_s -- 0 llc 0x0000000102ae63e8 llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 40 -- 1 llc 0x0000000102ae69a6 SignalHandler(int) + 358 -- 2 libsystem_platform.dylib 0x00007fffc23f4b3a _sigtramp + 26 -- 3 libsystem_c.dylib 0x00007fffc226498b __vfprintf + 17876 -- 4 llc 0x00000001029d5123 llvm::SelectionDAGISel::LowerArguments(llvm::Function const&) + 5699 -- 5 llc 0x0000000102a21a35 llvm::SelectionDAGISel::SelectAllBasicBlocks(llvm::Function const&) + 3381 -- 6 llc 0x0000000102a202b1 llvm::SelectionDAGISel::runOnMachineFunction(llvm::MachineFunction&) + 1457 -- 7 llc 0x0000000101bdc474 (anonymous namespace)::ARMDAGToDAGISel::runOnMachineFunction(llvm::MachineFunction&) + 20 -- 8 llc 0x00000001025573a6 llvm::MachineFunctionPass::runOnFunction(llvm::Function&) + 134 -- 9 llc 0x000000010274fb12 llvm::FPPassManager::runOnFunction(llvm::Function&) + 498 -- 10 llc 0x000000010274fd23 llvm::FPPassManager::runOnModule(llvm::Module&) + 67 -- 11 llc 0x00000001027501b8 llvm::legacy::PassManagerImpl::run(llvm::Module&) + 920 -- 12 llc 0x000000010195f075 compileModule(char**, llvm::LLVMContext&) + 12133 -- 13 llc 0x000000010195bf0b main + 491 -- 14 libdyld.dylib 0x00007fffc21e5235 start + 1 -- Stack dump: -- 0. Program arguments: llc -O3 -mtriple=arm-unknown-linux-gnueabihf -enable-tbaa /var/folders/fv/xqjrpfj516n5xq_m_ljpsjx00000gn/T/ghc33674_0/ghc_6.bc -o /var/folders/fv/xqjrpfj516n5xq_m_ljpsjx00000gn/T/ghc33674_0/ghc_7.lm_s -- 1. Running pass 'Function Pass Manager' on module '/var/folders/fv/xqjrpfj516n5xq_m_ljpsjx00000gn/T/ghc33674_0/ghc_6.bc'. -- 2. Running pass 'ARM Instruction Selection' on function '@"stg_gc_f1$def"' -- -- Observed at least with -mtriple=arm-unknown-linux-gnueabihf -enable-tbaa -- llvmOpts = case optLevel dflags of 0 -> "-O1" -- required to get the non-naive reg allocator. Passing -regalloc=greedy is not sufficient. 1 -> "-O1" _ -> "-O2" optFlag = if null (getOpts dflags opt_lc) then map SysTools.Option $ words llvmOpts else [] defaultOptions = map SysTools.Option . concat . fmap words . snd $ unzip (llvmOptions dflags) ----------------------------------------------------------------------------- -- LlvmMangle phase runPhase (RealPhase LlvmMangle) input_fn dflags = do let next_phase = As False output_fn <- phaseOutputFilename next_phase liftIO $ llvmFixupAsm dflags input_fn output_fn return (RealPhase next_phase, output_fn) ----------------------------------------------------------------------------- -- merge in stub objects runPhase (RealPhase MergeForeign) input_fn dflags = do PipeState{foreign_os} <- getPipeState output_fn <- phaseOutputFilename StopLn liftIO $ createDirectoryIfMissing True (takeDirectory output_fn) if null foreign_os then panic "runPhase(MergeForeign): no foreign objects" else do liftIO $ joinObjectFiles dflags (input_fn : foreign_os) output_fn return (RealPhase StopLn, output_fn) -- warning suppression runPhase (RealPhase other) _input_fn _dflags = panic ("runPhase: don't know how to run phase " ++ show other) maybeMergeForeign :: CompPipeline Phase maybeMergeForeign = do PipeState{foreign_os} <- getPipeState if null foreign_os then return StopLn else return MergeForeign getLocation :: HscSource -> ModuleName -> CompPipeline ModLocation getLocation src_flavour mod_name = do dflags <- getDynFlags PipeEnv{ src_basename=basename, src_suffix=suff } <- getPipeEnv PipeState { maybe_loc=maybe_loc} <- getPipeState case maybe_loc of -- Build a ModLocation to pass to hscMain. -- The source filename is rather irrelevant by now, but it's used -- by hscMain for messages. hscMain also needs -- the .hi and .o filenames. If we already have a ModLocation -- then simply update the extensions of the interface and object -- files to match the DynFlags, otherwise use the logic in Finder. Just l -> return $ l { ml_hs_file = Just $ basename <.> suff , ml_hi_file = ml_hi_file l -<.> hiSuf dflags , ml_obj_file = ml_obj_file l -<.> objectSuf dflags } _ -> do location1 <- liftIO $ mkHomeModLocation2 dflags mod_name basename suff -- Boot-ify it if necessary let location2 | HsBootFile <- src_flavour = addBootSuffixLocnOut location1 | otherwise = location1 -- Take -ohi into account if present -- This can't be done in mkHomeModuleLocation because -- it only applies to the module being compiles let ohi = outputHi dflags location3 | Just fn <- ohi = location2{ ml_hi_file = fn } | otherwise = location2 -- Take -o into account if present -- Very like -ohi, but we must *only* do this if we aren't linking -- (If we're linking then the -o applies to the linked thing, not to -- the object file for one module.) -- Note the nasty duplication with the same computation in compileFile -- above let expl_o_file = outputFile dflags location4 | Just ofile <- expl_o_file , isNoLink (ghcLink dflags) = location3 { ml_obj_file = ofile } | otherwise = location3 return location4 ----------------------------------------------------------------------------- -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file getHCFilePackages :: FilePath -> IO [InstalledUnitId] getHCFilePackages filename = Exception.bracket (openFile filename ReadMode) hClose $ \h -> do l <- hGetLine h case l of '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest -> return (map stringToInstalledUnitId (words rest)) _other -> return [] ----------------------------------------------------------------------------- -- Static linking, of .o files -- The list of packages passed to link is the list of packages on -- which this program depends, as discovered by the compilation -- manager. It is combined with the list of packages that the user -- specifies on the command line with -package flags. -- -- In one-shot linking mode, we can't discover the package -- dependencies (because we haven't actually done any compilation or -- read any interface files), so the user must explicitly specify all -- the packages. {- Note [-Xlinker -rpath vs -Wl,-rpath] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Wl takes a comma-separated list of options which in the case of -Wl,-rpath -Wl,some,path,with,commas parses the path with commas as separate options. Buck, the build system, produces paths with commas in them. -Xlinker doesn't have this disadvantage and as far as I can tell it is supported by both gcc and clang. Anecdotally nvcc supports -Xlinker, but not -Wl. -} linkBinary :: DynFlags -> [FilePath] -> [InstalledUnitId] -> IO () linkBinary = linkBinary' False linkBinary' :: Bool -> DynFlags -> [FilePath] -> [InstalledUnitId] -> IO () linkBinary' staticLink dflags o_files dep_packages = do let platform = targetPlatform dflags toolSettings' = toolSettings dflags verbFlags = getVerbFlags dflags output_fn = exeFileName staticLink dflags -- get the full list of packages to link with, by combining the -- explicit packages with the auto packages and all of their -- dependencies, and eliminating duplicates. full_output_fn <- if isAbsolute output_fn then return output_fn else do d <- getCurrentDirectory return $ normalise (d </> output_fn) pkg_lib_paths <- getPackageLibraryPath dflags dep_packages let pkg_lib_path_opts = concatMap get_pkg_lib_path_opts pkg_lib_paths get_pkg_lib_path_opts l | osElfTarget (platformOS platform) && dynLibLoader dflags == SystemDependent && WayDyn `elem` ways dflags = let libpath = if gopt Opt_RelativeDynlibPaths dflags then "$ORIGIN" </> (l `makeRelativeTo` full_output_fn) else l -- See Note [-Xlinker -rpath vs -Wl,-rpath] rpath = if gopt Opt_RPath dflags then ["-Xlinker", "-rpath", "-Xlinker", libpath] else [] -- Solaris 11's linker does not support -rpath-link option. It silently -- ignores it and then complains about next option which is -l<some -- dir> as being a directory and not expected object file, E.g -- ld: elf error: file -- /tmp/ghc-src/libraries/base/dist-install/build: -- elf_begin: I/O error: region read: Is a directory rpathlink = if (platformOS platform) == OSSolaris2 then [] else ["-Xlinker", "-rpath-link", "-Xlinker", l] in ["-L" ++ l] ++ rpathlink ++ rpath | osMachOTarget (platformOS platform) && dynLibLoader dflags == SystemDependent && WayDyn `elem` ways dflags && gopt Opt_RPath dflags = let libpath = if gopt Opt_RelativeDynlibPaths dflags then "@loader_path" </> (l `makeRelativeTo` full_output_fn) else l in ["-L" ++ l] ++ ["-Xlinker", "-rpath", "-Xlinker", libpath] | otherwise = ["-L" ++ l] pkg_lib_path_opts <- if gopt Opt_SingleLibFolder dflags then do libs <- getLibs dflags dep_packages tmpDir <- newTempDir dflags sequence_ [ copyFile lib (tmpDir </> basename) | (lib, basename) <- libs] return [ "-L" ++ tmpDir ] else pure pkg_lib_path_opts let dead_strip | gopt Opt_WholeArchiveHsLibs dflags = [] | otherwise = if osSubsectionsViaSymbols (platformOS platform) then ["-Wl,-dead_strip"] else [] let lib_paths = libraryPaths dflags let lib_path_opts = map ("-L"++) lib_paths extraLinkObj <- mkExtraObjToLinkIntoBinary dflags noteLinkObjs <- mkNoteObjsToLinkIntoBinary dflags dep_packages let (pre_hs_libs, post_hs_libs) | gopt Opt_WholeArchiveHsLibs dflags = if platformOS platform == OSDarwin then (["-Wl,-all_load"], []) -- OS X does not have a flag to turn off -all_load else (["-Wl,--whole-archive"], ["-Wl,--no-whole-archive"]) | otherwise = ([],[]) pkg_link_opts <- do (package_hs_libs, extra_libs, other_flags) <- getPackageLinkOpts dflags dep_packages return $ if staticLink then package_hs_libs -- If building an executable really means making a static -- library (e.g. iOS), then we only keep the -l options for -- HS packages, because libtool doesn't accept other options. -- In the case of iOS these need to be added by hand to the -- final link in Xcode. else other_flags ++ dead_strip ++ pre_hs_libs ++ package_hs_libs ++ post_hs_libs ++ extra_libs -- -Wl,-u,<sym> contained in other_flags -- needs to be put before -l<package>, -- otherwise Solaris linker fails linking -- a binary with unresolved symbols in RTS -- which are defined in base package -- the reason for this is a note in ld(1) about -- '-u' option: "The placement of this option -- on the command line is significant. -- This option must be placed before the library -- that defines the symbol." -- frameworks pkg_framework_opts <- getPkgFrameworkOpts dflags platform dep_packages let framework_opts = getFrameworkOpts dflags platform -- probably _stub.o files let extra_ld_inputs = ldInputs dflags rc_objs <- maybeCreateManifest dflags output_fn let link = if staticLink then SysTools.runLibtool else SysTools.runLink link dflags ( map SysTools.Option verbFlags ++ [ SysTools.Option "-o" , SysTools.FileOption "" output_fn ] ++ libmLinkOpts ++ map SysTools.Option ( [] -- See Note [No PIE when linking] ++ picCCOpts dflags -- Permit the linker to auto link _symbol to _imp_symbol. -- This lets us link against DLLs without needing an "import library". ++ (if platformOS platform == OSMinGW32 then ["-Wl,--enable-auto-import"] else []) -- '-no_compact_unwind' -- C++/Objective-C exceptions cannot use optimised -- stack unwinding code. The optimised form is the -- default in Xcode 4 on at least x86_64, and -- without this flag we're also seeing warnings -- like -- ld: warning: could not create compact unwind for .LFB3: non-standard register 5 being saved in prolog -- on x86. ++ (if toolSettings_ldSupportsCompactUnwind toolSettings' && not staticLink && (platformOS platform == OSDarwin) && case platformArch platform of ArchX86 -> True ArchX86_64 -> True ArchARM {} -> True ArchARM64 -> True _ -> False then ["-Wl,-no_compact_unwind"] else []) -- '-Wl,-read_only_relocs,suppress' -- ld gives loads of warnings like: -- ld: warning: text reloc in _base_GHCziArr_unsafeArray_info to _base_GHCziArr_unsafeArray_closure -- when linking any program. We're not sure -- whether this is something we ought to fix, but -- for now this flags silences them. ++ (if platformOS platform == OSDarwin && platformArch platform == ArchX86 && not staticLink then ["-Wl,-read_only_relocs,suppress"] else []) ++ (if toolSettings_ldIsGnuLd toolSettings' && not (gopt Opt_WholeArchiveHsLibs dflags) then ["-Wl,--gc-sections"] else []) ++ o_files ++ lib_path_opts) ++ extra_ld_inputs ++ map SysTools.Option ( rc_objs ++ framework_opts ++ pkg_lib_path_opts ++ extraLinkObj:noteLinkObjs ++ pkg_link_opts ++ pkg_framework_opts ++ (if platformOS platform == OSDarwin then [ "-Wl,-dead_strip_dylibs" ] else []) )) exeFileName :: Bool -> DynFlags -> FilePath exeFileName staticLink dflags | Just s <- outputFile dflags = case platformOS (targetPlatform dflags) of OSMinGW32 -> s <?.> "exe" _ -> if staticLink then s <?.> "a" else s | otherwise = if platformOS (targetPlatform dflags) == OSMinGW32 then "main.exe" else if staticLink then "liba.a" else "a.out" where s <?.> ext | null (takeExtension s) = s <.> ext | otherwise = s maybeCreateManifest :: DynFlags -> FilePath -- filename of executable -> IO [FilePath] -- extra objects to embed, maybe maybeCreateManifest dflags exe_filename | platformOS (targetPlatform dflags) == OSMinGW32 && gopt Opt_GenManifest dflags = do let manifest_filename = exe_filename <.> "manifest" writeFile manifest_filename $ "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"++ " <assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n"++ " <assemblyIdentity version=\"1.0.0.0\"\n"++ " processorArchitecture=\"X86\"\n"++ " name=\"" ++ dropExtension exe_filename ++ "\"\n"++ " type=\"win32\"/>\n\n"++ " <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n"++ " <security>\n"++ " <requestedPrivileges>\n"++ " <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n"++ " </requestedPrivileges>\n"++ " </security>\n"++ " </trustInfo>\n"++ "</assembly>\n" -- Windows will find the manifest file if it is named -- foo.exe.manifest. However, for extra robustness, and so that -- we can move the binary around, we can embed the manifest in -- the binary itself using windres: if not (gopt Opt_EmbedManifest dflags) then return [] else do rc_filename <- newTempName dflags TFL_CurrentModule "rc" rc_obj_filename <- newTempName dflags TFL_GhcSession (objectSuf dflags) writeFile rc_filename $ "1 24 MOVEABLE PURE " ++ show manifest_filename ++ "\n" -- magic numbers :-) -- show is a bit hackish above, but we need to escape the -- backslashes in the path. runWindres dflags $ map SysTools.Option $ ["--input="++rc_filename, "--output="++rc_obj_filename, "--output-format=coff"] -- no FileOptions here: windres doesn't like seeing -- backslashes, apparently removeFile manifest_filename return [rc_obj_filename] | otherwise = return [] linkDynLibCheck :: DynFlags -> [String] -> [InstalledUnitId] -> IO () linkDynLibCheck dflags o_files dep_packages = do when (haveRtsOptsFlags dflags) $ do putLogMsg dflags NoReason SevInfo noSrcSpan (defaultUserStyle dflags) (text "Warning: -rtsopts and -with-rtsopts have no effect with -shared." $$ text " Call hs_init_ghc() from your main() function to set these options.") linkDynLib dflags o_files dep_packages -- | Linking a static lib will not really link anything. It will merely produce -- a static archive of all dependent static libraries. The resulting library -- will still need to be linked with any remaining link flags. linkStaticLib :: DynFlags -> [String] -> [InstalledUnitId] -> IO () linkStaticLib dflags o_files dep_packages = do let extra_ld_inputs = [ f | FileOption _ f <- ldInputs dflags ] modules = o_files ++ extra_ld_inputs output_fn = exeFileName True dflags full_output_fn <- if isAbsolute output_fn then return output_fn else do d <- getCurrentDirectory return $ normalise (d </> output_fn) output_exists <- doesFileExist full_output_fn (when output_exists) $ removeFile full_output_fn pkg_cfgs <- getPreloadPackagesAnd dflags dep_packages archives <- concat <$> mapM (collectArchives dflags) pkg_cfgs ar <- foldl mappend <$> (Archive <$> mapM loadObj modules) <*> mapM loadAr archives if toolSettings_ldIsGnuLd (toolSettings dflags) then writeGNUAr output_fn $ afilter (not . isGNUSymdef) ar else writeBSDAr output_fn $ afilter (not . isBSDSymdef) ar -- run ranlib over the archive. write*Ar does *not* create the symbol index. runRanlib dflags [SysTools.FileOption "" output_fn] -- ----------------------------------------------------------------------------- -- Running CPP doCpp :: DynFlags -> Bool -> FilePath -> FilePath -> IO () doCpp dflags raw input_fn output_fn = do let hscpp_opts = picPOpts dflags let cmdline_include_paths = includePaths dflags pkg_include_dirs <- getPackageIncludePath dflags [] let include_paths_global = foldr (\ x xs -> ("-I" ++ x) : xs) [] (includePathsGlobal cmdline_include_paths ++ pkg_include_dirs) let include_paths_quote = foldr (\ x xs -> ("-iquote" ++ x) : xs) [] (includePathsQuote cmdline_include_paths) let include_paths = include_paths_quote ++ include_paths_global let verbFlags = getVerbFlags dflags let cpp_prog args | raw = SysTools.runCpp dflags args | otherwise = SysTools.runCc Nothing dflags (SysTools.Option "-E" : args) let targetArch = stringEncodeArch $ platformArch $ targetPlatform dflags targetOS = stringEncodeOS $ platformOS $ targetPlatform dflags let target_defs = [ "-D" ++ HOST_OS ++ "_BUILD_OS", "-D" ++ HOST_ARCH ++ "_BUILD_ARCH", "-D" ++ targetOS ++ "_HOST_OS", "-D" ++ targetArch ++ "_HOST_ARCH" ] -- remember, in code we *compile*, the HOST is the same our TARGET, -- and BUILD is the same as our HOST. let sse_defs = [ "-D__SSE__" | isSseEnabled dflags ] ++ [ "-D__SSE2__" | isSse2Enabled dflags ] ++ [ "-D__SSE4_2__" | isSse4_2Enabled dflags ] let avx_defs = [ "-D__AVX__" | isAvxEnabled dflags ] ++ [ "-D__AVX2__" | isAvx2Enabled dflags ] ++ [ "-D__AVX512CD__" | isAvx512cdEnabled dflags ] ++ [ "-D__AVX512ER__" | isAvx512erEnabled dflags ] ++ [ "-D__AVX512F__" | isAvx512fEnabled dflags ] ++ [ "-D__AVX512PF__" | isAvx512pfEnabled dflags ] backend_defs <- getBackendDefs dflags let th_defs = [ "-D__GLASGOW_HASKELL_TH__" ] -- Default CPP defines in Haskell source ghcVersionH <- getGhcVersionPathName dflags let hsSourceCppOpts = [ "-include", ghcVersionH ] -- MIN_VERSION macros let uids = explicitPackages (pkgState dflags) pkgs = catMaybes (map (lookupUnit dflags) uids) mb_macro_include <- if not (null pkgs) && gopt Opt_VersionMacros dflags then do macro_stub <- newTempName dflags TFL_CurrentModule "h" writeFile macro_stub (generatePackageVersionMacros pkgs) -- Include version macros for every *exposed* package. -- Without -hide-all-packages and with a package database -- size of 1000 packages, it takes cpp an estimated 2 -- milliseconds to process this file. See #10970 -- comment 8. return [SysTools.FileOption "-include" macro_stub] else return [] cpp_prog ( map SysTools.Option verbFlags ++ map SysTools.Option include_paths ++ map SysTools.Option hsSourceCppOpts ++ map SysTools.Option target_defs ++ map SysTools.Option backend_defs ++ map SysTools.Option th_defs ++ map SysTools.Option hscpp_opts ++ map SysTools.Option sse_defs ++ map SysTools.Option avx_defs ++ mb_macro_include -- Set the language mode to assembler-with-cpp when preprocessing. This -- alleviates some of the C99 macro rules relating to whitespace and the hash -- operator, which we tend to abuse. Clang in particular is not very happy -- about this. ++ [ SysTools.Option "-x" , SysTools.Option "assembler-with-cpp" , SysTools.Option input_fn -- We hackily use Option instead of FileOption here, so that the file -- name is not back-slashed on Windows. cpp is capable of -- dealing with / in filenames, so it works fine. Furthermore -- if we put in backslashes, cpp outputs #line directives -- with *double* backslashes. And that in turn means that -- our error messages get double backslashes in them. -- In due course we should arrange that the lexer deals -- with these \\ escapes properly. , SysTools.Option "-o" , SysTools.FileOption "" output_fn ]) getBackendDefs :: DynFlags -> IO [String] getBackendDefs dflags | hscTarget dflags == HscLlvm = do llvmVer <- figureLlvmVersion dflags return $ case fmap llvmVersionList llvmVer of Just [m] -> [ "-D__GLASGOW_HASKELL_LLVM__=" ++ format (m,0) ] Just (m:n:_) -> [ "-D__GLASGOW_HASKELL_LLVM__=" ++ format (m,n) ] _ -> [] where format (major, minor) | minor >= 100 = error "getBackendDefs: Unsupported minor version" | otherwise = show $ (100 * major + minor :: Int) -- Contract is Int getBackendDefs _ = return [] -- --------------------------------------------------------------------------- -- Macros (cribbed from Cabal) generatePackageVersionMacros :: [UnitInfo] -> String generatePackageVersionMacros pkgs = concat -- Do not add any C-style comments. See #3389. [ generateMacros "" pkgname version | pkg <- pkgs , let version = packageVersion pkg pkgname = map fixchar (packageNameString pkg) ] fixchar :: Char -> Char fixchar '-' = '_' fixchar c = c generateMacros :: String -> String -> Version -> String generateMacros prefix name version = concat ["#define ", prefix, "VERSION_",name," ",show (showVersion version),"\n" ,"#define MIN_", prefix, "VERSION_",name,"(major1,major2,minor) (\\\n" ," (major1) < ",major1," || \\\n" ," (major1) == ",major1," && (major2) < ",major2," || \\\n" ," (major1) == ",major1," && (major2) == ",major2," && (minor) <= ",minor,")" ,"\n\n" ] where (major1:major2:minor:_) = map show (versionBranch version ++ repeat 0) -- --------------------------------------------------------------------------- -- join object files into a single relocatable object file, using ld -r {- Note [Produce big objects on Windows] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The Windows Portable Executable object format has a limit of 32k sections, which we tend to blow through pretty easily. Thankfully, there is a "big object" extension, which raises this limit to 2^32. However, it must be explicitly enabled in the toolchain: * the assembler accepts the -mbig-obj flag, which causes it to produce a bigobj-enabled COFF object. * the linker accepts the --oformat pe-bigobj-x86-64 flag. Despite what the name suggests, this tells the linker to produce a bigobj-enabled COFF object, no a PE executable. We must enable bigobj output in a few places: * When merging object files (DriverPipeline.joinObjectFiles) * When assembling (DriverPipeline.runPhase (RealPhase As ...)) Unfortunately the big object format is not supported on 32-bit targets so none of this can be used in that case. -} joinObjectFiles :: DynFlags -> [FilePath] -> FilePath -> IO () joinObjectFiles dflags o_files output_fn = do let toolSettings' = toolSettings dflags ldIsGnuLd = toolSettings_ldIsGnuLd toolSettings' osInfo = platformOS (targetPlatform dflags) ld_r args cc = SysTools.runLink dflags ([ SysTools.Option "-nostdlib", SysTools.Option "-Wl,-r" ] -- See Note [No PIE while linking] in DynFlags ++ (if toolSettings_ccSupportsNoPie toolSettings' then [SysTools.Option "-no-pie"] else []) ++ (if any (cc ==) [Clang, AppleClang, AppleClang51] then [] else [SysTools.Option "-nodefaultlibs"]) ++ (if osInfo == OSFreeBSD then [SysTools.Option "-L/usr/lib"] else []) -- gcc on sparc sets -Wl,--relax implicitly, but -- -r and --relax are incompatible for ld, so -- disable --relax explicitly. ++ (if platformArch (targetPlatform dflags) `elem` [ArchSPARC, ArchSPARC64] && ldIsGnuLd then [SysTools.Option "-Wl,-no-relax"] else []) -- See Note [Produce big objects on Windows] ++ [ SysTools.Option "-Wl,--oformat,pe-bigobj-x86-64" | OSMinGW32 == osInfo , not $ target32Bit (targetPlatform dflags) ] ++ map SysTools.Option ld_build_id ++ [ SysTools.Option "-o", SysTools.FileOption "" output_fn ] ++ args) -- suppress the generation of the .note.gnu.build-id section, -- which we don't need and sometimes causes ld to emit a -- warning: ld_build_id | toolSettings_ldSupportsBuildId toolSettings' = ["-Wl,--build-id=none"] | otherwise = [] ccInfo <- getCompilerInfo dflags if ldIsGnuLd then do script <- newTempName dflags TFL_CurrentModule "ldscript" cwd <- getCurrentDirectory let o_files_abs = map (\x -> "\"" ++ (cwd </> x) ++ "\"") o_files writeFile script $ "INPUT(" ++ unwords o_files_abs ++ ")" ld_r [SysTools.FileOption "" script] ccInfo else if toolSettings_ldSupportsFilelist toolSettings' then do filelist <- newTempName dflags TFL_CurrentModule "filelist" writeFile filelist $ unlines o_files ld_r [SysTools.Option "-Wl,-filelist", SysTools.FileOption "-Wl," filelist] ccInfo else do ld_r (map (SysTools.FileOption "") o_files) ccInfo -- ----------------------------------------------------------------------------- -- Misc. writeInterfaceOnlyMode :: DynFlags -> Bool writeInterfaceOnlyMode dflags = gopt Opt_WriteInterface dflags && HscNothing == hscTarget dflags -- | Figure out if a source file was modified after an output file (or if we -- anyways need to consider the source file modified since the output is gone). sourceModified :: FilePath -- ^ destination file we are looking for -> UTCTime -- ^ last time of modification of source file -> IO Bool -- ^ do we need to regenerate the output? sourceModified dest_file src_timestamp = do dest_file_exists <- doesFileExist dest_file if not dest_file_exists then return True -- Need to recompile else do t2 <- getModificationUTCTime dest_file return (t2 <= src_timestamp) -- | What phase to run after one of the backend code generators has run hscPostBackendPhase :: HscSource -> HscTarget -> Phase hscPostBackendPhase HsBootFile _ = StopLn hscPostBackendPhase HsigFile _ = StopLn hscPostBackendPhase _ hsc_lang = case hsc_lang of HscC -> HCc HscAsm -> As False HscLlvm -> LlvmOpt HscNothing -> StopLn HscInterpreted -> StopLn touchObjectFile :: DynFlags -> FilePath -> IO () touchObjectFile dflags path = do createDirectoryIfMissing True $ takeDirectory path SysTools.touch dflags "Touching object file" path -- | Find out path to @ghcversion.h@ file getGhcVersionPathName :: DynFlags -> IO FilePath getGhcVersionPathName dflags = do candidates <- case ghcVersionFile dflags of Just path -> return [path] Nothing -> (map (</> "ghcversion.h")) <$> (getPackageIncludePath dflags [toInstalledUnitId rtsUnitId]) found <- filterM doesFileExist candidates case found of [] -> throwGhcExceptionIO (InstallationError ("ghcversion.h missing; tried: " ++ intercalate ", " candidates)) (x:_) -> return x -- Note [-fPIC for assembler] -- When compiling .c source file GHC's driver pipeline basically -- does the following two things: -- 1. ${CC} -S 'PIC_CFLAGS' source.c -- 2. ${CC} -x assembler -c 'PIC_CFLAGS' source.S -- -- Why do we need to pass 'PIC_CFLAGS' both to C compiler and assembler? -- Because on some architectures (at least sparc32) assembler also chooses -- the relocation type! -- Consider the following C module: -- -- /* pic-sample.c */ -- int v; -- void set_v (int n) { v = n; } -- int get_v (void) { return v; } -- -- $ gcc -S -fPIC pic-sample.c -- $ gcc -c pic-sample.s -o pic-sample.no-pic.o # incorrect binary -- $ gcc -c -fPIC pic-sample.s -o pic-sample.pic.o # correct binary -- -- $ objdump -r -d pic-sample.pic.o > pic-sample.pic.o.od -- $ objdump -r -d pic-sample.no-pic.o > pic-sample.no-pic.o.od -- $ diff -u pic-sample.pic.o.od pic-sample.no-pic.o.od -- -- Most of architectures won't show any difference in this test, but on sparc32 -- the following assembly snippet: -- -- sethi %hi(_GLOBAL_OFFSET_TABLE_-8), %l7 -- -- generates two kinds or relocations, only 'R_SPARC_PC22' is correct: -- -- 3c: 2f 00 00 00 sethi %hi(0), %l7 -- - 3c: R_SPARC_PC22 _GLOBAL_OFFSET_TABLE_-0x8 -- + 3c: R_SPARC_HI22 _GLOBAL_OFFSET_TABLE_-0x8 {- Note [Don't normalise input filenames] Summary We used to normalise input filenames when starting the unlit phase. This broke hpc in `--make` mode with imported literate modules (#2991). Introduction 1) --main When compiling a module with --main, GHC scans its imports to find out which other modules it needs to compile too. It turns out that there is a small difference between saying `ghc --make A.hs`, when `A` imports `B`, and specifying both modules on the command line with `ghc --make A.hs B.hs`. In the former case, the filename for B is inferred to be './B.hs' instead of 'B.hs'. 2) unlit When GHC compiles a literate haskell file, the source code first needs to go through unlit, which turns it into normal Haskell source code. At the start of the unlit phase, in `Driver.Pipeline.runPhase`, we call unlit with the option `-h` and the name of the original file. We used to normalise this filename using System.FilePath.normalise, which among other things removes an initial './'. unlit then uses that filename in #line directives that it inserts in the transformed source code. 3) SrcSpan A SrcSpan represents a portion of a source code file. It has fields linenumber, start column, end column, and also a reference to the file it originated from. The SrcSpans for a literate haskell file refer to the filename that was passed to unlit -h. 4) -fhpc At some point during compilation with -fhpc, in the function `deSugar.Coverage.isGoodTickSrcSpan`, we compare the filename that a `SrcSpan` refers to with the name of the file we are currently compiling. For some reason I don't yet understand, they can sometimes legitimally be different, and then hpc ignores that SrcSpan. Problem When running `ghc --make -fhpc A.hs`, where `A.hs` imports the literate module `B.lhs`, `B` is inferred to be in the file `./B.lhs` (1). At the start of the unlit phase, the name `./B.lhs` is normalised to `B.lhs` (2). Therefore the SrcSpans of `B` refer to the file `B.lhs` (3), but we are still compiling `./B.lhs`. Hpc thinks these two filenames are different (4), doesn't include ticks for B, and we have unhappy customers (#2991). Solution Do not normalise `input_fn` when starting the unlit phase. Alternative solution Another option would be to not compare the two filenames on equality, but to use System.FilePath.equalFilePath. That function first normalises its arguments. The problem is that by the time we need to do the comparison, the filenames have been turned into FastStrings, probably for performance reasons, so System.FilePath.equalFilePath can not be used directly. Archeology The call to `normalise` was added in a commit called "Fix slash direction on Windows with the new filePath code" (c9b6b5e8). The problem that commit was addressing has since been solved in a different manner, in a commit called "Fix the filename passed to unlit" (1eedbc6b). So the `normalise` is no longer necessary. -}
sdiehl/ghc
compiler/main/DriverPipeline.hs
bsd-3-clause
104,582
6
31
34,244
16,357
8,316
8,041
-1
-1
module Control.Monoid where import Control.Semigroup class Semigroup s => Monoid s where identity :: s
tonymorris/lens-proposal
src/Control/Monoid.hs
bsd-3-clause
111
0
6
23
32
17
15
5
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} module KAT_Ed25519 ( tests ) where import Crypto.Error import qualified Crypto.PubKey.Ed25519 as Ed25519 import Imports data Vec = Vec { vecSec :: ByteString , vecPub :: ByteString , vecMsg :: ByteString , vecSig :: ByteString } deriving (Show,Eq) vec1 = Vec { vecSec = "\x4c\xcd\x08\x9b\x28\xff\x96\xda\x9d\xb6\xc3\x46\xec\x11\x4e\x0f\x5b\x8a\x31\x9f\x35\xab\xa6\x24\xda\x8c\xf6\xed\x4f\xb8\xa6\xfb" , vecPub = "\x3d\x40\x17\xc3\xe8\x43\x89\x5a\x92\xb7\x0a\xa7\x4d\x1b\x7e\xbc\x9c\x98\x2c\xcf\x2e\xc4\x96\x8c\xc0\xcd\x55\xf1\x2a\xf4\x66\x0c" , vecMsg = "\x72" , vecSig = "\x92\xa0\x09\xa9\xf0\xd4\xca\xb8\x72\x0e\x82\x0b\x5f\x64\x25\x40\xa2\xb2\x7b\x54\x16\x50\x3f\x8f\xb3\x76\x22\x23\xeb\xdb\x69\xda\x08\x5a\xc1\xe4\x3e\x15\x99\x6e\x45\x8f\x36\x13\xd0\xf1\x1d\x8c\x38\x7b\x2e\xae\xb4\x30\x2a\xee\xb0\x0d\x29\x16\x12\xbb\x0c\x00" } testVec :: String -> Vec -> [TestTree] testVec s vec = [ testCase (s ++ " gen publickey") (pub @=? Ed25519.toPublic sec) , testCase (s ++ " gen signature") (sig @=? Ed25519.sign sec pub (vecMsg vec)) ] where !sig = throwCryptoError $ Ed25519.signature (vecSig vec) !pub = throwCryptoError $ Ed25519.publicKey (vecPub vec) !sec = throwCryptoError $ Ed25519.secretKey (vecSec vec) katTests :: [TestTree] katTests = testVec "vec 1" vec1 tests = testGroup "Ed25519" [ testGroup "KATs" katTests ]
nomeata/cryptonite
tests/KAT_Ed25519.hs
bsd-3-clause
1,502
0
11
255
297
164
133
28
1
{-# LANGUAGE RankNTypes, ScopedTypeVariables, GADTs #-} import Text.PrettyPrint.HughesPJClass import System.IO.Unsafe import Control.Monad import Control.Monad.State type UniqM = State [Int] uniqSupply :: [Int] uniqSupply = [0..] runUniq :: UniqM a -> a runUniq = flip evalState uniqSupply unique :: UniqM Int unique = get >>= \(x:ss) -> put ss >> return x -- -- Thingy is the "mother of all idioms": -- -- -- pure :: forall b. b -> i b -- -- (<**>) :: forall a. i a -> (forall b. i (a -> b) -> i b) -- -- -- -- pure id <*> v = v -- Identity -- -- pure (.) <*> u <*> v <*> w = u <*> (v <*> w) -- Composition -- -- pure f <*> pure x = pure (f x) -- Homomorphism -- -- u <*> pure y = pure ($ y) <*> u -- Interchange -- -- -- -- v ==> pure id <*> v -- Identity -- -- u <*> (v <*> w) ==> pure (.) <*> u <*> v <*> w -- Composition -- -- pure f <*> pure x ==> pure (f x) -- Homomorphism -- -- u <*> pure y ==> pure ($ y) <*> u -- Interchange -- newtype Thingy i a = Thingy { runThingy :: forall b. Yoneda i (a -> b) -> Yoneda i b } -- -- liftThingy :: Applicative i => i a -> Thingy i a -- liftThingy i = Thingy (liftYoneda . (<**>) i . lowerYoneda) -- -- lowerThingy :: Applicative i => Thingy i a -> i a -- lowerThingy i = lowerYoneda $ runThingy i (liftYoneda (pure id)) -- -- instance Functor i => Functor (Thingy i) where -- fmap f m = Thingy $ runThingy m . fmap (. f) -- -- instance Applicative (Thingy i) where -- pure x = Thingy $ \m -> Yoneda (\k -> runYoneda m (k . ($ x))) -- mf <*> mx = Thingy $ \m -> runThingy mx (runThingy mf (Yoneda (\k -> runYoneda m (k . (.))))) instance Pretty (IdiomSyn a) where pPrint (Pure e) = text "pure" <+> parens (pPrint e) pPrint (Ap mf mx) = pPrint mf <+> text "<*>" <+> parens (pPrint mx) pPrint (Foreign e) = text e instance Pretty (Term a) where pPrint = runUniq . pPrintTerm pPrintTerm :: Term a -> UniqM Doc pPrintTerm (Lam f) = do x <- fmap (\i -> "x" ++ show i) unique d <- pPrintTerm (f (ForeignE x)) return $ parens $ text "\\" <> text x <+> text "->" <+> d pPrintTerm (App e1 e2) = liftM2 (\e1 e2 -> e1 <+> parens e2) (pPrintTerm e1) (pPrintTerm e2) pPrintTerm (ForeignE e) = return $ text e data Term a where Lam :: (Term a -> Term b) -> Term (a -> b) App :: Term (a -> b) -> Term a -> Term b ForeignE :: String -> Term a data IdiomSyn a where Pure :: Term a -> IdiomSyn a Ap :: IdiomSyn (a -> b) -> IdiomSyn a -> IdiomSyn b Foreign :: String -> IdiomSyn a normalise :: IdiomSyn a -> IdiomSyn a normalise m = go m (\k -> Pure (k id)) id where --go :: forall a. IdiomSyn a -- -> (forall b. -- (forall c. ((Term a -> Term b) -> Term c) -> IdiomSyn c) -- -> (forall d. -- (Term b -> Term d) -- -> IdiomSyn d)) go :: forall a b d. IdiomSyn a -> (forall c. ((Term a -> Term b) -> Term c) -> IdiomSyn c) -> (Term b -> Term d) -> IdiomSyn d go (Pure x) m = \k -> m (\k' -> k (k' x)) --go (Ap mf mx) m = go mx (go mf (\k -> m (\k' -> k ((.) k')))) -- go (Ap mf mx) m = go mx (go mf (\k -> m (k . (\t -> "(.) (" ++ t ++ ")")))) go (Ap mf mx) m = go mx (\k' -> go mf (\x -> m (\y -> x (\z -> Lam (\e -> y (z `App` e))))) (\w -> k' (w `App`))) -- HAVE -- mf :: IdiomSyn (e -> a) -- mx :: IdiomSyn e -- m :: forall f. ((Term a -> Term b) -> Term f) -> IdiomSyn f -- k :: Term b -> Term d -- go mf :: forall i. -- (forall g. ((Term (e -> a) -> Term i) -> Term g) -> IdiomSyn g) -- -> (forall h. -- (Term i -> Term h) -- -> IdiomSyn h) -- go mx :: forall j. -- (forall k. ((Term e -> Term j) -> Term k) -> IdiomSyn k) -- -> (forall l. -- (Term j -> Term l) -- -> IdiomSyn l) -- -- GOAL -- undefined :: IdiomSyn d -- go mx (\(k' :: (Term e -> Term b) -> Term k) -> undefined :: IdiomSyn k) k :: IdiomSyn d -- go mx (\(k' :: (Term e -> Term b) -> Term k) -> go mf (\(x :: (Term (e -> a) -> Term (e -> b)) -> Term g) -> undefined :: IdiomSyn g) (undefined :: Term (e -> b) -> Term k) :: IdiomSyn k) k :: IdiomSyn d -- go mx (\(k' :: (Term e -> Term b) -> Term k) -> go mf (\(x :: (Term (e -> a) -> Term (e -> b)) -> Term g) -> m (\(y :: (Term a -> Term b)) -> undefined :: Term g) :: IdiomSyn g) (undefined :: Term (e -> b) -> Term k) :: IdiomSyn k) k :: IdiomSyn d -- go mx (\(k' :: (Term e -> Term b) -> Term k) -> go mf (\(x :: (Term (e -> a) -> Term (e -> b)) -> Term g) -> m (\(y :: (Term a -> Term b)) -> x (\(z :: Term (e -> a) -> Lam (\e -> y (z `App` e))))) :: IdiomSyn g) (\(w :: Term (e -> b)) -> k' (w `App`) :: Term k) :: IdiomSyn k) k :: IdiomSyn d -- x :: ((Term (e -> a) -> Term (e -> b)) -> Term g -- y :: Term a -> Term b -- -- x (\(z :: Term (e -> a) -> Lam (\e -> y (z `App` e)))) :: Term g -- go (Foreign e) m = \k -> m (\t -> "(.) (\\x -> " ++ k "x" ++ ") (" ++ t ++ ")") `Ap` Foreign e go x@(Foreign _) m = \k -> m (\k' -> Lam (k . k')) `Ap` x -- HAVE -- Foreign e :: IdiomSyn a -- m :: forall f. ((Term a -> Term b) -> Term f) -> IdiomSyn f -- k :: Term b -> Term d -- -- GOAL -- undefined :: IdiomSyn d -- m (\(k' :: Term a -> Term b) -> undefined :: Term (a -> d)) `Ap` Foreign e :: IdiomSyn d -- m (\(k' :: Term a -> Term b) -> Lam (k . k') :: Term (a -> d)) `Ap` Foreign e :: IdiomSyn d -- e :: i a -- m :: (forall c. ((a -> b) -> c) -> i c) -- k :: (b -> d) -- -- WANT: -- c =inst=> (a -> d) -- SO: -- m :: ((a -> b) -> (a -> d)) -> i (a -> d) -- (\t -> "(.) (\x -> " ++ k "x" ++ ")") :: ((a -> b) -> (a -> d)) comp :: Term ((b -> c) -> (a -> b) -> (a -> c)) comp = Lam (\f -> Lam (\g -> Lam (\x -> f `App` (g `App` x)))) non_normaliseds = [ -- Identity Foreign "effectful", Pure (Lam (\x -> x)) `Ap` Foreign "effectful", -- Composition Foreign "launchMissiles" `Ap` (Foreign "obtainLaunchCode" `Ap` Foreign "getAuthorization"), Pure comp `Ap` Foreign "launchMissiles" `Ap` Foreign "obtainLaunchCode" `Ap` Foreign "getAuthorization", Pure (ForeignE "launchMissiles'") `Ap` (Pure (ForeignE "obtainLaunchCode'") `Ap` Pure (ForeignE "getAuthorization'")), -- Homomorphism Pure (ForeignE "f") `Ap` Pure (ForeignE "x"), Pure (Lam (\x -> ForeignE "f" `App` x) `App` ForeignE "x"), -- Interchange Foreign "launchMissiles" `Ap` Pure (ForeignE "1337"), -- NB: demonstrates normaliser weakness. Beta-reduction introduced by normalisation! Pure (Lam (\x -> x `App` ForeignE "1337")) `Ap` Foreign "launchMissiles" ] main = forM_ non_normaliseds $ \non_normalised -> do putStrLn "== Before" print $ pPrint non_normalised putStrLn "== After" print $ pPrint $ normalise non_normalised
batterseapower/haskell-kata
IdiomNormalisation.hs
bsd-3-clause
7,065
0
24
2,146
1,390
763
627
60
3
module FreeDSL.BFS.VTraversal ( VTraverseDslCmds(..) , VTraversal , VObservation(..) -- low level API , rootAt , nextObservation , currentObservation , annotateAt , getAnnotationAt , getWithDefault , modifyAnnotationAt -- easy API , startWithAnnotation , rootWithAnnotation , nextVertex , annotate , adjustAnnotation , getAnnotation , appendAnnotation , currentVertex -- other versions , nextAsVertexPair ) where --import Control.Monad import Control.Monad.Free (Free(..),liftF) --import Control.Monad.State (State, execState, modify) --import qualified PolyGraph.Common.NonBlockingQueue as Q data VObservation v = Observe { on :: v, neighbor :: v } | NoMore deriving Show data VTraverseDslCmds a v n = StartAt v n | NextVObs (VObservation v -> n) | CurrentVObs (VObservation v -> n) | Put (v, a) n | Get v ( Maybe a -> n) deriving (Functor) type VTraversal a v = Free (VTraverseDslCmds a v) rootAt :: forall a v . v -> VTraversal a v () rootAt v = liftF (StartAt v ()) nextObservation :: forall a v . VTraversal a v (VObservation v) nextObservation = liftF (NextVObs id) nextAsVertexPair :: forall a v . VTraversal a v (Maybe (v,v)) nextAsVertexPair = nextObservation >>= (\obs -> case obs of NoMore -> return Nothing Observe v1 v2 -> return $ Just (v1, v2) ) currentObservation :: forall a v . VTraversal a v (VObservation v) currentObservation = liftF (CurrentVObs id) annotateAt :: forall a v . v -> a -> VTraversal a v () annotateAt v a = liftF (Put (v,a) ()) getAnnotationAt :: forall a v . v -> VTraversal a v (Maybe a) getAnnotationAt v = liftF (Get v id) modifyAnnotationAt :: forall a v . v -> (a -> a) -> VTraversal a v () modifyAnnotationAt v f = getAnnotationAt v >>= maybe (return ()) (annotateAt v . f) getWithDefault :: forall a v . a -> v -> VTraversal a v a getWithDefault defA v = getAnnotationAt v >>= return . (maybe defA id) rootWithAnnotation :: forall a v . v -> a -> VTraversal a v () rootWithAnnotation v a = rootAt v >> annotateAt v a startWithAnnotation :: forall a v . v -> a -> VTraversal a v (VObservation v) startWithAnnotation v a = rootWithAnnotation v a >> nextObservation nextVertex :: forall a v . VTraversal a v (Maybe v) nextVertex = nextObservation >>= (\obs -> case obs of NoMore -> return Nothing Observe _ v2 -> return $ Just v2 ) currentVertex :: forall a v . VTraversal a v (Maybe v) currentVertex = currentObservation >>= (\obs -> case obs of NoMore -> return Nothing Observe _ v2 -> return $ Just v2 ) annotate :: forall a v . a -> VTraversal a v () annotate a = currentObservation >>= (\obs -> case obs of NoMore -> return () Observe _ v2 -> annotateAt v2 a ) annotateR :: forall a v . a -> VTraversal a v (Maybe a) annotateR a = currentObservation >>= (\obs -> case obs of NoMore -> return Nothing Observe _ v2 -> do annotateAt v2 a return $ Just a ) getAnnotation :: forall a v . VTraversal a v (Maybe a) getAnnotation = currentObservation >>= (\obs -> case obs of NoMore -> return Nothing Observe v1 _ -> getAnnotationAt v1 ) adjustAnnotation :: forall a v . (a -> a) -> VTraversal a v (Maybe a) adjustAnnotation f = getAnnotation >>= maybe (return Nothing) (annotateR . f) appendAnnotation :: forall a v . Monoid a => a -> VTraversal a v (Maybe a) appendAnnotation a = adjustAnnotation (mappend a)
rpeszek/GraphPlay
src/FreeDSL/BFS/VTraversal.hs
bsd-3-clause
4,080
0
14
1,409
1,260
673
587
-1
-1
{-# LANGUAGE FlexibleInstances, TypeFamilies #-} {-# LANGUAGE QuasiQuotes #-} module Language.Pylon.Codegen.JS (mkProgram) where ------------------------------------------------------------------------------- import Prelude hiding (mapM_) import Language.Pylon.Codegen.Monad import Language.Pylon.STG.AST import Data.Foldable (forM_, mapM_) import Data.List (intercalate) import Text.InterpolatedString.Perl6 (qq) ------------------------------------------------------------------------------- endl :: String endl = "\n" type Name = String ------------------------------------------------------------------------------- -- Programs and Expressions ------------------------------------------------------------------------------- -- | Code for a STG program. mkProgram :: Program -> Codegen () mkProgram p = do [qq|var stg = require('./stg');{endl}|] mapM_ mkBind p -- | Code for a STG expression; binds the value of the expression to a fresh -- | name and returns that name. mkExp :: Exp -> Codegen Name mkExp (EApp v as) = mkEApp v as mkExp (EPrim po as) = mkEPrim po as mkExp (ECase as d e) = mkECase as d e mkExp (EAtom a) = mkEAtom a mkExp (ELet bs e) = mkELet bs e ------------------------------------------------------------------------------- -- Case Expressions ------------------------------------------------------------------------------- -- | Code for a case expression: -- | -- | For algebratic alternatives, the scrutinee is forced first; then the -- | index of its info structure is switched on. For primitive alternatives, -- | the scrutinee is switched on directly. -- | -- | When no alternative but the default one is provided, the switch will be -- | omitted, since it is not legal javascript to define a switch with only -- | a default alternative. mkECase :: Alts -> Default -> Exp -> Codegen Name mkECase (AAlts []) (Default dv de) scr = do scrE <- mkExp scr [qq|stg.force({scrE});{endl}|] forM_ dv $ \v -> [qq|var {v} = {scrE};{endl}|] mkExp de mkECase (AAlts as) def scr = withTemp $ \result -> do scrE <- mkExp scr [qq|stg.force({scrE});{endl}|] [qq|var {result};{endl}|] [qq|switch ({scrE}.index) \{{endl}|] indent $ do -- alternatives forM_ as $ \(AAlt c vs e) -> do [qq|case {c}:{endl}|] indent $ do -- bind cons fields forM_ (zip [0..] vs) $ \(i, v) -> [qq|var {v} = {scrE}.data[{i}];{endl}|] -- make nested expression bindTo result $ mkExp e [qq|break;{endl}|] -- default alternative mkDefault scrE result def [qq|}{endl}|] mkECase (PAlts []) (Default dv de) scr = do scrE <- mkExp scr forM_ dv $ \v -> [qq|var {v} = {scrE};{endl}|] mkExp de mkECase (PAlts as) def scr = withTemp $ \result -> do scrE <- mkExp scr [qq|var {result};{endl}|] [qq|switch ({scrE}) \{{endl}|] indent $ do -- alternatives forM_ as $ \(PAlt l e) -> do [qq|case {mkLit l}:{endl}|] indent $ do bindTo result $ mkExp e [qq|break;{endl}|] -- default alternative mkDefault scrE result def [qq|}{endl}|] -- | Code for the default case of a case expression. -- | Shared between algebraic and primitive alternatives. mkDefault :: Name -> Name -> Default -> Codegen Name mkDefault scr result (Default dv de) = do [qq|default:{endl}|] indent $ do forM_ dv $ \v -> [qq|var {v} = {scr};{endl}|] bindTo result $ mkExp de [qq|break;{endl}|] return result ------------------------------------------------------------------------------- -- Function and Primitive Application ------------------------------------------------------------------------------- -- | Code for function application: the function and the arguments are passed -- | to an apply function which handles the apply semantics. mkEApp :: Var -> [Atom] -> Codegen Name mkEApp v as = withTemp $ \result -> do let args = intercalate ", " $ v : fmap mkAtom as [qq|var $result = stg.apply($args);{endl}|] -- | Code for primitive application: The arguments are intercalated by the -- | primitive operator. mkEPrim :: PrimOp -> [Exp] -> Codegen Name mkEPrim (PForeign f _ _) as = withTemp $ \result -> do vs <- mapM mkExp as let args = intercalate ", " vs [qq|var $result = {f}({args});{endl}|] mkEPrim po as = withTemp $ \result -> do vs <- mapM mkExp as let ops = intercalate (mkPrim po) vs [qq|var {result} = {ops};{endl}|] -- | Primitive operators. mkPrim :: PrimOp -> String mkPrim (PPlus _) = "+" mkPrim (PMult _) = "*" mkPrim (PDiv _) = "/" mkPrim (PMinus _) = "-" mkPrim (PEq _) = "===" mkPrim (PLt _) = "<" mkPrim (PLte _) = "<=" mkPrim (PGt _) = ">" mkPrim (PGte _) = ">=" ---------------------------------------------------------------------------- -- Let Expressions and Bindings ------------------------------------------------------------------------------- -- | Code for let expressions: First bind, then execute the inner code. mkELet :: [Bind] -> Exp -> Codegen Name mkELet bs e = mapM_ mkBind bs >> mkExp e -- | Code for bindings: Binds the heap object generated by mkObject to the -- | target variable. mkBind :: Bind -> Codegen () mkBind (Bind v o) = do [qq|var {v} = \{{endl}|] indent $ mkObject o [qq|};{endl}|] -- | Code for a heap object. The info table is merged with the data here. mkObject :: Object -> Codegen () mkObject (Fun vs e) = do [qq|type : 0,{endl}|] [qq|arity: {length vs},{endl}|] [qq|code : function({intercalate "," vs}) \{{endl}|] withRet $ mkExp e [qq|}|] mkObject (Pap v as) = do [qq|type: 1,{endl}|] [qq|code: {v},{endl}|] [qq|data: [{mkAtoms as}]{endl}|] mkObject (Con c as) = do [qq|type : 2,{endl}|] [qq|index: {c},{endl}|] [qq|data : [{mkAtoms as}],{endl}|] [qq|code : function() \{}{endl}|] mkObject (Thunk e) = do [qq|type : 3,{endl}|] [qq|code : stg.thunk(function() \{{endl}|] withRet $ mkExp e [qq|})|] mkObject Error = do [qq|type : 4,{endl}|] [qq|code : function() \{ console.log("error"); }|] ------------------------------------------------------------------------------- -- Atoms and Literals ------------------------------------------------------------------------------- -- | Code for an atomic expression: Bind the value of the atom to a fresh var. mkEAtom :: Atom -> Codegen Name mkEAtom a = withTemp $ \r -> [qq|var {r} = {mkAtom a};{endl}|] -- | Intercalates multiple atoms. mkAtoms :: [Atom] -> String mkAtoms = intercalate "," . fmap mkAtom -- | Code for an atom. mkAtom :: Atom -> String mkAtom (AVar v) = v mkAtom (ALit l) = mkLit l -- | Code for an literal. mkLit :: Lit -> String mkLit (LInt i) = show i ------------------------------------------------------------------------------- -- Misc ------------------------------------------------------------------------------- -- | Generates the code and returns the result. withRet :: Codegen Name -> Codegen Name withRet cg = indent $ do ret <- cg [qq|return {ret};{endl}|] return ret -- | Introduces a fresh variable and supplies it to a code generator; then -- | use that fresh variable as the result. withTemp :: (Name -> Codegen a) -> Codegen Name withTemp cg = do result <- freshName cg result return result -- | Bind the result of a code generator to a variable- bindTo :: Name -> Codegen Name -> Codegen Name bindTo result cg = do result' <- cg [qq|{result} = {result'};{endl}|] return result
zrho/pylon
src/Language/Pylon/Codegen/JS.hs
bsd-3-clause
7,430
0
23
1,420
1,786
971
815
145
1
{-# LANGUAGE CPP #-} -- #define DEBUG {-# LANGUAGE PartialTypeSignatures #-} {-# OPTIONS_GHC -Wno-partial-type-signatures #-} {-| Module : AERN2.RealFun.SineCosine Description : Pointwise sine and cosine for functions Copyright : (c) Michal Konecny License : BSD3 Maintainer : [email protected] Stability : experimental Portability : portable Pointwise sine and cosine for functions -} module AERN2.RealFun.SineCosine -- ( -- ) where #ifdef DEBUG import Debug.Trace (trace) #define maybeTrace trace #else #define maybeTrace (flip const) #endif import MixedTypesNumPrelude -- import qualified Prelude as P import Text.Printf import qualified Data.Map as Map import qualified Data.List as List -- import Test.Hspec -- import Test.QuickCheck import AERN2.MP -- import qualified AERN2.MP.Ball as MPBall -- import AERN2.MP.Dyadic import AERN2.Real -- import AERN2.Interval import AERN2.RealFun.Operations {- To compute sin(xC+-xE): * compute (rC+-rE) = range(xC) * compute k = round(rC/(pi/2)) * compute sin or cos of txC = xC-k*pi/2 using Taylor series * use sin for even k and cos for odd k * which degree to use? * keep trying higher and higher degrees until * the accuracy of the result worsens * OR the accuracy of the result is 8x higher than xE * if k mod 4 = 2 then negate result * if k mod 4 = 3 then negate result * add xE to the error bound of the resulting polynomial -} sineWithAccuracyGuide :: _ => Accuracy -> f -> f sineWithAccuracyGuide = sineCosineWithAccuracyGuide True cosineWithAccuracyGuide :: _ => Accuracy -> f -> f cosineWithAccuracyGuide = sineCosineWithAccuracyGuide False sineCosineWithAccuracyGuide :: _ => Bool -> Accuracy -> f -> f sineCosineWithAccuracyGuide isSine acGuide x = maybeTrace ( "ChPoly.sineCosine: input:" ++ "\n isSine = " ++ show isSine -- ++ "\n xC = " ++ show xC ++ "\n xE = " ++ show xE ++ "\n xAccuracy = " ++ show xAccuracy ++ "\n r = " ++ show r ++ "\n k = " ++ show k ++ "\n trM = " ++ show trM ) $ maybeTrace ( "ChPoly.sineCosine: output:" ++ "\n Taylor series degree = " ++ show n ++ "\n getAccuracy taylorSum = " ++ show (getAccuracy taylorSum) ++ "\n taylorSumE = " ++ show taylorSumE ++ "\n getAccuracy result = " ++ show (getAccuracy res) ) $ -- xPoly (prec 100) -- dummy res where -- showB = show . getApproximate (bits 30) -- showAP = show . getApproximate (bits 50) . cheb2Power isCosine = not isSine -- first separate the centre of the polynomial x from its radius: xC = centreAsBall x xE = radius x xAccuracy = getAccuracy x -- compute (rC+-rE) = range(x): dom = getDomain x -- r = mpBall $ applyApprox xC (getDomain xC) r = fromEndpointsAsIntervals (mpBall $ minimumOverDom x dom) (mpBall $ maximumOverDom x dom) rC = centreAsBall r :: MPBall -- compute k = round(rC/(pi/2)): k = fst $ integerBounds $ 0.5 + (2*rC / pi) -- shift xC near 0 using multiples of pi/2: txC ac = (setPrecisionAtLeastAccuracy (ac) xC) - k * pi / 2 -- work out an absolute range bound for txC: (_, trM) = endpointsAsIntervals $ abs $ r - k * pi / 2 -- compute sin or cos of txC = xC-k*pi/2 using Taylor series: (taylorSum, taylorSumE, n) | isSine && even k = sineTaylorSum txC trM acGuide | isCosine && odd k = sineTaylorSum txC trM acGuide | otherwise = cosineTaylorSum txC trM acGuide -- if k mod 4 = 2 then negate result, -- if k mod 4 = 3 then negate result: km4 = k `mod` 4 resC | isSine && 2 <= km4 && km4 <= 3 = -taylorSum | isCosine && 1 <= km4 && km4 <= 2 = -taylorSum | otherwise = taylorSum -- add xE to the error bound of the resulting polynomial: res = updateRadius (+ (taylorSumE + xE)) resC {-| For a given polynomial @p@, compute a partial Taylor sum of @cos(p)@ and return it together with its error bound @e@ and the degree of the polynomial @n@. -} sineTaylorSum :: _ => (Accuracy -> f) -> MPBall -> Accuracy -> (f, ErrorBound, Integer) sineTaylorSum = sineCosineTaylorSum True {-| For a given polynomial @p@, compute a partial Taylor sum of @cos(p)@ and return it together with its error bound @e@ and the degree of the polynomial @n@. -} cosineTaylorSum :: _ => (Accuracy -> f) -> MPBall -> Accuracy -> (f, ErrorBound, Integer) cosineTaylorSum = sineCosineTaylorSum False sineCosineTaylorSum :: _ => Bool -> (Accuracy -> f) -> MPBall -> Accuracy -> (f, ErrorBound, Integer) sineCosineTaylorSum isSine (xAC :: Accuracy -> f) xM acGuidePre = let acGuide = acGuidePre + 4 _isCosine = not isSine -- Work out the degree of the highest term we need to get the -- Lagrange error bound acGuide-accurate: n = Map.size factorialsE - 1 -- the last one is used only for the error term (_, (_,_,termSumEB)) = Map.findMax factorialsE -- the Lagrange error bound for T_n -- At the same time, compute the factorials and keep the Lagrange error bounds: factorialsE = maybeTrace ("sineCosineTaylorSum: n = " ++ show (Map.size res - 1)) res where res = Map.fromAscList $ takeUntilAccurate $ map addE factorials factorials = aux 0 1 where aux i fc_i = (i,fc_i) : aux (i+1) (fc_i*(i+1)) addE (i, fc_i) = (i, (fc_i, xM_i, e_i)) where e_i = errorBound $ xM_i/fc_i xM_i = xM^i takeUntilAccurate (t_i@(i,(_fc_i, _xM_i,e_i)):rest) | getAccuracy e_i > acGuide && (even i == isSine) = [t_i] | otherwise = t_i : takeUntilAccurate rest takeUntilAccurate [] = error "sineCosineTaylorSum: internal error" -- Work out accuracy needed for each power x^n, given that x^n/n! should have -- accuracy around acGuide + 1: -- -log_2 (\eps/n!) ~ acGuide + 1 -- -log_2 (\eps) ~ acGuide + 1 - (-log_2(1/n!)) powerAccuracies0 = -- maybeTrace ("sineCosineTaylorSum: powerAccuracies0 = " ++ show res) res where res = Map.map aux factorialsE aux (fc_i,_xM_i,_e_i) = -- the accuracy needed of the power to give a sufficiently accurate term: acGuide + 1 + (bits $ getNormLog fc_i) -- Ensure the accuracies in powers are sufficient -- to compute accurate higher powers by their multiplications: powerAccuracies = -- maybeTrace ("sineCosineTaylorSum: powerAccuracies = " ++ show res) res where res = foldl updateAccuracies powerAccuracies0 $ drop 1 $ reverse $ -- from second-highest down to the lowest drop 2 $ Map.toAscList powerAccuracies0 -- the 2 lowest are computed directly updateAccuracies powerACs (i, ac_i) | odd i && odd j = -- pw_(2j+1) = x * pw_j * pw_j updateAC j (ac_i + log_pw_j + log_x) $ updateAC 1 (ac_i + log_pw_j + log_pw_j) $ powerACs -- pw_(2j+1) + e_pw2j1 = (x+e_x) * (pw_j + e_pwj) * (pw_j + e_pwj) -- = e_x * e_pwj * e_pwj -- ... -- + x * e_pwj * pw_j -- assume this term puts most constraint on the size of e_pwj -- + e_x * pw_j * pw_j -- assume this term puts most constraint on the size of e_x -- ... -- + x*pw_j*pw_j | odd i = -- pw_(2j+1) = x * pw_(j-1) * pw_(j+1) updateAC (j-1) (ac_i + log_pw_jU + log_x) $ updateAC (j+1) (ac_i + log_pw_jD + log_x) $ updateAC 1 (ac_i + log_pw_jU + log_pw_jD) $ powerACs | even j = -- pw_(2j) = (power j) * (power j) updateAC j (ac_i + log_pw_j) $ powerACs | otherwise = -- pw_(2j) = (power (j-1)) * (power (j+1)) updateAC (j-1) (ac_i + log_pw_jU) $ updateAC (j+1) (ac_i + log_pw_jD) $ powerACs where updateAC k ac_k = Map.adjust (max ac_k) k j = i `divI` 2 log_x = getLogXM 1 log_pw_j = getLogXM j log_pw_jU = getLogXM (j+1) log_pw_jD = getLogXM (j-1) getLogXM k = case (Map.lookup k factorialsE) of Just (_fc_k,xM_k,_e_k) -> bits $ getNormLog xM_k _ -> error "sineCosineTaylorSum: internal error" x = case Map.lookup 1 powerAccuracies of Just ac1 -> xAC ac1 _ -> error "sineCosineTaylorSum: internal error" -- Compute the powers needed for the terms, reducing their size while -- respecting the required accuracy: powers | isSine = powersSine | otherwise = powersCosine where powersSine = -- maybeTrace ("sineCosineTaylorSum: powerSine accuracies:\n" -- ++ (showPowerAccuracies res)) res where res = foldl addPower initPowers $ zip [1..] [3,5..n] initPowers = Map.fromAscList [(1, x)] addPower prevPowers (j,i) = maybeTrace (showPowerDebug i rpw_i) $ Map.insert i rpw_i prevPowers where rpw_i = reduce i pw_i pw_i | odd j = x * pwr j * pwr j | otherwise = x * pwr (j-1) * pwr (j+1) pwr k = case Map.lookup k prevPowers of Just r -> r _ -> error "sineCosineTaylorSum: internal error (powersSine: pwr k)" powersCosine = -- maybeTrace ("sineCosineTaylorSum: powerCosine accuracies:\n" -- ++ (showPowerAccuracies res)) res where res = foldl addPower initPowers $ zip [2..] [4,6..n] initPowers = Map.fromAscList [(2, xxR)] xxR = reduce 2 $ x*x addPower prevPowers (j,i) = maybeTrace (showPowerDebug i rpw_i) $ Map.insert i rpw_i prevPowers where rpw_i = reduce i pw_i pw_i | even j = pwr j * pwr j | otherwise = pwr (j-1) * pwr (j+1) pwr k = case Map.lookup k prevPowers of Just r -> r _ -> error "sineCosineTaylorSum: internal error (powersCosine: pwr k)" showPowerDebug :: Integer -> f -> String showPowerDebug i rpw_i = printf "power %d: accuracy req: %s, actual accuracy: %s" -- , degree: %d" i (show pa) (show $ getAccuracy rpw_i) -- (terms_degree $ poly_coeffs $ chPoly_poly p) where Just pa = Map.lookup i powerAccuracies -- showPowerAccuracies pwrs = -- unlines $ map showAAA $ Map.toAscList $ -- Map.intersectionWith (\p (pa0, pa) -> (pa0,pa, p)) pwrs $ -- Map.intersectionWith (,) powerAccuracies0 powerAccuracies -- where -- showAAA (i,(pa0,pa,p)) = -- printf "power %d: accuracy req 0: %s, accuracy req: %s, actual accuracy: %s" -- , degree: %d" -- i (show pa0) (show pa) (show $ getAccuracy p) -- (terms_degree $ poly_coeffs $ chPoly_poly p) reduce i = setPrecisionAtLeastAccuracy (ac_i + 10) where ac_i = case Map.lookup i powerAccuracies of Just ac -> ac _ -> error "sineCosineTaylorSum: internal error" termSum = maybeTrace ("sineCosineTaylorSum: term accuracies = " ++ (show (map (\(i,t) -> (i,getAccuracy t)) terms))) $ maybeTrace ("sineCosineTaylorSum: term partial sum accuracies = " ++ (show (map (getAccuracy . sumP) (tail $ List.inits (map snd terms))))) $ -- maybeTrace ("sineCosineTaylorSum: terms = " ++ (show terms)) $ -- maybeTrace ("sineCosineTaylorSum: term partial sums = " -- ++ (show (map sumP (tail $ List.inits (map snd terms))))) $ sumP (map snd terms) + initNum where sumP = foldl1 (+) terms = Map.toAscList $ Map.intersectionWithKey makeTerm powers factorialsE initNum | isSine = 0 | otherwise = 1 makeTerm i pwr (fact,_,_e) = sign * pwr/fact -- alternate signs where sign = if (even $ i `divI` 2) then 1 else -1 in (termSum, termSumEB, n) -- -- lookupForce :: P.Ord k => k -> Map.Map k a -> a -- lookupForce j amap = -- case Map.lookup j amap of -- Just t -> t -- Nothing -> error "internal error in SineCosine.lookupForce"
michalkonecny/aern2
aern2-fun/src/AERN2/RealFun/SineCosine.hs
bsd-3-clause
12,260
0
23
3,635
2,530
1,334
1,196
-1
-1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE ScopedTypeVariables #-} module Text.Authoring.State where import Control.Lens ((.~),(&),(^.)) import Control.Lens.TH (makeLenses) import Control.Monad import Control.Monad.RWS import Control.Monad.State as State import Control.Monad.Trans.Class (lift) import Data.Default import qualified Data.Map.Strict as Map import Data.Monoid import qualified Data.Set as Set import Data.String import Data.Text (Text) import Data.Typeable import Text.LaTeX (LaTeX) import Text.LaTeX.Base.Class (LaTeXC(..)) import Text.LaTeX.Base.Syntax (LaTeX) import Text.LaTeX.Base.Writer (LaTeXT, execLaTeXT) import qualified Text.CSL.Input.Identifier.Internal as Citation import Unsafe.Coerce -- | 'Label's are used to create a unique reference label -- in a paper. data Label = FromType !TypeRep | FromStr !String | Ap !Label !Label deriving (Eq, Ord) instance Show Label where show (FromType r) = show r show (FromStr s) = s show (Ap a b) = show a ++ show b infixl 1 ./ -- | Create a slightly different version of the label. (./) :: Show a => Label -> a -> Label l ./ x = Ap l (FromStr $ show x) -- | 'AuthorState' maintains whatever information -- needed to proceed the authoring of the body of a paper. -- After completing the body part, 'AuthorState' is used -- for generating bibliographies, etc. data AuthorState = AuthorState { _labelMap :: Map.Map Label Text , _citationDB :: Citation.DB , _citedUrlSet :: Set.Set String } $(makeLenses ''AuthorState) instance Default AuthorState where def = AuthorState def def def -- | An RWST monad that writes a 'LaTeX' and keeps 'AuthorState' type AuthorT = RWST () LaTeX AuthorState -- | An RWST monad that writes a 'LaTeX' and keeps 'AuthorState' type MonadAuthor = MonadRWS () LaTeX AuthorState -- | given a citation database filename and an 'AuthorT' monad to run, -- performs the authoring, updates the citation database file, -- runAuthorTWithDBFile :: forall m a. (MonadIO m) => FilePath -> AuthorT m a -> m (a, AuthorState, LaTeX) runAuthorTWithDBFile fn prog = do evalStateT (Citation.withDBFile fn go) def where go :: StateT Citation.DB m (a, AuthorState, LaTeX) go = do db1 <- State.get ret@(ret2, rootState2, doc2) <- lift $ runRWST prog () (def & citationDB .~ db1) State.put (rootState2 ^. citationDB) return ret instance Monad m => Monoid (AuthorT m a) where mempty = return $ unsafeCoerce () mappend = (>>) instance Monad m => IsString (AuthorT m a) where fromString str = (tell $ fromString str) >> mempty instance Monad m => LaTeXC (AuthorT m a) where liftListL f xs = do -- run the arguments piecewise, while updating the state and collecting the arguments. fragments <- forM xs $ \x -> do s0 <- get (_, s1, w1) <- lift $ runRWST x () s0 put s1 return w1 tell $ f fragments mempty
nushio3/authoring
old-src/Text/Authoring/State.hs
bsd-3-clause
3,233
0
16
777
841
464
377
79
1
{-# LANGUAGE OverloadedStrings, CPP #-} module ListEdit ( wlistEd) where import Text.Blaze.Html5 as El import Text.Blaze.Html5.Attributes as At hiding (step) import Data.String -- #define ALONE #ifdef ALONE import MFlow.Wai.Blaze.Html.All main= runNavigation "" $ transientNav wlistEd #else import MFlow.Wai.Blaze.Html.All hiding(page) import Menu #endif wlistEd= do r <- page $ pageFlow "listed" $ addLink ++> br ++> (wEditList El.div getString1 ["hi", "how are you"] "wEditListAdd") <++ br <** submitButton "send" page $ p << (show r ++ " returned") ++> wlink () (p " back to menu") where addLink = a ! At.id "wEditListAdd" ! href "#" $ b "add" delBox = input ! type_ "checkbox" ! checked "" ! onclick "this.parentNode.parentNode.removeChild(this.parentNode)" getString1 mx= El.div <<< delBox ++> getString mx <++ br -- to run it alone, change page by ask and uncomment this: --main= runNavigation "" $ transientNav wListEd
agocorona/MFlow
Demos/ListEdit.hs
bsd-3-clause
1,120
0
14
332
248
133
115
23
1
{-# LANGUAGE PatternSynonyms #-} module Main (main) where import Data.Matrix import System.Environment import System.FilePath.Posix (splitExtension) import Data.Matrix.Matlab pattern Extension = ".qx" main :: IO () main = do args <- getArgs case args of [fileName] | (_, Extension) <- splitExtension fileName -> do fileContents <- readFile fileName let Matlab mat = read fileContents :: Matlab Integer print (Matlab (fmap (^2) mat)) | otherwise -> error ("Wrong extension (expected " ++ Extension ++ ")") _ -> error "Wrong number of arguments. Expected 1."
ku-fpg/ecc-ldpc
utilities/ExpMatrix/Main.hs
bsd-3-clause
632
0
18
157
190
96
94
19
2
{-# LANGUAGE NoImplicitPrelude #-} module Protocol.ROC.PointTypes.PointType86 where import Data.Binary.Get (getWord8,Get) import Data.Word (Word8) import Prelude (($), return, Eq, Read, Show) import Protocol.ROC.Utils (getTLP) data PointType86 = PointType86 { pointType86MaxNumExtHistPnts :: !PointType86MaxNumExtHistPnts ,pointType86SampleLogInterval :: !PointType86SampleLogInterval ,pointType86PointTagIDTLP1 :: !PointType86PointTagIDTLP1 ,pointType86ExtHistLogPnt1 :: !PointType86ExtHistLogPnt1 ,pointType86ArchiveType1 :: !PointType86ArchiveType1 ,pointType86AveragingorRateType1 :: !PointType86AveragingorRateType1 ,pointType86PointTagIDTLP2 :: !PointType86PointTagIDTLP2 ,pointType86ExtHistLogPnt2 :: !PointType86ExtHistLogPnt2 ,pointType86ArchiveType2 :: !PointType86ArchiveType2 ,pointType86AveragingorRateType2 :: !PointType86AveragingorRateType2 ,pointType86PointTagIDTLP3 :: !PointType86PointTagIDTLP3 ,pointType86ExtHistLogPnt3 :: !PointType86ExtHistLogPnt3 ,pointType86ArchiveType3 :: !PointType86ArchiveType3 ,pointType86AveragingorRateType3 :: !PointType86AveragingorRateType3 ,pointType86PointTagIDTLP4 :: !PointType86PointTagIDTLP4 ,pointType86ExtHistLogPnt4 :: !PointType86ExtHistLogPnt4 ,pointType86ArchiveType4 :: !PointType86ArchiveType4 ,pointType86AveragingorRateType4 :: !PointType86AveragingorRateType4 ,pointType86PointTagIDTLP5 :: !PointType86PointTagIDTLP5 ,pointType86ExtHistLogPnt5 :: !PointType86ExtHistLogPnt5 ,pointType86ArchiveType5 :: !PointType86ArchiveType5 ,pointType86AveragingorRateType5 :: !PointType86AveragingorRateType5 ,pointType86PointTagIDTLP6 :: !PointType86PointTagIDTLP6 ,pointType86ExtHistLogPnt6 :: !PointType86ExtHistLogPnt6 ,pointType86ArchiveType6 :: !PointType86ArchiveType6 ,pointType86AveragingorRateType6 :: !PointType86AveragingorRateType6 ,pointType86PointTagIDTLP7 :: !PointType86PointTagIDTLP7 ,pointType86ExtHistLogPnt7 :: !PointType86ExtHistLogPnt7 ,pointType86ArchiveType7 :: !PointType86ArchiveType7 ,pointType86AveragingorRateType7 :: !PointType86AveragingorRateType7 ,pointType86PointTagIDTLP8 :: !PointType86PointTagIDTLP8 ,pointType86ExtHistLogPnt8 :: !PointType86ExtHistLogPnt8 ,pointType86ArchiveType8 :: !PointType86ArchiveType8 ,pointType86AveragingorRateType8 :: !PointType86AveragingorRateType8 ,pointType86PointTagIDTLP9 :: !PointType86PointTagIDTLP9 ,pointType86ExtHistLogPnt9 :: !PointType86ExtHistLogPnt9 ,pointType86ArchiveType9 :: !PointType86ArchiveType9 ,pointType86AveragingorRateType9 :: !PointType86AveragingorRateType9 ,pointType86PointTagIDTLP10 :: !PointType86PointTagIDTLP10 ,pointType86ExtHistLogPnt10 :: !PointType86ExtHistLogPnt10 ,pointType86ArchiveType10 :: !PointType86ArchiveType10 ,pointType86AveragingorRateType10 :: !PointType86AveragingorRateType10 ,pointType86PointTagIDTLP11 :: !PointType86PointTagIDTLP11 ,pointType86ExtHistLogPnt11 :: !PointType86ExtHistLogPnt11 ,pointType86ArchiveType11 :: !PointType86ArchiveType11 ,pointType86AveragingorRateType11 :: !PointType86AveragingorRateType11 ,pointType86PointTagIDTLP12 :: !PointType86PointTagIDTLP12 ,pointType86ExtHistLogPnt12 :: !PointType86ExtHistLogPnt12 ,pointType86ArchiveType12 :: !PointType86ArchiveType12 ,pointType86AveragingorRateType12 :: !PointType86AveragingorRateType12 ,pointType86PointTagIDTLP13 :: !PointType86PointTagIDTLP13 ,pointType86ExtHistLogPnt13 :: !PointType86ExtHistLogPnt13 ,pointType86ArchiveType13 :: !PointType86ArchiveType13 ,pointType86AveragingorRateType13 :: !PointType86AveragingorRateType13 ,pointType86PointTagIDTLP14 :: !PointType86PointTagIDTLP14 ,pointType86ExtHistLogPnt14 :: !PointType86ExtHistLogPnt14 ,pointType86ArchiveType14 :: !PointType86ArchiveType14 ,pointType86AveragingorRateType14 :: !PointType86AveragingorRateType14 ,pointType86PointTagIDTLP15 :: !PointType86PointTagIDTLP15 ,pointType86ExtHistLogPnt15 :: !PointType86ExtHistLogPnt15 ,pointType86ArchiveType15 :: !PointType86ArchiveType15 ,pointType86AveragingorRateType15 :: !PointType86AveragingorRateType15 ,pointType86PointTagIDTLP16 :: !PointType86PointTagIDTLP16 ,pointType86ExtHistLogPnt16 :: !PointType86ExtHistLogPnt16 ,pointType86ArchiveType16 :: !PointType86ArchiveType16 ,pointType86AveragingorRateType16 :: !PointType86AveragingorRateType16 ,pointType86PointTagIDTLP17 :: !PointType86PointTagIDTLP17 ,pointType86ExtHistLogPnt17 :: !PointType86ExtHistLogPnt17 ,pointType86ArchiveType17 :: !PointType86ArchiveType17 ,pointType86AveragingorRateType17 :: !PointType86AveragingorRateType17 ,pointType86PointTagIDTLP18 :: !PointType86PointTagIDTLP18 ,pointType86ExtHistLogPnt18 :: !PointType86ExtHistLogPnt18 ,pointType86ArchiveType18 :: !PointType86ArchiveType18 ,pointType86AveragingorRateType18 :: !PointType86AveragingorRateType18 ,pointType86PointTagIDTLP19 :: !PointType86PointTagIDTLP19 ,pointType86ExtHistLogPnt19 :: !PointType86ExtHistLogPnt19 ,pointType86ArchiveType19 :: !PointType86ArchiveType19 ,pointType86AveragingorRateType19 :: !PointType86AveragingorRateType19 ,pointType86PointTagIDTLP20 :: !PointType86PointTagIDTLP20 ,pointType86ExtHistLogPnt20 :: !PointType86ExtHistLogPnt20 ,pointType86ArchiveType20 :: !PointType86ArchiveType20 ,pointType86AveragingorRateType20 :: !PointType86AveragingorRateType20 ,pointType86PointTagIDTLP21 :: !PointType86PointTagIDTLP21 ,pointType86ExtHistLogPnt21 :: !PointType86ExtHistLogPnt21 ,pointType86ArchiveType21 :: !PointType86ArchiveType21 ,pointType86AveragingorRateType21 :: !PointType86AveragingorRateType21 ,pointType86PointTagIDTLP22 :: !PointType86PointTagIDTLP22 ,pointType86ExtHistLogPnt22 :: !PointType86ExtHistLogPnt22 ,pointType86ArchiveType22 :: !PointType86ArchiveType22 ,pointType86AveragingorRateType22 :: !PointType86AveragingorRateType22 ,pointType86PointTagIDTLP23 :: !PointType86PointTagIDTLP23 ,pointType86ExtHistLogPnt23 :: !PointType86ExtHistLogPnt23 ,pointType86ArchiveType23 :: !PointType86ArchiveType23 ,pointType86AveragingorRateType23 :: !PointType86AveragingorRateType23 ,pointType86PointTagIDTLP24 :: !PointType86PointTagIDTLP24 ,pointType86ExtHistLogPnt24 :: !PointType86ExtHistLogPnt24 ,pointType86ArchiveType24 :: !PointType86ArchiveType24 ,pointType86AveragingorRateType24 :: !PointType86AveragingorRateType24 ,pointType86PointTagIDTLP25 :: !PointType86PointTagIDTLP25 ,pointType86ExtHistLogPnt25 :: !PointType86ExtHistLogPnt25 ,pointType86ArchiveType25 :: !PointType86ArchiveType25 ,pointType86AveragingorRateType25 :: !PointType86AveragingorRateType25 ,pointType86PointTagIDTLP26 :: !PointType86PointTagIDTLP26 ,pointType86ExtHistLogPnt26 :: !PointType86ExtHistLogPnt26 ,pointType86ArchiveType26 :: !PointType86ArchiveType26 ,pointType86AveragingorRateType26 :: !PointType86AveragingorRateType26 ,pointType86PointTagIDTLP27 :: !PointType86PointTagIDTLP27 ,pointType86ExtHistLogPnt27 :: !PointType86ExtHistLogPnt27 ,pointType86ArchiveType27 :: !PointType86ArchiveType27 ,pointType86AveragingorRateType27 :: !PointType86AveragingorRateType27 ,pointType86PointTagIDTLP28 :: !PointType86PointTagIDTLP28 ,pointType86ExtHistLogPnt28 :: !PointType86ExtHistLogPnt28 ,pointType86ArchiveType28 :: !PointType86ArchiveType28 ,pointType86AveragingorRateType28 :: !PointType86AveragingorRateType28 ,pointType86PointTagIDTLP29 :: !PointType86PointTagIDTLP29 ,pointType86ExtHistLogPnt29 :: !PointType86ExtHistLogPnt29 ,pointType86ArchiveType29 :: !PointType86ArchiveType29 ,pointType86AveragingorRateType29 :: !PointType86AveragingorRateType29 ,pointType86PointTagIDTLP30 :: !PointType86PointTagIDTLP30 ,pointType86ExtHistLogPnt30 :: !PointType86ExtHistLogPnt30 ,pointType86ArchiveType30 :: !PointType86ArchiveType30 ,pointType86AveragingorRateType30 :: !PointType86AveragingorRateType30 ,pointType86PointTagIDTLP31 :: !PointType86PointTagIDTLP31 ,pointType86ExtHistLogPnt31 :: !PointType86ExtHistLogPnt31 ,pointType86ArchiveType31 :: !PointType86ArchiveType31 ,pointType86AveragingorRateType31 :: !PointType86AveragingorRateType31 ,pointType86PointTagIDTLP32 :: !PointType86PointTagIDTLP32 ,pointType86ExtHistLogPnt32 :: !PointType86ExtHistLogPnt32 ,pointType86ArchiveType32 :: !PointType86ArchiveType32 ,pointType86AveragingorRateType32 :: !PointType86AveragingorRateType32 ,pointType86PointTagIDTLP33 :: !PointType86PointTagIDTLP33 ,pointType86ExtHistLogPnt33 :: !PointType86ExtHistLogPnt33 ,pointType86ArchiveType33 :: !PointType86ArchiveType33 ,pointType86AveragingorRateType33 :: !PointType86AveragingorRateType33 ,pointType86PointTagIDTLP34 :: !PointType86PointTagIDTLP34 ,pointType86ExtHistLogPnt34 :: !PointType86ExtHistLogPnt34 ,pointType86ArchiveType34 :: !PointType86ArchiveType34 ,pointType86AveragingorRateType34 :: !PointType86AveragingorRateType34 ,pointType86PointTagIDTLP35 :: !PointType86PointTagIDTLP35 ,pointType86ExtHistLogPnt35 :: !PointType86ExtHistLogPnt35 ,pointType86ArchiveType35 :: !PointType86ArchiveType35 ,pointType86AveragingorRateType35 :: !PointType86AveragingorRateType35 ,pointType86PointTagIDTLP36 :: !PointType86PointTagIDTLP36 ,pointType86ExtHistLogPnt36 :: !PointType86ExtHistLogPnt36 ,pointType86ArchiveType36 :: !PointType86ArchiveType36 ,pointType86AveragingorRateType36 :: !PointType86AveragingorRateType36 ,pointType86PointTagIDTLP37 :: !PointType86PointTagIDTLP37 ,pointType86ExtHistLogPnt37 :: !PointType86ExtHistLogPnt37 ,pointType86ArchiveType37 :: !PointType86ArchiveType37 ,pointType86AveragingorRateType37 :: !PointType86AveragingorRateType37 ,pointType86PointTagIDTLP38 :: !PointType86PointTagIDTLP38 ,pointType86ExtHistLogPnt38 :: !PointType86ExtHistLogPnt38 ,pointType86ArchiveType38 :: !PointType86ArchiveType38 ,pointType86AveragingorRateType38 :: !PointType86AveragingorRateType38 ,pointType86PointTagIDTLP39 :: !PointType86PointTagIDTLP39 ,pointType86ExtHistLogPnt39 :: !PointType86ExtHistLogPnt39 ,pointType86ArchiveType39 :: !PointType86ArchiveType39 ,pointType86AveragingorRateType39 :: !PointType86AveragingorRateType39 ,pointType86PointTagIDTLP40 :: !PointType86PointTagIDTLP40 ,pointType86ExtHistLogPnt40 :: !PointType86ExtHistLogPnt40 ,pointType86ArchiveType40 :: !PointType86ArchiveType40 ,pointType86AveragingorRateType40 :: !PointType86AveragingorRateType40 ,pointType86PointTagIDTLP41 :: !PointType86PointTagIDTLP41 ,pointType86ExtHistLogPnt41 :: !PointType86ExtHistLogPnt41 ,pointType86ArchiveType41 :: !PointType86ArchiveType41 ,pointType86AveragingorRateType41 :: !PointType86AveragingorRateType41 ,pointType86PointTagIDTLP42 :: !PointType86PointTagIDTLP42 ,pointType86ExtHistLogPnt42 :: !PointType86ExtHistLogPnt42 ,pointType86ArchiveType42 :: !PointType86ArchiveType42 ,pointType86AveragingorRateType42 :: !PointType86AveragingorRateType42 ,pointType86PointTagIDTLP43 :: !PointType86PointTagIDTLP43 ,pointType86ExtHistLogPnt43 :: !PointType86ExtHistLogPnt43 ,pointType86ArchiveType43 :: !PointType86ArchiveType43 ,pointType86AveragingorRateType43 :: !PointType86AveragingorRateType43 ,pointType86PointTagIDTLP44 :: !PointType86PointTagIDTLP44 ,pointType86ExtHistLogPnt44 :: !PointType86ExtHistLogPnt44 ,pointType86ArchiveType44 :: !PointType86ArchiveType44 ,pointType86AveragingorRateType44 :: !PointType86AveragingorRateType44 ,pointType86PointTagIDTLP45 :: !PointType86PointTagIDTLP45 ,pointType86ExtHistLogPnt45 :: !PointType86ExtHistLogPnt45 ,pointType86ArchiveType45 :: !PointType86ArchiveType45 ,pointType86AveragingorRateType45 :: !PointType86AveragingorRateType45 ,pointType86PointTagIDTLP46 :: !PointType86PointTagIDTLP46 ,pointType86ExtHistLogPnt46 :: !PointType86ExtHistLogPnt46 ,pointType86ArchiveType46 :: !PointType86ArchiveType46 ,pointType86AveragingorRateType46 :: !PointType86AveragingorRateType46 ,pointType86PointTagIDTLP47 :: !PointType86PointTagIDTLP47 ,pointType86ExtHistLogPnt47 :: !PointType86ExtHistLogPnt47 ,pointType86ArchiveType47 :: !PointType86ArchiveType47 ,pointType86AveragingorRateType47 :: !PointType86AveragingorRateType47 ,pointType86PointTagIDTLP48 :: !PointType86PointTagIDTLP48 ,pointType86ExtHistLogPnt48 :: !PointType86ExtHistLogPnt48 ,pointType86ArchiveType48 :: !PointType86ArchiveType48 ,pointType86AveragingorRateType48 :: !PointType86AveragingorRateType48 ,pointType86PointTagIDTLP49 :: !PointType86PointTagIDTLP49 ,pointType86ExtHistLogPnt49 :: !PointType86ExtHistLogPnt49 ,pointType86ArchiveType49 :: !PointType86ArchiveType49 ,pointType86AveragingorRateType49 :: !PointType86AveragingorRateType49 ,pointType86PointTagIDTLP50 :: !PointType86PointTagIDTLP50 ,pointType86ExtHistLogPnt50 :: !PointType86ExtHistLogPnt50 ,pointType86ArchiveType50 :: !PointType86ArchiveType50 ,pointType86AveragingorRateType50 :: !PointType86AveragingorRateType50 } deriving (Read,Eq, Show) type PointType86MaxNumExtHistPnts = Word8 type PointType86SampleLogInterval = Word8 type PointType86PointTagIDTLP1 = [Word8] type PointType86ExtHistLogPnt1 = [Word8] type PointType86ArchiveType1 = Word8 type PointType86AveragingorRateType1 = Word8 type PointType86PointTagIDTLP2 = [Word8] type PointType86ExtHistLogPnt2 = [Word8] type PointType86ArchiveType2 = Word8 type PointType86AveragingorRateType2 = Word8 type PointType86PointTagIDTLP3 = [Word8] type PointType86ExtHistLogPnt3 = [Word8] type PointType86ArchiveType3 = Word8 type PointType86AveragingorRateType3 = Word8 type PointType86PointTagIDTLP4 = [Word8] type PointType86ExtHistLogPnt4 = [Word8] type PointType86ArchiveType4 = Word8 type PointType86AveragingorRateType4 = Word8 type PointType86PointTagIDTLP5 = [Word8] type PointType86ExtHistLogPnt5 = [Word8] type PointType86ArchiveType5 = Word8 type PointType86AveragingorRateType5 = Word8 type PointType86PointTagIDTLP6 = [Word8] type PointType86ExtHistLogPnt6 = [Word8] type PointType86ArchiveType6 = Word8 type PointType86AveragingorRateType6 = Word8 type PointType86PointTagIDTLP7 = [Word8] type PointType86ExtHistLogPnt7 = [Word8] type PointType86ArchiveType7 = Word8 type PointType86AveragingorRateType7 = Word8 type PointType86PointTagIDTLP8 = [Word8] type PointType86ExtHistLogPnt8 = [Word8] type PointType86ArchiveType8 = Word8 type PointType86AveragingorRateType8 = Word8 type PointType86PointTagIDTLP9 = [Word8] type PointType86ExtHistLogPnt9 = [Word8] type PointType86ArchiveType9 = Word8 type PointType86AveragingorRateType9 = Word8 type PointType86PointTagIDTLP10 = [Word8] type PointType86ExtHistLogPnt10 = [Word8] type PointType86ArchiveType10 = Word8 type PointType86AveragingorRateType10 = Word8 type PointType86PointTagIDTLP11 = [Word8] type PointType86ExtHistLogPnt11 = [Word8] type PointType86ArchiveType11 = Word8 type PointType86AveragingorRateType11 = Word8 type PointType86PointTagIDTLP12 = [Word8] type PointType86ExtHistLogPnt12 = [Word8] type PointType86ArchiveType12 = Word8 type PointType86AveragingorRateType12 = Word8 type PointType86PointTagIDTLP13 = [Word8] type PointType86ExtHistLogPnt13 = [Word8] type PointType86ArchiveType13 = Word8 type PointType86AveragingorRateType13 = Word8 type PointType86PointTagIDTLP14 = [Word8] type PointType86ExtHistLogPnt14 = [Word8] type PointType86ArchiveType14 = Word8 type PointType86AveragingorRateType14 = Word8 type PointType86PointTagIDTLP15 = [Word8] type PointType86ExtHistLogPnt15 = [Word8] type PointType86ArchiveType15 = Word8 type PointType86AveragingorRateType15 = Word8 type PointType86PointTagIDTLP16 = [Word8] type PointType86ExtHistLogPnt16 = [Word8] type PointType86ArchiveType16 = Word8 type PointType86AveragingorRateType16 = Word8 type PointType86PointTagIDTLP17 = [Word8] type PointType86ExtHistLogPnt17 = [Word8] type PointType86ArchiveType17 = Word8 type PointType86AveragingorRateType17 = Word8 type PointType86PointTagIDTLP18 = [Word8] type PointType86ExtHistLogPnt18 = [Word8] type PointType86ArchiveType18 = Word8 type PointType86AveragingorRateType18 = Word8 type PointType86PointTagIDTLP19 = [Word8] type PointType86ExtHistLogPnt19 = [Word8] type PointType86ArchiveType19 = Word8 type PointType86AveragingorRateType19 = Word8 type PointType86PointTagIDTLP20 = [Word8] type PointType86ExtHistLogPnt20 = [Word8] type PointType86ArchiveType20 = Word8 type PointType86AveragingorRateType20 = Word8 type PointType86PointTagIDTLP21 = [Word8] type PointType86ExtHistLogPnt21 = [Word8] type PointType86ArchiveType21 = Word8 type PointType86AveragingorRateType21 = Word8 type PointType86PointTagIDTLP22 = [Word8] type PointType86ExtHistLogPnt22 = [Word8] type PointType86ArchiveType22 = Word8 type PointType86AveragingorRateType22 = Word8 type PointType86PointTagIDTLP23 = [Word8] type PointType86ExtHistLogPnt23 = [Word8] type PointType86ArchiveType23 = Word8 type PointType86AveragingorRateType23 = Word8 type PointType86PointTagIDTLP24 = [Word8] type PointType86ExtHistLogPnt24 = [Word8] type PointType86ArchiveType24 = Word8 type PointType86AveragingorRateType24 = Word8 type PointType86PointTagIDTLP25 = [Word8] type PointType86ExtHistLogPnt25 = [Word8] type PointType86ArchiveType25 = Word8 type PointType86AveragingorRateType25 = Word8 type PointType86PointTagIDTLP26 = [Word8] type PointType86ExtHistLogPnt26 = [Word8] type PointType86ArchiveType26 = Word8 type PointType86AveragingorRateType26 = Word8 type PointType86PointTagIDTLP27 = [Word8] type PointType86ExtHistLogPnt27 = [Word8] type PointType86ArchiveType27 = Word8 type PointType86AveragingorRateType27 = Word8 type PointType86PointTagIDTLP28 = [Word8] type PointType86ExtHistLogPnt28 = [Word8] type PointType86ArchiveType28 = Word8 type PointType86AveragingorRateType28 = Word8 type PointType86PointTagIDTLP29 = [Word8] type PointType86ExtHistLogPnt29 = [Word8] type PointType86ArchiveType29 = Word8 type PointType86AveragingorRateType29 = Word8 type PointType86PointTagIDTLP30 = [Word8] type PointType86ExtHistLogPnt30 = [Word8] type PointType86ArchiveType30 = Word8 type PointType86AveragingorRateType30 = Word8 type PointType86PointTagIDTLP31 = [Word8] type PointType86ExtHistLogPnt31 = [Word8] type PointType86ArchiveType31 = Word8 type PointType86AveragingorRateType31 = Word8 type PointType86PointTagIDTLP32 = [Word8] type PointType86ExtHistLogPnt32 = [Word8] type PointType86ArchiveType32 = Word8 type PointType86AveragingorRateType32 = Word8 type PointType86PointTagIDTLP33 = [Word8] type PointType86ExtHistLogPnt33 = [Word8] type PointType86ArchiveType33 = Word8 type PointType86AveragingorRateType33 = Word8 type PointType86PointTagIDTLP34 = [Word8] type PointType86ExtHistLogPnt34 = [Word8] type PointType86ArchiveType34 = Word8 type PointType86AveragingorRateType34 = Word8 type PointType86PointTagIDTLP35 = [Word8] type PointType86ExtHistLogPnt35 = [Word8] type PointType86ArchiveType35 = Word8 type PointType86AveragingorRateType35 = Word8 type PointType86PointTagIDTLP36 = [Word8] type PointType86ExtHistLogPnt36 = [Word8] type PointType86ArchiveType36 = Word8 type PointType86AveragingorRateType36 = Word8 type PointType86PointTagIDTLP37 = [Word8] type PointType86ExtHistLogPnt37 = [Word8] type PointType86ArchiveType37 = Word8 type PointType86AveragingorRateType37 = Word8 type PointType86PointTagIDTLP38 = [Word8] type PointType86ExtHistLogPnt38 = [Word8] type PointType86ArchiveType38 = Word8 type PointType86AveragingorRateType38 = Word8 type PointType86PointTagIDTLP39 = [Word8] type PointType86ExtHistLogPnt39 = [Word8] type PointType86ArchiveType39 = Word8 type PointType86AveragingorRateType39 = Word8 type PointType86PointTagIDTLP40 = [Word8] type PointType86ExtHistLogPnt40 = [Word8] type PointType86ArchiveType40 = Word8 type PointType86AveragingorRateType40 = Word8 type PointType86PointTagIDTLP41 = [Word8] type PointType86ExtHistLogPnt41 = [Word8] type PointType86ArchiveType41 = Word8 type PointType86AveragingorRateType41 = Word8 type PointType86PointTagIDTLP42 = [Word8] type PointType86ExtHistLogPnt42 = [Word8] type PointType86ArchiveType42 = Word8 type PointType86AveragingorRateType42 = Word8 type PointType86PointTagIDTLP43 = [Word8] type PointType86ExtHistLogPnt43 = [Word8] type PointType86ArchiveType43 = Word8 type PointType86AveragingorRateType43 = Word8 type PointType86PointTagIDTLP44 = [Word8] type PointType86ExtHistLogPnt44 = [Word8] type PointType86ArchiveType44 = Word8 type PointType86AveragingorRateType44 = Word8 type PointType86PointTagIDTLP45 = [Word8] type PointType86ExtHistLogPnt45 = [Word8] type PointType86ArchiveType45 = Word8 type PointType86AveragingorRateType45 = Word8 type PointType86PointTagIDTLP46 = [Word8] type PointType86ExtHistLogPnt46 = [Word8] type PointType86ArchiveType46 = Word8 type PointType86AveragingorRateType46 = Word8 type PointType86PointTagIDTLP47 = [Word8] type PointType86ExtHistLogPnt47 = [Word8] type PointType86ArchiveType47 = Word8 type PointType86AveragingorRateType47 = Word8 type PointType86PointTagIDTLP48 = [Word8] type PointType86ExtHistLogPnt48 = [Word8] type PointType86ArchiveType48 = Word8 type PointType86AveragingorRateType48 = Word8 type PointType86PointTagIDTLP49 = [Word8] type PointType86ExtHistLogPnt49 = [Word8] type PointType86ArchiveType49 = Word8 type PointType86AveragingorRateType49 = Word8 type PointType86PointTagIDTLP50 = [Word8] type PointType86ExtHistLogPnt50 = [Word8] type PointType86ArchiveType50 = Word8 type PointType86AveragingorRateType50 = Word8 pointType86Parser :: Get PointType86 pointType86Parser = do maxNumExtHistPnts <- getWord8 sampleLogInterval <- getWord8 pointTagIDTLP1 <- getTLP extHistLogPnt1 <- getTLP archiveType1 <- getWord8 averagingorRateType1 <- getWord8 pointTagIDTLP2 <- getTLP extHistLogPnt2 <- getTLP archiveType2 <- getWord8 averagingorRateType2 <- getWord8 pointTagIDTLP3 <- getTLP extHistLogPnt3 <- getTLP archiveType3 <- getWord8 averagingorRateType3 <- getWord8 pointTagIDTLP4 <- getTLP extHistLogPnt4 <- getTLP archiveType4 <- getWord8 averagingorRateType4 <- getWord8 pointTagIDTLP5 <- getTLP extHistLogPnt5 <- getTLP archiveType5 <- getWord8 averagingorRateType5 <- getWord8 pointTagIDTLP6 <- getTLP extHistLogPnt6 <- getTLP archiveType6 <- getWord8 averagingorRateType6 <- getWord8 pointTagIDTLP7 <- getTLP extHistLogPnt7 <- getTLP archiveType7 <- getWord8 averagingorRateType7 <- getWord8 pointTagIDTLP8 <- getTLP extHistLogPnt8 <- getTLP archiveType8 <- getWord8 averagingorRateType8 <- getWord8 pointTagIDTLP9 <- getTLP extHistLogPnt9 <- getTLP archiveType9 <- getWord8 averagingorRateType9 <- getWord8 pointTagIDTLP10 <- getTLP extHistLogPnt10 <- getTLP archiveType10 <- getWord8 averagingorRateType10 <-getWord8 pointTagIDTLP11 <- getTLP extHistLogPnt11 <- getTLP archiveType11 <- getWord8 averagingorRateType11 <- getWord8 pointTagIDTLP12 <- getTLP extHistLogPnt12 <- getTLP archiveType12 <- getWord8 averagingorRateType12 <- getWord8 pointTagIDTLP13 <- getTLP extHistLogPnt13 <- getTLP archiveType13 <- getWord8 averagingorRateType13 <- getWord8 pointTagIDTLP14 <- getTLP extHistLogPnt14 <- getTLP archiveType14 <- getWord8 averagingorRateType14 <- getWord8 pointTagIDTLP15 <- getTLP extHistLogPnt15 <- getTLP archiveType15 <- getWord8 averagingorRateType15 <- getWord8 pointTagIDTLP16 <- getTLP extHistLogPnt16 <- getTLP archiveType16 <- getWord8 averagingorRateType16 <- getWord8 pointTagIDTLP17 <- getTLP extHistLogPnt17 <- getTLP archiveType17 <- getWord8 averagingorRateType17 <- getWord8 pointTagIDTLP18 <- getTLP extHistLogPnt18 <- getTLP archiveType18 <- getWord8 averagingorRateType18 <- getWord8 pointTagIDTLP19 <- getTLP extHistLogPnt19 <- getTLP archiveType19 <- getWord8 averagingorRateType19 <- getWord8 pointTagIDTLP20 <- getTLP extHistLogPnt20 <- getTLP archiveType20 <- getWord8 averagingorRateType20 <- getWord8 pointTagIDTLP21 <- getTLP extHistLogPnt21 <- getTLP archiveType21 <- getWord8 averagingorRateType21 <- getWord8 pointTagIDTLP22 <- getTLP extHistLogPnt22 <- getTLP archiveType22 <- getWord8 averagingorRateType22 <- getWord8 pointTagIDTLP23 <- getTLP extHistLogPnt23 <- getTLP archiveType23 <- getWord8 averagingorRateType23 <- getWord8 pointTagIDTLP24 <- getTLP extHistLogPnt24 <- getTLP archiveType24 <- getWord8 averagingorRateType24 <- getWord8 pointTagIDTLP25 <- getTLP extHistLogPnt25 <- getTLP archiveType25 <- getWord8 averagingorRateType25 <- getWord8 pointTagIDTLP26 <- getTLP extHistLogPnt26 <- getTLP archiveType26 <- getWord8 averagingorRateType26 <- getWord8 pointTagIDTLP27 <- getTLP extHistLogPnt27 <- getTLP archiveType27 <- getWord8 averagingorRateType27 <- getWord8 pointTagIDTLP28 <- getTLP extHistLogPnt28 <- getTLP archiveType28 <- getWord8 averagingorRateType28 <- getWord8 pointTagIDTLP29 <- getTLP extHistLogPnt29 <- getTLP archiveType29 <- getWord8 averagingorRateType29 <- getWord8 pointTagIDTLP30 <- getTLP extHistLogPnt30 <- getTLP archiveType30 <- getWord8 averagingorRateType30 <- getWord8 pointTagIDTLP31 <- getTLP extHistLogPnt31 <- getTLP archiveType31 <- getWord8 averagingorRateType31 <- getWord8 pointTagIDTLP32 <- getTLP extHistLogPnt32 <- getTLP archiveType32 <- getWord8 averagingorRateType32 <- getWord8 pointTagIDTLP33 <- getTLP extHistLogPnt33 <- getTLP archiveType33 <- getWord8 averagingorRateType33 <- getWord8 pointTagIDTLP34 <- getTLP extHistLogPnt34 <- getTLP archiveType34 <- getWord8 averagingorRateType34 <- getWord8 pointTagIDTLP35 <- getTLP extHistLogPnt35 <- getTLP archiveType35 <- getWord8 averagingorRateType35 <-getWord8 pointTagIDTLP36 <- getTLP extHistLogPnt36 <- getTLP archiveType36 <- getWord8 averagingorRateType36 <- getWord8 pointTagIDTLP37 <- getTLP extHistLogPnt37 <- getTLP archiveType37 <- getWord8 averagingorRateType37 <- getWord8 pointTagIDTLP38 <- getTLP extHistLogPnt38 <- getTLP archiveType38 <- getWord8 averagingorRateType38 <- getWord8 pointTagIDTLP39 <- getTLP extHistLogPnt39 <- getTLP archiveType39 <- getWord8 averagingorRateType39 <- getWord8 pointTagIDTLP40 <- getTLP extHistLogPnt40 <- getTLP archiveType40 <- getWord8 averagingorRateType40 <- getWord8 pointTagIDTLP41 <- getTLP extHistLogPnt41 <- getTLP archiveType41 <- getWord8 averagingorRateType41 <- getWord8 pointTagIDTLP42 <- getTLP extHistLogPnt42 <- getTLP archiveType42 <- getWord8 averagingorRateType42 <- getWord8 pointTagIDTLP43 <- getTLP extHistLogPnt43 <- getTLP archiveType43 <- getWord8 averagingorRateType43 <- getWord8 pointTagIDTLP44 <- getTLP extHistLogPnt44 <- getTLP archiveType44 <- getWord8 averagingorRateType44 <- getWord8 pointTagIDTLP45 <- getTLP extHistLogPnt45 <- getTLP archiveType45 <- getWord8 averagingorRateType45 <- getWord8 pointTagIDTLP46 <- getTLP extHistLogPnt46 <- getTLP archiveType46 <- getWord8 averagingorRateType46 <- getWord8 pointTagIDTLP47 <- getTLP extHistLogPnt47 <- getTLP archiveType47 <- getWord8 averagingorRateType47 <- getWord8 pointTagIDTLP48 <- getTLP extHistLogPnt48 <- getTLP archiveType48 <- getWord8 averagingorRateType48 <- getWord8 pointTagIDTLP49 <- getTLP extHistLogPnt49 <- getTLP archiveType49 <- getWord8 averagingorRateType49 <- getWord8 pointTagIDTLP50 <- getTLP extHistLogPnt50 <- getTLP archiveType50 <- getWord8 averagingorRateType50 <- getWord8 return $ PointType86 maxNumExtHistPnts sampleLogInterval pointTagIDTLP1 extHistLogPnt1 archiveType1 averagingorRateType1 pointTagIDTLP2 extHistLogPnt2 archiveType2 averagingorRateType2 pointTagIDTLP3 extHistLogPnt3 archiveType3 averagingorRateType3 pointTagIDTLP4 extHistLogPnt4 archiveType4 averagingorRateType4 pointTagIDTLP5 extHistLogPnt5 archiveType5 averagingorRateType5 pointTagIDTLP6 extHistLogPnt6 archiveType6 averagingorRateType6 pointTagIDTLP7 extHistLogPnt7 archiveType7 averagingorRateType7 pointTagIDTLP8 extHistLogPnt8 archiveType8 averagingorRateType8 pointTagIDTLP9 extHistLogPnt9 archiveType9 averagingorRateType9 pointTagIDTLP10 extHistLogPnt10 archiveType10 averagingorRateType10 pointTagIDTLP11 extHistLogPnt11 archiveType11 averagingorRateType11 pointTagIDTLP12 extHistLogPnt12 archiveType12 averagingorRateType12 pointTagIDTLP13 extHistLogPnt13 archiveType13 averagingorRateType13 pointTagIDTLP14 extHistLogPnt14 archiveType14 averagingorRateType14 pointTagIDTLP15 extHistLogPnt15 archiveType15 averagingorRateType15 pointTagIDTLP16 extHistLogPnt16 archiveType16 averagingorRateType16 pointTagIDTLP17 extHistLogPnt17 archiveType17 averagingorRateType17 pointTagIDTLP18 extHistLogPnt18 archiveType18 averagingorRateType18 pointTagIDTLP19 extHistLogPnt19 archiveType19 averagingorRateType19 pointTagIDTLP20 extHistLogPnt20 archiveType20 averagingorRateType20 pointTagIDTLP21 extHistLogPnt21 archiveType21 averagingorRateType21 pointTagIDTLP22 extHistLogPnt22 archiveType22 averagingorRateType22 pointTagIDTLP23 extHistLogPnt23 archiveType23 averagingorRateType23 pointTagIDTLP24 extHistLogPnt24 archiveType24 averagingorRateType24 pointTagIDTLP25 extHistLogPnt25 archiveType25 averagingorRateType25 pointTagIDTLP26 extHistLogPnt26 archiveType26 averagingorRateType26 pointTagIDTLP27 extHistLogPnt27 archiveType27 averagingorRateType27 pointTagIDTLP28 extHistLogPnt28 archiveType28 averagingorRateType28 pointTagIDTLP29 extHistLogPnt29 archiveType29 averagingorRateType29 pointTagIDTLP30 extHistLogPnt30 archiveType30 averagingorRateType30 pointTagIDTLP31 extHistLogPnt31 archiveType31 averagingorRateType31 pointTagIDTLP32 extHistLogPnt32 archiveType32 averagingorRateType32 pointTagIDTLP33 extHistLogPnt33 archiveType33 averagingorRateType33 pointTagIDTLP34 extHistLogPnt34 archiveType34 averagingorRateType34 pointTagIDTLP35 extHistLogPnt35 archiveType35 averagingorRateType35 pointTagIDTLP36 extHistLogPnt36 archiveType36 averagingorRateType36 pointTagIDTLP37 extHistLogPnt37 archiveType37 averagingorRateType37 pointTagIDTLP38 extHistLogPnt38 archiveType38 averagingorRateType38 pointTagIDTLP39 extHistLogPnt39 archiveType39 averagingorRateType39 pointTagIDTLP40 extHistLogPnt40 archiveType40 averagingorRateType40 pointTagIDTLP41 extHistLogPnt41 archiveType41 averagingorRateType41 pointTagIDTLP42 extHistLogPnt42 archiveType42 averagingorRateType42 pointTagIDTLP43 extHistLogPnt43 archiveType43 averagingorRateType43 pointTagIDTLP44 extHistLogPnt44 archiveType44 averagingorRateType44 pointTagIDTLP45 extHistLogPnt45 archiveType45 averagingorRateType45 pointTagIDTLP46 extHistLogPnt46 archiveType46 averagingorRateType46 pointTagIDTLP47 extHistLogPnt47 archiveType47 averagingorRateType47 pointTagIDTLP48 extHistLogPnt48 archiveType48 averagingorRateType48 pointTagIDTLP49 extHistLogPnt49 archiveType49 averagingorRateType49 pointTagIDTLP50 extHistLogPnt50 archiveType50 averagingorRateType50
plow-technologies/roc-translator
src/Protocol/ROC/PointTypes/PointType86.hs
bsd-3-clause
42,432
0
9
14,603
4,855
2,691
2,164
1,045
1
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor, DeriveDataTypeable, TypeSynonymInstances, PatternGuards #-} module Idris.AbsSyntaxTree where import Idris.Core.TT import Idris.Core.Evaluate import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Typecheck import Idris.Docstrings import IRTS.Lang import IRTS.CodegenCommon import Util.Pretty import Util.DynamicLinker import Idris.Colours import System.Console.Haskeline import System.IO import Prelude hiding ((<$>)) import Control.Applicative ((<|>)) import Control.Monad.Trans.State.Strict import Control.Monad.Trans.Except import qualified Control.Monad.Trans.Class as Trans (lift) import Data.Data (Data) import Data.Function (on) import Data.Generics.Uniplate.Data (universe) import Data.List hiding (group) import Data.Char import qualified Data.Map.Strict as M import qualified Data.Text as T import Data.Either import qualified Data.Set as S import Data.Word (Word) import Data.Maybe (fromMaybe, mapMaybe, maybeToList) import Data.Traversable (Traversable) import Data.Typeable import Data.Foldable (Foldable) import Debug.Trace import Text.PrettyPrint.Annotated.Leijen data ElabWhat = ETypes | EDefns | EAll deriving (Show, Eq) -- Data to pass to recursively called elaborators; e.g. for where blocks, -- paramaterised declarations, etc. -- rec_elabDecl is used to pass the top level elaborator into other elaborators, -- so that we can have mutually recursive elaborators in separate modules without -- having to muck about with cyclic modules. data ElabInfo = EInfo { params :: [(Name, PTerm)], inblock :: Ctxt [Name], -- names in the block, and their params liftname :: Name -> Name, namespace :: Maybe [String], elabFC :: Maybe FC, rec_elabDecl :: ElabWhat -> ElabInfo -> PDecl -> Idris () } toplevel :: ElabInfo toplevel = EInfo [] emptyContext id Nothing Nothing (\_ _ _ -> fail "Not implemented") eInfoNames :: ElabInfo -> [Name] eInfoNames info = map fst (params info) ++ M.keys (inblock info) data IOption = IOption { opt_logLevel :: Int, opt_typecase :: Bool, opt_typeintype :: Bool, opt_coverage :: Bool, opt_showimp :: Bool, -- ^^ show implicits opt_errContext :: Bool, opt_repl :: Bool, opt_verbose :: Bool, opt_nobanner :: Bool, opt_quiet :: Bool, opt_codegen :: Codegen, opt_outputTy :: OutputType, opt_ibcsubdir :: FilePath, opt_importdirs :: [FilePath], opt_triple :: String, opt_cpu :: String, opt_cmdline :: [Opt], -- remember whole command line opt_origerr :: Bool, opt_autoSolve :: Bool, -- ^ automatically apply "solve" tactic in prover opt_autoImport :: [FilePath], -- ^ e.g. Builtins+Prelude opt_optimise :: [Optimisation], opt_printdepth :: Maybe Int, opt_evaltypes :: Bool -- ^ normalise types in :t } deriving (Show, Eq) defaultOpts = IOption { opt_logLevel = 0 , opt_typecase = False , opt_typeintype = False , opt_coverage = True , opt_showimp = False , opt_errContext = False , opt_repl = True , opt_verbose = True , opt_nobanner = False , opt_quiet = False , opt_codegen = Via "c" , opt_outputTy = Executable , opt_ibcsubdir = "" , opt_importdirs = [] , opt_triple = "" , opt_cpu = "" , opt_cmdline = [] , opt_origerr = False , opt_autoSolve = True , opt_autoImport = [] , opt_optimise = defaultOptimise , opt_printdepth = Just 5000 , opt_evaltypes = True } data PPOption = PPOption { ppopt_impl :: Bool -- ^^ whether to show implicits , ppopt_depth :: Maybe Int } deriving (Show) data Optimisation = PETransform -- partial eval and associated transforms deriving (Show, Eq) defaultOptimise = [PETransform] -- | Pretty printing options with default verbosity. defaultPPOption :: PPOption defaultPPOption = PPOption { ppopt_impl = False , ppopt_depth = Just 200 } -- | Pretty printing options with the most verbosity. verbosePPOption :: PPOption verbosePPOption = PPOption { ppopt_impl = True, ppopt_depth = Just 200 } -- | Get pretty printing options from the big options record. ppOption :: IOption -> PPOption ppOption opt = PPOption { ppopt_impl = opt_showimp opt, ppopt_depth = opt_printdepth opt } -- | Get pretty printing options from an idris state record. ppOptionIst :: IState -> PPOption ppOptionIst = ppOption . idris_options data LanguageExt = TypeProviders | ErrorReflection deriving (Show, Eq, Read, Ord) -- | The output mode in use data OutputMode = RawOutput Handle -- ^ Print user output directly to the handle | IdeMode Integer Handle -- ^ Send IDE output for some request ID to the handle deriving Show -- | How wide is the console? data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines should not be broken | ColsWide Int -- ^ Manually specified - must be positive | AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise deriving (Show, Eq) -- | The global state used in the Idris monad data IState = IState { tt_ctxt :: Context, -- ^ All the currently defined names and their terms idris_constraints :: S.Set ConstraintFC, -- ^ A list of universe constraints and their corresponding source locations idris_infixes :: [FixDecl], -- ^ Currently defined infix operators idris_implicits :: Ctxt [PArg], idris_statics :: Ctxt [Bool], idris_classes :: Ctxt ClassInfo, idris_dsls :: Ctxt DSL, idris_optimisation :: Ctxt OptInfo, idris_datatypes :: Ctxt TypeInfo, idris_namehints :: Ctxt [Name], idris_patdefs :: Ctxt ([([Name], Term, Term)], [PTerm]), -- not exported -- ^ list of lhs/rhs, and a list of missing clauses idris_flags :: Ctxt [FnOpt], idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos idris_calledgraph :: Ctxt [Name], idris_docstrings :: Ctxt (Docstring DocTerm, [(Name, Docstring DocTerm)]), idris_moduledocs :: Ctxt (Docstring DocTerm), -- ^ module documentation is saved in a special MN so the context -- mechanism can be used for disambiguation idris_tyinfodata :: Ctxt TIData, idris_fninfo :: Ctxt FnInfo, idris_transforms :: Ctxt [(Term, Term)], idris_autohints :: Ctxt [Name], idris_totcheck :: [(FC, Name)], -- names to check totality on idris_defertotcheck :: [(FC, Name)], -- names to check at the end idris_totcheckfail :: [(FC, String)], idris_options :: IOption, idris_name :: Int, idris_lineapps :: [((FilePath, Int), PTerm)], -- ^ Full application LHS on source line idris_metavars :: [(Name, (Maybe Name, Int, [Name], Bool))], -- ^ The currently defined but not proven metavariables. The Int -- is the number of vars to display as a context, the Maybe Name -- is its top-level function, the [Name] is the list of local variables -- available for proof search and the Bool is whether :p is -- allowed idris_coercions :: [Name], idris_errRev :: [(Term, Term)], syntax_rules :: SyntaxRules, syntax_keywords :: [String], imported :: [FilePath], -- ^ The imported modules idris_scprims :: [(Name, (Int, PrimFn))], idris_objs :: [(Codegen, FilePath)], idris_libs :: [(Codegen, String)], idris_cgflags :: [(Codegen, String)], idris_hdrs :: [(Codegen, String)], idris_imported :: [(FilePath, Bool)], -- ^ Imported ibc file names, whether public proof_list :: [(Name, (Bool, [String]))], errSpan :: Maybe FC, parserWarnings :: [(FC, Err)], lastParse :: Maybe Name, indent_stack :: [Int], brace_stack :: [Maybe Int], lastTokenSpan :: Maybe FC, -- ^ What was the span of the latest token parsed? idris_parsedSpan :: Maybe FC, hide_list :: [(Name, Maybe Accessibility)], default_access :: Accessibility, default_total :: Bool, ibc_write :: [IBCWrite], compiled_so :: Maybe String, idris_dynamic_libs :: [DynamicLib], idris_language_extensions :: [LanguageExt], idris_outputmode :: OutputMode, idris_colourRepl :: Bool, idris_colourTheme :: ColourTheme, idris_errorhandlers :: [Name], -- ^ Global error handlers idris_nameIdx :: (Int, Ctxt (Int, Name)), idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)), -- ^ Specific error handlers module_aliases :: M.Map [T.Text] [T.Text], idris_consolewidth :: ConsoleWidth, -- ^ How many chars wide is the console? idris_postulates :: S.Set Name, idris_externs :: S.Set (Name, Int), idris_erasureUsed :: [(Name, Int)], -- ^ Function/constructor name, argument position is used idris_whocalls :: Maybe (M.Map Name [Name]), idris_callswho :: Maybe (M.Map Name [Name]), idris_repl_defs :: [Name], -- ^ List of names that were defined in the repl, and can be re-/un-defined elab_stack :: [(Name, Bool)], -- ^ Stack of names currently being elaborated, Bool set if it's an instance -- (instances appear twice; also as a funtion name) idris_symbols :: M.Map Name Name, -- ^ Symbol table (preserves sharing of names) idris_exports :: [Name], -- ^ Functions with ExportList idris_highlightedRegions :: [(FC, OutputAnnotation)], -- ^ Highlighting information to output idris_parserHighlights :: [(FC, OutputAnnotation)] -- ^ Highlighting information from the parser } -- Required for parsers library, and therefore trifecta instance Show IState where show = const "{internal state}" data SizeChange = Smaller | Same | Bigger | Unknown deriving (Show, Eq) {-! deriving instance Binary SizeChange deriving instance NFData SizeChange !-} type SCGEntry = (Name, [Maybe (Int, SizeChange)]) type UsageReason = (Name, Int) -- fn_name, its_arg_number data CGInfo = CGInfo { argsdef :: [Name], calls :: [(Name, [[Name]])], scg :: [SCGEntry], argsused :: [Name], usedpos :: [(Int, [UsageReason])] } deriving Show {-! deriving instance Binary CGInfo deriving instance NFData CGInfo !-} primDefs = [sUN "unsafePerformPrimIO", sUN "mkLazyForeignPrim", sUN "mkForeignPrim", sUN "void"] -- information that needs writing for the current module's .ibc file data IBCWrite = IBCFix FixDecl | IBCImp Name | IBCStatic Name | IBCClass Name | IBCInstance Bool Bool Name Name | IBCDSL Name | IBCData Name | IBCOpt Name | IBCMetavar Name | IBCSyntax Syntax | IBCKeyword String | IBCImport (Bool, FilePath) -- True = import public | IBCImportDir FilePath | IBCObj Codegen FilePath | IBCLib Codegen String | IBCCGFlag Codegen String | IBCDyLib String | IBCHeader Codegen String | IBCAccess Name Accessibility | IBCMetaInformation Name MetaInformation | IBCTotal Name Totality | IBCFlags Name [FnOpt] | IBCFnInfo Name FnInfo | IBCTrans Name (Term, Term) | IBCErrRev (Term, Term) | IBCCG Name | IBCDoc Name | IBCCoercion Name | IBCDef Name -- i.e. main context | IBCNameHint (Name, Name) | IBCLineApp FilePath Int PTerm | IBCErrorHandler Name | IBCFunctionErrorHandler Name Name Name | IBCPostulate Name | IBCExtern (Name, Int) | IBCTotCheckErr FC String | IBCParsedRegion FC | IBCModDocs Name -- ^ The name is the special name used to track module docs | IBCUsage (Name, Int) | IBCExport Name | IBCAutoHint Name Name deriving Show -- | The initial state for the compiler idrisInit :: IState idrisInit = IState initContext S.empty [] emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext [] [] [] defaultOpts 6 [] [] [] [] emptySyntaxRules [] [] [] [] [] [] [] [] [] Nothing [] Nothing [] [] Nothing Nothing [] Hidden False [] Nothing [] [] (RawOutput stdout) True defaultTheme [] (0, emptyContext) emptyContext M.empty AutomaticWidth S.empty S.empty [] Nothing Nothing [] [] M.empty [] [] [] -- | The monad for the main REPL - reading and processing files and updating -- global state (hence the IO inner monad). --type Idris = WriterT [Either String (IO ())] (State IState a)) type Idris = StateT IState (ExceptT Err IO) catchError :: Idris a -> (Err -> Idris a) -> Idris a catchError = liftCatch catchE throwError :: Err -> Idris a throwError = Trans.lift . throwE -- Commands in the REPL data Codegen = Via String -- | ViaC -- | ViaJava -- | ViaNode -- | ViaJavaScript -- | ViaLLVM | Bytecode deriving (Show, Eq) {-! deriving instance NFData Codegen !-} data HowMuchDocs = FullDocs | OverviewDocs -- | REPL commands data Command = Quit | Help | Eval PTerm | NewDefn [PDecl] -- ^ Each 'PDecl' should be either a type declaration (at most one) or a clause defining the same name. | Undefine [Name] | Check PTerm | Core PTerm | DocStr (Either Name Const) HowMuchDocs | TotCheck Name | Reload | Load FilePath (Maybe Int) -- up to maximum line number | ChangeDirectory FilePath | ModImport String | Edit | Compile Codegen String | Execute PTerm | ExecVal PTerm | Metavars | Prove Bool Name -- ^ If false, use prover, if true, use elab shell | AddProof (Maybe Name) | RmProof Name | ShowProof Name | Proofs | Universes | LogLvl Int | Spec PTerm | WHNF PTerm | TestInline PTerm | Defn Name | Missing Name | DynamicLink FilePath | ListDynamic | Pattelab PTerm | Search [String] PTerm | CaseSplitAt Bool Int Name | AddClauseFrom Bool Int Name | AddProofClauseFrom Bool Int Name | AddMissing Bool Int Name | MakeWith Bool Int Name | MakeCase Bool Int Name | MakeLemma Bool Int Name | DoProofSearch Bool -- update file Bool -- recursive search Int -- depth Name -- top level name [Name] -- hints | SetOpt Opt | UnsetOpt Opt | NOP | SetColour ColourType IdrisColour | ColourOn | ColourOff | ListErrorHandlers | SetConsoleWidth ConsoleWidth | SetPrinterDepth (Maybe Int) | Apropos [String] String | WhoCalls Name | CallsWho Name | Browse [String] | MakeDoc String -- IdrisDoc | Warranty | PrintDef Name | PPrint OutputFmt Int PTerm | TransformInfo Name -- Debugging commands | DebugInfo Name | DebugUnify PTerm PTerm data OutputFmt = HTMLOutput | LaTeXOutput data Opt = Filename String | Quiet | NoBanner | ColourREPL Bool | Idemode | IdemodeSocket | ShowLibs | ShowLibdir | ShowIncs | ShowPkgs | NoBasePkgs | NoPrelude | NoBuiltins -- only for the really primitive stuff! | NoREPL | OLogging Int | Output String | Interface | TypeCase | TypeInType | DefaultTotal | DefaultPartial | WarnPartial | WarnReach | EvalTypes | NoCoverage | ErrContext | ShowImpl | Verbose | Port String -- REPL TCP port | IBCSubDir String | ImportDir String | PkgBuild String | PkgInstall String | PkgClean String | PkgCheck String | PkgREPL String | PkgMkDoc String -- IdrisDoc | PkgTest String | PkgIndex FilePath | WarnOnly | Pkg String | BCAsm String | DumpDefun String | DumpCases String | UseCodegen Codegen | CodegenArgs String | OutputTy OutputType | Extension LanguageExt | InterpretScript String | EvalExpr String | TargetTriple String | TargetCPU String | OptLevel Int | AddOpt Optimisation | RemoveOpt Optimisation | Client String | ShowOrigErr | AutoWidth -- ^ Automatically adjust terminal width | AutoSolve -- ^ Automatically issue "solve" tactic in interactive prover | UseConsoleWidth ConsoleWidth | DumpHighlights deriving (Show, Eq) data ElabShellCmd = EQED | EAbandon | EUndo | EProofState | EProofTerm | EEval PTerm | ECheck PTerm | ESearch PTerm | EDocStr (Either Name Const) deriving (Show, Eq) -- Parsed declarations data Fixity = Infixl { prec :: Int } | Infixr { prec :: Int } | InfixN { prec :: Int } | PrefixN { prec :: Int } deriving Eq {-! deriving instance Binary Fixity deriving instance NFData Fixity !-} instance Show Fixity where show (Infixl i) = "infixl " ++ show i show (Infixr i) = "infixr " ++ show i show (InfixN i) = "infix " ++ show i show (PrefixN i) = "prefix " ++ show i data FixDecl = Fix Fixity String deriving Eq instance Show FixDecl where show (Fix f s) = show f ++ " " ++ s {-! deriving instance Binary FixDecl deriving instance NFData FixDecl !-} instance Ord FixDecl where compare (Fix x _) (Fix y _) = compare (prec x) (prec y) data Static = Static | Dynamic deriving (Show, Eq, Data, Typeable) {-! deriving instance Binary Static deriving instance NFData Static !-} -- Mark bindings with their explicitness, and laziness data Plicity = Imp { pargopts :: [ArgOpt], pstatic :: Static, pparam :: Bool, pscoped :: Maybe ImplicitInfo -- Nothing, if top level } | Exp { pargopts :: [ArgOpt], pstatic :: Static, pparam :: Bool } -- this is a param (rather than index) | Constraint { pargopts :: [ArgOpt], pstatic :: Static } | TacImp { pargopts :: [ArgOpt], pstatic :: Static, pscript :: PTerm } deriving (Show, Eq, Data, Typeable) {-! deriving instance Binary Plicity deriving instance NFData Plicity !-} is_scoped :: Plicity -> Maybe ImplicitInfo is_scoped (Imp _ _ _ s) = s is_scoped _ = Nothing impl = Imp [] Dynamic False Nothing forall_imp = Imp [] Dynamic False (Just (Impl False)) forall_constraint = Imp [] Dynamic False (Just (Impl True)) expl = Exp [] Dynamic False expl_param = Exp [] Dynamic True constraint = Constraint [] Static tacimpl t = TacImp [] Dynamic t data FnOpt = Inlinable -- always evaluate when simplifying | TotalFn | PartialFn | CoveringFn | Coinductive | AssertTotal | Dictionary -- type class dictionary, eval only when -- a function argument, and further evaluation resutls | Implicit -- implicit coercion | NoImplicit -- do not apply implicit coercions | CExport String -- export, with a C name | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension | ErrorReverse -- ^^ attempt to reverse normalise before showing in error | Reflection -- a reflecting function, compile-time only | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names | Constructor -- Data constructor type | AutoHint -- use in auto implicit search | PEGenerated -- generated by partial evaluator deriving (Show, Eq) {-! deriving instance Binary FnOpt deriving instance NFData FnOpt !-} type FnOpts = [FnOpt] inlinable :: FnOpts -> Bool inlinable = elem Inlinable dictionary :: FnOpts -> Bool dictionary = elem Dictionary -- | Type provider - what to provide data ProvideWhat' t = ProvTerm t t -- ^ the first is the goal type, the second is the term | ProvPostulate t -- ^ goal type must be Type, so only term deriving (Show, Eq, Functor) type ProvideWhat = ProvideWhat' PTerm -- | Top-level declarations such as compiler directives, definitions, -- datatypes and typeclasses. data PDecl' t = PFix FC Fixity [String] -- ^ Fixity declaration | PTy (Docstring (Either Err PTerm)) [(Name, Docstring (Either Err PTerm))] SyntaxInfo FC FnOpts Name FC t -- ^ Type declaration (last FC is precise name location) | PPostulate Bool -- external def if true (Docstring (Either Err PTerm)) SyntaxInfo FC FC FnOpts Name t -- ^ Postulate, second FC is precise name location | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause | PCAF FC Name t -- ^ Top level constant | PData (Docstring (Either Err PTerm)) [(Name, Docstring (Either Err PTerm))] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration. | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block | PNamespace String FC [PDecl' t] -- ^ New namespace, where FC is accurate location of the -- namespace in the file | PRecord (Docstring (Either Err PTerm)) SyntaxInfo FC DataOpts Name -- Record name FC -- Record name precise location [(Name, FC, Plicity, t)] -- Parameters, where FC is precise name span [(Name, Docstring (Either Err PTerm))] -- Param Docs [((Maybe (Name, FC)), Plicity, t, Maybe (Docstring (Either Err PTerm)))] -- Fields (Maybe (Name, FC)) -- Optional constructor name and location (Docstring (Either Err PTerm)) -- Constructor doc SyntaxInfo -- Constructor SyntaxInfo -- ^ Record declaration | PClass (Docstring (Either Err PTerm)) SyntaxInfo FC [(Name, t)] -- constraints Name -- class name FC -- accurate location of class name [(Name, FC, t)] -- parameters and precise locations [(Name, Docstring (Either Err PTerm))] -- parameter docstrings [(Name, FC)] -- determining parameters and precise locations [PDecl' t] -- declarations (Maybe (Name, FC)) -- instance constructor name and location (Docstring (Either Err PTerm)) -- instance constructor docs -- ^ Type class: arguments are documentation, syntax info, source location, constraints, -- class name, class name location, parameters, method declarations, optional constructor name | PInstance (Docstring (Either Err PTerm)) -- Instance docs [(Name, Docstring (Either Err PTerm))] -- Parameter docs SyntaxInfo FC [(Name, t)] -- constraints Name -- class FC -- precise location of class [t] -- parameters t -- full instance type (Maybe Name) -- explicit name [PDecl' t] -- ^ Instance declaration: arguments are documentation, syntax info, source -- location, constraints, class name, parameters, full instance -- type, optional explicit name, and definitions | PDSL Name (DSL' t) -- ^ DSL declaration | PSyntax FC Syntax -- ^ Syntax definition | PMutual FC [PDecl' t] -- ^ Mutual block | PDirective Directive -- ^ Compiler directive. | PProvider (Docstring (Either Err PTerm)) SyntaxInfo FC FC (ProvideWhat' t) Name -- ^ Type provider. The first t is the type, the second is the term. The second FC is precise highlighting location. | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If -- bool is True, lhs and rhs must be convertible deriving Functor {-! deriving instance Binary PDecl' deriving instance NFData PDecl' !-} -- | The set of source directives data Directive = DLib Codegen String | DLink Codegen String | DFlag Codegen String | DInclude Codegen String | DHide Name | DFreeze Name | DAccess Accessibility | DDefault Bool | DLogging Integer | DDynamicLibs [String] | DNameHint Name FC [(Name, FC)] | DErrorHandlers Name FC Name FC [(Name, FC)] | DLanguage LanguageExt | DUsed FC Name Name -- | A set of instructions for things that need to happen in IState -- after a term elaboration when there's been reflected elaboration. data RDeclInstructions = RTyDeclInstrs Name FC [PArg] Type | RClausesInstrs Name [([Name], Term, Term)] | RAddInstance Name Name -- | For elaborator state data EState = EState { case_decls :: [(Name, PDecl)], delayed_elab :: [(Int, Elab' EState ())], new_tyDecls :: [RDeclInstructions], highlighting :: [(FC, OutputAnnotation)] } initEState :: EState initEState = EState [] [] [] [] type ElabD a = Elab' EState a highlightSource :: FC -> OutputAnnotation -> ElabD () highlightSource fc annot = updateAux (\aux -> aux { highlighting = (fc, annot) : highlighting aux }) -- | One clause of a top-level definition. Term arguments to constructors are: -- -- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause) -- -- 2. The list of extra 'with' patterns -- -- 3. The right-hand side -- -- 4. The where block (PDecl' t) data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition. | PWith FC Name t [t] t (Maybe (Name, FC)) [PDecl' t] | PClauseR FC [t] t [PDecl' t] | PWithR FC [t] t (Maybe (Name, FC)) [PDecl' t] deriving Functor {-! deriving instance Binary PClause' deriving instance NFData PClause' !-} -- | Data declaration data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype d_name_fc :: FC, -- ^ The precise location of the type constructor name d_tcon :: t, -- ^ Type constructor d_cons :: [(Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, FC, t, FC, [Name])] -- ^ Constructors } -- ^ Data declaration | PLaterdecl { d_name :: Name, d_name_fc :: FC, d_tcon :: t } -- ^ "Placeholder" for data whose constructors are defined later deriving Functor {-! deriving instance Binary PData' deriving instance NFData PData' !-} -- Handy to get a free function for applying PTerm -> PTerm functions -- across a program, by deriving Functor type PDecl = PDecl' PTerm type PData = PData' PTerm type PClause = PClause' PTerm -- get all the names declared in a decl declared :: PDecl -> [Name] declared (PFix _ _ _) = [] declared (PTy _ _ _ _ _ n fc t) = [n] declared (PPostulate _ _ _ _ _ _ n t) = [n] declared (PClauses _ _ n _) = [] -- not a declaration declared (PCAF _ n _) = [n] declared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts where fstt (_, _, a, _, _, _, _) = a declared (PData _ _ _ _ _ (PLaterdecl n _ _)) = [n] declared (PParams _ _ ds) = concatMap declared ds declared (PNamespace _ _ ds) = concatMap declared ds declared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn) declared (PClass _ _ _ _ n _ _ _ _ ms cn cd) = n : (map fst (maybeToList cn) ++ concatMap declared ms) declared (PInstance _ _ _ _ _ _ _ _ _ _ _) = [] declared (PDSL n _) = [n] declared (PSyntax _ _) = [] declared (PMutual _ ds) = concatMap declared ds declared (PDirective _) = [] declared _ = [] -- get the names declared, not counting nested parameter blocks tldeclared :: PDecl -> [Name] tldeclared (PFix _ _ _) = [] tldeclared (PTy _ _ _ _ _ n _ t) = [n] tldeclared (PPostulate _ _ _ _ _ _ n t) = [n] tldeclared (PClauses _ _ n _) = [] -- not a declaration tldeclared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn) tldeclared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts where fstt (_, _, a, _, _, _, _) = a tldeclared (PParams _ _ ds) = [] tldeclared (PMutual _ ds) = concatMap tldeclared ds tldeclared (PNamespace _ _ ds) = concatMap tldeclared ds tldeclared (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap tldeclared ms) tldeclared (PInstance _ _ _ _ _ _ _ _ _ _ _) = [] tldeclared _ = [] defined :: PDecl -> [Name] defined (PFix _ _ _) = [] defined (PTy _ _ _ _ _ n _ t) = [] defined (PPostulate _ _ _ _ _ _ n t) = [] defined (PClauses _ _ n _) = [n] -- not a declaration defined (PCAF _ n _) = [n] defined (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts where fstt (_, _, a, _, _, _, _) = a defined (PData _ _ _ _ _ (PLaterdecl n _ _)) = [] defined (PParams _ _ ds) = concatMap defined ds defined (PNamespace _ _ ds) = concatMap defined ds defined (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn) defined (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap defined ms) defined (PInstance _ _ _ _ _ _ _ _ _ _ _) = [] defined (PDSL n _) = [n] defined (PSyntax _ _) = [] defined (PMutual _ ds) = concatMap defined ds defined (PDirective _) = [] defined _ = [] updateN :: [(Name, Name)] -> Name -> Name updateN ns n | Just n' <- lookup n ns = n' updateN _ n = n updateNs :: [(Name, Name)] -> PTerm -> PTerm updateNs [] t = t updateNs ns t = mapPT updateRef t where updateRef (PRef fc fcs f) = PRef fc fcs (updateN ns f) updateRef t = t -- updateDNs :: [(Name, Name)] -> PDecl -> PDecl -- updateDNs [] t = t -- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t -- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c) -- where updateCNs ns (PClause n l ts r ds) -- = PClause (updateN ns n) (fmap (updateNs ns) l) -- (map (fmap (updateNs ns)) ts) -- (fmap (updateNs ns) r) -- (map (updateDNs ns) ds) -- updateDNs ns c = c data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show, Data, Typeable) -- | High level language terms data PTerm = PQuote Raw -- ^ Inclusion of a core term into the high-level language | PRef FC [FC] Name -- ^ A reference to a variable. The FC is its precise source location for highlighting. The list of FCs is a collection of additional highlighting locations. | PInferRef FC [FC] Name -- ^ A name to be defined later | PPatvar FC Name -- ^ A pattern variable | PLam FC Name FC PTerm PTerm -- ^ A lambda abstraction. Second FC is name span. | PPi Plicity Name FC PTerm PTerm -- ^ (n : t1) -> t2, where the FC is for the precise location of the variable | PLet FC Name FC PTerm PTerm PTerm -- ^ A let binding (second FC is precise name location) | PTyped PTerm PTerm -- ^ Term with explicit type | PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x | PAppImpl PTerm [ImplicitInfo] -- ^ Implicit argument application (introduced during elaboration only) | PAppBind FC PTerm [PArg] -- ^ implicitly bound application | PMatchApp FC Name -- ^ Make an application by type matching | PIfThenElse FC PTerm PTerm PTerm -- ^ Conditional expressions - elaborated to an overloading of ifThenElse | PCase FC PTerm [(PTerm, PTerm)] -- ^ A case expression. Args are source location, scrutinee, and a list of pattern/RHS pairs | PTrue FC PunInfo -- ^ Unit type..? | PResolveTC FC -- ^ Solve this dictionary by type class resolution | PRewrite FC PTerm PTerm (Maybe PTerm) -- ^ "rewrite" syntax, with optional result type | PPair FC [FC] PunInfo PTerm PTerm -- ^ A pair (a, b) and whether it's a product type or a pair (solved by elaboration). The list of FCs is its punctuation. | PDPair FC [FC] PunInfo PTerm PTerm PTerm -- ^ A dependent pair (tm : a ** b) and whether it's a sigma type or a pair that inhabits one (solved by elaboration). The [FC] is its punctuation. | PAs FC Name PTerm -- ^ @-pattern, valid LHS only | PAlternative [(Name, Name)] PAltType [PTerm] -- ^ (| A, B, C|). Includes unapplied unique name mappings for mkUniqueNames. | PHidden PTerm -- ^ Irrelevant or hidden pattern | PType FC -- ^ 'Type' type | PUniverse Universe -- ^ Some universe | PGoal FC PTerm Name PTerm -- ^ quoteGoal, used for %reflection functions | PConstant FC Const -- ^ Builtin types | Placeholder -- ^ Underscore | PDoBlock [PDo] -- ^ Do notation | PIdiom FC PTerm -- ^ Idiom brackets | PReturn FC | PMetavar FC Name -- ^ A metavariable, ?name, and its precise location | PProof [PTactic] -- ^ Proof script | PTactics [PTactic] -- ^ As PProof, but no auto solving | PElabError Err -- ^ Error to report on elaboration | PImpossible -- ^ Special case for declaring when an LHS can't typecheck | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces | PUnifyLog PTerm -- ^ dump a trace of unifications when building term | PNoImplicits PTerm -- ^ never run implicit converions on the term | PQuasiquote PTerm (Maybe PTerm) -- ^ `(Term [: Term]) | PUnquote PTerm -- ^ ~Term | PQuoteName Name FC -- ^ `{n} where the FC is the precise highlighting for the name in particular | PRunElab FC PTerm [String] -- ^ %runElab tm - New-style proof script. Args are location, script, enclosing namespace. | PConstSugar FC PTerm -- ^ A desugared constant. The FC is a precise source location that will be used to highlight it later. deriving (Eq, Data, Typeable) data PAltType = ExactlyOne Bool -- ^ flag sets whether delay is allowed | FirstSuccess | TryImplicit deriving (Eq, Data, Typeable) -- | Transform the FCs in a PTerm. The first function transforms the -- general-purpose FCs, and the second transforms those that are used -- for semantic source highlighting, so they can be treated specially. mapPTermFC :: (FC -> FC) -> (FC -> FC) -> PTerm -> PTerm mapPTermFC f g (PQuote q) = PQuote q mapPTermFC f g (PRef fc fcs n) = PRef (g fc) (map g fcs) n mapPTermFC f g (PInferRef fc fcs n) = PInferRef (g fc) (map g fcs) n mapPTermFC f g (PPatvar fc n) = PPatvar (g fc) n mapPTermFC f g (PLam fc n fc' t1 t2) = PLam (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2) mapPTermFC f g (PPi plic n fc t1 t2) = PPi plic n (g fc) (mapPTermFC f g t1) (mapPTermFC f g t2) mapPTermFC f g (PLet fc n fc' t1 t2 t3) = PLet (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3) mapPTermFC f g (PTyped t1 t2) = PTyped (mapPTermFC f g t1) (mapPTermFC f g t2) mapPTermFC f g (PApp fc t args) = PApp (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args) mapPTermFC f g (PAppImpl t1 impls) = PAppImpl (mapPTermFC f g t1) impls mapPTermFC f g (PAppBind fc t args) = PAppBind (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args) mapPTermFC f g (PMatchApp fc n) = PMatchApp (f fc) n mapPTermFC f g (PIfThenElse fc t1 t2 t3) = PIfThenElse (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3) mapPTermFC f g (PCase fc t cases) = PCase (f fc) (mapPTermFC f g t) (map (\(l,r) -> (mapPTermFC f g l, mapPTermFC f g r)) cases) mapPTermFC f g (PTrue fc info) = PTrue (f fc) info mapPTermFC f g (PResolveTC fc) = PResolveTC (f fc) mapPTermFC f g (PRewrite fc t1 t2 t3) = PRewrite (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (fmap (mapPTermFC f g) t3) mapPTermFC f g (PPair fc hls info t1 t2) = PPair (f fc) (map g hls) info (mapPTermFC f g t1) (mapPTermFC f g t2) mapPTermFC f g (PDPair fc hls info t1 t2 t3) = PDPair (f fc) (map g hls) info (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3) mapPTermFC f g (PAs fc n t) = PAs (f fc) n (mapPTermFC f g t) mapPTermFC f g (PAlternative ns ty ts) = PAlternative ns ty (map (mapPTermFC f g) ts) mapPTermFC f g (PHidden t) = PHidden (mapPTermFC f g t) mapPTermFC f g (PType fc) = PType (f fc) mapPTermFC f g (PUniverse u) = PUniverse u mapPTermFC f g (PGoal fc t1 n t2) = PGoal (f fc) (mapPTermFC f g t1) n (mapPTermFC f g t2) mapPTermFC f g (PConstant fc c) = PConstant (f fc) c mapPTermFC f g Placeholder = Placeholder mapPTermFC f g (PDoBlock dos) = PDoBlock (map mapPDoFC dos) where mapPDoFC (DoExp fc t) = DoExp (f fc) (mapPTermFC f g t) mapPDoFC (DoBind fc n nfc t) = DoBind (f fc) n (g nfc) (mapPTermFC f g t) mapPDoFC (DoBindP fc t1 t2 alts) = DoBindP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (map (\(l,r)-> (mapPTermFC f g l, mapPTermFC f g r)) alts) mapPDoFC (DoLet fc n nfc t1 t2) = DoLet (f fc) n (g nfc) (mapPTermFC f g t1) (mapPTermFC f g t2) mapPDoFC (DoLetP fc t1 t2) = DoLetP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) mapPTermFC f g (PIdiom fc t) = PIdiom (f fc) (mapPTermFC f g t) mapPTermFC f g (PReturn fc) = PReturn (f fc) mapPTermFC f g (PMetavar fc n) = PMetavar (g fc) n mapPTermFC f g (PProof tacs) = PProof (map (fmap (mapPTermFC f g)) tacs) mapPTermFC f g (PTactics tacs) = PTactics (map (fmap (mapPTermFC f g)) tacs) mapPTermFC f g (PElabError err) = PElabError err mapPTermFC f g PImpossible = PImpossible mapPTermFC f g (PCoerced t) = PCoerced (mapPTermFC f g t) mapPTermFC f g (PDisamb msg t) = PDisamb msg (mapPTermFC f g t) mapPTermFC f g (PUnifyLog t) = PUnifyLog (mapPTermFC f g t) mapPTermFC f g (PNoImplicits t) = PNoImplicits (mapPTermFC f g t) mapPTermFC f g (PQuasiquote t1 t2) = PQuasiquote (mapPTermFC f g t1) (fmap (mapPTermFC f g) t2) mapPTermFC f g (PUnquote t) = PUnquote (mapPTermFC f g t) mapPTermFC f g (PRunElab fc tm ns) = PRunElab (f fc) (mapPTermFC f g tm) ns mapPTermFC f g (PConstSugar fc tm) = PConstSugar (g fc) (mapPTermFC f g tm) mapPTermFC f g (PQuoteName n fc) = PQuoteName n (g fc) {-! dg instance Binary PTerm deriving instance NFData PTerm !-} mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm mapPT f t = f (mpt t) where mpt (PLam fc n nfc t s) = PLam fc n nfc (mapPT f t) (mapPT f s) mpt (PPi p n nfc t s) = PPi p n nfc (mapPT f t) (mapPT f s) mpt (PLet fc n nfc ty v s) = PLet fc n nfc (mapPT f ty) (mapPT f v) (mapPT f s) mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s) (fmap (mapPT f) g) mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as) mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as) mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os) mpt (PIfThenElse fc c t e) = PIfThenElse fc (mapPT f c) (mapPT f t) (mapPT f e) mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r) mpt (PPair fc hls p l r) = PPair fc hls p (mapPT f l) (mapPT f r) mpt (PDPair fc hls p l t r) = PDPair fc hls p (mapPT f l) (mapPT f t) (mapPT f r) mpt (PAlternative ns a as) = PAlternative ns a (map (mapPT f) as) mpt (PHidden t) = PHidden (mapPT f t) mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds) mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts) mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts) mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm) mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm) mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm) mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc) mpt x = x data PTactic' t = Intro [Name] | Intros | Focus Name | Refine Name [Bool] | Rewrite t | DoUnify | Induction t | CaseTac t | Equiv t | Claim Name t | Unfocus | MatchRefine Name | LetTac Name t | LetTacTy Name t t | Exact t | Compute | Trivial | TCInstance | ProofSearch Bool Bool Int (Maybe Name) [Name] -- allowed local names [Name] -- hints -- ^ the bool is whether to search recursively | Solve | Attack | ProofState | ProofTerm | Undo | Try (PTactic' t) (PTactic' t) | TSeq (PTactic' t) (PTactic' t) | ApplyTactic t -- see Language.Reflection module | ByReflection t | Reflect t | Fill t | GoalType String (PTactic' t) | TCheck t | TEval t | TDocStr (Either Name Const) | TSearch t | Skip | TFail [ErrorReportPart] | Qed | Abandon | SourceFC deriving (Show, Eq, Functor, Foldable, Traversable, Data, Typeable) {-! deriving instance Binary PTactic' deriving instance NFData PTactic' !-} instance Sized a => Sized (PTactic' a) where size (Intro nms) = 1 + size nms size Intros = 1 size (Focus nm) = 1 + size nm size (Refine nm bs) = 1 + size nm + length bs size (Rewrite t) = 1 + size t size (Induction t) = 1 + size t size (LetTac nm t) = 1 + size nm + size t size (Exact t) = 1 + size t size Compute = 1 size Trivial = 1 size Solve = 1 size Attack = 1 size ProofState = 1 size ProofTerm = 1 size Undo = 1 size (Try l r) = 1 + size l + size r size (TSeq l r) = 1 + size l + size r size (ApplyTactic t) = 1 + size t size (Reflect t) = 1 + size t size (Fill t) = 1 + size t size Qed = 1 size Abandon = 1 size Skip = 1 size (TFail ts) = 1 + size ts size SourceFC = 1 size DoUnify = 1 size (CaseTac x) = 1 + size x size (Equiv t) = 1 + size t size (Claim x y) = 1 + size x + size y size Unfocus = 1 size (MatchRefine x) = 1 + size x size (LetTacTy x y z) = 1 + size x + size y + size z size TCInstance = 1 type PTactic = PTactic' PTerm data PDo' t = DoExp FC t | DoBind FC Name FC t -- ^ second FC is precise name location | DoBindP FC t t [(t,t)] | DoLet FC Name FC t t -- ^ second FC is precise name location | DoLetP FC t t deriving (Eq, Functor, Data, Typeable) {-! deriving instance Binary PDo' deriving instance NFData PDo' !-} instance Sized a => Sized (PDo' a) where size (DoExp fc t) = 1 + size fc + size t size (DoBind fc nm nfc t) = 1 + size fc + size nm + size nfc + size t size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts size (DoLet fc nm nfc l r) = 1 + size fc + size nm + size l + size r size (DoLetP fc l r) = 1 + size fc + size l + size r type PDo = PDo' PTerm -- The priority gives a hint as to elaboration order. Best to elaborate -- things early which will help give a more concrete type to other -- variables, e.g. a before (interpTy a). data PArg' t = PImp { priority :: Int, machine_inf :: Bool, -- true if the machine inferred it argopts :: [ArgOpt], pname :: Name, getTm :: t } | PExp { priority :: Int, argopts :: [ArgOpt], pname :: Name, getTm :: t } | PConstraint { priority :: Int, argopts :: [ArgOpt], pname :: Name, getTm :: t } | PTacImplicit { priority :: Int, argopts :: [ArgOpt], pname :: Name, getScript :: t, getTm :: t } deriving (Show, Eq, Functor, Data, Typeable) data ArgOpt = AlwaysShow | HideDisplay | InaccessibleArg | UnknownImp deriving (Show, Eq, Data, Typeable) instance Sized a => Sized (PArg' a) where size (PImp p _ l nm trm) = 1 + size nm + size trm size (PExp p l nm trm) = 1 + size nm + size trm size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm {-! deriving instance Binary PArg' deriving instance NFData PArg' !-} pimp n t mach = PImp 1 mach [] n t pexp t = PExp 1 [] (sMN 0 "arg") t pconst t = PConstraint 1 [] (sMN 0 "carg") t ptacimp n s t = PTacImplicit 2 [] n s t type PArg = PArg' PTerm -- | Get the highest FC in a term, if one exists highestFC :: PTerm -> Maybe FC highestFC (PQuote _) = Nothing highestFC (PRef fc _ _) = Just fc highestFC (PInferRef fc _ _) = Just fc highestFC (PPatvar fc _) = Just fc highestFC (PLam fc _ _ _ _) = Just fc highestFC (PPi _ _ _ _ _) = Nothing highestFC (PLet fc _ _ _ _ _) = Just fc highestFC (PTyped tm ty) = highestFC tm <|> highestFC ty highestFC (PApp fc _ _) = Just fc highestFC (PAppBind fc _ _) = Just fc highestFC (PMatchApp fc _) = Just fc highestFC (PCase fc _ _) = Just fc highestFC (PIfThenElse fc _ _ _) = Just fc highestFC (PTrue fc _) = Just fc highestFC (PResolveTC fc) = Just fc highestFC (PRewrite fc _ _ _) = Just fc highestFC (PPair fc _ _ _ _) = Just fc highestFC (PDPair fc _ _ _ _ _) = Just fc highestFC (PAs fc _ _) = Just fc highestFC (PAlternative _ _ args) = case mapMaybe highestFC args of [] -> Nothing (fc:_) -> Just fc highestFC (PHidden _) = Nothing highestFC (PType fc) = Just fc highestFC (PUniverse _) = Nothing highestFC (PGoal fc _ _ _) = Just fc highestFC (PConstant fc _) = Just fc highestFC Placeholder = Nothing highestFC (PDoBlock lines) = case map getDoFC lines of [] -> Nothing (fc:_) -> Just fc where getDoFC (DoExp fc t) = fc getDoFC (DoBind fc nm nfc t) = fc getDoFC (DoBindP fc l r alts) = fc getDoFC (DoLet fc nm nfc l r) = fc getDoFC (DoLetP fc l r) = fc highestFC (PIdiom fc _) = Just fc highestFC (PReturn fc) = Just fc highestFC (PMetavar fc _) = Just fc highestFC (PProof _) = Nothing highestFC (PTactics _) = Nothing highestFC (PElabError _) = Nothing highestFC PImpossible = Nothing highestFC (PCoerced tm) = highestFC tm highestFC (PDisamb _ opts) = highestFC opts highestFC (PUnifyLog tm) = highestFC tm highestFC (PNoImplicits tm) = highestFC tm highestFC (PQuasiquote _ _) = Nothing highestFC (PUnquote tm) = highestFC tm highestFC (PQuoteName _ fc) = Just fc highestFC (PRunElab fc _ _) = Just fc highestFC (PConstSugar fc _) = Just fc highestFC (PAppImpl t _) = highestFC t -- Type class data data ClassInfo = CI { instanceCtorName :: Name, class_methods :: [(Name, (FnOpts, PTerm))], class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl class_default_superclasses :: [PDecl], class_params :: [Name], class_instances :: [(Name, Bool)], -- the Bool is whether to include in instance search, so named instances are excluded class_determiners :: [Int] } deriving Show {-! deriving instance Binary ClassInfo deriving instance NFData ClassInfo !-} -- Type inference data data TIData = TIPartial -- ^ a function with a partially defined type | TISolution [Term] -- ^ possible solutions to a metavariable in a type deriving Show -- | Miscellaneous information about functions data FnInfo = FnInfo { fn_params :: [Int] } deriving Show {-! deriving instance Binary FnInfo deriving instance NFData FnInfo !-} data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting detaggable :: Bool } deriving Show {-! deriving instance Binary OptInfo deriving instance NFData OptInfo !-} -- | Syntactic sugar info data DSL' t = DSL { dsl_bind :: t, dsl_return :: t, dsl_apply :: t, dsl_pure :: t, dsl_var :: Maybe t, index_first :: Maybe t, index_next :: Maybe t, dsl_lambda :: Maybe t, dsl_let :: Maybe t, dsl_pi :: Maybe t } deriving (Show, Functor) {-! deriving instance Binary DSL' deriving instance NFData DSL' !-} type DSL = DSL' PTerm data SynContext = PatternSyntax | TermSyntax | AnySyntax deriving Show {-! deriving instance Binary SynContext deriving instance NFData SynContext !-} data Syntax = Rule [SSymbol] PTerm SynContext deriving Show syntaxNames :: Syntax -> [Name] syntaxNames (Rule syms _ _) = mapMaybe ename syms where ename (Keyword n) = Just n ename _ = Nothing syntaxSymbols :: Syntax -> [SSymbol] syntaxSymbols (Rule ss _ _) = ss {-! deriving instance Binary Syntax deriving instance NFData Syntax !-} data SSymbol = Keyword Name | Symbol String | Binding Name | Expr Name | SimpleExpr Name deriving (Show, Eq) {-! deriving instance Binary SSymbol deriving instance NFData SSymbol !-} newtype SyntaxRules = SyntaxRules { syntaxRulesList :: [Syntax] } emptySyntaxRules :: SyntaxRules emptySyntaxRules = SyntaxRules [] updateSyntaxRules :: [Syntax] -> SyntaxRules -> SyntaxRules updateSyntaxRules rules (SyntaxRules sr) = SyntaxRules newRules where newRules = sortBy (ruleSort `on` syntaxSymbols) (rules ++ sr) ruleSort [] [] = EQ ruleSort [] _ = LT ruleSort _ [] = GT ruleSort (s1:ss1) (s2:ss2) = case symCompare s1 s2 of EQ -> ruleSort ss1 ss2 r -> r -- Better than creating Ord instance for SSymbol since -- in general this ordering does not really make sense. symCompare (Keyword n1) (Keyword n2) = compare n1 n2 symCompare (Keyword _) _ = LT symCompare (Symbol _) (Keyword _) = GT symCompare (Symbol s1) (Symbol s2) = compare s1 s2 symCompare (Symbol _) _ = LT symCompare (Binding _) (Keyword _) = GT symCompare (Binding _) (Symbol _) = GT symCompare (Binding b1) (Binding b2) = compare b1 b2 symCompare (Binding _) _ = LT symCompare (Expr _) (Keyword _) = GT symCompare (Expr _) (Symbol _) = GT symCompare (Expr _) (Binding _) = GT symCompare (Expr e1) (Expr e2) = compare e1 e2 symCompare (Expr _) _ = LT symCompare (SimpleExpr _) (Keyword _) = GT symCompare (SimpleExpr _) (Symbol _) = GT symCompare (SimpleExpr _) (Binding _) = GT symCompare (SimpleExpr _) (Expr _) = GT symCompare (SimpleExpr e1) (SimpleExpr e2) = compare e1 e2 initDSL = DSL (PRef f [] (sUN ">>=")) (PRef f [] (sUN "return")) (PRef f [] (sUN "<*>")) (PRef f [] (sUN "pure")) Nothing Nothing Nothing Nothing Nothing Nothing where f = fileFC "(builtin)" data Using = UImplicit Name PTerm | UConstraint Name [Name] deriving (Show, Eq, Data, Typeable) {-! deriving instance Binary Using deriving instance NFData Using !-} data SyntaxInfo = Syn { using :: [Using], syn_params :: [(Name, PTerm)], syn_namespace :: [String], no_imp :: [Name], imp_methods :: [Name], -- class methods. When expanding -- implicits, these should be expanded even under -- binders decoration :: Name -> Name, inPattern :: Bool, implicitAllowed :: Bool, maxline :: Maybe Int, mut_nesting :: Int, dsl_info :: DSL, syn_in_quasiquote :: Int } deriving Show {-! deriving instance NFData SyntaxInfo deriving instance Binary SyntaxInfo !-} defaultSyntax = Syn [] [] [] [] [] id False False Nothing 0 initDSL 0 expandNS :: SyntaxInfo -> Name -> Name expandNS syn n@(NS _ _) = n expandNS syn n = case syn_namespace syn of [] -> n xs -> sNS n xs -- For inferring types of things bi = fileFC "builtin" inferTy = sMN 0 "__Infer" inferCon = sMN 0 "__infer" inferDecl = PDatadecl inferTy NoFC (PType bi) [(emptyDocstring, [], inferCon, NoFC, PPi impl (sMN 0 "iType") NoFC (PType bi) ( PPi expl (sMN 0 "ival") NoFC (PRef bi [] (sMN 0 "iType")) (PRef bi [] inferTy)), bi, [])] inferOpts = [] infTerm t = PApp bi (PRef bi [] inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t] infP = P (TCon 6 0) inferTy (TType (UVal 0)) getInferTerm, getInferType :: Term -> Term getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc getInferTerm (App _ (App _ _ _) tm) = tm getInferTerm tm = tm -- error ("getInferTerm " ++ show tm) getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc where toTy (Lam t) = Pi Nothing t (TType (UVar 0)) toTy (PVar t) = PVTy t toTy b = b getInferType (App _ (App _ _ ty) _) = ty -- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign primNames = [inferTy, inferCon] unitTy = sUN "Unit" unitCon = sUN "MkUnit" falseDoc = fmap (const $ Msg "") . parseDocstring . T.pack $ "The empty type, also known as the trivially false proposition." ++ "\n\n" ++ "Use `void` or `absurd` to prove anything if you have a variable " ++ "of type `Void` in scope." falseTy = sUN "Void" pairTy = sNS (sUN "Pair") ["Builtins"] pairCon = sNS (sUN "MkPair") ["Builtins"] upairTy = sNS (sUN "UPair") ["Builtins"] upairCon = sNS (sUN "MkUPair") ["Builtins"] eqTy = sUN "=" eqCon = sUN "Refl" eqDoc = fmap (const (Left $ Msg "")) . parseDocstring . T.pack $ "The propositional equality type. A proof that `x` = `y`." ++ "\n\n" ++ "To use such a proof, pattern-match on it, and the two equal things will " ++ "then need to be the _same_ pattern." ++ "\n\n" ++ "**Note**: Idris's equality type is potentially _heterogeneous_, which means that it " ++ "is possible to state equalities between values of potentially different " ++ "types. However, Idris will attempt the homogeneous case unless it fails to typecheck." ++ "\n\n" ++ "You may need to use `(~=~)` to explicitly request heterogeneous equality." eqDecl = PDatadecl eqTy NoFC (piBindp impl [(n "A", PType bi), (n "B", PType bi)] (piBind [(n "x", PRef bi [] (n "A")), (n "y", PRef bi [] (n "B"))] (PType bi))) [(reflDoc, reflParamDoc, eqCon, NoFC, PPi impl (n "A") NoFC (PType bi) ( PPi impl (n "x") NoFC (PRef bi [] (n "A")) (PApp bi (PRef bi [] eqTy) [pimp (n "A") Placeholder False, pimp (n "B") Placeholder False, pexp (PRef bi [] (n "x")), pexp (PRef bi [] (n "x"))])), bi, [])] where n a = sUN a reflDoc = annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "A proof that `x` in fact equals `x`. To construct this, you must have already " ++ "shown that both sides are in fact equal." reflParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type at which the equality is proven"), (n "x", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the element shown to be equal to itself.")] eqParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the left side of the equality"), (n "B", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the right side of the equality") ] where n a = sUN a eqOpts = [] -- | The special name to be used in the module documentation context - -- not for use in the main definition context. The namespace around it -- will determine the module to which the docs adhere. modDocName :: Name modDocName = sMN 0 "ModuleDocs" -- Defined in builtins.idr sigmaTy = sNS (sUN "Sigma") ["Builtins"] sigmaCon = sNS (sUN "MkSigma") ["Builtins"] piBind :: [(Name, PTerm)] -> PTerm -> PTerm piBind = piBindp expl piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm piBindp p [] t = t piBindp p ((n, ty):ns) t = PPi p n NoFC ty (piBindp p ns t) -- Pretty-printing declarations and terms -- These "show" instances render to an absurdly wide screen because inserted line breaks -- could interfere with interactive editing, which calls "show". instance Show PTerm where showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp defaultPPOption) tm instance Show PDecl where showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp verbosePPOption) d instance Show PClause where showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp verbosePPOption) c instance Show PData where showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp defaultPPOption) d instance Pretty PTerm OutputAnnotation where pretty = prettyImp defaultPPOption -- | Colourise annotations according to an Idris state. It ignores the names -- in the annotation, as there's no good way to show extended information on a -- terminal. consoleDecorate :: IState -> OutputAnnotation -> String -> String consoleDecorate ist _ | not (idris_colourRepl ist) = id consoleDecorate ist (AnnConst c) = let theme = idris_colourTheme ist in if constIsType c then colouriseType theme else colouriseData theme consoleDecorate ist (AnnData _ _) = colouriseData (idris_colourTheme ist) consoleDecorate ist (AnnType _ _) = colouriseType (idris_colourTheme ist) consoleDecorate ist (AnnBoundName _ True) = colouriseImplicit (idris_colourTheme ist) consoleDecorate ist (AnnBoundName _ False) = colouriseBound (idris_colourTheme ist) consoleDecorate ist AnnKeyword = colouriseKeyword (idris_colourTheme ist) consoleDecorate ist (AnnName n _ _ _) = let ctxt = tt_ctxt ist theme = idris_colourTheme ist in case () of _ | isDConName n ctxt -> colouriseData theme _ | isFnName n ctxt -> colouriseFun theme _ | isTConName n ctxt -> colouriseType theme _ | isPostulateName n ist -> colourisePostulate theme _ | otherwise -> id -- don't colourise unknown names consoleDecorate ist (AnnFC _) = id consoleDecorate ist (AnnTextFmt fmt) = Idris.Colours.colourise (colour fmt) where colour BoldText = IdrisColour Nothing True False True False colour UnderlineText = IdrisColour Nothing True True False False colour ItalicText = IdrisColour Nothing True False False True consoleDecorate ist (AnnTerm _ _) = id consoleDecorate ist (AnnSearchResult _) = id consoleDecorate ist (AnnErr _) = id consoleDecorate ist (AnnNamespace _ _) = id consoleDecorate ist (AnnLink url) = \txt -> Idris.Colours.colourise (IdrisColour Nothing True True False False) txt ++ " (" ++ url ++ ")" isPostulateName :: Name -> IState -> Bool isPostulateName n ist = S.member n (idris_postulates ist) -- | Pretty-print a high-level closed Idris term with no information about precedence/associativity prettyImp :: PPOption -- ^^ pretty printing options -> PTerm -- ^^ the term to pretty-print -> Doc OutputAnnotation prettyImp impl = pprintPTerm impl [] [] [] -- | Serialise something to base64 using its Binary instance. -- | Do the right thing for rendering a term in an IState prettyIst :: IState -> PTerm -> Doc OutputAnnotation prettyIst ist = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist) -- | Pretty-print a high-level Idris term in some bindings context with infix info pprintPTerm :: PPOption -- ^^ pretty printing options -> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit -> [Name] -- ^^ names to always show in pi, even if not used -> [FixDecl] -- ^^ Fixity declarations -> PTerm -- ^^ the term to pretty-print -> Doc OutputAnnotation pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd where startPrec = 0 funcAppPrec = 10 prettySe :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation prettySe d p bnd (PQuote r) = text "![" <> pretty r <> text "]" prettySe d p bnd (PPatvar fc n) = pretty n prettySe d p bnd e | Just str <- slist d p bnd e = depth d $ str | Just n <- snat d p e = depth d $ annotate (AnnData "Nat" "") (text (show n)) prettySe d p bnd (PRef fc _ n) = prettyName True (ppopt_impl ppo) bnd n prettySe d p bnd (PLam fc n nfc ty sc) = depth d . bracket p startPrec . group . align . hang 2 $ text "\\" <> prettyBindingOf n False <+> text "=>" <$> prettySe (decD d) startPrec ((n, False):bnd) sc prettySe d p bnd (PLet fc n nfc ty v sc) = depth d . bracket p startPrec . group . align $ kwd "let" <+> (group . align . hang 2 $ prettyBindingOf n False <+> text "=" <$> prettySe (decD d) startPrec bnd v) </> kwd "in" <+> (group . align . hang 2 $ prettySe (decD d) startPrec ((n, False):bnd) sc) prettySe d p bnd (PPi (Exp l s _) n _ ty sc) | n `elem` allNamesIn sc || ppopt_impl ppo || n `elem` docArgs = depth d . bracket p startPrec . group $ enclose lparen rparen (group . align $ prettyBindingOf n False <+> colon <+> prettySe (decD d) startPrec bnd ty) <+> st <> text "->" <$> prettySe (decD d) startPrec ((n, False):bnd) sc | otherwise = depth d . bracket p startPrec . group $ group (prettySe (decD d) (startPrec + 1) bnd ty <+> st) <> text "->" <$> group (prettySe (decD d) startPrec ((n, False):bnd) sc) where st = case s of Static -> text "[static]" <> space _ -> empty prettySe d p bnd (PPi (Imp l s _ fa) n _ ty sc) | ppopt_impl ppo = depth d . bracket p startPrec $ lbrace <> prettyBindingOf n True <+> colon <+> prettySe (decD d) startPrec bnd ty <> rbrace <+> st <> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc | otherwise = depth d $ prettySe (decD d) startPrec ((n, True):bnd) sc where st = case s of Static -> text "[static]" <> space _ -> empty prettySe d p bnd (PPi (Constraint _ _) n _ ty sc) = depth d . bracket p startPrec $ prettySe (decD d) (startPrec + 1) bnd ty <+> text "=>" </> prettySe (decD d) startPrec ((n, True):bnd) sc prettySe d p bnd (PPi (TacImp _ _ (PTactics [ProofSearch _ _ _ _ _ _])) n _ ty sc) = lbrace <> kwd "auto" <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <> rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc prettySe d p bnd (PPi (TacImp _ _ s) n _ ty sc) = depth d . bracket p startPrec $ lbrace <> kwd "default" <+> prettySe (decD d) (funcAppPrec + 1) bnd s <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <> rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc -- This case preserves the behavior of the former constructor PEq. -- It should be removed if feasible when the pretty-printing of infix -- operators in general is improved. prettySe d p bnd (PApp _ (PRef _ _ n) [lt, rt, l, r]) | n == eqTy, ppopt_impl ppo = depth d . bracket p eqPrec $ enclose lparen rparen eq <+> align (group (vsep (map (prettyArgS (decD d) bnd) [lt, rt, l, r]))) | n == eqTy = depth d . bracket p eqPrec . align . group $ prettyTerm (getTm l) <+> eq <$> group (prettyTerm (getTm r)) where eq = annName eqTy (text "=") eqPrec = startPrec prettyTerm = prettySe (decD d) (eqPrec + 1) bnd prettySe d p bnd (PApp _ (PRef _ _ f) args) -- normal names, no explicit args | UN nm <- basename f , not (ppopt_impl ppo) && null (getShowArgs args) = prettyName True (ppopt_impl ppo) bnd f prettySe d p bnd (PAppBind _ (PRef _ _ f) []) | not (ppopt_impl ppo) = text "!" <> prettyName True (ppopt_impl ppo) bnd f prettySe d p bnd (PApp _ (PRef _ _ op) args) -- infix operators | UN nm <- basename op , not (tnull nm) && (not (ppopt_impl ppo)) && (not $ isAlpha (thead nm)) = case getShowArgs args of [] -> opName True [x] -> group (opName True <$> group (prettySe (decD d) startPrec bnd (getTm x))) [l,r] -> let precedence = maybe (startPrec - 1) prec f in depth d . bracket p precedence $ inFix (getTm l) (getTm r) (l@(PExp _ _ _ _) : r@(PExp _ _ _ _) : rest) -> depth d . bracket p funcAppPrec $ enclose lparen rparen (inFix (getTm l) (getTm r)) <+> align (group (vsep (map (prettyArgS d bnd) rest))) as -> opName True <+> align (vsep (map (prettyArgS d bnd) as)) where opName isPrefix = prettyName isPrefix (ppopt_impl ppo) bnd op f = getFixity (opStr op) left = case f of Nothing -> funcAppPrec + 1 Just (Infixl p') -> p' Just f' -> prec f' + 1 right = case f of Nothing -> funcAppPrec + 1 Just (Infixr p') -> p' Just f' -> prec f' + 1 inFix l r = align . group $ (prettySe (decD d) left bnd l <+> opName False) <$> group (prettySe (decD d) right bnd r) prettySe d p bnd (PApp _ hd@(PRef fc _ f) [tm]) -- symbols, like 'foo | PConstant NoFC (Idris.Core.TT.Str str) <- getTm tm, f == sUN "Symbol_" = annotate (AnnType ("'" ++ str) ("The symbol " ++ str)) $ char '\'' <> prettySe (decD d) startPrec bnd (PRef fc [] (sUN str)) prettySe d p bnd (PApp _ f as) = -- Normal prefix applications let args = getShowArgs as fp = prettySe (decD d) (startPrec + 1) bnd f shownArgs = if ppopt_impl ppo then as else args in depth d . bracket p funcAppPrec . group $ if null shownArgs then fp else fp <+> align (vsep (map (prettyArgS d bnd) shownArgs)) prettySe d p bnd (PCase _ scr cases) = align $ kwd "case" <+> prettySe (decD d) startPrec bnd scr <+> kwd "of" <$> depth d (indent 2 (vsep (map ppcase cases))) where ppcase (l, r) = let prettyCase = prettySe (decD d) startPrec ([(n, False) | n <- vars l] ++ bnd) in nest nestingSize $ prettyCase l <+> text "=>" <+> prettyCase r -- Warning: this is a bit of a hack. At this stage, we don't have the -- global context, so we can't determine which names are constructors, -- which are types, and which are pattern variables on the LHS of the -- case pattern. We use the heuristic that names without a namespace -- are patvars, because right now case blocks in PTerms are always -- delaborated from TT before being sent to the pretty-printer. If they -- start getting printed directly, THIS WILL BREAK. -- Potential solution: add a list of known patvars to the cases in -- PCase, and have the delaborator fill it out, kind of like the pun -- disambiguation on PDPair. vars tm = filter noNS (allNamesIn tm) noNS (NS _ _) = False noNS _ = True prettySe d p bnd (PIfThenElse _ c t f) = depth d . bracket p funcAppPrec . group . align . hang 2 . vsep $ [ kwd "if" <+> prettySe (decD d) startPrec bnd c , kwd "then" <+> prettySe (decD d) startPrec bnd t , kwd "else" <+> prettySe (decD d) startPrec bnd f ] prettySe d p bnd (PHidden tm) = text "." <> prettySe (decD d) funcAppPrec bnd tm prettySe d p bnd (PResolveTC _) = kwd "%instance" prettySe d p bnd (PTrue _ IsType) = annName unitTy $ text "()" prettySe d p bnd (PTrue _ IsTerm) = annName unitCon $ text "()" prettySe d p bnd (PTrue _ TypeOrTerm) = text "()" prettySe d p bnd (PRewrite _ l r _) = depth d . bracket p startPrec $ text "rewrite" <+> prettySe (decD d) (startPrec + 1) bnd l <+> text "in" <+> prettySe (decD d) startPrec bnd r prettySe d p bnd (PTyped l r) = lparen <> prettySe (decD d) startPrec bnd l <+> colon <+> prettySe (decD d) startPrec bnd r <> rparen prettySe d p bnd pair@(PPair _ _ pun _ _) -- flatten tuples to the right, like parser | Just elts <- pairElts pair = depth d . enclose (ann lparen) (ann rparen) . align . group . vsep . punctuate (ann comma) $ map (prettySe (decD d) startPrec bnd) elts where ann = case pun of TypeOrTerm -> id IsType -> annName pairTy IsTerm -> annName pairCon prettySe d p bnd (PDPair _ _ pun l t r) = depth d $ annotated lparen <> left <+> annotated (text "**") <+> prettySe (decD d) startPrec (addBinding bnd) r <> annotated rparen where annotated = case pun of IsType -> annName sigmaTy IsTerm -> annName sigmaCon TypeOrTerm -> id (left, addBinding) = case (l, pun) of (PRef _ _ n, IsType) -> (bindingOf n False <+> text ":" <+> prettySe (decD d) startPrec bnd t, ((n, False) :)) _ -> (prettySe (decD d) startPrec bnd l, id) prettySe d p bnd (PAlternative ns a as) = lparen <> text "|" <> prettyAs <> text "|" <> rparen where prettyAs = foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (depth d . prettySe (decD d) startPrec bnd) as prettySe d p bnd (PType _) = annotate (AnnType "Type" "The type of types") $ text "Type" prettySe d p bnd (PUniverse u) = annotate (AnnType (show u) "The type of unique types") $ text (show u) prettySe d p bnd (PConstant _ c) = annotate (AnnConst c) (text (show c)) -- XXX: add pretty for tactics prettySe d p bnd (PProof ts) = kwd "proof" <+> lbrace <> ellipsis <> rbrace prettySe d p bnd (PTactics ts) = kwd "tactics" <+> lbrace <> ellipsis <> rbrace prettySe d p bnd (PMetavar _ n) = annotate (AnnName n (Just MetavarOutput) Nothing Nothing) $ text "?" <> pretty n prettySe d p bnd (PReturn f) = kwd "return" prettySe d p bnd PImpossible = kwd "impossible" prettySe d p bnd Placeholder = text "_" prettySe d p bnd (PDoBlock dos) = bracket p startPrec $ kwd "do" <+> align (vsep (map (group . align . hang 2) (ppdo bnd dos))) where ppdo bnd (DoExp _ tm:dos) = prettySe (decD d) startPrec bnd tm : ppdo bnd dos ppdo bnd (DoBind _ bn _ tm : dos) = (prettyBindingOf bn False <+> text "<-" <+> group (align (hang 2 (prettySe (decD d) startPrec bnd tm)))) : ppdo ((bn, False):bnd) dos ppdo bnd (DoBindP _ _ _ _ : dos) = -- ok because never made by delab text "no pretty printer for pattern-matching do binding" : ppdo bnd dos ppdo bnd (DoLet _ ln _ ty v : dos) = (kwd "let" <+> prettyBindingOf ln False <+> (if ty /= Placeholder then colon <+> prettySe (decD d) startPrec bnd ty <+> text "=" else text "=") <+> group (align (hang 2 (prettySe (decD d) startPrec bnd v)))) : ppdo ((ln, False):bnd) dos ppdo bnd (DoLetP _ _ _ : dos) = -- ok because never made by delab text "no pretty printer for pattern-matching do binding" : ppdo bnd dos ppdo _ [] = [] prettySe d p bnd (PCoerced t) = prettySe d p bnd t prettySe d p bnd (PElabError s) = pretty s -- Quasiquote pprinting ignores bound vars prettySe d p bnd (PQuasiquote t Nothing) = text "`(" <> prettySe (decD d) p [] t <> text ")" prettySe d p bnd (PQuasiquote t (Just g)) = text "`(" <> prettySe (decD d) p [] t <+> colon <+> prettySe (decD d) p [] g <> text ")" prettySe d p bnd (PUnquote t) = text "~" <> prettySe (decD d) p bnd t prettySe d p bnd (PQuoteName n _) = text "`{" <> prettyName True (ppopt_impl ppo) bnd n <> text "}" prettySe d p bnd (PRunElab _ tm _) = bracket p funcAppPrec . group . align . hang 2 $ text "%runElab" <$> prettySe (decD d) funcAppPrec bnd tm prettySe d p bnd (PConstSugar fc tm) = prettySe d p bnd tm -- should never occur, but harmless prettySe d p bnd _ = text "missing pretty-printer for term" prettyBindingOf :: Name -> Bool -> Doc OutputAnnotation prettyBindingOf n imp = annotate (AnnBoundName n imp) (text (display n)) where display (UN n) = T.unpack n display (MN _ n) = T.unpack n -- If a namespace is specified on a binding form, we'd better show it regardless of the implicits settings display (NS n ns) = (concat . intersperse "." . map T.unpack . reverse) ns ++ "." ++ display n display n = show n prettyArgS d bnd (PImp _ _ _ n tm) = prettyArgSi d bnd (n, tm) prettyArgS d bnd (PExp _ _ _ tm) = prettyArgSe d bnd tm prettyArgS d bnd (PConstraint _ _ _ tm) = prettyArgSc d bnd tm prettyArgS d bnd (PTacImplicit _ _ n _ tm) = prettyArgSti d bnd (n, tm) prettyArgSe d bnd arg = prettySe d (funcAppPrec + 1) bnd arg prettyArgSi d bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace prettyArgSc d bnd val = lbrace <> lbrace <> prettySe (decD d) startPrec bnd val <> rbrace <> rbrace prettyArgSti d bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation annName n = annotate (AnnName n Nothing Nothing Nothing) opStr :: Name -> String opStr (NS n _) = opStr n opStr (UN n) = T.unpack n slist' :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Maybe [Doc OutputAnnotation] slist' (Just d) _ _ _ | d <= 0 = Nothing slist' d _ _ e | containsHole e = Nothing slist' d p bnd (PApp _ (PRef _ _ nil) _) | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just [] slist' d p bnd (PRef _ _ nil) | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just [] slist' d p bnd (PApp _ (PRef _ _ cons) args) | nsroot cons == sUN "::", (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args, all isImp imps, Just tl' <- slist' (decD d) p bnd tl = Just (prettySe d startPrec bnd hd : tl') where isImp (PImp {}) = True isImp _ = False slist' _ _ _ tm = Nothing slist d p bnd e | Just es <- slist' d p bnd e = Just $ case es of [] -> annotate (AnnData "" "") $ text "[]" [x] -> enclose left right . group $ x xs -> enclose left right . align . group . vsep . punctuate comma $ xs where left = (annotate (AnnData "" "") (text "[")) right = (annotate (AnnData "" "") (text "]")) comma = (annotate (AnnData "" "") (text ",")) slist _ _ _ _ = Nothing pairElts :: PTerm -> Maybe [PTerm] pairElts (PPair _ _ _ x y) | Just elts <- pairElts y = Just (x:elts) | otherwise = Just [x, y] pairElts _ = Nothing natns = "Prelude.Nat." snat :: Maybe Int -> Int -> PTerm -> Maybe Integer snat (Just x) _ _ | x <= 0 = Nothing snat d p (PRef _ _ z) | show z == (natns++"Z") || show z == "Z" = Just 0 snat d p (PApp _ s [PExp {getTm=n}]) | show s == (natns++"S") || show s == "S", Just n' <- snat (decD d) p n = Just $ 1 + n' snat _ _ _ = Nothing bracket outer inner doc | outer > inner = lparen <> doc <> rparen | otherwise = doc ellipsis = text "..." depth Nothing = id depth (Just d) = if d <= 0 then const (ellipsis) else id decD = fmap (\x -> x - 1) kwd = annotate AnnKeyword . text fixities :: M.Map String Fixity fixities = M.fromList [(s, f) | (Fix f s) <- infixes] getFixity :: String -> Maybe Fixity getFixity = flip M.lookup fixities -- | Strip away namespace information basename :: Name -> Name basename (NS n _) = basename n basename n = n -- | Determine whether a name was the one inserted for a hole or -- guess by the delaborator isHoleName :: Name -> Bool isHoleName (UN n) = n == T.pack "[__]" isHoleName _ = False -- | Check whether a PTerm has been delaborated from a Term containing a Hole or Guess containsHole :: PTerm -> Bool containsHole pterm = or [isHoleName n | PRef _ _ n <- take 1000 $ universe pterm] -- | Pretty-printer helper for names that attaches the correct annotations prettyName :: Bool -- ^^ whether the name should be parenthesised if it is an infix operator -> Bool -- ^^ whether to show namespaces -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit -> Name -- ^^ the name to pprint -> Doc OutputAnnotation prettyName infixParen showNS bnd n | (MN _ s) <- n, isPrefixOf "_" $ T.unpack s = text "_" | (UN n') <- n, T.unpack n' == "_" = text "_" | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) fullName | otherwise = annotate (AnnName n Nothing Nothing Nothing) fullName where fullName = text nameSpace <> parenthesise (text (baseName n)) baseName (UN n) = T.unpack n baseName (NS n ns) = baseName n baseName (MN i s) = T.unpack s baseName other = show other nameSpace = case n of (NS n' ns) -> if showNS then (concatMap (++ ".") . map T.unpack . reverse) ns else "" _ -> "" isInfix = case baseName n of "" -> False (c : _) -> not (isAlpha c) parenthesise = if isInfix && infixParen then enclose lparen rparen else id showCImp :: PPOption -> PClause -> Doc OutputAnnotation showCImp ppo (PClause _ n l ws r w) = prettyImp ppo l <+> showWs ws <+> text "=" <+> prettyImp ppo r <+> text "where" <+> text (show w) where showWs [] = empty showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs showCImp ppo (PWith _ n l ws r pn w) = prettyImp ppo l <+> showWs ws <+> text "with" <+> prettyImp ppo r <+> braces (text (show w)) where showWs [] = empty showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs showDImp :: PPOption -> PData -> Doc OutputAnnotation showDImp ppo (PDatadecl n nfc ty cons) = text "data" <+> text (show n) <+> colon <+> prettyImp ppo ty <+> text "where" <$> (indent 2 $ vsep (map (\ (_, _, n, _, t, _, _) -> pipe <+> prettyName True False [] n <+> colon <+> prettyImp ppo t) cons)) showDecls :: PPOption -> [PDecl] -> Doc OutputAnnotation showDecls o ds = vsep (map (showDeclImp o) ds) showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops)) showDeclImp o (PTy _ _ _ _ _ n _ t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp o t showDeclImp o (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+> indent 2 (vsep (map (showCImp o) cs)) showDeclImp o (PData _ _ _ _ _ d) = showDImp o { ppopt_impl = True } d showDeclImp o (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls o ps <> line) showDeclImp o (PNamespace n fc ps) = text "namespace" <+> text n <> braces (line <> showDecls o ps <> line) showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn) showDeclImp o (PClass _ _ _ cs n _ ps _ _ ds _ _) = text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls o ds showDeclImp o (PInstance _ _ _ _ cs n _ _ t _ ds) = text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp o t <> line <> showDecls o ds showDeclImp _ _ = text "..." -- showDeclImp (PImport o) = "import " ++ o getImps :: [PArg] -> [(Name, PTerm)] getImps [] = [] getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs getImps (_ : xs) = getImps xs getExps :: [PArg] -> [PTerm] getExps [] = [] getExps (PExp _ _ _ tm : xs) = tm : getExps xs getExps (_ : xs) = getExps xs getShowArgs :: [PArg] -> [PArg] getShowArgs [] = [] getShowArgs (e@(PExp _ _ _ tm) : xs) = e : getShowArgs xs getShowArgs (e : xs) | AlwaysShow `elem` argopts e = e : getShowArgs xs | PImp _ _ _ _ tm <- e , containsHole tm = e : getShowArgs xs getShowArgs (_ : xs) = getShowArgs xs getConsts :: [PArg] -> [PTerm] getConsts [] = [] getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs getConsts (_ : xs) = getConsts xs getAll :: [PArg] -> [PTerm] getAll = map getTm -- | Show Idris name showName :: Maybe IState -- ^^ the Idris state, for information about names and colours -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit -> PPOption -- ^^ pretty printing options -> Bool -- ^^ whether to colourise -> Name -- ^^ the term to show -> String showName ist bnd ppo colour n = case ist of Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n Nothing -> showbasic n where name = if ppopt_impl ppo then show n else showbasic n showbasic n@(UN _) = showCG n showbasic (MN i s) = str s showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n showbasic (SN s) = show s fst3 (x, _, _) = x colourise n t = let ctxt' = fmap tt_ctxt ist in case ctxt' of Nothing -> name Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name else colouriseBound t name | isDConName n ctxt -> colouriseData t name | isFnName n ctxt -> colouriseFun t name | isTConName n ctxt -> colouriseType t name -- The assumption is that if a name is not bound and does not exist in the -- global context, then we're somewhere in which implicit info has been lost -- (like error messages). Thus, unknown vars are colourised as implicits. | otherwise -> colouriseImplicit t name showTm :: IState -- ^^ the Idris state, for information about identifiers and colours -> PTerm -- ^^ the term to show -> String showTm ist = displayDecorated (consoleDecorate ist) . renderPretty 0.8 100000 . prettyImp (ppOptionIst ist) -- | Show a term with implicits, no colours showTmImpls :: PTerm -> String showTmImpls = flip (displayS . renderCompact . prettyImp verbosePPOption) "" instance Sized PTerm where size (PQuote rawTerm) = size rawTerm size (PRef fc _ name) = size name size (PLam fc name _ ty bdy) = 1 + size ty + size bdy size (PPi plicity name fc ty bdy) = 1 + size ty + size fc + size bdy size (PLet fc name nfc ty def bdy) = 1 + size ty + size def + size bdy size (PTyped trm ty) = 1 + size trm + size ty size (PApp fc name args) = 1 + size args size (PAppBind fc name args) = 1 + size args size (PCase fc trm bdy) = 1 + size trm + size bdy size (PIfThenElse fc c t f) = 1 + sum (map size [c, t, f]) size (PTrue fc _) = 1 size (PResolveTC fc) = 1 size (PRewrite fc left right _) = 1 + size left + size right size (PPair fc _ _ left right) = 1 + size left + size right size (PDPair fs _ _ left ty right) = 1 + size left + size ty + size right size (PAlternative _ a alts) = 1 + size alts size (PHidden hidden) = size hidden size (PUnifyLog tm) = size tm size (PDisamb _ tm) = size tm size (PNoImplicits tm) = size tm size (PType _) = 1 size (PUniverse _) = 1 size (PConstant fc const) = 1 + size fc + size const size Placeholder = 1 size (PDoBlock dos) = 1 + size dos size (PIdiom fc term) = 1 + size term size (PReturn fc) = 1 size (PMetavar _ name) = 1 size (PProof tactics) = size tactics size (PElabError err) = size err size PImpossible = 1 size _ = 0 getPArity :: PTerm -> Int getPArity (PPi _ _ _ _ sc) = 1 + getPArity sc getPArity _ = 0 -- Return all names, free or globally bound, in the given term. allNamesIn :: PTerm -> [Name] allNamesIn tm = nub $ ni [] tm where -- TODO THINK added niTacImp, but is it right? ni env (PRef _ _ n) | not (n `elem` env) = [n] ni env (PPatvar _ n) = [n] ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os) ni env (PIfThenElse _ c t f) = ni env c ++ ni env t ++ ni env f ni env (PLam fc n _ ty sc) = ni env ty ++ ni (n:env) sc ni env (PPi p n _ ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc ni env (PLet _ n _ ty val sc) = ni env ty ++ ni env val ++ ni (n:env) sc ni env (PHidden tm) = ni env tm ni env (PRewrite _ l r _) = ni env l ++ ni env r ni env (PTyped l r) = ni env l ++ ni env r ni env (PPair _ _ _ l r) = ni env l ++ ni env r ni env (PDPair _ _ _ (PRef _ _ n) Placeholder r) = n : ni env r ni env (PDPair _ _ _ (PRef _ _ n) t r) = ni env t ++ ni (n:env) r ni env (PDPair _ _ _ l t r) = ni env l ++ ni env t ++ ni env r ni env (PAlternative ns a ls) = concatMap (ni env) ls ni env (PUnifyLog tm) = ni env tm ni env (PDisamb _ tm) = ni env tm ni env (PNoImplicits tm) = ni env tm ni env _ = [] niTacImp env (TacImp _ _ scr) = ni env scr niTacImp _ _ = [] -- Return all names defined in binders in the given term boundNamesIn :: PTerm -> [Name] boundNamesIn tm = S.toList (ni S.empty tm) where -- TODO THINK Added niTacImp, but is it right? ni set (PApp _ f as) = niTms (ni set f) (map getTm as) ni set (PAppBind _ f as) = niTms (ni set f) (map getTm as) ni set (PCase _ c os) = niTms (ni set c) (map snd os) ni set (PIfThenElse _ c t f) = niTms set [c, t, f] ni set (PLam fc n _ ty sc) = S.insert n $ ni (ni set ty) sc ni set (PLet fc n nfc ty val sc) = S.insert n $ ni (ni (ni set ty) val) sc ni set (PPi p n _ ty sc) = niTacImp (S.insert n $ ni (ni set ty) sc) p ni set (PRewrite _ l r _) = ni (ni set l) r ni set (PTyped l r) = ni (ni set l) r ni set (PPair _ _ _ l r) = ni (ni set l) r ni set (PDPair _ _ _ (PRef _ _ n) t r) = ni (ni set t) r ni set (PDPair _ _ _ l t r) = ni (ni (ni set l) t) r ni set (PAlternative ns a as) = niTms set as ni set (PHidden tm) = ni set tm ni set (PUnifyLog tm) = ni set tm ni set (PDisamb _ tm) = ni set tm ni set (PNoImplicits tm) = ni set tm ni set _ = set niTms set [] = set niTms set (x : xs) = niTms (ni set x) xs niTacImp set (TacImp _ _ scr) = ni set scr niTacImp set _ = set -- Return names which are valid implicits in the given term (type). implicitNamesIn :: [Name] -> IState -> PTerm -> [Name] implicitNamesIn uvars ist tm = nub $ ni [] tm where ni env (PRef _ _ n) | not (n `elem` env) = case lookupTy n (tt_ctxt ist) of [] -> [n] _ -> if n `elem` uvars then [n] else [] ni env (PApp _ f@(PRef _ _ n) as) | n `elem` uvars = ni env f ++ concatMap (ni env) (map getTm as) | otherwise = concatMap (ni env) (map getTm as) ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PCase _ c os) = ni env c ++ -- names in 'os', not counting the names bound in the cases (nub (concatMap (ni env) (map snd os)) \\ nub (concatMap (ni env) (map fst os))) ni env (PIfThenElse _ c t f) = concatMap (ni env) [c, t, f] ni env (PLam fc n _ ty sc) = ni env ty ++ ni (n:env) sc ni env (PPi p n _ ty sc) = ni env ty ++ ni (n:env) sc ni env (PRewrite _ l r _) = ni env l ++ ni env r ni env (PTyped l r) = ni env l ++ ni env r ni env (PPair _ _ _ l r) = ni env l ++ ni env r ni env (PDPair _ _ _ (PRef _ _ n) t r) = ni env t ++ ni (n:env) r ni env (PDPair _ _ _ l t r) = ni env l ++ ni env t ++ ni env r ni env (PAlternative ns a as) = concatMap (ni env) as ni env (PHidden tm) = ni env tm ni env (PUnifyLog tm) = ni env tm ni env (PDisamb _ tm) = ni env tm ni env (PNoImplicits tm) = ni env tm ni env _ = [] -- Return names which are free in the given term. namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name] namesIn uvars ist tm = nub $ ni [] tm where ni env (PRef _ _ n) | not (n `elem` env) = case lookupTy n (tt_ctxt ist) of [] -> [n] _ -> if n `elem` (map fst uvars) then [n] else [] ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PCase _ c os) = ni env c ++ -- names in 'os', not counting the names bound in the cases (nub (concatMap (ni env) (map snd os)) \\ nub (concatMap (ni env) (map fst os))) ni env (PIfThenElse _ c t f) = concatMap (ni env) [c, t, f] ni env (PLam fc n nfc ty sc) = ni env ty ++ ni (n:env) sc ni env (PPi p n _ ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc ni env (PRewrite _ l r _) = ni env l ++ ni env r ni env (PTyped l r) = ni env l ++ ni env r ni env (PPair _ _ _ l r) = ni env l ++ ni env r ni env (PDPair _ _ _ (PRef _ _ n) t r) = ni env t ++ ni (n:env) r ni env (PDPair _ _ _ l t r) = ni env l ++ ni env t ++ ni env r ni env (PAlternative ns a as) = concatMap (ni env) as ni env (PHidden tm) = ni env tm ni env (PUnifyLog tm) = ni env tm ni env (PDisamb _ tm) = ni env tm ni env (PNoImplicits tm) = ni env tm ni env _ = [] niTacImp env (TacImp _ _ scr) = ni env scr niTacImp _ _ = [] -- Return which of the given names are used in the given term. usedNamesIn :: [Name] -> IState -> PTerm -> [Name] usedNamesIn vars ist tm = nub $ ni [] tm where -- TODO THINK added niTacImp, but is it right? ni env (PRef _ _ n) | n `elem` vars && not (n `elem` env) = case lookupDefExact n (tt_ctxt ist) of Nothing -> [n] _ -> [] ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os) ni env (PIfThenElse _ c t f) = concatMap (ni env) [c, t, f] ni env (PLam fc n _ ty sc) = ni env ty ++ ni (n:env) sc ni env (PPi p n _ ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc ni env (PRewrite _ l r _) = ni env l ++ ni env r ni env (PTyped l r) = ni env l ++ ni env r ni env (PPair _ _ _ l r) = ni env l ++ ni env r ni env (PDPair _ _ _ (PRef _ _ n) t r) = ni env t ++ ni (n:env) r ni env (PDPair _ _ _ l t r) = ni env l ++ ni env t ++ ni env r ni env (PAlternative ns a as) = concatMap (ni env) as ni env (PHidden tm) = ni env tm ni env (PUnifyLog tm) = ni env tm ni env (PDisamb _ tm) = ni env tm ni env (PNoImplicits tm) = ni env tm ni env _ = [] niTacImp env (TacImp _ _ scr) = ni env scr niTacImp _ _ = [] -- Return the list of inaccessible (= dotted) positions for a name. getErasureInfo :: IState -> Name -> [Int] getErasureInfo ist n = case lookupCtxtExact n (idris_optimisation ist) of Just (Optimise inacc detagg) -> map fst inacc Nothing -> []
uwap/Idris-dev
src/Idris/AbsSyntaxTree.hs
bsd-3-clause
96,181
0
22
30,973
32,028
16,571
15,457
1,715
94
{-# LANGUAGE BangPatterns, OverloadedStrings #-} module Network.HPACK.Table.Entry ( -- * Type Size , Entry , Header -- re-exporting , HeaderName -- re-exporting , HeaderValue -- re-exporting , Index -- re-exporting -- * Header and Entry , toEntry , fromEntry -- * Getters , entrySize , entryHeader , entryHeaderName , entryHeaderValue -- * For initialization , dummyEntry , maxNumbers ) where import qualified Data.ByteString as BS import Network.HPACK.Types ---------------------------------------------------------------- -- | Size in bytes. type Size = Int -- | Type for table entry. Size includes the 32 bytes magic number. type Entry = (Size,Header) ---------------------------------------------------------------- headerSizeMagicNumber :: Size headerSizeMagicNumber = 32 headerSize :: Header -> Size headerSize (k,v) = BS.length k + BS.length v + headerSizeMagicNumber ---------------------------------------------------------------- -- | From 'Header' to 'Entry'. toEntry :: Header -> Entry toEntry h = (siz,h) where !siz = headerSize h -- | From 'Entry' to 'Header'. fromEntry :: Entry -> Header fromEntry = snd ---------------------------------------------------------------- -- | Getting the size of 'Entry'. entrySize :: Entry -> Size entrySize = fst -- | Getting 'Header'. entryHeader :: Entry -> Header entryHeader (_,h) = h -- | Getting 'HeaderName'. entryHeaderName :: Entry -> HeaderName entryHeaderName (_,(k,_)) = k -- | Getting 'HeaderValue'. entryHeaderValue :: Entry -> HeaderValue entryHeaderValue (_,(_,v)) = v ---------------------------------------------------------------- -- | Dummy 'Entry' to initialize a dynamic table. dummyEntry :: Entry dummyEntry = (0,("dummy","dummy")) -- | How many entries can be stored in a dynamic table? maxNumbers :: Size -> Int maxNumbers siz = siz `div` headerSizeMagicNumber
bergmark/http2
Network/HPACK/Table/Entry.hs
bsd-3-clause
1,946
0
8
356
348
216
132
43
1
{-# LANGUAGE OverloadedStrings #-} module HandleRequestTests where import qualified Data.HashMap.Strict as HashMap import Test.Tasty import Test.Tasty.HUnit import Webcrank import TestServerAPI handleRequestTests :: TestTree handleRequestTests = testGroup "handleRequest" [ getTest , postTest , putTest , deleteTest , notModifiedTest , serviceUnavailableTest ] getTest :: TestTree getTest = testCase "GET" $ let r = resource { contentTypesProvided = return [("plain" // "text", return "webcrank")] } in handleTestReq r req @?= Res ok200 (HashMap.singleton hContentType ["plain/text"]) (Just "webcrank") postTest :: TestTree postTest = testCase "POST" $ let r = resource { contentTypesAccepted = return [("plain" // "text", putResponseHeader hContentType "plain/text" >> writeLBS "webcrank")] , postAction = return . PostCreate $ ["new"] , allowedMethods = return [methodGet, methodHead, methodPost] } rq = req { reqMethod = methodPost , reqHeaders = HashMap.singleton hContentType ["plain/text"] } in handleTestReq r rq @?= Res created201 (HashMap.fromList [(hLocation, ["http://example.com/new"]), (hContentType, ["plain/text"])]) (Just "webcrank") putTest :: TestTree putTest = testCase "PUT" $ let r = resource { contentTypesAccepted = return [("plain" // "text", putResponseHeader hContentType "plain/text" >> writeLBS "webcrank")] , allowedMethods = return [methodGet, methodHead, methodPut] } rq = req { reqMethod = methodPut , reqHeaders = HashMap.singleton hContentType ["plain/text"] } in handleTestReq r rq @?= Res ok200 (HashMap.singleton hContentType ["plain/text"]) (Just "webcrank") deleteTest :: TestTree deleteTest = testCase "DELETE" $ let r = resource { allowedMethods = return [methodGet, methodHead, methodDelete] , deleteResource = return True } rq = req { reqMethod = methodDelete } in handleTestReq r rq @?= Res noContent204 (HashMap.singleton hContentType ["application/octet-stream"]) Nothing notModifiedTest :: TestTree notModifiedTest = testCase "Not modified" $ let r = resource { lastModified = return defaultHTTPDate , generateETag = return $ StrongETag "webcrank" , expires = return defaultHTTPDate } rq = req { reqHeaders = HashMap.singleton hIfModifiedSince [ formatHTTPDate defaultHTTPDate ] } in handleTestReq r rq @?= Res notModified304 (HashMap.fromList [(hETag, ["webcrank"]), (hExpires, [formatHTTPDate defaultHTTPDate])]) Nothing serviceUnavailableTest :: TestTree serviceUnavailableTest = testCase "Service unavailable" $ let r = resource { serviceAvailable = return False } in resStatus (handleTestReq r req) @?= serviceUnavailable503
webcrank/webcrank.hs
test/HandleRequestTests.hs
bsd-3-clause
2,878
0
16
631
773
421
352
-1
-1
{-# LANGUAGE GADTs, KindSignatures #-} module Combinatorics.Symbolic.AllowablConstructions where import Combinatorics.Symbolic.MathExpr import Data.Set hiding (map) data Class a where Nuetral :: Class a Atomic :: Set a -> Class a DisUnion :: Class a -> Class a -> Class a Cart :: Class a -> Class a -> Class a Sequence :: Class a -> Class a PowerSet :: Class a -> Class a Multiset :: Class a -> Class a Cycle :: Class a -> Class a one = Lit 1 sub x y = x :+: (SumInv y) divide x y = x :*: (ProductInv y) choose n k = (Factorial (Lit n)) `sub` ((Factorial (Lit k)) :*: (Factorial (Lit n `sub` Lit k))) toGenFunc :: Class a -> MathExpr toGenFunc Nuetral = one toGenFunc (Atomic x) = Var "z" toGenFunc (DisUnion x y) = (toGenFunc x) `sub` (toGenFunc y) toGenFunc (Cart x y) = (toGenFunc x) :*: (toGenFunc y) toGenFunc (Sequence x) = one `divide` (one `sub` (toGenFunc x)) toGenFunc (PowerSet x) = setize (:+:) x toGenFunc (Multiset x) = setize divide x setize :: (MathExpr -> MathExpr -> MathExpr) -> Class a -> MathExpr setize op x = BigProduct (Lit 0) (Lit $ sizeOf x) ((one `sub` (Var "z")) :^: Var "n") :^: (SumInv (App (toGenFunc x) $ Var "n")) valueChoose n 0 = 1 valueChoose 0 k = 0 valueChoose n k = valueChoose (n-1) (k-1) * n `div` k sizeOf :: Class a -> Int sizeOf (Nuetral) = 1 sizeOf (Atomic x) = size x sizeOf (DisUnion x y) = (sizeOf x) + (sizeOf y) sizeOf (Cart x y) = (sizeOf x) * (sizeOf y) sizeOf (Sequence x) = sum $ map (\k -> (sizeOf x) ^ k) [0..sizeOf x] sizeOf (PowerSet x) = sum $ map (valueChoose (sizeOf x)) [0..(sizeOf x)] sizeOf (Multiset x) = sum $ map (\k -> valueChoose ((sizeOf x) + k - 1) k) [0..(sizeOf x)] evalGF :: MathExpr -> Int -> MathExpr evalGF gf n = undefined distribution :: MathExpr -> (Double -> Double -> Double) distribution = undefined --the next thing is to make a isomorphism between the --so here is how I do it. The binary tree is pointing out one sequence. The sequence with 2 --unique colors, and visa versus. The binary trees formula is actually a sum expression of --the general tree expression. This is what we expect. So The operation of pointing is the --derivative. --or specifically take a binary tree. Divive the number of node options in half. --rotate nineties degrees and readd the root. --45 degs I finally get it. Subtract the root, connect rotate. --it is taken the derivative at the first part. and summing it up for each location. --what if division means derivative in value land. You to remove an object, but it is not --clear where. In otherwords any derivative will do. Division doesn't constrain the location --the derivative is evaluated. Thus since plane trees are always non-empty, zero is always possible. {- If every type can be broken into combinatorial class and a atomic set. Then you break into structure and elements. You make isometries between the classes and the you just need to convert the elements. Reify a type into a combinatorial class you can derive the ismorphism. My new thought is each type has a formula that it carries, at runtime. that is used to perform the conversion using an isometry for instance You can make a isometry between a binary tree and a plane tree with the same elements by I need the function Class -> Class -> Index -> Index where Index is an index into a combinatorial class enumeration I WAS having trouble with understanding what the definite integral of a derivative gives you. It gives you all the changes. -}
jfischoff/symbolic-combinatorics
src/Combinatorics/Symbolic/AllowableConstructions.hs
bsd-3-clause
3,646
0
14
842
948
493
455
45
1
-- | -- Module : Data.MultextEastMsd -- Copyright : (c) 2009 Jan Snajder -- License : BSD-3 (see the LICENSE file) -- -- Maintainer : Jan Snajder <[email protected]> -- Stability : experimental -- Portability : portable -- -- Implementation of the MULTEXT-East morphosyntactic descriptions. -- -- MULTEXT-East encodes values of morphosyntatic attributes in a single string, -- using positional encoding. Each attribute is represented by a single letter -- at a predefined position, while non-applicable attributes are represented by -- hyphens. For example, @Ncmsg@ denotes a common noun (@Nc@) in masculine -- singular genitive (@msg@) case. For details, refer to <http://nl.ijs.si/ME>. -- -- Currently, only MULTEXT-East Version 3 is supported. MULTEXT-East Version 3 -- covers morphosyntactic descriptions for Bulgarian, Croatian, Czech, English, -- Estonian, Hungarian, Lithuanian, Macedonian, Persian, Polish, Resian, -- Romanian, Russian, Serbian, Slovak, Slovene, and Ukrainian. For details, -- refer to <http://nl.ijs.si/ME/V3>. -- -- The library enables the conversion of strings from/to morphosyntactic -- descriptors (MSDs), setting and unsetting of MSD attribute values, and -- wildcard MSD matching. -- -- Usage example: -- -- >>> let Just d1 = fromString "Ncmsg" -- >>> pos d1 -- Noun -- >>> features d1 -- [NType Common,Gender Masculine,Number Singular,Case Genitive] -- >>> let d2 = unset NType d1 -- >>> toString d2 -- "N-msg" -- >>> d1 == d2 -- False -- >>> d1 =~= d2 -- True ------------------------------------------------------------------------------- module Data.MultextEastMsd ( -- * Datatype constructor Msd, msd, PoS (..), -- * Getting and setting values Attribute, get, set, unset, check, features, pos, -- * Wildcard matching (=~=), -- * From/to string conversion toString, fromString, validString, -- * Morphosyntactic features Feature (..), AType (..), Aspect (..), Case (..), Class (..), CoordType (..), CType (..), Definiteness (..), Degree (..), Formation (..), Gender (..), MForm (..), MType (..), NType (..), Number (..), Person (..), SType (..), SubType (..), Tense (..), VForm (..), Voice (..), VType (..)) where import Data.List (find,sort,delete,findIndex,deleteBy,intersectBy,nubBy) import Data.Maybe (catMaybes,isJust) import Control.Monad (liftM) data Msd = Msd PoS [Feature] deriving (Show) instance Eq Msd where Msd p1 fs1 == Msd p2 fs2 = p1==p2 && sort fs1==sort fs2 data PoS = Noun | Verb | Adjective | Adposition | Conjunction | Numeral deriving (Eq,Enum,Show) data Feature = Animate Bool | AType AType | Aspect Aspect | Case Case | Class Class | Clitic Bool | CliticS Bool | CoordType CoordType | Courtesy Bool | CType CType | Definiteness Definiteness | Degree Degree | Formation Formation | Gender Gender | MForm MForm | MType MType | Negative Bool | NType NType | Number Number | OwnedNumber Number | OwnerNumber Number | OwnerPerson Person | Person Person | SType SType | SubType SubType | Tense Tense | VForm VForm | Voice Voice | VType VType deriving (Show,Ord,Eq) data NType = Common | Proper deriving (Eq,Enum,Ord,Show) data Gender = Masculine | Feminine | Neuter deriving (Eq,Enum,Ord,Show) data Number = Singular | Plural | Dual | Count | Collective deriving (Eq,Enum,Ord,Show) data Case = Nominative | Genitive | Dative | Accusative | Vocative | Locative | Instrumental | Direct | Oblique | Partitive | Illative | Inessive | Elative | Allative | Adessive | Ablative | Translative | Terminative | Essive | Abessive | Komitative | Aditive | Temporalis | Causalis | Sublative | Delative | Sociative | Factive | Superessive | Distributive | EssiveFormal | Multiplicative deriving (Eq,Enum,Ord,Show) data Definiteness = No | Yes | ShortArt | FullArt | OneSTwoS deriving (Eq,Enum,Ord,Show) data VType = Main | Auxiliary | Modal | Copula | Base deriving (Eq,Enum,Ord,Show) data VForm = Indicative | Subjunctive | Imperative | Conditional | Infinitive | Participle | Gerund | Supine | Transgressive | Quotative deriving (Eq,Enum,Ord,Show) data Tense = Present | Imperfect | Future | Past | Pluperfect | Aorist deriving (Eq,Enum,Ord,Show) data Person = First | Second | Third deriving (Eq,Enum,Ord,Show) data Voice = Active | Passive deriving (Eq,Enum,Ord,Show) data Aspect = Progressive | Perfective deriving (Eq,Enum,Ord,Show) data AType = Qualificative | Indefinite | Possessive | OrdinalT deriving (Eq,Enum,Ord,Show) data Degree = Positive | Comparative | Superlative | ElativeD | Diminutive deriving (Eq,Enum,Ord,Show) data Formation = Nominal | Simple | Compound deriving (Eq,Enum,Ord,Show) data MType = Cardinal | Ordinal | Fractal | Multiple | Collect | Special deriving (Eq,Enum,Ord,Show) data MForm = Digit | Roman | Letter | Both | MForm_ | Approx deriving (Eq,Enum,Ord,Show) data Class = Definite1 | Definite2 | Definite34 | Definite | Demonstrative | IndefiniteC | Interrogative | Relative deriving (Eq,Enum,Ord,Show) data SType = Preposition | Postposition deriving (Eq,Enum,Ord,Show) data CType = Coordinating | Subordinating | Portmanteau deriving (Eq,Enum,Ord,Show) data CoordType = CTSimple | CTRepetit | CTCorrelat | CTSentence | CTWords | Initial | NonInitial deriving (Eq,Enum,Ord,Show) data SubType = STNegative | STPositive deriving (Eq,Enum,Ord,Show) -- A helper function to identify constructors in a list eq (Animate _) (Animate _) = True eq (AType _) (AType _) = True eq (Aspect _) (Aspect _) = True eq (Case _) (Case _) = True eq (Class _) (Class _) = True eq (Clitic _) (Clitic _) = True eq (CoordType _) (CoordType _) = True eq (Courtesy _) (Courtesy _) = True eq (CType _) (CType _) = True eq (Definiteness _) (Definiteness _) = True eq (Degree _) (Degree _) = True eq (Formation _) (Formation _) = True eq (Gender _) (Gender _) = True eq (MForm _) (MForm _) = True eq (MType _) (MType _) = True eq (Negative _) (Negative _) = True eq (NType _) (NType _) = True eq (Number _) (Number _) = True eq (OwnedNumber _) (OwnedNumber _) = True eq (OwnerNumber _) (OwnerNumber _) = True eq (OwnerPerson _) (OwnerPerson _) = True eq (Person _) (Person _) = True eq (SType _) (SType _) = True eq (SubType _) (SubType _) = True eq (Tense _) (Tense _) = True eq (VForm _) (VForm _) = True eq (Voice _) (Voice _) = True eq (VType _) (VType _) = True eq _ _ = False -- | Constructs a morphosyntactic descriptor (an abstract @Msd@ datatype) of -- a specified part-of-speech and with specified features (attribute-value -- pairs). Duplicated attributes and attributes not applicable to the given -- part-of-speech are ignored. msd :: PoS -> [Feature] -> Msd msd p fs = set fs $ Msd p [] class MsdPattern a where -- | A wildcard-matching operator between two Msd patterns. -- Relation @ d1 =~= d2 @ holds iff @d1@ and @d2@ are of the same -- part-of-speech and the attributes common to @d1@ -- and @d2@ have identical values. The attributes of @d1@ that are not -- set in @d2@ (and conversely) are ignored in the comparison. -- In MULTEXT-East notation, this is tantamount to -- having character code @-@ (hyphen) act as a wildcard. (=~=) :: a -> a -> Bool infix 4 =~= instance MsdPattern Msd where Msd p1 fs1 =~= Msd p2 fs2 = Msd p1 (intersectBy eq fs1 fs2) == Msd p2 (intersectBy eq fs2 fs1) instance MsdPattern a => MsdPattern (Maybe a) where (Just x) =~= (Just y) = x =~= y _ =~= _ = False instance MsdPattern a => MsdPattern [a] where xs =~= ys = and (zipWith (=~=) xs ys) && length xs == length ys type Attribute a = a -> Feature x_ :: (Enum a) => a x_ = toEnum 0 -- | Gets the value of a specified attribute. get :: (Enum a) => Attribute a -> Msd -> Maybe Feature get a (Msd _ fs) = find (`eq` a x_) fs -- | Sets the specified features (attribute-value pairs). Duplicated -- attributes and attributes not applicable to the given part-of-speech -- are ignored. set :: [Feature] -> Msd -> Msd set fs2 (Msd p fs1) = Msd p $ nubBy eq fs3 where fs3 = intersectBy eq fs2 (posFeatures p) ++ fs1 -- | Unsets the value of a specified attribute. unset :: (Enum a) => Attribute a -> Msd -> Msd unset a (Msd p fs) = Msd p $ deleteBy eq (a x_) fs -- | Checks whether the attributes are set to the specified values. check :: [Feature] -> Msd -> Bool check fs2 (Msd _ fs1) = all (\av -> isJust . find (==av) $ fs1) fs2 -- | Returns the features (attribute-value pairs) of a @Msd@. features :: Msd -> [Feature] features (Msd _ fs) = fs -- | Returns a part-of-speech ('PoS' value) of an @Msd@. pos :: Msd -> PoS pos (Msd pos _) = pos posCodes = "NVASCM" decodeWith :: (Enum a) => String -> Char -> Maybe a decodeWith cs c = toEnum `liftM` findIndex (==c) cs encodeWith :: (Enum a) => String -> a -> Char encodeWith cs x = cs !! fromEnum x -- | Converts an @Msd@ datatype into a MULTEXT-East string notation. toString :: Msd -> String toString (Msd p fs) = trim $ c : map (\av -> enc $ get av fs) (posFeatures p) where trim = reverse . dropWhile (=='-') . reverse enc Nothing = '-' enc (Just x) = encode x c = encodeWith posCodes p get av = find (`eq` av) -- | Converts a MULTEXT-East string notation into an @Msd@ datatype. -- Returns @Nothing@ if string is not a valid MULTEXT-East string. fromString :: String -> Maybe Msd fromString (c:cs) = do p <- decodeWith posCodes c let fs = zipWith decode (posFeatures p) cs if (all isJust fs) then Just $ Msd p (catMaybes . catMaybes $ fs) else Nothing -- | Checks whether the string conforms to the MULTEXT-East specification. -- Defined as: -- @ validString = isJust . fromString @ validString :: String -> Bool validString = isJust . fromString posFeatures Noun = [NType x_,Gender x_,Number x_,Case x_,Clitic x_,Definiteness x_, Animate x_,OwnerNumber x_,OwnerPerson x_,OwnedNumber x_] posFeatures Verb = [VType x_,VForm x_,Tense x_,Person x_,Number x_,Gender x_,Voice x_, Negative x_,Definiteness x_,Clitic x_,Case x_,Animate x_,CliticS x_, Aspect x_,Courtesy x_] posFeatures Adjective = [AType x_,Degree x_,Gender x_,Number x_,Case x_,Definiteness x_, Clitic x_,Animate x_,Formation x_,OwnerNumber x_,OwnerPerson x_, OwnedNumber x_] posFeatures Adposition = [SType x_,Formation x_,Case x_,Clitic x_] posFeatures Conjunction = [CType x_,Formation x_,CoordType x_,SubType x_,Clitic x_,Number x_, Person x_] posFeatures Numeral = [MType x_,Gender x_,Number x_,Case x_,MForm x_,Definiteness x_, Clitic x_,Class x_,Animate x_,OwnerNumber x_,OwnerPerson x_, OwnedNumber x_] -- Helper functions to unwrap the values encode (NType v) = enc NType v encode (Gender v) = enc Gender v encode (Number v) = enc Number v encode (Case v) = enc Case v encode (Definiteness v) = enc Definiteness v encode (Clitic v) = enc Clitic v encode (CliticS v) = enc CliticS v encode (VType v) = enc VType v encode (VForm v) = enc VForm v encode (Tense v) = enc Tense v encode (Person v) = enc Person v encode (AType v) = enc AType v encode (Voice v) = enc Voice v encode (Aspect v) = enc Aspect v encode (Degree v) = enc Degree v encode (Formation v) = enc Formation v encode (MType v) = enc MType v encode (MForm v) = enc MForm v encode (Class v) = enc Class v encode (SType v) = enc SType v encode (CType v) = enc CType v encode (CoordType v) = enc CoordType v encode (SubType v) = enc SubType v encode (Animate v) = enc Animate v encode (OwnerNumber v) = enc OwnerNumber v encode (OwnerPerson v) = enc OwnerPerson v encode (OwnedNumber v) = enc OwnedNumber v encode (Negative v) = enc Negative v encode (Courtesy v) = enc Courtesy v decode (NType _) = dec NType decode (Gender _) = dec Gender decode (Number _) = dec Number decode (Case _) = dec Case decode (Definiteness _) = dec Definiteness decode (Clitic _) = dec Clitic decode (CliticS _) = dec CliticS decode (VType _) = dec VType decode (VForm _) = dec VForm decode (Tense _) = dec Tense decode (Person _) = dec Person decode (AType _) = dec AType decode (Voice _) = dec Voice decode (Aspect _) = dec Aspect decode (Degree _) = dec Degree decode (Formation _) = dec Formation decode (MType _) = dec MType decode (MForm _) = dec MForm decode (Class _) = dec Class decode (SType _) = dec SType decode (CType _) = dec CType decode (CoordType _) = dec CoordType decode (SubType _) = dec SubType decode (Animate _) = dec Animate decode (OwnerNumber _) = dec OwnerNumber decode (OwnerPerson _) = dec OwnerPerson decode (OwnedNumber _) = dec OwnedNumber decode (Negative _) = dec Negative decode (Courtesy _) = dec Courtesy enc :: (Enum a) => Attribute a -> a -> Char enc a v = encodeWith (codes $ a x_) v dec :: (Enum a) => Attribute a -> Char -> Maybe (Maybe Feature) dec _ '-' = Just Nothing dec a c = decodeWith (codes $ a x_) c >>= return . Just . a -- MULTEXT-East Version 3 codes codes :: Feature -> String codes (NType x) = "cp" codes (Gender x_) = "mfn" codes (Number x_) = "spdtl" codes (Case x_) = "ngdavliro1x2et3b49w5k7mcshqypuf6" codes (Definiteness x_) = "nysf2" codes (Clitic x_) = "ny" codes (CliticS x_) = "ny" codes (VType x_) = "maoc" codes (VForm x_) = "ismcnpgutq" codes (Tense x_) = "pifsla" codes (Person x_) = "123" codes (AType x_) = "fiso" codes (Voice x_) = "ap" codes (Aspect x_) = "pe" codes (Degree x_) = "pcsed" codes (Formation x_) = "nsc" codes (MType x_) = "cofmls" codes (MForm x_) = "drlbma" codes (Class x_) = "123fdiqr" codes (SType x_) = "pt" codes (CType x_) = "csr" codes (CoordType x_) = "srcpwin" codes (SubType x_) = "zp" codes (Animate x_) = "ny" codes (Courtesy x_) = "ny" codes (Negative x_) = "ny" codes (OwnerNumber x_) = "spdtl" codes (OwnerPerson x_) = "123" codes (OwnedNumber x_) = "spdtl"
jsnajder/multext-east-msd
src/Data/MultextEastMsd.hs
bsd-3-clause
14,654
0
12
3,581
5,015
2,662
2,353
342
2
module TestImport ( module TestImport , module Export ) where import ClassyPrelude as Export import Test.Hspec as Export --runDB :: SqlPersistM a -> YesodExample App a --runDB query = do -- pool <- fmap appConnPool getTestYesod -- liftIO $ runSqlPersistMPool query pool --withApp :: SpecWith App -> Spec --withApp = before $ do -- settings <- loadAppSettings -- ["config/test-settings.yml", "config/settings.yml"] -- [] -- ignoreEnv -- makeFoundation settings
lambdacms/lambdacms
lambdacms-core/test/TestImport.hs
mit
528
0
4
135
37
30
7
5
0
module Lamdu.Editor.Fonts ( makeGetFonts ) where import qualified Control.Lens as Lens import Data.IORef import Data.MRUMemo (memoIO) import GUI.Momentu.Font (Font) import GUI.Momentu.Zoom (Zoom) import qualified GUI.Momentu.Zoom as Zoom import Lamdu.Config.Sampler (Sampler, Sample) import qualified Lamdu.Config.Sampler as Sampler import Lamdu.Config.Theme (Theme(..)) import qualified Lamdu.Config.Theme as Theme import Lamdu.Config.Theme.Fonts (FontSize, Fonts(..)) import qualified Lamdu.Config.Theme.Fonts as Fonts import qualified Lamdu.Font as Font import qualified Lamdu.I18N.Language as Language import System.FilePath ((</>)) import qualified System.FilePath as FilePath import System.Mem (performGC) import Lamdu.Prelude sampleConfigPath :: Lens' Sample FilePath sampleConfigPath = Sampler.sData . Sampler.sConfig . Sampler.primaryPath prependConfigPath :: Sample -> Fonts Theme.FontSel -> Fonts FilePath prependConfigPath sample = Lens.mapped %~ f where dir = FilePath.takeDirectory (sample ^. sampleConfigPath) fonts = sample ^. Sampler.sLanguageData . Language.lFonts f sel = dir </> fonts ^# Theme.fontSel sel assignFontSizes :: Theme -> Fonts FilePath -> Fonts (FontSize, FilePath) assignFontSizes theme fonts = fonts <&> (,) baseTextSize & Fonts.help . _1 .~ helpTextSize where baseTextSize = theme ^. Theme.baseTextSize helpTextSize = theme ^. Theme.help . Theme.helpTextSize curSampleFonts :: Sample -> Fonts (FontSize, FilePath) curSampleFonts sample = sample ^. Sampler.sThemeData . Theme.fonts & prependConfigPath sample & assignFontSizes (sample ^. Sampler.sThemeData) defaultFontPath :: FilePath -> FilePath defaultFontPath configPath = configDir </> "fonts/Purisa.ttf" where configDir = FilePath.takeDirectory configPath makeGetFonts :: Sampler -> Font.LCDSubPixelEnabled -> IO (Zoom -> IO (Fonts Font)) makeGetFonts configSampler subpixel = do timeTillGc <- newIORef gcEvery let maybePerformGC = atomicModifyIORef timeTillGc (\ttl -> if ttl == 0 then (gcEvery, performGC) else (ttl-1, pure ())) & join fmap f . memoIO $ \(path, fonts) -> do -- If we don't force full GC once in a while, these -- fonts linger and are uncollected. They leak not -- only memory but file descriptors, and those run out -- first, crashing lamdu if fonts are reloaded too frequently maybePerformGC Font.new subpixel path fonts where gcEvery :: Int gcEvery = 10 f cachedLoadFonts zoom = do sizeFactor <- Zoom.getZoomFactor zoom sample <- Sampler.getSample configSampler cachedLoadFonts ( defaultFontPath (sample ^. sampleConfigPath) , curSampleFonts sample <&> _1 *~ sizeFactor )
lamdu/lamdu
src/Lamdu/Editor/Fonts.hs
gpl-3.0
3,144
0
17
892
734
408
326
-1
-1
{-# LANGUAGE TypeFamilies, DataKinds, PolyKinds #-} module T6018failclosed12 where -- This should fail because there is no way to determine a, b and k from the RHS type family Gc (a :: k) (b :: k) = r | r -> k where Gc a b = Int
acowley/ghc
testsuite/tests/typecheck/should_fail/T6018failclosed12.hs
bsd-3-clause
235
0
6
54
44
30
14
4
0
{-# LANGUAGE BangPatterns #-} ----------------------------------------------------------------------------- -- -- Fast write-buffered Handles -- -- (c) The University of Glasgow 2005-2006 -- -- This is a simple abstraction over Handles that offers very fast write -- buffering, but without the thread safety that Handles provide. It's used -- to save time in Pretty.printDoc. -- ----------------------------------------------------------------------------- module Eta.Utils.BufWrite ( BufHandle(..), newBufHandle, bPutChar, bPutStr, bPutFS, bPutFZS, bPutLitString, bFlush, ) where import Eta.Utils.FastString import Eta.Utils.FastTypes import Eta.Utils.FastMutInt import Control.Monad ( when ) import Data.ByteString (ByteString) import qualified Data.ByteString.Unsafe as BS import Data.Char ( ord ) import Foreign import Foreign.C.String import System.IO -- ----------------------------------------------------------------------------- data BufHandle = BufHandle {-#UNPACK#-}!(Ptr Word8) {-#UNPACK#-}!FastMutInt Handle newBufHandle :: Handle -> IO BufHandle newBufHandle hdl = do ptr <- mallocBytes buf_size r <- newFastMutInt writeFastMutInt r 0 return (BufHandle ptr r hdl) buf_size :: Int buf_size = 8192 bPutChar :: BufHandle -> Char -> IO () bPutChar b@(BufHandle buf r hdl) !c = do i <- readFastMutInt r if (i >= buf_size) then do hPutBuf hdl buf buf_size writeFastMutInt r 0 bPutChar b c else do pokeElemOff buf i (fromIntegral (ord c) :: Word8) writeFastMutInt r (i+1) bPutStr :: BufHandle -> String -> IO () bPutStr (BufHandle buf r hdl) !str = do i <- readFastMutInt r loop str i where loop _ i | i `seq` False = undefined loop "" i = do writeFastMutInt r i; return () loop (c:cs) i | i >= buf_size = do hPutBuf hdl buf buf_size loop (c:cs) 0 | otherwise = do pokeElemOff buf i (fromIntegral (ord c)) loop cs (i+1) bPutFS :: BufHandle -> FastString -> IO () bPutFS b fs = bPutBS b $ fastStringToByteString fs bPutFZS :: BufHandle -> FastZString -> IO () bPutFZS b fs = bPutBS b $ fastZStringToByteString fs bPutBS :: BufHandle -> ByteString -> IO () bPutBS b bs = BS.unsafeUseAsCStringLen bs $ bPutCStringLen b bPutCStringLen :: BufHandle -> CStringLen -> IO () bPutCStringLen b@(BufHandle buf r hdl) cstr@(ptr, len) = do i <- readFastMutInt r if (i + len) >= buf_size then do hPutBuf hdl buf i writeFastMutInt r 0 if (len >= buf_size) then hPutBuf hdl ptr len else bPutCStringLen b cstr else do copyBytes (buf `plusPtr` i) ptr len writeFastMutInt r (i + len) bPutLitString :: BufHandle -> LitString -> FastInt -> IO () bPutLitString b@(BufHandle buf r hdl) a len_ = a `seq` do let len = iBox len_ i <- readFastMutInt r if (i+len) >= buf_size then do hPutBuf hdl buf i writeFastMutInt r 0 if (len >= buf_size) then hPutBuf hdl a len else bPutLitString b a len_ else do copyBytes (buf `plusPtr` i) a len writeFastMutInt r (i+len) bFlush :: BufHandle -> IO () bFlush (BufHandle buf r hdl) = do i <- readFastMutInt r when (i > 0) $ hPutBuf hdl buf i free buf return ()
rahulmutt/ghcvm
compiler/Eta/Utils/BufWrite.hs
bsd-3-clause
3,567
0
14
1,057
1,099
551
548
90
3
{-# LANGUAGE Haskell2010 #-} {-# LINE 1 "attoparsec-iso8601/Data/Attoparsec/Time/Internal.hs" #-} {-# LANGUAGE CPP #-} -- | -- Module: Data.Aeson.Internal.Time -- Copyright: (c) 2015-2016 Bryan O'Sullivan -- License: BSD3 -- Maintainer: Bryan O'Sullivan <[email protected]> -- Stability: experimental -- Portability: portable module Data.Attoparsec.Time.Internal ( TimeOfDay64(..) , fromPico , toPico , diffTimeOfDay64 , toTimeOfDay64 ) where import Prelude () import Prelude.Compat import Data.Int (Int64) import Data.Time import Unsafe.Coerce (unsafeCoerce) import Data.Fixed (Pico, Fixed(MkFixed)) toPico :: Integer -> Pico toPico = MkFixed fromPico :: Pico -> Integer fromPico (MkFixed i) = i -- | Like TimeOfDay, but using a fixed-width integer for seconds. data TimeOfDay64 = TOD {-# UNPACK #-} !Int {-# UNPACK #-} !Int {-# UNPACK #-} !Int64 diffTimeOfDay64 :: DiffTime -> TimeOfDay64 diffTimeOfDay64 t = TOD (fromIntegral h) (fromIntegral m) s where (h,mp) = fromIntegral pico `quotRem` 3600000000000000 (m,s) = mp `quotRem` 60000000000000 pico = unsafeCoerce t :: Integer toTimeOfDay64 :: TimeOfDay -> TimeOfDay64 toTimeOfDay64 (TimeOfDay h m s) = TOD h m (fromIntegral (fromPico s))
phischu/fragnix
tests/packages/scotty/Data.Attoparsec.Time.Internal.hs
bsd-3-clause
1,413
0
9
383
283
165
118
30
1
{-# LANGUAGE CPP, ForeignFunctionInterface #-} module Distribution.Client.Compat.Time (EpochTime, getModTime, getFileAge, getCurTime) where import Data.Int (Int64) import System.Directory (getModificationTime) #if MIN_VERSION_directory(1,2,0) import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds, posixDayLength) import Data.Time (getCurrentTime, diffUTCTime) #else import System.Time (ClockTime(..), getClockTime ,diffClockTimes, normalizeTimeDiff, tdDay) #endif #if defined mingw32_HOST_OS import Data.Bits ((.|.), bitSize, unsafeShiftL) import Data.Int (Int32) import Data.Word (Word64) import Foreign (allocaBytes, peekByteOff) import System.IO.Error (mkIOError, doesNotExistErrorType) import System.Win32.Types (BOOL, DWORD, LPCTSTR, LPVOID, withTString) foreign import stdcall "windows.h GetFileAttributesExW" c_getFileAttributesEx :: LPCTSTR -> Int32 -> LPVOID -> IO BOOL getFileAttributesEx :: String -> LPVOID -> IO BOOL getFileAttributesEx path lpFileInformation = withTString path $ \c_path -> c_getFileAttributesEx c_path getFileExInfoStandard lpFileInformation getFileExInfoStandard :: Int32 getFileExInfoStandard = 0 size_WIN32_FILE_ATTRIBUTE_DATA :: Int size_WIN32_FILE_ATTRIBUTE_DATA = 36 index_WIN32_FILE_ATTRIBUTE_DATA_ftLastWriteTime_dwLowDateTime :: Int index_WIN32_FILE_ATTRIBUTE_DATA_ftLastWriteTime_dwLowDateTime = 20 index_WIN32_FILE_ATTRIBUTE_DATA_ftLastWriteTime_dwHighDateTime :: Int index_WIN32_FILE_ATTRIBUTE_DATA_ftLastWriteTime_dwHighDateTime = 24 #else #if MIN_VERSION_base(4,5,0) import Foreign.C.Types (CTime(..)) #else import Foreign.C.Types (CTime) #endif import System.Posix.Files (getFileStatus, modificationTime) #endif -- | The number of seconds since the UNIX epoch. type EpochTime = Int64 -- | Return modification time of given file. Works around the low clock -- resolution problem that 'getModificationTime' has on GHC < 7.8. -- -- This is a modified version of the code originally written for OpenShake by -- Neil Mitchell. See module Development.Shake.FileTime. getModTime :: FilePath -> IO EpochTime #if defined mingw32_HOST_OS -- Directly against the Win32 API. getModTime path = allocaBytes size_WIN32_FILE_ATTRIBUTE_DATA $ \info -> do res <- getFileAttributesEx path info if not res then do let err = mkIOError doesNotExistErrorType "Distribution.Client.Compat.Time.getModTime" Nothing (Just path) ioError err else do dwLow <- peekByteOff info index_WIN32_FILE_ATTRIBUTE_DATA_ftLastWriteTime_dwLowDateTime dwHigh <- peekByteOff info index_WIN32_FILE_ATTRIBUTE_DATA_ftLastWriteTime_dwHighDateTime return $! windowsTimeToPOSIXSeconds dwLow dwHigh where windowsTimeToPOSIXSeconds :: DWORD -> DWORD -> EpochTime windowsTimeToPOSIXSeconds dwLow dwHigh = let wINDOWS_TICK = 10000000 sEC_TO_UNIX_EPOCH = 11644473600 qwTime = (fromIntegral dwHigh `unsafeShiftL` bitSize dwHigh) .|. (fromIntegral dwLow) res = ((qwTime :: Word64) `div` wINDOWS_TICK) - sEC_TO_UNIX_EPOCH -- TODO: What if the result is not representable as POSIX seconds? -- Probably fine to return garbage. in fromIntegral res #else -- Directly against the unix library. getModTime path = do -- CTime is Int32 in base 4.5, Int64 in base >= 4.6, and an abstract type in -- base < 4.5. t <- fmap modificationTime $ getFileStatus path #if MIN_VERSION_base(4,5,0) let CTime i = t return (fromIntegral i) #else return (read . show $ t) #endif #endif -- | Return age of given file in days. getFileAge :: FilePath -> IO Int getFileAge file = do t0 <- getModificationTime file #if MIN_VERSION_directory(1,2,0) t1 <- getCurrentTime let days = truncate $ (t1 `diffUTCTime` t0) / posixDayLength #else t1 <- getClockTime let days = (tdDay . normalizeTimeDiff) (t1 `diffClockTimes` t0) #endif return days getCurTime :: IO EpochTime getCurTime = do #if MIN_VERSION_directory(1,2,0) (truncate . utcTimeToPOSIXSeconds) `fmap` getCurrentTime #else (TOD s _) <- getClockTime return $! fromIntegral s #endif
jwiegley/ghc-release
libraries/Cabal/cabal-install/Distribution/Client/Compat/Time.hs
gpl-3.0
4,339
0
17
902
636
359
277
24
1
module FRP.Sodium.IO where import FRP.Sodium.Context import FRP.Sodium.Internal import Control.Concurrent (forkIO) -- | Execute the specified IO operation asynchronously on a separate thread, and -- signal the output event in a new transaction upon its completion. -- -- Caveat: Where 'switch' or 'switchE' is used, when some reactive logic has been -- switched away, we rely on garbage collection to actually disconnect this logic -- from any input it may be listening to. With normal Sodium code, everything is -- pure, so before garbage collection happens, the worst we will get is some wasted -- CPU cycles. If you are using 'executeAsyncIO'/'executeSyncIO' inside a 'switch' -- or 'switchE', however, it is possible that logic that has been switched away -- hasn't been garbage collected yet. This logic /could/ still run, and if it has -- observable effects, you could see it running after it is supposed to have been -- switched out. One way to avoid this is to pipe the source event for IO out of the -- switch, run the 'executeAsyncIO'/'executeSyncIO' outside the switch, and pipe its -- output back into the switch contents. executeAsyncIO :: Event Plain (IO a) -> Event Plain a executeAsyncIO ev = Event gl cacheRef (dep ev) where cacheRef = unsafeNewIORef Nothing ev gl = do (l, push, nodeRef) <- ioReactive newEventImpl unlistener <- later $ linkedListen ev (Just nodeRef) False $ \action -> do ioReactive $ do _ <- forkIO $ sync . push =<< action return () addCleanup_Listen unlistener l -- | Execute the specified IO operation synchronously and fire the output event -- in the same transaction. -- -- Caveat: See 'executeAsyncIO'. executeSyncIO :: Event Plain (IO a) -> Event Plain a executeSyncIO ev = Event gl cacheRef (dep ev) where cacheRef = unsafeNewIORef Nothing ev gl = do (l, push, nodeRef) <- ioReactive newEventImpl unlistener <- later $ linkedListen ev (Just nodeRef) False $ \action -> do push =<< ioReactive action addCleanup_Listen unlistener l
kevintvh/sodium
haskell/src/FRP/Sodium/IO.hs
bsd-3-clause
2,105
0
20
454
337
176
161
22
1
module Handler.Nomnichi ( getNomnichiR -- ノムニチトップ , getCreateArticleR -- 記事投稿ページの表示 , postCreateArticleR -- 記事の投稿 , getArticleR -- 記事の表示 , postArticleR -- 記事の編集 , getEditArticleR -- 記事の編集画面の表示 , postDeleteArticleR -- 記事の削除 , postCommentR -- コメントの投稿 ) where import Import as I import Data.List as I (isPrefixOf) import Data.Text as T (append, pack, unpack) import Data.Time import qualified Data.Time.Format() import Data.Maybe() import System.Locale (defaultTimeLocale) import System.IO.Unsafe (unsafePerformIO) import Yesod.Auth import Text.Blaze.Html (preEscapedToHtml) import Text.Blaze.Html.Renderer.String (renderHtml) import Yesod.Form.Nic() -- 記事作成,閲覧,更新 -- ノムニチトップ getNomnichiR :: Handler Html getNomnichiR = do creds <- maybeAuthId articles <- case creds of Just _ -> runDB $ selectList [] [Desc ArticlePublishedOn] Nothing -> runDB $ selectList [ArticleApproved ==. True] [Desc ArticlePublishedOn] users <- sequence $ fmap (\x -> articleAuthorName x) articles paramPage <- lookupGetParam "page" let zippedArticles = I.zip articles users articlesOnPage = takeArticlesOnPage calcPageNumber zippedArticles calcPageNumber = case paramPage of Just page -> if ((convTextToInt page) < minPageNumber) || ((convTextToInt page) > calcMaxPageNumber) then minPageNumber else convTextToInt page Nothing -> 1 minPageNumber = 1 calcMaxPageNumber = (+1) $ div (I.length articles) perPage linkToOtherPageNumber pageNumber = [hamlet| <table class="page-number"> <td> <a href=@{HomeR}/nomnichi?page=1><<</a> <td> <a href=@{HomeR}/nomnichi?page=#{show (pageNumber - 1)}><</a> $forall displayPageNumber <- displayPageNumbers pageNumber calcMaxPageNumber $if pageNumber == displayPageNumber <td> <font size="4" color="maroon">#{show displayPageNumber}</font> $else <td> <a href=@{HomeR}/nomnichi?page=#{show displayPageNumber}>#{show displayPageNumber}</a> <td> <a href=@{HomeR}/nomnichi?page=#{show (pageNumber + 1)}>></a> <td> <a href=@{HomeR}/nomnichi?page=#{show calcMaxPageNumber}>>></a> |] displayPageNumbers pageNumber maxPageNumber | pageNumber > 4 = if maxPageNumber > (pageNumber + 3) then I.take 9 [(pageNumber - 4)..] else [(pageNumber - 4)..maxPageNumber] | otherwise = if maxPageNumber > 9 then I.take 9 [1..] else [1..maxPageNumber] case articles of [] -> defaultLayout [whamlet| <div class="home"> <h1 class="home"> Articles <p> There are no articles in the blog. $maybe _ <- creds <a href=@{HomeR}/nomnichi/create> Create Article <br> <a href=@{HomeR}/auth/logout> Logout $nothing |] _ -> defaultLayout $ do $(widgetFile "articles") where takeArticlesOnPage pageNumber zippedArticles = I.drop (calcNumOfDroppingArticles pageNumber) $ I.take (calcNumOfArticles pageNumber) zippedArticles calcNumOfArticles pageNumber = perPage * pageNumber calcNumOfDroppingArticles pageNumber = perPage * (pageNumber - 1) lockedImg article = case articleApproved article of True -> [hamlet||] _ -> [hamlet|<img src="/lab/nom/static/img/lock.png" width="20px" height="20px">|] displayLinksforLoginedMember creds = case creds of (Just _) -> [hamlet| <a href=@{HomeR}/nomnichi/create> Create Article <br> <a href=@{ChangePassR}> Change Password <br> <a href=@{HomeR}/auth/logout> Logout |] _ -> [hamlet||] articleAuthorName :: Entity Article -> Handler (Maybe User) articleAuthorName (Entity _ article) = do runDB $ get (articleUser article) displayAuthorName :: Maybe User -> Text displayAuthorName (Just user) = userIdent user displayAuthorName Nothing = "Unknown user" convTextToInt :: Text -> Int convTextToInt text = read $ T.unpack text :: Int getCreateArticleR :: Handler Html getCreateArticleR = do userId <- requireAuthId user <- runDB $ get404 userId let format = "%Y%m%d-%H%M%S" utcToNomnichiTime = utcToLocalTime $ unsafePerformIO getCurrentTimeZone permaLinkTime = T.pack $ formatTime defaultTimeLocale format $ utcToNomnichiTime $ unsafePerformIO getCurrentTime permaLink = (userIdent user) `T.append` ("-" :: Text) `T.append` permaLinkTime (articleWidget, enctype) <- generateFormPost $ entryForm permaLink defaultLayout $ do $(widgetFile "createArticleForm") -- 記事作成 postCreateArticleR :: Handler Html postCreateArticleR = do ((res, articleWidget), enctype) <- runFormPost $ entryForm ("" :: Text) case res of FormSuccess article -> do let article' = Article{ articleUser = articleUser article , articleTitle = articleTitle article , articlePermaLink = articlePermaLink article , articleContent = articleContent article , articleCreatedOn = articleCreatedOn article , articleUpdatedOn = articleUpdatedOn article , articlePublishedOn = (jstToUTC $ articlePublishedOn article) , articleApproved = articleApproved article , articleCount = articleCount article , articlePromoteHeadline = articlePromoteHeadline article } articleId <- runDB $ insert article' setMessage $ toHtml (articleTitle article) <> " created." redirect $ ArticleR articleId _ -> defaultLayout $ do setTitle "Please correct your entry form." $(widgetFile "articleAddError") -- 記事表示 getArticleR :: ArticleId -> Handler Html getArticleR articleId = do creds <- maybeAuthId article <- runDB $ get404 articleId user <- runDB $ get (articleUser article) comments <- runDB $ selectList [CommentArticleId ==. articleId] [Asc CommentId] users <- sequence $ fmap (\x -> commentAuthorName x) comments let zippedComments = I.zip comments users displayComments commentsWithUsers = [hamlet| <div id=comments> $if I.null comments <p> There are no comments in this article. <hr> $else $forall (Entity _ comment, user) <- commentsWithUsers <div id=comment> #{displayAuthorName user} :<br> #{commentBody comment} <div class=published_on> #{formatToCommentTime comment} <hr> |] runDB $ do update articleId [ ArticleCount =. ((articleCount article) + 1) ] case creds of Just _ -> do (commentWidget, enctype) <- generateFormPost $ commentForm articleId defaultLayout $ do setTitle $ toHtml $ articleTitle article $(widgetFile "authedArticle") Nothing -> case articleApproved article of True -> defaultLayout $ do setTitle $ toHtml $ articleTitle article $(widgetFile "article") False -> defaultLayout $ do redirect $ NomnichiR commentAuthorName :: Entity Comment -> Handler (Maybe User) commentAuthorName (Entity _ comment) = do runDB $ get (commentUser comment) -- 記事更新 postArticleR :: ArticleId -> Handler Html postArticleR articleId = do beforeArticle <- runDB $ get404 articleId ((res, articleWidget), enctype) <- runFormPost (editForm (Just beforeArticle)) case res of FormSuccess article -> do runDB $ do update articleId [ ArticleUser =. articleUser article , ArticleTitle =. articleTitle article , ArticlePermaLink =. articlePermaLink article , ArticleContent =. articleContent article , ArticleUpdatedOn =. articleUpdatedOn article , ArticlePublishedOn =. jstToUTC (articlePublishedOn article) , ArticleApproved =. articleApproved article , ArticlePromoteHeadline =. articlePromoteHeadline article ] setMessage $ toHtml $ (articleTitle article) <> " is updated." redirect $ ArticleR articleId _ -> defaultLayout $ do setTitle "Please correct your entry form." $(widgetFile "editArticleForm") -- 編集画面 getEditArticleR :: ArticleId -> Handler Html getEditArticleR articleId = do article <- runDB $ get404 articleId (articleWidget, enctype) <- generateFormPost $ editForm (Just article) defaultLayout $ do $(widgetFile "editArticleForm") -- 記事削除 postDeleteArticleR :: ArticleId -> Handler Html postDeleteArticleR articleId = do runDB $ do delete articleId deleteWhere [ CommentArticleId ==. articleId ] setMessage "successfully deleted." redirect $ NomnichiR -- コメント -- コメント送信 postCommentR :: ArticleId -> Handler Html postCommentR articleId = do ((res, _), _) <- runFormPost $ commentForm articleId case res of FormSuccess comment -> do _ <- runDB $ insert comment setMessage "your comment was successfully posted." redirect $ ArticleR articleId _ -> do setMessage "please fill up your comment form." redirect $ ArticleR articleId -- 記事表示時の公開時刻の整形 formatToNomnichiTime :: Article -> String formatToNomnichiTime article = formatTime defaultTimeLocale format $ utcToNomnichiTime $ articlePublishedOn article where format = "%Y/%m/%d (%a) %H:%M" utcToNomnichiTime = utcToLocalTime $ unsafePerformIO getCurrentTimeZone -- コメント投稿時刻の整形 formatToCommentTime :: Comment -> String formatToCommentTime comment = formatTime defaultTimeLocale format $ utcToNomnichiTime $ commentCreatedAt comment where format = "%Y/%m/%d (%a) %H:%M" utcToNomnichiTime = utcToLocalTime $ unsafePerformIO getCurrentTimeZone utcToJST :: UTCTime -> UTCTime utcToJST utcTime = addUTCTime (60*60*9) utcTime jstToUTC :: UTCTime -> UTCTime jstToUTC utcTime = addUTCTime (60*60*(-9)) utcTime -- フォーム entryForm :: Text -> Form Article entryForm permaLink = renderDivs $ Article <$> lift requireAuthId <*> areq textField "Title" Nothing <*> areq textField "PermaLink" (Just permaLink) <*> areq htmlField "Content" Nothing <*> lift (liftIO getCurrentTime) -- CreatedOn <*> lift (liftIO getCurrentTime) -- UpdatedOn <*> areq utcTimeField "PublishedOn" (Just $ utcToJST (unsafePerformIO getCurrentTime)) <*> areq boolField "Approved" (Just False) <*> pure 0 -- Count <*> areq boolField "PromoteHeadline" (Just False) editForm :: Maybe Article -> Form Article editForm article = renderDivs $ Article <$> pure (nonMaybeUserId (articleUser <$> article)) <*> areq textField "Title" (articleTitle <$> article) <*> pure (nonMaybeText (articlePermaLink <$> article)) <*> areq htmlField "Content" (articleContent <$> article) <*> pure (nonMaybeUTCTime (articleCreatedOn <$> article)) <*> lift (liftIO getCurrentTime) -- UpdatedOn <*> areq utcTimeField "PublishedOn" (utcToJST <$> (articlePublishedOn <$> article)) <*> areq boolField "Approved" (articleApproved <$> article) <*> pure (nonMaybeInt (articleCount <$> article)) <*> areq boolField "PromoteHeadline" (articlePromoteHeadline <$> article) nonMaybeUserId :: Maybe UserId -> UserId nonMaybeUserId (Just uid) = uid nonMaybeUserId Nothing = (read "Key {unKey = PersistInt64 0}") :: UserId nonMaybeInt :: Num num => Maybe num -> num nonMaybeInt (Just num) = num nonMaybeInt Nothing = 0 nonMaybeText :: Maybe Text -> Text nonMaybeText (Just text) = text nonMaybeText Nothing = "" :: Text nonMaybeUTCTime :: Maybe UTCTime -> UTCTime nonMaybeUTCTime (Just utctime) = utctime nonMaybeUTCTime Nothing = (read "1970-01-01 00:00:00.0 UTC") :: UTCTime commentForm :: ArticleId -> Form Comment commentForm articleId = renderDivs $ Comment <$> lift requireAuthId <*> areq textareaField "Comment" Nothing <*> lift (liftIO getCurrentTime) <*> lift (liftIO getCurrentTime) <*> pure articleId takeHeadLine :: Html -> Html takeHeadLine content = preEscapedToHtml $ prettyHeadLine $ renderHtml content prettyHeadLine :: String -> String prettyHeadLine article = gsub "_br_" "<br>" $ stripTags $ gsub "<br>" "_br_" $ foldArticle article stripTags :: String -> String stripTags str = stripTags' False str stripTags' :: Bool -> String -> String stripTags' bool (x:xs) | xs == [] = if x == '>' then [] else [x] | bool == True = if x == '>' then stripTags' False xs else stripTags' True xs | bool == False = if x == '<' then stripTags' True xs else x : (stripTags' False xs) | otherwise = [] -- maybe don't occur gsub :: Eq a => [a] -> [a] -> [a] -> [a] gsub _ _ [] = [] gsub x y str@(s:ss) | I.isPrefixOf x str = y ++ gsub x y (I.drop (I.length x) str) | otherwise = s:gsub x y ss defaultNumOfLines :: Int defaultNumOfLines = 3 perPage :: Int perPage = 10 foldArticle :: String -> String foldArticle content = case foldAtFolding content of Just value -> value Nothing -> I.unlines $ I.take defaultNumOfLines $ I.lines content foldAtFolding :: String -> Maybe String foldAtFolding content = if (I.length splitContent) > 1 then Just $ I.head splitContent else Nothing where splitContent = split "<!-- folding -->" content -- We want to import Data.List.Utils (split), but... split :: Eq a => [a] -> [a] -> [[a]] split _ [] = [] split delim str = let (firstline, remainder) = breakList (startswith delim) str in firstline : case remainder of [] -> [] x -> if x == delim then [] : [] else split delim (drop (length delim) x) startswith :: Eq a => [a] -> [a] -> Bool startswith = isPrefixOf breakList :: ([a] -> Bool) -> [a] -> ([a], [a]) breakList func = spanList (not . func) spanList :: ([a] -> Bool) -> [a] -> ([a], [a]) spanList _ [] = ([],[]) spanList func list@(x:xs) = if func list then (x:ys,zs) else ([],list) where (ys,zs) = spanList func xs utcTimeField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m UTCTime utcTimeField = Field { fieldParse = parseHelper parseTime' , fieldView = \theId name attrs val isReq -> toWidget [hamlet| $newline never <input id="#{theId}" name="#{name}" type="datetime" *{attrs} :isReq:required="" value="#{showVal val}"> |] , fieldEnctype = UrlEncoded } where showVal = either id (pack . formatTime defaultTimeLocale "%F %T") parseTime' :: Text -> Either FormMessage UTCTime parseTime' theText = maybe (Left MsgInvalidTimeFormat) (\x -> Right x) (Data.Time.parseTime defaultTimeLocale "%F %T" $ unpack theText)
SuetakeY/nomnichi_yesod
Handler/Nomnichi.hs
bsd-2-clause
16,266
0
20
4,768
3,928
1,999
1,929
-1
-1
module DeleteDef.Dd3 where add5 :: (Num a) => a -> a add5 x = x+5 add5ToAll :: (Num a) => [a] -> [a] add5ToAll lst = map add5 lst
RefactoringTools/HaRe
test/testdata/DeleteDef/Dd3.hs
bsd-3-clause
132
0
7
31
73
40
33
5
1
module Lang where import qualified Gap import Types listLanguages :: Options -> IO String listLanguages opt = return $ convert opt Gap.supportedExtensions
syohex/ghc-mod
Lang.hs
bsd-3-clause
157
0
7
24
42
23
19
5
1
module UTF8Util where import System.IO.Error(isUserError,ioeGetErrorString) import UTF8 utf8 = encodeUTF8 -- . arrows {- -- Convert \ and -> into lambda and arrow arrows ('-':'>':s) = '\x2192':arrows s arrows ('\\':' ':s) = '\x03bb':' ':arrows s arrows (c:cs) = c:arrows cs arrows [] = [] -} -- Smileys happy = ['\x263a'] sad = ['\x2639'] -- Note: GHC <=5.02.2 silently truncates Unicode characters in string literals -- Encode error output utf8err e = if isUserError e then fail (utf8 (ioeGetErrorString e++"\n"++sad)) else ioError e
kmate/HaRe
old/tools/base/lib/UTF8Util.hs
bsd-3-clause
548
0
12
95
92
54
38
10
2