code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
module Glucose.Lexer.Location where import Data.Char import Glucose.Lexer.Char data Location = Location { codePoint, line, column :: Int } deriving (Eq, Ord) instance Show Location where show (Location cp line col) = show line ++ ":" ++ show col ++ "@" ++ show cp instance Read Location where readsPrec d s0 = [ (Location cp line col, s5) | (line, s1) <- readsPrec (d+1) s0 , (":", s2) <- lex s1 , (col, s3) <- readsPrec (d+1) s2 , ("@", s4) <- lex s3 , (cp, s5) <- readsPrec (d+1) s4] beginning :: Location beginning = Location 0 1 1 updateLocation :: Char -> Location -> Location updateLocation c (Location char line _) | isNewline c = Location (char+1) (line+1) 1 updateLocation c (Location char line col) | isControl c = Location (char+1) line col updateLocation _ (Location char line col) = Location (char+1) line (col+1) codePointsBetween :: Location -> Location -> Int codePointsBetween (Location start _ _) (Location end _ _) = end - start advance :: Location -> Int -> Location advance (Location cp line col) n = Location (cp + n) line (col + n) rewind :: Location -> Location rewind (Location _ _ 1) = error "Can't rewind a Location past a newline!" rewind (Location cp line col) = Location (cp-1) line (col-1)
sardonicpresence/glucose
src/Glucose/Lexer/Location.hs
Haskell
mit
1,364
module PayPal.Identity ( createIdentity , getIdentity ) where createIdentity = undefined getIdentity = undefined
AndrewRademacher/hs-paypal-rest
src/PayPal/Identity.hs
Haskell
mit
127
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE RecordWildCards #-} module Widgets.Tabs.Reviews ( panelReviews ) where import Control.Monad (join) import Commons import qualified Data.Text as T import Data.List (sortOn) import Data.Time.Format import QuaTypes.Review import Reflex.Dom import Widgets.Commons import Widgets.Generation panelReviews :: Reflex t => Dynamic t (Either JSError ReviewSettings) -> QuaWidget t x () panelReviews reviewSettingsD = do void $ dyn $ renderPanelReviews <$> reviewSettingsD renderPanelReviews :: Reflex t => Either JSError ReviewSettings -> QuaWidget t x () renderPanelReviews (Left _) = blank renderPanelReviews (Right reviewSettings) = do expertRespE <- renderWriteExpertReview reviewSettings respE <- renderWriteReview reviewSettings let revs = reverse . sortOn reviewTimestamp $ reviews reviewSettings reviewsE <- accum (flip ($)) revs $ leftmost [accumRevs <$> respE, onlyOneExpRev <$> expertRespE] let renderRevs = mapM_ $ renderReview $ criterions reviewSettings void $ widgetHold (renderRevs revs) (renderRevs <$> reviewsE) where accumRevs (Right newRev) revs = newRev:revs accumRevs (Left _) revs = revs onlyOneExpRev :: Either JSError Review -> [Review] -> [Review] onlyOneExpRev (Right newRev) revs = newRev : (filter (not . isMyExpertReview) revs) onlyOneExpRev (Left _) revs = revs -- draws the write-review-text-entry component if ReviewSettings contains `Just reviewsUrl`. -- Returns event of posted review, or error on unsuccessful post. renderWriteReview :: Reflex t => ReviewSettings -> QuaWidget t x (Event t (Either JSError Review)) renderWriteReview (ReviewSettings crits _ (Just revsUrl) _) = elAttr "div" ( "class" =: "card" <> "style" =: "padding: 0px; margin: 10px 0px 10px 0px" ) $ elClass "div" (T.unwords ["card-main", spaces2px, writeReviewClass]) $ mdo textD <- elClass "div" (T.unwords ["card-inner", spaces2px]) $ elClass "div" "form-group form-group-label" $ do tD <- renderTextArea resetTextE "Write a review" void $ dyn $ renderTxt <$> thumbD <*> critD return tD (critD, thumbD, clickE) <- elClass "div" (T.unwords ["card-action", spaces2px]) $ do cD <- renderCriterions crits tD <- renderThumbs cE <- buttonFlatDyn (hideState <$> critD <*> thumbD) "Send" mempty return (cD, tD, cE) let postDataOnClickE = (\th te c -> ReviewPost (criterionId c) th te) <$> current thumbD <*> current textD <@> fmapMaybe id (current critD <@ clickE) responseE <- httpPost $ (,) revsUrl <$> postDataOnClickE let reset (Right _) = Just "" reset _ = Nothing let resetTextE = fmapMaybe reset responseE renderError responseE return responseE where WidgetCSSClasses {..} = widgetCSS renderTxt _ Nothing = blank renderTxt None _ = blank renderTxt thumb (Just crit) = text $ toTxt thumb <> (textFromJSString $ criterionName crit) <> " " where toTxt ThumbUp = "Upvote " toTxt ThumbDown = "Downvote " toTxt None = "" renderWriteReview _ = return never renderReview :: Reflex t => [Criterion] -> Review -> QuaWidget t x () renderReview crits r = elClass "div" (T.unwords ["card", cardSpaces]) $ do case reviewRating r of ExpertRating _ -> pure () UserRating critId thumb -> elAttr "aside" ( "class" =: "card-side pull-left" <> "style" =: "background-color: #ffffff; width: 24px; margin: 2px; padding: 0px" ) $ do elClass "span" (T.unwords ["icon", icon24px, "text-brand-accent"]) $ text $ showThumb thumb renderCrit critId elClass "div" (T.unwords ["card-main", spaces0px]) $ elClass "div" (T.unwords ["card-inner", spaces2px]) $ do elClass "p" (T.unwords ["text-brand-accent", smallP]) $ do text $ T.pack $ ' ' : formatTime defaultTimeLocale "%F, %R - " (reviewTimestamp r) text $ textFromJSString $ reviewUserName r case reviewRating r of ExpertRating grade -> renderStars grade UserRating _ _ -> pure () elClass "p" smallP $ text $ textFromJSString $ reviewComment r where WidgetCSSClasses {..} = widgetCSS renderCrit critId = void $ for [ c | c <- crits, critId == criterionId c] $ \c -> do (spanEl, ()) <- elAttr' "span" ("style" =: "position: relative; top: 5px;") blank setInnerHTML spanEl $ criterionIcon c renderStars grade = let star t = elClass "span" "icon icon-lg" $ text t in sequence_ $ (Prelude.replicate grade $ star "star") ++ Prelude.replicate (5 - grade) (star "star_border") -- draws the write-expert-review-text-entry component -- if ReviewSettings contains `Just expertReviewsUrl`. -- Returns event of posted review, or error on unsuccessful post. renderWriteExpertReview :: Reflex t => ReviewSettings -> QuaWidget t x (Event t (Either JSError Review)) renderWriteExpertReview (ReviewSettings _ revs _ (Just revsUrl)) = elAttr "div" ( "class" =: "card" <> "style" =: "padding: 0px; margin: 10px 0px 10px 0px" ) $ elClass "div" (T.unwords ["card-main", spaces2px, writeReviewClass]) $ mdo textD <- elClass "div" (T.unwords ["card-inner", spaces2px]) $ elClass "div" "form-group form-group-label" $ join <$> widgetHold (renderTextArea resetTextE initLabel) (renderTextArea resetTextE <$> (updateReviewTxt <$ resetTextE)) (gradeD, clickE) <- elClass "div" (T.unwords ["card-action", spaces2px]) $ do gD <- renderGrade 0 cE <- buttonFlatDyn (hideZeroState <$> gradeD) "Grade" mempty return (gD, cE) let postDataOnClickE = (\txt grade -> ExpertReviewPost grade txt) <$> current textD <@> ffilter (> 0) (current gradeD <@ clickE) responseE <- httpPost $ (,) revsUrl <$> postDataOnClickE let reset (Right _) = Just "" reset _ = Nothing let resetTextE = fmapMaybe reset responseE renderError responseE return responseE where updateReviewTxt = "Update your expert review" writeReviewTxt = "Write an expert review" initLabel = if any isMyExpertReview revs then updateReviewTxt else writeReviewTxt WidgetCSSClasses {..} = widgetCSS renderWriteExpertReview _ = return never writeReviewClass :: Text writeReviewClass = $(do reviewCls <- newVar qcss [cassius| .#{reviewCls} .card-inner .form-group margin: 8px 0 0 0 width: 100% textarea resize: vertical .card-action min-height: 32px .btn-flat padding: 0 line-height: 14px |] returnVars [reviewCls] ) -- renders the `JSError` or blank renderError :: Reflex t => Event t (Either JSError a) -> QuaWidget t x () renderError event = do performEvent_ $ liftIO . print <$> (fst $ fanEither event) void $ widgetHold blank (renderErr <$> event) where renderErr (Left err) = el "div" $ text $ textFromJSString $ getJSError err renderErr (Right _) = blank -- render bootstrapified textarea and return dynamic of text it contains renderTextArea :: Reflex t => Event t Text -> Text -> QuaWidget t x (Dynamic t JSString) renderTextArea setValE label = do elAttr "label" ("class" =: "floating-label") $ text label let config = TextAreaConfig "" setValE $ constDyn ("class" =: "form-control") t <- textArea config return $ textToJSString <$> _textArea_value t -- | Render supplied criterios and return dynamic with criterionId of selected one renderCriterions :: Reflex t => [Criterion] -> QuaWidget t x (Dynamic t (Maybe Criterion)) renderCriterions crits = elClass "span" critsClass $ mdo let critE = leftmost critEs critEs <- for crits $ \c -> do let cTitle = "title" =: textFromJSString (criterionName c) activeStyle' = activeStyle <> cTitle inactiveStyle' = inactiveStyle <> cTitle chooseStyle mc _ | Just c' <- mc, criterionId c' == criterionId c = activeStyle' | otherwise = inactiveStyle' critAttrD <- foldDyn chooseStyle inactiveStyle' critE (spanEl, ()) <- elDynAttr' "span" critAttrD $ return () setInnerHTML spanEl $ criterionIcon c return $ Just c <$ domEvent Click spanEl holdDyn Nothing critE where critsClass = $(do critsCls <- newVar qcss [cassius| .#{critsCls} position: relative top: 5px margin-right: 15px span cursor: pointer &:hover opacity: 1 !important |] returnVars [critsCls] ) -- render grading stars and return dynamic of their state (0 is unselected) renderGrade :: Reflex t => Int -> QuaWidget t x (Dynamic t Int) renderGrade nrStartStars = mdo nrStarsD <- holdDyn nrStartStars nrStarsE nrStarsEE <- dyn (renderStars <$> nrStarsD) nrStarsE <- switchPromptly never nrStarsEE return nrStarsD where renderStars nr = do els <- sequence $ (Prelude.replicate nr $ renderStar "star") ++ (Prelude.replicate (5 - nr) $ renderStar "star_border") return $ leftmost $ (\(i, elm) -> i <$ domEvent Click elm) <$> Prelude.zip [1..] els renderStar t = fmap fst $ elClass' "span" (T.unwords ["icon","icon-lg", starsClass]) $ text t starsClass = $(do starsCls <- newVar qcss [cassius| .#{starsCls} cursor: pointer &:hover color: #ff6f00 |] returnVars [starsCls] ) -- render thumb-up and -down buttons and return dynamic of their state renderThumbs :: Reflex t => QuaWidget t x (Dynamic t ThumbState) renderThumbs = elClass "span" thumbsClass $ mdo let thumbE = leftmost [ ThumbUp <$ domEvent Click upEl , ThumbDown <$ domEvent Click dnEl ] let makeThumb upOrDown = do let chooseStyle th _ | th == upOrDown = activeStyle | otherwise = inactiveStyle thumbAttrD <- foldDyn chooseStyle inactiveStyle thumbE fst <$> elDynAttr' "span" (fmap (<> "class" =: "icon") thumbAttrD) (text $ showThumb upOrDown) upEl <- makeThumb ThumbUp dnEl <- makeThumb ThumbDown holdDyn None thumbE where thumbsClass = $(do thumbsCls <- newVar qcss [cassius| .#{thumbsCls} margin-right: 10px >span margin-right: 5px cursor: pointer &:hover opacity: 1 !important |] returnVars [thumbsCls] ) showThumb :: ThumbState -> Text showThumb ThumbUp = "thumb_up" showThumb ThumbDown = "thumb_down" showThumb None = "none" hideState :: Maybe a -> ThumbState -> ComponentState s hideState (Just _) ThumbUp = Active hideState (Just _) ThumbDown = Active hideState _ _ = Inactive hideZeroState :: Int -> ComponentState s hideZeroState 0 = Inactive hideZeroState _ = Active inactiveStyle :: Map Text Text inactiveStyle = "style" =: "opacity: 0.3" activeStyle :: Map Text Text activeStyle = "style" =: "opacity: 1" isMyExpertReview :: Review -> Bool isMyExpertReview rev = reviewIsMine rev && isExpertRating (reviewRating rev) where isExpertRating (ExpertRating _) = True isExpertRating _ = False
achirkin/qua-view
src/Widgets/Tabs/Reviews.hs
Haskell
mit
12,801
{-# LANGUAGE OverloadedStrings #-} module IRTS.CodegenGo (codegenGo) where import Control.Monad.Trans.State.Strict (State, evalState, gets) import Data.Char (isAlphaNum, ord) import Data.Int (Int64) import qualified Data.Map.Strict as M import Data.Maybe (fromMaybe, mapMaybe) import qualified Data.Set as S import qualified Data.Text as T import qualified Data.Text.IO as TIO import Formatting (int, sformat, stext, string, (%)) import System.IO (IOMode (..), withFile) import System.Process (CreateProcess (..), StdStream (..), createProcess, proc, waitForProcess) import Idris.Core.TT hiding (V, arity) import IRTS.CodegenCommon import IRTS.Lang (FDesc (..), FType (..), LVar (..), PrimFn (..)) import IRTS.Simplified data Line = Line (Maybe Var) [Var] T.Text deriving (Show) data Var = RVal | V Int deriving (Show, Eq, Ord) newtype CGState = CGState { requiresTrampoline :: Name -> Bool } type CG a = State CGState a createCgState :: (Name -> Bool) -> CGState createCgState trampolineLookup = CGState { requiresTrampoline = trampolineLookup } goPreamble :: [T.Text] -> T.Text goPreamble imports = T.unlines $ [ "// THIS FILE IS AUTOGENERATED! DO NOT EDIT" , "" , "package main" , "" , "import (" , " \"flag\"" , " \"log\"" , " \"math/big\"" , " \"os\"" , " \"strconv\"" , " \"unicode/utf8\"" , " \"unsafe\"" , " \"runtime\"" , " \"runtime/pprof\"" , ")" , "" ] ++ map ("import " `T.append`) imports ++ [ "" , "func BigIntFromString(s string) *big.Int {" , " value, _ := big.NewInt(0).SetString(s, 10)" , " return value" , "}" , "" , "type Con0 struct {" , " tag int" , "}" , "" , "type Con1 struct {" , " tag int" , " _0 unsafe.Pointer" , "}" , "" , "type Con2 struct {" , " tag int" , " _0, _1 unsafe.Pointer" , "}" , "" , "type Con3 struct {" , " tag int" , " _0, _1, _2 unsafe.Pointer" , "}" , "" , "type Con4 struct {" , " tag int" , " _0, _1, _2, _3 unsafe.Pointer" , "}" , "" , "type Con5 struct {" , " tag int" , " _0, _1, _2, _3, _4 unsafe.Pointer" , "}" , "" , "type Con6 struct {" , " tag int" , " _0, _1, _2, _3, _4, _5 unsafe.Pointer" , "}" , "" , "var nullCons [256]Con0" , "" , "func GetTag(con unsafe.Pointer) int {" , " return (*Con0)(con).tag" , "}" , "" , "func MkCon0(tag int) unsafe.Pointer {" , " return unsafe.Pointer(&Con0{tag})" , "}" , "" , "func MkCon1(tag int, _0 unsafe.Pointer) unsafe.Pointer {" , " return unsafe.Pointer(&Con1{tag, _0})" , "}" , "" , "func MkCon2(tag int, _0, _1 unsafe.Pointer) unsafe.Pointer {" , " return unsafe.Pointer(&Con2{tag, _0, _1})" , "}" , "" , "func MkCon3(tag int, _0, _1, _2 unsafe.Pointer) unsafe.Pointer {" , " return unsafe.Pointer(&Con3{tag, _0, _1, _2})" , "}" , "" , "func MkCon4(tag int, _0, _1, _2, _3 unsafe.Pointer) unsafe.Pointer {" , " return unsafe.Pointer(&Con4{tag, _0, _1, _2, _3})" , "}" , "" , "func MkCon5(tag int, _0, _1, _2, _3, _4 unsafe.Pointer) unsafe.Pointer {" , " return unsafe.Pointer(&Con5{tag, _0, _1, _2, _3, _4})" , "}" , "" , "func MkCon6(tag int, _0, _1, _2, _3, _4, _5 unsafe.Pointer) unsafe.Pointer {" , " return unsafe.Pointer(&Con6{tag, _0, _1, _2, _3, _4, _5})" , "}" , "" , "func MkIntFromBool(value bool) unsafe.Pointer {" , " if value {" , " return intOne" , " } else {" , " return intZero" , " }" , "}" , "" , "func MkInt(value int64) unsafe.Pointer {" , " var retVal *int64 = new(int64)" , " *retVal = value" , " return unsafe.Pointer(retVal)" , "}" , "" , "func MkRune(value rune) unsafe.Pointer {" , " var retVal *rune = new(rune)" , " *retVal = value" , " return unsafe.Pointer(retVal)" , "}" , "" , "func MkString(value string) unsafe.Pointer {" , " var retVal *string = new(string)" , " *retVal = value" , " return unsafe.Pointer(retVal)" , "}" , "" , "func RuneAtIndex(s string, index int) rune {" , " if index == 0 {" , " chr, _ := utf8.DecodeRuneInString(s)" , " return chr" , " } else {" , " i := 0" , " for _, chr := range s {" , " if i == index {" , " return chr" , " }" , " i++" , " }" , " }" , "panic(\"Illegal index: \" + string(index))" , "}" , "" , "func StrTail(s string) string {" , " _, offset := utf8.DecodeRuneInString(s)" , " return s[offset:]" , "}" , "" , "func WriteStr(str unsafe.Pointer) unsafe.Pointer {" , " _, err := os.Stdout.WriteString(*(*string)(str))" , " if (err != nil) {" , " return intZero" , " } else {" , " return intMinusOne" , " }" , "}" , "" , "func Go(action unsafe.Pointer) {" , " var th Thunk" , " go Trampoline(MkThunk2(&th, APPLY0, action, nil))" , "}" , "" , "func MkMaybe(value unsafe.Pointer, present bool) unsafe.Pointer {" , " if present {" , " return MkCon1(1, value)" , " } else {" , " return unsafe.Pointer(&nullCons[0])" , " }" , "}" , "" , "type Thunk0 func(*Thunk) unsafe.Pointer" , "type Thunk1 func(*Thunk, unsafe.Pointer) unsafe.Pointer" , "type Thunk2 func(*Thunk, unsafe.Pointer, unsafe.Pointer) unsafe.Pointer" , "type Thunk3 func(*Thunk, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer) unsafe.Pointer" , "type Thunk4 func(*Thunk, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer) unsafe.Pointer" , "type Thunk5 func(*Thunk, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer) unsafe.Pointer" , "type Thunk6 func(*Thunk, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer) unsafe.Pointer" , "type Thunk7 func(*Thunk, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer) unsafe.Pointer" , "" , "type Thunk struct {" , " arity int8" , " f0 Thunk0" , " f1 Thunk1" , " f2 Thunk2" , " f3 Thunk3" , " f4 Thunk4" , " f5 Thunk5" , " f6 Thunk6" , " f7 Thunk7" , " _0, _1, _2, _3, _4, _5, _6 unsafe.Pointer" , "}" , "" , "func (t *Thunk) Run() unsafe.Pointer {" , " switch t.arity {" , " case 0:" , " return t.f0(t)" , " case 1:" , " return t.f1(t, t._0)" , " case 2:" , " return t.f2(t, t._0, t._1)" , " case 3:" , " return t.f3(t, t._0, t._1, t._2)" , " case 4:" , " return t.f4(t, t._0, t._1, t._2, t._3)" , " case 5:" , " return t.f5(t, t._0, t._1, t._2, t._3, t._4,)" , " case 6:" , " return t.f6(t, t._0, t._1, t._2, t._3, t._4, t._5)" , " case 7:" , " return t.f7(t, t._0, t._1, t._2, t._3, t._4, t._5, t._6)" , " }" , " panic(\"Invalid arity: \" + string(t.arity))" , "}" , "" , "func MkThunk0(th *Thunk, f Thunk0) *Thunk {" , " th.arity = 0" , " th.f0 = f" , " return th" , "}" , "" , "func MkThunk1(th *Thunk, f Thunk1, _0 unsafe.Pointer) *Thunk {" , " th.arity = 1" , " th.f1 = f" , " th._0 = _0" , " return th" , "}" , "" , "func MkThunk2(th *Thunk, f Thunk2, _0, _1 unsafe.Pointer) *Thunk {" , " th.arity = 2" , " th.f2 = f" , " th._0 = _0" , " th._1 = _1" , " return th" , "}" , "" , "func MkThunk3(th *Thunk, f Thunk3, _0, _1, _2 unsafe.Pointer) *Thunk {" , " th.arity = 3" , " th.f3 = f" , " th._0 = _0" , " th._1 = _1" , " th._2 = _2" , " return th" , "}" , "" , "func MkThunk4(th *Thunk, f Thunk4, _0, _1, _2, _3 unsafe.Pointer) *Thunk {" , " th.arity = 4" , " th.f4 = f" , " th._0 = _0" , " th._1 = _1" , " th._2 = _2" , " th._3 = _3" , " return th" , "}" , "" , "func MkThunk5(th *Thunk, f Thunk5, _0, _1, _2, _3, _4 unsafe.Pointer) *Thunk {" , " th.arity = 5" , " th.f5 = f" , " th._0 = _0" , " th._1 = _1" , " th._2 = _2" , " th._3 = _3" , " th._4 = _4" , " return th" , "}" , "" , "func MkThunk6(th *Thunk, f Thunk6, _0, _1, _2, _3, _4, _5 unsafe.Pointer) *Thunk {" , " th.arity = 6" , " th.f6 = f" , " th._0 = _0" , " th._1 = _1" , " th._2 = _2" , " th._3 = _3" , " th._4 = _4" , " th._5 = _5" , " return th" , "}" , "" , "func MkThunk7(th *Thunk, f Thunk7, _0, _1, _2, _3, _4, _5, _6 unsafe.Pointer) *Thunk {" , " th.arity = 7" , " th.f7 = f" , " th._0 = _0" , " th._1 = _1" , " th._2 = _2" , " th._3 = _3" , " th._4 = _4" , " th._5 = _5" , " th._6 = _6" , " return th" , "}" , "" , "func Trampoline(th *Thunk) unsafe.Pointer {" , " var result unsafe.Pointer" , " for th.arity >= 0 {" , " result = th.Run()" , " }" , " return result" , "}" , "" , "func initNullCons() {" , " for i := 0; i < 256; i++ {" , " nullCons[i] = Con0{i}" , " }" , "}" , "" , "var bigZero *big.Int = big.NewInt(0)" , "var bigOne *big.Int = big.NewInt(1)" , "var intMinusOne unsafe.Pointer = MkInt(-1)" , "var intZero unsafe.Pointer = MkInt(0)" , "var intOne unsafe.Pointer = MkInt(1)" , "" -- This solely exists so the strconv import is used even if the program -- doesn't use the LIntStr primitive. , "func __useStrconvImport() string {" , " return strconv.Itoa(-42)" , "}" , "" ] mangleName :: Name -> T.Text mangleName name = T.concat $ map mangleChar (showCG name) where mangleChar x | isAlphaNum x = T.singleton x | otherwise = sformat ("_" % int % "_") (ord x) nameToGo :: Name -> T.Text nameToGo (MN i n) | T.all (\x -> isAlphaNum x || x == '_') n = n `T.append` T.pack (show i) nameToGo n = mangleName n lVarToGo :: LVar -> T.Text lVarToGo (Loc i) = sformat ("_" % int) i lVarToGo (Glob n) = nameToGo n lVarToVar :: LVar -> Var lVarToVar (Loc i) = V i lVarToVar v = error $ "LVar not convertible to var: " ++ show v varToGo :: Var -> T.Text varToGo RVal = "__rval" varToGo (V i) = sformat ("_" % int) i assign :: Var -> T.Text -> T.Text assign RVal x = "__thunk.arity = -1; " `T.append` varToGo RVal `T.append` " = " `T.append` x assign var x = varToGo var `T.append` " = " `T.append` x exprToGo :: Name -> Var -> SExp -> CG [Line] exprToGo f var SNothing = return . return $ Line (Just var) [] (assign var "nil") exprToGo _ var (SConst i@BI{}) | i == BI 0 = return [ Line (Just var) [] (assign var "unsafe.Pointer(bigZero)") ] | i == BI 1 = return [ Line (Just var) [] (assign var "unsafe.Pointer(bigOne)") ] | otherwise = return [ Line (Just var) [] (assign var (sformat ("unsafe.Pointer(" % stext % ")") (constToGo i))) ] exprToGo f var (SConst c@Ch{}) = return . return $ mkVal var c (sformat ("MkRune(" % stext % ")")) exprToGo _ var (SConst i@I{}) | i == I (-1) = return . return $ Line (Just var) [] (assign var "intMinusOne") | i == I 0 = return . return $ Line (Just var) [] (assign var "intZero") | i == I 1 = return . return $ Line (Just var) [] (assign var "intOne") | otherwise = return . return $ mkVal var i (sformat ("MkInt(" % stext % ")")) exprToGo f var (SConst s@Str{}) = return . return $ mkVal var s (sformat ("MkString(" % stext % ")")) exprToGo _ (V i) (SV (Loc j)) | i == j = return [] exprToGo _ var (SV (Loc i)) = return [ Line (Just var) [V i] (assign var (lVarToGo (Loc i))) ] exprToGo f var (SLet (Loc i) e sc) = do a <- exprToGo f (V i) e b <- exprToGo f var sc return $ a ++ b exprToGo f var (SApp True name vs) -- self call, simply goto to the entry again | f == name = return $ [ Line (Just (V i)) [ V a ] (sformat ("_" % int % " = _" % int) i a) | (i, Loc a) <- zip [0..] vs, i /= a ] ++ [ Line Nothing [ ] "goto entry" ] exprToGo f RVal (SApp True name vs) = do trampolined <- fmap ($ name) (gets requiresTrampoline) let args = T.intercalate ", " ("__thunk" : map lVarToGo vs) code = if trampolined then mkThunk name vs else assign RVal (nameToGo name `T.append` "(" `T.append` args `T.append` ")") return [ Line (Just RVal) [ V i | (Loc i) <- vs ] code ] exprToGo _ var (SApp True _ _) = error $ "Tail-recursive call, but should be assigned to " ++ show var exprToGo _ var (SApp False name vs) = do -- Not a tail call, but we might call a function that needs to be trampolined trampolined <- fmap ($ name) (gets requiresTrampoline) let code = if trampolined then assign var (sformat ("Trampoline(" % stext % ")") (mkThunk name vs)) else assign var (sformat (stext % "(" % stext % ")") (nameToGo name) args) return [ Line (Just var) [ V i | (Loc i) <- vs ] code ] where args = T.intercalate ", " ("__thunk" : map lVarToGo vs) exprToGo f var (SCase up (Loc l) alts) | isBigIntConst alts = constBigIntCase f var (V l) (dedupDefaults alts) | isConst alts = constCase f var (V l) alts | otherwise = conCase f var (V l) alts where isBigIntConst (SConstCase (BI _) _ : _) = True isBigIntConst _ = False isConst [] = False isConst (SConstCase _ _ : _) = True isConst (SConCase{} : _) = False isConst (_ : _) = False dedupDefaults (d@SDefaultCase{} : [SDefaultCase{}]) = [d] dedupDefaults (x : xs) = x : dedupDefaults xs dedupDefaults [] = [] exprToGo f var (SChkCase (Loc l) alts) = conCase f var (V l) alts exprToGo f var (SCon _ tag name args) = return . return $ Line (Just var) [ V i | (Loc i) <- args] (comment `T.append` assign var mkCon) where comment = "// " `T.append` (T.pack . show) name `T.append` "\n" mkCon | tag < 256 && null args = sformat ("unsafe.Pointer(&nullCons[" % int % "])") tag | otherwise = let argsCode = case args of [] -> T.empty _ -> ", " `T.append` T.intercalate ", " (map lVarToGo args) in sformat ("MkCon" % int % "(" % int % stext % ")") (length args) tag argsCode exprToGo f var (SOp prim args) = return . return $ primToGo var prim args exprToGo f var (SForeign ty (FApp callType callTypeArgs) args) = let call = toCall callType callTypeArgs in return . return $ Line Nothing [] (retVal (fDescToGoType ty) call) where convertedArgs = [ toArg (fDescToGoType t) (lVarToGo l) | (t, l) <- args] toCall ct [ FStr fname ] | ct == sUN "Function" = T.pack fname `T.append` "(" `T.append` T.intercalate ", " convertedArgs `T.append` ")" toCall ct [ FStr _, _, FStr methodName ] | ct == sUN "Method" = let obj : args = convertedArgs in sformat (stext % "." % string % "(" % stext % ")") obj methodName (T.intercalate ", " args) toCall ct a = error $ show ct ++ " " ++ show a toArg (GoInterface name) x = sformat ("(*(*" % string % ")(" % stext % "))") name x toArg GoByte x = "byte(*(*rune)(" `T.append` x `T.append` "))" toArg GoString x = "*(*string)(" `T.append` x `T.append` ")" toArg GoAny x = x toArg f _ = error $ "Not implemented yet: toArg " ++ show f ptrFromRef x = "unsafe.Pointer(&" `T.append` x `T.append` ")" toPtr (GoInterface _) x = ptrFromRef x toPtr GoInt x = ptrFromRef x toPtr GoString x = ptrFromRef x toPtr (GoNilable valueType) x = sformat ("MkMaybe(" % stext % ", " % stext % " != nil)" ) (toPtr valueType x) x retRef ty x = sformat ("{ __tmp := " % stext % "\n " % stext % " = " % stext % " }") x (varToGo var) (toPtr ty "__tmp") retVal GoUnit x = x retVal GoString x = retRef GoString x retVal (i@GoInterface{}) x = retRef i x retVal (n@GoNilable{}) x = retRef n x retVal (GoMultiVal varTypes) x = -- XXX assumes exactly two vars sformat ("{ " % stext % " := " % stext % "\n " % stext % " = MkCon" % int % "(0, " % stext % ") }") (T.intercalate ", " [ sformat ("__tmp" % int) i | i <- [1..length varTypes]]) x (varToGo var) (length varTypes) (T.intercalate ", " [ toPtr varTy (sformat ("__tmp" % int) i) | (i, varTy) <- zip [1 :: Int ..] varTypes ]) retVal (GoPtr _) x = sformat (stext % " = unsafe.Pointer(" % stext % ")") (varToGo var) x retVal t _ = error $ "Not implemented yet: retVal " ++ show t exprToGo _ _ expr = error $ "Not implemented yet: " ++ show expr data GoType = GoByte | GoInt | GoString | GoNilable GoType | GoInterface String | GoUnit | GoMultiVal [GoType] | GoPtr GoType | GoAny deriving (Show) fDescToGoType :: FDesc -> GoType fDescToGoType (FCon c) | c == sUN "Go_Byte" = GoByte | c == sUN "Go_Int" = GoInt | c == sUN "Go_Str" = GoString | c == sUN "Go_Unit" = GoUnit fDescToGoType (FApp c [ FStr name ]) | c == sUN "Go_Interface" = GoInterface name fDescToGoType (FApp c [ _ ]) | c == sUN "Go_Any" = GoAny fDescToGoType (FApp c [ _, ty ]) | c == sUN "Go_Nilable" = GoNilable (fDescToGoType ty) fDescToGoType (FApp c [ _, _, FApp c2 [ _, _, a, b ] ]) | c == sUN "Go_MultiVal" && c2 == sUN "MkPair" = GoMultiVal [ fDescToGoType a, fDescToGoType b ] fDescToGoType (FApp c [ _, ty ]) | c == sUN "Go_Ptr" = GoPtr (fDescToGoType ty) fDescToGoType f = error $ "Not implemented yet: fDescToGoType " ++ show f toFunType :: FDesc -> FType toFunType (FApp c [ _, _ ]) | c == sUN "Go_FnBase" = FFunction | c == sUN "Go_FnIO" = FFunctionIO toFunType desc = error $ "Not implemented yet: toFunType " ++ show desc mkThunk :: Name -> [LVar] -> T.Text mkThunk f [] = sformat ("MkThunk0(__thunk, " % stext % ")") (nameToGo f) mkThunk f args = sformat ("MkThunk" % int % "(__thunk, " % stext % ", " % stext % ")") (length args) (nameToGo f) (T.intercalate "," (map lVarToGo args)) mkVal :: Var -> Const -> (T.Text -> T.Text) -> Line mkVal var c factory = Line (Just var) [] (assign var (factory (constToGo c))) constToGo :: Const -> T.Text constToGo (BI i) | i == 0 = "bigZero" | i == 1 = "bigOne" | i < toInteger (maxBound :: Int64) && i > toInteger (minBound :: Int64) = "big.NewInt(" `T.append` T.pack (show i) `T.append` ")" | otherwise = "BigIntFromString(\"" `T.append` T.pack (show i) `T.append` "\")" constToGo (Ch '\DEL') = "'\\x7F'" constToGo (Ch '\SO') = "'\\x0e'" constToGo (Str s) = T.pack (show s) constToGo constVal = T.pack (show constVal) -- Special case for big.Ints, as we need to compare with Cmp there constBigIntCase :: Name -> Var -> Var -> [SAlt] -> CG [Line] constBigIntCase f var v alts = do cases <- traverse case_ alts return $ [ Line Nothing [] "switch {" ] ++ concat cases ++ [ Line Nothing [] "}" ] where valueCmp other = sformat ("(*big.Int)(" % stext % ").Cmp(" % stext % ") == 0") (varToGo v) (constToGo other) case_ (SConstCase constVal expr) = do code <- exprToGo f var expr return $ Line Nothing [v] (sformat ("case " % stext % ":") (valueCmp constVal)) : code case_ (SDefaultCase expr) = do code <- exprToGo f var expr return $ Line Nothing [] "default:" : code case_ c = error $ "Unexpected big int case: " ++ show c constCase :: Name -> Var -> Var -> [SAlt] -> CG [Line] constCase f var v alts = do cases <- traverse case_ alts return $ [ Line Nothing [v] (T.concat [ "switch " , castValue alts , " {" ]) ] ++ concat cases ++ [ Line Nothing [] "}" ] where castValue (SConstCase (Ch _) _ : _) = "*(*rune)(" `T.append` varToGo v `T.append` ")" castValue (SConstCase (I _) _ : _) = "*(*int64)(" `T.append` varToGo v `T.append` ")" castValue (SConstCase constVal _ : _) = error $ "Not implemented: cast for " ++ show constVal castValue _ = error "First alt not a SConstCase!" case_ (SDefaultCase expr) = do code <- exprToGo f var expr return $ Line Nothing [] "default:" : code case_ (SConstCase constVal expr) = do code <- exprToGo f var expr return $ Line Nothing [] (T.concat [ "case " , constToGo constVal , ":" ]) : code case_ c = error $ "Unexpected const case: " ++ show c conCase :: Name -> Var -> Var -> [SAlt] -> CG [Line] conCase f var v [ SDefaultCase expr ] = exprToGo f var expr conCase f var v alts = do cases <- traverse case_ alts return $ [ Line Nothing [v] (T.concat [ "switch GetTag(" , varToGo v , ") {" ]) ] ++ concat cases ++ [ Line Nothing [] "}" ] where project left i = Line (Just left) [v] (assign left (sformat ("(*Con" % int % ")(" % stext % ")._" % int) (i+1) (varToGo v) i)) case_ (SConCase base tag name args expr) = do let locals = [base .. base + length args - 1] projections = [ project (V i) (i - base) | i <- locals ] code <- exprToGo f var expr return $ [ Line Nothing [] (sformat ("case " % int % ":\n // Projection of " % stext) tag (nameToGo name)) ] ++ projections ++ code case_ (SDefaultCase expr) = do code <- exprToGo f var expr return $ Line Nothing [] "default:" : code case_ c = error $ "Unexpected con case: " ++ show c primToGo :: Var -> PrimFn -> [LVar] -> Line primToGo var (LChInt ITNative) [ch] = let code = "MkInt(int64(*(*rune)(" `T.append` lVarToGo ch `T.append` ")))" in Line (Just var) [ lVarToVar ch ] (assign var code) primToGo var (LEq (ATInt ITChar)) [left, right] = let code = T.concat [ "MkIntFromBool(*(*rune)(" , lVarToGo left , ") == *(*rune)(" , lVarToGo right , "))" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) primToGo var (LEq (ATInt ITNative)) [left, right] = let code = T.concat [ "MkIntFromBool(*(*int64)(" , lVarToGo left , ") == *(*int64)(" , lVarToGo right , "))" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) primToGo var (LEq (ATInt ITBig)) [left, right] = let code = T.concat [ "MkIntFromBool((*big.Int)(" , lVarToGo left , ").Cmp((*big.Int)(" , lVarToGo right , ")) == 0)" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) primToGo var (LSLt (ATInt ITChar)) [left, right] = let code = T.concat [ "MkIntFromBool(*(*rune)(" , lVarToGo left , ") < *(*rune)(" , lVarToGo right , "))" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) primToGo var (LSLt (ATInt ITNative)) [left, right] = let code = T.concat [ varToGo var , " = MkIntFromBool(*(*int64)(" , lVarToGo left , ") < *(*int64)(" , lVarToGo right , "))" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] code primToGo var (LSLt (ATInt ITBig)) [left, right] = let code = T.concat [ "MkIntFromBool((*big.Int)(" , lVarToGo left , ").Cmp((*big.Int)(" , lVarToGo right , ")) < 0)" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) primToGo var (LMinus (ATInt ITNative)) [left, right] = nativeIntBinOp var left right "-" primToGo var (LMinus (ATInt ITBig)) [left, right] = bigIntBigOp var left right "Sub" primToGo var (LPlus (ATInt ITNative)) [left, right] = nativeIntBinOp var left right "+" primToGo var (LPlus (ATInt ITBig)) [left, right] = bigIntBigOp var left right "Add" primToGo var (LSExt ITNative ITBig) [i] = let code = "unsafe.Pointer(big.NewInt(*(*int64)(" `T.append` lVarToGo i `T.append` ")))" in Line (Just var) [ lVarToVar i ] (assign var code) primToGo var (LIntStr ITBig) [i] = let code = "MkString((*big.Int)(" `T.append` lVarToGo i `T.append` ").String())" in Line (Just var) [ lVarToVar i ] (assign var code) primToGo var (LIntStr ITNative) [i] = let code = "MkString(strconv.FormatInt(*(*int64)(" `T.append` lVarToGo i `T.append` "), 10))" in Line (Just var) [ lVarToVar i ] (assign var code) primToGo var LStrEq [left, right] = let code = T.concat [ "MkIntFromBool(*(*string)(" , lVarToGo left , ") == *(*string)(" , lVarToGo right , "))" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) primToGo var LStrCons [c, s] = let code = T.concat [ "MkString(string(*(*rune)(" , lVarToGo c , ")) + *(*string)(" , lVarToGo s , "))" ] in Line (Just var) [ lVarToVar c, lVarToVar s ] (assign var code) primToGo var LStrHead [s] = let code = "MkRune(RuneAtIndex(*(*string)(" `T.append` lVarToGo s `T.append` "), 0))" in Line (Just var) [ lVarToVar s ] (assign var code) primToGo var LStrTail [s] = let code = "MkString(StrTail(*(*string)(" `T.append` lVarToGo s `T.append` ")))" in Line (Just var) [ lVarToVar s ] (assign var code) primToGo var LStrConcat [left, right] = let code = T.concat [ "MkString(*(*string)(" , lVarToGo left , ") + *(*string)(" , lVarToGo right , "))" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) primToGo var LWriteStr [world, s] = let code = "WriteStr(" `T.append` lVarToGo s `T.append` ")" in Line (Just var) [ lVarToVar world, lVarToVar s ] (assign var code) primToGo var (LTimes (ATInt ITNative)) [left, right] = nativeIntBinOp var left right "*" primToGo var (LTimes (ATInt ITBig)) [left, right] = bigIntBigOp var left right "Mul" primToGo _ fn _ = Line Nothing [] (sformat ("panic(\"Unimplemented PrimFn: " % string % "\")") (show fn)) bigIntBigOp :: Var -> LVar -> LVar -> T.Text -> Line bigIntBigOp var left right op = let code = T.concat [ "unsafe.Pointer(new(big.Int)." , op , "((*big.Int)(" , lVarToGo left , "), (*big.Int)(" , lVarToGo right , ")))" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) nativeIntBinOp :: Var -> LVar -> LVar -> T.Text -> Line nativeIntBinOp var left right op = let code = T.concat [ "MkInt(*(*int64)(" , lVarToGo left , ") " , op , " *(*int64)(" , lVarToGo right , "))" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) data TailCall = Self | Other deriving (Eq, Show) containsTailCall :: Name -> SExp -> [TailCall] containsTailCall self (SApp True n _) = if self == n then [ Self ] else [ Other ] containsTailCall self (SLet _ a b) = containsTailCall self a ++ containsTailCall self b containsTailCall self (SUpdate _ e) = containsTailCall self e containsTailCall self (SCase _ _ alts) = concatMap (altContainsTailCall self) alts containsTailCall self (SChkCase _ alts) = concatMap (altContainsTailCall self) alts containsTailCall _ _ = [] altContainsTailCall :: Name -> SAlt -> [TailCall] altContainsTailCall self (SConCase _ _ _ _ e) = containsTailCall self e altContainsTailCall self (SConstCase _ e) = containsTailCall self e altContainsTailCall self (SDefaultCase e) = containsTailCall self e extractUsedVars :: [Line] -> S.Set Var extractUsedVars lines = S.fromList (concat [used | Line _ used _ <- lines]) filterUnusedLines :: [Line] -> [Line] filterUnusedLines lines = let usedVars = extractUsedVars lines requiredLines = mapMaybe (required usedVars) lines in if length lines /= length requiredLines -- the filtered lines might have made some other lines obsolete, filter again then filterUnusedLines requiredLines else lines where required _ l@(Line Nothing _ _) = Just l required _ l@(Line (Just RVal) _ _) = Just l required usedVars l@(Line (Just v) _ _) = if S.member v usedVars then Just l else Nothing funToGo :: (Name, SDecl, [TailCall]) -> CG T.Text funToGo (name, SFun _ args locs expr, tailCalls) = do bodyLines <- filterUnusedLines <$> exprToGo name RVal expr let usedVars = extractUsedVars bodyLines pure . T.concat $ [ "// " , T.pack $ show name , "\nfunc " , nameToGo name , "(" , "__thunk *Thunk" `T.append` if (not . null) args then ", " else T.empty , T.intercalate ", " [ sformat ("_" % int % " unsafe.Pointer") i | i <- [0..length args-1]] , ") unsafe.Pointer {\n var __rval unsafe.Pointer\n" , reserve usedVars locs , tailCallEntry , T.unlines [ line | Line _ _ line <- bodyLines ] , "return __rval\n}\n\n" ] where tailCallEntry = if Self `elem` tailCalls then "entry:" else T.empty loc usedVars i = let i' = length args + i in if S.member (V i') usedVars then Just $ sformat ("_" % int) i' else Nothing reserve usedVars locs = case mapMaybe (loc usedVars) [0..locs] of [] -> T.empty usedLocs -> " var " `T.append` T.intercalate ", " usedLocs `T.append` " unsafe.Pointer\n" genMain :: T.Text genMain = T.unlines [ "var cpuprofile = flag.String(\"cpuprofile\", \"\", \"write cpu profile `file`\")" , "var memprofile = flag.String(\"memprofile\", \"\", \"write memory profile to `file`\")" , "" , "func main() {" , " flag.Parse()" , " initNullCons()" , " if *cpuprofile != \"\" {" , " f, err := os.Create(*cpuprofile)" , " if err != nil {" , " log.Fatal(\"Could not create CPU profile: \", err)" , " }" , " if err := pprof.StartCPUProfile(f); err != nil {" , " log.Fatal(\"Could not start CPU profile: \", err)" , " }" , " defer pprof.StopCPUProfile()" , " }" , " var thunk Thunk" , " runMain0(&thunk)" , " if *memprofile != \"\" {" , " f, err := os.Create(*memprofile)" , " if err != nil {" , " log.Fatal(\"Could not create memory profile: \", err)" , " }" , " runtime.GC()" , " if err := pprof.WriteHeapProfile(f); err != nil {" , " log.Fatal(\"Could not write memory profile: \", err)" , " }" , " f.Close()" , " }" , "}" ] codegenGo :: CodeGenerator codegenGo ci = do let funs = [ (name, fun, containsTailCall name expr) | (name, fun@(SFun _ _ _ expr)) <- simpleDecls ci ] needsTrampolineByName = M.fromList [ (name, Other `elem` tailCalls) | (name, _, tailCalls) <- funs ] trampolineLookup = fromMaybe False . (`M.lookup` needsTrampolineByName) funCodes = evalState (traverse funToGo funs) (createCgState trampolineLookup) code = T.concat [ goPreamble (map (T.pack . show) (includes ci)) , T.concat funCodes , genMain ] withFile (outputFile ci) WriteMode $ \hOut -> do (Just hIn, _, _, p) <- createProcess (proc "gofmt" [ "-s" ]){ std_in = CreatePipe, std_out = UseHandle hOut } TIO.hPutStr hIn code _ <- waitForProcess p return ()
Trundle/idris-go
src/IRTS/CodegenGo.hs
Haskell
mit
32,179
-- The solution of exercise 1.23 -- The `smallest-divisor` procedure shown at the start of this section does -- lots of needless testing: After it checks to see if the number is -- divisible by 2 there is no point in checking to see if it is divisible -- by any larger even numbers. This suggests that the values used for -- `test-divisor` should not be 2, 3, 4, 5, 6, ..., but rather 2, 3, 5, 7, -- 9,... . To implement this change, define a procedure `next` that returns -- 3 if its input is equal to 2 and otherwise returns its input plus 2. -- Modify the `smallest-divisor` procedure to use (next test-divisor) -- instead of (+ test-divisor 1). With `timed-prime-test` incorporating -- this modified version of `smallest-divisor`, run the test for each of -- the 12 primes found in exercise 1.22. Since this modification halves the -- number of test steps, you should expect it to run about twice as fast. -- Is this expectation confirmed? If not, what is the observed ratio of the -- speeds of the two algorithms, and how do you explain the fact that it is -- different from 2? -- -- -------- (above from SICP) -- import Data.Time -- Run 'cabal install vector' first! import qualified Data.Vector as V -- Find the smallest divisor of an integer smallestDivisor :: (Integral a) => a -> a smallestDivisor n = if n < 0 then smallestDivisor (-n) else let next n | n == 2 = 3 | n > 2 = n + 2 findDivisor m td | td * td > m = m | mod m td == 0 = td | otherwise = findDivisor m (next td) in findDivisor n 2 -- Test a number is a prime or not isPrime n | n < 0 = isPrime (-n) | n == 0 = False | n == 1 = False | otherwise = smallestDivisor n == n -- Find the smallest prime that is larger than n nextPrime :: (Integral a) => a -> a nextPrime n = let findPrime counter = if isPrime counter then counter else findPrime (counter + 1) in findPrime (n + 1) -- Find the smallest m primes that are larger than n nextPrimes :: (Integral a, Show a) => a -> a -> IO () nextPrimes n m = let searchPrimeCount init counter maxCount = if counter < maxCount then do let newPrime = nextPrime init putStrLn ("prime[" ++ show counter ++ "] " ++ show newPrime) searchPrimeCount newPrime (counter + 1) maxCount else return () in searchPrimeCount n 0 m -- Find the m th primes that are larger than n nextPrimesNum :: (Integral a) => a -> a -> a nextPrimesNum n m = let searchPrimeCount init counter maxCount = if counter < maxCount then let newPrime = nextPrime init in searchPrimeCount newPrime (counter + 1) maxCount else init in searchPrimeCount n 0 m -- -- Find the smallest m primes that are bigger than n and store all of them -- in a vector. Test an example: find the next 100 odd primes of 19999. -- -- *Main> nextPrimesVec 19999 100 -- [20011,20021,20023,20029,20047,20051,20063,20071,20089,20101,20107, -- 20113,20117,20123,20129,20143,20147,20149,20161,20173,20177,20183, -- 20201,20219,20231,20233,20249,20261,20269,20287,20297,20323,20327, -- 20333,20341,20347,20353,20357,20359,20369,20389,20393,20399,20407, -- 20411,20431,20441,20443,20477,20479,20483,20507,20509,20521,20533, -- 20543,20549,20551,20563,20593,20599,20611,20627,20639,20641,20663, -- 20681,20693,20707,20717,20719,20731,20743,20747,20749,20753,20759, -- 20771,20773,20789,20807,20809,20849,20857,20873,20879,20887,20897, -- 20899,20903,20921,20929,20939,20947,20959,20963,20981,20983,21001, -- 21011] -- nextPrimesVec :: (Integral a) => a -> a -> V.Vector a nextPrimesVec n m = let searchPrimeCount init counter maxCount vector = if counter < maxCount then let newPrime = nextPrime init in searchPrimeCount newPrime (counter + 1) maxCount (V.snoc vector newPrime) else vector v0 = V.fromList [] in searchPrimeCount n 0 m v0 -- Compute the runtime of `nextPrimesNum` computeRuntime n m = do start <- getCurrentTime print $ nextPrimesNum n m stop <- getCurrentTime print $ diffUTCTime stop start -- -- *Main> computeRuntime 100000000000 3 -- 100000000057 -- 0.978514s -- *Main> computeRuntime 1000000000000 3 -- 1000000000063 -- 2.987301s -- *Main> computeRuntime 10000000000000 3 -- 10000000000099 -- 11.742541s --
perryleo/sicp
ch1/sicpc1e23.hs
Haskell
mit
4,498
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Openshift.V1.ImageStreamImage where import GHC.Generics import Data.Text import Kubernetes.V1.ObjectMeta import Openshift.V1.Image import qualified Data.Aeson -- | data ImageStreamImage = ImageStreamImage { kind :: Maybe Text -- ^ Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds , apiVersion :: Maybe Text -- ^ APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources , metadata :: Maybe ObjectMeta -- ^ , image :: Image -- ^ the image associated with the ImageStream and image name } deriving (Show, Eq, Generic) instance Data.Aeson.FromJSON ImageStreamImage instance Data.Aeson.ToJSON ImageStreamImage
minhdoboi/deprecated-openshift-haskell-api
openshift/lib/Openshift/V1/ImageStreamImage.hs
Haskell
apache-2.0
1,233
{- Copyright 2020 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE RecordWildCards #-} {- Copyright 2020 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE ViewPatterns #-} -- | -- This module encapsulates the logics behind the prediction code in the -- multi-player setup. module CodeWorld.Prediction ( Timestamp, AnimationRate, StepFun, Future, initFuture, currentTimePasses, currentState, addEvent, currentStateDirect, eqFuture, printInternalState, ) where import Data.Bifunctor (second) import qualified Data.IntMap as IM import Data.List (foldl', intercalate) import qualified Data.MultiMap as M import Text.Printf type PlayerId = Int type Timestamp = Double -- in seconds, relative to some arbitrary starting point type AnimationRate = Double -- in seconds, e.g. 0.1 -- All we do with events is to apply them to the state. So let's just store the -- function that does that. type Event s = s -> s -- A state and an event only make sense together with a time. type TState s = (Timestamp, s) type TEvent s = (Timestamp, Event s) type StepFun s = Double -> s -> s type EventQueue s = M.MultiMap (Timestamp, PlayerId) (Event s) -- | Invariants about the time stamps in this data type: -- * committed <= pending <= current < future -- * The time is advanced with strictly ascending timestamps -- * For each player, events come in with strictly ascending timestamps -- * For each player, all events in pending or future are before the -- corresponding lastEvents entry. data Future s = Future { committed :: TState s, lastQuery :: Timestamp, lastEvents :: IM.IntMap Timestamp, pending :: EventQueue s, future :: EventQueue s, current :: TState s } initFuture :: s -> Int -> Future s initFuture s numPlayers = Future { committed = (0, s), lastQuery = 0, lastEvents = IM.fromList [(n, 0) | n <- [0 .. numPlayers - 1]], pending = M.empty, future = M.empty, current = (0, s) } -- Time handling. -- -- Move state forward in fixed animation rate steps, and get -- the timestamp as close to the given target as possible (but possibly stop short) timePassesBigStep :: StepFun s -> AnimationRate -> Timestamp -> TState s -> TState s timePassesBigStep step rate target (now, s) | now + rate <= target = timePassesBigStep step rate target (stepBy step rate (now, s)) | otherwise = (now, s) -- Move state forward in fixed animation rate steps, and get -- the timestamp as close to the given target as possible, and then do a final small step timePasses :: StepFun s -> AnimationRate -> Timestamp -> TState s -> TState s timePasses step rate target = stepTo step target . timePassesBigStep step rate target stepBy :: StepFun s -> Double -> TState s -> TState s stepBy step diff (now, s) = (now + diff, step diff s) stepTo :: StepFun s -> Timestamp -> TState s -> TState s stepTo step target (now, s) = (target, step (target - now) s) handleNextEvent :: StepFun s -> AnimationRate -> TEvent s -> TState s -> TState s handleNextEvent step rate (target, event) = second event . timePasses step rate target handleNextEvents :: StepFun s -> AnimationRate -> EventQueue s -> TState s -> TState s handleNextEvents step rate eq ts = foldl' (flip (handleNextEvent step rate)) ts $ map (\((t, _p), h) -> (t, h)) $ M.toList eq -- | This should be called shortly following 'currentTimePasses' currentState :: StepFun s -> AnimationRate -> Timestamp -> Future s -> s currentState step rate target f = snd $ timePasses step rate target (current f) -- | This should be called regularly, to keep the current state up to date, -- and to incorporate future events in it. currentTimePasses :: StepFun s -> AnimationRate -> Timestamp -> Future s -> Future s currentTimePasses step rate target = advanceCurrentTime step rate target . advanceFuture step rate target -- | Take a new event into account, local or remote. -- Invariant: -- * The timestamp of the event is larger than the timestamp -- of any event added for this player (which is the timestamp for the player -- in `lastEvents`) addEvent :: StepFun s -> AnimationRate -> PlayerId -> Timestamp -> Maybe (Event s) -> Future s -> Future s -- A future event. addEvent step rate player now mbEvent f | now > lastQuery f = recordActivity step rate player now $ f {future = maybe id (M.insertR (now, player)) mbEvent $ future f} -- A past event, goes to pending events. Pending events need to be replayed. addEvent step rate player now mbEvent f = replayPending step rate $ recordActivity step rate player now $ f {pending = maybe id (M.insertR (now, player)) mbEvent $ pending f} -- | Updates the 'lastEvents' field, and possibly updates the commmitted state recordActivity :: StepFun s -> AnimationRate -> PlayerId -> Timestamp -> Future s -> Future s recordActivity step rate player now f = advanceCommitted step rate $ f {lastEvents = IM.insert player now $ lastEvents f} -- | Commits events from the pending queue that are past the commitTime advanceCommitted :: StepFun s -> AnimationRate -> Future s -> Future s advanceCommitted step rate f | M.null eventsToCommit = f -- do not bother | otherwise = f {committed = committed', pending = uncommited'} where commitTime' = minimum $ IM.elems $ lastEvents f canCommit t = t < commitTime' (eventsToCommit, uncommited') = M.spanAntitone (canCommit . fst) (pending f) committed' = handleNextEvents step rate eventsToCommit $ committed f -- | Throws away the current state, and recreates it from -- pending events. To be used when inserting a pending event. replayPending :: StepFun s -> AnimationRate -> Future s -> Future s replayPending step rate f = f {current = current'} where current' = timePassesBigStep step rate (lastQuery f) $ handleNextEvents step rate (pending f) $ committed f -- | Takes into account all future event that happen before the given 'Timestamp' -- Does not have to call 'replayPending', as we only append to the 'pending' queue. -- But does have to call 'advanceCommitted', as the newly added events might -- go directly to the committed state. advanceFuture :: StepFun s -> AnimationRate -> Timestamp -> Future s -> Future s advanceFuture step rate target f | M.null toPerform = f | otherwise = advanceCommitted step rate $ f {current = current', pending = pending', future = future'} where hasHappened t = t <= target (toPerform, future') = M.spanAntitone (hasHappened . fst) (future f) pending' = pending f `M.union` toPerform current' = handleNextEvents step rate toPerform $ current f -- | Advances the current time (by big steps) advanceCurrentTime :: StepFun s -> AnimationRate -> Timestamp -> Future s -> Future s advanceCurrentTime step rate target f = f { current = timePassesBigStep step rate target $ current f, lastQuery = target } -- | Only for testing. currentStateDirect :: Future s -> (Timestamp, s) currentStateDirect = current -- | Only for testing. eqFuture :: Eq s => Future s -> Future s -> Bool eqFuture f1 f2 = ( current f1, lastEvents f1, M.keys (pending f1), M.keys (future f1), committed f1 ) == ( current f2, lastEvents f2, M.keys (pending f2), M.keys (future f2), committed f2 ) -- | Only for testing. printInternalState :: (s -> String) -> Future s -> IO () printInternalState showState f = do printf " Current: (%6.3f) %s\n" (fst (current f)) $ showState (snd (current f)) printf " Latest: %s\n" $ intercalate " " [printf "%d:%.3f" p t | (p, t) <- IM.toList (lastEvents f)] printf " Committed: (%6.3f) %s\n" (fst (committed f)) $ showState (snd (committed f))
google/codeworld
codeworld-prediction/src/CodeWorld/Prediction.hs
Haskell
apache-2.0
8,940
import Data.Char import Data.List import qualified Data.Vector.Unboxed as U insert_word :: [[Char]] -> [Char] -> [[Char]] insert_word (a:tail) word | a==word = [(a)] ++ tail | otherwise = [(a)] ++ insert_word tail word insert_word _ w = [(w)] find_word :: [[Char]] -> [Char] -> Bool find_word (a:tail) word | a==word = True | otherwise = find_word tail word find_word [] word = False word_counter :: [[Char]] -> [Char] -> Integer word_counter list word = find_word_counter list word 0 find_word_counter :: [[Char]] -> [Char] -> Integer -> Integer find_word_counter (a:tail) word counter | a==word = find_word_counter tail word counter+1 | otherwise = find_word_counter tail word counter find_word_counter [] word counter = counter --count words from words table, ignore case with map count_words ((a):tail) dictionary = let dict = (insert_word dictionary (map toLower a)) in count_words tail dict count_words [] dictionary = dictionary --TRIM -- check if letter is in "special charater" group special_char letter | letter `elem` [',', '.', ':', '!', '?', ';'] = True | otherwise = False --trim from word special characters defined above trim_special word | special_char (last word) == True = trim_special (init word) | otherwise = word --trim special characters from words table trim_every_special ((a):tail) = [(trim_special a)] ++ trim_every_special tail trim_every_special [] = [] --word_to_lower :: [Char] -> [Char] word_to_lower word@(a:tail) = map toLower word -- converts "trim words from string" to ["trim", "words", "from", string"] --trim_words b = trim_every_special (words b) trim_words b = map word_to_lower (map trim_special (words b)) -- /TRIM dictionary_sum (word:tail) dict = if (find_word dict word)==False then [word] ++ dictionary_sum tail (dict++[word]) else dictionary_sum tail dict dictionary_sum [] dict = [] algebraic_string_sum string1 string2 = sort (dictionary_sum (trim_words string1 ++ trim_words string2) []) -- FIXIT -> Fractional elements string_vector (a:tail) string = [word_counter string a] ++ (string_vector tail string) string_vector [] string = [] -- absolute sum of vector elements get_vector_abs_sum (a:tail) = (abs a) + get_vector_abs_sum tail get_vector_abs_sum [] = 0 -- module of vector -> (sum of elements module) / vector length get_vector_module vector = (fromIntegral (get_vector_abs_sum vector)) / (fromIntegral (length vector)) -- curse of floating numbers isInt x = x == fromInteger (round x) --vector1 - vector2 vector_minus (a:tail) (b:tail2) = [a-b] ++ (vector_minus tail tail2) vector_minus [] [] = [] -- Vector * Scalar vector_times_scalar (a:tail) scalar = [ a * scalar ] ++ (vector_times_scalar tail scalar) vector_times_scalar [] scalar = [] --get_multipier_vector :: (Integral a, Fractional b) => [a] -> [a] -> [b] get_multipier_vector (a:tail) (b:tail2) = if (b/=0) then [ ceiling (fromIntegral a / fromIntegral b)] ++ get_multipier_vector tail tail2 else (get_multipier_vector tail tail2) get_multipier_vector [] [] = [0] -- returns (vector1 - x*vector2) linear_combination vector1 vector2 x = vector_minus vector1 (vector_times_scalar vector2 x) -- FOR get_x_factor FUNCTION --get_x :: Integral a => [a] -> [a] -> [a] -> a -> a get_x vector1@(v1:t1) vector2@(v2:t2) mul_vec@(a:tail) minimum | get_vector_module (linear_combination vector1 vector2 a)< get_vector_module (linear_combination vector1 vector2 minimum) = get_x vector1 vector2 tail a | otherwise = get_x vector1 vector2 tail minimum get_x (v1:t1) (v2:t2) [] minimum = minimum --get_x_factor :: (Fractional a, Integral a) => [a] -> [a] -> a get_x_factor [] [] = 0 get_x_factor vector1 vector2 = get_x vector1 vector2 mul_vec min where mul_vec = (get_multipier_vector vector1 vector2) min = mul_vec !! 0 --(vector_minus vector1 (vector_times_scalar vector2 (mul_vec !! 0))) --recipe -- get two strings: str1 str2 -- trim words from strings: trim_words -- create strings sum : algebraic_string_sum str1 str2 -- create string vector for str1 and str2: v1 = string_vector dict (trim_words str1) -- get_x_factor from v1 v2 : x = get_x_factor v1 v2 -- Podobienstwo = 1 - f(x)/f(0) podobienstwo string1 string2 = 1.0 - (get_vector_module (linear_combination v1 v2 x)) / (get_vector_module v1) where suma = (algebraic_string_sum string1 string2) -- longer-shorter for security reasons (for Integral x's) longer = if length string1>length string2 then string1 else string2 shorter = if length string1>length string2 then string2 else string1 v1 = string_vector suma (trim_words longer) v2 = string_vector suma (trim_words shorter) x = get_x_factor v1 v2 main :: IO() main = do putStrLn (show "Podaj dwa teksty") string1 <- getLine string2 <- getLine --readLn reads any type you want let suma = (algebraic_string_sum string1 string2) v1 = string_vector suma (trim_words string1) v2 = string_vector suma (trim_words string2) x = get_x_factor v1 v2 putStrLn (show "Requested data: ") putStrLn (show ("Algebraic, sorted sum of strings: " ++ show suma)) putStrLn (show (string1 ++ " <-- vector " ++ show v1)) putStrLn (show (string2 ++ " <-- vector " ++ show v2)) putStrLn (show ("Determined x factor : " ++ show x)) putStrLn (show ("For known value of x linear combination equals = " ++ show (linear_combination v1 v2 x))) putStrLn (show ("Calculated similarity : " ++ show ((podobienstwo string1 string2) * 100.0) ++ show "%"))
rybycy/HaskellStringSimilarity
projekt_extended.hs
Haskell
apache-2.0
5,465
{-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Web.Twitter.Conduit.Request.Internal where import Control.Lens import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as S8 import Data.Proxy import Data.Text (Text) import qualified Data.Text.Encoding as T import Data.Time.Calendar (Day) import GHC.OverloadedLabels import GHC.TypeLits import qualified Network.HTTP.Types as HT data Param label t = label := t type EmptyParams = ('[] :: [Param Symbol *]) type HasParam (label :: Symbol) (paramType :: *) (params :: [Param Symbol *]) = ParamType label params ~ paramType type family ParamType (label :: Symbol) (params :: [Param Symbol *]) :: * where ParamType label ((label ':= paramType) ': ks) = paramType ParamType label ((label' ':= paramType') ': ks) = ParamType label ks type APIQuery = [APIQueryItem] type APIQueryItem = (ByteString, PV) data PV = PVInteger { unPVInteger :: Integer } | PVBool { unPVBool :: Bool } | PVString { unPVString :: Text } | PVIntegerArray { unPVIntegerArray :: [Integer] } | PVStringArray { unPVStringArray :: [Text] } | PVDay { unPVDay :: Day } deriving (Show, Eq) class Parameters req where type SupportParameters req :: [Param Symbol *] params :: Lens' req APIQuery class ParameterValue a where wrap :: a -> PV unwrap :: PV -> a instance ParameterValue Integer where wrap = PVInteger unwrap = unPVInteger instance ParameterValue Bool where wrap = PVBool unwrap = unPVBool instance ParameterValue Text where wrap = PVString unwrap = unPVString instance ParameterValue [Integer] where wrap = PVIntegerArray unwrap = unPVIntegerArray instance ParameterValue [Text] where wrap = PVStringArray unwrap = unPVStringArray instance ParameterValue Day where wrap = PVDay unwrap = unPVDay makeSimpleQuery :: APIQuery -> HT.SimpleQuery makeSimpleQuery = traversed . _2 %~ paramValueBS paramValueBS :: PV -> ByteString paramValueBS (PVInteger i) = S8.pack . show $ i paramValueBS (PVBool True) = "true" paramValueBS (PVBool False) = "false" paramValueBS (PVString txt) = T.encodeUtf8 txt paramValueBS (PVIntegerArray iarr) = S8.intercalate "," $ map (S8.pack . show) iarr paramValueBS (PVStringArray iarr) = S8.intercalate "," $ map T.encodeUtf8 iarr paramValueBS (PVDay day) = S8.pack . show $ day rawParam :: (Parameters p, ParameterValue a) => ByteString -- ^ key -> Lens' p (Maybe a) rawParam key = lens getter setter where getter = preview $ params . to (lookup key) . _Just . to unwrap setter = flip (over params . replace key) replace k (Just v) = ((k, wrap v):) . dropAssoc k replace k Nothing = dropAssoc k dropAssoc k = filter ((/= k) . fst) instance ( Parameters req , ParameterValue a , KnownSymbol label , HasParam label a (SupportParameters req) , Functor f , lens ~ ((Maybe a -> f (Maybe a)) -> req -> f req)) => IsLabel label lens where #if MIN_VERSION_base(4, 10, 0) fromLabel = rawParam key #else fromLabel _ = rawParam key #endif where key = S8.pack (symbolVal (Proxy :: Proxy label))
Javran/twitter-conduit
Web/Twitter/Conduit/Request/Internal.hs
Haskell
bsd-2-clause
3,530
{-# LANGUAGE DeriveGeneric, DeriveDataTypeable, GeneralizedNewtypeDeriving #-} -- | Handling project configuration, types. -- module Distribution.Client.ProjectConfig.Types ( -- * Types for project config ProjectConfig(..), ProjectConfigBuildOnly(..), ProjectConfigShared(..), PackageConfig(..), -- * Resolving configuration SolverSettings(..), BuildTimeSettings(..), -- * Extra useful Monoids MapLast(..), MapMappend(..), ) where import Distribution.Client.Types ( RemoteRepo ) import Distribution.Client.Dependency.Types ( PreSolver ) import Distribution.Client.Targets ( UserConstraint ) import Distribution.Client.BuildReports.Types ( ReportLevel(..) ) import Distribution.Solver.Types.Settings import Distribution.Solver.Types.ConstraintSource import Distribution.Package ( PackageName, PackageId, UnitId, Dependency ) import Distribution.Version ( Version ) import Distribution.System ( Platform ) import Distribution.PackageDescription ( FlagAssignment, SourceRepo(..) ) import Distribution.Simple.Compiler ( Compiler, CompilerFlavor , OptimisationLevel(..), ProfDetailLevel, DebugInfoLevel(..) ) import Distribution.Simple.Setup ( Flag, AllowNewer(..), AllowOlder(..) ) import Distribution.Simple.InstallDirs ( PathTemplate ) import Distribution.Utils.NubList ( NubList ) import Distribution.Verbosity ( Verbosity ) import Data.Map (Map) import qualified Data.Map as Map import Distribution.Compat.Binary (Binary) import Distribution.Compat.Semigroup import GHC.Generics (Generic) ------------------------------- -- Project config types -- -- | This type corresponds directly to what can be written in the -- @cabal.project@ file. Other sources of configuration can also be injected -- into this type, such as the user-wide @~/.cabal/config@ file and the -- command line of @cabal configure@ or @cabal build@. -- -- Since it corresponds to the external project file it is an instance of -- 'Monoid' and all the fields can be empty. This also means there has to -- be a step where we resolve configuration. At a minimum resolving means -- applying defaults but it can also mean merging information from multiple -- sources. For example for package-specific configuration the project file -- can specify configuration that applies to all local packages, and then -- additional configuration for a specific package. -- -- Future directions: multiple profiles, conditionals. If we add these -- features then the gap between configuration as written in the config file -- and resolved settings we actually use will become even bigger. -- data ProjectConfig = ProjectConfig { -- | Packages in this project, including local dirs, local .cabal files -- local and remote tarballs. When these are file globs, they must -- match at least one package. projectPackages :: [String], -- | Like 'projectConfigPackageGlobs' but /optional/ in the sense that -- file globs are allowed to match nothing. The primary use case for -- this is to be able to say @optional-packages: */@ to automagically -- pick up deps that we unpack locally without erroring when -- there aren't any. projectPackagesOptional :: [String], -- | Packages in this project from remote source repositories. projectPackagesRepo :: [SourceRepo], -- | Packages in this project from hackage repositories. projectPackagesNamed :: [Dependency], -- See respective types for an explanation of what these -- values are about: projectConfigBuildOnly :: ProjectConfigBuildOnly, projectConfigShared :: ProjectConfigShared, -- | Configuration to be applied to *local* packages; i.e., -- any packages which are explicitly named in `cabal.project`. projectConfigLocalPackages :: PackageConfig, projectConfigSpecificPackage :: MapMappend PackageName PackageConfig } deriving (Eq, Show, Generic) -- | That part of the project configuration that only affects /how/ we build -- and not the /value/ of the things we build. This means this information -- does not need to be tracked for changes since it does not affect the -- outcome. -- data ProjectConfigBuildOnly = ProjectConfigBuildOnly { projectConfigVerbosity :: Flag Verbosity, projectConfigDryRun :: Flag Bool, projectConfigOnlyDeps :: Flag Bool, projectConfigSummaryFile :: NubList PathTemplate, projectConfigLogFile :: Flag PathTemplate, projectConfigBuildReports :: Flag ReportLevel, projectConfigReportPlanningFailure :: Flag Bool, projectConfigSymlinkBinDir :: Flag FilePath, projectConfigOneShot :: Flag Bool, projectConfigNumJobs :: Flag (Maybe Int), projectConfigKeepGoing :: Flag Bool, projectConfigOfflineMode :: Flag Bool, projectConfigKeepTempFiles :: Flag Bool, projectConfigHttpTransport :: Flag String, projectConfigIgnoreExpiry :: Flag Bool, projectConfigCacheDir :: Flag FilePath, projectConfigLogsDir :: Flag FilePath } deriving (Eq, Show, Generic) -- | Project configuration that is shared between all packages in the project. -- In particular this includes configuration that affects the solver. -- data ProjectConfigShared = ProjectConfigShared { projectConfigHcFlavor :: Flag CompilerFlavor, projectConfigHcPath :: Flag FilePath, projectConfigHcPkg :: Flag FilePath, projectConfigHaddockIndex :: Flag PathTemplate, -- Things that only make sense for manual mode, not --local mode -- too much control! --projectConfigUserInstall :: Flag Bool, --projectConfigInstallDirs :: InstallDirs (Flag PathTemplate), --TODO: [required eventually] decide what to do with InstallDirs -- currently we don't allow it to be specified in the config file --projectConfigPackageDBs :: [Maybe PackageDB], -- configuration used both by the solver and other phases projectConfigRemoteRepos :: NubList RemoteRepo, -- ^ Available Hackage servers. projectConfigLocalRepos :: NubList FilePath, -- solver configuration projectConfigConstraints :: [(UserConstraint, ConstraintSource)], projectConfigPreferences :: [Dependency], projectConfigCabalVersion :: Flag Version, --TODO: [required eventually] unused projectConfigSolver :: Flag PreSolver, projectConfigAllowOlder :: Maybe AllowOlder, projectConfigAllowNewer :: Maybe AllowNewer, projectConfigMaxBackjumps :: Flag Int, projectConfigReorderGoals :: Flag ReorderGoals, projectConfigCountConflicts :: Flag CountConflicts, projectConfigStrongFlags :: Flag StrongFlags -- More things that only make sense for manual mode, not --local mode -- too much control! --projectConfigIndependentGoals :: Flag Bool, --projectConfigShadowPkgs :: Flag Bool, --projectConfigReinstall :: Flag Bool, --projectConfigAvoidReinstalls :: Flag Bool, --projectConfigOverrideReinstall :: Flag Bool, --projectConfigUpgradeDeps :: Flag Bool } deriving (Eq, Show, Generic) -- | Project configuration that is specific to each package, that is where we -- can in principle have different values for different packages in the same -- project. -- data PackageConfig = PackageConfig { packageConfigProgramPaths :: MapLast String FilePath, packageConfigProgramArgs :: MapMappend String [String], packageConfigProgramPathExtra :: NubList FilePath, packageConfigFlagAssignment :: FlagAssignment, packageConfigVanillaLib :: Flag Bool, packageConfigSharedLib :: Flag Bool, packageConfigDynExe :: Flag Bool, packageConfigProf :: Flag Bool, --TODO: [code cleanup] sort out packageConfigProfLib :: Flag Bool, -- this duplication packageConfigProfExe :: Flag Bool, -- and consistency packageConfigProfDetail :: Flag ProfDetailLevel, packageConfigProfLibDetail :: Flag ProfDetailLevel, packageConfigConfigureArgs :: [String], packageConfigOptimization :: Flag OptimisationLevel, packageConfigProgPrefix :: Flag PathTemplate, packageConfigProgSuffix :: Flag PathTemplate, packageConfigExtraLibDirs :: [FilePath], packageConfigExtraFrameworkDirs :: [FilePath], packageConfigExtraIncludeDirs :: [FilePath], packageConfigGHCiLib :: Flag Bool, packageConfigSplitObjs :: Flag Bool, packageConfigStripExes :: Flag Bool, packageConfigStripLibs :: Flag Bool, packageConfigTests :: Flag Bool, packageConfigBenchmarks :: Flag Bool, packageConfigCoverage :: Flag Bool, packageConfigRelocatable :: Flag Bool, packageConfigDebugInfo :: Flag DebugInfoLevel, packageConfigRunTests :: Flag Bool, --TODO: [required eventually] use this packageConfigDocumentation :: Flag Bool, --TODO: [required eventually] use this packageConfigHaddockHoogle :: Flag Bool, --TODO: [required eventually] use this packageConfigHaddockHtml :: Flag Bool, --TODO: [required eventually] use this packageConfigHaddockHtmlLocation :: Flag String, --TODO: [required eventually] use this packageConfigHaddockExecutables :: Flag Bool, --TODO: [required eventually] use this packageConfigHaddockTestSuites :: Flag Bool, --TODO: [required eventually] use this packageConfigHaddockBenchmarks :: Flag Bool, --TODO: [required eventually] use this packageConfigHaddockInternal :: Flag Bool, --TODO: [required eventually] use this packageConfigHaddockCss :: Flag FilePath, --TODO: [required eventually] use this packageConfigHaddockHscolour :: Flag Bool, --TODO: [required eventually] use this packageConfigHaddockHscolourCss :: Flag FilePath, --TODO: [required eventually] use this packageConfigHaddockContents :: Flag PathTemplate --TODO: [required eventually] use this } deriving (Eq, Show, Generic) instance Binary ProjectConfig instance Binary ProjectConfigBuildOnly instance Binary ProjectConfigShared instance Binary PackageConfig -- | Newtype wrapper for 'Map' that provides a 'Monoid' instance that takes -- the last value rather than the first value for overlapping keys. newtype MapLast k v = MapLast { getMapLast :: Map k v } deriving (Eq, Show, Functor, Generic, Binary) instance Ord k => Monoid (MapLast k v) where mempty = MapLast Map.empty mappend = (<>) instance Ord k => Semigroup (MapLast k v) where MapLast a <> MapLast b = MapLast (flip Map.union a b) -- rather than Map.union which is the normal Map monoid instance -- | Newtype wrapper for 'Map' that provides a 'Monoid' instance that -- 'mappend's values of overlapping keys rather than taking the first. newtype MapMappend k v = MapMappend { getMapMappend :: Map k v } deriving (Eq, Show, Functor, Generic, Binary) instance (Semigroup v, Ord k) => Monoid (MapMappend k v) where mempty = MapMappend Map.empty mappend = (<>) instance (Semigroup v, Ord k) => Semigroup (MapMappend k v) where MapMappend a <> MapMappend b = MapMappend (Map.unionWith (<>) a b) -- rather than Map.union which is the normal Map monoid instance instance Monoid ProjectConfig where mempty = gmempty mappend = (<>) instance Semigroup ProjectConfig where (<>) = gmappend instance Monoid ProjectConfigBuildOnly where mempty = gmempty mappend = (<>) instance Semigroup ProjectConfigBuildOnly where (<>) = gmappend instance Monoid ProjectConfigShared where mempty = gmempty mappend = (<>) instance Semigroup ProjectConfigShared where (<>) = gmappend instance Monoid PackageConfig where mempty = gmempty mappend = (<>) instance Semigroup PackageConfig where (<>) = gmappend ---------------------------------------- -- Resolving configuration to settings -- -- | Resolved configuration for the solver. The idea is that this is easier to -- use than the raw configuration because in the raw configuration everything -- is optional (monoidial). In the 'BuildTimeSettings' every field is filled -- in, if only with the defaults. -- -- Use 'resolveSolverSettings' to make one from the project config (by -- applying defaults etc). -- data SolverSettings = SolverSettings { solverSettingRemoteRepos :: [RemoteRepo], -- ^ Available Hackage servers. solverSettingLocalRepos :: [FilePath], solverSettingConstraints :: [(UserConstraint, ConstraintSource)], solverSettingPreferences :: [Dependency], solverSettingFlagAssignment :: FlagAssignment, -- ^ For all local packages solverSettingFlagAssignments :: Map PackageName FlagAssignment, solverSettingCabalVersion :: Maybe Version, --TODO: [required eventually] unused solverSettingSolver :: PreSolver, solverSettingAllowOlder :: AllowOlder, solverSettingAllowNewer :: AllowNewer, solverSettingMaxBackjumps :: Maybe Int, solverSettingReorderGoals :: ReorderGoals, solverSettingCountConflicts :: CountConflicts, solverSettingStrongFlags :: StrongFlags -- Things that only make sense for manual mode, not --local mode -- too much control! --solverSettingIndependentGoals :: Bool, --solverSettingShadowPkgs :: Bool, --solverSettingReinstall :: Bool, --solverSettingAvoidReinstalls :: Bool, --solverSettingOverrideReinstall :: Bool, --solverSettingUpgradeDeps :: Bool } deriving (Eq, Show, Generic) instance Binary SolverSettings -- | Resolved configuration for things that affect how we build and not the -- value of the things we build. The idea is that this is easier to use than -- the raw configuration because in the raw configuration everything is -- optional (monoidial). In the 'BuildTimeSettings' every field is filled in, -- if only with the defaults. -- -- Use 'resolveBuildTimeSettings' to make one from the project config (by -- applying defaults etc). -- data BuildTimeSettings = BuildTimeSettings { buildSettingDryRun :: Bool, buildSettingOnlyDeps :: Bool, buildSettingSummaryFile :: [PathTemplate], buildSettingLogFile :: Maybe (Compiler -> Platform -> PackageId -> UnitId -> FilePath), buildSettingLogVerbosity :: Verbosity, buildSettingBuildReports :: ReportLevel, buildSettingReportPlanningFailure :: Bool, buildSettingSymlinkBinDir :: [FilePath], buildSettingOneShot :: Bool, buildSettingNumJobs :: Int, buildSettingKeepGoing :: Bool, buildSettingOfflineMode :: Bool, buildSettingKeepTempFiles :: Bool, buildSettingRemoteRepos :: [RemoteRepo], buildSettingLocalRepos :: [FilePath], buildSettingCacheDir :: FilePath, buildSettingHttpTransport :: Maybe String, buildSettingIgnoreExpiry :: Bool }
sopvop/cabal
cabal-install/Distribution/Client/ProjectConfig/Types.hs
Haskell
bsd-3-clause
16,126
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.AmountOfMoney.EN.IE.Rules ( rules ) where import Data.HashMap.Strict (HashMap) import Data.String import Data.Text (Text) import Prelude import Duckling.AmountOfMoney.Helpers import Duckling.AmountOfMoney.Types (Currency(..)) import Duckling.Numeral.Helpers (isPositive) import Duckling.Regex.Types import Duckling.Types import qualified Data.HashMap.Strict as HashMap import qualified Data.Text as Text import qualified Duckling.AmountOfMoney.Helpers as Helpers import qualified Duckling.Numeral.Types as TNumeral ruleAGrand :: Rule ruleAGrand = Rule { name = "a grand" , pattern = [ regex "a grand" ] , prod = \_ -> Just . Token AmountOfMoney . withValue 1000 $ currencyOnly Dollar } ruleGrand :: Rule ruleGrand = Rule { name = "<amount> grand" , pattern = [ Predicate isPositive , regex "grand" ] , prod = \case (Token Numeral TNumeral.NumeralData{TNumeral.value = v}:_) -> Just . Token AmountOfMoney . withValue (1000 * v) $ currencyOnly Dollar _ -> Nothing } ruleDollarCoin :: Rule ruleDollarCoin = Rule { name = "dollar coin" , pattern = [ regex "(nickel|dime|quarter)s?" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> do c <- HashMap.lookup (Text.toLower match) Helpers.dollarCoins Just . Token AmountOfMoney . withValue c $ currencyOnly Dollar _ -> Nothing } rules :: [Rule] rules = [ ruleAGrand , ruleGrand , ruleDollarCoin ]
facebookincubator/duckling
Duckling/AmountOfMoney/EN/IE/Rules.hs
Haskell
bsd-3-clause
1,829
module Renkon.Command.List ( run ) where import ClassyPrelude import Control.Lens.Operators import Formatting import Renkon.Config import Renkon.Util import System.Directory (doesDirectoryExist) import System.FilePath (getSearchPath) import System.FilePath.Find as FilePath run :: Config -> Bool -> IO () run config detail = do let root' = config ^. path . renkonRoot bin' = config ^. path . renkonBin onDirAbsence root' $ do withColor Red $ do fprint ("renkon root does not exist." % ln) withColor White $ do fprint (" " % string % ln) root' guard False fprint ("Available generators:" % ln) path' <- getSearchPath gens' <- sequence $ findRenconGenerator config <$> path' let displayItem = bool displayItemSimple displayItemDetail detail traverse_ (displayList (displayItem config)) gens' displayList :: (FilePath -> IO ()) -> [FilePath] -> IO () displayList displayItem xs = traverse_ displayItem xs displayItemSimple :: Config -> FilePath -> IO () displayItemSimple config exe = do withColor Green $ do fprint (indent 2 % string % ln) . (takeGeneratorName config) $ exe displayItemDetail :: Config -> FilePath -> IO () displayItemDetail config exe = do withColor Green $ do fprint (indent 2 % string % ln) . (takeGeneratorName config) $ exe withColor Yellow $ do fprint (indent 2 % string % ln) exe withColor White $ do traverse_ (fprint (indent 4 % stext % ln)) . lines =<< execute' exe ["--help"] fprint ln isRenconBinDir :: Config -> FindClause Bool isRenconBinDir config = isPrefixOf pre' <$> filePath where pre' = config ^. path . renkonBin isRenconGenerator :: Config -> FindClause Bool isRenconGenerator config = isPrefixOf pre' <$> fileName where pre' = unpack $ config ^. path . renkonPrefix findRenconGenerator :: Config -> FilePath -> IO [FilePath] findRenconGenerator config dir = do exists <- doesDirectoryExist dir if exists then FilePath.find (filePath ==? dir) (isRenconGenerator config) dir else return [] onDirAbsence :: (MonadIO m) => FilePath -> m () -> m () onDirAbsence dir action = do exists <- liftIO $ doesDirectoryExist dir when (not exists) $ do action
kayhide/renkon
src/Renkon/Command/List.hs
Haskell
bsd-3-clause
2,202
{-# LANGUAGE CPP, DefaultSignatures, EmptyDataDecls, FlexibleInstances, FunctionalDependencies, KindSignatures, ScopedTypeVariables, TypeOperators, UndecidableInstances, ViewPatterns, NamedFieldPuns, FlexibleContexts, PatternGuards, RecordWildCards, DataKinds, NoImplicitPrelude #-} {-# OPTIONS_GHC -fno-warn-orphans #-} #include "overlapping-compat.h" -- TODO: is it true or not that Generic instances might go into infinite -- loops when the type refers to itself in some field? If yes, we have to -- warn (and if not, we can mention that it's alright). Same for Template -- Haskell and mkParseJson, I guess. module Json.Internal.Generic () where import BasePrelude import Json.Internal.Instances import Json.Internal.Types import Json.Internal.Classes import Json.Internal.ValueParser import qualified Json.Internal.Encode.ByteString as E import Data.ByteString.Builder as B import Data.DList (DList) import qualified Data.Text as T import Data.Text (Text) import GHC.Generics import qualified Data.HashMap.Strict as H import qualified Data.Vector as V import qualified Data.Vector.Mutable as VM -------------------------------------------------------------------------------- -- Generic toJson and toEncoding instance OVERLAPPABLE_ (GToJson a) => GToJson (M1 i c a) where -- Meta-information, which is not handled elsewhere, is ignored: gToJson opts = gToJson opts . unM1 gToEncoding opts = gToEncoding opts . unM1 instance (ToJson a) => GToJson (K1 i a) where -- Constant values are encoded using their ToJson instance: gToJson _opts = toJson . unK1 gToEncoding _opts = toEncoding . unK1 instance GToJson U1 where -- Empty constructors are encoded to an empty array: gToJson _opts _ = Array mempty gToEncoding _opts _ = emptyArrayE instance (ConsToJson a) => GToJson (C1 c a) where -- Constructors need to be encoded differently depending on whether they're -- a record or not. This distinction is made by 'consToJson': gToJson opts = consToJson opts . unM1 gToEncoding opts = Encoding . consToEncoding opts . unM1 instance ( WriteProduct a, WriteProduct b , EncodeProduct a, EncodeProduct b , ProductSize a, ProductSize b ) => GToJson (a :*: b) where -- Products are encoded to an array. Here we allocate a mutable vector of -- the same size as the product and write the product's elements to it -- using 'writeProduct': gToJson opts p = Array $ V.create $ do mv <- VM.unsafeNew lenProduct writeProduct opts mv 0 lenProduct p return mv where lenProduct = (unTagged2 :: Tagged2 (a :*: b) Int -> Int) productSize gToEncoding opts p = Encoding $ B.char7 '[' <> encodeProduct opts p <> B.char7 ']' instance ( AllNullary (a :+: b) allNullary , SumToJson (a :+: b) allNullary ) => GToJson (a :+: b) where -- If all constructors of a sum datatype are nullary and the -- 'allNullaryToStringTag' option is set they are encoded to -- strings. This distinction is made by 'sumToJson': gToJson opts = (unTagged :: Tagged allNullary Json -> Json) . sumToJson opts gToEncoding opts = Encoding . (unTagged :: Tagged allNullary B.Builder -> B.Builder) . sumToEncoding opts -------------------------------------------------------------------------------- class SumToJson f allNullary where sumToJson :: Options -> f a -> Tagged allNullary Json sumToEncoding :: Options -> f a -> Tagged allNullary B.Builder -- TODO: rename TwoElemArrayObj, etc to not mention Obj instance ( GetConName f , TaggedObjectPairs f , ObjectWithSingleFieldObj f , TwoElemArrayObj f ) => SumToJson f True where sumToJson opts | allNullaryToStringTag opts = Tagged . String . T.pack . constructorTagModifier opts . getConName | otherwise = Tagged . nonAllNullarySumToJson opts sumToEncoding opts | allNullaryToStringTag opts = Tagged . builder . constructorTagModifier opts . getConName | otherwise = Tagged . nonAllNullarySumToEncoding opts instance ( TwoElemArrayObj f , TaggedObjectPairs f , ObjectWithSingleFieldObj f ) => SumToJson f False where sumToJson opts = Tagged . nonAllNullarySumToJson opts sumToEncoding opts = Tagged . nonAllNullarySumToEncoding opts nonAllNullarySumToJson :: ( TwoElemArrayObj f , TaggedObjectPairs f , ObjectWithSingleFieldObj f ) => Options -> f a -> Json nonAllNullarySumToJson opts = case sumEncoding opts of TaggedObject{..} -> object . taggedObjectPairs opts tagFieldName contentsFieldName ObjectWithSingleField -> Object . objectWithSingleFieldObj opts TwoElemArray -> Array . twoElemArrayObj opts nonAllNullarySumToEncoding :: ( TwoElemArrayObj f , TaggedObjectPairs f , ObjectWithSingleFieldObj f ) => Options -> f a -> B.Builder nonAllNullarySumToEncoding opts = case sumEncoding opts of TaggedObject{..} -> taggedObjectEnc opts tagFieldName contentsFieldName ObjectWithSingleField -> objectWithSingleFieldEnc opts TwoElemArray -> twoElemArrayEnc opts -------------------------------------------------------------------------------- class TaggedObjectPairs f where taggedObjectPairs :: Options -> String -> String -> f a -> [Pair] taggedObjectEnc :: Options -> String -> String -> f a -> B.Builder instance ( TaggedObjectPairs a , TaggedObjectPairs b ) => TaggedObjectPairs (a :+: b) where taggedObjectPairs opts tagFieldName contentsFieldName (L1 x) = taggedObjectPairs opts tagFieldName contentsFieldName x taggedObjectPairs opts tagFieldName contentsFieldName (R1 x) = taggedObjectPairs opts tagFieldName contentsFieldName x taggedObjectEnc opts tagFieldName contentsFieldName (L1 x) = taggedObjectEnc opts tagFieldName contentsFieldName x taggedObjectEnc opts tagFieldName contentsFieldName (R1 x) = taggedObjectEnc opts tagFieldName contentsFieldName x instance ( IsRecord a isRecord , TaggedObjectPairs' a isRecord , Constructor c ) => TaggedObjectPairs (C1 c a) where taggedObjectPairs opts tagFieldName contentsFieldName = (T.pack tagFieldName .= constructorTagModifier opts (conName (undefined :: t c a p)) :) . (unTagged :: Tagged isRecord [Pair] -> [Pair]) . taggedObjectPairs' opts contentsFieldName . unM1 taggedObjectEnc opts tagFieldName contentsFieldName v = B.char7 '{' <> (builder tagFieldName <> B.char7 ':' <> builder (constructorTagModifier opts (conName (undefined :: t c a p)))) <> B.char7 ',' <> ((unTagged :: Tagged isRecord B.Builder -> B.Builder) . taggedObjectEnc' opts contentsFieldName . unM1 $ v) <> B.char7 '}' class TaggedObjectPairs' f isRecord where taggedObjectPairs' :: Options -> String -> f a -> Tagged isRecord [Pair] taggedObjectEnc' :: Options -> String -> f a -> Tagged isRecord B.Builder instance (RecordToPairs f) => TaggedObjectPairs' f True where taggedObjectPairs' opts _ = Tagged . toList . recordToPairs opts taggedObjectEnc' opts _ = Tagged . fst . recordToEncoding opts instance (GToJson f) => TaggedObjectPairs' f False where taggedObjectPairs' opts contentsFieldName = Tagged . (:[]) . (T.pack contentsFieldName .=) . gToJson opts taggedObjectEnc' opts contentsFieldName = Tagged . (\z -> builder contentsFieldName <> B.char7 ':' <> z) . gbuilder opts -------------------------------------------------------------------------------- -- | Get the name of the constructor of a sum datatype. class GetConName f where getConName :: f a -> String instance (GetConName a, GetConName b) => GetConName (a :+: b) where getConName (L1 x) = getConName x getConName (R1 x) = getConName x instance (Constructor c) => GetConName (C1 c a) where getConName = conName -------------------------------------------------------------------------------- class TwoElemArrayObj f where twoElemArrayObj :: Options -> f a -> V.Vector Json twoElemArrayEnc :: Options -> f a -> B.Builder instance (TwoElemArrayObj a, TwoElemArrayObj b) => TwoElemArrayObj (a :+: b) where twoElemArrayObj opts (L1 x) = twoElemArrayObj opts x twoElemArrayObj opts (R1 x) = twoElemArrayObj opts x twoElemArrayEnc opts (L1 x) = twoElemArrayEnc opts x twoElemArrayEnc opts (R1 x) = twoElemArrayEnc opts x instance ( GToJson a, ConsToJson a , Constructor c ) => TwoElemArrayObj (C1 c a) where twoElemArrayObj opts x = V.create $ do mv <- VM.unsafeNew 2 VM.unsafeWrite mv 0 $ String $ T.pack $ constructorTagModifier opts $ conName (undefined :: t c a p) VM.unsafeWrite mv 1 $ gToJson opts x return mv twoElemArrayEnc opts x = E.brackets $ builder (constructorTagModifier opts (conName (undefined :: t c a p))) <> B.char7 ',' <> gbuilder opts x -------------------------------------------------------------------------------- class ConsToJson f where consToJson :: Options -> f a -> Json consToEncoding :: Options -> f a -> B.Builder class ConsToJson' f isRecord where consToJson' :: Options -> Bool -- ^ Are we a record with one field? -> f a -> Tagged isRecord Json consToEncoding' :: Options -> Bool -- ^ Are we a record with one field? -> f a -> Tagged isRecord B.Builder instance ( IsRecord f isRecord , ConsToJson' f isRecord ) => ConsToJson f where consToJson opts = (unTagged :: Tagged isRecord Json -> Json) . consToJson' opts (isUnary (undefined :: f a)) consToEncoding opts = (unTagged :: Tagged isRecord B.Builder -> B.Builder) . consToEncoding' opts (isUnary (undefined :: f a)) instance (RecordToPairs f) => ConsToJson' f True where consToJson' opts isUn f = do let vals = toList $ recordToPairs opts f -- Note that checking that vals has only 1 element is needed because it's -- possible that it would have 0 elements – for instance, when -- omitNothingFields is enabled and it's a Nothing field. Checking for -- 'isUn' is not enough. case (unwrapUnaryRecords opts, isUn, vals) of (True, True, [(_,val)]) -> Tagged val _ -> Tagged $ object vals consToEncoding' opts isUn x = do let (enc, mbVal) = recordToEncoding opts x case (unwrapUnaryRecords opts, isUn, mbVal) of (True, True, Just val) -> Tagged val _ -> Tagged $ B.char7 '{' <> enc <> B.char7 '}' instance GToJson f => ConsToJson' f False where consToJson' opts _ = Tagged . gToJson opts consToEncoding' opts _ = Tagged . gbuilder opts -------------------------------------------------------------------------------- class RecordToPairs f where recordToPairs :: Options -> f a -> DList Pair -- 1st element: whole thing -- 2nd element: in case the record has only 1 field, just the value -- of the field (without the key); 'Nothing' otherwise recordToEncoding :: Options -> f a -> (B.Builder, Maybe B.Builder) instance (RecordToPairs a, RecordToPairs b) => RecordToPairs (a :*: b) where recordToPairs opts (a :*: b) = recordToPairs opts a <> recordToPairs opts b recordToEncoding opts (a :*: b) = (fst (recordToEncoding opts a) <> B.char7 ',' <> fst (recordToEncoding opts b), Nothing) instance (Selector s, GToJson a) => RecordToPairs (S1 s a) where recordToPairs = fieldToPair recordToEncoding = fieldToEncoding instance OVERLAPPING_ (Selector s, ToJson a) => RecordToPairs (S1 s (K1 i (Maybe a))) where recordToPairs opts (M1 k1) | omitNothingFields opts , K1 Nothing <- k1 = empty recordToPairs opts m1 = fieldToPair opts m1 recordToEncoding opts (M1 k1) | omitNothingFields opts , K1 Nothing <- k1 = (mempty, Nothing) recordToEncoding opts m1 = fieldToEncoding opts m1 fieldToPair :: (Selector s, GToJson a) => Options -> S1 s a p -> DList Pair fieldToPair opts m1 = pure (T.pack $ fieldLabelModifier opts $ selName m1, gToJson opts (unM1 m1)) fieldToEncoding :: (Selector s, GToJson a) => Options -> S1 s a p -> (B.Builder, Maybe B.Builder) fieldToEncoding opts m1 = do let keyBuilder = builder (fieldLabelModifier opts $ selName m1) valueBuilder = gbuilder opts (unM1 m1) (keyBuilder <> B.char7 ':' <> valueBuilder, Just valueBuilder) -------------------------------------------------------------------------------- class WriteProduct f where writeProduct :: Options -> VM.MVector s Json -> Int -- ^ index -> Int -- ^ length -> f a -> ST s () instance ( WriteProduct a , WriteProduct b ) => WriteProduct (a :*: b) where writeProduct opts mv ix len (a :*: b) = do writeProduct opts mv ix lenL a writeProduct opts mv ixR lenR b where lenL = len `unsafeShiftR` 1 lenR = len - lenL ixR = ix + lenL instance OVERLAPPABLE_ (GToJson a) => WriteProduct a where writeProduct opts mv ix _ = VM.unsafeWrite mv ix . gToJson opts -------------------------------------------------------------------------------- class EncodeProduct f where encodeProduct :: Options -> f a -> B.Builder instance ( EncodeProduct a , EncodeProduct b ) => EncodeProduct (a :*: b) where encodeProduct opts (a :*: b) = encodeProduct opts a <> B.char7 ',' <> encodeProduct opts b instance OVERLAPPABLE_ (GToJson a) => EncodeProduct a where encodeProduct opts = gbuilder opts -------------------------------------------------------------------------------- class ObjectWithSingleFieldObj f where objectWithSingleFieldObj :: Options -> f a -> Object objectWithSingleFieldEnc :: Options -> f a -> B.Builder instance ( ObjectWithSingleFieldObj a , ObjectWithSingleFieldObj b ) => ObjectWithSingleFieldObj (a :+: b) where objectWithSingleFieldObj opts (L1 x) = objectWithSingleFieldObj opts x objectWithSingleFieldObj opts (R1 x) = objectWithSingleFieldObj opts x objectWithSingleFieldEnc opts (L1 x) = objectWithSingleFieldEnc opts x objectWithSingleFieldEnc opts (R1 x) = objectWithSingleFieldEnc opts x instance ( GToJson a, ConsToJson a , Constructor c ) => ObjectWithSingleFieldObj (C1 c a) where objectWithSingleFieldObj opts = H.singleton typ . gToJson opts where typ = T.pack $ constructorTagModifier opts $ conName (undefined :: t c a p) objectWithSingleFieldEnc opts v = B.char7 '{' <> builder (constructorTagModifier opts (conName (undefined :: t c a p))) <> B.char7 ':' <> gbuilder opts v <> B.char7 '}' gbuilder :: GToJson f => Options -> f a -> Builder gbuilder opts = fromEncoding . gToEncoding opts -------------------------------------------------------------------------------- -- Generic parseJson instance OVERLAPPABLE_ (GFromJson a) => GFromJson (M1 i c a) where -- Meta-information, which is not handled elsewhere, is just added to the -- parsed value: gParseJson opts = M1 <$> gParseJson opts instance (FromJson a) => GFromJson (K1 i a) where -- Constant values are decoded using their FromJson instance: gParseJson _opts = K1 <$> parseJson instance GFromJson U1 where -- Empty constructors are expected to be encoded as an empty array: gParseJson _opts = withArray "unit constructor (U1)" $ do checkLength 0 return U1 instance (ConsFromJson a) => GFromJson (C1 c a) where -- Constructors need to be decoded differently depending on whether they're -- a record or not. This distinction is made by consParseJson: gParseJson opts = M1 <$> consParseJson opts instance ( FromProduct a, FromProduct b , ProductSize a, ProductSize b ) => GFromJson (a :*: b) where -- Products are expected to be encoded to an array. Here we check whether we -- got an array of the same size as the product, then parse each of the -- product's elements using parseProduct: gParseJson opts = withArray "product (:*:)" $ do let lenProduct = (unTagged2 :: Tagged2 (a :*: b) Int -> Int) productSize checkLength lenProduct parseProduct opts 0 lenProduct instance (AllNullary (a :+: b) allNullary, ParseSum (a :+: b) allNullary) => GFromJson (a :+: b) where -- If all constructors of a sum datatype are nullary and the -- 'allNullaryToStringTag' option is set they are expected to be -- encoded as strings. This distinction is made by 'parseSum': gParseJson opts = unT (parseSum opts) where unT :: Tagged allNullary (Parser Json ((a :+: b) d)) -> Parser Json ((a :+: b) d) unT = unTagged -------------------------------------------------------------------------------- class ParseSum f allNullary where parseSum :: Options -> Tagged allNullary (Parser Json (f a)) instance ( SumFromString (a :+: b) , FromPair (a :+: b) , FromTaggedObject (a :+: b) ) => ParseSum (a :+: b) True where parseSum opts | allNullaryToStringTag opts = Tagged (parseAllNullarySum opts) | otherwise = Tagged (parseNonAllNullarySum opts) instance ( FromPair (a :+: b) , FromTaggedObject (a :+: b) ) => ParseSum (a :+: b) False where parseSum opts = Tagged (parseNonAllNullarySum opts) -------------------------------------------------------------------------------- parseAllNullarySum :: SumFromString f => Options -> Parser Json (f a) parseAllNullarySum opts = do key <- getString "" maybe (notFound $ T.unpack key) return $ parseSumFromString opts key class SumFromString f where parseSumFromString :: Options -> Text -> Maybe (f a) instance (SumFromString a, SumFromString b) => SumFromString (a :+: b) where parseSumFromString opts key = (L1 <$> parseSumFromString opts key) <|> (R1 <$> parseSumFromString opts key) instance (Constructor c) => SumFromString (C1 c U1) where parseSumFromString opts key | key == name = Just $ M1 U1 | otherwise = Nothing where name = T.pack $ constructorTagModifier opts $ conName (undefined :: t c U1 p) -------------------------------------------------------------------------------- parseNonAllNullarySum :: (FromPair (a :+: b), FromTaggedObject (a :+: b)) => Options -> Parser Json ((a :+: b) c) parseNonAllNullarySum opts = case sumEncoding opts of TaggedObject{..} -> withObject "" $ do tag <- field (T.pack tagFieldName) fromMaybe (notFound $ T.unpack tag) $ parseFromTaggedObject opts contentsFieldName tag ObjectWithSingleField -> -- TODO: rename “withSingleton” to “inSingleton” or something? since it's -- different from withArray or withObject withSingleton "" $ \tagKey -> do fromMaybe (notFound $ T.unpack tagKey) $ parsePair opts tagKey TwoElemArray -> withArray "" $ do checkLength 2 -- TODO: rename “with” to “inside”? or something that doesn't clash -- with lens tag <- with (unsafeElementAt 0) $ getString "" with (unsafeElementAt 1) $ fromMaybe (notFound $ T.unpack tag) $ parsePair opts tag -------------------------------------------------------------------------------- class FromTaggedObject f where parseFromTaggedObject :: Options -> String -> Text -> Maybe (Parser Object (f a)) instance (FromTaggedObject a, FromTaggedObject b) => FromTaggedObject (a :+: b) where parseFromTaggedObject opts contentsFieldName tag = (fmap L1 <$> parseFromTaggedObject opts contentsFieldName tag) <|> (fmap R1 <$> parseFromTaggedObject opts contentsFieldName tag) instance ( FromTaggedObject' f , Constructor c ) => FromTaggedObject (C1 c f) where parseFromTaggedObject opts contentsFieldName tag | tag == name = Just $ M1 <$> parseFromTaggedObject' opts contentsFieldName | otherwise = Nothing where name = T.pack $ constructorTagModifier opts $ conName (undefined :: t c f p) -------------------------------------------------------------------------------- class FromTaggedObject' f where parseFromTaggedObject' :: Options -> String -> Parser Object (f a) class FromTaggedObject'' f isRecord where parseFromTaggedObject'' :: Options -> String -> Tagged isRecord (Parser Object (f a)) instance ( IsRecord f isRecord , FromTaggedObject'' f isRecord ) => FromTaggedObject' f where parseFromTaggedObject' opts contentsFieldName = unT (parseFromTaggedObject'' opts contentsFieldName) where unT :: Tagged isRecord (Parser Object (f a)) -> Parser Object (f a) unT = unTagged instance (FromRecord f) => FromTaggedObject'' f True where parseFromTaggedObject'' opts _ = Tagged (parseRecord opts Nothing) instance (GFromJson f) => FromTaggedObject'' f False where parseFromTaggedObject'' opts contentsFieldName = Tagged (with (field (T.pack contentsFieldName)) (gParseJson opts)) -------------------------------------------------------------------------------- class ConsFromJson f where consParseJson :: Options -> Parser Json (f a) class ConsFromJson' f isRecord where consParseJson' :: Options -> Maybe Text -- ^ A dummy label ('Nothing' to use proper label) -> Tagged isRecord (Parser Json (f a)) instance (IsRecord f isRecord, ConsFromJson' f isRecord) => ConsFromJson f where consParseJson opts = do v <- getInput let useDummy = unwrapUnaryRecords opts && isUnary (undefined :: f a) dummyObject = object [(T.pack "dummy", v)] dummyLabel = Just (T.pack "dummy") if useDummy then unT $ (`apply` dummyObject) <$> consParseJson' opts dummyLabel else unT $ (`apply` v) <$> consParseJson' opts Nothing where unT :: Tagged isRecord (Parser Json (f a)) -> Parser Json (f a) unT = unTagged instance (FromRecord f) => ConsFromJson' f True where consParseJson' opts mlab = Tagged (withObject "record (:*:)" $ parseRecord opts mlab) instance (GFromJson f) => ConsFromJson' f False where consParseJson' opts _ = Tagged (gParseJson opts) -------------------------------------------------------------------------------- class FromRecord f where parseRecord :: Options -> Maybe Text -- ^ A dummy label ('Nothing' to use proper label) -> Parser Object (f a) instance (FromRecord a, FromRecord b) => FromRecord (a :*: b) where parseRecord opts _ = (:*:) <$> parseRecord opts Nothing <*> parseRecord opts Nothing instance (Selector s, GFromJson a) => FromRecord (S1 s a) where parseRecord opts mbLab = with (field lab) (gParseJson opts) where selLabel = fieldLabelModifier opts $ selName (undefined :: t s a p) lab = fromMaybe (T.pack selLabel) mbLab instance OVERLAPPING_ (Selector s, FromJson a) => FromRecord (S1 s (K1 i (Maybe a))) where parseRecord opts mbLab = (M1 . K1) <$> optionalField lab where selLabel = fieldLabelModifier opts $ selName (undefined :: t s (K1 i (Maybe a)) p) lab = fromMaybe (T.pack selLabel) mbLab -------------------------------------------------------------------------------- class ProductSize f where productSize :: Tagged2 f Int instance (ProductSize a, ProductSize b) => ProductSize (a :*: b) where productSize = Tagged2 $ unTagged2 (productSize :: Tagged2 a Int) + unTagged2 (productSize :: Tagged2 b Int) instance ProductSize (S1 s a) where productSize = Tagged2 1 -------------------------------------------------------------------------------- class FromProduct f where parseProduct :: Options -> Int -> Int -> Parser Array (f a) instance (FromProduct a, FromProduct b) => FromProduct (a :*: b) where parseProduct opts ix len = (:*:) <$> parseProduct opts ix lenL <*> parseProduct opts ixR lenR where lenL = len `unsafeShiftR` 1 ixR = ix + lenL lenR = len - lenL instance (GFromJson a) => FromProduct (S1 s a) where parseProduct opts ix _ = with (unsafeElementAt ix) $ gParseJson opts -------------------------------------------------------------------------------- class FromPair f where parsePair :: Options -> Text -> Maybe (Parser Json (f a)) instance (FromPair a, FromPair b) => FromPair (a :+: b) where parsePair opts tag = (fmap L1 <$> parsePair opts tag) <|> (fmap R1 <$> parsePair opts tag) instance (Constructor c, GFromJson a, ConsFromJson a) => FromPair (C1 c a) where parsePair opts tag | tag == tag' = Just (gParseJson opts) | otherwise = Nothing where tag' = T.pack $ constructorTagModifier opts $ conName (undefined :: t c a p) -------------------------------------------------------------------------------- class IsRecord (f :: * -> *) isRecord | f -> isRecord where isUnary :: f a -> Bool isUnary = const True instance (IsRecord f isRecord) => IsRecord (f :*: g) isRecord where isUnary = const False #if MIN_VERSION_base(4,9,0) instance OVERLAPPING_ IsRecord (M1 S ('MetaSel 'Nothing u ss ds) f) False #else instance OVERLAPPING_ IsRecord (M1 S NoSelector f) False #endif instance (IsRecord f isRecord) => IsRecord (M1 S c f) isRecord instance IsRecord (K1 i c) True instance IsRecord U1 False where isUnary = const False -------------------------------------------------------------------------------- class AllNullary (f :: * -> *) allNullary | f -> allNullary instance ( AllNullary a allNullaryL , AllNullary b allNullaryR , And allNullaryL allNullaryR allNullary ) => AllNullary (a :+: b) allNullary instance AllNullary a allNullary => AllNullary (M1 i c a) allNullary instance AllNullary (a :*: b) False instance AllNullary (K1 i c) False instance AllNullary U1 True -------------------------------------------------------------------------------- data True data False class And bool1 bool2 bool3 | bool1 bool2 -> bool3 instance And True True True instance And False False False instance And False True False instance And True False False -------------------------------------------------------------------------------- newtype Tagged s b = Tagged {unTagged :: b} instance Functor (Tagged s) where fmap f (Tagged x) = Tagged (f x) {-# INLINE fmap #-} newtype Tagged2 (s :: * -> *) b = Tagged2 {unTagged2 :: b} -------------------------------------------------------------------------------- notFound :: String -> Parser x a notFound key = fail $ "The key \"" ++ key ++ "\" was not found" {-# INLINE notFound #-} builder :: ToJson a => a -> Builder builder = fromEncoding . toEncoding
aelve/json-x
lib/Json/Internal/Generic.hs
Haskell
bsd-3-clause
27,487
{-# LANGUAGE TemplateHaskell #-} module Quid2Pkg (Quid2Pkg(..)) where -- import Types import Test.Data import qualified Types as T import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L ( ByteString ,unpack,pack) import Quid2.HRT.Class.Serialize as Class.Serialize -- import Class.Serialize import Quid2.HRT.Data.Serialize import Quid2.HRT.Prelude data Quid2Pkg a = Quid2Pkg a deriving (Eq,Show) instance Serialize a => T.Serialize (Quid2Pkg a) where serialize (Quid2Pkg a) = L.pack . B.unpack . encode $ a deserialize = either (Left . error) (Right . Quid2Pkg) . decode . B.pack . L.unpack t = T.ser $ Quid2Pkg tree1 deriveSerialize ''Bool deriveSerialize ''Tree deriveSerialize ''Car deriveSerialize ''Acceleration deriveSerialize ''Consumption deriveSerialize ''Model deriveSerialize ''OptionalExtra deriveSerialize ''Engine
tittoassini/flat
benchmarks/PkgHRT.hs
Haskell
bsd-3-clause
871
module Problem61 where -- -- Problem 61: Cyclical figurate numbers -- -- Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers -- are all figurate (polygonal) numbers and are generated by the following formulae: -- -- Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ... -- Square P4,n=n^2 1, 4, 9, 16, 25, ... -- Pentagonal P5,n=n(3n−1)/2 1, 5, 12, 22, 35, ... -- Hexagonal P6,n=n(2n−1) 1, 6, 15, 28, 45, ... -- Heptagonal P7,n=n(5n−3)/2 1, 7, 18, 34, 55, ... -- Octagonal P8,n=n(3n−2) 1, 8, 21, 40, 65, ... -- -- The ordered set of three 4-digit numbers: 8128, 2882, 8281, has three -- interesting properties. -- -- 1. The set is cyclic, in that the last two digits of each number is the first -- two digits of the next number (including the last number with the first). -- 2. Each polygonal type: triangle (P3,127=8128), square (P4,91=8281), and -- pentagonal (P5,44=2882), is represented by a different number in the set. -- 3. This is the only set of 4-digit numbers with this property. -- -- Find the sum of the only ordered set of six cyclic 4-digit numbers for which -- each polygonal type: triangle, square, pentagonal, hexagonal, heptagonal, -- and octagonal, is represented by a different number in the set. problem61 :: Int problem61 = sum $ head $ cycleOptions initialCandidates [] pFn :: [Int -> Int] pFn = [ \n -> n*(n+1) `div` 2 , \n -> n*n , \n -> n*(3*n-1) `div` 2 , \n -> n*(2*n-1) , \n -> n*(5*n-3) `div` 2 , \n -> n*(3*n-2) ] initialCandidates = fourDigits . flip map [1..] <$> pFn splits xs = flip splitAt xs <$> [0..length xs-1] bottom x = x `mod` 100 top x = x `div` 100 cycleOptions :: [[Int]] -> [Int] -> [[Int]] cycleOptions [] path -- Link first and last of path | bottom (head path) == top (last path) = [reverse path] | otherwise = [] -- Start considering all numbers, in all columns of candidates cycleOptions ps [] = concatMap go $ splits ps where go (h, p:t) = concatMap (cycleOptions (h ++ t) . (:[])) p -- Given the head of the path (x), match numbers from all columns, -- whose top matches the bottom of x. cycleOptions ps path@(x:_) = concatMap go $ splits ps where hasPrefix y = top y == bottom x go (h, p:t) = concatMap (cycleOptions (h ++ t) . (:path)) $ filter hasPrefix p -- Assumes xs is a sorted (possibly infinite) list. fourDigits :: [Int] -> [Int] fourDigits = takeWhile (< 10^4) . dropWhile (< 10^3)
c0deaddict/project-euler
src/Part2/Problem61.hs
Haskell
bsd-3-clause
2,434
module CardDeck ( Deck, createOrderedDeck, getCard, getCards ) where import Card import qualified Data.Vector as V type CardVector = V.Vector Card data Deck = Deck CardVector deriving Show getCard :: Deck -> Int -> Card getCard (Deck xs) n = xs V.! n getCards :: Deck -> [Card] getCards (Deck v) = V.toList v createOrderedDeck :: Deck createOrderedDeck = Deck $ V.fromList createListOfCards createListOfCards :: [Card] createListOfCards = [mkCard r s | r <- [Two .. Ace], s <- [Heart .. Spade]]
fffej/HS-Poker
CardDeck.hs
Haskell
bsd-3-clause
525
module HudsonTest where import Text.ParserCombinators.Parsec import HudsonParser import Test.HUnit import HudsonPreproc (parseResult) param a b c = Just Param {ref = a, paramName = b, paramType = c} func a b c = Just FuncDecl {funcName = a, funcParams = b, funcCode = c} testParamSimple = "Simple param" ~: param False "param" Nothing ~=? parseResult parseParam "param" testParamRef = "Param with a ref" ~: param True "param_3A" Nothing ~=? parseResult parseParam "ref param_3A" testParamType = "Param with a ref and type" ~: param True "param_3A" (Just "Type") ~=? parseResult parseParam "ref param_3A : Type" testParamNewline = "Param with a bad newline" ~: Nothing ~=? parseResult parseParam "\nref" paramTests = TestLabel "param Tests" $ TestList [testParamSimple, testParamRef, testParamType, testParamNewline] testFuncSimple = "Simple Func" ~: func "simple" [] [BlockStmt $ Return $ Just $ LiteralInt 2] ~=? parseResult parseFuncDecl "function simple () is\n return 2" funcTests = TestLabel "func Tests" $ TestList [testFuncSimple] allTests = TestList [paramTests, funcTests] main = runTestTT allTests
jschaf/hudson-dev
src/Language/Hudson/HudsonTest.hs
Haskell
bsd-3-clause
1,314
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Numeral.ES.Rules ( rules ) where import qualified Data.HashMap.Strict as HashMap import Data.Maybe import qualified Data.Text as Text import Prelude import Data.String import Duckling.Dimensions.Types import Duckling.Numeral.Helpers import Duckling.Numeral.Types (NumeralData (..)) import qualified Duckling.Numeral.Types as TNumeral import Duckling.Regex.Types import Duckling.Types ruleNumeralsPrefixWithNegativeOrMinus :: Rule ruleNumeralsPrefixWithNegativeOrMinus = Rule { name = "numbers prefix with -, negative or minus" , pattern = [ regex "-|menos" , dimension Numeral ] , prod = \tokens -> case tokens of (_:Token Numeral (NumeralData {TNumeral.value = v}):_) -> double $ v * (- 1) _ -> Nothing } ruleIntegerNumeric :: Rule ruleIntegerNumeric = Rule { name = "integer (numeric)" , pattern = [ regex "(\\d{1,18})" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> do v <- parseInt match integer $ toInteger v _ -> Nothing } ruleDecimalWithThousandsSeparator :: Rule ruleDecimalWithThousandsSeparator = Rule { name = "decimal with thousands separator" , pattern = [ regex "(\\d+(\\.\\d\\d\\d)+,\\d+)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> let dot = Text.singleton '.' comma = Text.singleton ',' fmt = Text.replace comma dot $ Text.replace dot Text.empty match in parseDouble fmt >>= double _ -> Nothing } ruleDecimalNumeral :: Rule ruleDecimalNumeral = Rule { name = "decimal number" , pattern = [ regex "(\\d*,\\d+)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> parseDecimal False match _ -> Nothing } byTensMap :: HashMap.HashMap Text.Text Integer byTensMap = HashMap.fromList [ ( "veinte" , 20 ) , ( "treinta" , 30 ) , ( "cuarenta" , 40 ) , ( "cincuenta" , 50 ) , ( "sesenta" , 60 ) , ( "setenta" , 70 ) , ( "ochenta" , 80 ) , ( "noventa" , 90 ) ] ruleNumeral2 :: Rule ruleNumeral2 = Rule { name = "number (20..90)" , pattern = [ regex "(veinte|treinta|cuarenta|cincuenta|sesenta|setenta|ochenta|noventa)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> HashMap.lookup (Text.toLower match) byTensMap >>= integer _ -> Nothing } zeroToFifteenMap :: HashMap.HashMap Text.Text Integer zeroToFifteenMap = HashMap.fromList [ ( "zero" , 0 ) , ( "cero" , 0 ) , ( "un" , 1 ) , ( "una" , 1 ) , ( "uno" , 1 ) , ( "dos" , 2 ) , ( "tr\x00e9s" , 3 ) , ( "tres" , 3 ) , ( "cuatro" , 4 ) , ( "cinco" , 5 ) , ( "seis" , 6 ) , ( "s\x00e9is" , 6 ) , ( "siete" , 7 ) , ( "ocho" , 8 ) , ( "nueve" , 9 ) , ( "diez" , 10 ) , ( "dies" , 10 ) , ( "once" , 11 ) , ( "doce" , 12 ) , ( "trece" , 13 ) , ( "catorce" , 14 ) , ( "quince" , 15 ) ] ruleNumeral :: Rule ruleNumeral = Rule { name = "number (0..15)" , pattern = [ regex "((c|z)ero|un(o|a)?|dos|tr(\x00e9|e)s|cuatro|cinco|s(e|\x00e9)is|siete|ocho|nueve|die(z|s)|once|doce|trece|catorce|quince)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> HashMap.lookup (Text.toLower match) zeroToFifteenMap >>= integer _ -> Nothing } sixteenToTwentyNineMap :: HashMap.HashMap Text.Text Integer sixteenToTwentyNineMap = HashMap.fromList [ ( "dieciseis" , 16 ) , ( "diesis\x00e9is" , 16 ) , ( "diesiseis" , 16 ) , ( "diecis\x00e9is" , 16 ) , ( "diecisiete" , 17 ) , ( "dieciocho" , 18 ) , ( "diecinueve" , 19 ) , ( "veintiuno" , 21 ) , ( "veintiuna" , 21 ) , ( "veintidos" , 22 ) , ( "veintitr\x00e9s" , 23 ) , ( "veintitres" , 23 ) , ( "veinticuatro" , 24 ) , ( "veinticinco" , 25 ) , ( "veintis\x00e9is" , 26 ) , ( "veintiseis" , 26 ) , ( "veintisiete" , 27 ) , ( "veintiocho" , 28 ) , ( "veintinueve" , 29 ) ] ruleNumeral5 :: Rule ruleNumeral5 = Rule { name = "number (16..19 21..29)" , pattern = [ regex "(die(c|s)is(\x00e9|e)is|diecisiete|dieciocho|diecinueve|veintiun(o|a)|veintidos|veintitr(\x00e9|e)s|veinticuatro|veinticinco|veintis(\x00e9|e)is|veintisiete|veintiocho|veintinueve)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> HashMap.lookup (Text.toLower match) sixteenToTwentyNineMap >>= integer _ -> Nothing } ruleNumeral3 :: Rule ruleNumeral3 = Rule { name = "number (16..19)" , pattern = [ numberWith TNumeral.value (== 10) , regex "y" , numberBetween 6 10 ] , prod = \tokens -> case tokens of (_:_:Token Numeral (NumeralData {TNumeral.value = v}):_) -> double $ 10 + v _ -> Nothing } ruleNumeralsSuffixesKMG :: Rule ruleNumeralsSuffixesKMG = Rule { name = "numbers suffixes (K, M, G)" , pattern = [ dimension Numeral , regex "([kmg])(?=[\\W\\$\x20ac]|$)" ] , prod = \tokens -> case tokens of (Token Numeral (NumeralData {TNumeral.value = v}): Token RegexMatch (GroupMatch (match:_)): _) -> case Text.toLower match of "k" -> double $ v * 1e3 "m" -> double $ v * 1e6 "g" -> double $ v * 1e9 _ -> Nothing _ -> Nothing } oneHundredToThousandMap :: HashMap.HashMap Text.Text Integer oneHundredToThousandMap = HashMap.fromList [ ( "cien" , 100 ) , ( "cientos" , 100 ) , ( "ciento" , 100 ) , ( "doscientos" , 200 ) , ( "trescientos" , 300 ) , ( "cuatrocientos" , 400 ) , ( "quinientos" , 500 ) , ( "seiscientos" , 600 ) , ( "setecientos" , 700 ) , ( "ochocientos" , 800 ) , ( "novecientos" , 900 ) , ( "mil" , 1000 ) ] ruleNumeral6 :: Rule ruleNumeral6 = Rule { name = "number 100..1000 " , pattern = [ regex "(cien(to)?s?|doscientos|trescientos|cuatrocientos|quinientos|seiscientos|setecientos|ochocientos|novecientos|mil)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> HashMap.lookup (Text.toLower match) oneHundredToThousandMap >>= integer _ -> Nothing } ruleNumeral4 :: Rule ruleNumeral4 = Rule { name = "number (21..29 31..39 41..49 51..59 61..69 71..79 81..89 91..99)" , pattern = [ oneOf [70, 20, 60, 50, 40, 90, 30, 80] , regex "y" , numberBetween 1 10 ] , prod = \tokens -> case tokens of (Token Numeral (NumeralData {TNumeral.value = v1}): _: Token Numeral (NumeralData {TNumeral.value = v2}): _) -> double $ v1 + v2 _ -> Nothing } ruleNumerals :: Rule ruleNumerals = Rule { name = "numbers 200..999" , pattern = [ numberBetween 2 10 , numberWith TNumeral.value (== 100) , numberBetween 0 100 ] , prod = \tokens -> case tokens of (Token Numeral (NumeralData {TNumeral.value = v1}): _: Token Numeral (NumeralData {TNumeral.value = v2}): _) -> double $ 100 * v1 + v2 _ -> Nothing } ruleNumeralDotNumeral :: Rule ruleNumeralDotNumeral = Rule { name = "number dot number" , pattern = [ dimension Numeral , regex "punto" , numberWith TNumeral.grain isNothing ] , prod = \tokens -> case tokens of (Token Numeral (NumeralData {TNumeral.value = v1}): _: Token Numeral (NumeralData {TNumeral.value = v2}): _) -> double $ v1 + decimalsToDouble v2 _ -> Nothing } ruleIntegerWithThousandsSeparator :: Rule ruleIntegerWithThousandsSeparator = Rule { name = "integer with thousands separator ." , pattern = [ regex "(\\d{1,3}(\\.\\d\\d\\d){1,5})" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> parseDouble (Text.replace (Text.singleton '.') Text.empty match) >>= double _ -> Nothing } rules :: [Rule] rules = [ ruleDecimalNumeral , ruleDecimalWithThousandsSeparator , ruleIntegerNumeric , ruleIntegerWithThousandsSeparator , ruleNumeral , ruleNumeral2 , ruleNumeral3 , ruleNumeral4 , ruleNumeral5 , ruleNumeral6 , ruleNumeralDotNumeral , ruleNumerals , ruleNumeralsPrefixWithNegativeOrMinus , ruleNumeralsSuffixesKMG ]
rfranek/duckling
Duckling/Numeral/ES/Rules.hs
Haskell
bsd-3-clause
8,586
{-# OPTIONS_GHC -fno-warn-orphans #-} module Ed25519 ( benchmarks -- :: IO [Benchmark] ) where import Criterion.Main import Crypto.Key import Crypto.Sign.Ed25519 import Control.DeepSeq import qualified Data.ByteString as B import Util () instance NFData (SecretKey t) instance NFData (PublicKey t) benchmarks :: IO [Benchmark] benchmarks = do keys@(pk,sk) <- createKeypair let dummy = B.replicate 512 3 msg = sign sk dummy return [ bench "keypair" $ nfIO createKeypair , bench "sign" $ nf (sign sk) dummy , bench "verify" $ nf (verify pk) msg , bench "roundtrip" $ nf (signBench keys) dummy ] signBench :: (PublicKey Ed25519, SecretKey Ed25519) -> B.ByteString -> Bool signBench (pk, sk) xs = verify pk (sign sk xs)
thoughtpolice/hs-nacl
benchmarks/Ed25519.hs
Haskell
bsd-3-clause
874
{-# LANGUAGE ScopedTypeVariables, QuasiQuotes, TemplateHaskell, MultiParamTypeClasses, FlexibleInstances #-} module NestedPatMatch where import Data.Maybe import Language.XHaskell [xh| data Foo = Foo (Star Bar) deriving Show data Bar = Bar deriving Show f :: Foo -> Choice Foo () f (Foo (x :: Bar)) = Foo x f (Foo (x :: (Star Bar))) = () mapStar :: (a -> b) -> Star a -> Star b mapStar (f :: a -> b) = \x -> case x of { (x :: ()) -> x ; (x :: a, xs :: Star a) -> (f x, mapStar f xs) } g :: Star Foo -> Star Foo g (xs :: (Star Foo)) = (mapStar f xs) mapStar' :: (Foo -> Choice Foo ()) -> Star Foo -> Star (Choice Foo ()) mapStar' (f :: Foo -> Choice Foo ()) = \x -> case x of { (x :: ()) -> x ; (x :: Foo, xs :: Star Foo) -> (f x, mapStar' f xs) } |] {- *NestedPatMatch> f (Foo [Bar]) Left (Foo [Bar]) *NestedPatMatch> f (Foo []) Right () -}
luzhuomi/xhaskell
test/NestedPatMatch.hs
Haskell
bsd-3-clause
898
import Graphics.Efl.Simple import Control.Monad (when) import Paths_graphics_efl main :: IO () main = do initWindowingSystem engines <- getEngines putStrLn (show engines) let engine = if "opengl_x11" `elem` engines then Just "opengl_x11" else Nothing withDefaultWindow engine $ \ win canvas -> do engineName <- getEngineName win putStrLn $ "Using engine " ++ engineName setWindowTitle "Simple Haskell-EFL Example" win bgfile <- getDataFileName "examples/data/Red_Giant_Earth_warm.jpg" inTxt <- addText canvas |> setText "Your text: " |> resize 200 10 |> move 25 200 |> setTextStyle (TextStylePlain,TextStyleShadowDirectionBottomRight) |> setTextFont ("DejaVu",14) |> setObjectColor (255,255,255,255) |> enableEventPassing |> uncover -- bg <- addFilledImage canvas bg <- addRectangle canvas |> setImageFile bgfile Nothing |> setObjectColor (0,0,0,255) |> setLayer (-1) |> uncover |> setFocus True |> onKeyDown (\ _ ev -> do name <- keyDownKeyName ev old <- getText inTxt new <- case name of "Escape" -> quitMainLoop >> return old "BackSpace" -> return $ if null old then old else init old _ -> (old ++) <$> keyDownString ev setText new inTxt ) onWindowResize win $ do (_,_,w,h) <- getWindowGeometry win resize w h bg let clickHandler obj ev = do name <- getName obj btn <- mouseDownButton ev putStrLn $ "You clicked on " ++ name ++ " with button " ++ show btn r <- addRectangle canvas |> setName "First rectangle" |> resize 100 40 |> move 20 40 |> setObjectColor (255,0,0,255) |> uncover |> onMouseDown clickHandler |> onMouseMove (\_ _ -> putStrLn "Move!") r2 <- addRectangle canvas |> setName "Second rectangle" |> resize 100 40 |> move 100 100 |> setObjectColor (128,128,0,128) |> uncover |> onMouseIn (\_ ev -> do wxy <- mouseInWorldXY ev cxy <- mouseInCanvasXY ev t <- mouseInTimestamp ev putStrLn (show wxy ++ ";" ++ show cxy ++ ";" ++ show t)) |> onMouseDown clickHandler |> onMouseOut (\ _ _-> putStrLn "Out!") |> onMouseUp (\ _ _-> putStrLn "Up!") |> onMouseWheel (\ _ _-> putStrLn "Wheel!") let poly :: Int -> Double -> [(Coord,Coord)] poly n w = [(round $ x*w, round $ y*w) | (x,y) <- (map cos angles `zip` map sin angles)] where angles :: [Double] angles = map ((*c) . fromIntegral) [0..(n-1)] c = 2.0 * pi / fromIntegral n po <- addPolygon canvas |> addPolygonPoints (poly 8 10) |> setObjectColor (128,128,128,255) |> move 200 200 |> uncover style <- createTextBlockStyle |> configureTextBlockStyle "DEFAULT='font=DejaVuSans-Bold font_size=26 align=center color=#000000 wrap=word style=soft_outline outline_color=#3779cb' NewLine= '+\n'" _ <- addTextBlock canvas |> setTextBlockStyle style |> setTextBlockTextMarkup "Welcome to the <b>Haskell-EFL</b> demo!!!" |> resize 500 400 |> move 300 10 |> setObjectColor (255,255,255,255) |> enableEventPassing |> uncover let lipsum = "In this demo, you can:<br/>\ \ - click on objects (with any button)<br/>\ \ - scroll this text with the mouse wheel<br/>\ \ - enter some text<br/>\ \<br/><br/>\ \Press \"Escape\" to quit\ \" style2 <- createTextBlockStyle |> configureTextBlockStyle "DEFAULT='font=DejaVuSans-Bold font_size=20 align=left color=#000000 wrap=word style=soft_shadow shadow_color=#CCCCCC' NewLine= '+\n'" lipsumTxt <- addTextBlock canvas |> setTextBlockStyle style2 |> setTextBlockTextMarkup lipsum |> resize 500 400 |> move 20 400 |> enableEventPassing |> uncover flip onMouseWheel bg $ \ _ ev -> do dir <- mouseWheelDirection ev off <- mouseWheelOffset ev (x,y,_,_) <- getGeometry lipsumTxt when (dir == 0) $ move x (y + fromIntegral (-10 * off)) lipsumTxt when (dir == 1) $ move (x + fromIntegral (10 * off)) y lipsumTxt let center o = do (x,y,w,h) <- getGeometry o return (w `div` 2 + x, h `div` 2 + y) --setAnimatorFrameRate 4 (cx,cy) <- center r addAnimationLinear' 1.0 Nothing $ \step -> do m <- createMap 4 |> populateMapPointsFromObject r |> rotateMap (360.0 * step) (fromIntegral cx) (fromIntegral cy) setMap m r enableMap r anim <- addAnimationLinear 4.0 Nothing $ \step -> do (cx',cy') <- center r2 m <- createMap 4 |> populateMapPointsFromObject r2 |> rotateMap (360.0 * step) (fromIntegral cx') (fromIntegral cy') setMap m r2 enableMap r2 flip onMouseDown r2 $ \ _ _ -> freezeAnimator anim flip onMouseUp r2 $ \ _ _ -> thawAnimator anim addAnimationLinear' 3.0 (Just 1) $ \step -> do let x' = (100+(floor $ step * 200)) move x' 100 r2 addAnimationBounce' 4 Nothing $ \step -> do let x' = (100+(floor $ step * 400)) (_,y,_,_) <- getGeometry po move x' y po addAnimationSinusoidal' 6 8.0 Nothing $ \step -> do let y' = (200+(floor $ step * 100)) (x,_,_,_) <- getGeometry po move x y' po return ()
hsyl20/graphics-efl
examples/Simple.hs
Haskell
bsd-3-clause
6,156
------------------------------------------------------------------------ -- | -- Module : ALife.Creatur.Wain.AudioID.Experiment -- Copyright : (c) Amy de Buitléir 2012-2016 -- License : BSD-style -- Maintainer : amy@nualeargais.ie -- Stability : experimental -- Portability : portable -- -- A data mining agent, designed for the Créatúr framework. -- ------------------------------------------------------------------------ {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE Rank2Types #-} module ALife.Creatur.Wain.AudioID.Experiment ( PatternWain, randomPatternWain, PatternTweaker(..), run, finishRound, schemaQuality, printStats, versionInfo, idealPopControlDeltaE -- exported for testing only ) where import ALife.Creatur (agentId, isAlive, programVersion) import ALife.Creatur.Task (checkPopSize) import qualified ALife.Creatur.Wain as W import qualified ALife.Creatur.Wain.Audio.Wain as AW import ALife.Creatur.Wain.AudioID.Action (Action(..), correct, correctActions) import ALife.Creatur.Wain.Audio.Pattern (Pattern, mkAudio) import ALife.Creatur.Wain.Audio.PatternDB (PatternDB, anyPattern) import ALife.Creatur.Wain.Audio.Tweaker (PatternTweaker(..)) import qualified ALife.Creatur.Wain.AudioID.Universe as U import ALife.Creatur.Wain.Brain (makeBrain, predictor, scenarioReport, responseReport, decisionReport) import ALife.Creatur.Wain.Checkpoint (enforceAll) import qualified ALife.Creatur.Wain.Classifier as Cl import ALife.Creatur.Wain.Muser (makeMuser) import qualified ALife.Creatur.Wain.Predictor as P import ALife.Creatur.Wain.GeneticSOM (RandomLearningParams(..), randomLearningFunction, schemaQuality, modelMap) import qualified ALife.Creatur.Wain.Audio.Object as O import ALife.Creatur.Wain.Pretty (pretty) import ALife.Creatur.Wain.Raw (raw) import ALife.Creatur.Wain.Response (Response, _action, _outcomes) import ALife.Creatur.Wain.SimpleResponseTweaker (ResponseTweaker(..)) import ALife.Creatur.Wain.UnitInterval (uiToDouble) import qualified ALife.Creatur.Wain.Statistics as Stats import ALife.Creatur.Persistent (putPS, getPS) import ALife.Creatur.Wain.PersistentStatistics (updateStats, readStats, clearStats) import ALife.Creatur.Wain.Statistics (summarise) import ALife.Creatur.Wain.Weights (makeWeights) import Control.Conditional (whenM) import Control.Lens hiding (universe) import Control.Monad (when, unless) import Control.Monad.IO.Class (liftIO) import Control.Monad.Random (Rand, RandomGen, getRandomR, getRandomRs, getRandom, evalRandIO, fromList) import Control.Monad.State.Lazy (StateT, execStateT, evalStateT, get, put) import Data.List (intercalate, sortBy) import Data.Map (toList) import Data.Ord (comparing) import Data.Version (showVersion) import Data.Word (Word64) import Paths_exp_audio_id_wains (version) import System.Directory (createDirectoryIfMissing) import System.FilePath (dropFileName) versionInfo :: String versionInfo = "exp-audio-id-wains-" ++ showVersion version ++ ", compiled with " ++ AW.packageVersion ++ ", " ++ W.packageVersion ++ ", " ++ ALife.Creatur.programVersion type PatternWain = W.Wain Pattern PatternTweaker (ResponseTweaker Action) Action randomPatternWain :: RandomGen r => String -> U.Universe PatternWain -> Word64 -> Word64 -> Rand r PatternWain randomPatternWain wName u classifierSize predictorSize = do let fcp = RandomLearningParams { _r0Range = view U.uClassifierR0Range u, _rfRange = view U.uClassifierRfRange u, _tfRange = view U.uClassifierTfRange u } fc <- randomLearningFunction fcp classifierThreshold <- getRandomR (view U.uClassifierThresholdRange u) let c = Cl.buildClassifier fc classifierSize classifierThreshold PatternTweaker let fdp = RandomLearningParams { _r0Range = view U.uPredictorR0Range u, _rfRange = view U.uPredictorRfRange u, _tfRange = view U.uPredictorTfRange u } fd <- randomLearningFunction fdp predictorThreshold <- getRandomR (view U.uPredictorThresholdRange u) let p = P.buildPredictor fd predictorSize predictorThreshold ResponseTweaker -- TODO: Allow a range of random weights -- hw <- (makeWeights . take 3) <$> getRandomRs unitInterval let hw = makeWeights [0.7, 0.3, 0, 0.1] t <- getRandom s <- getRandomR (view U.uStrictnessRange u) dp <- getRandomR $ view U.uDepthRange u dos <- take 4 <$> getRandomRs (view U.uDefaultOutcomeRange u) let (Right mr) = makeMuser dos dp ios <- take 4 <$> getRandomRs (view U.uImprintOutcomeRange u) rds <- take 4 <$> getRandomRs (view U.uReinforcementDeltasRange u) let (Right wBrain) = makeBrain c mr p hw t s ios rds wDevotion <- getRandomR . view U.uDevotionRange $ u wAgeOfMaturity <- getRandomR . view U.uMaturityRange $ u wPassionDelta <- getRandomR . view U.uPassionDeltaRange $ u let wBoredomDelta = 0 let n = (view U.uNumVectors u)*(view U.uVectorLength u) let wAppearance = mkAudio $ replicate n 0 return $ W.buildWainAndGenerateGenome wName wAppearance wBrain wDevotion wAgeOfMaturity wPassionDelta wBoredomDelta data Summary = Summary { _rPopSize :: Int, _rMetabolismDeltaE :: Double, _rPopControlDeltaE :: Double, _rCatDeltaE :: Double, _rFlirtingDeltaE :: Double, _rMatingDeltaE :: Double, _rOldAgeDeltaE :: Double, _rOtherMatingDeltaE :: Double, _rNetDeltaE :: Double, _rChildNetDeltaE :: Double, _rDeltaEToReflectOn :: Double, _rDeltaPToReflectOn :: Double, _rDeltaHToReflectOn :: Double, _rErr :: Double, _rBirthCount :: Int, _rWeanCount :: Int, _rCatCount :: Int, _rFlirtCount :: Int, _rMateCount :: Int, _rDeathCount :: Int, _rMistakeCount :: Int } makeLenses ''Summary initSummary :: Int -> Summary initSummary p = Summary { _rPopSize = p, _rMetabolismDeltaE = 0, _rPopControlDeltaE = 0, _rCatDeltaE = 0, _rFlirtingDeltaE = 0, _rMatingDeltaE = 0, _rOldAgeDeltaE = 0, _rOtherMatingDeltaE = 0, _rNetDeltaE = 0, _rChildNetDeltaE = 0, _rDeltaEToReflectOn = 0, _rDeltaPToReflectOn = 0, _rDeltaHToReflectOn = 0, _rErr = 0, _rBirthCount = 0, _rWeanCount = 0, _rCatCount = 0, _rFlirtCount = 0, _rMateCount = 0, _rDeathCount = 0, _rMistakeCount = 0 } summaryStats :: Summary -> [Stats.Statistic] summaryStats r = [ Stats.dStat "pop. size" (view rPopSize r), Stats.dStat "adult metabolism Δe" (view rMetabolismDeltaE r), Stats.dStat "adult pop. control Δe" (view rPopControlDeltaE r), Stats.dStat "cat Δe" (view rCatDeltaE r), Stats.dStat "flirting Δe" (view rFlirtingDeltaE r), Stats.dStat "adult mating Δe" (view rMatingDeltaE r), Stats.dStat "adult old age Δe" (view rOldAgeDeltaE r), Stats.dStat "other adult mating Δe" (view rOtherMatingDeltaE r), Stats.dStat "adult net Δe" (view rNetDeltaE r), Stats.dStat "child net Δe" (view rChildNetDeltaE r), Stats.dStat "Δe to reflect on" (view rDeltaEToReflectOn r), Stats.dStat "Δp to reflect on" (view rDeltaPToReflectOn r), Stats.dStat "Δh to reflect on" (view rDeltaHToReflectOn r), Stats.dStat "err" (view rErr r), Stats.iStat "bore" (view rBirthCount r), Stats.iStat "weaned" (view rWeanCount r), Stats.iStat "classified" (view rCatCount r), Stats.iStat "flirted" (view rFlirtCount r), Stats.iStat "mated" (view rMateCount r), Stats.iStat "died" (view rDeathCount r), Stats.iStat "mistakes" (view rMistakeCount r) ] data Experiment = Experiment { _subject :: PatternWain, _other :: O.Object Action (ResponseTweaker Action), _weanlings :: [PatternWain], _universe :: U.Universe PatternWain, _summary :: Summary } makeLenses ''Experiment finishRound :: FilePath -> StateT (U.Universe PatternWain) IO () finishRound f = do xss <- readStats f let yss = summarise xss printStats yss let zs = concat yss adjustPopControlDeltaE zs cs <- use U.uCheckpoints enforceAll zs cs clearStats f (a, b) <- use U.uAllowedPopulationRange checkPopSize (a, b) report :: String -> StateT Experiment IO () report = zoom universe . U.writeToLog run :: [PatternWain] -> StateT (U.Universe PatternWain) IO [PatternWain] run (me:otherWain:xs) = do when (null xs) $ U.writeToLog "WARNING: Last two wains standing!" p <- U.popSize u <- get x <- liftIO $ chooseObject (view U.uFrequencies u) otherWain (view U.uPatternDB u) let e = Experiment { _subject = me, _other = x, _weanlings = [], _universe = u, _summary = initSummary p} e' <- liftIO $ execStateT run' e put (view universe e') let modifiedAgents = O.addIfWain (view other e') $ view subject e' : view weanlings e' U.writeToLog $ "Modified agents: " ++ show (map agentId modifiedAgents) reportAnyDeaths modifiedAgents return modifiedAgents run _ = error "too few wains" run' :: StateT Experiment IO () run' = do t <- zoom universe U.currentTime if (t < 100) then imprintCorrectAction else runNormal runNormal :: StateT Experiment IO () runNormal = do (e0, ec0) <- totalEnergy a <- use subject report $ "---------- " ++ agentId a ++ "'s turn ----------" report $ "At beginning of turn, " ++ agentId a ++ "'s summary: " ++ pretty (Stats.stats a) runMetabolism autoPopControl <- use (universe . U.uPopControl) when autoPopControl applyPopControl r <- chooseSubjectAction wainBeforeAction <- use subject runAction (_action r) letSubjectReflect wainBeforeAction r subject %= W.autoAdjustPassion subject %= W.incAge a' <- use subject -- assign (summary.rNetDeltaE) (energy a' - energy a) unless (isAlive a') $ assign (summary.rDeathCount) 1 summary %= fillInSummary (ef, ecf) <- totalEnergy balanceEnergyEquation e0 ec0 ef ecf updateChildren killIfTooOld agentStats <- ((Stats.stats a' ++) . summaryStats) <$> use summary report $ "At end of turn, " ++ agentId a ++ "'s summary: " ++ pretty agentStats rsf <- use (universe . U.uRawStatsFile) zoom universe $ writeRawStats (agentId a) rsf agentStats sf <- use (universe . U.uStatsFile) zoom universe $ updateStats agentStats sf fillInSummary :: Summary -> Summary fillInSummary s = s { _rNetDeltaE = _rMetabolismDeltaE s + _rPopControlDeltaE s + _rCatDeltaE s + _rFlirtingDeltaE s + _rMatingDeltaE s + _rOldAgeDeltaE s + _rOtherMatingDeltaE s, _rChildNetDeltaE = 0 -- include energy given to wains when they are born - _rMatingDeltaE s - _rOtherMatingDeltaE s } balanceEnergyEquation :: Double -> Double -> Double -> Double -> StateT Experiment IO () balanceEnergyEquation e0 ec0 ef ecf = do netDeltaE1 <- use (summary . rNetDeltaE) let netDeltaE2 = ef - e0 let err = abs (netDeltaE1 - netDeltaE2) when (err > 0.000001) $ do report $ "WARNING: Adult energy equation doesn't balance" report $ "e0=" ++ show e0 ++ ", ef=" ++ show ef ++ ", netDeltaE2=" ++ show netDeltaE2 ++ ", netDeltaE1=" ++ show netDeltaE1 ++ ", err=" ++ show err childNetDeltaE1 <- use (summary . rChildNetDeltaE) let childNetDeltaE2 = ecf - ec0 let childErr = abs (childNetDeltaE1 - childNetDeltaE2) when (childErr > 0.000001) $ do report $ "WARNING: Child energy equation doesn't balance" report $ "ec0=" ++ show ec0 ++ ", ecf=" ++ show ecf ++ ", childNetDeltaE2=" ++ show childNetDeltaE2 ++ ", childNetDeltaE1=" ++ show childNetDeltaE1 ++ ", childErr=" ++ show childErr runMetabolism :: StateT Experiment IO () runMetabolism = do a <- use subject bmc <- use (universe . U.uBaseMetabolismDeltaE) cpcm <- use (universe . U.uEnergyCostPerClassifierModel) ccf <- use (universe . U.uChildCostFactor) let deltaE = AW.metabCost bmc cpcm 1 a + sum (map (AW.metabCost bmc cpcm ccf) (view W.litter a)) AW.adjustEnergy subject deltaE rMetabolismDeltaE "metab." summary report chooseSubjectAction :: StateT Experiment IO (Response Action) chooseSubjectAction = do a <- use subject obj <- use other (r, a') <- zoom universe $ chooseAction3 a obj assign subject a' return r chooseAction3 :: PatternWain -> O.Object Action (ResponseTweaker Action) -> StateT (U.Universe PatternWain) IO (Response Action, PatternWain) chooseAction3 w obj = do whenM (use U.uShowPredictorModels) $ do U.writeToLog "begin predictor models" describeModels w U.writeToLog "end predictor models" let (ldss, sps, rplos, aohs, r, w') = W.chooseAction [O.objectAppearance obj] w whenM (use U.uGenFmris) --writeFmri w (mapM_ U.writeToLog . AW.describeClassifierModels $ w) whenM (use U.uShowScenarioReport) $ do U.writeToLog "begin scenario report" mapM_ U.writeToLog $ scenarioReport sps U.writeToLog "end scenario report" whenM (use U.uShowResponseReport) $ do U.writeToLog "begin response report" mapM_ U.writeToLog $ responseReport rplos U.writeToLog "end response report" whenM (use U.uShowDecisionReport) $ do U.writeToLog "begin decision report" mapM_ U.writeToLog $ decisionReport aohs U.writeToLog "end decision report" let bmuInfo = formatBMUs . map fst . sortBy (comparing snd) . head $ ldss U.writeToLog $ agentId w ++ " sees " ++ O.objectId obj ++ ", classifies it as " ++ bmuInfo ++ " and chooses to " ++ show (_action r) ++ " predicting the outcomes " ++ show (_outcomes r) return (r, w') describeModels :: PatternWain -> StateT (U.Universe PatternWain) IO () describeModels w = mapM_ (U.writeToLog . f) ms where ms = toList . modelMap . view (W.brain . predictor) $ w f (l, r) = view W.name w ++ "'s predictor model " ++ show l ++ "=" ++ pretty r formatBMUs :: [Cl.Label] -> String formatBMUs (cBMU:cBMU2:_) = show cBMU ++ " (alt. " ++ show cBMU2 ++ ")" formatBMUs (cBMU:_) = show cBMU formatBMUs _ = error "no BMUs" chooseObject :: [Rational] -> PatternWain -> PatternDB -> IO (O.Object Action (ResponseTweaker Action)) chooseObject freqs w db = do (img1, audioId1) <- evalStateT anyPattern db fromList $ zip [O.PObject img1 audioId1, O.AObject w] freqs runAction :: Action -> StateT Experiment IO () -- -- Flirt -- runAction Flirt = do applyFlirtationEffects obj <- use other unless (O.isPattern obj) flirt (summary.rFlirtCount) += 1 -- -- Categorise -- runAction a = do obj <- use other let n = O.objectNum obj deltaE <- if correct a n then use (universe . U.uCorrectDeltaE) else use (universe . U.uIncorrectDeltaE) AW.adjustEnergy subject deltaE rCatDeltaE "audio ID" summary report (summary.rCatCount) += 1 -- -- Utility functions -- applyPopControl :: StateT Experiment IO () applyPopControl = do deltaE <- zoom (universe . U.uPopControlDeltaE) getPS AW.adjustEnergy subject deltaE rPopControlDeltaE "pop. control" summary report flirt :: StateT Experiment IO () flirt = do a <- use subject (O.AObject b) <- use other babyName <- zoom universe U.genName (a':b':_, msgs, aMatingDeltaE, bMatingDeltaE) <- liftIO . evalRandIO $ W.mate a b babyName if null msgs then do report $ agentId a ++ " and " ++ agentId b ++ " mated" report $ "Contribution to child: " ++ agentId a ++ "'s share is " ++ show aMatingDeltaE ++ " " ++ agentId b ++ "'s share is " ++ show bMatingDeltaE assign subject a' assign other (O.AObject b') recordBirths (summary . rMatingDeltaE) += aMatingDeltaE (summary . rOtherMatingDeltaE) += bMatingDeltaE (summary . rMateCount) += 1 else mapM_ report msgs recordBirths :: StateT Experiment IO () recordBirths = do a <- use subject (summary.rBirthCount) += length (view W.litter a) applyFlirtationEffects :: StateT Experiment IO () applyFlirtationEffects = do deltaE <- use (universe . U.uFlirtingDeltaE) report $ "Applying flirtation energy adjustment" AW.adjustEnergy subject deltaE rFlirtingDeltaE "flirting" summary report (summary.rFlirtCount) += 1 updateChildren :: StateT Experiment IO () updateChildren = do (a:matureChildren) <- W.weanMatureChildren <$> use subject assign subject a (a':deadChildren) <- W.pruneDeadChildren <$> use subject assign subject a' assign weanlings (matureChildren ++ deadChildren) (summary.rWeanCount) += length matureChildren killIfTooOld :: StateT Experiment IO () killIfTooOld = do a <- view W.age <$> use subject maxAge <- use (universe . U.uMaxAge) when (fromIntegral a > maxAge) $ AW.adjustEnergy subject (-100) rOldAgeDeltaE "old age" summary report adjustPopControlDeltaE :: [Stats.Statistic] -> StateT (U.Universe PatternWain) IO () adjustPopControlDeltaE xs = unless (null xs) $ do let (Just average) = Stats.lookup "avg. energy" xs let (Just total) = Stats.lookup "total energy" xs budget <- use U.uEnergyBudget pop <- U.popSize let c = idealPopControlDeltaE average total budget pop U.writeToLog $ "Current avg. energy = " ++ show average U.writeToLog $ "Current total energy = " ++ show total U.writeToLog $ "energy budget = " ++ show budget U.writeToLog $ "Adjusted pop. control Δe = " ++ show c zoom U.uPopControlDeltaE $ putPS c -- TODO: Make the 0.8 configurable idealPopControlDeltaE :: Double -> Double -> Double -> Int -> Double idealPopControlDeltaE average total budget pop | average < 0.8 = (budget - total) / (fromIntegral pop) | otherwise = 0.8 - average totalEnergy :: StateT Experiment IO (Double, Double) totalEnergy = do a <- fmap uiToDouble $ view W.energy <$> use subject b <- fmap uiToDouble $ O.objectEnergy <$> use other d <- W.childEnergy <$> use subject e <- O.objectChildEnergy <$> use other return (a + b, d + e) printStats :: [[Stats.Statistic]] -> StateT (U.Universe PatternWain) IO () printStats = mapM_ f where f xs = U.writeToLog $ "Summary - " ++ intercalate "," (map pretty xs) letSubjectReflect :: PatternWain -> Response Action -> StateT Experiment IO () letSubjectReflect wBefore r = do w <- use subject obj <- use other let p = O.objectAppearance obj let energyBefore = view W.energy wBefore let passionBefore = view W.passion wBefore let happinessBefore = W.happiness wBefore energyAfter <- use (subject . W.energy) passionAfter <- use (subject . W.passion) happinessAfter <- W.happiness <$> use subject let deltaH = uiToDouble happinessAfter - uiToDouble happinessBefore assign (summary . rDeltaEToReflectOn) (uiToDouble energyAfter - uiToDouble energyBefore) assign (summary . rDeltaPToReflectOn) (uiToDouble passionAfter - uiToDouble passionBefore) assign (summary . rDeltaHToReflectOn) deltaH let (w', err) = W.reflect [p] r wBefore w assign subject w' assign (summary . rErr) err if (correct (_action r) (O.objectNum obj)) then report $ agentId w ++ "'s choice to " ++ show (_action r) ++ " (with) " ++ O.objectId obj ++ " was correct" else do report $ agentId w ++ "'s choice to " ++ show (_action r) ++ " (with) " ++ O.objectId obj ++ " was wrong" (summary . rMistakeCount) += 1 imprintCorrectAction :: StateT Experiment IO () imprintCorrectAction = do w <- use subject obj <- use other let p = O.objectAppearance obj let a = correctActions !! (O.objectNum obj) report $ "Teaching " ++ agentId w ++ " that correct action for " ++ O.objectId obj ++ " is " ++ show a let (_, _, _, _, w') = W.imprint [p] a w assign subject w' writeRawStats :: String -> FilePath -> [Stats.Statistic] -> StateT (U.Universe PatternWain) IO () writeRawStats n f xs = do liftIO $ createDirectoryIfMissing True (dropFileName f) t <- U.currentTime liftIO . appendFile f $ "time=" ++ show t ++ ",agent=" ++ n ++ ',':raw xs ++ "\n" reportAnyDeaths :: [PatternWain] -> StateT (U.Universe PatternWain) IO () reportAnyDeaths ws = mapM_ f ws where f w = when (not . isAlive $ w) $ U.writeToLog (agentId w ++ " dead at age " ++ show (view W.age w))
mhwombat/exp-audio-id-wains
src/ALife/Creatur/Wain/AudioID/Experiment.hs
Haskell
bsd-3-clause
20,431
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} module System.HFind.Expr.Eval ( Eval , EvalContext , UninitializedVariableException(..) , RuntimeVar(..) , ctxGetVarValues, ctxGetActiveMatch, ctxGetBacktrace, ctxGetBakerContext , newContext , runEvalT , wrapEvalT , readonly , getVarValue , setVarValue , getCaptureValue , setCaptures , evalWithin ) where import Control.Exception (Exception, throw) import Control.Monad.Trans.Except (throwE) import Control.Monad.Catch (MonadThrow, MonadCatch, catchAll) import Control.Monad.Except import Control.Monad.Reader import Control.Monad.Morph import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.ICU as ICU import Data.Vector.Mutable (IOVector) import qualified Data.Vector as V import qualified Data.Vector.Mutable as MV import Data.Void (Void) import Unsafe.Coerce (unsafeCoerce) import System.HFind.Expr.Types (Name, TypedName(..), ErasedValue(..), Value, eraseType, RxCaptureMode(..)) import System.HFind.Expr.Baker (VarId) import qualified System.HFind.Expr.Baker as Baker import qualified System.HFind.Expr.Error as Err data EvalContext = EvalContext { ctxValues :: !(IOVector (Value Void)) -- reversed , ctxActiveMatch :: !(IORef (Maybe ICU.Match)) , ctxBacktrace :: !(IORef Err.Backtrace) , ctxBakerContext :: !Baker.BakingContext } instance Show EvalContext where show _ = "<ctx>" data UninitializedVariableException = UninitializedVariableException deriving (Eq, Show) instance Exception UninitializedVariableException newContext :: Baker.BakingContext -> IO EvalContext newContext ctx = do vals <- MV.replicate (Baker.ctxGetNumVars ctx) (throw UninitializedVariableException) activeMatch <- newIORef Nothing backtrace <- newIORef Err.emptyBacktrace return (EvalContext vals activeMatch backtrace ctx) data RuntimeVar where RuntimeVar :: !Name -> !(Value t) -> RuntimeVar ctxGetVarValues :: EvalContext -> IO [RuntimeVar] ctxGetVarValues ctx = do let vars = Baker.ctxGetVars (ctxBakerContext ctx) values <- V.freeze (ctxValues ctx) return (zipWith runtimeVar vars (V.toList values)) where runtimeVar :: TypedName -> Value Void -> RuntimeVar runtimeVar (TypedName ty name) val = case eraseType ty (unsafeCoerce val) of ErasedValue val' -> RuntimeVar name val' ctxGetActiveMatch :: EvalContext -> IO (Maybe ICU.Match) ctxGetActiveMatch = readIORef . ctxActiveMatch ctxGetBacktrace :: EvalContext -> IO Err.Backtrace ctxGetBacktrace = readIORef . ctxBacktrace ctxGetBakerContext :: EvalContext -> Baker.BakingContext ctxGetBakerContext = ctxBakerContext type Eval = EvalT IO type instance Baker.EvalMonad Baker.BakerT = Eval newtype EvalT m a = EvalT (ExceptT Err.RuntimeError (ReaderT EvalContext m) a) deriving (Functor, Applicative, Monad, MonadIO, MonadError Err.RuntimeError, MonadThrow, MonadCatch) instance MonadTrans EvalT where lift = EvalT . lift . lift instance MFunctor EvalT where hoist f (EvalT m) = EvalT $ hoist (hoist f) m -- Eval primitives -------------------------------------------------- runEvalT :: MonadIO m => EvalContext -> EvalT m a -> ExceptT (EvalContext, Err.RuntimeError) m a runEvalT ctx (EvalT m) = do res <- lift $ runReaderT (runExceptT m) ctx case res of Left err -> throwE (ctx, err) Right a -> return a wrapEvalT :: Monad m => ExceptT (EvalContext, Err.RuntimeError) m a -> EvalT m a wrapEvalT m = EvalT $ ExceptT $ ReaderT $ \_ -> do r <- runExceptT m case r of Left (_, e) -> return (Left e) Right a -> return (Right a) readonly :: MonadIO m => EvalT m a -> EvalT m a readonly (EvalT m) = EvalT $ do -- variables may change in the action, but the current language does not -- allow it in predicates and this is just used in Eval.hs, so we're -- safe for now ctx <- ask match <- liftIO $ readIORef (ctxActiveMatch ctx) bt <- liftIO $ readIORef (ctxBacktrace ctx) a <- m liftIO $ writeIORef (ctxActiveMatch ctx) match liftIO $ writeIORef (ctxBacktrace ctx) bt return a -- evil unsafeCoerceValue :: VarId a -> Value Void -> Value a unsafeCoerceValue _ = unsafeCoerce unsafeVoidValue :: VarId a -> Value a -> Value Void unsafeVoidValue _ = unsafeCoerce getVarValue :: (MonadIO m, MonadCatch m) => VarId a -> EvalT m (Value a) getVarValue i = do vals <- EvalT $ asks ctxValues val <- liftIO (MV.read vals (Baker.varIdNum i)) `catchAll` (throwError . Err.NativeError) return (unsafeCoerceValue i val) setVarValue :: (MonadIO m, MonadCatch m) => VarId a -> Value a -> EvalT m () setVarValue i val = do vals <- EvalT $ asks ctxValues liftIO (MV.write vals (Baker.varIdNum i) (unsafeVoidValue i val)) `catchAll` (throwError . Err.NativeError) getCaptureValue :: MonadIO m => Int -> EvalT m Text getCaptureValue i = EvalT $ do Just match <- liftIO . readIORef =<< asks ctxActiveMatch case ICU.group i match of Just text -> return text Nothing -> error $ "getCaptureValue: could not find $" ++ show i ++ " of " ++ T.unpack (ICU.pattern match) setCaptures :: MonadIO m => RxCaptureMode -> ICU.Match -> EvalT m () setCaptures NoCapture _ = return () setCaptures Capture match = EvalT $ do activeMatch <- asks ctxActiveMatch liftIO $ writeIORef activeMatch $! Just $! match evalWithin :: MonadIO m => Err.Backtrace -> EvalT m a -> EvalT m a evalWithin bt (EvalT ma) = EvalT $ do btRef <- asks ctxBacktrace prev <- liftIO $ readIORef btRef liftIO $ writeIORef btRef bt a <- ma liftIO $ writeIORef btRef prev return a
xcv-/pipes-find
src/System/HFind/Expr/Eval.hs
Haskell
mit
6,295
{-# LANGUAGE PatternGuards #-} module CPS.FromGHC where import CPS.Syntax hiding (Subst, renameIdBinder) import qualified GHC.Data as G import qualified GHC.Var as G import qualified GHC.Syntax as G import qualified GHC.Type as G import qualified GHC.Kind as G import GHC.Primitives import Name import Utilities -- FIXME: it might be easier to just permit unboxed tuples everywhere, including inside other unboxed tuples and on the left-hand-side of function arrows. -- The only wrinkle is that fromId may have to manufacture some fresh names. -- FIXME: we can even permit unboxed tuples as e.g. arguments to (,)! Of course, you can't use such types as arguments to polymorphic functions (ill-kinded type application). -- In GHC we would also have to be careful about what info tables such things get -- we can't reuse the polymorphic one (closure layout will change). -- NB: the input type must be of a TypeKind kind -- NB: the type returned is the *unlifted* version of the type -- NB: may return multiple types for unboxed tuples -- NB: do not look through newtypes here or we may produce an infinite type fromType :: G.Type -> [Type] fromType (G.ForAllTy _ ty) = fromType ty fromType ty = case G.splitTyConAppTy_maybe ty of Just (tc, [_, _]) | tc == G.funTyCon -> [PtrTy] | Just _ <- G.isEqHashTyCon tc -> [] | tc == G.pairTyCon -> [PtrTy] Just (tc, []) | tc == G.boolTyCon -> [PtrTy] | tc == G.intTyCon -> [PtrTy] | tc == G.intHashTyCon -> [IntHashTy] Just (tc, tys) | Just n <- G.isUnboxedTupleTyCon_maybe tc , n == length tys -> concatMap fromTypeThunky tys -- NB: this does not actualy permit nested unboxed tuples, the list is needed if some components are void Just _ -> error "fromType: unrecognised explicit TyCon" Nothing -> case G.typeKind ty of G.LiftedTypeKind -> [PtrTy] _ -> error "fromType: non-TyCon non-lifted type" -- GHC currently has a bug where you can lambda-abstract over type variables of non-lifted kind. -- This is a serious problem because there is no way to reliably determine the representation of -- that type variable. This becomes explicit in our translation. -- -- FIXME: we should allow such types in *result* positions (e.g. for error :: forall (a :: OPEN). a). -- In this case, we can return [] on the understanding that such functions can never return. -- NB: the input type must be lifted fromLiftedType :: G.Type -> Type fromLiftedType ty = case fromType ty of [ty] -> ty _ -> error "fromLiftedType: non-unary input type - must be an unboxed tuple or void unlifted type" -- NB: the input type must be lifted fromLiftedTypeThunky :: G.Type -> Type fromLiftedTypeThunky ty = case fromTypeThunky ty of [ty] -> ty _ -> error "fromLiftedTypeThunky: non-unary input type - must be an unboxed tuple or void unlifted type" fromTypeThunky :: G.Type -> [Type] fromTypeThunky ty | G.typeKind ty /= G.LiftedTypeKind = fromType ty | otherwise = [PtrTy] -- We don't have to worry about occurrences of unboxed tuple Ids, but void Ids may occur fromId :: G.Id -> [Id] fromId x = case fromTypeThunky (G.idType x) of [] -> [] [ty] -> [Id { idName = G.idName x, idType = ty }] _ -> error "fromId: unboxed tuple Ids are not present in the input" -- NB: the type of the input Id must be lifted fromLiftedId :: G.Id -> Id fromLiftedId x = case fromId x of [x] -> x _ -> error "fromLiftedId: void input Id" type Context = (UniqueSupply, InScopeSet) type Subst = UniqueMap (Maybe Trivial) type In a = (Subst, a) instance Uniqueable G.Id where getUnique = getUnique . G.idName rename :: Subst -> G.Id -> Maybe Trivial rename subst x = findUniqueWithDefault (error "rename: out of scope") x subst renameLifted :: Subst -> G.Id -> Trivial renameLifted subst x = case rename subst x of Just t -> t Nothing -> error "renameLifted: binding not lifted" renameIdBinder :: Context -> Subst -> G.Id -> (Context, Subst, Maybe Id) renameIdBinder ids subst x = (ids', insertUniqueMap x (fmap IdOcc mb_x') subst, mb_x') where (ids', mb_x') = renameIdBinder' ids x renameIdBinder' :: Context -> G.Id -> (Context, Maybe Id) renameIdBinder' (ids, iss) x = case fromTypeThunky (G.idType x) of [] -> ((ids, iss), Nothing) [ty] -> ((ids, iss'), Just x') where n = G.idName x (iss', n') = uniqAwayName iss n x' = Id { idName = n', idType = ty } -- NB: don't need to rename types _ -> error "renameIdBinder': unboxed tuple binders are always dead" --renameBinders :: Context -> Subst -> [G.Id] -> (Context, Subst, [Maybe Id]) --renameBinders ids subst = third3 catMaybes . mapAccumL (\(ids, subst) x -> case renameBinder ids subst x of (ids, subst, mb_x') -> ((ids, subst, mb_x'))) (ids, subst) freshId :: Context -> String -> Type -> (Context, Id) freshId (ids, iss) s ty = ((ids', iss'), Id { idName = n', idType = ty }) where (ids', n) = freshName ids s (iss', n') = uniqAwayName iss n freshCoId :: Context -> String -> CoType -> (Context, CoId) freshCoId (ids, iss) s nty = ((ids', iss'), CoId { coIdName = n', coIdType = nty }) where (ids', n) = freshName ids s (iss', n') = uniqAwayName iss n freshs :: (Context -> String -> a -> (Context, b)) -> Context -> String -> [a] -> (Context, [b]) freshs fresh ids s tys = mapAccumL (\ids ty -> fresh ids s ty) ids tys -- fromTerm ids (subst, e) u -- -- NB: -- fromType (termType e) `allR subType` coIdType u -- FVs are available in the environment of the output with their *thunky* types data Kont = Unknown CoId | Known [Type] (Context -> [Trivial] -> Term) returnToKont :: Kont -> Context -> [Trivial] -> Term returnToKont (Unknown u) _ ts = Term [] [] (Return u ts) returnToKont (Known _ f) ids ts = f ids ts bindKont :: Kont -> Context -> (Context -> CoId -> Term) -> Term bindKont (Unknown u) ids nested = nested ids u bindKont (Known tys f) ids0 nested = addContinuation u k (nested ids2 u) -- FIXME: should tys come from bindCont caller? (Casts) where k = Continuation xs (f ids2 (map IdOcc xs)) (ids1, u) = freshCoId ids0 "u" (continuationCoType k) (ids2, xs) = freshs freshId ids1 "x" tys fromTerm :: Context -> In G.Term -> Kont -> Term fromTerm ids (subst, G.Var x) u | G.typeKind (G.idType x) /= G.LiftedTypeKind = returnToKont u ids (maybeToList (rename subst x)) | otherwise = bindKont u ids $ \_ u -> Term [] [] (Call (renameLifted subst x) (Enter []) [u]) fromTerm ids0 (subst, G.Value v) u = case v of G.Coercion _ -> returnToKont u ids0 [] G.Lambda (G.ATyVar _) e -> fromTerm ids0 (subst, e) u G.Lambda (G.AnId x) e -> addFunction y f (returnToKont u ids1 [IdOcc y]) where (ids1, y) = freshId ids0 "fun" PtrTy (ids2, subst', mb_x') = renameIdBinder ids1 subst x (ids3, w) = freshCoId ids2 "w" (fromType (G.termType e)) f = Function (maybeToList mb_x') [w] (fromTerm ids3 (subst', e) (Unknown w)) G.Data dc _ _ xs | Just _ <- G.isUnboxedTupleTyCon_maybe (G.dataConTyCon dc) -> returnToKont u ids0 (mapMaybe (rename subst) xs) | otherwise -> addFunction y f (returnToKont u ids1 [IdOcc y]) where dcs = G.dataConFamily dc ListPoint tys_lefts _tys_here tys_rights = fmap (concatMap fromTypeThunky . G.dataConFields) $ locateListPoint (==dc) dcs f = Box tys_lefts (mapMaybe (rename subst) xs) tys_rights (ids1, y) = freshId ids0 "data" PtrTy G.Literal l -> returnToKont u ids0 [Literal l] fromTerm ids (subst, G.App e x) u = fromTerm ids (subst, e) $ Known (fromType (G.termType e)) $ \ids [t] -> bindKont u ids $ \_ u -> Term [] [] (Call t (Enter (maybeToList (rename subst x))) [u]) fromTerm ids (subst, G.TyApp e _) u = fromTerm ids (subst, e) u fromTerm ids (subst, G.PrimOp pop es) u = foldr (\e known ids ts -> fromTerm ids (subst, e) $ Known (fromType (G.termType e)) $ \ids extra_ts -> known ids (ts ++ extra_ts)) (\ids ts -> bindKont u ids $ \_ u -> Term [] [] (Call (PrimOp pop) (Enter ts) [u])) es ids [] fromTerm ids0 (subst, G.Case e _ x alts) u | [(G.DataAlt dc _ xs, e_alt)] <- alts , Just _ <- G.isUnboxedTupleTyCon_maybe (G.dataConTyCon dc) , let combine [] [] = [] combine (x:xs) ts = case fromTypeThunky (G.idType x) of [] -> (x, Nothing) : combine xs ts [_] | (t:ts) <- ts -> (x, Just t) : combine xs ts _ -> error "combine: binder, but no matching trivials" combine [] (_:_) = error "combine: not enough trivials" = fromTerm ids0 (subst, e) $ Known (fromType (G.idType x)) $ \ids0 ts -> fromTerm ids0 (foldr (uncurry insertUniqueMap) subst (combine xs ts), e_alt) u | otherwise = fromTerm ids0 (subst, e) $ Known (fromType (G.idType x)) $ \ids0 ts -> let subst' = insertUniqueMap x (if G.typeKind (G.idType x) /= G.LiftedTypeKind then listToMaybe ts else Just (case ts of [t] -> t)) subst in case alts of [(G.DefaultAlt, e)] -> fromTerm ids0 (subst', e) u ((G.DefaultAlt, e_def):(G.DataAlt dc _ xs, e):alts) | [t] <- ts -> fromAlts (selectData t) ids0 subst' (Just e_def) ((dc, (xs, e)):[(dc, (xs, e)) | (G.DataAlt dc _ xs, e) <- alts]) u ((G.DataAlt dc _ xs, e):alts) | [t] <- ts -> fromAlts (selectData t) ids0 subst' Nothing ((dc, (xs, e)):[(dc, (xs, e)) | (G.DataAlt dc _ xs, e) <- alts]) u ((G.DefaultAlt, e_def):(G.LiteralAlt l, e):alts) | [t] <- ts -> fromAlts (selectLiteral t) ids0 subst' (Just e_def) ((l, ([], e)):[(l, ([], e)) | (G.LiteralAlt l, e) <- alts]) u ((G.LiteralAlt l, e):alts) | [t] <- ts -> fromAlts (selectLiteral t) ids0 subst' Nothing ((l, ([], e)):[(l, ([], e)) | (G.LiteralAlt l, e) <- alts]) u fromTerm ids0 (subst0, G.LetRec xes e) u = e' where (ids3, subst2, e') = foldr (\(x, e) (ids1, subst0, e') -> let (ids2, subst1, Just x') = renameIdBinder ids1 subst0 x ty = fromLiftedType (G.termType e) (ids3, w) = freshCoId ids2 "w" [ty] in (ids2, subst1, addFunction x' (Function [] [w] (fromTerm ids3 (subst2, e) (Known [ty] $ \_ [t] -> Term [] [] (Call (Update [] (coIdType w) []) (Enter [IdOcc x', t]) [w])))) e')) (ids0, subst0, fromTerm ids3 (subst2, e) u) xes fromTerm ids (subst, G.Cast e _) u = fromTerm ids (subst, e) u -- FIXME: I'm a bit worried about the type-precision consequences of this -- dropping casts may kill typeability of the output! -- -- Consider: -- \(y :: Int) -> let x :: F Int = (\(x :: Int) -> x) |> (co :: (Int -> Int) ~ F Int) -- in x |> (sym co) y -- -- Which would naively translate to: -- let x :: * = \(x :: *) -> x -- in x y -- -- Which is ill typed. -- -- How about in CPS-core? (NB: I'm using * to stand for the evaluated form of the lifted type Int) -- let x :: <> -> * = \<> (k :: *) -> let xv :: (<> -> *) -> * = \x k -> x <> k -- in k xv -- l :: (<> -> *) -> * = \(xv :: (<> -> *) -> *) -> xv y halt -- in x l -- -- This is STILL ill typed -- look at the (x l) application, where l demands more than the x can supply. -- -- Even worse, since x is hidden by a lambda: -- \(y :: Int) -> let x :: F Int = (\(x :: Int) -> x) |> (co :: (Int -> Int) ~ F Int) -- in (\(x :: F Int) -> x |> (sym co) y) x -- -- One other thing we have to be careful about is recursive types: -- f :: Rec = (\(x :: Int) -> f) |> (nt_ax :: (Int -> Rec) ~ Rec) -- -- Translating to: -- f :: * = (\(x :: *) -> f) :: * -> * -- -- From this, it is clear that we could -- but *should not* -- update let-binder types from the type of -- their RHSs, since we can iterate this forever and build infinite arbitrarily large types. selectData :: Trivial -> CoId -> [(G.DataCon, CoId)] -> Term selectData t u_def dcs_us = Term [] [] (Call t Unbox [lookup dc dcs_us `orElse` u_def | dc <- dc_family]) where dc_family = G.dataConFamily (fst (head dcs_us)) selectLiteral :: Trivial -> CoId -> [(Literal, CoId)] -> Term selectLiteral t = error "FIXME: selectLiteral (perhaps via a primitive Id we can call)" t typeFromVar :: G.Var -> [Type] typeFromVar (G.AnId x) = fromTypeThunky (G.idType x) typeFromVar (G.ATyVar _) = [] fromVar :: G.Var -> [Id] fromVar (G.AnId x) = fromId x fromVar (G.ATyVar _) = [] fromAlts :: (CoId -> [(a, CoId)] -> Term) -> Context -> Subst -> Maybe G.Term -> [(a, ([G.Id], G.Term))] -> Kont -> Term fromAlts select ids0 subst mb_def selectors_alts u = bindKont u ids0 fromAlts' where fromAlts' ids0 u = e2 where e0 = select (mb_def_u `orElse` error "FIXME: add an unreachable fallback") selector_us ((ids1, mb_def_u), e1) = case mb_def of Nothing -> ((ids0, Nothing), e0) Just e -> ((ids1, Just w), addContinuation w (Continuation [] (fromTerm ids2 (subst, e) (Unknown u))) e0) where (ids1, w) = freshCoId ids0 "w" [] ((ids2, e2), selector_us) = mapAccumL (\(ids1, e1) (selector, (xs, e)) -> let k = Continuation (catMaybes mb_ys) (fromTerm ids2 (subst', e) (Unknown u)) (ids2a, w) = freshCoId ids1 "w" (continuationCoType k) (ids2b, subst', mb_ys) = renameBinders renameIdBinder ids2a subst xs in ((ids2b, addContinuation w k e1), (selector, w))) (ids1, e1) selectors_alts
beni55/cps-core
CPS/FromGHC.hs
Haskell
bsd-3-clause
14,206
import Diagrams.Prelude hiding (doRender) import Diagrams.Backend.OpenGL import Diagrams.Backend.OpenGL.CmdLine main :: IO () main = do defaultMain d v1 :: R2 v1 = r2 (0,1) v2 :: R2 v2 = r2 (0.5,-0.5) p :: Path R2 p = pathFromTrail . closeTrail $ fromOffsets [v1,v2] p2_ :: Path R2 p2_ = pathFromTrail . closeTrail $ fromOffsets [v2, v1] d :: Diagram OpenGL R2 d = stroke p # fc green <> (stroke p2_ # lc blue # fc cyan # translate (r2 (0,0.5)))
mbernat/diagrams-opengl
examples/polygons.hs
Haskell
bsd-3-clause
459
-- Copyright (c) 2014-present, Facebook, Inc. -- All rights reserved. -- -- This source code is distributed under the terms of a BSD license, -- found in the LICENSE file. {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleInstances #-} module SleepDataSource ( sleep, ) where import Haxl.Prelude import Prelude () import Haxl.Core import Haxl.DataSource.ConcurrentIO import Control.Concurrent import Data.Hashable import Data.Typeable sleep :: Int -> GenHaxl u Int sleep n = dataFetch (Sleep n) data Sleep deriving Typeable instance ConcurrentIO Sleep where data ConcurrentIOReq Sleep a where Sleep :: Int -> ConcurrentIOReq Sleep Int performIO (Sleep n) = threadDelay (n*1000) >> return n deriving instance Eq (ConcurrentIOReq Sleep a) deriving instance Show (ConcurrentIOReq Sleep a) instance ShowP (ConcurrentIOReq Sleep) where showp = show instance Hashable (ConcurrentIOReq Sleep a) where hashWithSalt s (Sleep n) = hashWithSalt s n
simonmar/Haxl
tests/SleepDataSource.hs
Haskell
bsd-3-clause
1,179
{-# LANGUAGE CPP #-} module TcSimplify( simplifyInfer, pickQuantifiablePreds, growThetaTyVars, simplifyAmbiguityCheck, simplifyDefault, simplifyTop, simplifyInteractive, solveWantedsTcM, -- For Rules we need these twoo solveWanteds, runTcS ) where #include "HsVersions.h" import Bag import Class ( classKey ) import Class ( Class ) import DynFlags ( ExtensionFlag( Opt_AllowAmbiguousTypes , Opt_FlexibleContexts ) ) import ErrUtils ( emptyMessages ) import FastString import Id ( idType ) import Inst import Kind ( isKind, defaultKind_maybe ) import ListSetOps import Maybes ( isNothing ) import Name import Outputable import PrelInfo import PrelNames import TcErrors import TcEvidence import TcInteract import TcMType as TcM import TcRnMonad as TcRn import TcSMonad as TcS import TcType import TrieMap () -- DV: for now import TyCon ( isTypeFamilyTyCon ) import Type ( classifyPredType, isIPClass, PredTree(..) , getClassPredTys_maybe, EqRel(..) ) import Unify ( tcMatchTy ) import Util import Var import VarSet import Control.Monad ( unless ) import Data.List ( partition ) {- ********************************************************************************* * * * External interface * * * ********************************************************************************* -} simplifyTop :: WantedConstraints -> TcM (Bag EvBind) -- Simplify top-level constraints -- Usually these will be implications, -- but when there is nothing to quantify we don't wrap -- in a degenerate implication, so we do that here instead simplifyTop wanteds = do { traceTc "simplifyTop {" $ text "wanted = " <+> ppr wanteds ; ((final_wc, unsafe_ol), binds1) <- runTcS $ simpl_top wanteds ; traceTc "End simplifyTop }" empty ; traceTc "reportUnsolved {" empty ; binds2 <- reportUnsolved final_wc ; traceTc "reportUnsolved }" empty ; traceTc "reportUnsolved (unsafe overlapping) {" empty ; unless (isEmptyCts unsafe_ol) $ do { -- grab current error messages and clear, warnAllUnsolved will -- update error messages which we'll grab and then restore saved -- messges. ; errs_var <- getErrsVar ; saved_msg <- TcRn.readTcRef errs_var ; TcRn.writeTcRef errs_var emptyMessages ; warnAllUnsolved $ WC { wc_simple = unsafe_ol , wc_insol = emptyCts , wc_impl = emptyBag } ; whyUnsafe <- fst <$> TcRn.readTcRef errs_var ; TcRn.writeTcRef errs_var saved_msg ; recordUnsafeInfer whyUnsafe } ; traceTc "reportUnsolved (unsafe overlapping) }" empty ; return (binds1 `unionBags` binds2) } type SafeOverlapFailures = Cts -- ^ See Note [Safe Haskell Overlapping Instances Implementation] type FinalConstraints = (WantedConstraints, SafeOverlapFailures) simpl_top :: WantedConstraints -> TcS FinalConstraints -- See Note [Top-level Defaulting Plan] simpl_top wanteds = do { wc_first_go <- nestTcS (solveWantedsAndDrop wanteds) -- This is where the main work happens ; wc_final <- try_tyvar_defaulting wc_first_go ; unsafe_ol <- getSafeOverlapFailures ; return (wc_final, unsafe_ol) } where try_tyvar_defaulting :: WantedConstraints -> TcS WantedConstraints try_tyvar_defaulting wc | isEmptyWC wc = return wc | otherwise = do { free_tvs <- TcS.zonkTyVarsAndFV (tyVarsOfWC wc) ; let meta_tvs = varSetElems (filterVarSet isMetaTyVar free_tvs) -- zonkTyVarsAndFV: the wc_first_go is not yet zonked -- filter isMetaTyVar: we might have runtime-skolems in GHCi, -- and we definitely don't want to try to assign to those! ; meta_tvs' <- mapM defaultTyVar meta_tvs -- Has unification side effects ; if meta_tvs' == meta_tvs -- No defaulting took place; -- (defaulting returns fresh vars) then try_class_defaulting wc else do { wc_residual <- nestTcS (solveWantedsAndDrop wc) -- See Note [Must simplify after defaulting] ; try_class_defaulting wc_residual } } try_class_defaulting :: WantedConstraints -> TcS WantedConstraints try_class_defaulting wc | isEmptyWC wc = return wc | otherwise -- See Note [When to do type-class defaulting] = do { something_happened <- applyDefaultingRules wc -- See Note [Top-level Defaulting Plan] ; if something_happened then do { wc_residual <- nestTcS (solveWantedsAndDrop wc) ; try_class_defaulting wc_residual } else return wc } {- Note [When to do type-class defaulting] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In GHC 7.6 and 7.8.2, we did type-class defaulting only if insolubleWC was false, on the grounds that defaulting can't help solve insoluble constraints. But if we *don't* do defaulting we may report a whole lot of errors that would be solved by defaulting; these errors are quite spurious because fixing the single insoluble error means that defaulting happens again, which makes all the other errors go away. This is jolly confusing: Trac #9033. So it seems better to always do type-class defaulting. However, always doing defaulting does mean that we'll do it in situations like this (Trac #5934): run :: (forall s. GenST s) -> Int run = fromInteger 0 We don't unify the return type of fromInteger with the given function type, because the latter involves foralls. So we're left with (Num alpha, alpha ~ (forall s. GenST s) -> Int) Now we do defaulting, get alpha := Integer, and report that we can't match Integer with (forall s. GenST s) -> Int. That's not totally stupid, but perhaps a little strange. Another potential alternative would be to suppress *all* non-insoluble errors if there are *any* insoluble errors, anywhere, but that seems too drastic. Note [Must simplify after defaulting] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We may have a deeply buried constraint (t:*) ~ (a:Open) which we couldn't solve because of the kind incompatibility, and 'a' is free. Then when we default 'a' we can solve the constraint. And we want to do that before starting in on type classes. We MUST do it before reporting errors, because it isn't an error! Trac #7967 was due to this. Note [Top-level Defaulting Plan] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We have considered two design choices for where/when to apply defaulting. (i) Do it in SimplCheck mode only /whenever/ you try to solve some simple constraints, maybe deep inside the context of implications. This used to be the case in GHC 7.4.1. (ii) Do it in a tight loop at simplifyTop, once all other constraint has finished. This is the current story. Option (i) had many disadvantages: a) First it was deep inside the actual solver, b) Second it was dependent on the context (Infer a type signature, or Check a type signature, or Interactive) since we did not want to always start defaulting when inferring (though there is an exception to this see Note [Default while Inferring]) c) It plainly did not work. Consider typecheck/should_compile/DfltProb2.hs: f :: Int -> Bool f x = const True (\y -> let w :: a -> a w a = const a (y+1) in w y) We will get an implication constraint (for beta the type of y): [untch=beta] forall a. 0 => Num beta which we really cannot default /while solving/ the implication, since beta is untouchable. Instead our new defaulting story is to pull defaulting out of the solver loop and go with option (i), implemented at SimplifyTop. Namely: - First have a go at solving the residual constraint of the whole program - Try to approximate it with a simple constraint - Figure out derived defaulting equations for that simple constraint - Go round the loop again if you did manage to get some equations Now, that has to do with class defaulting. However there exists type variable /kind/ defaulting. Again this is done at the top-level and the plan is: - At the top-level, once you had a go at solving the constraint, do figure out /all/ the touchable unification variables of the wanted constraints. - Apply defaulting to their kinds More details in Note [DefaultTyVar]. Note [Safe Haskell Overlapping Instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In Safe Haskell, we apply an extra restriction to overlapping instances. The motive is to prevent untrusted code provided by a third-party, changing the behavior of trusted code through type-classes. This is due to the global and implicit nature of type-classes that can hide the source of the dictionary. Another way to state this is: if a module M compiles without importing another module N, changing M to import N shouldn't change the behavior of M. Overlapping instances with type-classes can violate this principle. However, overlapping instances aren't always unsafe. They are just unsafe when the most selected dictionary comes from untrusted code (code compiled with -XSafe) and overlaps instances provided by other modules. In particular, in Safe Haskell at a call site with overlapping instances, we apply the following rule to determine if it is a 'unsafe' overlap: 1) Most specific instance, I1, defined in an `-XSafe` compiled module. 2) I1 is an orphan instance or a MPTC. 3) At least one overlapped instance, Ix, is both: A) from a different module than I1 B) Ix is not marked `OVERLAPPABLE` This is a slightly involved heuristic, but captures the situation of an imported module N changing the behavior of existing code. For example, if condition (2) isn't violated, then the module author M must depend either on a type-class or type defined in N. Secondly, when should these heuristics be enforced? We enforced them when the type-class method call site is in a module marked `-XSafe` or `-XTrustworthy`. This allows `-XUnsafe` modules to operate without restriction, and for Safe Haskell inferrence to infer modules with unsafe overlaps as unsafe. One alternative design would be to also consider if an instance was imported as a `safe` import or not and only apply the restriction to instances imported safely. However, since instances are global and can be imported through more than one path, this alternative doesn't work. Note [Safe Haskell Overlapping Instances Implementation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ How is this implemented? It's compilcated! So we'll step through it all: 1) `InstEnv.lookupInstEnv` -- Performs instance resolution, so this is where we check if a particular type-class method call is safe or unsafe. We do this through the return type, `ClsInstLookupResult`, where the last parameter is a list of instances that are unsafe to overlap. When the method call is safe, the list is null. 2) `TcInteract.matchClassInst` -- This module drives the instance resolution / dictionary generation. The return type is `LookupInstResult`, which either says no instance matched, or one found and if it was a safe or unsafe overlap. 3) `TcInteract.doTopReactDict` -- Takes a dictionary / class constraint and tries to resolve it by calling (in part) `matchClassInst`. The resolving mechanism has a work list (of constraints) that it process one at a time. If the constraint can't be resolved, it's added to an inert set. When compiling an `-XSafe` or `-XTrustworthy` module we follow this approach as we know compilation should fail. These are handled as normal constraint resolution failures from here-on (see step 6). Otherwise, we may be inferring safety (or using `-fwarn-unsafe`) and compilation should succeed, but print warnings and/or mark the compiled module as `-XUnsafe`. In this case, we call `insertSafeOverlapFailureTcS` which adds the unsafe (but resolved!) constraint to the `inert_safehask` field of `InertCans`. 4) `TcSimplify.simpl_top` -- Top-level function for driving the simplifier for constraint resolution. Once finished, we call `getSafeOverlapFailures` to retrieve the list of overlapping instances that were successfully resolved, but unsafe. Remember, this is only applicable for generating warnings (`-fwarn-unsafe`) or inferring a module unsafe. `-XSafe` and `-XTrustworthy` cause compilation failure by not resolving the unsafe constraint at all. `simpl_top` returns a list of unresolved constraints (all types), and resolved (but unsafe) resolved dictionary constraints. 5) `TcSimplify.simplifyTop` -- Is the caller of `simpl_top`. For unresolved constraints, it calls `TcErrors.reportUnsolved`, while for unsafe overlapping instance constraints, it calls `TcErrors.warnAllUnsolved`. Both functions convert constraints into a warning message for the user. 6) `TcErrors.*Unsolved` -- Generates error messages for conastraints by actually calling `InstEnv.lookupInstEnv` again! Yes, confusing, but all we know is the constraint that is unresolved or unsafe. For dictionary, this is know we need a dictionary of type C, but not what instances are available and how they overlap. So we once again call `lookupInstEnv` to figure that out so we can generate a helpful error message. 7) `TcSimplify.simplifyTop` -- In the case of `warnAllUnsolved` for resolved, but unsafe dictionary constraints, we collect the generated warning message (pop it) and call `TcRnMonad.recordUnsafeInfer` to mark the module we are compiling as unsafe, passing the warning message along as the reason. 8) `TcRnMonad.recordUnsafeInfer` -- Save the unsafe result and reason in an IORef called `tcg_safeInfer`. 9) `HscMain.tcRnModule'` -- Reads `tcg_safeInfer` after type-checking, calling `HscMain.markUnsafeInfer` (passing the reason along) when safe-inferrence failed. -} ------------------ simplifyAmbiguityCheck :: Type -> WantedConstraints -> TcM () simplifyAmbiguityCheck ty wanteds = do { traceTc "simplifyAmbiguityCheck {" (text "type = " <+> ppr ty $$ text "wanted = " <+> ppr wanteds) ; ((final_wc, _), _binds) <- runTcS $ simpl_top wanteds ; traceTc "End simplifyAmbiguityCheck }" empty -- Normally report all errors; but with -XAllowAmbiguousTypes -- report only insoluble ones, since they represent genuinely -- inaccessible code ; allow_ambiguous <- xoptM Opt_AllowAmbiguousTypes ; traceTc "reportUnsolved(ambig) {" empty ; unless (allow_ambiguous && not (insolubleWC final_wc)) (discardResult (reportUnsolved final_wc)) ; traceTc "reportUnsolved(ambig) }" empty ; return () } ------------------ simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind) simplifyInteractive wanteds = traceTc "simplifyInteractive" empty >> simplifyTop wanteds ------------------ simplifyDefault :: ThetaType -- Wanted; has no type variables in it -> TcM () -- Succeeds iff the constraint is soluble simplifyDefault theta = do { traceTc "simplifyInteractive" empty ; wanted <- newWanteds DefaultOrigin theta ; unsolved <- solveWantedsTcM wanted ; traceTc "reportUnsolved {" empty -- See Note [Deferring coercion errors to runtime] ; reportAllUnsolved unsolved ; traceTc "reportUnsolved }" empty ; return () } {- ********************************************************************************* * * * Inference * * *********************************************************************************** Note [Inferring the type of a let-bound variable] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f x = rhs To infer f's type we do the following: * Gather the constraints for the RHS with ambient level *one more than* the current one. This is done by the call pushLevelAndCaptureConstraints (tcMonoBinds...) in TcBinds.tcPolyInfer * Call simplifyInfer to simplify the constraints and decide what to quantify over. We pass in the level used for the RHS constraints, here called rhs_tclvl. This ensures that the implication constraint we generate, if any, has a strictly-increased level compared to the ambient level outside the let binding. -} simplifyInfer :: TcLevel -- Used when generating the constraints -> Bool -- Apply monomorphism restriction -> [(Name, TcTauType)] -- Variables to be generalised, -- and their tau-types -> WantedConstraints -> TcM ([TcTyVar], -- Quantify over these type variables [EvVar], -- ... and these constraints (fully zonked) Bool, -- The monomorphism restriction did something -- so the results type is not as general as -- it could be TcEvBinds) -- ... binding these evidence variables simplifyInfer rhs_tclvl apply_mr name_taus wanteds | isEmptyWC wanteds = do { gbl_tvs <- tcGetGlobalTyVars ; qtkvs <- quantifyTyVars gbl_tvs (tyVarsOfTypes (map snd name_taus)) ; traceTc "simplifyInfer: empty WC" (ppr name_taus $$ ppr qtkvs) ; return (qtkvs, [], False, emptyTcEvBinds) } | otherwise = do { traceTc "simplifyInfer {" $ vcat [ ptext (sLit "binds =") <+> ppr name_taus , ptext (sLit "rhs_tclvl =") <+> ppr rhs_tclvl , ptext (sLit "apply_mr =") <+> ppr apply_mr , ptext (sLit "(unzonked) wanted =") <+> ppr wanteds ] -- Historical note: Before step 2 we used to have a -- HORRIBLE HACK described in Note [Avoid unecessary -- constraint simplification] but, as described in Trac -- #4361, we have taken in out now. That's why we start -- with step 2! -- Step 2) First try full-blown solving -- NB: we must gather up all the bindings from doing -- this solving; hence (runTcSWithEvBinds ev_binds_var). -- And note that since there are nested implications, -- calling solveWanteds will side-effect their evidence -- bindings, so we can't just revert to the input -- constraint. ; ev_binds_var <- TcM.newTcEvBinds ; wanted_transformed_incl_derivs <- setTcLevel rhs_tclvl $ runTcSWithEvBinds ev_binds_var (solveWanteds wanteds) ; wanted_transformed_incl_derivs <- TcM.zonkWC wanted_transformed_incl_derivs -- Step 4) Candidates for quantification are an approximation of wanted_transformed -- NB: Already the fixpoint of any unifications that may have happened -- NB: We do not do any defaulting when inferring a type, this can lead -- to less polymorphic types, see Note [Default while Inferring] ; tc_lcl_env <- TcRn.getLclEnv ; null_ev_binds_var <- TcM.newTcEvBinds ; let wanted_transformed = dropDerivedWC wanted_transformed_incl_derivs ; quant_pred_candidates -- Fully zonked <- if insolubleWC wanted_transformed_incl_derivs then return [] -- See Note [Quantification with errors] -- NB: must include derived errors in this test, -- hence "incl_derivs" else do { let quant_cand = approximateWC wanted_transformed meta_tvs = filter isMetaTyVar (varSetElems (tyVarsOfCts quant_cand)) ; gbl_tvs <- tcGetGlobalTyVars -- Miminise quant_cand. We are not interested in any evidence -- produced, because we are going to simplify wanted_transformed -- again later. All we want here is the predicates over which to -- quantify. -- -- If any meta-tyvar unifications take place (unlikely), we'll -- pick that up later. ; WC { wc_simple = simples } <- setTcLevel rhs_tclvl $ runTcSWithEvBinds null_ev_binds_var $ do { mapM_ (promoteAndDefaultTyVar rhs_tclvl gbl_tvs) meta_tvs -- See Note [Promote _and_ default when inferring] ; solveSimpleWanteds quant_cand } ; return [ ctEvPred ev | ct <- bagToList simples , let ev = ctEvidence ct , isWanted ev ] } -- NB: quant_pred_candidates is already fully zonked -- Decide what type variables and constraints to quantify ; zonked_taus <- mapM (TcM.zonkTcType . snd) name_taus ; let zonked_tau_tvs = tyVarsOfTypes zonked_taus ; (qtvs, bound_theta, mr_bites) <- decideQuantification apply_mr quant_pred_candidates zonked_tau_tvs -- Emit an implication constraint for the -- remaining constraints from the RHS ; bound_ev_vars <- mapM TcM.newEvVar bound_theta ; let skol_info = InferSkol [ (name, mkSigmaTy [] bound_theta ty) | (name, ty) <- name_taus ] -- Don't add the quantified variables here, because -- they are also bound in ic_skols and we want them -- to be tidied uniformly implic = Implic { ic_tclvl = rhs_tclvl , ic_skols = qtvs , ic_no_eqs = False , ic_given = bound_ev_vars , ic_wanted = wanted_transformed , ic_status = IC_Unsolved , ic_binds = ev_binds_var , ic_info = skol_info , ic_env = tc_lcl_env } ; emitImplication implic -- Promote any type variables that are free in the inferred type -- of the function: -- f :: forall qtvs. bound_theta => zonked_tau -- These variables now become free in the envt, and hence will show -- up whenever 'f' is called. They may currently at rhs_tclvl, but -- they had better be unifiable at the outer_tclvl! -- Example: envt mentions alpha[1] -- tau_ty = beta[2] -> beta[2] -- consraints = alpha ~ [beta] -- we don't quantify over beta (since it is fixed by envt) -- so we must promote it! The inferred type is just -- f :: beta -> beta ; outer_tclvl <- TcRn.getTcLevel ; zonked_tau_tvs <- TcM.zonkTyVarsAndFV zonked_tau_tvs -- decideQuantification turned some meta tyvars into -- quantified skolems, so we have to zonk again ; let phi_tvs = tyVarsOfTypes bound_theta `unionVarSet` zonked_tau_tvs promote_tvs = varSetElems (closeOverKinds phi_tvs `delVarSetList` qtvs) ; runTcSWithEvBinds null_ev_binds_var $ -- runTcS just to get the types right :-( mapM_ (promoteTyVar outer_tclvl) promote_tvs -- All done! ; traceTc "} simplifyInfer/produced residual implication for quantification" $ vcat [ ptext (sLit "quant_pred_candidates =") <+> ppr quant_pred_candidates , ptext (sLit "zonked_taus") <+> ppr zonked_taus , ptext (sLit "zonked_tau_tvs=") <+> ppr zonked_tau_tvs , ptext (sLit "promote_tvs=") <+> ppr promote_tvs , ptext (sLit "bound_theta =") <+> vcat [ ppr v <+> dcolon <+> ppr (idType v) | v <- bound_ev_vars] , ptext (sLit "mr_bites =") <+> ppr mr_bites , ptext (sLit "qtvs =") <+> ppr qtvs , ptext (sLit "implic =") <+> ppr implic ] ; return ( qtvs, bound_ev_vars, mr_bites, TcEvBinds ev_binds_var) } {- ************************************************************************ * * Quantification * * ************************************************************************ Note [Deciding quantification] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If the monomorphism restriction does not apply, then we quantify as follows: * Take the global tyvars, and "grow" them using the equality constraints E.g. if x:alpha is in the environment, and alpha ~ [beta] (which can happen because alpha is untouchable here) then do not quantify over beta, because alpha fixes beta, and beta is effectively free in the environment too These are the mono_tvs * Take the free vars of the tau-type (zonked_tau_tvs) and "grow" them using all the constraints. These are tau_tvs_plus * Use quantifyTyVars to quantify over (tau_tvs_plus - mono_tvs), being careful to close over kinds, and to skolemise the quantified tyvars. (This actually unifies each quantifies meta-tyvar with a fresh skolem.) Result is qtvs. * Filter the constraints using pickQuantifyablePreds and the qtvs. We have to zonk the constraints first, so they "see" the freshly created skolems. If the MR does apply, mono_tvs includes all the constrained tyvars, and the quantified constraints are empty. -} decideQuantification :: Bool -- Apply monomorphism restriction -> [PredType] -> TcTyVarSet -- Constraints and type variables from RHS -> TcM ( [TcTyVar] -- Quantify over these tyvars (skolems) , [PredType] -- and this context (fully zonked) , Bool ) -- Did the MR bite? -- See Note [Deciding quantification] decideQuantification apply_mr constraints zonked_tau_tvs | apply_mr -- Apply the Monomorphism restriction = do { gbl_tvs <- tcGetGlobalTyVars ; let constrained_tvs = tyVarsOfTypes constraints mono_tvs = gbl_tvs `unionVarSet` constrained_tvs mr_bites = constrained_tvs `intersectsVarSet` zonked_tau_tvs ; qtvs <- quantifyTyVars mono_tvs zonked_tau_tvs ; traceTc "decideQuantification 1" (vcat [ppr constraints, ppr gbl_tvs, ppr mono_tvs, ppr qtvs]) ; return (qtvs, [], mr_bites) } | otherwise = do { gbl_tvs <- tcGetGlobalTyVars ; let mono_tvs = growThetaTyVars (filter isEqPred constraints) gbl_tvs tau_tvs_plus = growThetaTyVars constraints zonked_tau_tvs ; qtvs <- quantifyTyVars mono_tvs tau_tvs_plus ; constraints <- zonkTcThetaType constraints -- quantifyTyVars turned some meta tyvars into -- quantified skolems, so we have to zonk again ; theta <- pickQuantifiablePreds (mkVarSet qtvs) constraints ; let min_theta = mkMinimalBySCs theta -- See Note [Minimize by Superclasses] ; traceTc "decideQuantification 2" (vcat [ppr constraints, ppr gbl_tvs, ppr mono_tvs , ppr tau_tvs_plus, ppr qtvs, ppr min_theta]) ; return (qtvs, min_theta, False) } ------------------ pickQuantifiablePreds :: TyVarSet -- Quantifying over these -> TcThetaType -- Proposed constraints to quantify -> TcM TcThetaType -- A subset that we can actually quantify -- This function decides whether a particular constraint shoudl be -- quantified over, given the type variables that are being quantified pickQuantifiablePreds qtvs theta = do { flex_ctxt <- xoptM Opt_FlexibleContexts ; return (filter (pick_me flex_ctxt) theta) } where pick_me flex_ctxt pred = case classifyPredType pred of ClassPred cls tys | isIPClass cls -> True -- See note [Inheriting implicit parameters] | otherwise -> pick_cls_pred flex_ctxt tys EqPred ReprEq ty1 ty2 -> pick_cls_pred flex_ctxt [ty1, ty2] -- Representational equality is like a class constraint EqPred NomEq ty1 ty2 -> quant_fun ty1 || quant_fun ty2 IrredPred ty -> tyVarsOfType ty `intersectsVarSet` qtvs pick_cls_pred flex_ctxt tys = tyVarsOfTypes tys `intersectsVarSet` qtvs && (checkValidClsArgs flex_ctxt tys) -- Only quantify over predicates that checkValidType -- will pass! See Trac #10351. -- See Note [Quantifying over equality constraints] quant_fun ty = case tcSplitTyConApp_maybe ty of Just (tc, tys) | isTypeFamilyTyCon tc -> tyVarsOfTypes tys `intersectsVarSet` qtvs _ -> False ------------------ growThetaTyVars :: ThetaType -> TyVarSet -> TyVarSet -- See Note [Growing the tau-tvs using constraints] growThetaTyVars theta tvs | null theta = tvs | otherwise = transCloVarSet mk_next seed_tvs where seed_tvs = tvs `unionVarSet` tyVarsOfTypes ips (ips, non_ips) = partition isIPPred theta -- See note [Inheriting implicit parameters] mk_next :: VarSet -> VarSet -- Maps current set to newly-grown ones mk_next so_far = foldr (grow_one so_far) emptyVarSet non_ips grow_one so_far pred tvs | pred_tvs `intersectsVarSet` so_far = tvs `unionVarSet` pred_tvs | otherwise = tvs where pred_tvs = tyVarsOfType pred {- Note [Quantifying over equality constraints] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Should we quantify over an equality constraint (s ~ t)? In general, we don't. Doing so may simply postpone a type error from the function definition site to its call site. (At worst, imagine (Int ~ Bool)). However, consider this forall a. (F [a] ~ Int) => blah Should we quantify over the (F [a] ~ Int). Perhaps yes, because at the call site we will know 'a', and perhaps we have instance F [Bool] = Int. So we *do* quantify over a type-family equality where the arguments mention the quantified variables. Note [Growing the tau-tvs using constraints] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (growThetaTyVars insts tvs) is the result of extending the set of tyvars tvs using all conceivable links from pred E.g. tvs = {a}, preds = {H [a] b, K (b,Int) c, Eq e} Then growThetaTyVars preds tvs = {a,b,c} Notice that growThetaTyVars is conservative if v might be fixed by vs => v `elem` grow(vs,C) Note [Inheriting implicit parameters] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this: f x = (x::Int) + ?y where f is *not* a top-level binding. From the RHS of f we'll get the constraint (?y::Int). There are two types we might infer for f: f :: Int -> Int (so we get ?y from the context of f's definition), or f :: (?y::Int) => Int -> Int At first you might think the first was better, because then ?y behaves like a free variable of the definition, rather than having to be passed at each call site. But of course, the WHOLE IDEA is that ?y should be passed at each call site (that's what dynamic binding means) so we'd better infer the second. BOTTOM LINE: when *inferring types* you must quantify over implicit parameters, *even if* they don't mention the bound type variables. Reason: because implicit parameters, uniquely, have local instance declarations. See the pickQuantifiablePreds. Note [Quantification with errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we find that the RHS of the definition has some absolutely-insoluble constraints, we abandon all attempts to find a context to quantify over, and instead make the function fully-polymorphic in whatever type we have found. For two reasons a) Minimise downstream errors b) Avoid spurious errors from this function But NB that we must include *derived* errors in the check. Example: (a::*) ~ Int# We get an insoluble derived error *~#, and we don't want to discard it before doing the isInsolubleWC test! (Trac #8262) Note [Default while Inferring] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Our current plan is that defaulting only happens at simplifyTop and not simplifyInfer. This may lead to some insoluble deferred constraints Example: instance D g => C g Int b constraint inferred = (forall b. 0 => C gamma alpha b) /\ Num alpha type inferred = gamma -> gamma Now, if we try to default (alpha := Int) we will be able to refine the implication to (forall b. 0 => C gamma Int b) which can then be simplified further to (forall b. 0 => D gamma) Finally we /can/ approximate this implication with (D gamma) and infer the quantified type: forall g. D g => g -> g Instead what will currently happen is that we will get a quantified type (forall g. g -> g) and an implication: forall g. 0 => (forall b. 0 => C g alpha b) /\ Num alpha which, even if the simplifyTop defaults (alpha := Int) we will still be left with an unsolvable implication: forall g. 0 => (forall b. 0 => D g) The concrete example would be: h :: C g a s => g -> a -> ST s a f (x::gamma) = (\_ -> x) (runST (h x (undefined::alpha)) + 1) But it is quite tedious to do defaulting and resolve the implication constraints and we have not observed code breaking because of the lack of defaulting in inference so we don't do it for now. Note [Minimize by Superclasses] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we quantify over a constraint, in simplifyInfer we need to quantify over a constraint that is minimal in some sense: For instance, if the final wanted constraint is (Eq alpha, Ord alpha), we'd like to quantify over Ord alpha, because we can just get Eq alpha from superclass selection from Ord alpha. This minimization is what mkMinimalBySCs does. Then, simplifyInfer uses the minimal constraint to check the original wanted. Note [Avoid unecessary constraint simplification] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -------- NB NB NB (Jun 12) ------------- This note not longer applies; see the notes with Trac #4361. But I'm leaving it in here so we remember the issue.) ---------------------------------------- When inferring the type of a let-binding, with simplifyInfer, try to avoid unnecessarily simplifying class constraints. Doing so aids sharing, but it also helps with delicate situations like instance C t => C [t] where .. f :: C [t] => .... f x = let g y = ...(constraint C [t])... in ... When inferring a type for 'g', we don't want to apply the instance decl, because then we can't satisfy (C t). So we just notice that g isn't quantified over 't' and partition the constraints before simplifying. This only half-works, but then let-generalisation only half-works. ********************************************************************************* * * * Main Simplifier * * * *********************************************************************************** Note [Deferring coercion errors to runtime] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ While developing, sometimes it is desirable to allow compilation to succeed even if there are type errors in the code. Consider the following case: module Main where a :: Int a = 'a' main = print "b" Even though `a` is ill-typed, it is not used in the end, so if all that we're interested in is `main` it is handy to be able to ignore the problems in `a`. Since we treat type equalities as evidence, this is relatively simple. Whenever we run into a type mismatch in TcUnify, we normally just emit an error. But it is always safe to defer the mismatch to the main constraint solver. If we do that, `a` will get transformed into co :: Int ~ Char co = ... a :: Int a = 'a' `cast` co The constraint solver would realize that `co` is an insoluble constraint, and emit an error with `reportUnsolved`. But we can also replace the right-hand side of `co` with `error "Deferred type error: Int ~ Char"`. This allows the program to compile, and it will run fine unless we evaluate `a`. This is what `deferErrorsToRuntime` does. It does this by keeping track of which errors correspond to which coercion in TcErrors (with ErrEnv). TcErrors.reportTidyWanteds does not print the errors and does not fail if -fdefer-type-errors is on, so that we can continue compilation. The errors are turned into warnings in `reportUnsolved`. -} solveWantedsTcM :: [CtEvidence] -> TcM WantedConstraints -- Simplify the input constraints -- Discard the evidence binds -- Discards all Derived stuff in result -- Result is /not/ guaranteed zonked solveWantedsTcM wanted = do { (wanted1, _binds) <- runTcS (solveWantedsAndDrop (mkSimpleWC wanted)) ; return wanted1 } solveWantedsAndDrop :: WantedConstraints -> TcS WantedConstraints -- Since solveWanteds returns the residual WantedConstraints, -- it should always be called within a runTcS or something similar, -- Result is not zonked solveWantedsAndDrop wanted = do { wc <- solveWanteds wanted ; return (dropDerivedWC wc) } solveWanteds :: WantedConstraints -> TcS WantedConstraints -- so that the inert set doesn't mindlessly propagate. -- NB: wc_simples may be wanted /or/ derived now solveWanteds wc@(WC { wc_simple = simples, wc_insol = insols, wc_impl = implics }) = do { traceTcS "solveWanteds {" (ppr wc) -- Try the simple bit, including insolubles. Solving insolubles a -- second time round is a bit of a waste; but the code is simple -- and the program is wrong anyway, and we don't run the danger -- of adding Derived insolubles twice; see -- TcSMonad Note [Do not add duplicate derived insolubles] ; wc1 <- solveSimpleWanteds simples ; let WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 } = wc1 ; (floated_eqs, implics2) <- solveNestedImplications (implics `unionBags` implics1) ; final_wc <- simpl_loop 0 floated_eqs (WC { wc_simple = simples1, wc_impl = implics2 , wc_insol = insols `unionBags` insols1 }) ; bb <- getTcEvBindsMap ; traceTcS "solveWanteds }" $ vcat [ text "final wc =" <+> ppr final_wc , text "current evbinds =" <+> ppr (evBindMapBinds bb) ] ; return final_wc } simpl_loop :: Int -> Cts -> WantedConstraints -> TcS WantedConstraints simpl_loop n floated_eqs wc@(WC { wc_simple = simples, wc_insol = insols, wc_impl = implics }) | n > 10 = do { traceTcS "solveWanteds: loop!" (ppr wc); return wc } | no_floated_eqs = return wc -- Done! | otherwise = do { traceTcS "simpl_loop, iteration" (int n) -- solveSimples may make progress if either float_eqs hold ; (unifs_happened1, wc1) <- if no_floated_eqs then return (False, emptyWC) else reportUnifications $ solveSimpleWanteds (floated_eqs `unionBags` simples) -- Put floated_eqs first so they get solved first -- NB: the floated_eqs may include /derived/ equalities -- arising from fundeps inside an implication ; let WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 } = wc1 -- solveImplications may make progress only if unifs2 holds ; (floated_eqs2, implics2) <- if not unifs_happened1 && isEmptyBag implics1 then return (emptyBag, implics) else solveNestedImplications (implics `unionBags` implics1) ; simpl_loop (n+1) floated_eqs2 (WC { wc_simple = simples1, wc_impl = implics2 , wc_insol = insols `unionBags` insols1 }) } where no_floated_eqs = isEmptyBag floated_eqs solveNestedImplications :: Bag Implication -> TcS (Cts, Bag Implication) -- Precondition: the TcS inerts may contain unsolved simples which have -- to be converted to givens before we go inside a nested implication. solveNestedImplications implics | isEmptyBag implics = return (emptyBag, emptyBag) | otherwise = do { traceTcS "solveNestedImplications starting {" empty ; (floated_eqs_s, unsolved_implics) <- mapAndUnzipBagM solveImplication implics ; let floated_eqs = concatBag floated_eqs_s -- ... and we are back in the original TcS inerts -- Notice that the original includes the _insoluble_simples so it was safe to ignore -- them in the beginning of this function. ; traceTcS "solveNestedImplications end }" $ vcat [ text "all floated_eqs =" <+> ppr floated_eqs , text "unsolved_implics =" <+> ppr unsolved_implics ] ; return (floated_eqs, catBagMaybes unsolved_implics) } solveImplication :: Implication -- Wanted -> TcS (Cts, -- All wanted or derived floated equalities: var = type Maybe Implication) -- Simplified implication (empty or singleton) -- Precondition: The TcS monad contains an empty worklist and given-only inerts -- which after trying to solve this implication we must restore to their original value solveImplication imp@(Implic { ic_tclvl = tclvl , ic_binds = ev_binds , ic_skols = skols , ic_given = givens , ic_wanted = wanteds , ic_info = info , ic_status = status , ic_env = env }) | IC_Solved {} <- status = return (emptyCts, Just imp) -- Do nothing | otherwise -- Even for IC_Insoluble it is worth doing more work -- The insoluble stuff might be in one sub-implication -- and other unsolved goals in another; and we want to -- solve the latter as much as possible = do { inerts <- getTcSInerts ; traceTcS "solveImplication {" (ppr imp $$ text "Inerts" <+> ppr inerts) -- Solve the nested constraints ; (no_given_eqs, given_insols, residual_wanted) <- nestImplicTcS ev_binds tclvl $ do { given_insols <- solveSimpleGivens (mkGivenLoc tclvl info env) givens ; no_eqs <- getNoGivenEqs tclvl skols ; residual_wanted <- solveWanteds wanteds -- solveWanteds, *not* solveWantedsAndDrop, because -- we want to retain derived equalities so we can float -- them out in floatEqualities ; return (no_eqs, given_insols, residual_wanted) } ; (floated_eqs, residual_wanted) <- floatEqualities skols no_given_eqs residual_wanted ; let final_wanted = residual_wanted `addInsols` given_insols ; res_implic <- setImplicationStatus (imp { ic_no_eqs = no_given_eqs , ic_wanted = final_wanted }) ; evbinds <- getTcEvBindsMap ; traceTcS "solveImplication end }" $ vcat [ text "no_given_eqs =" <+> ppr no_given_eqs , text "floated_eqs =" <+> ppr floated_eqs , text "res_implic =" <+> ppr res_implic , text "implication evbinds = " <+> ppr (evBindMapBinds evbinds) ] ; return (floated_eqs, res_implic) } ---------------------- setImplicationStatus :: Implication -> TcS (Maybe Implication) -- Finalise the implication returned from solveImplication: -- * Set the ic_status field -- * Trim the ic_wanted field to remove Derived constraints -- Return Nothing if we can discard the implication altogether setImplicationStatus implic@(Implic { ic_binds = EvBindsVar ev_binds_var _ , ic_info = info , ic_wanted = wc , ic_given = givens }) | some_insoluble = return $ Just $ implic { ic_status = IC_Insoluble , ic_wanted = wc { wc_simple = pruned_simples , wc_insol = pruned_insols } } | some_unsolved = return $ Just $ implic { ic_status = IC_Unsolved , ic_wanted = wc { wc_simple = pruned_simples , wc_insol = pruned_insols } } | otherwise -- Everything is solved; look at the implications -- See Note [Tracking redundant constraints] = do { ev_binds <- TcS.readTcRef ev_binds_var ; let all_needs = neededEvVars ev_binds implic_needs dead_givens | warnRedundantGivens info = filterOut (`elemVarSet` all_needs) givens | otherwise = [] -- None to report final_needs = all_needs `delVarSetList` givens discard_entire_implication -- Can we discard the entire implication? = null dead_givens -- No warning from this implication && isEmptyBag pruned_implics -- No live children && isEmptyVarSet final_needs -- No needed vars to pass up to parent final_status = IC_Solved { ics_need = final_needs , ics_dead = dead_givens } final_implic = implic { ic_status = final_status , ic_wanted = wc { wc_simple = pruned_simples , wc_insol = pruned_insols , wc_impl = pruned_implics } } -- We can only prune the child implications (pruned_implics) -- in the IC_Solved status case, because only then we can -- accumulate their needed evidence variales into the -- IC_Solved final_status field of the parent implication. ; return $ if discard_entire_implication then Nothing else Just final_implic } where WC { wc_simple = simples, wc_impl = implics, wc_insol = insols } = wc some_insoluble = insolubleWC wc some_unsolved = not (isEmptyBag simples && isEmptyBag insols) || isNothing mb_implic_needs pruned_simples = dropDerivedSimples simples pruned_insols = dropDerivedInsols insols pruned_implics = filterBag need_to_keep_implic implics mb_implic_needs :: Maybe VarSet -- Just vs => all implics are IC_Solved, with 'vs' needed -- Nothing => at least one implic is not IC_Solved mb_implic_needs = foldrBag add_implic (Just emptyVarSet) implics Just implic_needs = mb_implic_needs add_implic implic acc | Just vs_acc <- acc , IC_Solved { ics_need = vs } <- ic_status implic = Just (vs `unionVarSet` vs_acc) | otherwise = Nothing need_to_keep_implic ic | IC_Solved { ics_dead = [] } <- ic_status ic -- Fully solved, and no redundant givens to report , isEmptyBag (wc_impl (ic_wanted ic)) -- And no children that might have things to report = False | otherwise = True warnRedundantGivens :: SkolemInfo -> Bool warnRedundantGivens (SigSkol ctxt _) = case ctxt of FunSigCtxt _ warn_redundant -> warn_redundant ExprSigCtxt -> True _ -> False warnRedundantGivens InstSkol = True warnRedundantGivens _ = False neededEvVars :: EvBindMap -> VarSet -> VarSet -- Find all the evidence variables that are "needed", -- and then delete all those bound by the evidence bindings -- A variable is "needed" if -- a) it is free in the RHS of a Wanted EvBind (add_wanted) -- b) it is free in the RHS of an EvBind whose LHS is needed (transClo) -- c) it is in the ic_need_evs of a nested implication (initial_seeds) -- (after removing the givens) neededEvVars ev_binds initial_seeds = needed `minusVarSet` bndrs where seeds = foldEvBindMap add_wanted initial_seeds ev_binds needed = transCloVarSet also_needs seeds bndrs = foldEvBindMap add_bndr emptyVarSet ev_binds add_wanted :: EvBind -> VarSet -> VarSet add_wanted (EvBind { eb_is_given = is_given, eb_rhs = rhs }) needs | is_given = needs -- Add the rhs vars of the Wanted bindings only | otherwise = evVarsOfTerm rhs `unionVarSet` needs also_needs :: VarSet -> VarSet also_needs needs = foldVarSet add emptyVarSet needs where add v needs | Just ev_bind <- lookupEvBind ev_binds v , EvBind { eb_is_given = is_given, eb_rhs = rhs } <- ev_bind , is_given = evVarsOfTerm rhs `unionVarSet` needs | otherwise = needs add_bndr :: EvBind -> VarSet -> VarSet add_bndr (EvBind { eb_lhs = v }) vs = extendVarSet vs v {- Note [Tracking redundant constraints] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ With Opt_WarnRedundantConstraints, GHC can report which constraints of a type signature (or instance declaration) are redundant, and can be omitted. Here is an overview of how it works: ----- What is a redudant constraint? * The things that can be redundant are precisely the Given constraints of an implication. * A constraint can be redundant in two different ways: a) It is implied by other givens. E.g. f :: (Eq a, Ord a) => blah -- Eq a unnecessary g :: (Eq a, a~b, Eq b) => blah -- Either Eq a or Eq b unnecessary b) It is not needed by the Wanted constraints covered by the implication E.g. f :: Eq a => a -> Bool f x = True -- Equality not uesd * To find (a), when we have two Given constraints, we must be careful to drop the one that is a naked variable (if poss). So if we have f :: (Eq a, Ord a) => blah then we may find [G] sc_sel (d1::Ord a) :: Eq a [G] d2 :: Eq a We want to discard d2 in favour of the superclass selection from the Ord dictionary. This is done by TcInteract.solveOneFromTheOther See Note [Replacement vs keeping]. * To find (b) we need to know which evidence bindings are 'wanted'; hence the eb_is_given field on an EvBind. ----- How tracking works * When the constraint solver finishes solving all the wanteds in an implication, it sets its status to IC_Solved - The ics_dead field of IC_Solved records the subset of the ic_given of this implication that are redundant (not needed). - The ics_need field of IC_Solved then records all the in-scope (given) evidence variables, bound by the context, that were needed to solve this implication, including all its nested implications. (We remove the ic_given of this implication from the set, of course.) * We compute which evidence variables are needed by an implication in setImplicationStatus. A variable is needed if a) it is free in the RHS of a Wanted EvBind b) it is free in the RHS of an EvBind whose LHS is needed c) it is in the ics_need of a nested implication * We need to be careful not to discard an implication prematurely, even one that is fully solved, because we might thereby forget which variables it needs, and hence wrongly report a constraint as redundant. But we can discard it once its free vars have been incorporated into its parent; or if it simply has no free vars. This careful discarding is also handled in setImplicationStatus ----- Reporting redundant constraints * TcErrors does the actual warning, in warnRedundantConstraints. * We don't report redundant givens for *every* implication; only for those which reply True to TcSimplify.warnRedundantGivens: - For example, in a class declaration, the default method *can* use the class constraint, but it certainly doesn't *have* to, and we don't want to report an error there. - More subtly, in a function definition f :: (Ord a, Ord a, Ix a) => a -> a f x = rhs we do an ambiguity check on the type (which would find that one of the Ord a constraints was redundant), and then we check that the definition has that type (which might find that both are redundant). We don't want to report the same error twice, so we disable it for the ambiguity check. Hence the flag in TcType.FunSigCtxt. This decision is taken in setImplicationStatus, rather than TcErrors so that we can discard implication constraints that we don't need. So ics_dead consists only of the *reportable* redundant givens. ----- Shortcomings Consider (see Trac #9939) f2 :: (Eq a, Ord a) => a -> a -> Bool -- Ord a redundant, but Eq a is reported f2 x y = (x == y) We report (Eq a) as redundant, whereas actually (Ord a) is. But it's really not easy to detect that! Note [Cutting off simpl_loop] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is very important not to iterate in simpl_loop unless there is a chance of progress. Trac #8474 is a classic example: * There's a deeply-nested chain of implication constraints. ?x:alpha => ?y1:beta1 => ... ?yn:betan => [W] ?x:Int * From the innermost one we get a [D] alpha ~ Int, but alpha is untouchable until we get out to the outermost one * We float [D] alpha~Int out (it is in floated_eqs), but since alpha is untouchable, the solveInteract in simpl_loop makes no progress * So there is no point in attempting to re-solve ?yn:betan => [W] ?x:Int because we'll just get the same [D] again * If we *do* re-solve, we'll get an ininite loop. It is cut off by the fixed bound of 10, but solving the next takes 10*10*...*10 (ie exponentially many) iterations! Conclusion: we should iterate simpl_loop iff we will get more 'givens' in the inert set when solving the nested implications. That is the result of prepareInertsForImplications is larger. How can we tell this? Consider floated_eqs (all wanted or derived): (a) [W/D] CTyEqCan (a ~ ty). This can give rise to a new given only by causing a unification. So we count those unifications. (b) [W] CFunEqCan (F tys ~ xi). Even though these are wanted, they are pushed in as givens by prepareInertsForImplications. See Note [Preparing inert set for implications] in TcSMonad. But because of that very fact, we won't generate another copy if we iterate simpl_loop. So we iterate if there any of these -} promoteTyVar :: TcLevel -> TcTyVar -> TcS TcTyVar -- When we float a constraint out of an implication we must restore -- invariant (MetaTvInv) in Note [TcLevel and untouchable type variables] in TcType -- See Note [Promoting unification variables] promoteTyVar tclvl tv | isFloatedTouchableMetaTyVar tclvl tv = do { cloned_tv <- TcS.cloneMetaTyVar tv ; let rhs_tv = setMetaTyVarTcLevel cloned_tv tclvl ; unifyTyVar tv (mkTyVarTy rhs_tv) ; return rhs_tv } | otherwise = return tv promoteAndDefaultTyVar :: TcLevel -> TcTyVarSet -> TcTyVar -> TcS TcTyVar -- See Note [Promote _and_ default when inferring] promoteAndDefaultTyVar tclvl gbl_tvs tv = do { tv1 <- if tv `elemVarSet` gbl_tvs then return tv else defaultTyVar tv ; promoteTyVar tclvl tv1 } defaultTyVar :: TcTyVar -> TcS TcTyVar -- Precondition: MetaTyVars only -- See Note [DefaultTyVar] defaultTyVar the_tv | Just default_k <- defaultKind_maybe (tyVarKind the_tv) = do { tv' <- TcS.cloneMetaTyVar the_tv ; let new_tv = setTyVarKind tv' default_k ; traceTcS "defaultTyVar" (ppr the_tv <+> ppr new_tv) ; unifyTyVar the_tv (mkTyVarTy new_tv) ; return new_tv } -- Why not directly derived_pred = mkTcEqPred k default_k? -- See Note [DefaultTyVar] -- We keep the same TcLevel on tv' | otherwise = return the_tv -- The common case approximateWC :: WantedConstraints -> Cts -- Postcondition: Wanted or Derived Cts -- See Note [ApproximateWC] approximateWC wc = float_wc emptyVarSet wc where float_wc :: TcTyVarSet -> WantedConstraints -> Cts float_wc trapping_tvs (WC { wc_simple = simples, wc_impl = implics }) = filterBag is_floatable simples `unionBags` do_bag (float_implic new_trapping_tvs) implics where is_floatable ct = tyVarsOfCt ct `disjointVarSet` new_trapping_tvs new_trapping_tvs = transCloVarSet grow trapping_tvs grow :: VarSet -> VarSet -- Maps current trapped tyvars to newly-trapped ones grow so_far = foldrBag (grow_one so_far) emptyVarSet simples grow_one so_far ct tvs | ct_tvs `intersectsVarSet` so_far = tvs `unionVarSet` ct_tvs | otherwise = tvs where ct_tvs = tyVarsOfCt ct float_implic :: TcTyVarSet -> Implication -> Cts float_implic trapping_tvs imp | ic_no_eqs imp -- No equalities, so float = float_wc new_trapping_tvs (ic_wanted imp) | otherwise -- Don't float out of equalities = emptyCts -- See Note [ApproximateWC] where new_trapping_tvs = trapping_tvs `extendVarSetList` ic_skols imp do_bag :: (a -> Bag c) -> Bag a -> Bag c do_bag f = foldrBag (unionBags.f) emptyBag {- Note [ApproximateWC] ~~~~~~~~~~~~~~~~~~~~ approximateWC takes a constraint, typically arising from the RHS of a let-binding whose type we are *inferring*, and extracts from it some *simple* constraints that we might plausibly abstract over. Of course the top-level simple constraints are plausible, but we also float constraints out from inside, if they are not captured by skolems. The same function is used when doing type-class defaulting (see the call to applyDefaultingRules) to extract constraints that that might be defaulted. There are two caveats: 1. We do *not* float anything out if the implication binds equality constraints, because that defeats the OutsideIn story. Consider data T a where TInt :: T Int MkT :: T a f TInt = 3::Int We get the implication (a ~ Int => res ~ Int), where so far we've decided f :: T a -> res We don't want to float (res~Int) out because then we'll infer f :: T a -> Int which is only on of the possible types. (GHC 7.6 accidentally *did* float out of such implications, which meant it would happily infer non-principal types.) 2. We do not float out an inner constraint that shares a type variable (transitively) with one that is trapped by a skolem. Eg forall a. F a ~ beta, Integral beta We don't want to float out (Integral beta). Doing so would be bad when defaulting, because then we'll default beta:=Integer, and that makes the error message much worse; we'd get Can't solve F a ~ Integer rather than Can't solve Integral (F a) Moreover, floating out these "contaminated" constraints doesn't help when generalising either. If we generalise over (Integral b), we still can't solve the retained implication (forall a. F a ~ b). Indeed, arguably that too would be a harder error to understand. Note [DefaultTyVar] ~~~~~~~~~~~~~~~~~~~ defaultTyVar is used on any un-instantiated meta type variables to default the kind of OpenKind and ArgKind etc to *. This is important to ensure that instance declarations match. For example consider instance Show (a->b) foo x = show (\_ -> True) Then we'll get a constraint (Show (p ->q)) where p has kind ArgKind, and that won't match the typeKind (*) in the instance decl. See tests tc217 and tc175. We look only at touchable type variables. No further constraints are going to affect these type variables, so it's time to do it by hand. However we aren't ready to default them fully to () or whatever, because the type-class defaulting rules have yet to run. An important point is that if the type variable tv has kind k and the default is default_k we do not simply generate [D] (k ~ default_k) because: (1) k may be ArgKind and default_k may be * so we will fail (2) We need to rewrite all occurrences of the tv to be a type variable with the right kind and we choose to do this by rewriting the type variable /itself/ by a new variable which does have the right kind. Note [Promote _and_ default when inferring] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we are inferring a type, we simplify the constraint, and then use approximateWC to produce a list of candidate constraints. Then we MUST a) Promote any meta-tyvars that have been floated out by approximateWC, to restore invariant (MetaTvInv) described in Note [TcLevel and untouchable type variables] in TcType. b) Default the kind of any meta-tyyvars that are not mentioned in in the environment. To see (b), suppose the constraint is (C ((a :: OpenKind) -> Int)), and we have an instance (C ((x:*) -> Int)). The instance doesn't match -- but it should! If we don't solve the constraint, we'll stupidly quantify over (C (a->Int)) and, worse, in doing so zonkQuantifiedTyVar will quantify over (b:*) instead of (a:OpenKind), which can lead to disaster; see Trac #7332. Trac #7641 is a simpler example. Note [Promoting unification variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we float an equality out of an implication we must "promote" free unification variables of the equality, in order to maintain Invariant (MetaTvInv) from Note [TcLevel and untouchable type variables] in TcType. for the leftover implication. This is absolutely necessary. Consider the following example. We start with two implications and a class with a functional dependency. class C x y | x -> y instance C [a] [a] (I1) [untch=beta]forall b. 0 => F Int ~ [beta] (I2) [untch=beta]forall c. 0 => F Int ~ [[alpha]] /\ C beta [c] We float (F Int ~ [beta]) out of I1, and we float (F Int ~ [[alpha]]) out of I2. They may react to yield that (beta := [alpha]) which can then be pushed inwards the leftover of I2 to get (C [alpha] [a]) which, using the FunDep, will mean that (alpha := a). In the end we will have the skolem 'b' escaping in the untouchable beta! Concrete example is in indexed_types/should_fail/ExtraTcsUntch.hs: class C x y | x -> y where op :: x -> y -> () instance C [a] [a] type family F a :: * h :: F Int -> () h = undefined data TEx where TEx :: a -> TEx f (x::beta) = let g1 :: forall b. b -> () g1 _ = h [x] g2 z = case z of TEx y -> (h [[undefined]], op x [y]) in (g1 '3', g2 undefined) Note [Solving Family Equations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ After we are done with simplification we may be left with constraints of the form: [Wanted] F xis ~ beta If 'beta' is a touchable unification variable not already bound in the TyBinds then we'd like to create a binding for it, effectively "defaulting" it to be 'F xis'. When is it ok to do so? 1) 'beta' must not already be defaulted to something. Example: [Wanted] F Int ~ beta <~ Will default [beta := F Int] [Wanted] F Char ~ beta <~ Already defaulted, can't default again. We have to report this as unsolved. 2) However, we must still do an occurs check when defaulting (F xis ~ beta), to set [beta := F xis] only if beta is not among the free variables of xis. 3) Notice that 'beta' can't be bound in ty binds already because we rewrite RHS of type family equations. See Inert Set invariants in TcInteract. This solving is now happening during zonking, see Note [Unflattening while zonking] in TcMType. ********************************************************************************* * * * Floating equalities * * * ********************************************************************************* Note [Float Equalities out of Implications] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For ordinary pattern matches (including existentials) we float equalities out of implications, for instance: data T where MkT :: Eq a => a -> T f x y = case x of MkT _ -> (y::Int) We get the implication constraint (x::T) (y::alpha): forall a. [untouchable=alpha] Eq a => alpha ~ Int We want to float out the equality into a scope where alpha is no longer untouchable, to solve the implication! But we cannot float equalities out of implications whose givens may yield or contain equalities: data T a where T1 :: T Int T2 :: T Bool T3 :: T a h :: T a -> a -> Int f x y = case x of T1 -> y::Int T2 -> y::Bool T3 -> h x y We generate constraint, for (x::T alpha) and (y :: beta): [untouchables = beta] (alpha ~ Int => beta ~ Int) -- From 1st branch [untouchables = beta] (alpha ~ Bool => beta ~ Bool) -- From 2nd branch (alpha ~ beta) -- From 3rd branch If we float the equality (beta ~ Int) outside of the first implication and the equality (beta ~ Bool) out of the second we get an insoluble constraint. But if we just leave them inside the implications we unify alpha := beta and solve everything. Principle: We do not want to float equalities out which may need the given *evidence* to become soluble. Consequence: classes with functional dependencies don't matter (since there is no evidence for a fundep equality), but equality superclasses do matter (since they carry evidence). -} floatEqualities :: [TcTyVar] -> Bool -> WantedConstraints -> TcS (Cts, WantedConstraints) -- Main idea: see Note [Float Equalities out of Implications] -- -- Precondition: the wc_simple of the incoming WantedConstraints are -- fully zonked, so that we can see their free variables -- -- Postcondition: The returned floated constraints (Cts) are only -- Wanted or Derived and come from the input wanted -- ev vars or deriveds -- -- Also performs some unifications (via promoteTyVar), adding to -- monadically-carried ty_binds. These will be used when processing -- floated_eqs later -- -- Subtleties: Note [Float equalities from under a skolem binding] -- Note [Skolem escape] floatEqualities skols no_given_eqs wanteds@(WC { wc_simple = simples }) | not no_given_eqs -- There are some given equalities, so don't float = return (emptyBag, wanteds) -- Note [Float Equalities out of Implications] | otherwise = do { outer_tclvl <- TcS.getTcLevel ; mapM_ (promoteTyVar outer_tclvl) (varSetElems (tyVarsOfCts float_eqs)) -- See Note [Promoting unification variables] ; traceTcS "floatEqualities" (vcat [ text "Skols =" <+> ppr skols , text "Simples =" <+> ppr simples , text "Floated eqs =" <+> ppr float_eqs ]) ; return (float_eqs, wanteds { wc_simple = remaining_simples }) } where skol_set = mkVarSet skols (float_eqs, remaining_simples) = partitionBag (usefulToFloat is_useful) simples is_useful pred = tyVarsOfType pred `disjointVarSet` skol_set {- Note [Float equalities from under a skolem binding] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Which of the simple equalities can we float out? Obviously, only ones that don't mention the skolem-bound variables. But that is over-eager. Consider [2] forall a. F a beta[1] ~ gamma[2], G beta[1] gamma[2] ~ Int The second constraint doesn't mention 'a'. But if we float it we'll promote gamma[2] to gamma'[1]. Now suppose that we learn that beta := Bool, and F a Bool = a, and G Bool _ = Int. Then we'll we left with the constraint [2] forall a. a ~ gamma'[1] which is insoluble because gamma became untouchable. Solution: float only constraints that stand a jolly good chance of being soluble simply by being floated, namely ones of form a ~ ty where 'a' is a currently-untouchable unification variable, but may become touchable by being floated (perhaps by more than one level). We had a very complicated rule previously, but this is nice and simple. (To see the notes, look at this Note in a version of TcSimplify prior to Oct 2014). Note [Skolem escape] ~~~~~~~~~~~~~~~~~~~~ You might worry about skolem escape with all this floating. For example, consider [2] forall a. (a ~ F beta[2] delta, Maybe beta[2] ~ gamma[1]) The (Maybe beta ~ gamma) doesn't mention 'a', so we float it, and solve with gamma := beta. But what if later delta:=Int, and F b Int = b. Then we'd get a ~ beta[2], and solve to get beta:=a, and now the skolem has escaped! But it's ok: when we float (Maybe beta[2] ~ gamma[1]), we promote beta[2] to beta[1], and that means the (a ~ beta[1]) will be stuck, as it should be. ********************************************************************************* * * * Defaulting and disamgiguation * * * ********************************************************************************* -} applyDefaultingRules :: WantedConstraints -> TcS Bool -- True <=> I did some defaulting, by unifying a meta-tyvar -- Imput WantedConstraints are not necessarily zonked applyDefaultingRules wanteds | isEmptyWC wanteds = return False | otherwise = do { info@(default_tys, _) <- getDefaultInfo ; wanteds <- TcS.zonkWC wanteds ; let groups = findDefaultableGroups info wanteds ; traceTcS "applyDefaultingRules {" $ vcat [ text "wanteds =" <+> ppr wanteds , text "groups =" <+> ppr groups , text "info =" <+> ppr info ] ; something_happeneds <- mapM (disambigGroup default_tys) groups ; traceTcS "applyDefaultingRules }" (ppr something_happeneds) ; return (or something_happeneds) } findDefaultableGroups :: ( [Type] , (Bool,Bool) ) -- (Overloaded strings, extended default rules) -> WantedConstraints -- Unsolved (wanted or derived) -> [(TyVar, [Ct])] findDefaultableGroups (default_tys, (ovl_strings, extended_defaults)) wanteds | null default_tys = [] | otherwise = [ (tv, map fstOf3 group) | group@((_,_,tv):_) <- unary_groups , defaultable_tyvar tv , defaultable_classes (map sndOf3 group) ] where simples = approximateWC wanteds (unaries, non_unaries) = partitionWith find_unary (bagToList simples) unary_groups = equivClasses cmp_tv unaries unary_groups :: [[(Ct, Class, TcTyVar)]] -- (C tv) constraints unaries :: [(Ct, Class, TcTyVar)] -- (C tv) constraints non_unaries :: [Ct] -- and *other* constraints -- Finds unary type-class constraints -- But take account of polykinded classes like Typeable, -- which may look like (Typeable * (a:*)) (Trac #8931) find_unary cc | Just (cls,tys) <- getClassPredTys_maybe (ctPred cc) , Just (kinds, ty) <- snocView tys -- Ignore kind arguments , all isKind kinds -- for this purpose , Just tv <- tcGetTyVar_maybe ty , isMetaTyVar tv -- We might have runtime-skolems in GHCi, and -- we definitely don't want to try to assign to those! = Left (cc, cls, tv) find_unary cc = Right cc -- Non unary or non dictionary bad_tvs :: TcTyVarSet -- TyVars mentioned by non-unaries bad_tvs = mapUnionVarSet tyVarsOfCt non_unaries cmp_tv (_,_,tv1) (_,_,tv2) = tv1 `compare` tv2 defaultable_tyvar tv = let b1 = isTyConableTyVar tv -- Note [Avoiding spurious errors] b2 = not (tv `elemVarSet` bad_tvs) in b1 && b2 defaultable_classes clss | extended_defaults = any isInteractiveClass clss | otherwise = all is_std_class clss && (any is_num_class clss) -- In interactive mode, or with -XExtendedDefaultRules, -- we default Show a to Show () to avoid graututious errors on "show []" isInteractiveClass cls = is_num_class cls || (classKey cls `elem` [showClassKey, eqClassKey, ordClassKey]) is_num_class cls = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey)) -- is_num_class adds IsString to the standard numeric classes, -- when -foverloaded-strings is enabled is_std_class cls = isStandardClass cls || (ovl_strings && (cls `hasKey` isStringClassKey)) -- Similarly is_std_class ------------------------------ disambigGroup :: [Type] -- The default types -> (TcTyVar, [Ct]) -- All classes of the form (C a) -- sharing same type variable -> TcS Bool -- True <=> something happened, reflected in ty_binds disambigGroup [] _ = return False disambigGroup (default_ty:default_tys) group@(the_tv, wanteds) = do { traceTcS "disambigGroup {" (vcat [ ppr default_ty, ppr the_tv, ppr wanteds ]) ; fake_ev_binds_var <- TcS.newTcEvBinds ; tclvl <- TcS.getTcLevel ; success <- nestImplicTcS fake_ev_binds_var (pushTcLevel tclvl) try_group ; if success then -- Success: record the type variable binding, and return do { unifyTyVar the_tv default_ty ; wrapWarnTcS $ warnDefaulting wanteds default_ty ; traceTcS "disambigGroup succeeded }" (ppr default_ty) ; return True } else -- Failure: try with the next type do { traceTcS "disambigGroup failed, will try other default types }" (ppr default_ty) ; disambigGroup default_tys group } } where try_group | Just subst <- mb_subst = do { wanted_evs <- mapM (newWantedEvVarNC loc . substTy subst . ctPred) wanteds ; residual_wanted <- solveSimpleWanteds $ listToBag $ map mkNonCanonical wanted_evs ; return (isEmptyWC residual_wanted) } | otherwise = return False tmpl_tvs = extendVarSet (tyVarsOfType (tyVarKind the_tv)) the_tv mb_subst = tcMatchTy tmpl_tvs (mkTyVarTy the_tv) default_ty -- Make sure the kinds match too; hence this call to tcMatchTy -- E.g. suppose the only constraint was (Typeable k (a::k)) loc = CtLoc { ctl_origin = GivenOrigin UnkSkol , ctl_env = panic "disambigGroup:env" , ctl_depth = initialSubGoalDepth } {- Note [Avoiding spurious errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When doing the unification for defaulting, we check for skolem type variables, and simply don't default them. For example: f = (*) -- Monomorphic g :: Num a => a -> a g x = f x x Here, we get a complaint when checking the type signature for g, that g isn't polymorphic enough; but then we get another one when dealing with the (Num a) context arising from f's definition; we try to unify a with Int (to default it), but find that it's already been unified with the rigid variable from g's type sig -}
fmthoma/ghc
compiler/typecheck/TcSimplify.hs
Haskell
bsd-3-clause
77,037
{- This module handles generation of position independent code and dynamic-linking related issues for the native code generator. This depends both the architecture and OS, so we define it here instead of in one of the architecture specific modules. Things outside this module which are related to this: + module CLabel - PIC base label (pretty printed as local label 1) - DynamicLinkerLabels - several kinds: CodeStub, SymbolPtr, GotSymbolPtr, GotSymbolOffset - labelDynamic predicate + module Cmm - The GlobalReg datatype has a PicBaseReg constructor - The CmmLit datatype has a CmmLabelDiffOff constructor + codeGen & RTS - When tablesNextToCode, no absolute addresses are stored in info tables any more. Instead, offsets from the info label are used. - For Win32 only, SRTs might contain addresses of __imp_ symbol pointers because Win32 doesn't support external references in data sections. TODO: make sure this still works, it might be bitrotted + NCG - The cmmToCmm pass in AsmCodeGen calls cmmMakeDynamicReference for all labels. - nativeCodeGen calls pprImportedSymbol and pprGotDeclaration to output all the necessary stuff for imported symbols. - The NCG monad keeps track of a list of imported symbols. - MachCodeGen invokes initializePicBase to generate code to initialize the PIC base register when needed. - MachCodeGen calls cmmMakeDynamicReference whenever it uses a CLabel that wasn't in the original Cmm code (e.g. floating point literals). -} module PIC ( cmmMakeDynamicReference, CmmMakeDynamicReferenceM(..), ReferenceKind(..), needImportedSymbols, pprImportedSymbol, pprGotDeclaration, initializePicBase_ppc, initializePicBase_x86 ) where import qualified PPC.Instr as PPC import qualified PPC.Regs as PPC import qualified X86.Instr as X86 import Platform import Instruction import Reg import NCGMonad import Hoopl import Cmm import CLabel ( CLabel, ForeignLabelSource(..), pprCLabel, mkDynamicLinkerLabel, DynamicLinkerLabelInfo(..), dynamicLinkerLabelInfo, mkPicBaseLabel, labelDynamic, externallyVisibleCLabel ) import CLabel ( mkForeignLabel ) import BasicTypes import Module import Outputable import DynFlags import FastString -------------------------------------------------------------------------------- -- It gets called by the cmmToCmm pass for every CmmLabel in the Cmm -- code. It does The Right Thing(tm) to convert the CmmLabel into a -- position-independent, dynamic-linking-aware reference to the thing -- in question. -- Note that this also has to be called from MachCodeGen in order to -- access static data like floating point literals (labels that were -- created after the cmmToCmm pass). -- The function must run in a monad that can keep track of imported symbols -- A function for recording an imported symbol must be passed in: -- - addImportCmmOpt for the CmmOptM monad -- - addImportNat for the NatM monad. data ReferenceKind = DataReference | CallReference | JumpReference deriving(Eq) class Monad m => CmmMakeDynamicReferenceM m where addImport :: CLabel -> m () getThisModule :: m Module instance CmmMakeDynamicReferenceM NatM where addImport = addImportNat getThisModule = getThisModuleNat cmmMakeDynamicReference :: CmmMakeDynamicReferenceM m => DynFlags -> ReferenceKind -- whether this is the target of a jump -> CLabel -- the label -> m CmmExpr cmmMakeDynamicReference dflags referenceKind lbl | Just _ <- dynamicLinkerLabelInfo lbl = return $ CmmLit $ CmmLabel lbl -- already processed it, pass through | otherwise = do this_mod <- getThisModule case howToAccessLabel dflags (platformArch $ targetPlatform dflags) (platformOS $ targetPlatform dflags) this_mod referenceKind lbl of AccessViaStub -> do let stub = mkDynamicLinkerLabel CodeStub lbl addImport stub return $ CmmLit $ CmmLabel stub AccessViaSymbolPtr -> do let symbolPtr = mkDynamicLinkerLabel SymbolPtr lbl addImport symbolPtr return $ CmmLoad (cmmMakePicReference dflags symbolPtr) (bWord dflags) AccessDirectly -> case referenceKind of -- for data, we might have to make some calculations: DataReference -> return $ cmmMakePicReference dflags lbl -- all currently supported processors support -- PC-relative branch and call instructions, -- so just jump there if it's a call or a jump _ -> return $ CmmLit $ CmmLabel lbl -- ----------------------------------------------------------------------------- -- Create a position independent reference to a label. -- (but do not bother with dynamic linking). -- We calculate the label's address by adding some (platform-dependent) -- offset to our base register; this offset is calculated by -- the function picRelative in the platform-dependent part below. cmmMakePicReference :: DynFlags -> CLabel -> CmmExpr cmmMakePicReference dflags lbl -- Windows doesn't need PIC, -- everything gets relocated at runtime | OSMinGW32 <- platformOS $ targetPlatform dflags = CmmLit $ CmmLabel lbl | OSAIX <- platformOS $ targetPlatform dflags = CmmMachOp (MO_Add W32) [ CmmReg (CmmGlobal PicBaseReg) , CmmLit $ picRelative (platformArch $ targetPlatform dflags) (platformOS $ targetPlatform dflags) lbl ] -- both ABI versions default to medium code model | ArchPPC_64 _ <- platformArch $ targetPlatform dflags = CmmMachOp (MO_Add W32) -- code model medium [ CmmReg (CmmGlobal PicBaseReg) , CmmLit $ picRelative (platformArch $ targetPlatform dflags) (platformOS $ targetPlatform dflags) lbl ] | (gopt Opt_PIC dflags || WayDyn `elem` ways dflags) && absoluteLabel lbl = CmmMachOp (MO_Add (wordWidth dflags)) [ CmmReg (CmmGlobal PicBaseReg) , CmmLit $ picRelative (platformArch $ targetPlatform dflags) (platformOS $ targetPlatform dflags) lbl ] | otherwise = CmmLit $ CmmLabel lbl absoluteLabel :: CLabel -> Bool absoluteLabel lbl = case dynamicLinkerLabelInfo lbl of Just (GotSymbolPtr, _) -> False Just (GotSymbolOffset, _) -> False _ -> True -------------------------------------------------------------------------------- -- Knowledge about how special dynamic linker labels like symbol -- pointers, code stubs and GOT offsets look like is located in the -- module CLabel. -- We have to decide which labels need to be accessed -- indirectly or via a piece of stub code. data LabelAccessStyle = AccessViaStub | AccessViaSymbolPtr | AccessDirectly howToAccessLabel :: DynFlags -> Arch -> OS -> Module -> ReferenceKind -> CLabel -> LabelAccessStyle -- Windows -- In Windows speak, a "module" is a set of objects linked into the -- same Portable Exectuable (PE) file. (both .exe and .dll files are PEs). -- -- If we're compiling a multi-module program then symbols from other modules -- are accessed by a symbol pointer named __imp_SYMBOL. At runtime we have the -- following. -- -- (in the local module) -- __imp_SYMBOL: addr of SYMBOL -- -- (in the other module) -- SYMBOL: the real function / data. -- -- To access the function at SYMBOL from our local module, we just need to -- dereference the local __imp_SYMBOL. -- -- If not compiling with -dynamic we assume that all our code will be linked -- into the same .exe file. In this case we always access symbols directly, -- and never use __imp_SYMBOL. -- howToAccessLabel dflags _ OSMinGW32 this_mod _ lbl -- Assume all symbols will be in the same PE, so just access them directly. | WayDyn `notElem` ways dflags = AccessDirectly -- If the target symbol is in another PE we need to access it via the -- appropriate __imp_SYMBOL pointer. | labelDynamic dflags this_mod lbl = AccessViaSymbolPtr -- Target symbol is in the same PE as the caller, so just access it directly. | otherwise = AccessDirectly -- Mach-O (Darwin, Mac OS X) -- -- Indirect access is required in the following cases: -- * things imported from a dynamic library -- * (not on x86_64) data from a different module, if we're generating PIC code -- It is always possible to access something indirectly, -- even when it's not necessary. -- howToAccessLabel dflags arch OSDarwin this_mod DataReference lbl -- data access to a dynamic library goes via a symbol pointer | labelDynamic dflags this_mod lbl = AccessViaSymbolPtr -- when generating PIC code, all cross-module data references must -- must go via a symbol pointer, too, because the assembler -- cannot generate code for a label difference where one -- label is undefined. Doesn't apply t x86_64. -- Unfortunately, we don't know whether it's cross-module, -- so we do it for all externally visible labels. -- This is a slight waste of time and space, but otherwise -- we'd need to pass the current Module all the way in to -- this function. | arch /= ArchX86_64 , gopt Opt_PIC dflags && externallyVisibleCLabel lbl = AccessViaSymbolPtr | otherwise = AccessDirectly howToAccessLabel dflags arch OSDarwin this_mod JumpReference lbl -- dyld code stubs don't work for tailcalls because the -- stack alignment is only right for regular calls. -- Therefore, we have to go via a symbol pointer: | arch == ArchX86 || arch == ArchX86_64 , labelDynamic dflags this_mod lbl = AccessViaSymbolPtr howToAccessLabel dflags arch OSDarwin this_mod _ lbl -- Code stubs are the usual method of choice for imported code; -- not needed on x86_64 because Apple's new linker, ld64, generates -- them automatically. | arch /= ArchX86_64 , labelDynamic dflags this_mod lbl = AccessViaStub | otherwise = AccessDirectly ---------------------------------------------------------------------------- -- AIX -- quite simple (for now) howToAccessLabel _dflags _arch OSAIX _this_mod kind _lbl = case kind of DataReference -> AccessViaSymbolPtr CallReference -> AccessDirectly JumpReference -> AccessDirectly -- ELF (Linux) -- -- ELF tries to pretend to the main application code that dynamic linking does -- not exist. While this may sound convenient, it tends to mess things up in -- very bad ways, so we have to be careful when we generate code for the main -- program (-dynamic but no -fPIC). -- -- Indirect access is required for references to imported symbols -- from position independent code. It is also required from the main program -- when dynamic libraries containing Haskell code are used. howToAccessLabel _ (ArchPPC_64 _) os _ kind _ | osElfTarget os = case kind of -- ELF PPC64 (powerpc64-linux), AIX, MacOS 9, BeOS/PPC DataReference -> AccessViaSymbolPtr -- RTLD does not generate stubs for function descriptors -- in tail calls. Create a symbol pointer and generate -- the code to load the function descriptor at the call site. JumpReference -> AccessViaSymbolPtr -- regular calls are handled by the runtime linker _ -> AccessDirectly howToAccessLabel dflags _ os _ _ _ -- no PIC -> the dynamic linker does everything for us; -- if we don't dynamically link to Haskell code, -- it actually manages to do so without messing things up. | osElfTarget os , not (gopt Opt_PIC dflags) && WayDyn `notElem` ways dflags = AccessDirectly howToAccessLabel dflags arch os this_mod DataReference lbl | osElfTarget os = case () of -- A dynamic label needs to be accessed via a symbol pointer. _ | labelDynamic dflags this_mod lbl -> AccessViaSymbolPtr -- For PowerPC32 -fPIC, we have to access even static data -- via a symbol pointer (see below for an explanation why -- PowerPC32 Linux is especially broken). | arch == ArchPPC , gopt Opt_PIC dflags -> AccessViaSymbolPtr | otherwise -> AccessDirectly -- In most cases, we have to avoid symbol stubs on ELF, for the following reasons: -- on i386, the position-independent symbol stubs in the Procedure Linkage Table -- require the address of the GOT to be loaded into register %ebx on entry. -- The linker will take any reference to the symbol stub as a hint that -- the label in question is a code label. When linking executables, this -- will cause the linker to replace even data references to the label with -- references to the symbol stub. -- This leaves calling a (foreign) function from non-PIC code -- (AccessDirectly, because we get an implicit symbol stub) -- and calling functions from PIC code on non-i386 platforms (via a symbol stub) howToAccessLabel dflags arch os this_mod CallReference lbl | osElfTarget os , labelDynamic dflags this_mod lbl && not (gopt Opt_PIC dflags) = AccessDirectly | osElfTarget os , arch /= ArchX86 , labelDynamic dflags this_mod lbl && gopt Opt_PIC dflags = AccessViaStub howToAccessLabel dflags _ os this_mod _ lbl | osElfTarget os = if labelDynamic dflags this_mod lbl then AccessViaSymbolPtr else AccessDirectly -- all other platforms howToAccessLabel dflags _ _ _ _ _ | not (gopt Opt_PIC dflags) = AccessDirectly | otherwise = panic "howToAccessLabel: PIC not defined for this platform" -- ------------------------------------------------------------------- -- | Says what we we have to add to our 'PIC base register' in order to -- get the address of a label. picRelative :: Arch -> OS -> CLabel -> CmmLit -- Darwin, but not x86_64: -- The PIC base register points to the PIC base label at the beginning -- of the current CmmDecl. We just have to use a label difference to -- get the offset. -- We have already made sure that all labels that are not from the current -- module are accessed indirectly ('as' can't calculate differences between -- undefined labels). picRelative arch OSDarwin lbl | arch /= ArchX86_64 = CmmLabelDiffOff lbl mkPicBaseLabel 0 -- On AIX we use an indirect local TOC anchored by 'gotLabel'. -- This way we use up only one global TOC entry per compilation-unit -- (this is quite similiar to GCC's @-mminimal-toc@ compilation mode) picRelative _ OSAIX lbl = CmmLabelDiffOff lbl gotLabel 0 -- PowerPC Linux: -- The PIC base register points to our fake GOT. Use a label difference -- to get the offset. -- We have made sure that *everything* is accessed indirectly, so this -- is only used for offsets from the GOT to symbol pointers inside the -- GOT. picRelative ArchPPC os lbl | osElfTarget os = CmmLabelDiffOff lbl gotLabel 0 -- Most Linux versions: -- The PIC base register points to the GOT. Use foo@got for symbol -- pointers, and foo@gotoff for everything else. -- Linux and Darwin on x86_64: -- The PIC base register is %rip, we use foo@gotpcrel for symbol pointers, -- and a GotSymbolOffset label for other things. -- For reasons of tradition, the symbol offset label is written as a plain label. picRelative arch os lbl | osElfTarget os || (os == OSDarwin && arch == ArchX86_64) = let result | Just (SymbolPtr, lbl') <- dynamicLinkerLabelInfo lbl = CmmLabel $ mkDynamicLinkerLabel GotSymbolPtr lbl' | otherwise = CmmLabel $ mkDynamicLinkerLabel GotSymbolOffset lbl in result picRelative _ _ _ = panic "PositionIndependentCode.picRelative undefined for this platform" -------------------------------------------------------------------------------- needImportedSymbols :: DynFlags -> Arch -> OS -> Bool needImportedSymbols dflags arch os | os == OSDarwin , arch /= ArchX86_64 = True | os == OSAIX = True -- PowerPC Linux: -fPIC or -dynamic | osElfTarget os , arch == ArchPPC = gopt Opt_PIC dflags || WayDyn `elem` ways dflags -- PowerPC 64 Linux: always | osElfTarget os , arch == ArchPPC_64 ELF_V1 || arch == ArchPPC_64 ELF_V2 = True -- i386 (and others?): -dynamic but not -fPIC | osElfTarget os , arch /= ArchPPC_64 ELF_V1 && arch /= ArchPPC_64 ELF_V2 = WayDyn `elem` ways dflags && not (gopt Opt_PIC dflags) | otherwise = False -- gotLabel -- The label used to refer to our "fake GOT" from -- position-independent code. gotLabel :: CLabel gotLabel -- HACK: this label isn't really foreign = mkForeignLabel (fsLit ".LCTOC1") Nothing ForeignLabelInThisPackage IsData -------------------------------------------------------------------------------- -- We don't need to declare any offset tables. -- However, for PIC on x86, we need a small helper function. pprGotDeclaration :: DynFlags -> Arch -> OS -> SDoc pprGotDeclaration dflags ArchX86 OSDarwin | gopt Opt_PIC dflags = vcat [ text ".section __TEXT,__textcoal_nt,coalesced,no_toc", text ".weak_definition ___i686.get_pc_thunk.ax", text ".private_extern ___i686.get_pc_thunk.ax", text "___i686.get_pc_thunk.ax:", text "\tmovl (%esp), %eax", text "\tret" ] pprGotDeclaration _ _ OSDarwin = empty -- Emit XCOFF TOC section pprGotDeclaration _ _ OSAIX = vcat $ [ text ".toc" , text ".tc ghc_toc_table[TC],.LCTOC1" , text ".csect ghc_toc_table[RW]" -- See Note [.LCTOC1 in PPC PIC code] , text ".set .LCTOC1,$+0x8000" ] -- PPC 64 ELF v1needs a Table Of Contents (TOC) on Linux pprGotDeclaration _ (ArchPPC_64 ELF_V1) OSLinux = text ".section \".toc\",\"aw\"" -- In ELF v2 we also need to tell the assembler that we want ABI -- version 2. This would normally be done at the top of the file -- right after a file directive, but I could not figure out how -- to do that. pprGotDeclaration _ (ArchPPC_64 ELF_V2) OSLinux = vcat [ text ".abiversion 2", text ".section \".toc\",\"aw\"" ] pprGotDeclaration _ (ArchPPC_64 _) _ = panic "pprGotDeclaration: ArchPPC_64 only Linux supported" -- Emit GOT declaration -- Output whatever needs to be output once per .s file. pprGotDeclaration dflags arch os | osElfTarget os , arch /= ArchPPC_64 ELF_V1 && arch /= ArchPPC_64 ELF_V2 , not (gopt Opt_PIC dflags) = empty | osElfTarget os , arch /= ArchPPC_64 ELF_V1 && arch /= ArchPPC_64 ELF_V2 = vcat [ -- See Note [.LCTOC1 in PPC PIC code] text ".section \".got2\",\"aw\"", text ".LCTOC1 = .+32768" ] pprGotDeclaration _ _ _ = panic "pprGotDeclaration: no match" -------------------------------------------------------------------------------- -- On Darwin, we have to generate our own stub code for lazy binding.. -- For each processor architecture, there are two versions, one for PIC -- and one for non-PIC. -- -- Whenever you change something in this assembler output, make sure -- the splitter in driver/split/ghc-split.pl recognizes the new output pprImportedSymbol :: DynFlags -> Platform -> CLabel -> SDoc pprImportedSymbol dflags platform@(Platform { platformArch = ArchPPC, platformOS = OSDarwin }) importedLbl | Just (CodeStub, lbl) <- dynamicLinkerLabelInfo importedLbl = case gopt Opt_PIC dflags of False -> vcat [ text ".symbol_stub", text "L" <> pprCLabel platform lbl <> ptext (sLit "$stub:"), text "\t.indirect_symbol" <+> pprCLabel platform lbl, text "\tlis r11,ha16(L" <> pprCLabel platform lbl <> text "$lazy_ptr)", text "\tlwz r12,lo16(L" <> pprCLabel platform lbl <> text "$lazy_ptr)(r11)", text "\tmtctr r12", text "\taddi r11,r11,lo16(L" <> pprCLabel platform lbl <> text "$lazy_ptr)", text "\tbctr" ] True -> vcat [ text ".section __TEXT,__picsymbolstub1," <> text "symbol_stubs,pure_instructions,32", text "\t.align 2", text "L" <> pprCLabel platform lbl <> ptext (sLit "$stub:"), text "\t.indirect_symbol" <+> pprCLabel platform lbl, text "\tmflr r0", text "\tbcl 20,31,L0$" <> pprCLabel platform lbl, text "L0$" <> pprCLabel platform lbl <> char ':', text "\tmflr r11", text "\taddis r11,r11,ha16(L" <> pprCLabel platform lbl <> text "$lazy_ptr-L0$" <> pprCLabel platform lbl <> char ')', text "\tmtlr r0", text "\tlwzu r12,lo16(L" <> pprCLabel platform lbl <> text "$lazy_ptr-L0$" <> pprCLabel platform lbl <> text ")(r11)", text "\tmtctr r12", text "\tbctr" ] $+$ vcat [ text ".lazy_symbol_pointer", text "L" <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr:"), text "\t.indirect_symbol" <+> pprCLabel platform lbl, text "\t.long dyld_stub_binding_helper"] | Just (SymbolPtr, lbl) <- dynamicLinkerLabelInfo importedLbl = vcat [ text ".non_lazy_symbol_pointer", char 'L' <> pprCLabel platform lbl <> text "$non_lazy_ptr:", text "\t.indirect_symbol" <+> pprCLabel platform lbl, text "\t.long\t0"] | otherwise = empty pprImportedSymbol dflags platform@(Platform { platformArch = ArchX86, platformOS = OSDarwin }) importedLbl | Just (CodeStub, lbl) <- dynamicLinkerLabelInfo importedLbl = case gopt Opt_PIC dflags of False -> vcat [ text ".symbol_stub", text "L" <> pprCLabel platform lbl <> ptext (sLit "$stub:"), text "\t.indirect_symbol" <+> pprCLabel platform lbl, text "\tjmp *L" <> pprCLabel platform lbl <> text "$lazy_ptr", text "L" <> pprCLabel platform lbl <> text "$stub_binder:", text "\tpushl $L" <> pprCLabel platform lbl <> text "$lazy_ptr", text "\tjmp dyld_stub_binding_helper" ] True -> vcat [ text ".section __TEXT,__picsymbolstub2," <> text "symbol_stubs,pure_instructions,25", text "L" <> pprCLabel platform lbl <> ptext (sLit "$stub:"), text "\t.indirect_symbol" <+> pprCLabel platform lbl, text "\tcall ___i686.get_pc_thunk.ax", text "1:", text "\tmovl L" <> pprCLabel platform lbl <> text "$lazy_ptr-1b(%eax),%edx", text "\tjmp *%edx", text "L" <> pprCLabel platform lbl <> text "$stub_binder:", text "\tlea L" <> pprCLabel platform lbl <> text "$lazy_ptr-1b(%eax),%eax", text "\tpushl %eax", text "\tjmp dyld_stub_binding_helper" ] $+$ vcat [ text ".section __DATA, __la_sym_ptr" <> (if gopt Opt_PIC dflags then int 2 else int 3) <> text ",lazy_symbol_pointers", text "L" <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr:"), text "\t.indirect_symbol" <+> pprCLabel platform lbl, text "\t.long L" <> pprCLabel platform lbl <> text "$stub_binder"] | Just (SymbolPtr, lbl) <- dynamicLinkerLabelInfo importedLbl = vcat [ text ".non_lazy_symbol_pointer", char 'L' <> pprCLabel platform lbl <> text "$non_lazy_ptr:", text "\t.indirect_symbol" <+> pprCLabel platform lbl, text "\t.long\t0"] | otherwise = empty pprImportedSymbol _ (Platform { platformOS = OSDarwin }) _ = empty -- XCOFF / AIX -- -- Similiar to PPC64 ELF v1, there's dedicated TOC register (r2). To -- workaround the limitation of a global TOC we use an indirect TOC -- with the label `ghc_toc_table`. -- -- See also GCC's `-mminimal-toc` compilation mode or -- http://www.ibm.com/developerworks/rational/library/overview-toc-aix/ -- -- NB: No DSO-support yet pprImportedSymbol _ platform@(Platform { platformOS = OSAIX }) importedLbl = case dynamicLinkerLabelInfo importedLbl of Just (SymbolPtr, lbl) -> vcat [ text "LC.." <> pprCLabel platform lbl <> char ':', text "\t.long" <+> pprCLabel platform lbl ] _ -> empty -- ELF / Linux -- -- In theory, we don't need to generate any stubs or symbol pointers -- by hand for Linux. -- -- Reality differs from this in two areas. -- -- 1) If we just use a dynamically imported symbol directly in a read-only -- section of the main executable (as GCC does), ld generates R_*_COPY -- relocations, which are fundamentally incompatible with reversed info -- tables. Therefore, we need a table of imported addresses in a writable -- section. -- The "official" GOT mechanism (label@got) isn't intended to be used -- in position dependent code, so we have to create our own "fake GOT" -- when not Opt_PIC && WayDyn `elem` ways dflags. -- -- 2) PowerPC Linux is just plain broken. -- While it's theoretically possible to use GOT offsets larger -- than 16 bit, the standard crt*.o files don't, which leads to -- linker errors as soon as the GOT size exceeds 16 bit. -- Also, the assembler doesn't support @gotoff labels. -- In order to be able to use a larger GOT, we have to circumvent the -- entire GOT mechanism and do it ourselves (this is also what GCC does). -- When needImportedSymbols is defined, -- the NCG will keep track of all DynamicLinkerLabels it uses -- and output each of them using pprImportedSymbol. pprImportedSymbol _ platform@(Platform { platformArch = ArchPPC_64 _ }) importedLbl | osElfTarget (platformOS platform) = case dynamicLinkerLabelInfo importedLbl of Just (SymbolPtr, lbl) -> vcat [ text ".section \".toc\", \"aw\"", text ".LC_" <> pprCLabel platform lbl <> char ':', text "\t.quad" <+> pprCLabel platform lbl ] _ -> empty pprImportedSymbol dflags platform importedLbl | osElfTarget (platformOS platform) = case dynamicLinkerLabelInfo importedLbl of Just (SymbolPtr, lbl) -> let symbolSize = case wordWidth dflags of W32 -> sLit "\t.long" W64 -> sLit "\t.quad" _ -> panic "Unknown wordRep in pprImportedSymbol" in vcat [ text ".section \".got2\", \"aw\"", text ".LC_" <> pprCLabel platform lbl <> char ':', ptext symbolSize <+> pprCLabel platform lbl ] -- PLT code stubs are generated automatically by the dynamic linker. _ -> empty pprImportedSymbol _ _ _ = panic "PIC.pprImportedSymbol: no match" -------------------------------------------------------------------------------- -- Generate code to calculate the address that should be put in the -- PIC base register. -- This is called by MachCodeGen for every CmmProc that accessed the -- PIC base register. It adds the appropriate instructions to the -- top of the CmmProc. -- It is assumed that the first NatCmmDecl in the input list is a Proc -- and the rest are CmmDatas. -- Darwin is simple: just fetch the address of a local label. -- The FETCHPC pseudo-instruction is expanded to multiple instructions -- during pretty-printing so that we don't have to deal with the -- local label: -- PowerPC version: -- bcl 20,31,1f. -- 1: mflr picReg -- i386 version: -- call 1f -- 1: popl %picReg -- Get a pointer to our own fake GOT, which is defined on a per-module basis. -- This is exactly how GCC does it in linux. initializePicBase_ppc :: Arch -> OS -> Reg -> [NatCmmDecl CmmStatics PPC.Instr] -> NatM [NatCmmDecl CmmStatics PPC.Instr] initializePicBase_ppc ArchPPC os picReg (CmmProc info lab live (ListGraph blocks) : statics) | osElfTarget os = do let gotOffset = PPC.ImmConstantDiff (PPC.ImmCLbl gotLabel) (PPC.ImmCLbl mkPicBaseLabel) blocks' = case blocks of [] -> [] (b:bs) -> fetchPC b : map maybeFetchPC bs maybeFetchPC b@(BasicBlock bID _) | bID `mapMember` info = fetchPC b | otherwise = b -- GCC does PIC prologs thusly: -- bcl 20,31,.L1 -- .L1: -- mflr 30 -- addis 30,30,.LCTOC1-.L1@ha -- addi 30,30,.LCTOC1-.L1@l -- TODO: below we use it over temporary register, -- it can and should be optimised by picking -- correct PIC reg. fetchPC (BasicBlock bID insns) = BasicBlock bID (PPC.FETCHPC picReg : PPC.ADDIS picReg picReg (PPC.HA gotOffset) : PPC.ADDI picReg picReg (PPC.LO gotOffset) : PPC.MR PPC.r30 picReg : insns) return (CmmProc info lab live (ListGraph blocks') : statics) initializePicBase_ppc ArchPPC OSDarwin picReg (CmmProc info lab live (ListGraph (entry:blocks)) : statics) -- just one entry because of splitting = return (CmmProc info lab live (ListGraph (b':blocks)) : statics) where BasicBlock bID insns = entry b' = BasicBlock bID (PPC.FETCHPC picReg : insns) ------------------------------------------------------------------------- -- Load TOC into register 2 -- PowerPC 64-bit ELF ABI 2.0 requires the address of the callee -- in register 12. -- We pass the label to FETCHTOC and create a .localentry too. -- TODO: Explain this better and refer to ABI spec! {- We would like to do approximately this, but spill slot allocation might be added before the first BasicBlock. That violates the ABI. For now we will emit the prologue code in the pretty printer, which is also what we do for ELF v1. initializePicBase_ppc (ArchPPC_64 ELF_V2) OSLinux picReg (CmmProc info lab live (ListGraph (entry:blocks)) : statics) = do bID <-getUniqueM return (CmmProc info lab live (ListGraph (b':entry:blocks)) : statics) where BasicBlock entryID _ = entry b' = BasicBlock bID [PPC.FETCHTOC picReg lab, PPC.BCC PPC.ALWAYS entryID] -} initializePicBase_ppc _ _ _ _ = panic "initializePicBase_ppc: not needed" -- We cheat a bit here by defining a pseudo-instruction named FETCHGOT -- which pretty-prints as: -- call 1f -- 1: popl %picReg -- addl __GLOBAL_OFFSET_TABLE__+.-1b, %picReg -- (See PprMach.hs) initializePicBase_x86 :: Arch -> OS -> Reg -> [NatCmmDecl (Alignment, CmmStatics) X86.Instr] -> NatM [NatCmmDecl (Alignment, CmmStatics) X86.Instr] initializePicBase_x86 ArchX86 os picReg (CmmProc info lab live (ListGraph blocks) : statics) | osElfTarget os = return (CmmProc info lab live (ListGraph blocks') : statics) where blocks' = case blocks of [] -> [] (b:bs) -> fetchGOT b : map maybeFetchGOT bs -- we want to add a FETCHGOT instruction to the beginning of -- every block that is an entry point, which corresponds to -- the blocks that have entries in the info-table mapping. maybeFetchGOT b@(BasicBlock bID _) | bID `mapMember` info = fetchGOT b | otherwise = b fetchGOT (BasicBlock bID insns) = BasicBlock bID (X86.FETCHGOT picReg : insns) initializePicBase_x86 ArchX86 OSDarwin picReg (CmmProc info lab live (ListGraph (entry:blocks)) : statics) = return (CmmProc info lab live (ListGraph (block':blocks)) : statics) where BasicBlock bID insns = entry block' = BasicBlock bID (X86.FETCHPC picReg : insns) initializePicBase_x86 _ _ _ _ = panic "initializePicBase_x86: not needed"
olsner/ghc
compiler/nativeGen/PIC.hs
Haskell
bsd-3-clause
34,518
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="sr-SP"> <title>GraalVM JavaScript</title> <maps> <homeID>graaljs</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/graaljs/src/main/javahelp/help_sr_SP/helpset_sr_SP.hs
Haskell
apache-2.0
967
module OrphanInstancesClass (AClass(..)) where class AClass a where aClass :: a -> Int
niteria/haddock
html-test/src/OrphanInstancesClass.hs
Haskell
bsd-2-clause
90
{-# LANGUAGE OverloadedStrings #-} -- | BigTable benchmark implemented using Hamlet. -- {-# LANGUAGE QuasiQuotes #-} module Main where import Criterion.Main import Text.Hamlet import Numeric (showInt) import qualified Data.ByteString.Lazy as L import qualified Text.Blaze.Html.Renderer.Utf8 as Utf8 import Data.Monoid (mconcat) import Text.Blaze.Html5 (table, tr, td) import Text.Blaze.Html (toHtml) import Yesod.Core.Widget import Control.Monad.Trans.Writer import Control.Monad.Trans.RWS import Data.Functor.Identity import Yesod.Core.Types import Data.Monoid import Data.IORef main = defaultMain [ bench "bigTable html" $ nf bigTableHtml bigTableData , bench "bigTable hamlet" $ nf bigTableHamlet bigTableData , bench "bigTable widget" $ nfIO (bigTableWidget bigTableData) , bench "bigTable blaze" $ nf bigTableBlaze bigTableData ] where rows :: Int rows = 1000 bigTableData :: [[Int]] bigTableData = replicate rows [1..10] {-# NOINLINE bigTableData #-} bigTableHtml rows = L.length $ Utf8.renderHtml $ ($ id) [hamlet| <table> $forall row <- rows <tr> $forall cell <- row <td>#{show cell} |] bigTableHamlet rows = L.length $ Utf8.renderHtml $ ($ id) [hamlet| <table> $forall row <- rows <tr> $forall cell <- row <td>#{show cell} |] bigTableWidget rows = fmap (L.length . Utf8.renderHtml . ($ render)) (run [whamlet| <table> $forall row <- rows <tr> $forall cell <- row <td>#{show cell} |]) where render _ _ = "foo" run (WidgetT w) = do (_, GWData { gwdBody = Body x }) <- w undefined return x bigTableBlaze t = L.length $ Utf8.renderHtml $ table $ mconcat $ map row t where row r = tr $ mconcat $ map (td . toHtml . show) r
ygale/yesod
yesod-core/bench/widget.hs
Haskell
mit
1,816
----------------------------------------------------------------------------- -- | -- Module : XMonad.Util.Dzen -- Copyright : (c) glasser@mit.edu -- License : BSD -- -- Maintainer : glasser@mit.edu -- Stability : stable -- Portability : unportable -- -- Handy wrapper for dzen. Requires dzen >= 0.2.4. -- ----------------------------------------------------------------------------- module XMonad.Util.Dzen ( -- * Flexible interface dzenConfig, DzenConfig, timeout, font, xScreen, vCenter, hCenter, center, onCurr, x, y, addArgs, -- * Legacy interface dzen, dzenScreen, dzenWithArgs, -- * Miscellaneous seconds, chomp, (>=>), ) where import Control.Monad import XMonad import XMonad.StackSet import XMonad.Util.Run (runProcessWithInputAndWait, seconds) type DzenConfig = (Int, [String]) -> X (Int, [String]) -- | @dzenConfig config s@ will display the string @s@ according to the -- configuration @config@. For example, to display the string @\"foobar\"@ with -- all the default settings, you can simply call -- -- > dzenConfig return "foobar" -- -- Or, to set a longer timeout, you could use -- -- > dzenConfig (timeout 10) "foobar" -- -- You can combine configurations with the (>=>) operator. To display -- @\"foobar\"@ for 10 seconds on the first screen, you could use -- -- > dzenConfig (timeout 10 >=> xScreen 0) "foobar" -- -- As a final example, you could adapt the above to display @\"foobar\"@ for -- 10 seconds on the current screen with -- -- > dzenConfig (timeout 10 >=> onCurr xScreen) "foobar" dzenConfig :: DzenConfig -> String -> X () dzenConfig conf s = do (t, args) <- conf (seconds 3, []) runProcessWithInputAndWait "dzen2" args (chomp s) t -- | dzen wants exactly one newline at the end of its input, so this can be -- used for your own invocations of dzen. However, all functions in this -- module will call this for you. chomp :: String -> String chomp = (++"\n") . reverse . dropWhile ('\n' ==) . reverse -- | Set the timeout, in seconds. This defaults to 3 seconds if not -- specified. timeout :: Rational -> DzenConfig timeout = timeoutMicro . seconds -- | Set the timeout, in microseconds. Mostly here for the legacy -- interface. timeoutMicro :: Int -> DzenConfig timeoutMicro n (_, ss) = return (n, ss) -- | Add raw command-line arguments to the configuration. These will be -- passed on verbatim to dzen2. The default includes no arguments. addArgs :: [String] -> DzenConfig addArgs ss (n, ss') = return (n, ss ++ ss') -- | Start dzen2 on a particular screen. Only works with versions of dzen -- that support the "-xs" argument. xScreen :: ScreenId -> DzenConfig xScreen sc = addArgs ["-xs", show (fromIntegral sc + 1 :: Int)] -- | Take a screen-specific configuration and supply it with the screen ID -- of the currently focused screen, according to xmonad. For example, show -- a 100-pixel wide bar centered within the current screen, you could use -- -- > dzenConfig (onCurr (hCenter 100)) "foobar" -- -- Of course, you can still combine these with (>=>); for example, to center -- the string @\"foobar\"@ both horizontally and vertically in a 100x14 box -- using the lovely Terminus font, you could use -- -- > terminus = "-*-terminus-*-*-*-*-12-*-*-*-*-*-*-*" -- > dzenConfig (onCurr (center 100 14) >=> font terminus) "foobar" onCurr :: (ScreenId -> DzenConfig) -> DzenConfig onCurr f conf = gets (screen . current . windowset) >>= flip f conf -- | Put the top of the dzen bar at a particular pixel. x :: Int -> DzenConfig x n = addArgs ["-x", show n] -- | Put the left of the dzen bar at a particular pixel. y :: Int -> DzenConfig y n = addArgs ["-y", show n] -- | Specify the font. Check out xfontsel to get the format of the String -- right; if your dzen supports xft, then you can supply that here, too. font :: String -> DzenConfig font fn = addArgs ["-fn", fn] -- | @vCenter height sc@ sets the configuration to have the dzen bar appear -- on screen @sc@ with height @height@, vertically centered with respect to -- the actual size of that screen. vCenter :: Int -> ScreenId -> DzenConfig vCenter = center' rect_height "-h" "-y" -- | @hCenter width sc@ sets the configuration to have the dzen bar appear -- on screen @sc@ with width @width@, horizontally centered with respect to -- the actual size of that screen. hCenter :: Int -> ScreenId -> DzenConfig hCenter = center' rect_width "-w" "-x" -- | @center width height sc@ sets the configuration to have the dzen bar -- appear on screen @sc@ with width @width@ and height @height@, centered -- both horizontally and vertically with respect to the actual size of that -- screen. center :: Int -> Int -> ScreenId -> DzenConfig center width height sc = hCenter width sc >=> vCenter height sc -- Center things along a single dimension on a particular screen. center' :: (Rectangle -> Dimension) -> String -> String -> Int -> ScreenId -> DzenConfig center' selector extentName positionName extent sc conf = do rect <- gets (detailFromScreenId sc . windowset) case rect of Nothing -> return conf Just r -> addArgs [extentName , show extent, positionName, show ((fromIntegral (selector r) - extent) `div` 2), "-xs" , show (fromIntegral sc + 1 :: Int) ] conf -- Get the rectangle outlining a particular screen. detailFromScreenId :: ScreenId -> WindowSet -> Maybe Rectangle detailFromScreenId sc ws = fmap screenRect maybeSD where c = current ws v = visible ws mapping = map (\s -> (screen s, screenDetail s)) (c:v) maybeSD = lookup sc mapping -- | @dzen str timeout@ pipes @str@ to dzen2 for @timeout@ microseconds. -- Example usage: -- -- > dzen "Hi, mom!" (5 `seconds`) dzen :: String -> Int -> X () dzen = flip (dzenConfig . timeoutMicro) -- | @dzen str args timeout@ pipes @str@ to dzen2 for @timeout@ seconds, passing @args@ to dzen. -- Example usage: -- -- > dzenWithArgs "Hi, dons!" ["-ta", "r"] (5 `seconds`) dzenWithArgs :: String -> [String] -> Int -> X () dzenWithArgs str args t = dzenConfig (timeoutMicro t >=> addArgs args) str -- | @dzenScreen sc str timeout@ pipes @str@ to dzen2 for @timeout@ microseconds, and on screen @sc@. -- Requires dzen to be compiled with Xinerama support. dzenScreen :: ScreenId -> String -> Int -> X () dzenScreen sc str t = dzenConfig (timeoutMicro t >=> xScreen sc) str
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Util/Dzen.hs
Haskell
bsd-2-clause
6,457
import Test.Hspec import qualified YesodCoreTest main :: IO () main = hspec YesodCoreTest.specs
psibi/yesod
yesod-core/test/test.hs
Haskell
mit
97
{-# LANGUAGE GADTs #-} module Main where import Data.IORef data T a where Li:: Int -> T Int Lb:: Bool -> T Bool La:: a -> T a writeInt:: T a -> IORef a -> IO () writeInt v ref = case v of ~(Li x) -> writeIORef ref (1::Int) readBool:: T a -> IORef a -> IO () readBool v ref = case v of ~(Lb x) -> readIORef ref >>= (print . not) tt::T a -> IO () tt v = case v of ~(Li x) -> print "OK" main = do tt (La undefined) ref <- newIORef undefined writeInt (La undefined) ref readBool (La undefined) ref
ezyang/ghc
testsuite/tests/gadt/rw.hs
Haskell
bsd-3-clause
610
import Common main = print $ foldl (\acc x -> 10*acc + x) 0 $take 10 $ toDigits $ sum numbers numbers = [ 37107287533902102798797998220837590246510135740250, 46376937677490009712648124896970078050417018260538, 74324986199524741059474233309513058123726617309629, 91942213363574161572522430563301811072406154908250, 23067588207539346171171980310421047513778063246676, 89261670696623633820136378418383684178734361726757, 28112879812849979408065481931592621691275889832738, 44274228917432520321923589422876796487670272189318, 47451445736001306439091167216856844588711603153276, 70386486105843025439939619828917593665686757934951, 62176457141856560629502157223196586755079324193331, 64906352462741904929101432445813822663347944758178, 92575867718337217661963751590579239728245598838407, 58203565325359399008402633568948830189458628227828, 80181199384826282014278194139940567587151170094390, 35398664372827112653829987240784473053190104293586, 86515506006295864861532075273371959191420517255829, 71693888707715466499115593487603532921714970056938, 54370070576826684624621495650076471787294438377604, 53282654108756828443191190634694037855217779295145, 36123272525000296071075082563815656710885258350721, 45876576172410976447339110607218265236877223636045, 17423706905851860660448207621209813287860733969412, 81142660418086830619328460811191061556940512689692, 51934325451728388641918047049293215058642563049483, 62467221648435076201727918039944693004732956340691, 15732444386908125794514089057706229429197107928209, 55037687525678773091862540744969844508330393682126, 18336384825330154686196124348767681297534375946515, 80386287592878490201521685554828717201219257766954, 78182833757993103614740356856449095527097864797581, 16726320100436897842553539920931837441497806860984, 48403098129077791799088218795327364475675590848030, 87086987551392711854517078544161852424320693150332, 59959406895756536782107074926966537676326235447210, 69793950679652694742597709739166693763042633987085, 41052684708299085211399427365734116182760315001271, 65378607361501080857009149939512557028198746004375, 35829035317434717326932123578154982629742552737307, 94953759765105305946966067683156574377167401875275, 88902802571733229619176668713819931811048770190271, 25267680276078003013678680992525463401061632866526, 36270218540497705585629946580636237993140746255962, 24074486908231174977792365466257246923322810917141, 91430288197103288597806669760892938638285025333403, 34413065578016127815921815005561868836468420090470, 23053081172816430487623791969842487255036638784583, 11487696932154902810424020138335124462181441773470, 63783299490636259666498587618221225225512486764533, 67720186971698544312419572409913959008952310058822, 95548255300263520781532296796249481641953868218774, 76085327132285723110424803456124867697064507995236, 37774242535411291684276865538926205024910326572967, 23701913275725675285653248258265463092207058596522, 29798860272258331913126375147341994889534765745501, 18495701454879288984856827726077713721403798879715, 38298203783031473527721580348144513491373226651381, 34829543829199918180278916522431027392251122869539, 40957953066405232632538044100059654939159879593635, 29746152185502371307642255121183693803580388584903, 41698116222072977186158236678424689157993532961922, 62467957194401269043877107275048102390895523597457, 23189706772547915061505504953922979530901129967519, 86188088225875314529584099251203829009407770775672, 11306739708304724483816533873502340845647058077308, 82959174767140363198008187129011875491310547126581, 97623331044818386269515456334926366572897563400500, 42846280183517070527831839425882145521227251250327, 55121603546981200581762165212827652751691296897789, 32238195734329339946437501907836945765883352399886, 75506164965184775180738168837861091527357929701337, 62177842752192623401942399639168044983993173312731, 32924185707147349566916674687634660915035914677504, 99518671430235219628894890102423325116913619626622, 73267460800591547471830798392868535206946944540724, 76841822524674417161514036427982273348055556214818, 97142617910342598647204516893989422179826088076852, 87783646182799346313767754307809363333018982642090, 10848802521674670883215120185883543223812876952786, 71329612474782464538636993009049310363619763878039, 62184073572399794223406235393808339651327408011116, 66627891981488087797941876876144230030984490851411, 60661826293682836764744779239180335110989069790714, 85786944089552990653640447425576083659976645795096, 66024396409905389607120198219976047599490197230297, 64913982680032973156037120041377903785566085089252, 16730939319872750275468906903707539413042652315011, 94809377245048795150954100921645863754710598436791, 78639167021187492431995700641917969777599028300699, 15368713711936614952811305876380278410754449733078, 40789923115535562561142322423255033685442488917353, 44889911501440648020369068063960672322193204149535, 41503128880339536053299340368006977710650566631954, 81234880673210146739058568557934581403627822703280, 82616570773948327592232845941706525094512325230608, 22918802058777319719839450180888072429661980811197, 77158542502016545090413245809786882778948721859617, 72107838435069186155435662884062257473692284509516, 20849603980134001723930671666823555245252804609722, 53503534226472524250874054075591789781264330331690]
lekto/haskell
Project-Euler-Solutions/problem0013.hs
Haskell
mit
5,409
module U.Codebase.Sqlite.Patch.Format where import Data.Vector (Vector) import U.Codebase.Sqlite.DbId (HashId, ObjectId, PatchObjectId, TextId) import U.Codebase.Sqlite.Patch.Diff (LocalPatchDiff) import U.Codebase.Sqlite.Patch.Full (LocalPatch) import Data.ByteString (ByteString) data PatchFormat = Full PatchLocalIds LocalPatch | Diff PatchObjectId PatchLocalIds LocalPatchDiff data PatchLocalIds = LocalIds { patchTextLookup :: Vector TextId, patchHashLookup :: Vector HashId, patchDefnLookup :: Vector ObjectId } data SyncPatchFormat = SyncFull PatchLocalIds ByteString | SyncDiff PatchObjectId PatchLocalIds ByteString
unisonweb/platform
codebase2/codebase-sqlite/U/Codebase/Sqlite/Patch/Format.hs
Haskell
mit
648
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, TypeFamilies #-} module Main where import Data.Bits import Data.Monoid import Control.Monad import Control.Exception import System.Socket import System.Socket.Family.Inet as Inet import System.Exit main :: IO () main = do t0001 t0002 t0003 t0001 :: IO () t0001 = do ais <- getAddressInfo (Just "127.0.0.1") (Just "http") aiNumericHost `onException` p 0 :: IO [AddressInfo Inet Stream TCP] when (length ais /= 1) (e 1) let [ai] = ais when (canonicalName ai /= Nothing) (e 2) let sa = socketAddress ai when (port sa /= 80) (e 3) when (address sa /= Inet.loopback) (e 4) where p i = print ("t0001." ++ show i) e i = error ("t0001." ++ show i) t0002 :: IO () t0002 = do let x = getAddressInfo Nothing Nothing mempty :: IO [AddressInfo Inet Stream TCP] eui <- tryJust (\ex@(AddressInfoException _)-> if ex == eaiNoName then Just () else Nothing) (x `onException` p 0) when (eui /= Left ()) (e 1) where p i = print ("t0002." ++ show i) e i = error ("t0002." ++ show i) -- | This tests the correct funtionality of the flags -- AI_V4MAPPEND and AI_ALL. Asking for localhost should -- yield an additional v4-mappend IPV6-Address in the second case, -- but not in the first one. t0003 :: IO () t0003 = do x <- getAddressInfo (Just "localhost") Nothing mempty `onException` p 0:: IO [AddressInfo Inet6 Stream TCP] y <- getAddressInfo (Just "localhost") Nothing (aiAll `mappend` aiV4Mapped) `onException` p 1 :: IO [AddressInfo Inet6 Stream TCP] when (length x == length y) (e 2) where p i = print ("t0003." ++ show i) e i = error ("t0003." ++ show i)
nh2/haskell-socket
tests/AddrInfo.hs
Haskell
mit
1,838
module Twelve where import Data.Char (toUpper) import Data.List (intersperse, unfoldr) notThe :: String -> Maybe String notThe w | w == "the" || w == "The" = Nothing | otherwise = Just w removeThe :: Maybe String -> String removeThe (Just x) = x removeThe Nothing = "a" replaceThe :: String -> String replaceThe s = concat $ intersperse " " $ fmap (removeThe . notThe) w where w = words s isVowel :: Char -> Bool isVowel letter = elem (toUpper letter) "AEIOU" counter :: (Bool, Integer) -> String -> (Bool, Integer) counter (_, cnt) "the" = (True, cnt) counter (True, cnt) (w:ws) = if isVowel w then (False, cnt+1) else (False, cnt) counter (False, cnt) _ = (False, cnt) countTheBeforeVowel :: String -> Integer countTheBeforeVowel s = (\(_, cnt) -> cnt) $ foldl counter (False, 0) w where w = words s countVowels :: String -> Integer countVowels s = (toInteger . length) $ filter isVowel s newtype Word' = Word' String deriving (Eq, Show) mkWord :: String -> Maybe Word' mkWord s = go s (0, 0) where go [] (consonants, vowels) = if vowels > consonants then Nothing else Just (Word' s) go (x:xs) (consonants, vowels) | isVowel x = go xs (consonants, vowels + 1) | otherwise = go xs (consonants + 1, vowels) data Nat = Zero | Succ Nat deriving (Eq, Show) natToInteger :: Nat -> Integer natToInteger Zero = 0 natToInteger (Succ nat) = 1 + (natToInteger nat) integerToNat :: Integer -> Maybe Nat integerToNat i | i < 0 = Nothing | otherwise = Just (go i) where go int | int == 0 = Zero | otherwise = (Succ (go (int - 1))) isJust :: Maybe a -> Bool isJust Nothing = False isJust (Just _) = True isNothing :: Maybe a -> Bool isNothing Nothing = True isNothing (Just _) = False mayybee :: b -> (a -> b) -> Maybe a -> b mayybee b _ Nothing = b mayybee _ f (Just a) = f a fromMaybe :: a -> Maybe a -> a fromMaybe a m = mayybee a id m listToMaybe :: [a] -> Maybe a listToMaybe [] = Nothing listToMaybe (x:_) = Just x maybeToList :: Maybe a -> [a] maybeToList (Just a) = [a] maybeToList Nothing = [] catMaybes :: [Maybe a] -> [a] catMaybes ms = foldr f [] ms where f (Just a) b = [a] ++ b f Nothing b = b flipMaybe :: [Maybe a] -> Maybe [a] flipMaybe = foldr f (Just []) where f _ Nothing = Nothing f Nothing _ = Nothing f (Just a) (Just b) = Just ([a] ++ b) lefts' :: [Either a b] -> [a] lefts' = foldr f [] where f (Left a) acc = [a] ++ acc f (Right _) acc = acc rights' :: [Either a b] -> [b] rights' = foldr f [] where f (Left _) acc = acc f (Right b) acc = [b] ++ acc partitionEithers' :: [Either a b] -> ([a], [b]) partitionEithers' = foldr f ([], []) where f (Left a) (lefts, rights) = ([a] ++ lefts, rights) f (Right b) (lefts, rights) = (lefts, [b] ++ rights) eitherMaybe' :: (b -> c) -> Either a b -> Maybe c eitherMaybe' _ (Left _) = Nothing eitherMaybe' f (Right b) = Just (f b) either' :: (a -> c) -> (b -> c) -> Either a b -> c either' f _ (Left a) = f a either' _ g (Right b) = g b eitherMaybe'' :: (b -> c) -> Either a b -> Maybe c eitherMaybe'' _ (Left _) = Nothing eitherMaybe'' g r@(Right b) = Just (either' (\_ -> g b) g r) myIterate :: (a -> a) -> a -> [a] myIterate f a = [a] ++ (myIterate f (f a)) unf :: (Ord b, Num b) => b -> Maybe (b, b) unf n | n > 10 = Nothing | otherwise = Just (n, n + 1) myUnfoldr :: (b -> Maybe (a, b)) -> b -> [a] myUnfoldr f b = go $ f b where go Nothing = [] go (Just (a, nextB)) = [a] ++ (go $ f nextB) betterIterate :: (a -> a) -> a -> [a] betterIterate f x = myUnfoldr (\x -> Just (x, f x)) x
mudphone/HaskellBook
src/Twelve.hs
Haskell
mit
3,627
-- A tutorial on the universality and expressiveness of fold -- TODO: https://jeremykun.com/tag/foldr/ -- foldr -- f x acc fold :: (a -> b -> b) -> b -> [a] -> b fold f v [] = v fold f v (x:xs) = f x (fold f v xs) -- foldl f v (x:xs) = f (fold f v xs) x -- f acc n product = fold (*) 0 and = fold (&) True or = fold (|) False (++) :: [a] -> [a] -> [a] (++ ys) = fold (:) ys length = fold (\x n -> n + 1) 0 reverse = fold (\x xs -> xs ++ [x]) 0 map f = fold (\x xs -> f x : xs) [] filter p = fold (\x xs -> if p x then x : xs else xs) [] -- recursion theory -- universal property (definition) -- g [] = v -- g (x:xs) = f x (g xs) <=> g = fold f v -- (+1) . sum = fold (+) 1 -- (+1) . sum [] = 1 -- (+1) . sum (x : xs) = (+) x (((+1) . sum) xs) -- fusion property -- h w = v -- h (g x y) = f x (h y) <=> h . fold g w = fold f v -- (+1) . sum = fold (+) 1 -- (+1) . fold (+) 0 = fold (+) 1 -- (+1) 0 = 1 -- (+1) ((+) x y) = (+) x ((+1) y) -- infix n op -- (op a) . fold (op) b = fold (op) (b op a) -- map f = fold (\x xs -> f x : xs) [] -- map f [] = [] -- map f (g x : y) = (f . g) x : map f y -- generate tuples -- sum and length sumLength :: [Int] -> (Int, Int) -- sumLength xs = (sum xs, length xs) sumLength = fold (\n (x, y) -> (n + x, 1 + y)) (0, 0) -- cannot be implemented as fold because xs is stateless dropWhile :: (a -> Bool) -> [a] -> [a] -- using tupling techniques we can redefine it dropWhile' :: (a -> Bool) -> ([a] -> ([a], [a])) dropWhile' p = fold f v where f x (ys, xs) = (if p x then ys else x : xs, x : xs) v = ([], []) -- primitive recursion -- h y [] = f y -- h y (x:xs) = g y x (h y xs) -- h y = fold (g y) (f y) -- primitive recursion -- h y [] = f y -- h y (x:xs) = g y x xs (h y xs) -- k y [] = (f y, []) -- k y xs = (h y xs, xs) -- k y [] = j -- k y (x:xs) = i x (k y xs) -- k y = fold i j where -- i x (z, xs) = (g y x xs, x : xs) -- j = (f y, []) -- h y = fst . k y -- generate functions compose :: [a -> a] -> a -> a compose = fold (.) id -- right to left sum :: [Int] -> Int sum = fold (+) 0 suml :: [Int] -> Int suml xs = suml' xs 0 where suml' [] n = n suml' (x:xs) n = suml' xs (n + x) -- suml' :: [Int] -> Int -> Int -- suml' = fold (\x g -> (\n -> g (n + x))) id -- suml xs = fold (\x g -> (\n -> g (n + x))) id xs 0 foldl f v xs = fold (\x g -> (\a -> g (f a x))) id xs v ack :: [Int] -> [Int] -> [Int] ack [] ys = 1 : ys ack (x:xs) [] = ack xs [1] ack (x:xs) (y:ys) = ack xs (ack (x:xs) ys) -- ack = fold (\x g -> fold (\y -> g) ( g [1] )) (1 :) -- Other works -- fold for regular datatypes (not just lists) -- fold for nested datatypes -- fold for functional datatypes -- Monadic fold -- Relational fold -- other reursion operators -- automatic program transformation -- polytypic programming -- programming languages
Airtnp/Freshman_Simple_Haskell_Lib
Theoritical/Universal-fold.hs
Haskell
mit
2,945
module Countdown where data Op = Add | Sub | Mul | Div instance Show Op where show Add = "+" show Sub = "-" show Mul = "*" show Div = "/" valid :: Op -> Int -> Int -> Bool valid Add _ _ = True valid Sub x y = x > y valid Mul _ _ = True valid Div x y = x `mod` y == 0 apply :: Op -> Int -> Int -> Int apply Add x y = x + y apply Sub x y = x - y apply Mul x y = x * y apply Div x y = x `div` y data Expr = Val Int | App Op Expr Expr instance Show Expr where show (Val n) = show n show (App o l r) = brak l ++ show o ++ brak r where brak (Val n) = show n brak e = "(" ++ show e ++ ")" values :: Expr -> [Int] values (Val n) = [n] values (App _ l r) = values l ++ values r eval :: Expr -> [Int] eval (Val n) = [n | n > 0] eval (App o l r) = [apply o x y | x <- eval l, y <- eval r, valid o x y] computer :: Expr -> Int computer = head . eval
brodyberg/LearnHaskell
CaesarCypher.hsproj/Countdown.hs
Haskell
mit
1,051
{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, StandaloneDeriving #-} module Eval where import Prelude hiding (id, exp) import qualified Prelude import Control.Lens hiding (reuses) import Data.Either (partitionEithers) import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import qualified Data.Text as T import Data.Functor.Foldable.Extended import qualified Id import qualified Lam import Lam (BindingWithId, ExpWithId) import qualified Primitives flattenBinding :: BindingWithId i -> Maybe (i, i, Lam.Name, ExpWithId i) flattenBinding binding = flip fmap (Lam.bindingExp binding) $ \exp -> (binding ^. Id.id, Lam.expTopId exp, Lam.bindingName binding, exp) data EvalError i = UndefinedVar i T.Text | UndefinedMember i (Frame i) T.Text | TypeError i (Val i) T.Text deriving (Eq, Ord, Show) type ThunkWithId i = Id.WithId i Identity (Thunk i) data Suspension i = Suspension i (Map i (Val i)) [Suspension i] deriving (Eq, Ord, Show) data Val i = Primitive Primitives.Prim | Thunk [[i]] (Set i) (Env i) (ThunkWithId i) | ValSuspension (Suspension i) | ValFrame (Frame i) | ValList [Val i] deriving (Show, Ord, Eq) type Env i = Map i (Val i) newtype GlobalEnv i = GlobalEnv { unGlobalEnv :: Env i } type Trail i = Set (Frame i, Val i) data Trailing i a = Trailing (Trail i) a data Thunk i = ThunkFn (Env i -> GlobalEnv i -> Either [EvalError i] (Val i)) | ThunkResolvedFn (Frame i -> Env i -> GlobalEnv i -> Lam.Resolved i -> Either [EvalError i] (Trailing i (Val i))) | ThunkEvalFn (Env i -> GlobalEnv i -> (Val i -> Either [EvalError i] (Trailing i (Val i))) -> Either [EvalError i] (Trailing i (Val i))) | ThunkTrailFn (Trail i -> Env i -> GlobalEnv i -> Either [EvalError i] (Val i)) | ThunkExp (ExpWithId i) | ThunkRecord instance Show i => Show (Thunk i) where show (ThunkFn _) = "thunkfn" show (ThunkResolvedFn _) = "thunkresolvedfn" show (ThunkTrailFn _) = "thunktrailfn" show (ThunkEvalFn _) = "thunkevalfn" show (ThunkExp _) = "thunkexp" show (ThunkRecord) = "thunkrecord" pprintVal :: Show i => Val i -> String pprintVal = unlines . go 0 where put indent s = [replicate indent ' ' ++ s] go indent (Primitive p) = put indent ("Primitive " ++ show p) go indent (Thunk ss needed env t) = concat $ [ put indent $ "Thunk " ++ (show $ t ^. Id.id) ++ " " ++ show ss ++ " " ++ (show $ t ^. Id.value) , concat neededArgsRows , put (indent + 2) "has" , concat [ put (indent + 4) (show k) ++ concat [ go (indent + 6) v ] | (k, v) <- Map.assocs env ] ] where neededArgsRows | Set.null needed = [ put (indent + 2) "satisfied" ] | otherwise = [ put (indent + 2) "needs" , concat $ (put (indent + 4) . show) <$> Set.toList needed ] go indent (ValSuspension _) = put indent ("Suspension") go indent (ValFrame frame) = concat [ put indent $ "ValFrame " ++ show (_frameCodeDbId frame) ++ " " ++ show (_frameParent frame) , put (indent + 2) "ValFrameEnv" , concat [ concat [ put (indent + 4) "ValFrameEnvElem" , put (indent + 6) (show k) , go (indent + 8) v ] | (k, v) <- Map.assocs (_frameEnv frame) ] ] go indent (ValList elems) = concat [ put indent "ValList" , concat $ go (indent + 2) <$> elems ] data Frame i = Frame { _frameParent :: Maybe (Frame i) , _frameCodeDbId :: i , _frameEnv :: Env i } deriving (Ord, Eq, Show) makeLenses ''Frame instance (Ord i, Show i, Monoid a) => Monoid (Trailing i a) where mempty = Trailing Set.empty mempty mappend (Trailing t1 v1) (Trailing t2 v2) = Trailing (mappend t1 t2) (mappend v1 v2) instance (Eq a, Eq i) => Eq (Trailing i a) where Trailing t1 v1 == Trailing t2 v2 = (t1 == t2) && (v1 == v2) instance (Show a) => Show (Trailing i a) where show (Trailing _ v1) = show v1 instance Functor (Trailing i) where fmap f (Trailing t v) = Trailing t (f v) instance (Ord i, Show i) => Applicative (Trailing i) where pure v = noTrail v Trailing t1 f <*> Trailing t2 v = Trailing (mappend t1 t2) (f v) noTrail :: Ord i => a -> Trailing i a noTrail v = Trailing mempty v dropTrail :: Trailing t t1 -> t1 dropTrail (Trailing _ v) = v withTrail :: (Trail t -> Trail i) -> Trailing t a -> Trailing i a withTrail f (Trailing t v) = Trailing (f t) v expandTrail :: (Ord i, Show i) => [[i]] -> (Frame i, Val i) -> Trailing i v -> Trailing i v expandTrail [] _ = Prelude.id expandTrail _ frameWithResult = withTrail (Set.insert frameWithResult) withEitherTrail :: (Ord i, Show i) => (v1 -> Either e (Trailing i v2)) -> Either e (Trailing i v1) -> Either e (Trailing i v2) withEitherTrail f e = do Trailing t1 v1 <- e Trailing t2 v2 <- f v1 pure $ Trailing (t1 `mappend` t2) v2 invertTrailingEither :: Trailing i (Either e v) -> Either e (Trailing i v) invertTrailingEither (Trailing t v) = Trailing t <$> v eval :: (Ord i, Show i) => Lam.Resolved i -> GlobalEnv i -> Frame i -> Map i (Val i) -> Trail i -> ExpWithId i -> Either [EvalError i] (Trailing i (Val i)) eval resolved globalEnv parentFrames env trail (Fix (Lam.ExpW (Id.WithId id (Identity v)))) = withEitherTrail (evalVal resolved globalEnv parentFrames env trail) $ case v of Lam.LamF susable args exp -> let argIds = map (^. Id.id) args in noTrail <$> (Thunk <$> flattenSusable resolved id susable <*> pure (Set.fromList argIds) <*> pure env <*> pure (Id.withId id (ThunkExp exp))) Lam.AppF exp args -> flip withEitherTrail (evalArgs resolved globalEnv parentFrames env trail args) $ \argValues -> eval resolved globalEnv parentFrames (Map.union argValues env) trail exp Lam.LamArgIdF var -> case lookupVarId id resolved of Nothing -> Left [UndefinedVar id var] Just varId -> Right $ noTrail $ ValSuspension (Suspension varId Map.empty []) Lam.VarF var -> case lookupVar id resolved env globalEnv of Nothing -> Left [UndefinedVar id var] Just val -> Right $ noTrail val Lam.SuspendF suspendSpec -> let evalSuspension (Lam.SuspendSpec (Id.WithId suspensionId (Identity name)) args parents) = do case Map.lookup suspensionId resolved of Nothing -> Left [UndefinedVar id name] Just resolvedId -> do argsEnv <- evalArgs resolved globalEnv parentFrames env trail args parentSuspensions <- eitherList $ (evalSuspension <$> parents) pure $ Suspension resolvedId (dropTrail argsEnv) parentSuspensions -- noTrail . dropTrail is pretty weird! But since we're evaluating things to specify a suspension, we're kind of not in the real world maybe? Perhaps these shouldn't be expressions in their own right, but references to expressions in the tree that are fully legit? That way there wouldn't be this weird case where expressions don't leave a trail. We don't have a good 'syntax' for referring to expressions like that though. in noTrail . ValSuspension <$> evalSuspension suspendSpec Lam.LitF (Lam.Number n) -> pure $ noTrail $ Primitive $ Primitives.Number n Lam.LitF (Lam.Text n) -> pure $ noTrail $ Primitive $ Primitives.Text n evalArgs :: (Ord i, Show i) => Lam.Resolved i -> GlobalEnv i -> Frame i -> Map i (Val i) -> Trail i -> [(Id.WithId i Identity Lam.Name, ExpWithId i)] -> Either [EvalError i] (Trailing i (Map i (Val i))) evalArgs resolved globalEnv parentFrame env trail args = let evalArg (Id.WithId argId (Identity argName), exp) = case Map.lookup argId resolved of Just resolvedArgId -> fmap (resolvedArgId,) <$> eval resolved globalEnv parentFrame env trail exp Nothing -> Left [UndefinedVar argId argName] in fmap (fmap Map.fromList . sequenceA) . eitherList $ evalArg <$> args eitherList :: Monoid e => [Either e r] -> Either e [r] eitherList es = case partitionEithers es of ([], successesList) -> Right successesList (failuresList, _) -> Left (mconcat failuresList) evalVal :: (Ord i, Show i) => Lam.Resolved i -> GlobalEnv i -> Frame i -> Map i (Val i) -> Trail i -> Val i -> Either [EvalError i] (Trailing i (Val i)) evalVal resolved globalEnv parentFrames env trail (Thunk thunkSusable thunkArgs thunkEnv thunk) = let argsInEnv = Set.intersection thunkArgs (Map.keysSet env) argsEnv = Map.filterWithKey (\k _ -> k `Set.member` argsInEnv) env thunkEnv' = Map.unions [env, argsEnv, thunkEnv] in if Set.size argsInEnv == Set.size thunkArgs then fmap (fmap (reSus thunkSusable)) . evalThunk resolved globalEnv parentFrames trail thunkSusable thunkEnv' argsEnv $ thunk else Right $ noTrail $ Thunk thunkSusable thunkArgs thunkEnv' thunk evalVal _ _ _ _ _ v = Right $ noTrail v evalThunk :: (Show i, Ord i) => Lam.Resolved i -> GlobalEnv i -> Frame i -> Trail i -> [[i]] -> Env i -> Env i -> Id.WithId i Identity (Thunk i) -> Either [EvalError i] (Trailing i (Val i)) evalThunk resolved globalEnv parentFrame trail susable thunkEnv argsEnv thunk = let newFrame = Frame (Just parentFrame) (thunk ^. Id.id) argsEnv in do result <- withEitherTrail (evalVal resolved globalEnv newFrame thunkEnv trail . reSus susable) $ case Id.unId thunk of ThunkFn fn -> fmap noTrail $ fn thunkEnv globalEnv ThunkTrailFn fn -> fmap noTrail $ fn trail thunkEnv globalEnv ThunkResolvedFn fn -> fn newFrame thunkEnv globalEnv resolved ThunkEvalFn fn -> fn thunkEnv globalEnv (evalVal resolved globalEnv newFrame thunkEnv trail) ThunkExp exp -> eval resolved globalEnv newFrame thunkEnv trail exp ThunkRecord -> pure . pure . ValFrame $ newFrame let finalSusable = case result of Trailing _ (Thunk s _ _ _) -> s ++ susable _ -> susable pure $ expandTrail finalSusable (newFrame, dropTrail result) result reSus :: [[i]] -> Val i -> Val i reSus susable (Thunk susable' a e t) = Thunk (susable' ++ susable) a e t reSus _ v = v lookupVar :: (Ord i, Show i) => i -> Lam.Resolved i -> Map i (Val i) -> GlobalEnv i -> Maybe (Val i) lookupVar id resolved env globalEnv = maybe Nothing (lookupVarByResolvedId env globalEnv) $ lookupVarId id resolved lookupVarByResolvedId :: Ord i => Map i (Val i) -> GlobalEnv i -> i -> Maybe (Val i) lookupVarByResolvedId env globalEnv k = case Map.lookup k env of Just x -> Just x Nothing -> Map.lookup k . unGlobalEnv $ globalEnv lookupVarId :: Ord k => k -> Map k a -> Maybe a lookupVarId id resolved = Map.lookup id resolved flattenSusable :: (Show i, Ord i) => Lam.Resolved i -> i -> Lam.Susable (Id.WithId i Identity) -> Either [EvalError i] [[i]] flattenSusable resolved errId (Lam.Susable ss) = eitherList ((\s -> eitherList (go <$> s)) <$> ss) where go (Id.WithId id (Identity name)) = maybe (Left [UndefinedVar errId name]) Right (Map.lookup id resolved)
imccoy/utopia
src/Eval.hs
Haskell
mit
12,800
import Data.Tuple import Data.Maybe import Data.List.Extra import Data.Map (Map) import qualified Data.Map as M test1_map :: OrbitMap test1_map = mkMap [ "COM)B", "B)C", "C)D", "D)E", "E)F", "B)G", "G)H", "D)I", "E)J", "J)K", "K)L"] test2_map :: OrbitMap test2_map = mkMap [ "COM)B", "B)C", "C)D", "D)E", "E)F", "B)G", "G)H", "D)I", "E)J", "J)K", "K)L", "K)YOU", "I)SAN"] type Pair = (String,String) toPair :: String -> Pair toPair xs = (a,b) where [a,b] = splitOn ")" xs type OrbitMap = Map String String mkMap :: [String] -> OrbitMap mkMap = M.fromList . map (swap . toPair) get :: String -> OrbitMap -> [String] get s m = takeWhile (/= "COM") $ iterate look s where look s' = let fnd = M.lookup s' m in fromMaybe "COM" fnd -- 278744 part_1 :: OrbitMap -> Int part_1 m = sum $ length . flip get m <$> ks where ks = M.keys m -- 475 part_2 :: OrbitMap -> Int part_2 m = yn + sn where you = reverse $ get "YOU" m san = reverse $ get "SAN" m zz = takeWhile (uncurry (==)) $ zip you san lz = length zz you' = drop lz you san' = drop lz san yn = pred $ length you' sn = pred $ length san' main :: IO () main = do print $ part_1 test1_map print $ part_2 test2_map mps <- mkMap . lines <$> getContents print $ part_1 mps print $ part_2 mps
wizzup/advent_of_code
2019/haskell/exe/Day06.hs
Haskell
mit
1,355
-- (220、284)、(1,184、1,210)、(2,620、2,924)、(5,020、5,564)、(6,232、6,368)、 -- import System.Environment amicable :: Int -> Int -> Bool amicable n m | sum(propDivis n) /= m = False | otherwise = sum(propDivis m) == n amicables :: Int -> [[Int]] amicables n = [[i,j]|i<-[4..n],j<-[i..min n (i*16`div`10)],amicable i j] propDivis :: Int -> [Int] propDivis n = [i | i<-[1..(n-1)], n `mod` i == 0] answer' n = concat [ps | ps<-amicables n] answer n = concat [if p/=q then p:q:[] else [] | (p:q:[])<-amicables n] main = do args <- getArgs let n = read (head args) print $ answer' n print $ sum $ answer' n print $ answer n print $ sum $ answer n
yuto-matsum/contest-util-hs
src/Euler/021.hs
Haskell
mit
689
{- Copyright (c) 2008-2015 the Urho3D project. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} module Mover where import Data.IORef import Foreign import Control.Lens hiding (Context, element) import Graphics.Urho3D import Sample -- | Custom logic component for moving the animated model and rotating at area edges. type Mover = CustomLogicComponent -- | Internal state of component data MoverState = MoverState { moverSpeed :: Float -- ^ Forward movement speed. , moverRotateSpeed :: Float -- ^ Rotation speed. , moverBounds :: BoundingBox -- ^ Movement boundaries. } -- | Custom logic component setup that holds state and callbacks. type MoverSetup = CustomLogicComponentSetup MoverState -- | Type hash of our mover component type MoverType = StringHash -- | Register mover within Urho engine, resulting type is used for creation of -- the component instances. registerMover :: MonadIO m => Ptr Context -> m MoverType registerMover cntx = registerCustomComponent cntx "Mover" moverState moverDef where moverState = MoverState { moverSpeed = 0 , moverRotateSpeed = 0 , moverBounds = 0 } -- | Update internal state of mover. Set motion parameters: forward movement speed, rotation speed, and movement boundaries. setMoverParameters :: MonadIO m => Ptr Mover -> Float -> Float -> BoundingBox -> m () setMoverParameters ptr moveSpeed rotateSpeed bounds = liftIO $ do ref <- getCustomComponentState ptr writeIORef ref $ MoverState { moverSpeed = moveSpeed , moverRotateSpeed = rotateSpeed , moverBounds = bounds } -- | Return forward movement speed. moverGetMoveSpeed :: MonadIO m => Ptr Mover -> m Float moverGetMoveSpeed ptr = liftIO $ do ref <- getCustomComponentState ptr moverSpeed <$> readIORef ref -- | Return rotation speed. moverGetRotationSpeed :: MonadIO m => Ptr Mover -> m Float moverGetRotationSpeed ptr = liftIO $ do ref <- getCustomComponentState ptr moverRotateSpeed <$> readIORef ref -- | Return movement boundaries. moverGetBounds :: MonadIO m => Ptr Mover -> m BoundingBox moverGetBounds ptr = liftIO $ do ref <- getCustomComponentState ptr moverBounds <$> readIORef ref -- | Custom logic component for rotating a scene node. moverDef :: MoverSetup moverDef = defaultCustomLogicComponent { componentUpdate = Just $ \ref compNode t -> do -- Component state is passed via reference MoverState {..} <- readIORef ref nodeTranslate compNode (vec3Forward * vec3 (moverSpeed * t)) TSLocal -- If in risk of going outside the plane, rotate the model right pos <- nodeGetPosition compNode when ((pos ^. x < moverBounds ^. minVector ^. x) || (pos ^. x > moverBounds ^. maxVector ^. x) || (pos ^. z < moverBounds ^. minVector ^. z) || (pos ^. z > moverBounds ^. maxVector ^. z)) $ nodeYaw compNode (moverRotateSpeed * t) TSLocal -- Get the model's first (only) animation state and advance its time. Note the convenience accessor to other components -- in the same scene node (model :: Ptr AnimatedModel) <- fromJustTrace "AnimatedModel mover" <$> nodeGetComponent compNode False whenM ((> 0) <$> animatedModelGetNumAnimationStates model) $ do states <- animatedModelGetAnimationStates model animationStateAddTime (head states) t }
Teaspot-Studio/Urho3D-Haskell
app/sample06/Mover.hs
Haskell
mit
4,305
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE ScopedTypeVariables #-} module Main where import qualified Map import Control.Applicative import Control.Concurrent.Async import Control.Concurrent.MSem import Control.Concurrent.Timeout import Control.Monad.Catch import Control.Monad import Data.Time.Clock.POSIX import Data.Timeout import System.Environment import System.IO import Text.Printf import Language.Haskell.Liquid.Types (GhcSpec) import Test.Target import Test.Target.Monad instance Show (a -> b) where show _ = "<function>" main :: IO () main = do [t] <- getArgs withFile ("_results/Map-" ++ t ++ ".tsv") WriteMode $ \h -> do hPutStrLn h "Function\tDepth\tTime(s)\tResult" mapPool 12 (checkMany h (read t # Minute)) funs putStrLn "done" putStrLn "" mapPool max f xs = do sem <- new max mapConcurrently (with sem . f) xs checkMany :: Handle -> Timeout -> (Test, String) -> IO [(Int, Double, Outcome)] checkMany h time (f,sp) = putStrNow (printf "Testing %s..\n" sp) >> go 2 where go 21 = return [] go n = checkAt f sp n time >>= \case (d,Nothing) -> do let s = printf "%s\t%d\t%.2f\t%s" sp n d (show TimeOut) putStrLn s >> hFlush stdout hPutStrLn h s >> hFlush h return [(n,d,TimeOut)] --NOTE: timeout is a bit unreliable.. (d,_) | round d >= time #> Second -> do let s = printf "%s\t%d\t%.2f\t%s" sp n d (show TimeOut) putStrLn s >> hFlush stdout hPutStrLn h s >> hFlush h putStrLn "WARNING: timeout seems to have been ignored..." return [(n,d,TimeOut)] --NOTE: sometimes the timeout causes an error instead of a timeout exn (d,Just (Errored s)) -> return [(n,d,Complete (Errored s))] --NOTE: ignore counter-examples for the sake of exploring coverage --(d,Just (Failed s)) -> return [(n,d,Complete (Failed s))] (d,Just r) -> do let s = printf "%s\t%d\t%.2f\t%s" sp n d (show (Complete r)) putStrLn s >> hFlush stdout hPutStrLn h s >> hFlush h ((n,d,Complete r):) <$> go (n+1) checkAt :: Test -> String -> Int -> Timeout -> IO (Double, Maybe Result) checkAt (T f) sp n time = timed $ do r <- try $ timeout time $ targetResultWithStr f sp "bench/Map.hs" (defaultOpts {logging=False, keepGoing = True, depth = n}) case r of Left (e :: SomeException) -> return $ Just $ Errored $ show e Right r -> return r -- time = 5 # Minute getTime :: IO Double getTime = realToFrac `fmap` getPOSIXTime timed x = do start <- getTime v <- x end <- getTime return (end-start, v) putStrNow s = putStr s >> hFlush stdout data Outcome = Complete Result | TimeOut deriving (Show) funs :: [(Test,String)] funs = [(T ((Map.!) :: Map.Map Map.Char () -> Map.Char -> ()), "Map.!") ,(T ((Map.\\) :: Map.Map Map.Char () -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.\\\\") ,(T ((Map.null) :: Map.Map Map.Char () -> Map.Bool), "Map.null") ,(T ((Map.lookup) :: Map.Char -> Map.Map Map.Char () -> Map.Maybe ()), "Map.lookup") ,(T ((Map.member) :: Map.Char -> Map.Map Map.Char () -> Map.Bool), "Map.member") ,(T ((Map.notMember) :: Map.Char -> Map.Map Map.Char () -> Map.Bool), "Map.notMember") ,(T ((Map.findWithDefault) :: () -> Map.Char -> Map.Map Map.Char () -> ()), "Map.findWithDefault") ,(T ((Map.lookupLT) :: Map.Char -> Map.Map Map.Char () -> Map.Maybe (Map.Char, ())), "Map.lookupLT") ,(T ((Map.lookupGT) :: Map.Char -> Map.Map Map.Char () -> Map.Maybe (Map.Char, ())), "Map.lookupGT") ,(T ((Map.lookupLE) :: Map.Char -> Map.Map Map.Char () -> Map.Maybe (Map.Char, ())), "Map.lookupLE") ,(T ((Map.lookupGE) :: Map.Char -> Map.Map Map.Char () -> Map.Maybe (Map.Char, ())), "Map.lookupGE") ,(T ((Map.singleton) :: Map.Char -> () -> Map.Map Map.Char ()), "Map.singleton") ,(T ((Map.insert) :: Map.Char -> () -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.insert") ,(T ((Map.insertWith) :: (() -> () -> ())-> Map.Char -> () -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.insertWith") ,(T ((Map.insertWithKey) :: (Map.Char -> () -> () -> ())-> Map.Char -> () -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.insertWithKey") ,(T ((Map.insertLookupWithKey) :: (Map.Char -> () -> () -> ())-> Map.Char-> ()-> Map.Map Map.Char ()-> (Map.Maybe (), Map.Map Map.Char ())), "Map.insertLookupWithKey") ,(T ((Map.delete) :: Map.Char -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.delete") ,(T ((Map.adjust) :: (() -> ())-> Map.Char -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.adjust") ,(T ((Map.adjustWithKey) :: (Map.Char -> () -> ())-> Map.Char -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.adjustWithKey") ,(T ((Map.update) :: (() -> Map.Maybe ())-> Map.Char -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.update") ,(T ((Map.updateWithKey) :: (Map.Char -> () -> Map.Maybe ())-> Map.Char -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.updateWithKey") ,(T ((Map.updateLookupWithKey) :: (Map.Char -> () -> Map.Maybe ())-> Map.Char-> Map.Map Map.Char ()-> (Map.Maybe (), Map.Map Map.Char ())), "Map.updateLookupWithKey") ,(T ((Map.alter) :: (Map.Maybe () -> Map.Maybe ())-> Map.Char -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.alter") ,(T ((Map.findIndex) :: Map.Char -> Map.Map Map.Char () -> Map.Int), "Map.findIndex") ,(T ((Map.lookupIndex) :: Map.Char -> Map.Map Map.Char () -> Map.Maybe Map.Int), "Map.lookupIndex") ,(T ((Map.elemAt) :: Map.Int -> Map.Map Map.Char () -> (Map.Char, ())), "Map.elemAt") ,(T ((Map.updateAt) :: (Map.Char -> () -> Map.Maybe ())-> Map.Int -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.updateAt") ,(T ((Map.deleteAt) :: Map.Int -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.deleteAt") ,(T ((Map.findMin) :: Map.Map Map.Char () -> (Map.Char, ())), "Map.findMin") ,(T ((Map.findMax) :: Map.Map Map.Char () -> (Map.Char, ())), "Map.findMax") ,(T ((Map.deleteMin) :: Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.deleteMin") ,(T ((Map.deleteMax) :: Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.deleteMax") ,(T ((Map.updateMin) :: (() -> Map.Maybe ()) -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.updateMin") ,(T ((Map.updateMax) :: (() -> Map.Maybe ()) -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.updateMax") ,(T ((Map.updateMinWithKey) :: (Map.Char -> () -> Map.Maybe ())-> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.updateMinWithKey") ,(T ((Map.updateMaxWithKey) :: (Map.Char -> () -> Map.Maybe ())-> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.updateMaxWithKey") ,(T ((Map.minViewWithKey) :: Map.Map Map.Char ()-> Map.Maybe (Map.Char, (), Map.Map Map.Char ())), "Map.minViewWithKey") ,(T ((Map.maxViewWithKey) :: Map.Map Map.Char ()-> Map.Maybe (Map.Char, (), Map.Map Map.Char ())), "Map.maxViewWithKey") ,(T ((Map.minView) :: Map.Map Map.Char () -> Map.Maybe ((), Map.Map Map.Char ())), "Map.minView") ,(T ((Map.maxView) :: Map.Map Map.Char () -> Map.Maybe ((), Map.Map Map.Char ())), "Map.maxView") ,(T ((Map.unions) :: [Map.Map Map.Char ()] -> Map.Map Map.Char ()), "Map.unions") ,(T ((Map.unionsWith) :: (() -> () -> ()) -> [Map.Map Map.Char ()] -> Map.Map Map.Char ()), "Map.unionsWith") ,(T ((Map.union) :: Map.Map Map.Char () -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.union") ,(T ((Map.unionWith) :: (() -> () -> ())-> Map.Map Map.Char ()-> Map.Map Map.Char ()-> Map.Map Map.Char ()), "Map.unionWith") ,(T ((Map.unionWithKey) :: (Map.Char -> () -> () -> ())-> Map.Map Map.Char ()-> Map.Map Map.Char ()-> Map.Map Map.Char ()), "Map.unionWithKey") ,(T ((Map.difference) :: Map.Map Map.Char () -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.difference") ,(T ((Map.differenceWith) :: (() -> () -> Map.Maybe ())-> Map.Map Map.Char ()-> Map.Map Map.Char ()-> Map.Map Map.Char ()), "Map.differenceWith") ,(T ((Map.differenceWithKey) :: (Map.Char -> () -> () -> Map.Maybe ())-> Map.Map Map.Char ()-> Map.Map Map.Char ()-> Map.Map Map.Char ()), "Map.differenceWithKey") ,(T ((Map.intersection) :: Map.Map Map.Char () -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.intersection") ,(T ((Map.intersectionWith) :: (() -> () -> ())-> Map.Map Map.Char ()-> Map.Map Map.Char ()-> Map.Map Map.Char ()), "Map.intersectionWith") ,(T ((Map.intersectionWithKey) :: (Map.Char -> () -> () -> ())-> Map.Map Map.Char ()-> Map.Map Map.Char ()-> Map.Map Map.Char ()), "Map.intersectionWithKey") ,(T ((Map.mergeWithKey) :: (Map.Char -> () -> () -> Map.Maybe ())-> (Map.MaybeS Map.Char -> Map.MaybeS Map.Char -> Map.Map Map.Char () -> Map.Map Map.Char ())-> (Map.MaybeS Map.Char -> Map.MaybeS Map.Char -> Map.Map Map.Char () -> Map.Map Map.Char ())-> Map.Map Map.Char ()-> Map.Map Map.Char ()-> Map.Map Map.Char ()), "Map.mergeWithKey") ,(T ((Map.isSubmapOf) :: Map.Map Map.Char () -> Map.Map Map.Char () -> Map.Bool), "Map.isSubmapOf") ,(T ((Map.isSubmapOfBy) :: (() -> () -> Map.Bool)-> Map.Map Map.Char () -> Map.Map Map.Char () -> Map.Bool), "Map.isSubmapOfBy") ,(T ((Map.isProperSubmapOf) :: Map.Map Map.Char () -> Map.Map Map.Char () -> Map.Bool), "Map.isProperSubmapOf") ,(T ((Map.isProperSubmapOfBy) :: (() -> () -> Map.Bool)-> Map.Map Map.Char () -> Map.Map Map.Char () -> Map.Bool), "Map.isProperSubmapOfBy") ,(T ((Map.filter) :: (() -> Map.Bool) -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.filter") ,(T ((Map.filterWithKey) :: (Map.Char -> () -> Map.Bool)-> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.filterWithKey") ,(T ((Map.partition) :: (() -> Map.Bool)-> Map.Map Map.Char ()-> (Map.Map Map.Char (), Map.Map Map.Char ())), "Map.partition") ,(T ((Map.partitionWithKey) :: (Map.Char -> () -> Map.Bool)-> Map.Map Map.Char ()-> (Map.Map Map.Char (), Map.Map Map.Char ())), "Map.partitionWithKey") ,(T ((Map.mapMaybe) :: (() -> Map.Maybe ()) -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.mapMaybe") ,(T ((Map.mapMaybeWithKey) :: (Map.Char -> () -> Map.Maybe ())-> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.mapMaybeWithKey") ,(T ((Map.mapEither) :: (() -> Map.Either () ())-> Map.Map Map.Char ()-> (Map.Map Map.Char (), Map.Map Map.Char ())), "Map.mapEither") ,(T ((Map.mapEitherWithKey) :: (Map.Char -> () -> Map.Either () ())-> Map.Map Map.Char ()-> (Map.Map Map.Char (), Map.Map Map.Char ())), "Map.mapEitherWithKey") ,(T ((Map.map) :: (() -> ()) -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.map") ,(T ((Map.mapWithKey) :: (Map.Char -> () -> ())-> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.mapWithKey") ,(T ((Map.mapAccum) :: (() -> () -> ((), ()))-> () -> Map.Map Map.Char () -> ((), Map.Map Map.Char ())), "Map.mapAccum") ,(T ((Map.mapAccumWithKey) :: (() -> Map.Char -> () -> ((), ()))-> () -> Map.Map Map.Char () -> ((), Map.Map Map.Char ())), "Map.mapAccumWithKey") ,(T ((Map.mapAccumRWithKey) :: (() -> Map.Char -> () -> ((), ()))-> () -> Map.Map Map.Char () -> ((), Map.Map Map.Char ())), "Map.mapAccumRWithKey") ,(T ((Map.mapKeys) :: (Map.Char -> Map.Char)-> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.mapKeys") ,(T ((Map.mapKeysWith) :: (() -> () -> ())-> (Map.Char -> Map.Char)-> Map.Map Map.Char ()-> Map.Map Map.Char ()), "Map.mapKeysWith") ,(T ((Map.mapKeysMonotonic) :: (Map.Char -> Map.Char)-> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.mapKeysMonotonic") ,(T ((Map.foldr) :: (() -> () -> ()) -> () -> Map.Map Map.Char () -> ()), "Map.foldr") ,(T ((Map.foldr') :: (() -> () -> ()) -> () -> Map.Map Map.Char () -> ()), "Map.foldr'") ,(T ((Map.foldl) :: (() -> () -> ()) -> () -> Map.Map Map.Char () -> ()), "Map.foldl") ,(T ((Map.foldl') :: (() -> () -> ()) -> () -> Map.Map Map.Char () -> ()), "Map.foldl'") ,(T ((Map.foldrWithKey) :: (Map.Char -> () -> () -> ()) -> () -> Map.Map Map.Char () -> ()), "Map.foldrWithKey") ,(T ((Map.foldrWithKey') :: (Map.Char -> () -> () -> ()) -> () -> Map.Map Map.Char () -> ()), "Map.foldrWithKey'") ,(T ((Map.foldlWithKey) :: (() -> Map.Char -> () -> ()) -> () -> Map.Map Map.Char () -> ()), "Map.foldlWithKey") ,(T ((Map.foldlWithKey') :: (() -> Map.Char -> () -> ()) -> () -> Map.Map Map.Char () -> ()), "Map.foldlWithKey'") ,(T ((Map.elems) :: Map.Map Map.Char () -> [()]), "Map.elems") ,(T ((Map.keys) :: Map.Map Map.Char () -> [Map.Char]), "Map.keys") ,(T ((Map.assocs) :: Map.Map Map.Char () -> [(Map.Char, ())]), "Map.assocs") ,(T ((Map.fromList) :: [(Map.Char, ())] -> Map.Map Map.Char ()), "Map.fromList") ,(T ((Map.fromListWith) :: (() -> () -> ()) -> [(Map.Char, ())] -> Map.Map Map.Char ()), "Map.fromListWith") ,(T ((Map.fromListWithKey) :: (Map.Char -> () -> () -> ())-> [(Map.Char, ())] -> Map.Map Map.Char ()), "Map.fromListWithKey") ,(T ((Map.toList) :: Map.Map Map.Char () -> [(Map.Char, ())]), "Map.toList") ,(T ((Map.toAscList) :: Map.Map Map.Char () -> [(Map.Char, ())]), "Map.toAscList") ,(T ((Map.toDescList) :: Map.Map Map.Char () -> [(Map.Char, ())]), "Map.toDescList") ,(T ((Map.fromAscList) :: [(Map.Char, ())] -> Map.Map Map.Char ()), "Map.fromAscList") ,(T ((Map.fromAscListWith) :: (() -> () -> ()) -> [(Map.Char, ())] -> Map.Map Map.Char ()), "Map.fromAscListWith") ,(T ((Map.fromAscListWithKey) :: (Map.Char -> () -> () -> ())-> [(Map.Char, ())] -> Map.Map Map.Char ()), "Map.fromAscListWithKey") ,(T ((Map.fromDistinctAscList) :: [(Map.Char, ())] -> Map.Map Map.Char ()), "Map.fromDistinctAscList") ,(T ((Map.split) :: Map.Char-> Map.Map Map.Char ()-> (Map.Map Map.Char (), Map.Map Map.Char ())), "Map.split") ,(T ((Map.splitLookup) :: Map.Char-> Map.Map Map.Char ()-> (Map.Map Map.Char (), Map.Maybe (), Map.Map Map.Char ())), "Map.splitLookup") --,(T ((Map.deleteFindMin) :: Map.Map Map.Char () -> (Map.Char, (), Map.Map Map.Char ())), "Map.deleteFindMin") --,(T ((Map.deleteFindMax) :: Map.Map Map.Char () -> (Map.Char, (), Map.Map Map.Char ())), "Map.deleteFindMax") ]
gridaphobe/target
bench/MapCoverage.hs
Haskell
mit
14,904
-- Number-Star ladder -- https://www.codewars.com/kata/5631213916d70a0979000066 module Codewars.Kata.NumberStar where import Data.List(intercalate) pattern :: Int -> String pattern n = intercalate "\n" . ("1" :) . map (\i -> "1" ++ replicate (pred i) '*' ++ show i) $ [2..n]
gafiatulin/codewars
src/7 kyu/NumberStar.hs
Haskell
mit
278
module Language.Drasil.Format where -- | Possible formats for output data Format = TeX | Plain | HTML
JacquesCarette/literate-scientific-software
code/drasil-printers/Language/Drasil/Format.hs
Haskell
bsd-2-clause
104
module Text.Tokenize.Util.String ( unHyphen ) where unHyphen :: String -> String unHyphen ('‑':'\n':xs) = unHyphen xs unHyphen (x:xs) = x : unHyphen xs unHyphen [] = []
kawu/tokenize
Text/Tokenize/Util/String.hs
Haskell
bsd-2-clause
172
-- Collztz sequences chain :: (Integral a) => a -> [a] chain 1 = [1] chain n | even n = n:chain (n `div` 2) | odd n = n:chain (n * 3 + 1) numLongChains :: Int numLongChains = length (filter (\xs -> length xs > 15) (map chain [1..100])) addThree :: (Num a) => a -> a -> a -> a addThree = \x -> \y -> \z -> x + y + z flip' :: (a -> b -> c) -> b -> a -> c flip' f = \x y -> f y x
sharkspeed/dororis
languages/haskell/LYHGG/6-higher-order-functions/2-lambda.hs
Haskell
bsd-2-clause
388
{-# LANGUAGE PackageImports #-} -- {-# LANGUAGE PackageImports, FlexibleContexts, FlexibleInstances, UndecidableInstances, RankNTypes #-} -- , OverlappingInstances {- | Radix sort of lists, based on binary representation of * floats * Int<N> * Word<N> The lsd prefix is for Least significant digit radix sort, while msd is for the parallelized Most significant digit one. Here we partition numbers by sign and sort both lists in parallel (you should link with -threaded) The digit size is set to 8 bits. Digit value queues ('Seq' a) are appended as difference lists ('DList' from package dlist, O(1) on append) Instances of RadixRep for 'Int' and 'Word' are not supported. The instance for 'Int' (machine word size) is not portable because it may have reserved bits for compiler use. The type Word may be restricted to the same number of bits as Int. Check The word size story at <http://www.haskell.org/ghc/docs/7.2.2/html/libraries/ghc-prim-0.2.0.0/GHC-Prim.html#g:1> A quickcheck test-suite has been added. -} -- @author: Gabriel Riba Faura -- Internally uses (.$) = flip ($) module Data.List.RadixSort.Base ( msdSort, lsdSort, msdSortBy, lsdSortBy, RadixRep(..) ) where import Data.List.RadixSort.Internal.Types import Data.List.RadixSort.Internal.MSD (msdRadixSort) import Data.List.RadixSort.Internal.LSD (lsdRadixSort) import Data.List.RadixSort.Internal.Counters (countAndPartBySign) import Data.List.RadixSort.Internal.RadixRep (getSortInfo) import qualified Data.List as L -- import "dlist" Data.DList (DList) import qualified "dlist" Data.DList as D import "parallel" Control.Parallel.Strategies (using, rpar, rseq) import GHC.ST (runST) -- | A first pass to build digit counters is used to split lists by sign, then they are sorted in parallel. -- -- Each split group is sparked to compute in parallel -- -- Worst case O((k+1) n + length negatives (append)) where k= #digits. msdSort :: (RadixRep a) => [a] -> [a] msdSort = msdSortBy id msdSortBy :: (RadixRep b) => (a -> b) -> [a] -> [a] msdSortBy _indexMap [] = [] msdSortBy _indexMap [x] = [x] msdSortBy indexMap list@(x:_) = case repType rep of RT_Float -> msdSortFloats sortInfo indexMap list RT_IntN -> msdSortInts sortInfo indexMap list RT_WordN -> msdSortNats sortInfo indexMap list where sortInfo = getSortInfo ST_MSD rep rep = indexMap x -- | A first pass to build digit counters is used to split lists by sign, then they are sorted in parallel -- -- Worst case O((k+1) n + length negatives (append)) where k= #digits. lsdSort :: (RadixRep a) => [a] -> [a] lsdSort = lsdSortBy id lsdSortBy :: (RadixRep b) => (a -> b) -> [a] -> [a] lsdSortBy _indexMap [] = [] lsdSortBy _indexMap [x] = [x] lsdSortBy indexMap list@(x:_) = case repType rep of RT_Float -> lsdSortFloats sortInfo indexMap list RT_IntN -> lsdSortInts sortInfo indexMap list RT_WordN -> lsdSortNats sortInfo indexMap list where sortInfo = getSortInfo ST_LSD rep rep = indexMap x ---------------------------------- msdSortFloats :: (RadixRep b) => SortInfo -> (a -> b) -> [a] -> [a] msdSortFloats sortInfo indexMap list = (sortedPoss `using` rpar) `prependReversing` (sortedNegs `using` rseq) where (poss, digitsConstPos, negs, digitsConstNeg) = runST $ countAndPartBySign indexMap sortInfo list sortedPoss = D.toList $ msdRadixSort indexMap sortInfo digitsConstPos poss sortedNegs = D.toList $ msdRadixSort indexMap sortInfo {siIsOrderReverse = True} digitsConstNeg negs prependReversing :: [a] -> [a] -> [a] prependReversing = L.foldl' (flip (:)) {-# INLINABLE prependReversing #-} lsdSortFloats :: (RadixRep b) => SortInfo -> (a -> b) -> [a] -> [a] lsdSortFloats sortInfo indexMap list = (sortedPoss `using` rpar) `prependReversing` (sortedNegs `using` rseq) where (poss, digitsConstPos, negs, digitsConstNeg) = runST $ countAndPartBySign indexMap sortInfo list sortedPoss = D.toList $ lsdRadixSort indexMap sortInfo digitsConstPos poss sortedNegs = D.toList $ msdRadixSort indexMap sortInfo {siIsOrderReverse = True} digitsConstNeg negs ---------------------------------- msdSortInts :: (RadixRep b) => SortInfo -> (a -> b) -> [a] -> [a] msdSortInts sortInfo indexMap list = D.toList $ D.concat [(sortedNegs `using` rpar), (sortedPoss `using` rseq)] where (poss, digitsConstPos, negs, digitsConstNeg) = runST $ countAndPartBySign indexMap sortInfo list sortedPoss = msdRadixSort indexMap sortInfo digitsConstPos poss sortedNegs = msdRadixSort indexMap sortInfo digitsConstNeg negs lsdSortInts :: (RadixRep b) => SortInfo -> (a -> b) -> [a] -> [a] lsdSortInts sortInfo indexMap list = D.toList $ D.concat [(sortedNegs `using` rpar), (sortedPoss `using` rseq)] where (poss, digitsConstPos, negs, digitsConstNeg) = runST $ countAndPartBySign indexMap sortInfo list sortedPoss = lsdRadixSort indexMap sortInfo digitsConstPos poss sortedNegs = lsdRadixSort indexMap sortInfo digitsConstNeg negs ---------------------------------- msdSortNats :: (RadixRep b) => SortInfo -> (a -> b) -> [a] -> [a] msdSortNats sortInfo indexMap list = D.toList $ msdRadixSort indexMap sortInfo digitsConstPos poss where (poss, digitsConstPos, _, _) = runST $ countAndPartBySign indexMap sortInfo list lsdSortNats :: (RadixRep b) => SortInfo -> (a -> b) -> [a] -> [a] lsdSortNats sortInfo indexMap list = D.toList $ lsdRadixSort indexMap sortInfo digitsConstPos poss where (poss, digitsConstPos, _, _) = runST $ countAndPartBySign indexMap sortInfo list
griba2001/haskell-binaryrep-radix-sort
Data/List/RadixSort/Base.hs
Haskell
bsd-2-clause
5,805
module Database.SqlServer.Create.PartitionFunction ( PartitionFunction ) where import Prelude hiding (Left, Right) import Database.SqlServer.Create.Identifier hiding (unwrap) import Database.SqlServer.Create.DataType import Database.SqlServer.Create.Value import Database.SqlServer.Create.Entity import Data.List (nub) import Text.PrettyPrint hiding (render) import Test.QuickCheck import Data.Maybe (fromJust) {- All data types are valid for use as partitioning columns, except text, ntext, image, xml, timestamp, varchar(max), nvarchar(max), varbinary(max), alias data types, or CLR user-defined data types. -} newtype InputParameterType = InputParameterType { unwrap :: Type } instance Arbitrary InputParameterType where arbitrary = do x <- arbitrary `suchThat` isSupportedTypeForPartitionFunction return (InputParameterType x) data Range = Left | Right instance Arbitrary Range where arbitrary = elements [Left, Right] renderRange :: Range -> Doc renderRange Left = text "LEFT" renderRange Right = text "RIGHT" -- TODO boundaryValues need to all be the same type.... data PartitionFunction = PartitionFunction { partitionFunctionName :: RegularIdentifier , inputType :: InputParameterType , range :: Range , boundaryValues :: [SQLValue] } renderValues :: [SQLValue] -> Doc renderValues xs = parens (vcat (punctuate comma $ map renderValue xs)) instance Arbitrary PartitionFunction where arbitrary = do n <- arbitrary t <- arbitrary r <- arbitrary let b = fromJust $ value (unwrap t) -- otherwise an error in my code bv <- listOf b return $ PartitionFunction n t r (nub bv) instance Entity PartitionFunction where name = partitionFunctionName render a = text "CREATE PARTITION FUNCTION" <+> renderName a <+> parens (renderDataType (unwrap $ inputType a)) $+$ text "AS RANGE" <+> renderRange (range a) <+> text "FOR VALUES" <+> renderValues (boundaryValues a) $+$ text "GO\n" instance Show PartitionFunction where show = show . render
fffej/sql-server-gen
src/Database/SqlServer/Create/PartitionFunction.hs
Haskell
bsd-2-clause
2,086
module Main where import Prelude hiding (lookup) import Control.Concurrent import Control.DeepSeq import Control.Monad import Data.Binary.Put import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import Data.IORef import System.Mem import Data.Disk.Swapper import Data.Disk.Swapper.Cache import Data.Disk.Swapper.Snapshot instance NFData BS.ByteString where rnf x = x `seq` () main :: IO () main = do x <- newIORef =<< mkSwapper "data" [] setCacheRef x =<< mkClockCache 5 forM_ [1..7] $ \_ -> do d <- BS.readFile "in" x' <- readIORef x writeIORef x $! adding (:) d x' performGC forM_ [3..4] $ \i -> do BS.writeFile "out" . getting (!!i) =<< readIORef x performGC forM_ [8..10] $ \_ -> do d <- BS.readFile "in" x' <- readIORef x writeIORef x $! adding (:) d x' performGC forM_ [2..6] $ \i -> do x' <- return . getting (!!i) =<< readIORef x BS.writeFile "out" x' performGC forM_ [2..6] $ \_ -> do modifyIORef x $ changing tail performGC forM_ [8..10] $ \_ -> do d <- BS.readFile "in" x' <- readIORef x writeIORef x $! adding (:) d x' performGC BSL.writeFile "snapshot0" . runPut =<< putToSnapshot =<< readIORef x forM_ [1..7] $ \_ -> do d <- BS.readFile "in" x' <- readIORef x writeIORef x $! adding (:) d x' performGC wait1 <- newEmptyMVar wait2 <- newEmptyMVar forkIO $ do BSL.writeFile "snapshot1" . runPut =<< putToSnapshot =<< readIORef x putMVar wait1 () forkIO $ do BSL.writeFile "snapshot2" . runPut =<< putToSnapshot =<< readIORef x putMVar wait2 () takeMVar wait1 takeMVar wait2 print . BS.length . getting last =<< readIORef x
roman-smrz/swapper
test/test.hs
Haskell
bsd-2-clause
2,151
{-# LANGUAGE NoImplicitPrelude #-} module Bamboo.Plugin.Photo.View where import Bamboo.Plugin.Photo.Model import MPSUTF8 import Prelude hiding ((.), (>), (^), (/), id, div) import Text.XHtml.Strict hiding (select, sub, meta) id :: String -> HtmlAttr id = identifier div_id :: String -> Html -> Html div_id s = thediv ! [id s] div_class :: String -> Html -> Html div_class s = thediv ! [theclass s] div_class_id :: String -> String -> Html -> Html div_class_id x y = thediv ! [theclass x, id y] span :: Html -> Html div :: Html -> Html d :: Html -> Html ul :: Html -> Html span = thespan div = thediv d = div ul = ulist klass :: String -> HtmlAttr klass = theclass c :: String -> Html -> Html c x = d ! [klass x] -- i x = d ! [id x] ic, ci:: String -> String -> Html -> Html ic x y = d ! [id x, klass y] ci x y = ic y x link :: String -> Html -> HotLink link = hotlink img :: Html space_html :: Html img = image space_html = primHtml "&#160;" render :: Album -> Html render = show_album empty_html :: Html empty_html = toHtml "" show_album :: Album -> Html show_album x = case x.album_type of Fade -> show_fade x Galleria -> show_galleria x SlideViewer -> show_slide_viewer x Popeye -> show_popeye x show_popeye :: Album -> Html show_popeye x = c "popeye" << ul << x.data_list.map picture_li where picture_li (l, t, i) = li << link l << img ! [src i, alt t] show_slide_viewer :: Album -> Html show_slide_viewer x = ul ! [id "slide-viewer", klass "svw"] << x.data_list.map picture_li where picture_li (_, t, i) = li << img ! [src i, alt t] show_galleria :: Album -> Html show_galleria x = ul ! [klass "gallery"] << x.data_list.map picture_li where picture_li (_, t, i) = li << img ! [src i, alt t] show_fade :: Album -> Html show_fade x = ul ! [klass "fade-album"] << x.data_list.map picture_li where picture_li (l, t, i) = li << [ toHtml $ link l << img ! [src i, alt t] , if x.show_description then p << t else empty_html ]
nfjinjing/bamboo-plugin-photo
src/Bamboo/Plugin/Photo/View.hs
Haskell
bsd-3-clause
2,106
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.PixelRectangles.Convolution -- Copyright : (c) Sven Panne 2002-2005 -- License : BSD-style (see the file libraries/OpenGL/LICENSE) -- -- Maintainer : sven.panne@aedion.de -- Stability : provisional -- Portability : portable -- -- This module corresponds to a part of section 3.6.1 (Pixel Storage Modes) of -- the OpenGL 1.5 specs. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.PixelRectangles.Convolution ( ConvolutionTarget(..), convolution, convolutionFilter1D, getConvolutionFilter1D, convolutionFilter2D, getConvolutionFilter2D, separableFilter2D, getSeparableFilter2D, copyConvolutionFilter1D, copyConvolutionFilter2D, convolutionWidth, convolutionHeight, maxConvolutionWidth, maxConvolutionHeight, ConvolutionBorderMode(..), convolutionBorderMode, convolutionFilterScale, convolutionFilterBias, ) where import Foreign.Marshal.Alloc ( alloca ) import Foreign.Marshal.Utils ( with ) import Foreign.Ptr ( Ptr, nullPtr ) import Foreign.Storable ( Storable(..) ) import Graphics.Rendering.OpenGL.GL.Capability ( EnableCap(CapConvolution1D, CapConvolution2D,CapSeparable2D), makeCapability ) import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum, GLint, GLsizei, GLfloat, Capability ) import Graphics.Rendering.OpenGL.GL.CoordTrans ( Position(..), Size(..) ) import Graphics.Rendering.OpenGL.GL.Extensions ( FunPtr, unsafePerformIO, Invoker, getProcAddress ) import Graphics.Rendering.OpenGL.GL.PeekPoke ( peek1 ) import Graphics.Rendering.OpenGL.GL.PixelRectangles.ColorTable ( PixelInternalFormat ) import Graphics.Rendering.OpenGL.GL.PixelRectangles.Rasterization ( PixelData(..) ) import Graphics.Rendering.OpenGL.GL.PixelData ( withPixelData ) import Graphics.Rendering.OpenGL.GL.Texturing.PixelInternalFormat ( marshalPixelInternalFormat' ) import Graphics.Rendering.OpenGL.GL.StateVar ( GettableStateVar, makeGettableStateVar, StateVar, makeStateVar ) import Graphics.Rendering.OpenGL.GL.VertexSpec ( Color4(..) ) import Graphics.Rendering.OpenGL.GLU.ErrorsInternal ( recordInvalidValue ) -------------------------------------------------------------------------------- #include "HsOpenGLExt.h" -------------------------------------------------------------------------------- data ConvolutionTarget = Convolution1D | Convolution2D | Separable2D deriving ( Eq, Ord, Show ) marshalConvolutionTarget :: ConvolutionTarget -> GLenum marshalConvolutionTarget x = case x of Convolution1D -> 0x8010 Convolution2D -> 0x8011 Separable2D -> 0x8012 convolutionTargetToEnableCap :: ConvolutionTarget -> EnableCap convolutionTargetToEnableCap x = case x of Convolution1D -> CapConvolution1D Convolution2D -> CapConvolution2D Separable2D -> CapSeparable2D -------------------------------------------------------------------------------- convolution :: ConvolutionTarget -> StateVar Capability convolution = makeCapability . convolutionTargetToEnableCap -------------------------------------------------------------------------------- convolutionFilter1D :: PixelInternalFormat -> GLsizei -> PixelData a -> IO () convolutionFilter1D int w pd = withPixelData pd $ glConvolutionFilter1D (marshalConvolutionTarget Convolution1D) (marshalPixelInternalFormat' int) w EXTENSION_ENTRY("GL_ARB_imaging",glConvolutionFilter1D,GLenum -> GLenum -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ()) -------------------------------------------------------------------------------- getConvolutionFilter1D :: PixelData a -> IO () getConvolutionFilter1D = getConvolutionFilter Convolution1D getConvolutionFilter :: ConvolutionTarget -> PixelData a -> IO () getConvolutionFilter t pd = withPixelData pd $ glGetConvolutionFilter (marshalConvolutionTarget t) EXTENSION_ENTRY("GL_ARB_imaging",glGetConvolutionFilter,GLenum -> GLenum -> GLenum -> Ptr a -> IO ()) -------------------------------------------------------------------------------- convolutionFilter2D :: PixelInternalFormat -> Size -> PixelData a -> IO () convolutionFilter2D int (Size w h) pd = withPixelData pd $ glConvolutionFilter2D (marshalConvolutionTarget Convolution2D) (marshalPixelInternalFormat' int) w h EXTENSION_ENTRY("GL_ARB_imaging",glConvolutionFilter2D,GLenum -> GLenum -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ()) -------------------------------------------------------------------------------- getConvolutionFilter2D :: PixelData a -> IO () getConvolutionFilter2D = getConvolutionFilter Convolution2D -------------------------------------------------------------------------------- separableFilter2D :: PixelInternalFormat -> Size -> PixelData a -> PixelData a -> IO () separableFilter2D int (Size w h) pdRow pdCol = withPixelData pdRow $ \f1 d1 p1 -> withPixelData pdCol $ \f2 d2 p2 -> if f1 == f2 && d1 == d2 then glSeparableFilter2D (marshalConvolutionTarget Separable2D) (marshalPixelInternalFormat' int) w h f1 d1 p1 p2 else recordInvalidValue EXTENSION_ENTRY("GL_ARB_imaging",glSeparableFilter2D,GLenum -> GLenum -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> Ptr a -> IO ()) -------------------------------------------------------------------------------- getSeparableFilter2D :: PixelData a -> PixelData a -> IO () getSeparableFilter2D pdRow pdCol = withPixelData pdRow $ \f1 d1 p1 -> withPixelData pdCol $ \f2 d2 p2 -> if f1 == f2 && d1 == d2 then glGetSeparableFilter (marshalConvolutionTarget Separable2D) f1 d1 p1 p2 nullPtr else recordInvalidValue EXTENSION_ENTRY("GL_ARB_imaging",glGetSeparableFilter,GLenum -> GLenum -> GLenum -> Ptr a -> Ptr a -> Ptr a -> IO ()) -------------------------------------------------------------------------------- copyConvolutionFilter1D :: PixelInternalFormat -> Position -> GLsizei -> IO () copyConvolutionFilter1D int (Position x y) = glCopyConvolutionFilter1D (marshalConvolutionTarget Convolution1D) (marshalPixelInternalFormat' int) x y EXTENSION_ENTRY("GL_ARB_imaging",glCopyConvolutionFilter1D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> IO ()) -------------------------------------------------------------------------------- copyConvolutionFilter2D :: PixelInternalFormat -> Position -> Size -> IO () copyConvolutionFilter2D int (Position x y) (Size w h) = glCopyConvolutionFilter2D (marshalConvolutionTarget Convolution2D) (marshalPixelInternalFormat' int) x y w h EXTENSION_ENTRY("GL_ARB_imaging",glCopyConvolutionFilter2D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> IO ()) -------------------------------------------------------------------------------- data ConvolutionParameter = ConvolutionBorderColor | ConvolutionBorderMode | ConvolutionFilterScale | ConvolutionFilterBias | ConvolutionFormat | ConvolutionWidth | ConvolutionHeight | MaxConvolutionWidth | MaxConvolutionHeight deriving ( Eq, Ord, Show ) marshalConvolutionParameter :: ConvolutionParameter -> GLenum marshalConvolutionParameter x = case x of ConvolutionBorderColor -> 0x8154 ConvolutionBorderMode -> 0x8013 ConvolutionFilterScale -> 0x8014 ConvolutionFilterBias -> 0x8015 ConvolutionFormat -> 0x8017 ConvolutionWidth -> 0x8018 ConvolutionHeight -> 0x8019 MaxConvolutionWidth -> 0x801a MaxConvolutionHeight -> 0x801b -------------------------------------------------------------------------------- convolutionWidth :: ConvolutionTarget -> GettableStateVar GLsizei convolutionWidth t = convolutionParameteri t ConvolutionWidth convolutionHeight :: ConvolutionTarget -> GettableStateVar GLsizei convolutionHeight t = convolutionParameteri t ConvolutionHeight maxConvolutionWidth :: ConvolutionTarget -> GettableStateVar GLsizei maxConvolutionWidth t = convolutionParameteri t MaxConvolutionWidth maxConvolutionHeight :: ConvolutionTarget -> GettableStateVar GLsizei maxConvolutionHeight t = convolutionParameteri t MaxConvolutionHeight convolutionParameteri :: ConvolutionTarget -> ConvolutionParameter -> GettableStateVar GLsizei convolutionParameteri t p = makeGettableStateVar (getConvolutionParameteri fromIntegral t p) getConvolutionParameteri :: (GLint -> a) -> ConvolutionTarget -> ConvolutionParameter -> IO a getConvolutionParameteri f t p = alloca $ \buf -> do glGetConvolutionParameteriv (marshalConvolutionTarget t) (marshalConvolutionParameter p) buf peek1 f buf EXTENSION_ENTRY("GL_ARB_imaging",glGetConvolutionParameteriv,GLenum -> GLenum -> Ptr GLint -> IO ()) -------------------------------------------------------------------------------- data ConvolutionBorderMode' = Reduce' | ConstantBorder' | ReplicateBorder' marshalConvolutionBorderMode' :: ConvolutionBorderMode' -> GLint marshalConvolutionBorderMode' x = case x of Reduce' -> 0x8016 ConstantBorder' -> 0x8151 ReplicateBorder' -> 0x8153 unmarshalConvolutionBorderMode' :: GLint -> ConvolutionBorderMode' unmarshalConvolutionBorderMode' x | x == 0x8016 = Reduce' | x == 0x8151 = ConstantBorder' | x == 0x8153 = ReplicateBorder' | otherwise = error ("unmarshalConvolutionBorderMode': illegal value " ++ show x) -------------------------------------------------------------------------------- data ConvolutionBorderMode = Reduce | ConstantBorder (Color4 GLfloat) | ReplicateBorder deriving ( Eq, Ord, Show ) -------------------------------------------------------------------------------- convolutionBorderMode :: ConvolutionTarget -> StateVar ConvolutionBorderMode convolutionBorderMode t = makeStateVar (getConvolutionBorderMode t) (setConvolutionBorderMode t) getConvolutionBorderMode :: ConvolutionTarget -> IO ConvolutionBorderMode getConvolutionBorderMode t = do mode <- getConvolutionParameteri unmarshalConvolutionBorderMode' t ConvolutionBorderMode case mode of Reduce' -> return Reduce ConstantBorder' -> do c <- getConvolutionParameterC4f t ConvolutionBorderColor return $ ConstantBorder c ReplicateBorder' -> return ReplicateBorder setConvolutionBorderMode :: ConvolutionTarget -> ConvolutionBorderMode -> IO () setConvolutionBorderMode t mode = do let setBM = setConvolutionParameteri marshalConvolutionBorderMode' t ConvolutionBorderMode case mode of Reduce -> setBM Reduce' ConstantBorder c -> do setBM ConstantBorder' convolutionParameterC4f t ConvolutionBorderColor c ReplicateBorder -> setBM ReplicateBorder' setConvolutionParameteri :: (a -> GLint) -> ConvolutionTarget -> ConvolutionParameter -> a -> IO () setConvolutionParameteri f t p x = glConvolutionParameteri (marshalConvolutionTarget t) (marshalConvolutionParameter p) (f x) EXTENSION_ENTRY("GL_ARB_imaging",glConvolutionParameteri,GLenum -> GLenum -> GLint -> IO ()) -------------------------------------------------------------------------------- convolutionFilterScale :: ConvolutionTarget -> StateVar (Color4 GLfloat) convolutionFilterScale = convolutionC4f ConvolutionFilterScale convolutionFilterBias :: ConvolutionTarget -> StateVar (Color4 GLfloat) convolutionFilterBias = convolutionC4f ConvolutionFilterBias convolutionC4f :: ConvolutionParameter -> ConvolutionTarget -> StateVar (Color4 GLfloat) convolutionC4f p t = makeStateVar (getConvolutionParameterC4f t p) (convolutionParameterC4f t p) getConvolutionParameterC4f :: ConvolutionTarget -> ConvolutionParameter -> IO (Color4 GLfloat) getConvolutionParameterC4f t p = alloca $ \buf -> do glGetConvolutionParameterfv (marshalConvolutionTarget t) (marshalConvolutionParameter p) buf peek buf EXTENSION_ENTRY("GL_ARB_imaging",glGetConvolutionParameterfv,GLenum -> GLenum -> Ptr (Color4 GLfloat) -> IO ()) convolutionParameterC4f :: ConvolutionTarget -> ConvolutionParameter -> Color4 GLfloat -> IO () convolutionParameterC4f t p c = with c $ glConvolutionParameterfv (marshalConvolutionTarget t) (marshalConvolutionParameter p) EXTENSION_ENTRY("GL_ARB_imaging",glConvolutionParameterfv,GLenum -> GLenum -> Ptr (Color4 GLfloat) -> IO ())
FranklinChen/hugs98-plus-Sep2006
packages/OpenGL/Graphics/Rendering/OpenGL/GL/PixelRectangles/Convolution.hs
Haskell
bsd-3-clause
12,502
{-# Language PatternGuards #-} module Blub ( blub , foo , bar ) where #include "Foo.h" #ifdef FOO import Control.Applicative #endif import Control.BiFunctor import Control.Monad f :: Int -> Int -- ^ Some Haddock doc -- One line more f = (+ 3) g :: Int -> Int g = where
dan-t/hsimport
tests/goldenFiles/ModuleTest37.hs
Haskell
bsd-3-clause
289
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ExtendedDefaultRules #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE StandaloneDeriving #-} module Mitsuba.Utils where import Mitsuba.Types import Mitsuba.Element hiding (Visibility (Hidden)) import qualified Mitsuba.Element as E import Control.Lens hiding ((#), (.>)) import Control.Lens.Fold import Data.Word import Data.Text.Format import Data.Double.Conversion.Text import Control.Applicative import Data.Monoid import Data.Data import GHC.Generics import qualified Data.Text as T import qualified Data.Text.Lazy as TL import Data.Text (Text) import Text.Blaze import Data.List import qualified Data.HashMap.Strict as H import Data.HashMap.Strict (HashMap) import Control.Arrow hiding (left) import qualified Data.Foldable as F import Data.Maybe import Mitsuba.Types.Primitives import Mitsuba.Types.Transform import Mitsuba.LensTH import Data.Default.Generics import Data.Map (Map) import qualified Data.Map as M import Language.Haskell.TH.Module.Magic class HasToWorld a where toWorld :: Traversal' a Transform class HasBSDF a where bsdf :: Traversal' a BSDF instance HasToWorld ShapeLeaf where toWorld = shapeLeafToWorldL instance HasBSDF (Child BSDF) where bsdf f = \case CRef x -> CRef <$> pure x CNested x -> CNested <$> f x instance HasBSDF ShapeLeaf where bsdf = shapeLeafLeafL.bsdf instance HasBSDF SimpleShapeLeaf where bsdf = simpleShapeLeafMaterialL . bsdf instance (HasBSDF a, HasBSDF b) => HasBSDF (Either a b) where bsdf f = \case Left x -> Left <$> bsdf f x Right x -> Right <$> bsdf f x instance HasBSDF OBJLeaf where bsdf f OBJLeaf {..} = OBJLeaf objLeafObj <$> case objLeafMaterial of Left x -> Left <$> bsdf f x Right x -> Right <$> pure x twosided :: NonTransmission -> BSDF twosided = BSDFTwosided . Twosided . CNested diffuse :: BSDF diffuse = BSDFDiffuse $ Diffuse $ CSpectrum $ SUniform 1.0 class DielectricI a where dielectric :: a -> a -> BSDF instance DielectricI RefractiveValue where dielectric x y = BSDFDielectric $ Dielectric { dielectricIntIOR = IOR x , dielectricExtIOR = IOR y , dielectricSpecularReflectance = def , dielectricSpecularTransmittance = def } instance DielectricI KnownMaterial where dielectric x y = BSDFDielectric $ Dielectric { dielectricIntIOR = RKM x , dielectricExtIOR = RKM y , dielectricSpecularReflectance = def , dielectricSpecularTransmittance = def } instance HasToWorld Shape where toWorld = _SShapeLeaf . toWorld instance HasBSDF Shape where bsdf f = \case SShapeGroup xs -> SShapeGroup <$> traverse (bsdf f) xs SShapeLeaf x -> SShapeLeaf <$> bsdf f x objMaterialMap :: Traversal' Shape (Map Text (Child BSDF)) objMaterialMap = _SShapeLeaf . shapeLeafLeafL . _Right . objLeafMaterialL . _Right shapeLeaf :: ShapeType -> Shape shapeLeaf st = SShapeLeaf $ ShapeLeaf ( Left $ SimpleShapeLeaf st (CNested diffuse) ) mempty Nothing Nothing cube :: Shape cube = shapeLeaf $ STCube $ Cube False sphere :: PositiveDouble -> Shape sphere radius = SShapeLeaf $ ShapeLeaf ( Left $ SimpleShapeLeaf (STSphere $ Sphere zeroPoint radius True) (CNested diffuse) ) mempty Nothing Nothing cylinder :: PositiveDouble -> Shape cylinder radius = SShapeLeaf $ ShapeLeaf ( Left $ SimpleShapeLeaf (STCylinder $ Cylinder zeroPoint (Point 0 1 0) radius True) (CNested diffuse) ) mempty Nothing Nothing -- TODO make the rectangle command square :: Shape square = SShapeLeaf $ ShapeLeaf ( Left $ SimpleShapeLeaf (STRectangle $ Rectangle True) (CNested diffuse) ) mempty Nothing Nothing --rectangle :: Double -> Double -> Shape --rectangle width height -- = Shape (STRectangle ) disk :: Shape disk = SShapeLeaf $ ShapeLeaf ( Left $ SimpleShapeLeaf (STDisk $ Disk True) (CNested diffuse) ) mempty Nothing Nothing obj :: FilePath -> Shape obj filePath = SShapeLeaf $ ShapeLeaf ( Right $ OBJLeaf ( OBJ filePath False 0.0 False False ) (Left $ CNested diffuse) ) mempty Nothing Nothing ply :: FilePath -> Shape ply filePath = SShapeLeaf $ ShapeLeaf ( Left $ SimpleShapeLeaf (STPLY $ PLY filePath True 0.0 False False) (CNested diffuse) ) mempty Nothing Nothing objMultiMaterial :: FilePath -> Shape objMultiMaterial filePath = SShapeLeaf $ ShapeLeaf ( Right $ OBJLeaf ( OBJ filePath False 0.0 False False ) (Right mempty) ) mempty Nothing Nothing serialized :: FilePath -> Shape serialized filepath = shapeLeaf $ STSerialized $ Serialized { serializedFilename = filepath , serializedShapeIndex = 0 , serializedFaceNormals = True , serializedMaxSmoothAngle = 0.0 , serializedFlipNormals = False } instanceShape :: Ref Shape -> Shape instanceShape = shapeLeaf . STInstance . Instance hair :: FilePath -> Shape hair filePath = shapeLeaf $ STHair $ Hair { hairFilename = filePath , hairRadius = 1.0 , hairAngleThreshold = 0.0 , hairReduction = 0.0 , hairWidth = 1 , hairHeight = 1 , hairTexture = TCheckerboard $ def } heightField :: FilePath -> Shape heightField filePath = shapeLeaf $ STHeightField $ HeightField { heightFieldShadingNormals = True , heightFieldFlipNormals = False , heightFieldWidth = 1 , heightFieldHeight = 1 , heightFieldScale = 1 , heightFieldFilename = filePath , heightFieldTexture = TCheckerboard $ def }
jfischoff/hs-mitsuba
src/Mitsuba/Utils.hs
Haskell
bsd-3-clause
6,458
module Goblin.Workshop.Scheduler where import Control.Concurrent import Control.Concurrent.STM import Control.Monad import Goblin.Workshop.Types import Goblin.Workshop.Util import System.Log.Logger import Text.Printf newSchedulerBus :: STM (SchedulerBus m) newSchedulerBus = newTChan talk :: TaskId -> SchedulerBus IO -> TaskMessage -> IO () talk tid sbus msg = atomically $ writeTChan sbus $ STaskTalk tid $ case msg of TProgress progress -> STaskTalkProgress progress TOutput s -> STaskTalkOutput s translateTalkMessage :: STaskTalk -> WTaskTalk translateTalkMessage (STaskTalkProgress progress) = WTaskTalkProgress progress translateTalkMessage (STaskTalkOutput s) = WTaskTalkOutput s defaultScheduler :: Scheduler IO defaultScheduler = Scheduler $ \sbus dbus wbus -> do infoM "gw.s" "Scheduler launched" listen sbus dbus wbus where listen sbus dbus wbus = do msg <- atomically $ readTChan sbus case msg of SSpawnTask tid task -> do debugM "gw.s" $ printf "Spawning task: %d" tid forkIO $ do result <- case task of Task action -> action TalkativeTask action -> action (talk tid sbus) debugM "gw.t" $ printf "Task %d is done. Informing scheduler" tid atomically $ writeTChan sbus $ STaskDone tid result listen sbus dbus wbus STaskDone tid result -> do debugM "gw.s" $ printf "Task %d is done. Informing dispatcher" tid atomically $ writeTChan dbus $ DTaskDone tid result listen sbus dbus wbus STaskTalk tid stt -> do atomically $ writeMaybeTChan wbus $ WTaskTalk tid $ translateTalkMessage stt listen sbus dbus wbus SFin -> do infoM "gw.s" "Bye" _ -> error "Not implemented yet"
y-usuzumi/goblin-workshop
src/Goblin/Workshop/Scheduler.hs
Haskell
bsd-3-clause
1,894
module SecondFront.Config ( module SecondFront.Config.Defaults, module SecondFront.Config.Types )where import SecondFront.Config.Defaults import SecondFront.Config.Types
alcidesv/second-front
hs-src/SecondFront/Config.hs
Haskell
bsd-3-clause
190
{-# LANGUAGE PatternGuards, TypeSynonymInstances, CPP #-} module IRTS.Compiler(compile, generate) where import IRTS.Lang import IRTS.LangOpts import IRTS.Defunctionalise import IRTS.Simplified import IRTS.CodegenCommon import IRTS.CodegenC import IRTS.DumpBC import IRTS.CodegenJavaScript import IRTS.Inliner import IRTS.Exports import Idris.AbsSyntax import Idris.AbsSyntaxTree import Idris.ASTUtils import Idris.Erasure import Idris.Error import Debug.Trace import Idris.Core.TT import Idris.Core.Evaluate import Idris.Core.CaseTree import Control.Category import Prelude hiding (id, (.)) import Control.Applicative import Control.Monad.State import Data.Maybe import Data.List import Data.Ord import Data.IntSet (IntSet) import qualified Data.IntSet as IS import qualified Data.Map as M import qualified Data.Set as S import System.Process import System.IO import System.Exit import System.Directory import System.Environment import System.FilePath ((</>), addTrailingPathSeparator) -- | Given a 'main' term to compiler, return the IRs which can be used to -- generate code. compile :: Codegen -> FilePath -> Maybe Term -> Idris CodegenInfo compile codegen f mtm = do checkMVs -- check for undefined metavariables checkTotality -- refuse to compile if there are totality problems exports <- findExports let rootNames = case mtm of Nothing -> [] Just t -> freeNames t reachableNames <- performUsageAnalysis (rootNames ++ getExpNames exports) maindef <- case mtm of Nothing -> return [] Just tm -> do md <- irMain tm logLvl 1 $ "MAIN: " ++ show md return [(sMN 0 "runMain", md)] objs <- getObjectFiles codegen libs <- getLibs codegen flags <- getFlags codegen hdrs <- getHdrs codegen impdirs <- allImportDirs defsIn <- mkDecls reachableNames -- if no 'main term' given, generate interface files let iface = case mtm of Nothing -> True Just _ -> False let defs = defsIn ++ maindef -- iputStrLn $ showSep "\n" (map show defs) -- Inlined top level LDecl made here let defsInlined = inlineAll defs let defsUniq = map (allocUnique (addAlist defsInlined emptyContext)) defsInlined let (nexttag, tagged) = addTags 65536 (liftAll defsUniq) let ctxtIn = addAlist tagged emptyContext logLvl 1 "Defunctionalising" let defuns_in = defunctionalise nexttag ctxtIn logLvl 5 $ show defuns_in logLvl 1 "Inlining" let defuns = inline defuns_in logLvl 5 $ show defuns logLvl 1 "Resolving variables for CG" -- iputStrLn $ showSep "\n" (map show (toAlist defuns)) let checked = simplifyDefs defuns (toAlist defuns) outty <- outputTy dumpCases <- getDumpCases dumpDefun <- getDumpDefun case dumpCases of Nothing -> return () Just f -> runIO $ writeFile f (showCaseTrees defs) case dumpDefun of Nothing -> return () Just f -> runIO $ writeFile f (dumpDefuns defuns) triple <- Idris.AbsSyntax.targetTriple cpu <- Idris.AbsSyntax.targetCPU logLvl 1 "Building output" case checked of OK c -> do return $ CodegenInfo f outty triple cpu hdrs impdirs objs libs flags NONE c (toAlist defuns) tagged iface exports -- runIO $ case codegen of -- ViaC -> codegenC cginfo -- ViaJava -> codegenJava cginfo -- ViaJavaScript -> codegenJavaScript cginfo -- ViaNode -> codegenNode cginfo -- ViaLLVM -> codegenLLVM cginfo -- Bytecode -> dumpBC c f Error e -> ierror e where checkMVs = do i <- getIState case map fst (idris_metavars i) \\ primDefs of [] -> return () ms -> ifail $ "There are undefined holes: " ++ show ms checkTotality = do i <- getIState case idris_totcheckfail i of [] -> return () ((fc, msg):fs) -> ierror . At fc . Msg $ "Cannot compile:\n " ++ msg inDir d h = do let f = d </> h ex <- doesFileExist f if ex then return f else return h generate :: Codegen -> FilePath -> CodegenInfo -> IO () generate codegen mainmod ir = case codegen of -- Built-in code generators (FIXME: lift these out!) Via "c" -> codegenC ir -- Any external code generator Via cg -> do let cmd = "idris-codegen-" ++ cg args = ["--yes-really", mainmod, "-o", outputFile ir] ++ compilerFlags ir exit <- rawSystem cmd args when (exit /= ExitSuccess) $ putStrLn ("FAILURE: " ++ show cmd ++ " " ++ show args) Bytecode -> dumpBC (simpleDecls ir) (outputFile ir) irMain :: TT Name -> Idris LDecl irMain tm = do i <- irTerm M.empty [] tm return $ LFun [] (sMN 0 "runMain") [] (LForce i) mkDecls :: [Name] -> Idris [(Name, LDecl)] mkDecls used = do i <- getIState let ds = filter (\(n, d) -> n `elem` used || isCon d) $ ctxtAlist (tt_ctxt i) decls <- mapM build ds return decls showCaseTrees :: [(Name, LDecl)] -> String showCaseTrees = showSep "\n\n" . map showCT . sortBy (comparing defnRank) where showCT (n, LFun _ f args lexp) = show n ++ " " ++ showSep " " (map show args) ++ " =\n\t" ++ show lexp showCT (n, LConstructor c t a) = "data " ++ show n ++ " " ++ show a defnRank :: (Name, LDecl) -> String defnRank (n, LFun _ _ _ _) = "1" ++ nameRank n defnRank (n, LConstructor _ _ _) = "2" ++ nameRank n nameRank :: Name -> String nameRank (UN s) = "1" ++ show s nameRank (MN i s) = "2" ++ show s ++ show i nameRank (NS n ns) = "3" ++ concatMap show (reverse ns) ++ nameRank n nameRank (SN sn) = "4" ++ snRank sn nameRank n = "5" ++ show n snRank :: SpecialName -> String snRank (WhereN i n n') = "1" ++ nameRank n' ++ nameRank n ++ show i snRank (InstanceN n args) = "2" ++ nameRank n ++ concatMap show args snRank (ParentN n s) = "3" ++ nameRank n ++ show s snRank (MethodN n) = "4" ++ nameRank n snRank (CaseN n) = "5" ++ nameRank n snRank (ElimN n) = "6" ++ nameRank n snRank (InstanceCtorN n) = "7" ++ nameRank n snRank (WithN i n) = "8" ++ nameRank n ++ show i isCon (TyDecl _ _) = True isCon _ = False build :: (Name, Def) -> Idris (Name, LDecl) build (n, d) = do i <- getIState case getPrim n i of Just (ar, op) -> let args = map (\x -> sMN x "op") [0..] in return (n, (LFun [] n (take ar args) (LOp op (map (LV . Glob) (take ar args))))) _ -> do def <- mkLDecl n d logLvl 3 $ "Compiled " ++ show n ++ " =\n\t" ++ show def return (n, def) where getPrim n i | Just (ar, op) <- lookup n (idris_scprims i) = Just (ar, op) | Just ar <- lookup n (S.toList (idris_externs i)) = Just (ar, LExternal n) getPrim n i = Nothing declArgs args inl n (LLam xs x) = declArgs (args ++ xs) inl n x declArgs args inl n x = LFun (if inl then [Inline] else []) n args x mkLDecl n (Function tm _) = declArgs [] True n <$> irTerm M.empty [] tm mkLDecl n (CaseOp ci _ _ _ pats cd) = declArgs [] (case_inlinable ci || caseName n) n <$> irTree args sc where (args, sc) = cases_runtime cd -- Always attempt to inline functions arising from 'case' expressions caseName (SN (CaseN _)) = True caseName (SN (WithN _ _)) = True caseName (NS n _) = caseName n caseName _ = False mkLDecl n (TyDecl (DCon tag arity _) _) = LConstructor n tag . length <$> fgetState (cg_usedpos . ist_callgraph n) mkLDecl n (TyDecl (TCon t a) _) = return $ LConstructor n (-1) a mkLDecl n _ = return $ (declArgs [] True n LNothing) -- postulate, never run data VarInfo = VI { viMethod :: Maybe Name } deriving Show type Vars = M.Map Name VarInfo irTerm :: Vars -> [Name] -> Term -> Idris LExp irTerm vs env tm@(App _ f a) = do ist <- getIState case unApply tm of (P _ (UN m) _, args) | m == txt "mkForeignPrim" -> doForeign vs env (reverse (drop 4 args)) -- drop implicits (P _ (UN u) _, [_, arg]) | u == txt "unsafePerformPrimIO" -> irTerm vs env arg -- TMP HACK - until we get inlining. (P _ (UN r) _, [_, _, _, _, _, arg]) | r == txt "replace" -> irTerm vs env arg -- Laziness, the old way (P _ (UN l) _, [_, arg]) | l == txt "lazy" -> error "lazy has crept in somehow" (P _ (UN l) _, [_, arg]) | l == txt "force" -> LForce <$> irTerm vs env arg -- Laziness, the new way (P _ (UN l) _, [_, _, arg]) | l == txt "Delay" -> LLazyExp <$> irTerm vs env arg (P _ (UN l) _, [_, _, arg]) | l == txt "Force" -> LForce <$> irTerm vs env arg (P _ (UN a) _, [_, _, _, arg]) | a == txt "assert_smaller" -> irTerm vs env arg (P _ (UN a) _, [_, arg]) | a == txt "assert_total" -> irTerm vs env arg (P _ (UN p) _, [_, arg]) | p == txt "par" -> do arg' <- irTerm vs env arg return $ LOp LPar [LLazyExp arg'] (P _ (UN pf) _, [arg]) | pf == txt "prim_fork" -> do arg' <- irTerm vs env arg return $ LOp LFork [LLazyExp arg'] (P _ (UN m) _, [_,size,t]) | m == txt "malloc" -> irTerm vs env t (P _ (UN tm) _, [_,t]) | tm == txt "trace_malloc" -> irTerm vs env t -- TODO -- This case is here until we get more general inlining. It's just -- a really common case, and the laziness hurts... (P _ (NS (UN be) [b,p]) _, [_,x,(App _ (App _ (App _ (P _ (UN d) _) _) _) t), (App _ (App _ (App _ (P _ (UN d') _) _) _) e)]) | be == txt "ifThenElse" , d == txt "Delay" , d' == txt "Delay" , b == txt "Bool" , p == txt "Prelude" -> do x' <- irTerm vs env x t' <- irTerm vs env t e' <- irTerm vs env e return (LCase Shared x' [LConCase 0 (sNS (sUN "False") ["Bool","Prelude"]) [] e' ,LConCase 1 (sNS (sUN "True" ) ["Bool","Prelude"]) [] t' ]) -- data constructor (P (DCon t arity _) n _, args) -> do detag <- fgetState (opt_detaggable . ist_optimisation n) used <- map fst <$> fgetState (cg_usedpos . ist_callgraph n) let isNewtype = length used == 1 && detag let argsPruned = [a | (i,a) <- zip [0..] args, i `elem` used] -- The following code removes fields from data constructors -- and performs the newtype optimisation. -- -- The general rule here is: -- Everything we get as input is not touched by erasure, -- so it conforms to the official arities and types -- and we can reason about it like it's plain TT. -- -- It's only the data that leaves this point that's erased -- and possibly no longer typed as the original TT version. -- -- Especially, underapplied constructors must yield functions -- even if all the remaining arguments are erased -- (the resulting function *will* be applied, to NULLs). -- -- This will probably need rethinking when we get erasure from functions. -- "padLams" will wrap our term in LLam-bdas and give us -- the "list of future unerased args" coming from these lambdas. -- -- We can do whatever we like with the list of unerased args, -- hence it takes a lambda: \unerased_argname_list -> resulting_LExp. let padLams = padLambdas used (length args) arity case compare (length args) arity of -- overapplied GT -> ifail ("overapplied data constructor: " ++ show tm) -- exactly saturated EQ | isNewtype -> irTerm vs env (head argsPruned) | otherwise -- not newtype, plain data ctor -> buildApp (LV $ Glob n) argsPruned -- not saturated, underapplied LT | isNewtype -- newtype , length argsPruned == 1 -- and we already have the value -> padLams . (\tm [] -> tm) -- the [] asserts there are no unerased args <$> irTerm vs env (head argsPruned) | isNewtype -- newtype but the value is not among args yet -> return . padLams $ \[vn] -> LApp False (LV $ Glob n) [LV $ Glob vn] -- not a newtype, just apply to a constructor | otherwise -> padLams . applyToNames <$> buildApp (LV $ Glob n) argsPruned -- type constructor (P (TCon t a) n _, args) -> return LNothing -- an external name applied to arguments (P _ n _, args) | S.member (n, length args) (idris_externs ist) -> do LOp (LExternal n) <$> mapM (irTerm vs env) args -- a name applied to arguments (P _ n _, args) -> do case lookup n (idris_scprims ist) of -- if it's a primitive that is already saturated, -- compile to the corresponding op here already to save work Just (arity, op) | length args == arity -> LOp op <$> mapM (irTerm vs env) args -- otherwise, just apply the name _ -> applyName n ist args -- turn de bruijn vars into regular named references and try again (V i, args) -> irTerm vs env $ mkApp (P Bound (env !! i) Erased) args (f, args) -> LApp False <$> irTerm vs env f <*> mapM (irTerm vs env) args where buildApp :: LExp -> [Term] -> Idris LExp buildApp e [] = return e buildApp e xs = LApp False e <$> mapM (irTerm vs env) xs applyToNames :: LExp -> [Name] -> LExp applyToNames tm [] = tm applyToNames tm ns = LApp False tm $ map (LV . Glob) ns padLambdas :: [Int] -> Int -> Int -> ([Name] -> LExp) -> LExp padLambdas used startIdx endSIdx mkTerm = LLam allNames $ mkTerm nonerasedNames where allNames = [sMN i "sat" | i <- [startIdx .. endSIdx-1]] nonerasedNames = [sMN i "sat" | i <- [startIdx .. endSIdx-1], i `elem` used] applyName :: Name -> IState -> [Term] -> Idris LExp applyName n ist args = LApp False (LV $ Glob n) <$> mapM (irTerm vs env . erase) (zip [0..] args) where erase (i, x) | i >= arity || i `elem` used = x | otherwise = Erased arity = case fst4 <$> lookupCtxtExact n (definitions . tt_ctxt $ ist) of Just (CaseOp ci ty tys def tot cdefs) -> length tys Just (TyDecl (DCon tag ar _) _) -> ar Just (TyDecl Ref ty) -> length $ getArgTys ty Just (Operator ty ar op) -> ar Just def -> error $ "unknown arity: " ++ show (n, def) Nothing -> 0 -- no definition, probably local name => can't erase anything -- name for purposes of usage info lookup uName | Just n' <- viMethod =<< M.lookup n vs = n' | otherwise = n used = maybe [] (map fst . usedpos) $ lookupCtxtExact uName (idris_callgraph ist) fst4 (x,_,_,_) = x irTerm vs env (P _ n _) = return $ LV (Glob n) irTerm vs env (V i) | i >= 0 && i < length env = return $ LV (Glob (env!!i)) | otherwise = ifail $ "bad de bruijn index: " ++ show i irTerm vs env (Bind n (Lam _) sc) = LLam [n'] <$> irTerm vs (n':env) sc where n' = uniqueName n env irTerm vs env (Bind n (Let _ v) sc) = LLet n <$> irTerm vs env v <*> irTerm vs (n : env) sc irTerm vs env (Bind _ _ _) = return $ LNothing irTerm vs env (Proj t (-1)) = do t' <- irTerm vs env t return $ LOp (LMinus (ATInt ITBig)) [t', LConst (BI 1)] irTerm vs env (Proj t i) = LProj <$> irTerm vs env t <*> pure i irTerm vs env (Constant TheWorld) = return $ LNothing irTerm vs env (Constant c) = return $ LConst c irTerm vs env (TType _) = return $ LNothing irTerm vs env Erased = return $ LNothing irTerm vs env Impossible = return $ LNothing doForeign :: Vars -> [Name] -> [Term] -> Idris LExp doForeign vs env (ret : fname : world : args) = do args' <- mapM splitArg args let fname' = toFDesc fname let ret' = toFDesc ret return $ LForeign ret' fname' args' where splitArg tm | (_, [_,_,l,r]) <- unApply tm -- pair, two implicits = do let l' = toFDesc l r' <- irTerm vs env r return (l', r') splitArg _ = ifail "Badly formed foreign function call" toFDesc (Constant (Str str)) = FStr str toFDesc tm | (P _ n _, []) <- unApply tm = FCon (deNS n) | (P _ n _, as) <- unApply tm = FApp (deNS n) (map toFDesc as) toFDesc _ = FUnknown deNS (NS n _) = n deNS n = n doForeign vs env xs = ifail "Badly formed foreign function call" {- - | (_, (Constant (Str fgnName) : fgnArgTys : ret : [])) <- unApply fgn = case getFTypes fgnArgTys of Nothing -> ifail $ "Foreign type specification is not a constant list: " ++ show (fgn:args) Just tys -> do args' <- mapM (irTerm vs env) (init args) return $ LForeign LANG_C (mkIty' ret) fgnName (zip tys args') | otherwise = ifail "Badly formed foreign function call" where getFTypes :: TT Name -> Maybe [FType] getFTypes tm = case unApply tm of -- nil : {a : Type} -> List a (nil, [_]) -> Just [] -- cons : {a : Type} -> a -> List a -> List a (cons, [_, ty, xs]) -> (mkIty' ty :) <$> getFTypes xs _ -> Nothing mkIty' (P _ (UN ty) _) = mkIty (str ty) mkIty' (App (P _ (UN fi) _) (P _ (UN intTy) _)) | fi == txt "FIntT" = mkIntIty (str intTy) mkIty' (App (App (P _ (UN ff) _) _) (App (P _ (UN fa) _) (App (P _ (UN io) _) _))) | ff == txt "FFunction" , fa == txt "FAny" , io == txt "IO" = FFunctionIO mkIty' (App (App (P _ (UN ff) _) _) _) | ff == txt "FFunction" = FFunction mkIty' _ = FAny -- would be better if these FInt types were evaluated at compile time -- TODO: add %eval directive for such things -- Issue #1742 on the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1742 mkIty "FFloat" = FArith ATFloat mkIty "FInt" = mkIntIty "ITNative" mkIty "FChar" = mkIntIty "ITChar" mkIty "FByte" = mkIntIty "IT8" mkIty "FShort" = mkIntIty "IT16" mkIty "FLong" = mkIntIty "IT64" mkIty "FBits8" = mkIntIty "IT8" mkIty "FBits16" = mkIntIty "IT16" mkIty "FBits32" = mkIntIty "IT32" mkIty "FBits64" = mkIntIty "IT64" mkIty "FString" = FString mkIty "FPtr" = FPtr mkIty "FManagedPtr" = FManagedPtr mkIty "FUnit" = FUnit mkIty "FFunction" = FFunction mkIty "FFunctionIO" = FFunctionIO mkIty "FBits8x16" = FArith (ATInt (ITVec IT8 16)) mkIty "FBits16x8" = FArith (ATInt (ITVec IT16 8)) mkIty "FBits32x4" = FArith (ATInt (ITVec IT32 4)) mkIty "FBits64x2" = FArith (ATInt (ITVec IT64 2)) mkIty x = error $ "Unknown type " ++ x mkIntIty "ITNative" = FArith (ATInt ITNative) mkIntIty "ITChar" = FArith (ATInt ITChar) mkIntIty "IT8" = FArith (ATInt (ITFixed IT8)) mkIntIty "IT16" = FArith (ATInt (ITFixed IT16)) mkIntIty "IT32" = FArith (ATInt (ITFixed IT32)) mkIntIty "IT64" = FArith (ATInt (ITFixed IT64)) -} irTree :: [Name] -> SC -> Idris LExp irTree args tree = do logLvl 3 $ "Compiling " ++ show args ++ "\n" ++ show tree LLam args <$> irSC M.empty tree irSC :: Vars -> SC -> Idris LExp irSC vs (STerm t) = irTerm vs [] t irSC vs (UnmatchedCase str) = return $ LError str irSC vs (ProjCase tm alts) = do tm' <- irTerm vs [] tm alts' <- mapM (irAlt vs tm') alts return $ LCase Shared tm' alts' -- Transform matching on Delay to applications of Force. irSC vs (Case up n [ConCase (UN delay) i [_, _, n'] sc]) | delay == txt "Delay" = do sc' <- irSC vs $ mkForce n' n sc return $ LLet n' (LForce (LV (Glob n))) sc' -- There are two transformations in this case: -- -- 1. Newtype-case elimination: -- case {e0} of -- wrap({e1}) -> P({e1}) ==> P({e0}) -- -- This is important because newtyped constructors are compiled away entirely -- and we need to do that everywhere. -- -- 2. Unused-case elimination (only valid for singleton branches): -- case {e0} of ==> P -- C(x,y) -> P[... x,y not used ...] -- -- This is important for runtime because sometimes we case on irrelevant data: -- -- In the example above, {e0} will most probably have been erased -- so this vain projection would make the resulting program segfault -- because the code generator still emits a PROJECT(...) G-machine instruction. -- -- Hence, we check whether the variables are used at all -- and erase the casesplit if they are not. -- irSC vs (Case up n [alt]) = do replacement <- case alt of ConCase cn a ns sc -> do detag <- fgetState (opt_detaggable . ist_optimisation cn) used <- map fst <$> fgetState (cg_usedpos . ist_callgraph cn) if detag && length used == 1 then return . Just $ substSC (ns !! head used) n sc else return Nothing _ -> return Nothing case replacement of Just sc -> irSC vs sc _ -> do alt' <- irAlt vs (LV (Glob n)) alt return $ case namesBoundIn alt' `usedIn` subexpr alt' of [] -> subexpr alt' -- strip the unused top-most case _ -> LCase up (LV (Glob n)) [alt'] where namesBoundIn :: LAlt -> [Name] namesBoundIn (LConCase cn i ns sc) = ns namesBoundIn (LConstCase c sc) = [] namesBoundIn (LDefaultCase sc) = [] subexpr :: LAlt -> LExp subexpr (LConCase _ _ _ e) = e subexpr (LConstCase _ e) = e subexpr (LDefaultCase e) = e -- FIXME: When we have a non-singleton case-tree of the form -- -- case {e0} of -- C(x) => ... -- ... => ... -- -- and C is detaggable (the only constructor of the family), we can be sure -- that the first branch will be always taken -- so we add special handling -- to remove the dead default branch. -- -- If we don't do so and C is newtype-optimisable, we will miss this newtype -- transformation and the resulting code will probably segfault. -- -- This work-around is not entirely optimal; the best approach would be -- to ensure that such case trees don't arise in the first place. -- irSC vs (Case up n alts@[ConCase cn a ns sc, DefaultCase sc']) = do detag <- fgetState (opt_detaggable . ist_optimisation cn) if detag then irSC vs (Case up n [ConCase cn a ns sc]) else LCase up (LV (Glob n)) <$> mapM (irAlt vs (LV (Glob n))) alts irSC vs sc@(Case up n alts) = do -- check that neither alternative needs the newtype optimisation, -- see comment above goneWrong <- or <$> mapM isDetaggable alts when goneWrong $ ifail ("irSC: non-trivial case-match on detaggable data: " ++ show sc) -- everything okay LCase up (LV (Glob n)) <$> mapM (irAlt vs (LV (Glob n))) alts where isDetaggable (ConCase cn _ _ _) = fgetState $ opt_detaggable . ist_optimisation cn isDetaggable _ = return False irSC vs ImpossibleCase = return LNothing irAlt :: Vars -> LExp -> CaseAlt -> Idris LAlt -- this leaves out all unused arguments of the constructor irAlt vs _ (ConCase n t args sc) = do used <- map fst <$> fgetState (cg_usedpos . ist_callgraph n) let usedArgs = [a | (i,a) <- zip [0..] args, i `elem` used] LConCase (-1) n usedArgs <$> irSC (methodVars `M.union` vs) sc where methodVars = case n of SN (InstanceCtorN className) -> M.fromList [(v, VI { viMethod = Just $ mkFieldName n i }) | (v,i) <- zip args [0..]] _ -> M.empty -- not an instance constructor irAlt vs _ (ConstCase x rhs) | matchable x = LConstCase x <$> irSC vs rhs | matchableTy x = LDefaultCase <$> irSC vs rhs where matchable (I _) = True matchable (BI _) = True matchable (Ch _) = True matchable (Str _) = True matchable (B8 _) = True matchable (B16 _) = True matchable (B32 _) = True matchable (B64 _) = True matchable _ = False matchableTy (AType (ATInt ITNative)) = True matchableTy (AType (ATInt ITBig)) = True matchableTy (AType (ATInt ITChar)) = True matchableTy StrType = True matchableTy (AType (ATInt (ITFixed IT8))) = True matchableTy (AType (ATInt (ITFixed IT16))) = True matchableTy (AType (ATInt (ITFixed IT32))) = True matchableTy (AType (ATInt (ITFixed IT64))) = True matchableTy _ = False irAlt vs tm (SucCase n rhs) = do rhs' <- irSC vs rhs return $ LDefaultCase (LLet n (LOp (LMinus (ATInt ITBig)) [tm, LConst (BI 1)]) rhs') irAlt vs _ (ConstCase c rhs) = ifail $ "Can't match on (" ++ show c ++ ")" irAlt vs _ (DefaultCase rhs) = LDefaultCase <$> irSC vs rhs
rpglover64/Idris-dev
src/IRTS/Compiler.hs
Haskell
bsd-3-clause
26,376
module Main(main) where import PolyPaver.Invocation import Data.Ratio ((%)) main = defaultMain Problem { box = [(0,(409018325532672 % 579004697502343,9015995347763200 % 6369051672525773)),(1,(1 % 2,2 % 1))] ,theorem = thm } thm = Implies (Geq (Var 0) (Over (Over (Lit (1023 % 1)) (Lit (1024 % 1))) (Sqrt (Var 1)))) (Implies (Leq (Var 0) (Over (Over (Lit (1025 % 1)) (Lit (1024 % 1))) (Sqrt (Var 1)))) (Implies (Geq (Var 1) (Neg (Lit (340282000000000000000000000000000000000 % 1)))) (Implies (Geq (Var 1) (Over (Lit (1 % 1)) (Lit (2 % 1)))) (Implies (Leq (Var 1) (Lit (2 % 1))) (Implies (Geq (Var 0) (Neg (Lit (340282000000000000000000000000000000000 % 1)))) (Implies (Leq (Var 0) (Lit (340282000000000000000000000000000000000 % 1))) (And (Geq (FTimes (Over (Lit (1 % 1)) (Lit (2 % 1))) (Var 0)) (Neg (Lit (340282000000000000000000000000000000000 % 1)))) (Leq (FTimes (Over (Lit (1 % 1)) (Lit (2 % 1))) (Var 0)) (Lit (340282000000000000000000000000000000000 % 1))))))))))
michalkonecny/polypaver
examples/old/their_sqrt/their_sqrt_11.hs
Haskell
bsd-3-clause
1,018
{-# LANGUAGE DataKinds #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# OPTIONS -Wall #-} -- | -- Module : GHC.TypeLits.SigNat -- License : BSD3 -- Maintainer : ehaussecker@alphaheavy.com -- Stability : Experimental -- Portability : GHC 7.8.* on Unix -- -- This module provides support for signed type-level naturals. module GHC.TypeLits.SigNat ( -- ** Signed Type-Level Naturals SigNat(..) , KnownSigNat(..) , SomeSigNat(..) , someSigNatVal , promoteSigNat ) where import Data.Maybe (fromJust) import Data.Proxy (Proxy(..)) import GHC.TypeLits -- | -- This is the kind of a signed type-level natural. data SigNat where Plus :: Nat -> SigNat Minus :: Nat -> SigNat -- | -- This class gives the integer associated with a signed type-level natural. class KnownSigNat (signat :: SigNat) where sigNatVal :: Proxy signat -> Integer instance KnownNat nat => KnownSigNat (Plus nat) where sigNatVal _ = natVal (Proxy :: Proxy nat) instance KnownNat nat => KnownSigNat (Minus nat) where sigNatVal _ = negate $ natVal (Proxy :: Proxy nat) -- | -- This type represents an unknown signed type-level natural. data SomeSigNat = forall signat . KnownSigNat signat => SomeSigNat (Proxy signat) instance Eq SomeSigNat where SomeSigNat proxy1 == SomeSigNat proxy2 = sigNatVal proxy1 == sigNatVal proxy2 deriving instance Show SomeSigNat -- | -- Convert an integer into an unknown signed type-level natural. someSigNatVal :: Integer -> SomeSigNat someSigNatVal x = case fromJust . someNatVal $ abs x of SomeNat (_ :: Proxy nat) -> if x >= 0 then SomeSigNat (Proxy :: Proxy (Plus nat)) else SomeSigNat (Proxy :: Proxy (Minus nat)) -- | -- Promote a signed type-level natural. promoteSigNat :: forall proxy signat a . KnownSigNat signat => proxy signat -> (Proxy signat -> a) -> a promoteSigNat _ f = f Proxy
time-cube/time-cube
src/GHC/TypeLits/SigNat.hs
Haskell
bsd-3-clause
2,116
{- BlendEqn.hs (adapted from blendeqn.c which is (c) Silicon Graphics, Inc.) Copyright (c) Sven Panne 2002-2005 <sven.panne@aedion.de> This file is part of HOpenGL and distributed under a BSD-style license See the file libraries/GLUT/LICENSE Demonstrate the different blending functions available with the OpenGL imaging subset. This program demonstrates use of blendEquation. The following keys change the selected blend equation function: 'a' -> FuncAdd 's' -> FuncSubtract 'r' -> FuncReverseSubtract 'm' -> Min 'x' -> Max -} import Data.Char ( toLower ) import System.Exit ( exitWith, ExitCode(ExitSuccess) ) import Graphics.UI.GLUT myInit :: IO () myInit = do clearColor $= Color4 1 1 0 0 blendFunc $= (One, One) blend $= Enabled display :: DisplayCallback display = do clear [ ColorBuffer ] color (Color3 0 0 (1 :: GLfloat)) rect (Vertex2 (-0.5) (-0.5)) (Vertex2 0.5 (0.5 :: GLfloat)) flush reshape :: ReshapeCallback reshape size@(Size w h) = do let aspect = fromIntegral w / fromIntegral h viewport $= (Position 0 0, size) matrixMode $= Projection loadIdentity if aspect < 1 then let aspect' = recip aspect in ortho (-aspect') aspect' (-1) 1 (-1) 1 else ortho (-1) 1 (-aspect) aspect (-1) 1 matrixMode $= Modelview 0 keyboard :: KeyboardMouseCallback keyboard (Char c) Down _ _ = case toLower c of -- Colors are added as: (0, 0, 1) + (1, 1, 0) = (1, 1, 1) -- which will produce a white square on a yellow background. 'a' -> setBlendEquation FuncAdd -- Colors are subtracted as: (0, 0, 1) - (1, 1, 0) = (-1, -1, 1) -- which is clamped to (0, 0, 1), producing a blue square on a -- yellow background 's' -> setBlendEquation FuncSubtract -- Colors are subtracted as: (1, 1, 0) - (0, 0, 1) = (1, 1, -1) -- which is clamed to (1, 1, 0). This produces yellow for both -- the square and the background. 'r' -> setBlendEquation FuncReverseSubtract -- The minimum of each component is computed, as -- [min(0, 1), min(0, 1), min(1, 0)] which equates to (0, 0, 0). -- This will produce a black square on the yellow background. 'm' -> setBlendEquation Min -- The minimum of each component is computed, as -- [max(0, 1), max(0, 1), max(1, 0)] which equates to (1, 1, 1) -- This will produce a white square on the yellow background. 'x' -> setBlendEquation Max '\27' -> exitWith ExitSuccess _ -> return () where setBlendEquation e = do blendEquation $= e postRedisplay Nothing keyboard _ _ _ _ = return () main :: IO () main = do (progName, _args) <- getArgsAndInitialize initialDisplayMode $= [ SingleBuffered, RGBMode ] initialWindowSize $= Size 512 512 initialWindowPosition $= Position 100 100 createWindow progName myInit reshapeCallback $= Just reshape keyboardMouseCallback $= Just keyboard displayCallback $= display mainLoop
FranklinChen/hugs98-plus-Sep2006
packages/GLUT/examples/RedBook/BlendEqn.hs
Haskell
bsd-3-clause
3,007
{-# LANGUAGE TemplateHaskell, GeneralizedNewtypeDeriving #-} import System.IO import System.Linux.Input.Event import Control.Concurrent.STM import Control.Concurrent import Control.Lens import Control.Applicative import Data.Int import Data.Functor.Rep import Linear import Control.Monad (forever) import Control.Monad.State.Strict import Data.Traversable as T import Data.Foldable as F import Data.Monoid import Options.Applicative hiding ((&)) import qualified MercuryController as MM import qualified ZMotor as Z data Config = Config { xyDevice :: FilePath , zDevice :: FilePath , inputDevice :: FilePath , driveCurrent :: Int , holdCurrent :: Int } axisNames :: V3 String axisNames = V3 "x" "y" "z" config = Config <$> strOption ( long "xy" <> metavar "DEVICE" <> value "/dev/ttyUSB.stage" <> help "XY stepper device path") <*> strOption ( long "z" <> metavar "DEVICE" <> value "/dev/ttyUSB.zstage" <> help "Z stepper device path") <*> strOption ( long "input" <> metavar "DEVICE" <> value "/dev/input/event4" <> help "Joystick input device") <*> option auto ( long "drive-current" <> metavar "MA" <> value 350 <> help "Motor drive current") <*> option auto ( long "hold-current" <> metavar "MA" <> value 350 <> help "Motor drive current") newtype Position = Pos Int deriving (Show, Eq, Ord, Num, Integral, Real, Enum) data NavAxis = NavAxis { _position :: Position , _velocity :: Double -- | Position units per second } deriving (Show, Eq) makeLenses ''NavAxis type Mover = Position -> IO () newNavAxis :: Int -> Mover -> Position -> IO (MVar NavAxis) newNavAxis updateRate move initial = do ref <- newMVar $ NavAxis initial 0 forkIO $ forever $ update ref initial return ref where dt = 1 / realToFrac updateRate update ref lastPos = do threadDelay $ round (1e6 * dt) na' <- modifyMVar ref $ \na->do let dx = round $ dt * na ^. velocity na' = na & position %~ (+dx) pos = na' ^. position when (lastPos /= pos) $ move pos return (na', na') update ref (na' ^. position) newMotorQueue :: FilePath -> IO (TQueue (MM.Bus -> IO ())) newMotorQueue device = do bus <- MM.open device queue <- newTQueueIO forkIO $ forever $ atomically (readTQueue queue) >>= ($ bus) return queue data JoystickState = JSS { _jssPosition :: V3 Int32 , _jssEnabled :: V3 Bool , _jssCurrentAxis :: [E V3] } makeLenses ''JoystickState listenEvDev :: Handle -> V3 (MVar NavAxis) -> IO () listenEvDev h navAxes = void $ flip evalStateT s0 $ forever $ lift (hReadEvent h) >>= maybe (return ()) handleEvent where s0 = JSS { _jssPosition = pure 0 , _jssEnabled = pure True , _jssCurrentAxis = cycle [ex, ey, ez] } handleEvent :: Event -> StateT JoystickState IO () handleEvent (KeyEvent {evKeyCode=key, evKeyEventType=Released}) | key == btn_0 = do curAxis:_ <- use jssCurrentAxis jssEnabled . el curAxis %= not en <- use jssEnabled when (not $ en ^. el curAxis) $ do jssPosition . el curAxis .= 0 lift $ putStrLn $ "Enabled axes: "++show en | key == btn_1 = do jssCurrentAxis %= tail axis:_ <- use jssCurrentAxis lift $ putStrLn $ "Selected axis: "++(axisNames ^. el axis) handleEvent event@(RelEvent {}) = do case relAxisToLens (evRelAxis event) of Just l -> do enabled <- use $ jssEnabled . el l when enabled $ do jssPosition . el l .= evValue event update Nothing -> return () handleEvent _ = return () tabulateV3 = tabulate :: (E V3 -> a) -> V3 a update :: StateT JoystickState IO () update = void $ T.sequence $ tabulateV3 $ \(E l)->do v <- uses (jssPosition . l) realToFrac lift $ modifyMVar_ (navAxes ^. l) $ return . (velocity .~ v) relAxisToLens :: RelAxis -> Maybe (E V3) relAxisToLens ax | ax == rel_x = Just ex | ax == rel_y = Just ey | ax == rel_z = Just ez | otherwise = Nothing valueToVelocity :: V3 Int32 -> V3 Double valueToVelocity v | norm v' < thresh = 0 | otherwise = gain * (norm v' - thresh)**1.4 *^ vhat where thresh = 30 gain = 1 v' = fmap realToFrac v vhat = normalize v' updateRate = 30 axes = V2 (MM.Axis 0) (MM.Axis 1) main :: IO () main = do args <- execParser $ info (helper <*> config) mempty putStrLn "Opening XY stage" queue <- newMotorQueue (xyDevice args) let enqueue :: (MM.Bus -> IO ()) -> IO () enqueue = atomically . writeTQueue queue initialVar <- newEmptyMVar enqueue $ \bus->do initialPos <- T.forM axes $ \axis->do MM.select bus axis --MM.getError bus >>= print MM.setBrake bus False MM.setDriveCurrent bus (driveCurrent args) MM.setHoldCurrent bus (holdCurrent args) MM.setMotorPower bus True either (error "Error fetching initial position") fromIntegral <$> MM.getPosition bus putMVar initialVar initialPos initial <- takeMVar initialVar let moveStage :: MM.Axis -> Mover moveStage axis (Pos n) = enqueue $ \bus->do MM.select bus axis MM.moveAbs bus (MM.Pos $ fromIntegral n) putStrLn $ "Move "++show axis++" to "++show n putStrLn "Opening Z stage" zMotor <- Z.open (zDevice args) let moveZStage (Pos n) = do Z.move zMotor n putStrLn $ "Move Z to "++show n --forkIO $ forever $ threadDelay 1000000 >> enqueue reportPositions navAxes <- T.sequence $ V3 (newNavAxis updateRate (moveStage (axes ^. _x)) (initial ^. _x)) (newNavAxis updateRate (moveStage (axes ^. _y)) (initial ^. _y)) (newNavAxis updateRate moveZStage 0) putStrLn "Opening joystick" joystick <- openFile (inputDevice args) ReadMode listenEvDev joystick navAxes reportPositions :: MM.Bus -> IO () reportPositions bus = F.forM_ axes $ \axis->do MM.select bus axis p <- MM.getPosition bus putStrLn $ show axis++" is "++show p
bgamari/navigate
Navigate.hs
Haskell
bsd-3-clause
6,750
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Time.IT.Tests ( tests ) where import Data.String import Prelude import Test.Tasty import Duckling.Dimensions.Types import Duckling.Testing.Asserts import Duckling.Time.IT.Corpus tests :: TestTree tests = testGroup "IT Tests" [ makeCorpusTest [Seal Time] corpus , makeNegativeCorpusTest [Seal Time] negativeCorpus ]
facebookincubator/duckling
tests/Duckling/Time/IT/Tests.hs
Haskell
bsd-3-clause
549
{-# LANGUAGE RecordWildCards #-} module Tronkell.Server.Server where import Tronkell.Server.Types as Server import Tronkell.Game.Types as Game import Tronkell.Types() import Tronkell.Game.Engine as Engine import qualified Tronkell.Utils as SUtils import qualified Tronkell.Network.Websockets as W import qualified Tronkell.Network.TcpSockets as Tcp import Control.Concurrent import Control.Concurrent.STM import qualified Data.Text as T import Data.Maybe (fromJust) import Control.Monad (void, foldM, forever, when) import Control.Monad.Fix (fix) import qualified Data.Map as M import qualified Data.List as L (foldl') startServer :: Game.GameConfig -> IO () startServer gConfig = do firstUId <- newMVar $ UserID 0 playersVar <- newMVar M.empty networkInChan <- newChan clientSpecificOutChan <- newChan serverChan <- atomically newTChan clientsChan <- newChan internalChan <- newChan let networkChans = (networkInChan, clientSpecificOutChan) server = Server gConfig playersVar networkChans serverChan clientsChan internalChan -- start game server : one game at a time. gameThread <- forkIO $ forever $ do moveAllPlayersToWaiting (serverUsers server) gameEngineThread server Nothing -- start network wsThread <- forkIO $ W.start firstUId networkChans clientsChan tcpThread <- forkIO $ Tcp.start firstUId networkChans clientsChan -- to avoid space msg leak.. -- fixme : move to broadcast tchan forkIO . forever . readChan $ clientSpecificOutChan forkIO . forever . readChan $ clientsChan forkIO . forever . readChan $ internalChan clientsLoop server M.empty killThread gameThread killThread wsThread killThread tcpThread where moveAllPlayersToWaiting serverUsers = modifyMVar_ serverUsers (return . M.map (\u -> u { userState = Waiting })) clientsLoop :: Server -> M.Map UserID (TChan InMessage) -> IO () clientsLoop server@Server{..} userChans = do let (networkInChan, _) = networkChans msg <- readChan networkInChan case msg of PlayerJoined uId -> do userChan <- atomically newTChan let userChans' = M.insert uId userChan userChans -- check if uId already not there void $ forkIO $ runClient uId userChan server -- remove useChan after runClient returns. clientsLoop server userChans' _ -> do let uId = SUtils.getUserId msg userChan = M.lookup uId userChans maybe (return ()) (\c -> atomically $ writeTChan c msg) userChan clientsLoop server userChans runClient :: UserID -> TChan InMessage -> Server -> IO () runClient uId clientChan server@Server{..} = do let (_, clientSpecificOutChan) = networkChans writeChan clientSpecificOutChan $ (uId, ServerMsg "Take a nick name : ") msg <- atomically $ readTChan clientChan let nick = case msg of PlayerName _ name -> Just name _ -> Nothing case nick of Nothing -> runClient uId clientChan server Just _ -> do let user = User uId nick Waiting failedToAdd <- modifyMVar serverUsers $ \users -> -- for player we still have name as id ; so keep it unique. if isNickTaken users nick then return (users, True) else return (M.insert uId user users, False) if failedToAdd then runClient uId clientChan server else do atomically $ writeTChan serverChan $ PlayerJoined uId waitForPlayerReady clientSpecificOutChan nick where isNickTaken users nick = any (\u -> nick == userNick u) users waitForPlayerReady clientSpecificOutChan nick = fix $ \ loop -> do writeChan clientSpecificOutChan $ (uId, ServerMsg $ "Hi.. " ++ T.unpack (fromJust nick) ++ ".. send \"ready\" when you are ready to play..") m <- atomically $ readTChan clientChan case m of PlayerReady _ -> do playClient uId clientChan server exists <- userExistsNow serverUsers when exists $ loop UserExit _ -> onUserExit uId serverUsers _ -> loop userExistsNow users = do currentUsers <- readMVar users return (M.member uId currentUsers) playClient :: UserID -> TChan InMessage -> Server -> IO () playClient clientId inChan Server{..} = do let (_, clientSpecificOutChan) = networkChans clientInternalChan <- dupChan internalChan writeChan clientSpecificOutChan (clientId, ServerMsg "Waiting for other players to start the game...!!!") writeChan clientSpecificOutChan (clientId, PlayerRegisterId clientId) atomically $ writeTChan serverChan $ PlayerReady clientId -- block on ready-signal from server-thread to start the game. signal <- readChan clientInternalChan case signal of GameReadySignal _ _ -> return () writeList2Chan clientSpecificOutChan [ (clientId, ServerMsg "Here.. you go!!!") , (clientId, ServerMsg "Movements: type L for left , R for right, Q for quit... enjoy.") ] -- flush all accumulated messages till now before allowing to play the game. _ <- SUtils.readMsgs inChan fix $ \loop -> do msg <- atomically $ readTChan inChan case msg of PlayerExit _ -> void $ writeChan clientSpecificOutChan (clientId, ServerMsg "Sayonara !!!") UserExit _ -> atomically $ writeTChan serverChan msg _ -> atomically (writeTChan serverChan msg) >> loop atomically $ writeTChan serverChan (PlayerExit clientId) -- Adds user to user list and returns whether all users are ready updateUserReady :: UserID -> M.Map UserID User -> IO (M.Map UserID User, Bool) updateUserReady clientId users = let newUsers = M.adjust (\u -> u { userState = Ready }) clientId users -- We have at least 2 users, and all users are ready ready = length users > 1 && all ((Ready ==) . userState) newUsers in return (newUsers, ready) oneSecond :: Int oneSecond = 1000000 onUserExit :: UserID -> MVar (M.Map UserID User) -> IO () onUserExit clientId serverUsers = modifyMVar_ serverUsers (return . M.delete clientId) processMessages :: Server -> Maybe Game -> [InMessage] -> IO (Maybe Game) processMessages server@Server{..} game inMsgs = do game' <- foldM threadGameOverEvent game inMsgs moveAllDeadPlayersToWaiting game' return game' where threadGameOverEvent g' inMsg = case inMsg of PlayerJoined _ -> return game PlayerReady clientId -> processPlayerReady clientId PlayerTurnLeft clientId -> processEvent' g' TurnLeft clientId PlayerTurnRight clientId -> processEvent' g' TurnRight clientId UserExit clientId -> do onUserExit clientId serverUsers processEvent' g' PlayerQuit clientId PlayerExit clientId -> do processEvent' g' PlayerQuit clientId PlayerName _ _ -> return game processPlayerReady clientId = case game of -- do not disturb already running game. Just game' -> return $ Just game' -- start a new game. Nothing -> do ready <- modifyMVar serverUsers $ updateUserReady clientId -- if all users are ready, start the game. if ready then do users <- readMVar serverUsers players <- SUtils.playersFromUsers serverGameConfig users writeChan internalChan $ GameReadySignal serverGameConfig (M.elems players) writeChan clientsChan $ GameReady serverGameConfig (M.elems players) return $ Just $ Game Nothing players InProgress serverGameConfig else return Nothing processEvent' game' evCons clientId = do let event = evCons . PlayerId . getUserID $ clientId processEvent server game' event moveAllDeadPlayersToWaiting maybeGame = case maybeGame of -- try maybe Nothing -> return () Just g' -> let deadUserIds = map SUtils.playerIdToUserId $ Engine.deadPlayers g' in modifyMVar_ serverUsers $ \users -> return $ L.foldl' (\newUsers deadUId -> M.adjust (\u -> u { userState = Waiting }) deadUId newUsers) users deadUserIds processEvent :: Server -> Maybe Game -> InputEvent -> IO (Maybe Game) processEvent Server{..} g event = do users <- readMVar serverUsers let (outEvs, game') = runGame g event outMsgs = SUtils.outEventToOutMessage users <$> outEvs writeList2Chan clientsChan outMsgs return game' gameEngineThread :: Server -> Maybe Game -> IO Game gameEngineThread server@Server{..} game = do threadDelay . quot oneSecond . gameTicksPerSecond $ serverGameConfig inMsgs <- SUtils.readMsgs serverChan game' <- processMessages server game inMsgs game'' <- processEvent server game' Tick if isGameFinished game'' then return . fromJust $ game'' else gameEngineThread server game'' where isGameFinished g = case g of Nothing -> False Just g' -> Finished == gameStatus g' runGame :: Maybe Game -> InputEvent -> ([OutEvent], Maybe Game) runGame game event = case game of Nothing -> ([], Nothing) Just g -> Just <$> Engine.runEngine Engine.gameEngine g [event]
nilenso/tronkell
src/Tronkell/Server/Server.hs
Haskell
bsd-3-clause
9,308
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} -- | Resolving a build plan for a set of packages in a given Stackage -- snapshot. module Stack.BuildPlan ( BuildPlanException (..) , MiniBuildPlan(..) , MiniPackageInfo(..) , Snapshots (..) , getSnapshots , loadMiniBuildPlan , resolveBuildPlan , findBuildPlan , ToolMap , getToolMap , shadowMiniBuildPlan , parseCustomMiniBuildPlan ) where import Control.Applicative import Control.Exception (assert) import Control.Monad (liftM, forM) import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (asks) import Control.Monad.State.Strict (State, execState, get, modify, put) import Control.Monad.Trans.Control (MonadBaseControl) import qualified Crypto.Hash.SHA256 as SHA256 import Data.Aeson.Extended (FromJSON (..), withObject, withText, (.:), (.:?), (.!=)) import Data.Binary.VersionTagged (taggedDecodeOrLoad) import Data.ByteString (ByteString) import qualified Data.ByteString.Base16 as B16 import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import Data.Either (partitionEithers) import qualified Data.Foldable as F import qualified Data.HashMap.Strict as HM import Data.IntMap (IntMap) import qualified Data.IntMap as IntMap import Data.List (intercalate) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromMaybe, mapMaybe) import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Data.Time (Day) import qualified Data.Traversable as Tr import Data.Typeable (Typeable) import Data.Yaml (decodeEither', decodeFileEither) import Distribution.PackageDescription (GenericPackageDescription, flagDefault, flagManual, flagName, genPackageFlags, executables, exeName, library, libBuildInfo, buildable) import qualified Distribution.Package as C import qualified Distribution.PackageDescription as C import qualified Distribution.Version as C import Distribution.Text (display) import Network.HTTP.Download import Network.HTTP.Types (Status(..)) import Network.HTTP.Client (checkStatus) import Path import Path.IO import Prelude -- Fix AMP warning import Stack.Constants import Stack.Fetch import Stack.GhcPkg import Stack.Package import Stack.PackageIndex import Stack.Types import Stack.Types.StackT import System.Directory (canonicalizePath) import qualified System.FilePath as FP data BuildPlanException = UnknownPackages (Path Abs File) -- stack.yaml file (Map PackageName (Maybe Version, (Set PackageName))) -- truly unknown (Map PackageName (Set PackageIdentifier)) -- shadowed | SnapshotNotFound SnapName deriving (Typeable) instance Exception BuildPlanException instance Show BuildPlanException where show (SnapshotNotFound snapName) = unlines [ "SnapshotNotFound " ++ snapName' , "Non existing resolver: " ++ snapName' ++ "." , "For a complete list of available snapshots see https://www.stackage.org/snapshots" ] where snapName' = show $ renderSnapName snapName show (UnknownPackages stackYaml unknown shadowed) = unlines $ unknown' ++ shadowed' where unknown' :: [String] unknown' | Map.null unknown = [] | otherwise = concat [ ["The following packages do not exist in the build plan:"] , map go (Map.toList unknown) , case mapMaybe goRecommend $ Map.toList unknown of [] -> [] rec -> ("Recommended action: modify the extra-deps field of " ++ toFilePath stackYaml ++ " to include the following:") : (rec ++ ["Note: further dependencies may need to be added"]) , case mapMaybe getNoKnown $ Map.toList unknown of [] -> [] noKnown -> [ "There are no known versions of the following packages:" , intercalate ", " $ map packageNameString noKnown ] ] where go (dep, (_, users)) | Set.null users = packageNameString dep go (dep, (_, users)) = concat [ packageNameString dep , " (used by " , intercalate ", " $ map packageNameString $ Set.toList users , ")" ] goRecommend (name, (Just version, _)) = Just $ "- " ++ packageIdentifierString (PackageIdentifier name version) goRecommend (_, (Nothing, _)) = Nothing getNoKnown (name, (Nothing, _)) = Just name getNoKnown (_, (Just _, _)) = Nothing shadowed' :: [String] shadowed' | Map.null shadowed = [] | otherwise = concat [ ["The following packages are shadowed by local packages:"] , map go (Map.toList shadowed) , ["Recommended action: modify the extra-deps field of " ++ toFilePath stackYaml ++ " to include the following:"] , extraDeps , ["Note: further dependencies may need to be added"] ] where go (dep, users) | Set.null users = concat [ packageNameString dep , " (internal stack error: this should never be null)" ] go (dep, users) = concat [ packageNameString dep , " (used by " , intercalate ", " $ map (packageNameString . packageIdentifierName) $ Set.toList users , ")" ] extraDeps = map (\ident -> "- " ++ packageIdentifierString ident) $ Set.toList $ Set.unions $ Map.elems shadowed -- | Determine the necessary packages to install to have the given set of -- packages available. -- -- This function will not provide test suite and benchmark dependencies. -- -- This may fail if a target package is not present in the @BuildPlan@. resolveBuildPlan :: (MonadThrow m, MonadIO m, MonadReader env m, HasBuildConfig env, MonadLogger m, HasHttpManager env, MonadBaseControl IO m,MonadCatch m) => EnvOverride -> MiniBuildPlan -> (PackageName -> Bool) -- ^ is it shadowed by a local package? -> Map PackageName (Set PackageName) -- ^ required packages, and users of it -> m ( Map PackageName (Version, Map FlagName Bool) , Map PackageName (Set PackageName) ) resolveBuildPlan menv mbp isShadowed packages | Map.null (rsUnknown rs) && Map.null (rsShadowed rs) = return (rsToInstall rs, rsUsedBy rs) | otherwise = do cache <- getPackageCaches menv let maxVer = Map.fromListWith max $ map toTuple $ Map.keys cache unknown = flip Map.mapWithKey (rsUnknown rs) $ \ident x -> (Map.lookup ident maxVer, x) bconfig <- asks getBuildConfig throwM $ UnknownPackages (bcStackYaml bconfig) unknown (rsShadowed rs) where rs = getDeps mbp isShadowed packages data ResolveState = ResolveState { rsVisited :: Map PackageName (Set PackageName) -- ^ set of shadowed dependencies , rsUnknown :: Map PackageName (Set PackageName) , rsShadowed :: Map PackageName (Set PackageIdentifier) , rsToInstall :: Map PackageName (Version, Map FlagName Bool) , rsUsedBy :: Map PackageName (Set PackageName) } toMiniBuildPlan :: (MonadIO m, MonadLogger m, MonadReader env m, HasHttpManager env, MonadThrow m, HasConfig env, MonadBaseControl IO m, MonadCatch m) => Version -- ^ GHC version -> Map PackageName Version -- ^ cores -> Map PackageName (Version, Map FlagName Bool) -- ^ non-core packages -> m MiniBuildPlan toMiniBuildPlan ghcVersion corePackages packages = do $logInfo "Caching build plan" -- Determine the dependencies of all of the packages in the build plan. We -- handle core packages specially, because some of them will not be in the -- package index. For those, we allow missing packages to exist, and then -- remove those from the list of dependencies, since there's no way we'll -- ever reinstall them anyway. (cores, missingCores) <- addDeps True ghcVersion $ fmap (, Map.empty) corePackages (extras, missing) <- addDeps False ghcVersion packages assert (Set.null missing) $ return MiniBuildPlan { mbpGhcVersion = ghcVersion , mbpPackages = Map.unions [ fmap (removeMissingDeps (Map.keysSet cores)) cores , extras , Map.fromList $ map goCore $ Set.toList missingCores ] } where goCore (PackageIdentifier name version) = (name, MiniPackageInfo { mpiVersion = version , mpiFlags = Map.empty , mpiPackageDeps = Set.empty , mpiToolDeps = Set.empty , mpiExes = Set.empty , mpiHasLibrary = True }) removeMissingDeps cores mpi = mpi { mpiPackageDeps = Set.intersection cores (mpiPackageDeps mpi) } -- | Add in the resolved dependencies from the package index addDeps :: (MonadIO m, MonadLogger m, MonadReader env m, HasHttpManager env, MonadThrow m, HasConfig env, MonadBaseControl IO m, MonadCatch m) => Bool -- ^ allow missing -> Version -- ^ GHC version -> Map PackageName (Version, Map FlagName Bool) -> m (Map PackageName MiniPackageInfo, Set PackageIdentifier) addDeps allowMissing ghcVersion toCalc = do menv <- getMinimalEnvOverride platform <- asks $ configPlatform . getConfig (resolvedMap, missingIdents) <- if allowMissing then do (missingNames, missingIdents, m) <- resolvePackagesAllowMissing menv (Map.keysSet idents0) Set.empty assert (Set.null missingNames) $ return (m, missingIdents) else do m <- resolvePackages menv (Map.keysSet idents0) Set.empty return (m, Set.empty) let byIndex = Map.fromListWith (++) $ flip map (Map.toList resolvedMap) $ \(ident, rp) -> (indexName $ rpIndex rp, [( ident , rpCache rp , maybe Map.empty snd $ Map.lookup (packageIdentifierName ident) toCalc )]) res <- forM (Map.toList byIndex) $ \(indexName', pkgs) -> withCabalFiles indexName' pkgs $ \ident flags cabalBS -> do gpd <- readPackageUnresolvedBS Nothing cabalBS let packageConfig = PackageConfig { packageConfigEnableTests = False , packageConfigEnableBenchmarks = False , packageConfigFlags = flags , packageConfigGhcVersion = ghcVersion , packageConfigPlatform = platform } name = packageIdentifierName ident pd = resolvePackageDescription packageConfig gpd exes = Set.fromList $ map (ExeName . S8.pack . exeName) $ executables pd notMe = Set.filter (/= name) . Map.keysSet return (name, MiniPackageInfo { mpiVersion = packageIdentifierVersion ident , mpiFlags = flags , mpiPackageDeps = notMe $ packageDependencies pd , mpiToolDeps = Map.keysSet $ packageToolDependencies pd , mpiExes = exes , mpiHasLibrary = maybe False (buildable . libBuildInfo) (library pd) }) return (Map.fromList $ concat res, missingIdents) where idents0 = Map.fromList $ map (\(n, (v, f)) -> (PackageIdentifier n v, Left f)) $ Map.toList toCalc -- | Resolve all packages necessary to install for getDeps :: MiniBuildPlan -> (PackageName -> Bool) -- ^ is it shadowed by a local package? -> Map PackageName (Set PackageName) -> ResolveState getDeps mbp isShadowed packages = execState (mapM_ (uncurry goName) $ Map.toList packages) ResolveState { rsVisited = Map.empty , rsUnknown = Map.empty , rsShadowed = Map.empty , rsToInstall = Map.empty , rsUsedBy = Map.empty } where toolMap = getToolMap mbp -- | Returns a set of shadowed packages we depend on. goName :: PackageName -> Set PackageName -> State ResolveState (Set PackageName) goName name users = do -- Even though we could check rsVisited first and short-circuit things -- earlier, lookup in mbpPackages first so that we can produce more -- usable error information on missing dependencies rs <- get put rs { rsUsedBy = Map.insertWith Set.union name users $ rsUsedBy rs } case Map.lookup name $ mbpPackages mbp of Nothing -> do modify $ \rs' -> rs' { rsUnknown = Map.insertWith Set.union name users $ rsUnknown rs' } return Set.empty Just mpi -> case Map.lookup name (rsVisited rs) of Just shadowed -> return shadowed Nothing -> do put rs { rsVisited = Map.insert name Set.empty $ rsVisited rs } let depsForTools = Set.unions $ mapMaybe (flip Map.lookup toolMap) (Set.toList $ mpiToolDeps mpi) let deps = Set.filter (/= name) (mpiPackageDeps mpi <> depsForTools) shadowed <- fmap F.fold $ Tr.forM (Set.toList deps) $ \dep -> if isShadowed dep then do modify $ \rs' -> rs' { rsShadowed = Map.insertWith Set.union dep (Set.singleton $ PackageIdentifier name (mpiVersion mpi)) (rsShadowed rs') } return $ Set.singleton dep else do shadowed <- goName dep (Set.singleton name) let m = Map.fromSet (\_ -> Set.singleton $ PackageIdentifier name (mpiVersion mpi)) shadowed modify $ \rs' -> rs' { rsShadowed = Map.unionWith Set.union m $ rsShadowed rs' } return shadowed modify $ \rs' -> rs' { rsToInstall = Map.insert name (mpiVersion mpi, mpiFlags mpi) $ rsToInstall rs' , rsVisited = Map.insert name shadowed $ rsVisited rs' } return shadowed -- | Look up with packages provide which tools. type ToolMap = Map ByteString (Set PackageName) -- | Map from tool name to package providing it getToolMap :: MiniBuildPlan -> Map ByteString (Set PackageName) getToolMap mbp = Map.unionsWith Set.union {- We no longer do this, following discussion at: https://github.com/commercialhaskell/stack/issues/308#issuecomment-112076704 -- First grab all of the package names, for times where a build tool is -- identified by package name $ Map.fromList (map (packageNameByteString &&& Set.singleton) (Map.keys ps)) -} -- And then get all of the explicit executable names $ concatMap goPair (Map.toList ps) where ps = mbpPackages mbp goPair (pname, mpi) = map (flip Map.singleton (Set.singleton pname) . unExeName) $ Set.toList $ mpiExes mpi -- | Download the 'Snapshots' value from stackage.org. getSnapshots :: (MonadThrow m, MonadIO m, MonadReader env m, HasHttpManager env, HasStackRoot env, HasConfig env) => m Snapshots getSnapshots = askLatestSnapshotUrl >>= parseUrl . T.unpack >>= downloadJSON -- | Most recent Nightly and newest LTS version per major release. data Snapshots = Snapshots { snapshotsNightly :: !Day , snapshotsLts :: !(IntMap Int) } deriving Show instance FromJSON Snapshots where parseJSON = withObject "Snapshots" $ \o -> Snapshots <$> (o .: "nightly" >>= parseNightly) <*> (fmap IntMap.unions $ mapM parseLTS $ map snd $ filter (isLTS . fst) $ HM.toList o) where parseNightly t = case parseSnapName t of Left e -> fail $ show e Right (LTS _ _) -> fail "Unexpected LTS value" Right (Nightly d) -> return d isLTS = ("lts-" `T.isPrefixOf`) parseLTS = withText "LTS" $ \t -> case parseSnapName t of Left e -> fail $ show e Right (LTS x y) -> return $ IntMap.singleton x y Right (Nightly _) -> fail "Unexpected nightly value" -- | Load up a 'MiniBuildPlan', preferably from cache loadMiniBuildPlan :: (MonadIO m, MonadThrow m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, MonadBaseControl IO m, MonadCatch m) => SnapName -> m MiniBuildPlan loadMiniBuildPlan name = do path <- configMiniBuildPlanCache name let fp = toFilePath path taggedDecodeOrLoad fp $ liftM buildPlanFixes $ do bp <- loadBuildPlan name toMiniBuildPlan (siGhcVersion $ bpSystemInfo bp) (siCorePackages $ bpSystemInfo bp) (fmap goPP $ bpPackages bp) where goPP pp = ( ppVersion pp , pcFlagOverrides $ ppConstraints pp ) -- | Some hard-coded fixes for build plans, hopefully to be irrelevant over -- time. buildPlanFixes :: MiniBuildPlan -> MiniBuildPlan buildPlanFixes mbp = mbp { mbpPackages = Map.fromList $ map go $ Map.toList $ mbpPackages mbp } where go (name, mpi) = (name, mpi { mpiFlags = goF (packageNameString name) (mpiFlags mpi) }) goF "persistent-sqlite" = Map.insert $(mkFlagName "systemlib") False goF "yaml" = Map.insert $(mkFlagName "system-libyaml") False goF _ = id -- | Load the 'BuildPlan' for the given snapshot. Will load from a local copy -- if available, otherwise downloading from Github. loadBuildPlan :: (MonadIO m, MonadThrow m, MonadLogger m, MonadReader env m, HasHttpManager env, HasStackRoot env) => SnapName -> m BuildPlan loadBuildPlan name = do env <- ask let stackage = getStackRoot env file' <- parseRelFile $ T.unpack file let fp = stackage </> $(mkRelDir "build-plan") </> file' $logDebug $ "Decoding build plan from: " <> T.pack (toFilePath fp) eres <- liftIO $ decodeFileEither $ toFilePath fp case eres of Right bp -> return bp Left e -> do $logDebug $ "Decoding build plan from file failed: " <> T.pack (show e) createTree (parent fp) req <- parseUrl $ T.unpack url $logSticky $ "Downloading " <> renderSnapName name <> " build plan ..." $logDebug $ "Downloading build plan from: " <> url _ <- download req { checkStatus = handle404 } fp $logStickyDone $ "Downloaded " <> renderSnapName name <> " build plan." liftIO (decodeFileEither $ toFilePath fp) >>= either throwM return where file = renderSnapName name <> ".yaml" reponame = case name of LTS _ _ -> "lts-haskell" Nightly _ -> "stackage-nightly" url = rawGithubUrl "fpco" reponame "master" file handle404 (Status 404 _) _ _ = Just $ SomeException $ SnapshotNotFound name handle404 _ _ _ = Nothing -- | Find the set of @FlagName@s necessary to get the given -- @GenericPackageDescription@ to compile against the given @BuildPlan@. Will -- only modify non-manual flags, and will prefer default values for flags. -- Returns @Nothing@ if no combination exists. checkBuildPlan :: (MonadLogger m, MonadThrow m, MonadIO m, MonadReader env m, HasConfig env, MonadCatch m) => Map PackageName Version -- ^ locally available packages -> MiniBuildPlan -> GenericPackageDescription -> m (Either DepErrors (Map PackageName (Map FlagName Bool))) checkBuildPlan locals mbp gpd = do platform <- asks (configPlatform . getConfig) return $ loop platform flagOptions where packages = Map.union locals $ fmap mpiVersion $ mbpPackages mbp loop _ [] = assert False $ Left Map.empty loop platform (flags:rest) | Map.null errs = Right $ if Map.null flags then Map.empty else Map.singleton (packageName pkg) flags | null rest = Left errs | otherwise = loop platform rest where errs = checkDeps (packageName pkg) (packageDeps pkg) packages pkg = resolvePackage pkgConfig gpd pkgConfig = PackageConfig { packageConfigEnableTests = True , packageConfigEnableBenchmarks = True , packageConfigFlags = flags , packageConfigGhcVersion = ghcVersion , packageConfigPlatform = platform } ghcVersion = mbpGhcVersion mbp flagName' = fromCabalFlagName . flagName -- Avoid exponential complexity in flag combinations making us sad pandas. -- See: https://github.com/commercialhaskell/stack/issues/543 maxFlagOptions = 128 flagOptions = take maxFlagOptions $ map Map.fromList $ mapM getOptions $ genPackageFlags gpd getOptions f | flagManual f = [(flagName' f, flagDefault f)] | flagDefault f = [ (flagName' f, True) , (flagName' f, False) ] | otherwise = [ (flagName' f, False) , (flagName' f, True) ] -- | Checks if the given package dependencies can be satisfied by the given set -- of packages. Will fail if a package is either missing or has a version -- outside of the version range. checkDeps :: PackageName -- ^ package using dependencies, for constructing DepErrors -> Map PackageName VersionRange -> Map PackageName Version -> DepErrors checkDeps myName deps packages = Map.unionsWith mappend $ map go $ Map.toList deps where go :: (PackageName, VersionRange) -> DepErrors go (name, range) = case Map.lookup name packages of Nothing -> Map.singleton name DepError { deVersion = Nothing , deNeededBy = Map.singleton myName range } Just v | withinRange v range -> Map.empty | otherwise -> Map.singleton name DepError { deVersion = Just v , deNeededBy = Map.singleton myName range } type DepErrors = Map PackageName DepError data DepError = DepError { deVersion :: !(Maybe Version) , deNeededBy :: !(Map PackageName VersionRange) } instance Monoid DepError where mempty = DepError Nothing Map.empty mappend (DepError a x) (DepError b y) = DepError (maybe a Just b) (Map.unionWith C.intersectVersionRanges x y) -- | Find a snapshot and set of flags that is compatible with the given -- 'GenericPackageDescription'. Returns 'Nothing' if no such snapshot is found. findBuildPlan :: (MonadIO m, MonadCatch m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, MonadBaseControl IO m) => [GenericPackageDescription] -> [SnapName] -> m (Maybe (SnapName, Map PackageName (Map FlagName Bool))) findBuildPlan gpds0 = loop where loop [] = return Nothing loop (name:names') = do mbp <- loadMiniBuildPlan name $logInfo $ "Checking against build plan " <> renderSnapName name res <- mapM (checkBuildPlan localNames mbp) gpds0 case partitionEithers res of ([], flags) -> return $ Just (name, Map.unions flags) (errs, _) -> do $logInfo "" $logInfo "* Build plan did not match your requirements:" displayDepErrors $ Map.unionsWith mappend errs $logInfo "" loop names' localNames = Map.fromList $ map (fromCabalIdent . C.package . C.packageDescription) gpds0 fromCabalIdent (C.PackageIdentifier name version) = (fromCabalPackageName name, fromCabalVersion version) displayDepErrors :: MonadLogger m => DepErrors -> m () displayDepErrors errs = F.forM_ (Map.toList errs) $ \(depName, DepError mversion neededBy) -> do $logInfo $ T.concat [ " " , T.pack $ packageNameString depName , case mversion of Nothing -> " not found" Just version -> T.concat [ " version " , T.pack $ versionString version , " found" ] ] F.forM_ (Map.toList neededBy) $ \(user, range) -> $logInfo $ T.concat [ " - " , T.pack $ packageNameString user , " requires " , T.pack $ display range ] $logInfo "" shadowMiniBuildPlan :: MiniBuildPlan -> Set PackageName -> (MiniBuildPlan, Map PackageName MiniPackageInfo) shadowMiniBuildPlan (MiniBuildPlan ghc pkgs0) shadowed = (MiniBuildPlan ghc $ Map.fromList met, Map.fromList unmet) where pkgs1 = Map.difference pkgs0 $ Map.fromSet (\_ -> ()) shadowed depsMet = flip execState Map.empty $ mapM_ (check Set.empty) (Map.keys pkgs1) check visited name | name `Set.member` visited = error $ "shadowMiniBuildPlan: cycle detected, your MiniBuildPlan is broken: " ++ show (visited, name) | otherwise = do m <- get case Map.lookup name m of Just x -> return x Nothing -> case Map.lookup name pkgs1 of Nothing | name `Set.member` shadowed -> return False -- In this case, we have to assume that we're -- constructing a build plan on a different OS or -- architecture, and therefore different packages -- are being chosen. The common example of this is -- the Win32 package. | otherwise -> return True Just mpi -> do let visited' = Set.insert name visited ress <- mapM (check visited') (Set.toList $ mpiPackageDeps mpi) let res = and ress modify $ \m' -> Map.insert name res m' return res (met, unmet) = partitionEithers $ map toEither $ Map.toList pkgs1 toEither pair@(name, _) = wrapper pair where wrapper = case Map.lookup name depsMet of Just True -> Left Just False -> Right Nothing -> assert False Right parseCustomMiniBuildPlan :: (MonadIO m, MonadCatch m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, MonadBaseControl IO m) => Path Abs File -- ^ stack.yaml file location -> T.Text -> m MiniBuildPlan parseCustomMiniBuildPlan stackYamlFP url0 = do yamlFP <- getYamlFP url0 yamlBS <- liftIO $ S.readFile $ toFilePath yamlFP let yamlHash = S8.unpack $ B16.encode $ SHA256.hash yamlBS binaryFilename <- parseRelFile $ yamlHash ++ ".bin" customPlanDir <- getCustomPlanDir let binaryFP = customPlanDir </> $(mkRelDir "bin") </> binaryFilename taggedDecodeOrLoad (toFilePath binaryFP) $ do cs <- either throwM return $ decodeEither' yamlBS let addFlags :: PackageIdentifier -> (PackageName, (Version, Map FlagName Bool)) addFlags (PackageIdentifier name ver) = (name, (ver, fromMaybe Map.empty $ Map.lookup name $ csFlags cs)) toMiniBuildPlan (csGhcVersion cs) Map.empty (Map.fromList $ map addFlags $ Set.toList $ csPackages cs) where getCustomPlanDir = do root <- asks $ configStackRoot . getConfig return $ root </> $(mkRelDir "custom-plan") -- Get the path to the YAML file getYamlFP url = case parseUrl $ T.unpack url of Just req -> getYamlFPFromReq url req Nothing -> getYamlFPFromFile url getYamlFPFromReq url req = do let hashStr = S8.unpack $ B16.encode $ SHA256.hash $ encodeUtf8 url hashFP <- parseRelFile $ hashStr ++ ".yaml" customPlanDir <- getCustomPlanDir let cacheFP = customPlanDir </> $(mkRelDir "yaml") </> hashFP _ <- download req cacheFP return cacheFP getYamlFPFromFile url = do fp <- liftIO $ canonicalizePath $ toFilePath (parent stackYamlFP) FP.</> T.unpack (fromMaybe url $ T.stripPrefix "file://" url <|> T.stripPrefix "file:" url) parseAbsFile fp data CustomSnapshot = CustomSnapshot { csGhcVersion :: !Version , csPackages :: !(Set PackageIdentifier) , csFlags :: !(Map PackageName (Map FlagName Bool)) } instance FromJSON CustomSnapshot where parseJSON = withObject "CustomSnapshot" $ \o -> CustomSnapshot <$> ((o .: "compiler") >>= (\t -> maybe (fail $ "Invalid compiler: " ++ T.unpack t) return $ do cv <- parseCompilerVersion t case cv of GhcVersion v -> return v)) <*> o .: "packages" <*> o .:? "flags" .!= Map.empty
joozek78/stack
src/Stack/BuildPlan.hs
Haskell
bsd-3-clause
31,150
module Main where import System.Environment import System.Directory import Data.List import Lib main :: IO () main = getArgs >>= parseArgs parseArgs :: [String] -> IO () parseArgs [] = runDefault parseArgs [path] = processDirectory path parseArgs args = photoProcess args runDefault :: IO () runDefault = do putStrLn "No file specified. Running on directory." currentDirectory <- getCurrentDirectory imagePaths <- getFilesFromDirectory currentDirectory photoProcess imagePaths getFilesFromDirectory :: FilePath -> IO [FilePath] getFilesFromDirectory directory = do filesAndDirectories <- listDirectory directory return (filter fileIsMedia filesAndDirectories) processDirectory :: String -> IO () processDirectory path = do isDirectory <- doesDirectoryExist path if (isDirectory) then do putStrLn "You asked me to work on a directory." files <- getFilesFromDirectory path let relativePaths = map ((path ++ "/") ++) files absolutePaths <- mapM makeAbsolute relativePaths photoProcess absolutePaths else do photoProcess [path]
dominikmayer/photo-process
app/Main.hs
Haskell
bsd-3-clause
1,091
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Y.Buffer where import Control.Lens import Control.Lens.TH import Data.Default import Data.Group import Data.Monoid import qualified Data.Vector as V import qualified Y.String as S data Buffer = Buffer { _text :: S.YiString , _cursorPosition :: S.Position } deriving (Eq, Show) makeLenses ''Buffer instance Default Buffer where def = Buffer "" 0 data BufferUpdate = Composite (V.Vector BufferUpdate) | Insert S.YiString | Delete S.YiString | CursorFromTo S.Position S.Position | Nop deriving (Show, Eq) cursorUp :: Buffer -> BufferUpdate cursorUp (Buffer string cursor) = if y > 0 then CursorFromTo cursor (S.positionForCoords (pred y, 0) string) else Nop where (y, x) = S.coordsOfPosition cursor string instance Monoid BufferUpdate where mempty = Nop mappend x Nop = x mappend Nop x = x mappend (Insert s) (Insert t) = Insert (mappend s t) mappend (Composite xs) (Composite ys) = Composite (mappend xs ys) mappend x y = Composite (V.fromList [x, y]) instance Group BufferUpdate where invert Nop = Nop invert (Insert s) = Delete s invert (Delete s) = Insert s invert (CursorFromTo x y) = CursorFromTo y x invert (Composite xs) = Composite (V.reverse (fmap invert xs)) cursorDown :: Buffer -> BufferUpdate cursorDown (Buffer string cursor) = if y < lineCount then CursorFromTo cursor (S.positionForCoords (succ y, 0) string) else Nop where (y, x) = S.coordsOfPosition cursor string lineCount = S.countNewLines string cursorLeft :: Buffer -> BufferUpdate cursorLeft b | atSof b = Nop cursorLeft (Buffer _ cursor) = CursorFromTo cursor (pred cursor) cursorRight :: Buffer -> BufferUpdate cursorRight b | atEof b = Nop cursorRight (Buffer _ cursor) = CursorFromTo cursor (succ cursor) atSof :: Buffer -> Bool atSof (Buffer _ 0) = True atSof _ = False atEof :: Buffer -> Bool atEof (Buffer string cursor) = cursor == S.fromSize (S.length string)
ethercrow/y
src/Y/Buffer.hs
Haskell
bsd-3-clause
2,078
module Parse.Helpers where import Prelude hiding (until) import Control.Applicative ((<$>),(<*>),(<*)) import Control.Monad (guard, join) import Control.Monad.State (State) import Data.Char (isUpper) import qualified Data.Map as Map import qualified Language.GLSL.Parser as GLP import qualified Language.GLSL.Syntax as GLS import Text.Parsec hiding (newline, spaces, State) import Text.Parsec.Indent (indented, runIndent) import qualified Text.Parsec.Token as T import qualified AST.Declaration as Decl import qualified AST.Expression.General as E import qualified AST.Expression.Source as Source import qualified AST.Helpers as Help import qualified AST.Literal as L import qualified AST.Variable as Variable import qualified Reporting.Annotation as A import qualified Reporting.Error.Syntax as Syntax import qualified Reporting.Region as R reserveds :: [String] reserveds = [ "if", "then", "else" , "case", "of" , "let", "in" , "type" , "module", "where" , "import", "as", "hiding", "exposing" , "port", "export", "foreign" , "perform" , "deriving" ] -- ERROR HELP expecting = flip (<?>) -- SETUP type OpTable = Map.Map String (Int, Decl.Assoc) type SourceM = State SourcePos type IParser a = ParsecT String OpTable SourceM a iParse :: IParser a -> String -> Either ParseError a iParse parser source = iParseWithTable "" Map.empty parser source iParseWithTable :: SourceName -> OpTable -> IParser a -> String -> Either ParseError a iParseWithTable sourceName table aParser input = runIndent sourceName $ runParserT aParser table sourceName input -- VARIABLES var :: IParser String var = makeVar (letter <|> char '_') <?> "a name" lowVar :: IParser String lowVar = makeVar lower <?> "a lower case name" capVar :: IParser String capVar = makeVar upper <?> "an upper case name" qualifiedVar :: IParser String qualifiedVar = do vars <- many ((++) <$> capVar <*> string ".") (++) (concat vars) <$> lowVar rLabel :: IParser String rLabel = lowVar innerVarChar :: IParser Char innerVarChar = alphaNum <|> char '_' <|> char '\'' <?> "more letters in this name" makeVar :: IParser Char -> IParser String makeVar firstChar = do variable <- (:) <$> firstChar <*> many innerVarChar if variable `elem` reserveds then fail (Syntax.keyword variable) else return variable reserved :: String -> IParser String reserved word = expecting ("reserved word `" ++ word ++ "`") $ do string word notFollowedBy innerVarChar return word -- INFIX OPERATORS anyOp :: IParser String anyOp = betwixt '`' '`' qualifiedVar <|> symOp <?> "an infix operator like (+)" symOp :: IParser String symOp = do op <- many1 (satisfy Help.isSymbol) guard (op `notElem` [ "=", "..", "->", "--", "|", "\8594", ":" ]) case op of "." -> notFollowedBy lower >> return op _ -> return op -- COMMON SYMBOLS equals :: IParser String equals = string "=" <?> "=" rightArrow :: IParser String rightArrow = string "->" <|> string "\8594" <?> "->" leftArrow :: IParser String leftArrow = string "<-" <?> "<- for a record update" hasType :: IParser String hasType = string ":" <?> "the \"has type\" symbol ':'" commitIf check p = commit <|> try p where commit = try (lookAhead check) >> p -- SEPARATORS spaceySepBy1 :: IParser b -> IParser a -> IParser [a] spaceySepBy1 sep parser = do value <- parser (value:) <$> spaceyPrefixBy sep parser spaceyPrefixBy :: IParser sep -> IParser a -> IParser [a] spaceyPrefixBy sep parser = many (commitIf (whitespace >> sep) (padded sep >> parser)) comma :: IParser Char comma = char ',' <?> "a comma ','" commaSep1 :: IParser a -> IParser [a] commaSep1 = spaceySepBy1 comma commaSep :: IParser a -> IParser [a] commaSep = option [] . commaSep1 semiSep1 :: IParser a -> IParser [a] semiSep1 = spaceySepBy1 (char ';' <?> "a semicolon ';'") pipeSep1 :: IParser a -> IParser [a] pipeSep1 = spaceySepBy1 (char '|' <?> "a vertical bar '|'") consSep1 :: IParser a -> IParser [a] consSep1 = spaceySepBy1 (string "::" <?> "a cons operator '::'") dotSep1 :: IParser a -> IParser [a] dotSep1 p = (:) <$> p <*> many (try (char '.') >> p) spaceSep1 :: IParser a -> IParser [a] spaceSep1 p = (:) <$> p <*> spacePrefix p spacePrefix p = constrainedSpacePrefix p (\_ -> return ()) constrainedSpacePrefix parser constraint = many $ choice [ try (spacing >> lookAhead (oneOf "[({")) >> parser , try (spacing >> parser) ] where spacing = do n <- whitespace constraint n <?> Syntax.whitespace indented -- SURROUNDED BY followedBy a b = do x <- a b return x betwixt :: Char -> Char -> IParser a -> IParser a betwixt a b c = do char a out <- c char b <?> "a closing '" ++ [b] ++ "'" return out surround :: Char -> Char -> String -> IParser a -> IParser a surround a z name p = do char a v <- padded p char z <?> unwords ["a closing", name, show z] return v braces :: IParser a -> IParser a braces = surround '[' ']' "brace" parens :: IParser a -> IParser a parens = surround '(' ')' "paren" brackets :: IParser a -> IParser a brackets = surround '{' '}' "bracket" -- HELPERS FOR EXPRESSIONS getMyPosition :: IParser R.Position getMyPosition = R.fromSourcePos <$> getPosition addLocation :: IParser a -> IParser (A.Located a) addLocation expr = do (start, e, end) <- located expr return (A.at start end e) located :: IParser a -> IParser (R.Position, a, R.Position) located parser = do start <- getMyPosition value <- parser end <- getMyPosition return (start, value, end) accessible :: IParser Source.Expr -> IParser Source.Expr accessible exprParser = do start <- getMyPosition annotatedRootExpr@(A.A _ rootExpr) <- exprParser access <- optionMaybe (try dot <?> "a field access like .name") case access of Nothing -> return annotatedRootExpr Just _ -> accessible $ do v <- var end <- getMyPosition return . A.at start end $ case rootExpr of E.Var (Variable.Raw name@(c:_)) | isUpper c -> E.rawVar (name ++ '.' : v) _ -> E.Access annotatedRootExpr v dot :: IParser () dot = do char '.' notFollowedBy (char '.') -- WHITESPACE padded :: IParser a -> IParser a padded p = do whitespace out <- p whitespace return out spaces :: IParser String spaces = let space = string " " <|> multiComment <?> Syntax.whitespace in concat <$> many1 space forcedWS :: IParser String forcedWS = choice [ (++) <$> spaces <*> (concat <$> many nl_space) , concat <$> many1 nl_space ] where nl_space = try ((++) <$> (concat <$> many1 newline) <*> spaces) -- Just eats whitespace until the next meaningful character. dumbWhitespace :: IParser String dumbWhitespace = concat <$> many (spaces <|> newline) whitespace :: IParser String whitespace = option "" forcedWS freshLine :: IParser [[String]] freshLine = try (many1 newline >> many space_nl) <|> try (many1 space_nl) <?> Syntax.freshLine where space_nl = try $ spaces >> many1 newline newline :: IParser String newline = simpleNewline <|> lineComment <?> Syntax.newline simpleNewline :: IParser String simpleNewline = try (string "\r\n") <|> string "\n" lineComment :: IParser String lineComment = do try (string "--") comment <- anyUntil $ simpleNewline <|> (eof >> return "\n") return ("--" ++ comment) docComment :: IParser String docComment = do try (string "{-|") contents <- closeComment return (init (init contents)) multiComment :: IParser String multiComment = (++) <$> try (string "{-" <* notFollowedBy (string "|")) <*> closeComment closeComment :: IParser String closeComment = anyUntil $ choice $ [ try (string "-}") <?> "the end of a comment -}" , concat <$> sequence [ try (string "{-"), closeComment, closeComment ] ] -- ODD COMBINATORS failure msg = do inp <- getInput setInput ('x':inp) anyToken fail msg until :: IParser a -> IParser b -> IParser b until p end = go where go = end <|> (p >> go) anyUntil :: IParser String -> IParser String anyUntil end = go where go = end <|> (:) <$> anyChar <*> go ignoreUntil :: IParser a -> IParser (Maybe a) ignoreUntil end = go where ignore p = const () <$> p filler = choice [ try (ignore chr) <|> ignore str , ignore multiComment , ignore docComment , ignore anyChar ] go = choice [ Just <$> end , filler `until` choice [ const Nothing <$> eof, newline >> go ] ] onFreshLines :: (a -> b -> b) -> b -> IParser a -> IParser b onFreshLines insert init thing = go init where go values = do optionValue <- ignoreUntil thing case optionValue of Nothing -> return values Just v -> go (insert v values) withSource :: IParser a -> IParser (String, a) withSource p = do start <- getParserState result <- p endPos <- getPosition setParserState start raw <- anyUntilPos endPos return (raw, result) anyUntilPos :: SourcePos -> IParser String anyUntilPos pos = do currentPos <- getPosition if currentPos == pos then return [] else (:) <$> anyChar <*> anyUntilPos pos -- BASIC LANGUAGE LITERALS shader :: IParser (String, L.GLShaderTipe) shader = do try (string "[glsl|") rawSrc <- closeShader id case glSource rawSrc of Left err -> parserFail . show $ err Right tipe -> return (rawSrc, tipe) closeShader :: (String -> a) -> IParser a closeShader builder = choice [ do try (string "|]") return (builder "") , do c <- anyChar closeShader (builder . (c:)) ] glSource :: String -> Either ParseError L.GLShaderTipe glSource src = case GLP.parse src of Left e -> Left e Right (GLS.TranslationUnit decls) -> map extractGLinputs decls |> join |> foldr addGLinput emptyDecls |> Right where (|>) = flip ($) emptyDecls = L.GLShaderTipe Map.empty Map.empty Map.empty addGLinput (qual,tipe,name) glDecls = case qual of GLS.Attribute -> glDecls { L.attribute = Map.insert name tipe $ L.attribute glDecls } GLS.Uniform -> glDecls { L.uniform = Map.insert name tipe $ L.uniform glDecls } GLS.Varying -> glDecls { L.varying = Map.insert name tipe $ L.varying glDecls } _ -> error "Should never happen due to below filter" extractGLinputs decl = case decl of GLS.Declaration (GLS.InitDeclaration (GLS.TypeDeclarator (GLS.FullType (Just (GLS.TypeQualSto qual)) (GLS.TypeSpec _prec (GLS.TypeSpecNoPrecision tipe _mexpr1)))) [GLS.InitDecl name _mexpr2 _mexpr3] ) -> case elem qual [GLS.Attribute, GLS.Varying, GLS.Uniform] of False -> [] True -> case tipe of GLS.Int -> return (qual, L.Int,name) GLS.Float -> return (qual, L.Float,name) GLS.Vec2 -> return (qual, L.V2,name) GLS.Vec3 -> return (qual, L.V3,name) GLS.Vec4 -> return (qual, L.V4,name) GLS.Mat4 -> return (qual, L.M4,name) GLS.Sampler2D -> return (qual, L.Texture,name) _ -> [] _ -> [] str :: IParser String str = expecting "a string" $ do s <- choice [ multiStr, singleStr ] processAs T.stringLiteral . sandwich '\"' $ concat s where rawString quote insides = quote >> manyTill insides quote multiStr = rawString (try (string "\"\"\"")) multilineStringChar singleStr = rawString (char '"') stringChar stringChar :: IParser String stringChar = choice [ newlineChar, escaped '\"', (:[]) <$> satisfy (/= '\"') ] multilineStringChar :: IParser String multilineStringChar = do noEnd choice [ newlineChar, escaped '\"', expandQuote <$> anyChar ] where noEnd = notFollowedBy (string "\"\"\"") expandQuote c = if c == '\"' then "\\\"" else [c] newlineChar :: IParser String newlineChar = choice [ char '\n' >> return "\\n" , char '\r' >> return "\\r" ] sandwich :: Char -> String -> String sandwich delim s = delim : s ++ [delim] escaped :: Char -> IParser String escaped delim = try $ do char '\\' c <- char '\\' <|> char delim return ['\\', c] chr :: IParser Char chr = betwixt '\'' '\'' character <?> "a character" where nonQuote = satisfy (/='\'') character = do c <- choice [ escaped '\'' , (:) <$> char '\\' <*> many1 nonQuote , (:[]) <$> nonQuote ] processAs T.charLiteral $ sandwich '\'' c processAs :: (T.GenTokenParser String u SourceM -> IParser a) -> String -> IParser a processAs processor s = calloutParser s (processor lexer) where calloutParser :: String -> IParser a -> IParser a calloutParser inp p = either (fail . show) return (iParse p inp) lexer :: T.GenTokenParser String u SourceM lexer = T.makeTokenParser elmDef -- I don't know how many of these are necessary for charLiteral/stringLiteral elmDef :: T.GenLanguageDef String u SourceM elmDef = T.LanguageDef { T.commentStart = "{-" , T.commentEnd = "-}" , T.commentLine = "--" , T.nestedComments = True , T.identStart = undefined , T.identLetter = undefined , T.opStart = undefined , T.opLetter = undefined , T.reservedNames = reserveds , T.reservedOpNames = [":", "->", "<-", "|"] , T.caseSensitive = True }
johnpmayer/elm-compiler
src/Parse/Helpers.hs
Haskell
bsd-3-clause
14,360
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -Wall #-} module Dhall.Import.Types where import Control.Exception (Exception) import Control.Monad.Trans.State.Strict (StateT) import Data.ByteString (ByteString) import Data.CaseInsensitive (CI) import Data.Dynamic import Data.HashMap.Strict (HashMap) import Data.List.NonEmpty (NonEmpty) import Data.Void (Void) import Dhall.Context (Context) import Dhall.Core ( Expr , Import (..) , ReifiedNormalizer (..) , URL ) import Dhall.Map (Map) import Dhall.Parser (Src) import Lens.Family (LensLike') import Prettyprinter (Pretty (..)) #ifdef WITH_HTTP import qualified Dhall.Import.Manager #endif import qualified Data.Text import qualified Dhall.Context import qualified Dhall.Map as Map import qualified Dhall.Substitution -- | A fully \"chained\" import, i.e. if it contains a relative path that path -- is relative to the current directory. If it is a remote import with headers -- those are well-typed (either of type `List { header : Text, value Text}` or -- `List { mapKey : Text, mapValue Text})` and in normal form. These -- invariants are preserved by the API exposed by @Dhall.Import@. newtype Chained = Chained { chainedImport :: Import -- ^ The underlying import } deriving (Eq, Ord) instance Pretty Chained where pretty (Chained import_) = pretty import_ -- | An import that has been fully interpeted newtype ImportSemantics = ImportSemantics { importSemantics :: Expr Void Void -- ^ The fully resolved import, typechecked and beta-normal. } -- | `parent` imports (i.e. depends on) `child` data Depends = Depends { parent :: Chained, child :: Chained } {-| This enables or disables the semantic cache for imports protected by integrity checks -} data SemanticCacheMode = IgnoreSemanticCache | UseSemanticCache deriving (Eq) -- | Shared state for HTTP requests type Manager = #ifdef WITH_HTTP Dhall.Import.Manager.Manager #else () #endif -- | The default HTTP 'Manager' defaultNewManager :: IO Manager defaultNewManager = #ifdef WITH_HTTP Dhall.Import.Manager.defaultNewManager #else pure () #endif -- | HTTP headers type HTTPHeader = (CI ByteString, ByteString) -- | A map of site origin -> HTTP headers type OriginHeaders = HashMap Data.Text.Text [HTTPHeader] {-| Used internally to track whether or not we've already warned the user about caching issues -} data CacheWarning = CacheNotWarned | CacheWarned -- | State threaded throughout the import process data Status = Status { _stack :: NonEmpty Chained -- ^ Stack of `Import`s that we've imported along the way to get to the -- current point , _graph :: [Depends] -- ^ Graph of all the imports visited so far, represented by a list of -- import dependencies. , _cache :: Map Chained ImportSemantics -- ^ Cache of imported expressions with their node id in order to avoid -- importing the same expression twice with different values , _newManager :: IO Manager , _manager :: Maybe Manager -- ^ Used to cache the `Dhall.Import.Manager.Manager` when making multiple -- requests , _loadOriginHeaders :: StateT Status IO OriginHeaders -- ^ Load the origin headers from environment or configuration file. -- After loading once, further evaluations return the cached version. , _remote :: URL -> StateT Status IO Data.Text.Text -- ^ The remote resolver, fetches the content at the given URL. , _substitutions :: Dhall.Substitution.Substitutions Src Void , _normalizer :: Maybe (ReifiedNormalizer Void) , _startingContext :: Context (Expr Src Void) , _semanticCacheMode :: SemanticCacheMode , _cacheWarning :: CacheWarning -- ^ Records whether or not we already warned the user about issues with -- cache directory } -- | Initial `Status`, parameterised over the HTTP 'Manager', -- the origin headers and the remote resolver, -- importing relative to the given root import. emptyStatusWith :: IO Manager -> StateT Status IO OriginHeaders -> (URL -> StateT Status IO Data.Text.Text) -> Import -> Status emptyStatusWith _newManager _loadOriginHeaders _remote rootImport = Status {..} where _stack = pure (Chained rootImport) _graph = [] _cache = Map.empty _manager = Nothing _substitutions = Dhall.Substitution.empty _normalizer = Nothing _startingContext = Dhall.Context.empty _semanticCacheMode = UseSemanticCache _cacheWarning = CacheNotWarned -- | Lens from a `Status` to its `_stack` field stack :: Functor f => LensLike' f Status (NonEmpty Chained) stack k s = fmap (\x -> s { _stack = x }) (k (_stack s)) -- | Lens from a `Status` to its `_graph` field graph :: Functor f => LensLike' f Status [Depends] graph k s = fmap (\x -> s { _graph = x }) (k (_graph s)) -- | Lens from a `Status` to its `_cache` field cache :: Functor f => LensLike' f Status (Map Chained ImportSemantics) cache k s = fmap (\x -> s { _cache = x }) (k (_cache s)) -- | Lens from a `Status` to its `_remote` field remote :: Functor f => LensLike' f Status (URL -> StateT Status IO Data.Text.Text) remote k s = fmap (\x -> s { _remote = x }) (k (_remote s)) -- | Lens from a `Status` to its `_substitutions` field substitutions :: Functor f => LensLike' f Status (Dhall.Substitution.Substitutions Src Void) substitutions k s = fmap (\x -> s { _substitutions = x }) (k (_substitutions s)) -- | Lens from a `Status` to its `_normalizer` field normalizer :: Functor f => LensLike' f Status (Maybe (ReifiedNormalizer Void)) normalizer k s = fmap (\x -> s {_normalizer = x}) (k (_normalizer s)) -- | Lens from a `Status` to its `_startingContext` field startingContext :: Functor f => LensLike' f Status (Context (Expr Src Void)) startingContext k s = fmap (\x -> s { _startingContext = x }) (k (_startingContext s)) -- | Lens from a `Status` to its `_cacheWarning` field cacheWarning :: Functor f => LensLike' f Status CacheWarning cacheWarning k s = fmap (\x -> s { _cacheWarning = x }) (k (_cacheWarning s)) {-| This exception indicates that there was an internal error in Dhall's import-related logic This exception indicates that an invalid `Dhall.Syntax.Type` was provided to the `Dhall.input` function -} data InternalError = InternalError deriving (Typeable) instance Show InternalError where show InternalError = unlines [ _ERROR <> ": Compiler bug " , " " , "Explanation: This error message means that there is a bug in the Dhall compiler." , "You didn't do anything wrong, but if you would like to see this problem fixed " , "then you should report the bug at: " , " " , "https://github.com/dhall-lang/dhall-haskell/issues " , " " , "Please include the following text in your bug report: " , " " , "``` " , "Header extraction failed even though the header type-checked " , "``` " ] where _ERROR :: String _ERROR = "\ESC[1;31mError\ESC[0m" instance Exception InternalError -- | Wrapper around `Network.HTTP.Client.HttpException`s with a prettier `Show` -- instance -- -- In order to keep the library API constant even when the @with-http@ Cabal -- flag is disabled the pretty error message is pre-rendered and the real -- 'Network.HTTP.Client.HttpException' is stored in a 'Dynamic' data PrettyHttpException = PrettyHttpException String Dynamic deriving (Typeable) instance Exception PrettyHttpException instance Show PrettyHttpException where show (PrettyHttpException msg _) = msg
Gabriel439/Haskell-Dhall-Library
dhall/src/Dhall/Import/Types.hs
Haskell
bsd-3-clause
8,562
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 TcInstDecls: Typechecking instance declarations -} {-# LANGUAGE CPP #-} module TcInstDcls ( tcInstDecls1, tcInstDecls2 ) where #include "HsVersions.h" import HsSyn import TcBinds import TcTyClsDecls import TcClassDcl( tcClassDecl2, HsSigFun, lookupHsSig, mkHsSigFun, findMethodBind, instantiateMethod ) import TcPat ( TcIdSigInfo, addInlinePrags, completeIdSigPolyId, lookupPragEnv, emptyPragEnv ) import TcRnMonad import TcValidity import TcMType import TcType import BuildTyCl import Inst import InstEnv import FamInst import FamInstEnv import TcDeriv import TcEnv import TcHsType import TcUnify import Coercion ( pprCoAxiom {- , isReflCo, mkSymCo, mkSubCo -} ) import MkCore ( nO_METHOD_BINDING_ERROR_ID ) import Type import TcEvidence import TyCon import CoAxiom import DataCon import Class import Var import VarEnv import VarSet import PrelNames ( typeableClassName, genericClassNames ) -- , knownNatClassName, knownSymbolClassName ) import Bag import BasicTypes import DynFlags import ErrUtils import FastString import HscTypes ( isHsBoot ) import Id import MkId import Name import NameSet import Outputable import SrcLoc import Util import BooleanFormula ( isUnsatisfied, pprBooleanFormulaNice ) import Control.Monad import Maybes import Data.List ( mapAccumL, partition ) {- Typechecking instance declarations is done in two passes. The first pass, made by @tcInstDecls1@, collects information to be used in the second pass. This pre-processed info includes the as-yet-unprocessed bindings inside the instance declaration. These are type-checked in the second pass, when the class-instance envs and GVE contain all the info from all the instance and value decls. Indeed that's the reason we need two passes over the instance decls. Note [How instance declarations are translated] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is how we translate instance declarations into Core Running example: class C a where op1, op2 :: Ix b => a -> b -> b op2 = <dm-rhs> instance C a => C [a] {-# INLINE [2] op1 #-} op1 = <rhs> ===> -- Method selectors op1,op2 :: forall a. C a => forall b. Ix b => a -> b -> b op1 = ... op2 = ... -- Default methods get the 'self' dictionary as argument -- so they can call other methods at the same type -- Default methods get the same type as their method selector $dmop2 :: forall a. C a => forall b. Ix b => a -> b -> b $dmop2 = /\a. \(d:C a). /\b. \(d2: Ix b). <dm-rhs> -- NB: type variables 'a' and 'b' are *both* in scope in <dm-rhs> -- Note [Tricky type variable scoping] -- A top-level definition for each instance method -- Here op1_i, op2_i are the "instance method Ids" -- The INLINE pragma comes from the user pragma {-# INLINE [2] op1_i #-} -- From the instance decl bindings op1_i, op2_i :: forall a. C a => forall b. Ix b => [a] -> b -> b op1_i = /\a. \(d:C a). let this :: C [a] this = df_i a d -- Note [Subtle interaction of recursion and overlap] local_op1 :: forall b. Ix b => [a] -> b -> b local_op1 = <rhs> -- Source code; run the type checker on this -- NB: Type variable 'a' (but not 'b') is in scope in <rhs> -- Note [Tricky type variable scoping] in local_op1 a d op2_i = /\a \d:C a. $dmop2 [a] (df_i a d) -- The dictionary function itself {-# NOINLINE CONLIKE df_i #-} -- Never inline dictionary functions df_i :: forall a. C a -> C [a] df_i = /\a. \d:C a. MkC (op1_i a d) (op2_i a d) -- But see Note [Default methods in instances] -- We can't apply the type checker to the default-method call -- Use a RULE to short-circuit applications of the class ops {-# RULE "op1@C[a]" forall a, d:C a. op1 [a] (df_i d) = op1_i a d #-} Note [Instances and loop breakers] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Note that df_i may be mutually recursive with both op1_i and op2_i. It's crucial that df_i is not chosen as the loop breaker, even though op1_i has a (user-specified) INLINE pragma. * Instead the idea is to inline df_i into op1_i, which may then select methods from the MkC record, and thereby break the recursion with df_i, leaving a *self*-recurisve op1_i. (If op1_i doesn't call op at the same type, it won't mention df_i, so there won't be recursion in the first place.) * If op1_i is marked INLINE by the user there's a danger that we won't inline df_i in it, and that in turn means that (since it'll be a loop-breaker because df_i isn't), op1_i will ironically never be inlined. But this is OK: the recursion breaking happens by way of a RULE (the magic ClassOp rule above), and RULES work inside InlineRule unfoldings. See Note [RULEs enabled in SimplGently] in SimplUtils Note [ClassOp/DFun selection] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ One thing we see a lot is stuff like op2 (df d1 d2) where 'op2' is a ClassOp and 'df' is DFun. Now, we could inline *both* 'op2' and 'df' to get case (MkD ($cop1 d1 d2) ($cop2 d1 d2) ... of MkD _ op2 _ _ _ -> op2 And that will reduce to ($cop2 d1 d2) which is what we wanted. But it's tricky to make this work in practice, because it requires us to inline both 'op2' and 'df'. But neither is keen to inline without having seen the other's result; and it's very easy to get code bloat (from the big intermediate) if you inline a bit too much. Instead we use a cunning trick. * We arrange that 'df' and 'op2' NEVER inline. * We arrange that 'df' is ALWAYS defined in the sylised form df d1 d2 = MkD ($cop1 d1 d2) ($cop2 d1 d2) ... * We give 'df' a magical unfolding (DFunUnfolding [$cop1, $cop2, ..]) that lists its methods. * We make CoreUnfold.exprIsConApp_maybe spot a DFunUnfolding and return a suitable constructor application -- inlining df "on the fly" as it were. * ClassOp rules: We give the ClassOp 'op2' a BuiltinRule that extracts the right piece iff its argument satisfies exprIsConApp_maybe. This is done in MkId mkDictSelId * We make 'df' CONLIKE, so that shared uses still match; eg let d = df d1 d2 in ...(op2 d)...(op1 d)... Note [Single-method classes] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If the class has just one method (or, more accurately, just one element of {superclasses + methods}), then we use a different strategy. class C a where op :: a -> a instance C a => C [a] where op = <blah> We translate the class decl into a newtype, which just gives a top-level axiom. The "constructor" MkC expands to a cast, as does the class-op selector. axiom Co:C a :: C a ~ (a->a) op :: forall a. C a -> (a -> a) op a d = d |> (Co:C a) MkC :: forall a. (a->a) -> C a MkC = /\a.\op. op |> (sym Co:C a) The clever RULE stuff doesn't work now, because ($df a d) isn't a constructor application, so exprIsConApp_maybe won't return Just <blah>. Instead, we simply rely on the fact that casts are cheap: $df :: forall a. C a => C [a] {-# INLINE df #-} -- NB: INLINE this $df = /\a. \d. MkC [a] ($cop_list a d) = $cop_list |> forall a. C a -> (sym (Co:C [a])) $cop_list :: forall a. C a => [a] -> [a] $cop_list = <blah> So if we see (op ($df a d)) we'll inline 'op' and '$df', since both are simply casts, and good things happen. Why do we use this different strategy? Because otherwise we end up with non-inlined dictionaries that look like $df = $cop |> blah which adds an extra indirection to every use, which seems stupid. See Trac #4138 for an example (although the regression reported there wasn't due to the indirection). There is an awkward wrinkle though: we want to be very careful when we have instance C a => C [a] where {-# INLINE op #-} op = ... then we'll get an INLINE pragma on $cop_list but it's important that $cop_list only inlines when it's applied to *two* arguments (the dictionary and the list argument). So we must not eta-expand $df above. We ensure that this doesn't happen by putting an INLINE pragma on the dfun itself; after all, it ends up being just a cast. There is one more dark corner to the INLINE story, even more deeply buried. Consider this (Trac #3772): class DeepSeq a => C a where gen :: Int -> a instance C a => C [a] where gen n = ... class DeepSeq a where deepSeq :: a -> b -> b instance DeepSeq a => DeepSeq [a] where {-# INLINE deepSeq #-} deepSeq xs b = foldr deepSeq b xs That gives rise to these defns: $cdeepSeq :: DeepSeq a -> [a] -> b -> b -- User INLINE( 3 args )! $cdeepSeq a (d:DS a) b (x:[a]) (y:b) = ... $fDeepSeq[] :: DeepSeq a -> DeepSeq [a] -- DFun (with auto INLINE pragma) $fDeepSeq[] a d = $cdeepSeq a d |> blah $cp1 a d :: C a => DeepSep [a] -- We don't want to eta-expand this, lest -- $cdeepSeq gets inlined in it! $cp1 a d = $fDeepSep[] a (scsel a d) $fC[] :: C a => C [a] -- Ordinary DFun $fC[] a d = MkC ($cp1 a d) ($cgen a d) Here $cp1 is the code that generates the superclass for C [a]. The issue is this: we must not eta-expand $cp1 either, or else $fDeepSeq[] and then $cdeepSeq will inline there, which is definitely wrong. Like on the dfun, we solve this by adding an INLINE pragma to $cp1. Note [Subtle interaction of recursion and overlap] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this class C a where { op1,op2 :: a -> a } instance C a => C [a] where op1 x = op2 x ++ op2 x op2 x = ... instance C [Int] where ... When type-checking the C [a] instance, we need a C [a] dictionary (for the call of op2). If we look up in the instance environment, we find an overlap. And in *general* the right thing is to complain (see Note [Overlapping instances] in InstEnv). But in *this* case it's wrong to complain, because we just want to delegate to the op2 of this same instance. Why is this justified? Because we generate a (C [a]) constraint in a context in which 'a' cannot be instantiated to anything that matches other overlapping instances, or else we would not be executing this version of op1 in the first place. It might even be a bit disguised: nullFail :: C [a] => [a] -> [a] nullFail x = op2 x ++ op2 x instance C a => C [a] where op1 x = nullFail x Precisely this is used in package 'regex-base', module Context.hs. See the overlapping instances for RegexContext, and the fact that they call 'nullFail' just like the example above. The DoCon package also does the same thing; it shows up in module Fraction.hs. Conclusion: when typechecking the methods in a C [a] instance, we want to treat the 'a' as an *existential* type variable, in the sense described by Note [Binding when looking up instances]. That is why isOverlappableTyVar responds True to an InstSkol, which is the kind of skolem we use in tcInstDecl2. Note [Tricky type variable scoping] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In our example class C a where op1, op2 :: Ix b => a -> b -> b op2 = <dm-rhs> instance C a => C [a] {-# INLINE [2] op1 #-} op1 = <rhs> note that 'a' and 'b' are *both* in scope in <dm-rhs>, but only 'a' is in scope in <rhs>. In particular, we must make sure that 'b' is in scope when typechecking <dm-rhs>. This is achieved by subFunTys, which brings appropriate tyvars into scope. This happens for both <dm-rhs> and for <rhs>, but that doesn't matter: the *renamer* will have complained if 'b' is mentioned in <rhs>. ************************************************************************ * * \subsection{Extracting instance decls} * * ************************************************************************ Gather up the instance declarations from their various sources -} tcInstDecls1 -- Deal with both source-code and imported instance decls :: [TyClGroup Name] -- For deriving stuff -> [LInstDecl Name] -- Source code instance decls -> [LDerivDecl Name] -- Source code stand-alone deriving decls -> TcM (TcGblEnv, -- The full inst env [InstInfo Name], -- Source-code instance decls to process; -- contains all dfuns for this module HsValBinds Name) -- Supporting bindings for derived instances tcInstDecls1 tycl_decls inst_decls deriv_decls = checkNoErrs $ do { -- Stop if addInstInfos etc discovers any errors -- (they recover, so that we get more than one error each -- round) -- Do class and family instance declarations ; stuff <- mapAndRecoverM tcLocalInstDecl inst_decls ; let (local_infos_s, fam_insts_s, datafam_deriv_infos) = unzip3 stuff fam_insts = concat fam_insts_s local_infos' = concat local_infos_s -- Handwritten instances of the poly-kinded Typeable class are -- forbidden, so we handle those separately (typeable_instances, local_infos) = partition bad_typeable_instance local_infos' ; addClsInsts local_infos $ addFamInsts fam_insts $ do { -- Compute instances from "deriving" clauses; -- This stuff computes a context for the derived instance -- decl, so it needs to know about all the instances possible -- NB: class instance declarations can contain derivings as -- part of associated data type declarations failIfErrsM -- If the addInsts stuff gave any errors, don't -- try the deriving stuff, because that may give -- more errors still ; traceTc "tcDeriving" Outputable.empty ; th_stage <- getStage -- See Note [Deriving inside TH brackets ] ; (gbl_env, deriv_inst_info, deriv_binds) <- if isBrackStage th_stage then do { gbl_env <- getGblEnv ; return (gbl_env, emptyBag, emptyValBindsOut) } else do { data_deriv_infos <- mkDerivInfos tycl_decls ; let deriv_infos = concat datafam_deriv_infos ++ data_deriv_infos ; tcDeriving deriv_infos deriv_decls } -- Fail if there are any handwritten instance of poly-kinded Typeable ; mapM_ typeable_err typeable_instances -- Check that if the module is compiled with -XSafe, there are no -- hand written instances of old Typeable as then unsafe casts could be -- performed. Derived instances are OK. ; dflags <- getDynFlags ; when (safeLanguageOn dflags) $ forM_ local_infos $ \x -> case x of _ | genInstCheck x -> addErrAt (getSrcSpan $ iSpec x) (genInstErr x) _ -> return () -- As above but for Safe Inference mode. ; when (safeInferOn dflags) $ forM_ local_infos $ \x -> case x of _ | genInstCheck x -> recordUnsafeInfer emptyBag _ -> return () ; return ( gbl_env , bagToList deriv_inst_info ++ local_infos , deriv_binds ) }} where -- Separate the Typeable instances from the rest bad_typeable_instance i = typeableClassName == is_cls_nm (iSpec i) -- Check for hand-written Generic instances (disallowed in Safe Haskell) genInstCheck ty = is_cls_nm (iSpec ty) `elem` genericClassNames genInstErr i = hang (ptext (sLit $ "Generic instances can only be " ++ "derived in Safe Haskell.") $+$ ptext (sLit "Replace the following instance:")) 2 (pprInstanceHdr (iSpec i)) -- Report an error or a warning for a `Typeable` instances. -- If we are working on an .hs-boot file, we just report a warning, -- and ignore the instance. We do this, to give users a chance to fix -- their code. typeable_err i = setSrcSpan (getSrcSpan (iSpec i)) $ do env <- getGblEnv if isHsBoot (tcg_src env) then do warn <- woptM Opt_WarnDerivingTypeable when warn $ addWarnTc $ vcat [ ptext (sLit "`Typeable` instances in .hs-boot files are ignored.") , ptext (sLit "This warning will become an error in future versions of the compiler.") ] else addErrTc $ ptext (sLit "Class `Typeable` does not support user-specified instances.") addClsInsts :: [InstInfo Name] -> TcM a -> TcM a addClsInsts infos thing_inside = tcExtendLocalInstEnv (map iSpec infos) thing_inside addFamInsts :: [FamInst] -> TcM a -> TcM a -- Extend (a) the family instance envt -- (b) the type envt with stuff from data type decls addFamInsts fam_insts thing_inside = tcExtendLocalFamInstEnv fam_insts $ tcExtendGlobalEnv things $ do { traceTc "addFamInsts" (pprFamInsts fam_insts) ; tcg_env <- tcAddImplicits things ; setGblEnv tcg_env thing_inside } where axioms = map (toBranchedAxiom . famInstAxiom) fam_insts tycons = famInstsRepTyCons fam_insts things = map ATyCon tycons ++ map ACoAxiom axioms {- Note [Deriving inside TH brackets] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Given a declaration bracket [d| data T = A | B deriving( Show ) |] there is really no point in generating the derived code for deriving( Show) and then type-checking it. This will happen at the call site anyway, and the type check should never fail! Moreover (Trac #6005) the scoping of the generated code inside the bracket does not seem to work out. The easy solution is simply not to generate the derived instances at all. (A less brutal solution would be to generate them with no bindings.) This will become moot when we shift to the new TH plan, so the brutal solution will do. -} tcLocalInstDecl :: LInstDecl Name -> TcM ([InstInfo Name], [FamInst], [DerivInfo]) -- A source-file instance declaration -- Type-check all the stuff before the "where" -- -- We check for respectable instance type, and context tcLocalInstDecl (L loc (TyFamInstD { tfid_inst = decl })) = do { fam_inst <- tcTyFamInstDecl Nothing (L loc decl) ; return ([], [fam_inst], []) } tcLocalInstDecl (L loc (DataFamInstD { dfid_inst = decl })) = do { (fam_inst, m_deriv_info) <- tcDataFamInstDecl Nothing (L loc decl) ; return ([], [fam_inst], maybeToList m_deriv_info) } tcLocalInstDecl (L loc (ClsInstD { cid_inst = decl })) = do { (insts, fam_insts, deriv_infos) <- tcClsInstDecl (L loc decl) ; return (insts, fam_insts, deriv_infos) } tcClsInstDecl :: LClsInstDecl Name -> TcM ([InstInfo Name], [FamInst], [DerivInfo]) -- the returned DerivInfos are for any associated data families tcClsInstDecl (L loc (ClsInstDecl { cid_poly_ty = poly_ty, cid_binds = binds , cid_sigs = uprags, cid_tyfam_insts = ats , cid_overlap_mode = overlap_mode , cid_datafam_insts = adts })) = setSrcSpan loc $ addErrCtxt (instDeclCtxt1 poly_ty) $ do { is_boot <- tcIsHsBootOrSig ; checkTc (not is_boot || (isEmptyLHsBinds binds && null uprags)) badBootDeclErr ; (tyvars, theta, clas, inst_tys) <- tcHsInstHead InstDeclCtxt poly_ty ; let mini_env = mkVarEnv (classTyVars clas `zip` inst_tys) mini_subst = mkTvSubst (mkInScopeSet (mkVarSet tyvars)) mini_env mb_info = Just (clas, mini_env) -- Next, process any associated types. ; traceTc "tcLocalInstDecl" (ppr poly_ty) ; tyfam_insts0 <- tcExtendTyVarEnv tyvars $ mapAndRecoverM (tcTyFamInstDecl mb_info) ats ; datafam_stuff <- tcExtendTyVarEnv tyvars $ mapAndRecoverM (tcDataFamInstDecl mb_info) adts ; let (datafam_insts, m_deriv_infos) = unzip datafam_stuff deriv_infos = catMaybes m_deriv_infos -- Check for missing associated types and build them -- from their defaults (if available) ; let defined_ats = mkNameSet (map (tyFamInstDeclName . unLoc) ats) `unionNameSet` mkNameSet (map (unLoc . dfid_tycon . unLoc) adts) ; tyfam_insts1 <- mapM (tcATDefault loc mini_subst defined_ats) (classATItems clas) -- Finally, construct the Core representation of the instance. -- (This no longer includes the associated types.) ; dfun_name <- newDFunName clas inst_tys (getLoc poly_ty) -- Dfun location is that of instance *header* ; ispec <- newClsInst (fmap unLoc overlap_mode) dfun_name tyvars theta clas inst_tys ; let inst_info = InstInfo { iSpec = ispec , iBinds = InstBindings { ib_binds = binds , ib_tyvars = map Var.varName tyvars -- Scope over bindings , ib_pragmas = uprags , ib_extensions = [] , ib_derived = False } } ; return ( [inst_info], tyfam_insts0 ++ concat tyfam_insts1 ++ datafam_insts , deriv_infos ) } tcATDefault :: SrcSpan -> TvSubst -> NameSet -> ClassATItem -> TcM [FamInst] -- ^ Construct default instances for any associated types that -- aren't given a user definition -- Returns [] or singleton tcATDefault loc inst_subst defined_ats (ATI fam_tc defs) -- User supplied instances ==> everything is OK | tyConName fam_tc `elemNameSet` defined_ats = return [] -- No user instance, have defaults ==> instatiate them -- Example: class C a where { type F a b :: *; type F a b = () } -- instance C [x] -- Then we want to generate the decl: type F [x] b = () | Just (rhs_ty, _loc) <- defs = do { let (subst', pat_tys') = mapAccumL subst_tv inst_subst (tyConTyVars fam_tc) rhs' = substTy subst' rhs_ty tv_set' = tyVarsOfTypes pat_tys' tvs' = varSetElemsKvsFirst tv_set' ; rep_tc_name <- newFamInstTyConName (L loc (tyConName fam_tc)) pat_tys' ; let axiom = mkSingleCoAxiom Nominal rep_tc_name tvs' fam_tc pat_tys' rhs' -- NB: no validity check. We check validity of default instances -- in the class definition. Because type instance arguments cannot -- be type family applications and cannot be polytypes, the -- validity check is redundant. ; traceTc "mk_deflt_at_instance" (vcat [ ppr fam_tc, ppr rhs_ty , pprCoAxiom axiom ]) ; fam_inst <- ASSERT( tyVarsOfType rhs' `subVarSet` tv_set' ) newFamInst SynFamilyInst axiom ; return [fam_inst] } -- No defaults ==> generate a warning | otherwise -- defs = Nothing = do { warnMissingMethodOrAT "associated type" (tyConName fam_tc) ; return [] } where subst_tv subst tc_tv | Just ty <- lookupVarEnv (getTvSubstEnv subst) tc_tv = (subst, ty) | otherwise = (extendTvSubst subst tc_tv ty', ty') where ty' = mkTyVarTy (updateTyVarKind (substTy subst) tc_tv) {- ************************************************************************ * * Type checking family instances * * ************************************************************************ Family instances are somewhat of a hybrid. They are processed together with class instance heads, but can contain data constructors and hence they share a lot of kinding and type checking code with ordinary algebraic data types (and GADTs). -} tcFamInstDeclCombined :: Maybe ClsInfo -> Located Name -> TcM TyCon tcFamInstDeclCombined mb_clsinfo fam_tc_lname = do { -- Type family instances require -XTypeFamilies -- and can't (currently) be in an hs-boot file ; traceTc "tcFamInstDecl" (ppr fam_tc_lname) ; type_families <- xoptM Opt_TypeFamilies ; is_boot <- tcIsHsBootOrSig -- Are we compiling an hs-boot file? ; checkTc type_families $ badFamInstDecl fam_tc_lname ; checkTc (not is_boot) $ badBootFamInstDeclErr -- Look up the family TyCon and check for validity including -- check that toplevel type instances are not for associated types. ; fam_tc <- tcLookupLocatedTyCon fam_tc_lname ; when (isNothing mb_clsinfo && -- Not in a class decl isTyConAssoc fam_tc) -- but an associated type (addErr $ assocInClassErr fam_tc_lname) ; return fam_tc } tcTyFamInstDecl :: Maybe ClsInfo -> LTyFamInstDecl Name -> TcM FamInst -- "type instance" tcTyFamInstDecl mb_clsinfo (L loc decl@(TyFamInstDecl { tfid_eqn = eqn })) = setSrcSpan loc $ tcAddTyFamInstCtxt decl $ do { let fam_lname = tfe_tycon (unLoc eqn) ; fam_tc <- tcFamInstDeclCombined mb_clsinfo fam_lname -- (0) Check it's an open type family ; checkTc (isFamilyTyCon fam_tc) (notFamily fam_tc) ; checkTc (isTypeFamilyTyCon fam_tc) (wrongKindOfFamily fam_tc) ; checkTc (isOpenTypeFamilyTyCon fam_tc) (notOpenFamily fam_tc) -- (1) do the work of verifying the synonym group ; co_ax_branch <- tcTyFamInstEqn (famTyConShape fam_tc) mb_clsinfo eqn -- (2) check for validity ; checkValidCoAxBranch mb_clsinfo fam_tc co_ax_branch -- (3) construct coercion axiom ; rep_tc_name <- newFamInstAxiomName loc (unLoc fam_lname) [co_ax_branch] ; let axiom = mkUnbranchedCoAxiom rep_tc_name fam_tc co_ax_branch ; newFamInst SynFamilyInst axiom } tcDataFamInstDecl :: Maybe ClsInfo -> LDataFamInstDecl Name -> TcM (FamInst, Maybe DerivInfo) -- "newtype instance" and "data instance" tcDataFamInstDecl mb_clsinfo (L loc decl@(DataFamInstDecl { dfid_pats = pats , dfid_tycon = fam_tc_name , dfid_defn = defn@HsDataDefn { dd_ND = new_or_data, dd_cType = cType , dd_ctxt = ctxt, dd_cons = cons , dd_derivs = derivs } })) = setSrcSpan loc $ tcAddDataFamInstCtxt decl $ do { fam_tc <- tcFamInstDeclCombined mb_clsinfo fam_tc_name -- Check that the family declaration is for the right kind ; checkTc (isFamilyTyCon fam_tc) (notFamily fam_tc) ; checkTc (isAlgTyCon fam_tc) (wrongKindOfFamily fam_tc) -- Kind check type patterns ; tcFamTyPats (famTyConShape fam_tc) mb_clsinfo pats (kcDataDefn defn) $ \tvs' pats' res_kind -> do { -- Check that left-hand side contains no type family applications -- (vanilla synonyms are fine, though, and we checked for -- foralls earlier) checkValidFamPats fam_tc tvs' pats' -- Check that type patterns match class instance head, if any ; checkConsistentFamInst mb_clsinfo fam_tc tvs' pats' -- Result kind must be '*' (otherwise, we have too few patterns) ; checkTc (isLiftedTypeKind res_kind) $ tooFewParmsErr (tyConArity fam_tc) ; stupid_theta <- tcHsContext ctxt ; gadt_syntax <- dataDeclChecks (tyConName fam_tc) new_or_data stupid_theta cons -- Construct representation tycon ; rep_tc_name <- newFamInstTyConName fam_tc_name pats' ; axiom_name <- newImplicitBinder rep_tc_name mkInstTyCoOcc ; let orig_res_ty = mkTyConApp fam_tc pats' ; (rep_tc, fam_inst) <- fixM $ \ ~(rec_rep_tc, _) -> do { data_cons <- tcConDecls new_or_data rec_rep_tc (tvs', orig_res_ty) cons ; tc_rhs <- case new_or_data of DataType -> return (mkDataTyConRhs data_cons) NewType -> ASSERT( not (null data_cons) ) mkNewTyConRhs rep_tc_name rec_rep_tc (head data_cons) -- freshen tyvars ; let (eta_tvs, eta_pats) = eta_reduce tvs' pats' axiom = mkSingleCoAxiom Representational axiom_name eta_tvs fam_tc eta_pats (mkTyConApp rep_tc (mkTyVarTys eta_tvs)) parent = FamInstTyCon axiom fam_tc pats' roles = map (const Nominal) tvs' -- NB: Use the tvs' from the pats. See bullet toward -- the end of Note [Data type families] in TyCon rep_tc = buildAlgTyCon rep_tc_name tvs' roles (fmap unLoc cType) stupid_theta tc_rhs Recursive False -- No promotable to the kind level gadt_syntax parent -- We always assume that indexed types are recursive. Why? -- (1) Due to their open nature, we can never be sure that a -- further instance might not introduce a new recursive -- dependency. (2) They are always valid loop breakers as -- they involve a coercion. ; fam_inst <- newFamInst (DataFamilyInst rep_tc) axiom ; return (rep_tc, fam_inst) } -- Remember to check validity; no recursion to worry about here ; checkValidTyCon rep_tc ; let m_deriv_info = case derivs of Nothing -> Nothing Just (L _ preds) -> Just $ DerivInfo { di_rep_tc = rep_tc , di_preds = preds , di_ctxt = tcMkDataFamInstCtxt decl } ; return (fam_inst, m_deriv_info) } } where -- See Note [Eta reduction for data family axioms] -- [a,b,c,d].T [a] c Int c d ==> [a,b,c]. T [a] c Int c eta_reduce tvs pats = go (reverse tvs) (reverse pats) go (tv:tvs) (pat:pats) | Just tv' <- getTyVar_maybe pat , tv == tv' , not (tv `elemVarSet` tyVarsOfTypes pats) = go tvs pats go tvs pats = (reverse tvs, reverse pats) {- Note [Eta reduction for data family axioms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this data family T a b :: * newtype instance T Int a = MkT (IO a) deriving( Monad ) We'd like this to work. From the 'newtype instance' you might think we'd get: newtype TInt a = MkT (IO a) axiom ax1 a :: T Int a ~ TInt a -- The type-instance part axiom ax2 a :: TInt a ~ IO a -- The newtype part But now what can we do? We have this problem Given: d :: Monad IO Wanted: d' :: Monad (T Int) = d |> ???? What coercion can we use for the ??? Solution: eta-reduce both axioms, thus: axiom ax1 :: T Int ~ TInt axiom ax2 :: TInt ~ IO Now d' = d |> Monad (sym (ax2 ; ax1)) This eta reduction happens both for data instances and newtype instances. See Note [Newtype eta] in TyCon. ************************************************************************ * * Type-checking instance declarations, pass 2 * * ************************************************************************ -} tcInstDecls2 :: [LTyClDecl Name] -> [InstInfo Name] -> TcM (LHsBinds Id) -- (a) From each class declaration, -- generate any default-method bindings -- (b) From each instance decl -- generate the dfun binding tcInstDecls2 tycl_decls inst_decls = do { -- (a) Default methods from class decls let class_decls = filter (isClassDecl . unLoc) tycl_decls ; dm_binds_s <- mapM tcClassDecl2 class_decls ; let dm_binds = unionManyBags dm_binds_s -- (b) instance declarations ; let dm_ids = collectHsBindsBinders dm_binds -- Add the default method Ids (again) -- See Note [Default methods and instances] ; inst_binds_s <- tcExtendLetEnv TopLevel dm_ids $ mapM tcInstDecl2 inst_decls -- Done ; return (dm_binds `unionBags` unionManyBags inst_binds_s) } {- See Note [Default methods and instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The default method Ids are already in the type environment (see Note [Default method Ids and Template Haskell] in TcTyClsDcls), BUT they don't have their InlinePragmas yet. Usually that would not matter, because the simplifier propagates information from binding site to use. But, unusually, when compiling instance decls we *copy* the INLINE pragma from the default method to the method for that particular operation (see Note [INLINE and default methods] below). So right here in tcInstDecls2 we must re-extend the type envt with the default method Ids replete with their INLINE pragmas. Urk. -} tcInstDecl2 :: InstInfo Name -> TcM (LHsBinds Id) -- Returns a binding for the dfun tcInstDecl2 (InstInfo { iSpec = ispec, iBinds = ibinds }) = recoverM (return emptyLHsBinds) $ setSrcSpan loc $ addErrCtxt (instDeclCtxt2 (idType dfun_id)) $ do { -- Instantiate the instance decl with skolem constants ; (inst_tyvars, dfun_theta, inst_head) <- tcSkolDFunType (idType dfun_id) ; dfun_ev_vars <- newEvVars dfun_theta -- We instantiate the dfun_id with superSkolems. -- See Note [Subtle interaction of recursion and overlap] -- and Note [Binding when looking up instances] ; let (clas, inst_tys) = tcSplitDFunHead inst_head (class_tyvars, sc_theta, _, op_items) = classBigSig clas sc_theta' = substTheta (zipOpenTvSubst class_tyvars inst_tys) sc_theta ; traceTc "tcInstDecl2" (vcat [ppr inst_tyvars, ppr inst_tys, ppr dfun_theta, ppr sc_theta']) -- Deal with 'SPECIALISE instance' pragmas -- See Note [SPECIALISE instance pragmas] ; spec_inst_info@(spec_inst_prags,_) <- tcSpecInstPrags dfun_id ibinds -- Typecheck superclasses and methods -- See Note [Typechecking plan for instance declarations] ; dfun_ev_binds_var <- newTcEvBinds ; let dfun_ev_binds = TcEvBinds dfun_ev_binds_var ; ((sc_meth_ids, sc_meth_binds, sc_meth_implics), tclvl) <- pushTcLevelM $ do { fam_envs <- tcGetFamInstEnvs ; (sc_ids, sc_binds, sc_implics) <- tcSuperClasses dfun_id clas inst_tyvars dfun_ev_vars inst_tys dfun_ev_binds fam_envs sc_theta' -- Typecheck the methods ; (meth_ids, meth_binds, meth_implics) <- tcMethods dfun_id clas inst_tyvars dfun_ev_vars inst_tys dfun_ev_binds spec_inst_info op_items ibinds ; return ( sc_ids ++ meth_ids , sc_binds `unionBags` meth_binds , sc_implics `unionBags` meth_implics ) } ; env <- getLclEnv ; emitImplication $ Implic { ic_tclvl = tclvl , ic_skols = inst_tyvars , ic_no_eqs = False , ic_given = dfun_ev_vars , ic_wanted = addImplics emptyWC sc_meth_implics , ic_status = IC_Unsolved , ic_binds = dfun_ev_binds_var , ic_env = env , ic_info = InstSkol } -- Create the result bindings ; self_dict <- newDict clas inst_tys ; let class_tc = classTyCon clas [dict_constr] = tyConDataCons class_tc dict_bind = mkVarBind self_dict (L loc con_app_args) -- We don't produce a binding for the dict_constr; instead we -- rely on the simplifier to unfold this saturated application -- We do this rather than generate an HsCon directly, because -- it means that the special cases (e.g. dictionary with only one -- member) are dealt with by the common MkId.mkDataConWrapId -- code rather than needing to be repeated here. -- con_app_tys = MkD ty1 ty2 -- con_app_scs = MkD ty1 ty2 sc1 sc2 -- con_app_args = MkD ty1 ty2 sc1 sc2 op1 op2 con_app_tys = wrapId (mkWpTyApps inst_tys) (dataConWrapId dict_constr) con_app_args = foldl app_to_meth con_app_tys sc_meth_ids app_to_meth :: HsExpr Id -> Id -> HsExpr Id app_to_meth fun meth_id = L loc fun `HsApp` L loc (wrapId arg_wrapper meth_id) inst_tv_tys = mkTyVarTys inst_tyvars arg_wrapper = mkWpEvVarApps dfun_ev_vars <.> mkWpTyApps inst_tv_tys -- Do not inline the dfun; instead give it a magic DFunFunfolding dfun_spec_prags | isNewTyCon class_tc = SpecPrags [] -- Newtype dfuns just inline unconditionally, -- so don't attempt to specialise them | otherwise = SpecPrags spec_inst_prags export = ABE { abe_wrap = idHsWrapper, abe_poly = dfun_id , abe_mono = self_dict, abe_prags = dfun_spec_prags } -- NB: see Note [SPECIALISE instance pragmas] main_bind = AbsBinds { abs_tvs = inst_tyvars , abs_ev_vars = dfun_ev_vars , abs_exports = [export] , abs_ev_binds = [] , abs_binds = unitBag dict_bind } ; return (unitBag (L loc main_bind) `unionBags` sc_meth_binds) } where dfun_id = instanceDFunId ispec loc = getSrcSpan dfun_id wrapId :: HsWrapper -> id -> HsExpr id wrapId wrapper id = mkHsWrap wrapper (HsVar id) {- Note [Typechecking plan for instance declarations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For intance declarations we generate the following bindings and implication constraints. Example: instance Ord a => Ord [a] where compare = <compare-rhs> generates this: Bindings: -- Method bindings $ccompare :: forall a. Ord a => a -> a -> Ordering $ccompare = /\a \(d:Ord a). let <meth-ev-binds> in ... -- Superclass bindings $cp1Ord :: forall a. Ord a => Eq [a] $cp1Ord = /\a \(d:Ord a). let <sc-ev-binds> in dfEqList (dw :: Eq a) Constraints: forall a. Ord a => -- Method constraint (forall. (empty) => <constraints from compare-rhs>) -- Superclass constraint /\ (forall. (empty) => dw :: Eq a) Notice that * Per-meth/sc implication. There is one inner implication per superclass or method, with no skolem variables or givens. The only reason for this one is to gather the evidence bindings privately for this superclass or method. This implication is generated by checkInstConstraints. * Overall instance implication. There is an overall enclosing implication for the whole instance declaratation, with the expected skolems and givens. We need this to get the correct "redundant constraint" warnings, gathering all the uses from all the methods and superclasses. See TcSimplify Note [Tracking redundant constraints] * The given constraints in the outer implication may generate evidence, notably by superclass selection. Since the method and superclass bindings are top-level, we want that evidence copied into *every* method or superclass definition. (Some of it will be usused in some, but dead-code elimination will drop it.) We achieve this by putting the the evidence variable for the overall instance implicaiton into the AbsBinds for each method/superclass. Hence the 'dfun_ev_binds' passed into tcMethods and tcSuperClasses. (And that in turn is why the abs_ev_binds field of AbBinds is a [TcEvBinds] rather than simply TcEvBinds. This is a bit of a hack, but works very nicely in practice. * Note that if a method has a locally-polymorphic binding, there will be yet another implication for that, generated by tcPolyCheck in tcMethodBody. E.g. class C a where foo :: forall b. Ord b => blah ************************************************************************ * * Type-checking superclases * * ************************************************************************ -} tcSuperClasses :: DFunId -> Class -> [TcTyVar] -> [EvVar] -> [TcType] -> TcEvBinds -> FamInstEnvs -> TcThetaType -> TcM ([EvVar], LHsBinds Id, Bag Implication) -- Make a new top-level function binding for each superclass, -- something like -- $Ordp1 :: forall a. Ord a => Eq [a] -- $Ordp1 = /\a \(d:Ord a). dfunEqList a (sc_sel d) -- -- See Note [Recursive superclasses] for why this is so hard! -- In effect, be build a special-purpose solver for the first step -- of solving each superclass constraint tcSuperClasses dfun_id cls tyvars dfun_evs inst_tys dfun_ev_binds _fam_envs sc_theta = do { (ids, binds, implics) <- mapAndUnzip3M tc_super (zip sc_theta [fIRST_TAG..]) ; return (ids, listToBag binds, listToBag implics) } where loc = getSrcSpan dfun_id size = sizeTypes inst_tys tc_super (sc_pred, n) = do { (sc_implic, sc_ev_id) <- checkInstConstraints $ \_ -> emitWanted (ScOrigin size) sc_pred ; sc_top_name <- newName (mkSuperDictAuxOcc n (getOccName cls)) ; let sc_top_ty = mkForAllTys tyvars (mkPiTypes dfun_evs sc_pred) sc_top_id = mkLocalId sc_top_name sc_top_ty export = ABE { abe_wrap = idHsWrapper, abe_poly = sc_top_id , abe_mono = sc_ev_id , abe_prags = SpecPrags [] } local_ev_binds = TcEvBinds (ic_binds sc_implic) bind = AbsBinds { abs_tvs = tyvars , abs_ev_vars = dfun_evs , abs_exports = [export] , abs_ev_binds = [dfun_ev_binds, local_ev_binds] , abs_binds = emptyBag } ; return (sc_top_id, L loc bind, sc_implic) } ------------------- checkInstConstraints :: (EvBindsVar -> TcM result) -> TcM (Implication, result) -- See Note [Typechecking plan for instance declarations] -- The thing_inside is also passed the EvBindsVar, -- so that emit_sc_pred can add evidence for the superclass -- (not used for methods) checkInstConstraints thing_inside = do { ev_binds_var <- newTcEvBinds ; env <- getLclEnv ; (result, tclvl, wanted) <- pushLevelAndCaptureConstraints $ thing_inside ev_binds_var ; let implic = Implic { ic_tclvl = tclvl , ic_skols = [] , ic_no_eqs = False , ic_given = [] , ic_wanted = wanted , ic_status = IC_Unsolved , ic_binds = ev_binds_var , ic_env = env , ic_info = InstSkol } ; return (implic, result) } {- Note [Recursive superclasses] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See Trac #3731, #4809, #5751, #5913, #6117, #6161, which all describe somewhat more complicated situations, but ones encountered in practice. See also tests tcrun020, tcrun021, tcrun033 ----- THE PROBLEM -------- The problem is that it is all too easy to create a class whose superclass is bottom when it should not be. Consider the following (extreme) situation: class C a => D a where ... instance D [a] => D [a] where ... (dfunD) instance C [a] => C [a] where ... (dfunC) Although this looks wrong (assume D [a] to prove D [a]), it is only a more extreme case of what happens with recursive dictionaries, and it can, just about, make sense because the methods do some work before recursing. To implement the dfunD we must generate code for the superclass C [a], which we had better not get by superclass selection from the supplied argument: dfunD :: forall a. D [a] -> D [a] dfunD = \d::D [a] -> MkD (scsel d) .. Otherwise if we later encounter a situation where we have a [Wanted] dw::D [a] we might solve it thus: dw := dfunD dw Which is all fine except that now ** the superclass C is bottom **! The instance we want is: dfunD :: forall a. D [a] -> D [a] dfunD = \d::D [a] -> MkD (dfunC (scsel d)) ... ----- THE SOLUTION -------- The basic solution is simple: be very careful about using superclass selection to generate a superclass witness in a dictionary function definition. More precisely: Superclass Invariant: in every class dictionary, every superclass dictionary field is non-bottom To achieve the Superclass Invariant, in a dfun definition we can generate a guaranteed-non-bottom superclass witness from: (sc1) one of the dictionary arguments itself (all non-bottom) (sc2) an immediate superclass of a smaller dictionary (sc3) a call of a dfun (always returns a dictionary constructor) The tricky case is (sc2). We proceed by induction on the size of the (type of) the dictionary, defined by TcValidity.sizeTypes. Let's suppose we are building a dictionary of size 3, and suppose the Superclass Invariant holds of smaller dictionaries. Then if we have a smaller dictionary, its immediate superclasses will be non-bottom by induction. What does "we have a smaller dictionary" mean? It might be one of the arguments of the instance, or one of its superclasses. Here is an example, taken from CmmExpr: class Ord r => UserOfRegs r a where ... (i1) instance UserOfRegs r a => UserOfRegs r (Maybe a) where (i2) instance (Ord r, UserOfRegs r CmmReg) => UserOfRegs r CmmExpr where For (i1) we can get the (Ord r) superclass by selection from (UserOfRegs r a), since it is smaller than the thing we are building (UserOfRegs r (Maybe a). But for (i2) that isn't the case, so we must add an explicit, and perhaps surprising, (Ord r) argument to the instance declaration. Here's another example from Trac #6161: class Super a => Duper a where ... class Duper (Fam a) => Foo a where ... (i3) instance Foo a => Duper (Fam a) where ... (i4) instance Foo Float where ... It would be horribly wrong to define dfDuperFam :: Foo a -> Duper (Fam a) -- from (i3) dfDuperFam d = MkDuper (sc_sel1 (sc_sel2 d)) ... dfFooFloat :: Foo Float -- from (i4) dfFooFloat = MkFoo (dfDuperFam dfFooFloat) ... Now the Super superclass of Duper is definitely bottom! This won't happen because when processing (i3) we can use the superclasses of (Foo a), which is smaller, namely Duper (Fam a). But that is *not* smaller than the target so we can't take *its* superclasses. As a result the program is rightly rejected, unless you add (Super (Fam a)) to the context of (i3). Note [Solving superclass constraints] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ How do we ensure that every superclass witness is generated by one of (sc1) (sc2) or (sc3) in Note [Recursive superclases]. Answer: * Superclass "wanted" constraints have CtOrigin of (ScOrigin size) where 'size' is the size of the instance declaration. e.g. class C a => D a where... instance blah => D [a] where ... The wanted superclass constraint for C [a] has origin ScOrigin size, where size = size( D [a] ). * (sc1) When we rewrite such a wanted constraint, it retains its origin. But if we apply an instance declaration, we can set the origin to (ScOrigin infinity), thus lifting any restrictions by making prohibitedSuperClassSolve return False. * (sc2) ScOrigin wanted constraints can't be solved from a superclass selection, except at a smaller type. This test is implemented by TcInteract.prohibitedSuperClassSolve * The "given" constraints of an instance decl have CtOrigin GivenOrigin InstSkol. * When we make a superclass selection from InstSkol we use a SkolemInfo of (InstSC size), where 'size' is the size of the constraint whose superclass we are taking. An similarly when taking the superclass of an InstSC. This is implemented in TcCanonical.newSCWorkFromFlavored Note [Silent superclass arguments] (historical interest only) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ NB1: this note describes our *old* solution to the recursive-superclass problem. I'm keeping the Note for now, just as institutional memory. However, the code for silent superclass arguments was removed in late Dec 2014 NB2: the silent-superclass solution introduced new problems of its own, in the form of instance overlap. Tests SilentParametersOverlapping, T5051, and T7862 are examples NB3: the silent-superclass solution also generated tons of extra dictionaries. For example, in monad-transformer code, when constructing a Monad dictionary you had to pass an Applicative dictionary; and to construct that you neede a Functor dictionary. Yet these extra dictionaries were often never used. Test T3064 compiled *far* faster after silent superclasses were eliminated. Our solution to this problem "silent superclass arguments". We pass to each dfun some ``silent superclass arguments’’, which are the immediate superclasses of the dictionary we are trying to construct. In our example: dfun :: forall a. C [a] -> D [a] -> D [a] dfun = \(dc::C [a]) (dd::D [a]) -> DOrd dc ... Notice the extra (dc :: C [a]) argument compared to the previous version. This gives us: ----------------------------------------------------------- DFun Superclass Invariant ~~~~~~~~~~~~~~~~~~~~~~~~ In the body of a DFun, every superclass argument to the returned dictionary is either * one of the arguments of the DFun, or * constant, bound at top level ----------------------------------------------------------- This net effect is that it is safe to treat a dfun application as wrapping a dictionary constructor around its arguments (in particular, a dfun never picks superclasses from the arguments under the dictionary constructor). No superclass is hidden inside a dfun application. The extra arguments required to satisfy the DFun Superclass Invariant always come first, and are called the "silent" arguments. You can find out how many silent arguments there are using Id.dfunNSilent; and then you can just drop that number of arguments to see the ones that were in the original instance declaration. DFun types are built (only) by MkId.mkDictFunId, so that is where we decide what silent arguments are to be added. -} {- ************************************************************************ * * Type-checking an instance method * * ************************************************************************ tcMethod - Make the method bindings, as a [(NonRec, HsBinds)], one per method - Remembering to use fresh Name (the instance method Name) as the binder - Bring the instance method Ids into scope, for the benefit of tcInstSig - Use sig_fn mapping instance method Name -> instance tyvars - Ditto prag_fn - Use tcValBinds to do the checking -} tcMethods :: DFunId -> Class -> [TcTyVar] -> [EvVar] -> [TcType] -> TcEvBinds -> ([Located TcSpecPrag], TcPragEnv) -> [(Id, DefMeth)] -> InstBindings Name -> TcM ([Id], LHsBinds Id, Bag Implication) -- The returned inst_meth_ids all have types starting -- forall tvs. theta => ... tcMethods dfun_id clas tyvars dfun_ev_vars inst_tys dfun_ev_binds prags@(spec_inst_prags,_) op_items (InstBindings { ib_binds = binds , ib_tyvars = lexical_tvs , ib_pragmas = sigs , ib_extensions = exts , ib_derived = is_derived }) = tcExtendTyVarEnv2 (lexical_tvs `zip` tyvars) $ -- The lexical_tvs scope over the 'where' part do { traceTc "tcInstMeth" (ppr sigs $$ ppr binds) ; checkMinimalDefinition ; (ids, binds, mb_implics) <- set_exts exts $ mapAndUnzip3M tc_item op_items ; return (ids, listToBag binds, listToBag (catMaybes mb_implics)) } where set_exts :: [ExtensionFlag] -> TcM a -> TcM a set_exts es thing = foldr setXOptM thing es hs_sig_fn = mkHsSigFun sigs inst_loc = getSrcSpan dfun_id ---------------------- tc_item :: (Id, DefMeth) -> TcM (Id, LHsBind Id, Maybe Implication) tc_item (sel_id, dm_info) | Just (user_bind, bndr_loc) <- findMethodBind (idName sel_id) binds = tcMethodBody clas tyvars dfun_ev_vars inst_tys dfun_ev_binds is_derived hs_sig_fn prags sel_id user_bind bndr_loc | otherwise = do { traceTc "tc_def" (ppr sel_id) ; tc_default sel_id dm_info } ---------------------- tc_default :: Id -> DefMeth -> TcM (TcId, LHsBind Id, Maybe Implication) tc_default sel_id (GenDefMeth dm_name) = do { meth_bind <- mkGenericDefMethBind clas inst_tys sel_id dm_name ; tcMethodBody clas tyvars dfun_ev_vars inst_tys dfun_ev_binds is_derived hs_sig_fn prags sel_id meth_bind inst_loc } tc_default sel_id NoDefMeth -- No default method at all = do { traceTc "tc_def: warn" (ppr sel_id) ; (meth_id, _, _) <- mkMethIds hs_sig_fn clas tyvars dfun_ev_vars inst_tys sel_id ; dflags <- getDynFlags ; let meth_bind = mkVarBind meth_id $ mkLHsWrap lam_wrapper (error_rhs dflags) ; return (meth_id, meth_bind, Nothing) } where error_rhs dflags = L inst_loc $ HsApp error_fun (error_msg dflags) error_fun = L inst_loc $ wrapId (WpTyApp meth_tau) nO_METHOD_BINDING_ERROR_ID error_msg dflags = L inst_loc (HsLit (HsStringPrim "" (unsafeMkByteString (error_string dflags)))) meth_tau = funResultTy (applyTys (idType sel_id) inst_tys) error_string dflags = showSDoc dflags (hcat [ppr inst_loc, text "|", ppr sel_id ]) lam_wrapper = mkWpTyLams tyvars <.> mkWpLams dfun_ev_vars tc_default sel_id (DefMeth dm_name) -- A polymorphic default method = do { -- Build the typechecked version directly, -- without calling typecheck_method; -- see Note [Default methods in instances] -- Generate /\as.\ds. let self = df as ds -- in $dm inst_tys self -- The 'let' is necessary only because HsSyn doesn't allow -- you to apply a function to a dictionary *expression*. ; self_dict <- newDict clas inst_tys ; let self_ev_bind = mkWantedEvBind self_dict (EvDFunApp dfun_id (mkTyVarTys tyvars) dfun_ev_vars) ; (meth_id, local_meth_sig, hs_wrap) <- mkMethIds hs_sig_fn clas tyvars dfun_ev_vars inst_tys sel_id ; dm_id <- tcLookupId dm_name ; let dm_inline_prag = idInlinePragma dm_id rhs = HsWrap (mkWpEvVarApps [self_dict] <.> mkWpTyApps inst_tys) $ HsVar dm_id -- A method always has a complete type signature, -- hence it is safe to call completeIdSigPolyId local_meth_id = completeIdSigPolyId local_meth_sig meth_bind = mkVarBind local_meth_id (L inst_loc rhs) meth_id1 = meth_id `setInlinePragma` dm_inline_prag -- Copy the inline pragma (if any) from the default -- method to this version. Note [INLINE and default methods] export = ABE { abe_wrap = hs_wrap, abe_poly = meth_id1 , abe_mono = local_meth_id , abe_prags = mk_meth_spec_prags meth_id1 spec_inst_prags [] } bind = AbsBinds { abs_tvs = tyvars, abs_ev_vars = dfun_ev_vars , abs_exports = [export] , abs_ev_binds = [EvBinds (unitBag self_ev_bind)] , abs_binds = unitBag meth_bind } -- Default methods in an instance declaration can't have their own -- INLINE or SPECIALISE pragmas. It'd be possible to allow them, but -- currently they are rejected with -- "INLINE pragma lacks an accompanying binding" ; return (meth_id1, L inst_loc bind, Nothing) } ---------------------- -- Check if one of the minimal complete definitions is satisfied checkMinimalDefinition = whenIsJust (isUnsatisfied methodExists (classMinimalDef clas)) $ warnUnsatisfiedMinimalDefinition where methodExists meth = isJust (findMethodBind meth binds) ------------------------ tcMethodBody :: Class -> [TcTyVar] -> [EvVar] -> [TcType] -> TcEvBinds -> Bool -> HsSigFun -> ([LTcSpecPrag], TcPragEnv) -> Id -> LHsBind Name -> SrcSpan -> TcM (TcId, LHsBind Id, Maybe Implication) tcMethodBody clas tyvars dfun_ev_vars inst_tys dfun_ev_binds is_derived sig_fn (spec_inst_prags, prag_fn) sel_id (L bind_loc meth_bind) bndr_loc = add_meth_ctxt $ do { traceTc "tcMethodBody" (ppr sel_id <+> ppr (idType sel_id)) ; (global_meth_id, local_meth_sig, hs_wrap) <- setSrcSpan bndr_loc $ mkMethIds sig_fn clas tyvars dfun_ev_vars inst_tys sel_id ; let prags = lookupPragEnv prag_fn (idName sel_id) -- A method always has a complete type signature, -- so it is safe to call cmpleteIdSigPolyId local_meth_id = completeIdSigPolyId local_meth_sig lm_bind = meth_bind { fun_id = L bndr_loc (idName local_meth_id) } -- Substitute the local_meth_name for the binder -- NB: the binding is always a FunBind ; global_meth_id <- addInlinePrags global_meth_id prags ; spec_prags <- tcSpecPrags global_meth_id prags ; (meth_implic, (tc_bind, _)) <- checkInstConstraints $ \ _ev_binds -> tcPolyCheck NonRecursive no_prag_fn local_meth_sig (L bind_loc lm_bind) ; let specs = mk_meth_spec_prags global_meth_id spec_inst_prags spec_prags export = ABE { abe_poly = global_meth_id , abe_mono = local_meth_id , abe_wrap = hs_wrap , abe_prags = specs } local_ev_binds = TcEvBinds (ic_binds meth_implic) full_bind = AbsBinds { abs_tvs = tyvars , abs_ev_vars = dfun_ev_vars , abs_exports = [export] , abs_ev_binds = [dfun_ev_binds, local_ev_binds] , abs_binds = tc_bind } ; return (global_meth_id, L bind_loc full_bind, Just meth_implic) } where -- For instance decls that come from deriving clauses -- we want to print out the full source code if there's an error -- because otherwise the user won't see the code at all add_meth_ctxt thing | is_derived = addLandmarkErrCtxt (derivBindCtxt sel_id clas inst_tys) thing | otherwise = thing no_prag_fn = emptyPragEnv -- No pragmas for local_meth_id; -- they are all for meth_id ------------------------ mkMethIds :: HsSigFun -> Class -> [TcTyVar] -> [EvVar] -> [TcType] -> Id -> TcM (TcId, TcIdSigInfo, HsWrapper) mkMethIds sig_fn clas tyvars dfun_ev_vars inst_tys sel_id = do { poly_meth_name <- newName (mkClassOpAuxOcc sel_occ) ; local_meth_name <- newName sel_occ -- Base the local_meth_name on the selector name, because -- type errors from tcMethodBody come from here ; let poly_meth_id = mkLocalId poly_meth_name poly_meth_ty local_meth_id = mkLocalId local_meth_name local_meth_ty ; case lookupHsSig sig_fn sel_name of Just lhs_ty -- There is a signature in the instance declaration -- See Note [Instance method signatures] -> setSrcSpan (getLoc lhs_ty) $ do { inst_sigs <- xoptM Opt_InstanceSigs ; checkTc inst_sigs (misplacedInstSig sel_name lhs_ty) ; sig_ty <- tcHsSigType (FunSigCtxt sel_name False) lhs_ty ; let poly_sig_ty = mkSigmaTy tyvars theta sig_ty ctxt = FunSigCtxt sel_name True ; tc_sig <- instTcTySig ctxt lhs_ty sig_ty Nothing [] local_meth_name ; hs_wrap <- addErrCtxtM (methSigCtxt sel_name poly_sig_ty poly_meth_ty) $ tcSubType ctxt poly_sig_ty poly_meth_ty ; return (poly_meth_id, tc_sig, hs_wrap) } Nothing -- No type signature -> do { tc_sig <- instTcTySigFromId local_meth_id ; return (poly_meth_id, tc_sig, idHsWrapper) } } -- Absent a type sig, there are no new scoped type variables here -- Only the ones from the instance decl itself, which are already -- in scope. Example: -- class C a where { op :: forall b. Eq b => ... } -- instance C [c] where { op = <rhs> } -- In <rhs>, 'c' is scope but 'b' is not! where sel_name = idName sel_id sel_occ = nameOccName sel_name local_meth_ty = instantiateMethod clas sel_id inst_tys poly_meth_ty = mkSigmaTy tyvars theta local_meth_ty theta = map idType dfun_ev_vars methSigCtxt :: Name -> TcType -> TcType -> TidyEnv -> TcM (TidyEnv, MsgDoc) methSigCtxt sel_name sig_ty meth_ty env0 = do { (env1, sig_ty) <- zonkTidyTcType env0 sig_ty ; (env2, meth_ty) <- zonkTidyTcType env1 meth_ty ; let msg = hang (ptext (sLit "When checking that instance signature for") <+> quotes (ppr sel_name)) 2 (vcat [ ptext (sLit "is more general than its signature in the class") , ptext (sLit "Instance sig:") <+> ppr sig_ty , ptext (sLit " Class sig:") <+> ppr meth_ty ]) ; return (env2, msg) } misplacedInstSig :: Name -> LHsType Name -> SDoc misplacedInstSig name hs_ty = vcat [ hang (ptext (sLit "Illegal type signature in instance declaration:")) 2 (hang (pprPrefixName name) 2 (dcolon <+> ppr hs_ty)) , ptext (sLit "(Use InstanceSigs to allow this)") ] {- Note [Instance method signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ With -XInstanceSigs we allow the user to supply a signature for the method in an instance declaration. Here is an artificial example: data Age = MkAge Int instance Ord Age where compare :: a -> a -> Bool compare = error "You can't compare Ages" The instance signature can be *more* polymorphic than the instantiated class method (in this case: Age -> Age -> Bool), but it cannot be less polymorphic. Moreover, if a signature is given, the implementation code should match the signature, and type variables bound in the singature should scope over the method body. We achieve this by building a TcSigInfo for the method, whether or not there is an instance method signature, and using that to typecheck the declaration (in tcMethodBody). That means, conveniently, that the type variables bound in the signature will scope over the body. What about the check that the instance method signature is more polymorphic than the instantiated class method type? We just do a tcSubType call in mkMethIds, and use the HsWrapper thus generated in the method AbsBind. It's very like the tcSubType impedance-matching call in mkExport. We have to pass the HsWrapper into tcMethodBody. -} ---------------------- mk_meth_spec_prags :: Id -> [LTcSpecPrag] -> [LTcSpecPrag] -> TcSpecPrags -- Adapt the 'SPECIALISE instance' pragmas to work for this method Id -- There are two sources: -- * spec_prags_for_me: {-# SPECIALISE op :: <blah> #-} -- * spec_prags_from_inst: derived from {-# SPECIALISE instance :: <blah> #-} -- These ones have the dfun inside, but [perhaps surprisingly] -- the correct wrapper. -- See Note [Handling SPECIALISE pragmas] in TcBinds mk_meth_spec_prags meth_id spec_inst_prags spec_prags_for_me = SpecPrags (spec_prags_for_me ++ spec_prags_from_inst) where spec_prags_from_inst | isInlinePragma (idInlinePragma meth_id) = [] -- Do not inherit SPECIALISE from the instance if the -- method is marked INLINE, because then it'll be inlined -- and the specialisation would do nothing. (Indeed it'll provoke -- a warning from the desugarer | otherwise = [ L inst_loc (SpecPrag meth_id wrap inl) | L inst_loc (SpecPrag _ wrap inl) <- spec_inst_prags] mkGenericDefMethBind :: Class -> [Type] -> Id -> Name -> TcM (LHsBind Name) mkGenericDefMethBind clas inst_tys sel_id dm_name = -- A generic default method -- If the method is defined generically, we only have to call the -- dm_name. do { dflags <- getDynFlags ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Filling in method body" (vcat [ppr clas <+> ppr inst_tys, nest 2 (ppr sel_id <+> equals <+> ppr rhs)])) ; return (noLoc $ mkTopFunBind Generated (noLoc (idName sel_id)) [mkSimpleMatch [] rhs]) } where rhs = nlHsVar dm_name ---------------------- derivBindCtxt :: Id -> Class -> [Type ] -> SDoc derivBindCtxt sel_id clas tys = vcat [ ptext (sLit "When typechecking the code for") <+> quotes (ppr sel_id) , nest 2 (ptext (sLit "in a derived instance for") <+> quotes (pprClassPred clas tys) <> colon) , nest 2 $ ptext (sLit "To see the code I am typechecking, use -ddump-deriv") ] warnMissingMethodOrAT :: String -> Name -> TcM () warnMissingMethodOrAT what name = do { warn <- woptM Opt_WarnMissingMethods ; traceTc "warn" (ppr name <+> ppr warn <+> ppr (not (startsWithUnderscore (getOccName name)))) ; warnTc (warn -- Warn only if -fwarn-missing-methods && not (startsWithUnderscore (getOccName name))) -- Don't warn about _foo methods (ptext (sLit "No explicit") <+> text what <+> ptext (sLit "or default declaration for") <+> quotes (ppr name)) } warnUnsatisfiedMinimalDefinition :: ClassMinimalDef -> TcM () warnUnsatisfiedMinimalDefinition mindef = do { warn <- woptM Opt_WarnMissingMethods ; warnTc warn message } where message = vcat [ptext (sLit "No explicit implementation for") ,nest 2 $ pprBooleanFormulaNice mindef ] {- Note [Export helper functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We arrange to export the "helper functions" of an instance declaration, so that they are not subject to preInlineUnconditionally, even if their RHS is trivial. Reason: they are mentioned in the DFunUnfolding of the dict fun as Ids, not as CoreExprs, so we can't substitute a non-variable for them. We could change this by making DFunUnfoldings have CoreExprs, but it seems a bit simpler this way. Note [Default methods in instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this class Baz v x where foo :: x -> x foo y = <blah> instance Baz Int Int From the class decl we get $dmfoo :: forall v x. Baz v x => x -> x $dmfoo y = <blah> Notice that the type is ambiguous. That's fine, though. The instance decl generates $dBazIntInt = MkBaz fooIntInt fooIntInt = $dmfoo Int Int $dBazIntInt BUT this does mean we must generate the dictionary translation of fooIntInt directly, rather than generating source-code and type-checking it. That was the bug in Trac #1061. In any case it's less work to generate the translated version! Note [INLINE and default methods] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Default methods need special case. They are supposed to behave rather like macros. For exmample class Foo a where op1, op2 :: Bool -> a -> a {-# INLINE op1 #-} op1 b x = op2 (not b) x instance Foo Int where -- op1 via default method op2 b x = <blah> The instance declaration should behave just as if 'op1' had been defined with the code, and INLINE pragma, from its original definition. That is, just as if you'd written instance Foo Int where op2 b x = <blah> {-# INLINE op1 #-} op1 b x = op2 (not b) x So for the above example we generate: {-# INLINE $dmop1 #-} -- $dmop1 has an InlineCompulsory unfolding $dmop1 d b x = op2 d (not b) x $fFooInt = MkD $cop1 $cop2 {-# INLINE $cop1 #-} $cop1 = $dmop1 $fFooInt $cop2 = <blah> Note carefully: * We *copy* any INLINE pragma from the default method $dmop1 to the instance $cop1. Otherwise we'll just inline the former in the latter and stop, which isn't what the user expected * Regardless of its pragma, we give the default method an unfolding with an InlineCompulsory source. That means that it'll be inlined at every use site, notably in each instance declaration, such as $cop1. This inlining must happen even though a) $dmop1 is not saturated in $cop1 b) $cop1 itself has an INLINE pragma It's vital that $dmop1 *is* inlined in this way, to allow the mutual recursion between $fooInt and $cop1 to be broken * To communicate the need for an InlineCompulsory to the desugarer (which makes the Unfoldings), we use the IsDefaultMethod constructor in TcSpecPrags. ************************************************************************ * * Specialise instance pragmas * * ************************************************************************ Note [SPECIALISE instance pragmas] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider instance (Ix a, Ix b) => Ix (a,b) where {-# SPECIALISE instance Ix (Int,Int) #-} range (x,y) = ... We make a specialised version of the dictionary function, AND specialised versions of each *method*. Thus we should generate something like this: $dfIxPair :: (Ix a, Ix b) => Ix (a,b) {-# DFUN [$crangePair, ...] #-} {-# SPECIALISE $dfIxPair :: Ix (Int,Int) #-} $dfIxPair da db = Ix ($crangePair da db) (...other methods...) $crange :: (Ix a, Ix b) -> ((a,b),(a,b)) -> [(a,b)] {-# SPECIALISE $crange :: ((Int,Int),(Int,Int)) -> [(Int,Int)] #-} $crange da db = <blah> The SPECIALISE pragmas are acted upon by the desugarer, which generate dii :: Ix Int dii = ... $s$dfIxPair :: Ix ((Int,Int),(Int,Int)) {-# DFUN [$crangePair di di, ...] #-} $s$dfIxPair = Ix ($crangePair di di) (...) {-# RULE forall (d1,d2:Ix Int). $dfIxPair Int Int d1 d2 = $s$dfIxPair #-} $s$crangePair :: ((Int,Int),(Int,Int)) -> [(Int,Int)] $c$crangePair = ...specialised RHS of $crangePair... {-# RULE forall (d1,d2:Ix Int). $crangePair Int Int d1 d2 = $s$crangePair #-} Note that * The specialised dictionary $s$dfIxPair is very much needed, in case we call a function that takes a dictionary, but in a context where the specialised dictionary can be used. See Trac #7797. * The ClassOp rule for 'range' works equally well on $s$dfIxPair, because it still has a DFunUnfolding. See Note [ClassOp/DFun selection] * A call (range ($dfIxPair Int Int d1 d2)) might simplify two ways: --> {ClassOp rule for range} $crangePair Int Int d1 d2 --> {SPEC rule for $crangePair} $s$crangePair or thus: --> {SPEC rule for $dfIxPair} range $s$dfIxPair --> {ClassOpRule for range} $s$crangePair It doesn't matter which way. * We want to specialise the RHS of both $dfIxPair and $crangePair, but the SAME HsWrapper will do for both! We can call tcSpecPrag just once, and pass the result (in spec_inst_info) to tcMethods. -} tcSpecInstPrags :: DFunId -> InstBindings Name -> TcM ([Located TcSpecPrag], TcPragEnv) tcSpecInstPrags dfun_id (InstBindings { ib_binds = binds, ib_pragmas = uprags }) = do { spec_inst_prags <- mapM (wrapLocM (tcSpecInst dfun_id)) $ filter isSpecInstLSig uprags -- The filter removes the pragmas for methods ; return (spec_inst_prags, mkPragEnv uprags binds) } ------------------------------ tcSpecInst :: Id -> Sig Name -> TcM TcSpecPrag tcSpecInst dfun_id prag@(SpecInstSig _ hs_ty) = addErrCtxt (spec_ctxt prag) $ do { (tyvars, theta, clas, tys) <- tcHsInstHead SpecInstCtxt hs_ty ; let spec_dfun_ty = mkDictFunTy tyvars theta clas tys ; co_fn <- tcSpecWrapper SpecInstCtxt (idType dfun_id) spec_dfun_ty ; return (SpecPrag dfun_id co_fn defaultInlinePragma) } where spec_ctxt prag = hang (ptext (sLit "In the SPECIALISE pragma")) 2 (ppr prag) tcSpecInst _ _ = panic "tcSpecInst" {- ************************************************************************ * * \subsection{Error messages} * * ************************************************************************ -} instDeclCtxt1 :: LHsType Name -> SDoc instDeclCtxt1 hs_inst_ty = inst_decl_ctxt (case unLoc hs_inst_ty of HsForAllTy _ _ _ _ (L _ ty') -> ppr ty' _ -> ppr hs_inst_ty) -- Don't expect this instDeclCtxt2 :: Type -> SDoc instDeclCtxt2 dfun_ty = inst_decl_ctxt (ppr (mkClassPred cls tys)) where (_,_,cls,tys) = tcSplitDFunTy dfun_ty inst_decl_ctxt :: SDoc -> SDoc inst_decl_ctxt doc = hang (ptext (sLit "In the instance declaration for")) 2 (quotes doc) badBootFamInstDeclErr :: SDoc badBootFamInstDeclErr = ptext (sLit "Illegal family instance in hs-boot file") notFamily :: TyCon -> SDoc notFamily tycon = vcat [ ptext (sLit "Illegal family instance for") <+> quotes (ppr tycon) , nest 2 $ parens (ppr tycon <+> ptext (sLit "is not an indexed type family"))] tooFewParmsErr :: Arity -> SDoc tooFewParmsErr arity = ptext (sLit "Family instance has too few parameters; expected") <+> ppr arity assocInClassErr :: Located Name -> SDoc assocInClassErr name = ptext (sLit "Associated type") <+> quotes (ppr name) <+> ptext (sLit "must be inside a class instance") badFamInstDecl :: Located Name -> SDoc badFamInstDecl tc_name = vcat [ ptext (sLit "Illegal family instance for") <+> quotes (ppr tc_name) , nest 2 (parens $ ptext (sLit "Use TypeFamilies to allow indexed type families")) ] notOpenFamily :: TyCon -> SDoc notOpenFamily tc = ptext (sLit "Illegal instance for closed family") <+> quotes (ppr tc)
ghc-android/ghc
compiler/typecheck/TcInstDcls.hs
Haskell
bsd-3-clause
78,248
{-# LANGUAGE FunctionalDependencies #-} module Rachel.Types ( -- * Pretty printing Pretty (..) -- * Rachel values -- ** Primitive values , PrimitiveType (..) , RReal (..), RInteger (..) , RBool (..), RSound (..) -- ** All values , Value (..) -- * Expressions , Id , Exp (..) -- * Type of a expression , Type (..) , typeVars , mapTypeVars , prefixType, sufixType , hasHash, removeHash -- * Context , Context, Environment , OpAssoc (..) , Fixity (..), defaultFixity , Entity (..) , insertEntity , contextFromEnv -- * Declarations , Dec (..) ) where import Data.Sound -- Data structures import Data.Map (Map,insert) import Data.Set (Set) import qualified Data.Set as Set import Data.Fixed (Micro, showFixed) -- Other imports import Data.String import Data.Char (isLetter) import qualified Data.Foldable as F -- Pretty printing -- | Human readable representation. class Pretty a where pretty :: a -> String parens :: Bool -> String -> String parens True str = '(' : (str ++ ")") parens _ str = str -- Rachel types -- | Real numbers represented as floating point numbers (double precision). newtype RReal = RReal Double deriving (Show,Eq) instance Pretty RReal where pretty (RReal r) = showFixed True ((fromRational . toRational) r :: Micro) -- | Integer numbers. newtype RInteger = RInteger Integer deriving (Show,Eq) instance Pretty RInteger where pretty (RInteger i) = show i -- | Booleans. newtype RBool = RBool Bool instance Pretty RBool where pretty (RBool True) = "true" pretty (RBool False) = "false" -- | A sound. See 'Sound'. newtype RSound = RSound Sound instance Pretty RSound where pretty (RSound _) = "#sound#" -------------------------- class PrimitiveType p h | h -> p , p -> h where toPrimitive :: h -> p fromPrimitive :: p -> h toValue :: p -> Value fromValue :: Value -> Maybe p toType :: p -> Type instance PrimitiveType RInteger Integer where toPrimitive = RInteger fromPrimitive (RInteger i) = i toValue = VInteger fromValue (VInteger i) = Just i fromValue _ = Nothing toType _ = TInteger instance PrimitiveType RReal Double where toPrimitive = RReal fromPrimitive (RReal i) = i toValue = VReal fromValue (VReal i) = Just i fromValue _ = Nothing toType _ = TReal instance PrimitiveType RBool Bool where toPrimitive = RBool fromPrimitive (RBool i) = i toValue = VBool fromValue (VBool i) = Just i fromValue _ = Nothing toType _ = TBool instance PrimitiveType RSound Sound where toPrimitive = RSound fromPrimitive (RSound i) = i toValue = VSound fromValue (VSound i) = Just i fromValue _ = Nothing toType _ = TSound -- instance (PrimitiveType p h, PrimitiveType p' h') -- => PrimitiveType (p -> p') (h -> h') where -- toPrimitive f = toPrimitive . f . fromPrimitive -------------------------- -- | Any identifier contains a value of this type. data Value = -- | Real numbers. VReal RReal -- | Integer numbers. | VInteger RInteger -- | Booleans. | VBool RBool -- | Sounds. | VSound RSound -- | Product. | VProd Value Value -- | Left value of a sum. | VSumL Value -- | Right value of a sum. | VSumR Value -- | Functions. | VFun (Value -> Value) -- | Bottom. | VBottom String instance Pretty Value where pretty (VReal r) = pretty r pretty (VInteger i) = pretty i pretty (VBool b) = pretty b pretty (VSound s) = pretty s pretty (VProd x y) = "(" ++ pretty x ++ "," ++ pretty y ++ ")" pretty (VSumL x) = "L (" ++ pretty x ++ ")" pretty (VSumR x) = "R (" ++ pretty x ++ ")" pretty (VFun _) = "#function#" pretty (VBottom str) = "_|_: " ++ str -- Expressions and types -- | Identifiers are stored as 'String's. type Id = String -- | An expression in the Rachel language. data Exp = EReal RReal -- ^ @1.0@ | EInteger RInteger -- ^ @1@ | EVar Id -- ^ @x@ | EProd Exp Exp -- ^ @(e1,e2)@ | ESumL -- ^ @L@ | ESumR -- ^ @R@ | EApp Exp Exp -- ^ @e1 e2@ | ELambda Id Exp -- ^ @\\x.e@ | ELet Id Exp Exp -- ^ @let x = e1 in e2@ deriving (Show,Eq) instance IsString Exp where fromString = EVar isEOp :: Exp -> Bool isEOp (EProd _ _) = True isEOp (EApp _ _) = True isEOp _ = False instance Pretty Exp where pretty (EReal r) = pretty r pretty (EInteger i) = pretty i pretty (EVar str) = case str of [] -> error "Variable with empty name!" (x:_) -> if isLetter x || x == '_' then str else "(" ++ str ++ ")" pretty (EProd x y) = let pretty' e = parens (isEOp e) (pretty e) in "(" ++ pretty' x ++ "," ++ pretty' y ++ ")" pretty ESumL = "L" pretty ESumR = "R" pretty (EApp f x) = let pretty' e = parens (isEOp e) (pretty e) in pretty' f ++ " " ++ pretty' x pretty (ELambda x e) = "\\" ++ x ++ "." ++ pretty e pretty (ELet x e1 e2) = "let " ++ x ++ " = " ++ pretty e1 ++ " in " ++ pretty e2 -- | The type of Rachel types. data Type = -- Primitive types TReal | TInteger | TBool | TSound -- Arity two types | TFun Type Type | TProd Type Type | TSum Type Type -- Type variables | TVar Id deriving (Show,Eq) isTOp :: Type -> Bool isTOp (TFun _ _) = True isTOp (TProd _ _) = True isTOp (TSum _ _) = True isTOp _ = False isTFun :: Type -> Bool isTFun (TFun _ _) = True isTFun _ = False hasHash :: Type -> Bool hasHash = F.any (elem '#') . typeVars -- | Remove all the characters after a hash (including the hash) -- in every type variable. removeHash :: Type -> Type removeHash = mapTypeVars $ takeWhile (/='#') instance Pretty Type where pretty TReal = "Real" pretty TInteger = "Integer" pretty TBool = "Bool" pretty TSound = "Sound" pretty (TFun f x) = let pretty' e = parens (isTFun e) (pretty e) in pretty' f ++ " -> " ++ pretty x pretty (TProd x y) = let pretty' e = parens (isTOp e) (pretty e) in pretty' x ++ "*" ++ pretty' y pretty (TSum x y) = let pretty' e = parens (isTOp e) (pretty e) in pretty' x ++ "+" ++ pretty' y pretty (TVar str) = str -- | Map a function over all variable names in a type. mapTypeVars :: (String -> String) -> Type -> Type mapTypeVars f = go where go (TVar v) = TVar $ f v go (TFun x y) = TFun (go x) (go y) go (TProd x y) = TProd (go x) (go y) go (TSum x y) = TSum (go x) (go y) go t = t -- | Add a prefix to all the variables in a type. -- This has the property that, given any two types @t1@ and @t2@, -- if the strings @str1@ and @str2@ are /different/, then the -- set of variables of @prefixType str1 t1@ and @prefixType str2 t2@ -- are disjoint. prefixType :: String -> Type -> Type prefixType str = mapTypeVars (str++) -- | Add a sufix to all the variables in a type. sufixType :: String -> Type -> Type sufixType str = mapTypeVars (++str) -- | Type variables in a type. typeVars :: Type -> Set Id typeVars = typeVarsAux Set.empty typeVarsAux :: Set Id -> Type -> Set Id typeVarsAux xs (TVar x) = Set.insert x xs typeVarsAux xs (TFun f x) = let ys = typeVarsAux xs f in typeVarsAux ys x typeVarsAux xs (TProd x y) = let ys = typeVarsAux xs x in typeVarsAux ys y typeVarsAux xs (TSum x y) = let ys = typeVarsAux xs x in typeVarsAux ys y typeVarsAux xs _ = xs data OpAssoc = LeftA | RightA deriving Eq -- | A fixity value of an 'Entity'. -- The first parameter indicates the associativity as operator. -- The second parameter indicates the priority. data Fixity = Fixity OpAssoc Int deriving Eq instance Pretty Fixity where pretty (Fixity a p) = let str = if a == LeftA then "l" else "r" in "infix" ++ str ++ " " ++ show p defaultFixity :: Fixity defaultFixity = Fixity LeftA 10 -- | A complete 'Entity' with identity, type, fixity and value. data Entity = Entity Id Type Fixity Value -- | A context is a map from each defined identity to its 'Type'. type Context = Map Id Type -- | An environment is a map from each defined identity to its full definition, -- i.e. its type, its fixity and its value. type Environment = Map Id (Type,Fixity,Value) -- | Insert an 'Entity' in an environment, replacing the type and value of an -- already defined identity. insertEntity :: Entity -> Environment -> Environment insertEntity (Entity i t f v) = insert i (t,f,v) -- | Discard the values of every identity to get a 'Context' from an 'Environment'. contextFromEnv :: Environment -> Context contextFromEnv = fmap $ \(t,_,_) -> t -- Declarations -- | Rachel top level declarations. data Dec = TypeDec Id Type | FunDec Id Exp | InfixDec Id Fixity | PatDec Id Int [[Id]] -- ^ Pattern declaration. The 'Int' value specifies the number of columns.
Daniel-Diaz/rachel
Rachel/Types.hs
Haskell
bsd-3-clause
8,847
-- -- HTTP client for use with pipes -- -- 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 Main where import Control.Exception (bracket) import Network.Http.Client -- -- Otherwise redundent imports, but useful for testing in GHCi. -- import Blaze.ByteString.Builder (Builder) import qualified Blaze.ByteString.Builder as Builder import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as S import Debug.Trace main :: IO () main = do c <- openConnection "kernel.operationaldynamics.com" 58080 q <- buildRequest $ do http GET "/time" setAccept "text/plain" putStr $ show q -- Requests [headers] are terminated by a double newline -- already. We need a better way of emitting debug -- information mid-stream from this library. sendRequest c q emptyBody receiveResponse c debugHandler closeConnection c
afcowie/pipes-http
tests/ActualSnippet.hs
Haskell
bsd-3-clause
1,203
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE CPP #-} module Main where import Common import Data.Aeson import Data.Proxy import Data.Text (Text) import qualified Data.Text as T import GHC.Generics import qualified Lucid as L import Lucid.Base import Network.HTTP.Types hiding (Header) import Network.Wai import Network.Wai.Handler.Warp import Network.Wai.Middleware.Gzip import Network.Wai.Application.Static import Network.Wai.Middleware.RequestLogger import Servant import Servant.Server.Internal import qualified System.IO as IO import Miso import Miso.String main :: IO () main = do IO.hPutStrLn IO.stderr "Running on port 3002..." run 3002 $ logStdout (compress app) where compress = gzip def { gzipFiles = GzipCompress } app :: Application #if MIN_VERSION_servant(0,11,0) app = serve (Proxy @ API) (static :<|> serverHandlers :<|> pure misoManifest :<|> Tagged handle404) #else app = serve (Proxy @ API) (static :<|> serverHandlers :<|> pure misoManifest :<|> handle404) #endif where static = serveDirectoryWith (defaultWebAppSettings "static") -- | Wrapper for setting HTML doctype and header newtype Wrapper a = Wrapper a deriving (Show, Eq) -- | Convert client side routes into server-side web handlers type ServerRoutes = ToServerRoutes ClientRoutes Wrapper Action -- | API type type API = ("static" :> Raw) :<|> ServerRoutes :<|> ("manifest.json" :> Get '[JSON] Manifest) :<|> Raw data Manifest = Manifest { name :: Text , short_name :: Text , start_url :: Text , display :: Text , theme_color :: Text , description :: Text } deriving (Show, Eq, Generic) instance ToJSON Manifest misoManifest :: Manifest misoManifest = Manifest { name = "Haskell Miso" , short_name = "Miso" , start_url = "." , display = "standalone" , theme_color = "#00d1b2" , description = "A tasty Haskell front-end framework" } handle404 :: Application handle404 _ respond = respond $ responseLBS status404 [("Content-Type", "text/html")] $ renderBS $ toHtml $ Wrapper $ the404 Model { uri = goHome, navMenuOpen = False } instance L.ToHtml a => L.ToHtml (Wrapper a) where toHtmlRaw = L.toHtml toHtml (Wrapper x) = do L.doctype_ L.html_ [ L.lang_ "en" ] $ do L.head_ $ do L.title_ "Miso: A tasty Haskell front-end framework" L.link_ [ L.rel_ "stylesheet" , L.href_ "https://cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.2.2/gh-fork-ribbon.min.css" ] L.link_ [ L.rel_ "manifest" , L.href_ "/manifest.json" ] L.meta_ [ L.charset_ "utf-8" ] L.meta_ [ L.name_ "theme-color", L.content_ "#00d1b2" ] L.meta_ [ L.httpEquiv_ "X-UA-Compatible" , L.content_ "IE=edge" ] L.meta_ [ L.name_ "viewport" , L.content_ "width=device-width, initial-scale=1" ] L.meta_ [ L.name_ "description" , L.content_ "Miso is a small isomorphic Haskell front-end framework featuring a virtual-dom, diffing / patching algorithm, event delegation, event batching, SVG, Server-sent events, Websockets, type-safe servant-style routing and an extensible Subscription-based subsystem. Inspired by Elm, Redux and Bobril. Miso is pure by default, but side effects (like XHR) can be introduced into the system via the Effect data type. Miso makes heavy use of the GHCJS FFI and therefore has minimal dependencies." ] L.style_ ".github-fork-ribbon:before { background-color: \"#e59751\" !important; } " cssRef animateRef cssRef bulmaRef cssRef fontAwesomeRef jsRef "https://buttons.github.io/buttons.js" L.script_ analytics jsRef "static/all.js" L.body_ (L.toHtml x) where jsRef href = L.with (L.script_ mempty) [ makeAttribute "src" href , makeAttribute "async" mempty , makeAttribute "defer" mempty ] cssRef href = L.with (L.link_ mempty) [ L.rel_ "stylesheet" , L.type_ "text/css" , L.href_ href ] fontAwesomeRef :: MisoString fontAwesomeRef = "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" animateRef :: MisoString animateRef = "https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" bulmaRef :: MisoString bulmaRef = "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.3/css/bulma.min.css" analytics :: MisoString analytics = -- Multiline strings don’t work well with CPP mconcat [ "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){" , "(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o)," , "m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)" , "})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');" , "ga('create', 'UA-102668481-1', 'auto');" , "ga('send', 'pageview');" ] serverHandlers :: Handler (Wrapper (View Action)) :<|> Handler (Wrapper (View Action)) :<|> Handler (Wrapper (View Action)) :<|> Handler (Wrapper (View Action)) serverHandlers = examplesHandler :<|> docsHandler :<|> communityHandler :<|> homeHandler where send f u = pure $ Wrapper $ f Model {uri = u, navMenuOpen = False} homeHandler = send home goHome examplesHandler = send examples goExamples docsHandler = send docs goDocs communityHandler = send community goCommunity
dmjio/miso
examples/haskell-miso.org/server/Main.hs
Haskell
bsd-3-clause
6,330
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="zh-CN"> <title>Replacer | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/replacer/src/main/javahelp/org/zaproxy/zap/extension/replacer/resources/help_zh_CN/helpset_zh_CN.hs
Haskell
apache-2.0
970
module Haskus.Tests.Common ( isBijective , isEquivalent , ArbitraryByteString (..) , ArbitraryByteStringNoNul (..) , ArbitraryBuffer (..) , ArbitraryBufferNoNul (..) ) where import Test.Tasty.QuickCheck as QC import qualified Data.ByteString as BS import Haskus.Format.Binary.Buffer -- | Ensure a function is bijective isBijective :: Eq a => (a -> a) -> a -> Bool isBijective f w = w == (f (f w)) -- | Ensure that two functions return the same thing for the same input isEquivalent :: Eq b => (a -> b) -> (a -> b) -> a -> Bool isEquivalent f g x = (f x) == (g x) -- | Arbitrary ByteString (50 chars long max) newtype ArbitraryByteString = ArbitraryByteString BS.ByteString deriving (Show) instance Arbitrary ArbitraryByteString where arbitrary = ArbitraryByteString . BS.pack <$> resize 50 (listOf arbitrary) shrink (ArbitraryByteString bs) | BS.null bs = [] | otherwise = [ArbitraryByteString $ BS.take (BS.length bs `div` 2) bs] -- | Arbitrary ByteString (50 chars long max, no Nul) newtype ArbitraryByteStringNoNul = ArbitraryByteStringNoNul BS.ByteString deriving (Show) instance Arbitrary ArbitraryByteStringNoNul where arbitrary = ArbitraryByteStringNoNul . BS.pack <$> resize 50 (listOf (choose (1,255))) -- we exclude 0 shrink (ArbitraryByteStringNoNul bs) | BS.null bs = [] | otherwise = [ArbitraryByteStringNoNul $ BS.take (BS.length bs `div` 2) bs] -- | Arbitrary Buffer (50 chars long max) newtype ArbitraryBuffer = ArbitraryBuffer Buffer deriving (Show) instance Arbitrary ArbitraryBuffer where arbitrary = do ArbitraryByteString bs <- arbitrary return (ArbitraryBuffer (Buffer bs)) shrink (ArbitraryBuffer bs) | isBufferEmpty bs = [] | otherwise = [ArbitraryBuffer $ bufferTake (bufferSize bs `div` 2) bs] -- | Arbitrary Buffer (50 chars long max, no Nul) newtype ArbitraryBufferNoNul = ArbitraryBufferNoNul Buffer deriving (Show) instance Arbitrary ArbitraryBufferNoNul where arbitrary = do ArbitraryByteStringNoNul bs <- arbitrary return (ArbitraryBufferNoNul (Buffer bs)) shrink (ArbitraryBufferNoNul bs) | isBufferEmpty bs = [] | otherwise = [ArbitraryBufferNoNul $ bufferTake (bufferSize bs `div` 2) bs]
hsyl20/ViperVM
haskus-system/src/tests/Haskus/Tests/Common.hs
Haskell
bsd-3-clause
2,345
-- | -- Module : Crypto.PubKey.Ed25519 -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : unknown -- -- Ed25519 support -- {-# LANGUAGE BangPatterns #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Crypto.PubKey.Ed25519 ( SecretKey , PublicKey , Signature -- * Size constants , publicKeySize , secretKeySize , signatureSize -- * Smart constructors , signature , publicKey , secretKey -- * Methods , toPublic , sign , verify , generateSecretKey ) where import Data.Word import Foreign.C.Types import Foreign.Ptr import Crypto.Error import Crypto.Internal.ByteArray (ByteArrayAccess, Bytes, ScrubbedBytes, withByteArray) import qualified Crypto.Internal.ByteArray as B import Crypto.Internal.Compat import Crypto.Internal.Imports import Crypto.Random -- | An Ed25519 Secret key newtype SecretKey = SecretKey ScrubbedBytes deriving (Show,Eq,ByteArrayAccess,NFData) -- | An Ed25519 public key newtype PublicKey = PublicKey Bytes deriving (Show,Eq,ByteArrayAccess,NFData) -- | An Ed25519 signature newtype Signature = Signature Bytes deriving (Show,Eq,ByteArrayAccess,NFData) -- | Try to build a public key from a bytearray publicKey :: ByteArrayAccess ba => ba -> CryptoFailable PublicKey publicKey bs | B.length bs == publicKeySize = CryptoPassed $ PublicKey $ B.copyAndFreeze bs (\_ -> return ()) | otherwise = CryptoFailed $ CryptoError_PublicKeySizeInvalid -- | Try to build a secret key from a bytearray secretKey :: ByteArrayAccess ba => ba -> CryptoFailable SecretKey secretKey bs | B.length bs == secretKeySize = unsafeDoIO $ withByteArray bs initialize | otherwise = CryptoFailed CryptoError_SecretKeyStructureInvalid where initialize inp = do valid <- isValidPtr inp if valid then (CryptoPassed . SecretKey) <$> B.copy bs (\_ -> return ()) else return $ CryptoFailed CryptoError_SecretKeyStructureInvalid isValidPtr _ = return True {-# NOINLINE secretKey #-} -- | Try to build a signature from a bytearray signature :: ByteArrayAccess ba => ba -> CryptoFailable Signature signature bs | B.length bs == signatureSize = CryptoPassed $ Signature $ B.copyAndFreeze bs (\_ -> return ()) | otherwise = CryptoFailed CryptoError_SecretKeyStructureInvalid -- | Create a public key from a secret key toPublic :: SecretKey -> PublicKey toPublic (SecretKey sec) = PublicKey <$> B.allocAndFreeze publicKeySize $ \result -> withByteArray sec $ \psec -> ccryptonite_ed25519_publickey psec result {-# NOINLINE toPublic #-} -- | Sign a message using the key pair sign :: ByteArrayAccess ba => SecretKey -> PublicKey -> ba -> Signature sign secret public message = Signature $ B.allocAndFreeze signatureSize $ \sig -> withByteArray secret $ \sec -> withByteArray public $ \pub -> withByteArray message $ \msg -> ccryptonite_ed25519_sign msg (fromIntegral msgLen) sec pub sig where !msgLen = B.length message -- | Verify a message verify :: ByteArrayAccess ba => PublicKey -> ba -> Signature -> Bool verify public message signatureVal = unsafeDoIO $ withByteArray signatureVal $ \sig -> withByteArray public $ \pub -> withByteArray message $ \msg -> do r <- ccryptonite_ed25519_sign_open msg (fromIntegral msgLen) pub sig return (r == 0) where !msgLen = B.length message -- | Generate a secret key generateSecretKey :: MonadRandom m => m SecretKey generateSecretKey = SecretKey <$> getRandomBytes secretKeySize -- | A public key is 32 bytes publicKeySize :: Int publicKeySize = 32 -- | A secret key is 32 bytes secretKeySize :: Int secretKeySize = 32 -- | A signature is 64 bytes signatureSize :: Int signatureSize = 64 foreign import ccall "cryptonite_ed25519_publickey" ccryptonite_ed25519_publickey :: Ptr SecretKey -- secret key -> Ptr PublicKey -- public key -> IO () foreign import ccall "cryptonite_ed25519_sign_open" ccryptonite_ed25519_sign_open :: Ptr Word8 -- message -> CSize -- message len -> Ptr PublicKey -- public -> Ptr Signature -- signature -> IO CInt foreign import ccall "cryptonite_ed25519_sign" ccryptonite_ed25519_sign :: Ptr Word8 -- message -> CSize -- message len -> Ptr SecretKey -- secret -> Ptr PublicKey -- public -> Ptr Signature -- signature -> IO ()
tekul/cryptonite
Crypto/PubKey/Ed25519.hs
Haskell
bsd-3-clause
5,061
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} module Quoter (quote, quoteFile, quoteFileReload) where import Language.Haskell.TH.Syntax import Language.Haskell.TH.Quote (QuasiQuoter (..)) #ifdef TEST_COFFEE import Text.Coffee import Text.Coffee (coffeeSettings) import Text.Shakespeare (shakespeare) #else # ifdef TEST_ROY import Text.Roy # else import Text.Julius # endif #endif quote :: QuasiQuoter quoteFile :: FilePath -> Q Exp quoteFileReload :: FilePath -> Q Exp #ifdef TEST_COFFEE translate ('#':'{':rest) = translate $ '%':'{':translate rest translate (c:other) = c:translate other translate [] = [] quote = QuasiQuoter { quoteExp = \s -> do rs <- coffeeSettings quoteExp (shakespeare rs) (translate s) } quoteFile = coffeeFile quoteFileReload = coffeeFileReload #else # ifdef TEST_ROY quote = roy quoteFile = royFile quoteFileReload = royFileReload # else quote = julius quoteFile = juliusFile quoteFileReload = juliusFileReload # endif #endif
fgaray/shakespeare
test/Quoter.hs
Haskell
mit
996
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- Determine which packages are already installed module Stack.Build.Installed ( InstalledMap , Installed (..) , GetInstalledOpts (..) , getInstalled ) where import Control.Applicative import Control.Monad import Control.Monad.Catch (MonadMask) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Resource import Data.Conduit import qualified Data.Conduit.List as CL import Data.Function import qualified Data.Foldable as F import qualified Data.HashSet as HashSet import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import qualified Data.Map.Strict as Map import Data.Maybe import Data.Maybe.Extra (mapMaybeM) import Data.Monoid import qualified Data.Text as T import Network.HTTP.Client.Conduit (HasHttpManager) import Path import Prelude hiding (FilePath, writeFile) import Stack.Build.Cache import Stack.Types.Build import Stack.Types.Version import Stack.Constants import Stack.GhcPkg import Stack.PackageDump import Stack.Types import Stack.Types.Internal type M env m = (MonadIO m,MonadReader env m,HasHttpManager env,HasEnvConfig env,MonadLogger m,MonadBaseControl IO m,MonadMask m,HasLogLevel env) -- | Options for 'getInstalled'. data GetInstalledOpts = GetInstalledOpts { getInstalledProfiling :: !Bool -- ^ Require profiling libraries? , getInstalledHaddock :: !Bool -- ^ Require haddocks? } -- | Returns the new InstalledMap and all of the locally registered packages. getInstalled :: (M env m, PackageInstallInfo pii) => EnvOverride -> GetInstalledOpts -> Map PackageName pii -- ^ does not contain any installed information -> m ( InstalledMap , [DumpPackage () ()] -- globally installed , [DumpPackage () ()] -- snapshot installed , [DumpPackage () ()] -- locally installed ) getInstalled menv opts sourceMap = do snapDBPath <- packageDatabaseDeps localDBPath <- packageDatabaseLocal extraDBPaths <- packageDatabaseExtra bconfig <- asks getBuildConfig mcache <- if getInstalledProfiling opts || getInstalledHaddock opts then liftM Just $ loadInstalledCache $ configInstalledCache bconfig else return Nothing let loadDatabase' = loadDatabase menv opts mcache sourceMap (installedLibs0, globalDumpPkgs) <- loadDatabase' Nothing [] (installedLibs1, _extraInstalled) <- (foldM (\lhs' pkgdb -> loadDatabase' (Just (ExtraGlobal, pkgdb)) (fst lhs') ) (installedLibs0, globalDumpPkgs) extraDBPaths) (installedLibs2, snapshotDumpPkgs) <- loadDatabase' (Just (InstalledTo Snap, snapDBPath)) installedLibs1 (installedLibs3, localDumpPkgs) <- loadDatabase' (Just (InstalledTo Local, localDBPath)) installedLibs2 let installedLibs = M.fromList $ map lhPair installedLibs3 F.forM_ mcache (saveInstalledCache (configInstalledCache bconfig)) -- Add in the executables that are installed, making sure to only trust a -- listed installation under the right circumstances (see below) let exesToSM loc = Map.unions . map (exeToSM loc) exeToSM loc (PackageIdentifier name version) = case Map.lookup name sourceMap of -- Doesn't conflict with anything, so that's OK Nothing -> m Just pii -- Not the version we want, ignore it | version /= piiVersion pii || loc /= piiLocation pii -> Map.empty | otherwise -> m where m = Map.singleton name (loc, Executable $ PackageIdentifier name version) exesSnap <- getInstalledExes Snap exesLocal <- getInstalledExes Local let installedMap = Map.unions [ exesToSM Local exesLocal , exesToSM Snap exesSnap , installedLibs ] return ( installedMap , globalDumpPkgs , snapshotDumpPkgs , localDumpPkgs ) -- | Outputs both the modified InstalledMap and the Set of all installed packages in this database -- -- The goal is to ascertain that the dependencies for a package are present, -- that it has profiling if necessary, and that it matches the version and -- location needed by the SourceMap loadDatabase :: (M env m, PackageInstallInfo pii) => EnvOverride -> GetInstalledOpts -> Maybe InstalledCache -- ^ if Just, profiling or haddock is required -> Map PackageName pii -- ^ to determine which installed things we should include -> Maybe (InstalledPackageLocation, Path Abs Dir) -- ^ package database, Nothing for global -> [LoadHelper] -- ^ from parent databases -> m ([LoadHelper], [DumpPackage () ()]) loadDatabase menv opts mcache sourceMap mdb lhs0 = do wc <- getWhichCompiler (lhs1', dps) <- ghcPkgDump menv wc (fmap snd (maybeToList mdb)) $ conduitDumpPackage =$ sink let ghcjsHack = wc == Ghcjs && isNothing mdb lhs1 <- mapMaybeM (processLoadResult mdb ghcjsHack) lhs1' let lhs = pruneDeps id lhId lhDeps const (lhs0 ++ lhs1) return (map (\lh -> lh { lhDeps = [] }) $ Map.elems lhs, dps) where conduitProfilingCache = case mcache of Just cache | getInstalledProfiling opts -> addProfiling cache -- Just an optimization to avoid calculating the profiling -- values when they aren't necessary _ -> CL.map (\dp -> dp { dpProfiling = False }) conduitHaddockCache = case mcache of Just cache | getInstalledHaddock opts -> addHaddock cache -- Just an optimization to avoid calculating the haddock -- values when they aren't necessary _ -> CL.map (\dp -> dp { dpHaddock = False }) mloc = fmap fst mdb sinkDP = conduitProfilingCache =$ conduitHaddockCache =$ CL.map (\dp -> (isAllowed opts mcache sourceMap mloc dp, toLoadHelper mloc dp)) =$ CL.consume sink = getZipSink $ (,) <$> ZipSink sinkDP <*> ZipSink CL.consume processLoadResult :: MonadLogger m => Maybe (InstalledPackageLocation, Path Abs Dir) -> Bool -> (Allowed, LoadHelper) -> m (Maybe LoadHelper) processLoadResult _ _ (Allowed, lh) = return (Just lh) processLoadResult _ True (WrongVersion actual wanted, lh) -- Allow some packages in the ghcjs global DB to have the wrong -- versions. Treat them as wired-ins by setting deps to []. | fst (lhPair lh) `HashSet.member` ghcjsBootPackages = do $logWarn $ T.concat [ "Ignoring that the GHCJS boot package \"" , packageNameText (fst (lhPair lh)) , "\" has a different version, " , versionText actual , ", than the resolver's wanted version, " , versionText wanted ] return (Just lh) processLoadResult mdb _ (reason, lh) = do $logDebug $ T.concat $ [ "Ignoring package " , packageNameText (fst (lhPair lh)) ] ++ maybe [] (\db -> [", from ", T.pack (show db), ","]) mdb ++ [ " due to" , case reason of Allowed -> " the impossible?!?!" NeedsProfiling -> " it needing profiling." NeedsHaddock -> " it needing haddocks." UnknownPkg -> " it being unknown to the resolver / extra-deps." WrongLocation mloc loc -> " wrong location: " <> T.pack (show (mloc, loc)) WrongVersion actual wanted -> T.concat [ " wanting version " , versionText wanted , " instead of " , versionText actual ] ] return Nothing data Allowed = Allowed | NeedsProfiling | NeedsHaddock | UnknownPkg | WrongLocation (Maybe InstalledPackageLocation) InstallLocation | WrongVersion Version Version deriving (Eq, Show) -- | Check if a can be included in the set of installed packages or not, based -- on the package selections made by the user. This does not perform any -- dirtiness or flag change checks. isAllowed :: PackageInstallInfo pii => GetInstalledOpts -> Maybe InstalledCache -> Map PackageName pii -> Maybe InstalledPackageLocation -> DumpPackage Bool Bool -> Allowed isAllowed opts mcache sourceMap mloc dp -- Check that it can do profiling if necessary | getInstalledProfiling opts && isJust mcache && not (dpProfiling dp) = NeedsProfiling -- Check that it has haddocks if necessary | getInstalledHaddock opts && isJust mcache && not (dpHaddock dp) = NeedsHaddock | otherwise = case Map.lookup name sourceMap of Nothing -> case mloc of -- The sourceMap has nothing to say about this global -- package, so we can use it Nothing -> Allowed Just ExtraGlobal -> Allowed -- For non-global packages, don't include unknown packages. -- See: -- https://github.com/commercialhaskell/stack/issues/292 Just _ -> UnknownPkg Just pii | not (checkLocation (piiLocation pii)) -> WrongLocation mloc (piiLocation pii) | version /= piiVersion pii -> WrongVersion version (piiVersion pii) | otherwise -> Allowed where PackageIdentifier name version = dpPackageIdent dp -- Ensure that the installed location matches where the sourceMap says it -- should be installed checkLocation Snap = mloc /= Just (InstalledTo Local) -- we can allow either global or snap checkLocation Local = mloc == Just (InstalledTo Local) || mloc == Just ExtraGlobal -- 'locally' installed snapshot packages can come from extra dbs data LoadHelper = LoadHelper { lhId :: !GhcPkgId , lhDeps :: ![GhcPkgId] , lhPair :: !(PackageName, (InstallLocation, Installed)) } deriving Show toLoadHelper :: Maybe InstalledPackageLocation -> DumpPackage Bool Bool -> LoadHelper toLoadHelper mloc dp = LoadHelper { lhId = gid , lhDeps = -- We always want to consider the wired in packages as having all -- of their dependencies installed, since we have no ability to -- reinstall them. This is especially important for using different -- minor versions of GHC, where the dependencies of wired-in -- packages may change slightly and therefore not match the -- snapshot. if name `HashSet.member` wiredInPackages then [] else dpDepends dp , lhPair = (name, (toPackageLocation mloc, Library ident gid)) } where gid = dpGhcPkgId dp ident@(PackageIdentifier name _) = dpPackageIdent dp toPackageLocation :: Maybe InstalledPackageLocation -> InstallLocation toPackageLocation Nothing = Snap toPackageLocation (Just ExtraGlobal) = Snap toPackageLocation (Just (InstalledTo loc)) = loc
phadej/stack
src/Stack/Build/Installed.hs
Haskell
bsd-3-clause
11,896
----------------------------------------------------------------------------- -- -- GHCi's :ctags and :etags commands -- -- (c) The GHC Team 2005-2007 -- ----------------------------------------------------------------------------- {-# OPTIONS_GHC -fno-warn-name-shadowing #-} module GHCi.UI.Tags ( createCTagsWithLineNumbersCmd, createCTagsWithRegExesCmd, createETagsFileCmd ) where import Exception import GHC import GHCi.UI.Monad import Outputable -- ToDo: figure out whether we need these, and put something appropriate -- into the GHC API instead import Name (nameOccName) import OccName (pprOccName) import ConLike import MonadUtils import Control.Monad import Data.Function import Data.List import Data.Maybe import Data.Ord import DriverPhases import Panic import Prelude import System.Directory import System.IO import System.IO.Error ----------------------------------------------------------------------------- -- create tags file for currently loaded modules. createCTagsWithLineNumbersCmd, createCTagsWithRegExesCmd, createETagsFileCmd :: String -> GHCi () createCTagsWithLineNumbersCmd "" = ghciCreateTagsFile CTagsWithLineNumbers "tags" createCTagsWithLineNumbersCmd file = ghciCreateTagsFile CTagsWithLineNumbers file createCTagsWithRegExesCmd "" = ghciCreateTagsFile CTagsWithRegExes "tags" createCTagsWithRegExesCmd file = ghciCreateTagsFile CTagsWithRegExes file createETagsFileCmd "" = ghciCreateTagsFile ETags "TAGS" createETagsFileCmd file = ghciCreateTagsFile ETags file data TagsKind = ETags | CTagsWithLineNumbers | CTagsWithRegExes ghciCreateTagsFile :: TagsKind -> FilePath -> GHCi () ghciCreateTagsFile kind file = do createTagsFile kind file -- ToDo: -- - remove restriction that all modules must be interpreted -- (problem: we don't know source locations for entities unless -- we compiled the module. -- -- - extract createTagsFile so it can be used from the command-line -- (probably need to fix first problem before this is useful). -- createTagsFile :: TagsKind -> FilePath -> GHCi () createTagsFile tagskind tagsFile = do graph <- GHC.getModuleGraph mtags <- mapM listModuleTags (map GHC.ms_mod $ GHC.mgModSummaries graph) either_res <- liftIO $ collateAndWriteTags tagskind tagsFile $ concat mtags case either_res of Left e -> liftIO $ hPutStrLn stderr $ ioeGetErrorString e Right _ -> return () listModuleTags :: GHC.Module -> GHCi [TagInfo] listModuleTags m = do is_interpreted <- GHC.moduleIsInterpreted m -- should we just skip these? when (not is_interpreted) $ let mName = GHC.moduleNameString (GHC.moduleName m) in throwGhcException (CmdLineError ("module '" ++ mName ++ "' is not interpreted")) mbModInfo <- GHC.getModuleInfo m case mbModInfo of Nothing -> return [] Just mInfo -> do dflags <- getDynFlags mb_print_unqual <- GHC.mkPrintUnqualifiedForModule mInfo let unqual = fromMaybe GHC.alwaysQualify mb_print_unqual let names = fromMaybe [] $GHC.modInfoTopLevelScope mInfo let localNames = filter ((m==) . nameModule) names mbTyThings <- mapM GHC.lookupName localNames return $! [ tagInfo dflags unqual exported kind name realLoc | tyThing <- catMaybes mbTyThings , let name = getName tyThing , let exported = GHC.modInfoIsExportedName mInfo name , let kind = tyThing2TagKind tyThing , let loc = srcSpanStart (nameSrcSpan name) , RealSrcLoc realLoc <- [loc] ] where tyThing2TagKind (AnId _) = 'v' tyThing2TagKind (AConLike RealDataCon{}) = 'd' tyThing2TagKind (AConLike PatSynCon{}) = 'p' tyThing2TagKind (ATyCon _) = 't' tyThing2TagKind (ACoAxiom _) = 'x' data TagInfo = TagInfo { tagExported :: Bool -- is tag exported , tagKind :: Char -- tag kind , tagName :: String -- tag name , tagFile :: String -- file name , tagLine :: Int -- line number , tagCol :: Int -- column number , tagSrcInfo :: Maybe (String,Integer) -- source code line and char offset } -- get tag info, for later translation into Vim or Emacs style tagInfo :: DynFlags -> PrintUnqualified -> Bool -> Char -> Name -> RealSrcLoc -> TagInfo tagInfo dflags unqual exported kind name loc = TagInfo exported kind (showSDocForUser dflags unqual $ pprOccName (nameOccName name)) (showSDocForUser dflags unqual $ ftext (srcLocFile loc)) (srcLocLine loc) (srcLocCol loc) Nothing -- throw an exception when someone tries to overwrite existing source file (fix for #10989) writeTagsSafely :: FilePath -> String -> IO () writeTagsSafely file str = do dfe <- doesFileExist file if dfe && isSourceFilename file then throwGhcException (CmdLineError (file ++ " is existing source file. " ++ "Please specify another file name to store tags data")) else writeFile file str collateAndWriteTags :: TagsKind -> FilePath -> [TagInfo] -> IO (Either IOError ()) -- ctags style with the Ex expression being just the line number, Vim et al collateAndWriteTags CTagsWithLineNumbers file tagInfos = do let tags = unlines $ sort $ map showCTag tagInfos tryIO (writeTagsSafely file tags) -- ctags style with the Ex expression being a regex searching the line, Vim et al collateAndWriteTags CTagsWithRegExes file tagInfos = do -- ctags style, Vim et al tagInfoGroups <- makeTagGroupsWithSrcInfo tagInfos let tags = unlines $ sort $ map showCTag $concat tagInfoGroups tryIO (writeTagsSafely file tags) collateAndWriteTags ETags file tagInfos = do -- etags style, Emacs/XEmacs tagInfoGroups <- makeTagGroupsWithSrcInfo $filter tagExported tagInfos let tagGroups = map processGroup tagInfoGroups tryIO (writeTagsSafely file $ concat tagGroups) where processGroup [] = throwGhcException (CmdLineError "empty tag file group??") processGroup group@(tagInfo:_) = let tags = unlines $ map showETag group in "\x0c\n" ++ tagFile tagInfo ++ "," ++ show (length tags) ++ "\n" ++ tags makeTagGroupsWithSrcInfo :: [TagInfo] -> IO [[TagInfo]] makeTagGroupsWithSrcInfo tagInfos = do let groups = groupBy ((==) `on` tagFile) $ sortBy (comparing tagFile) tagInfos mapM addTagSrcInfo groups where addTagSrcInfo [] = throwGhcException (CmdLineError "empty tag file group??") addTagSrcInfo group@(tagInfo:_) = do file <- readFile $tagFile tagInfo let sortedGroup = sortBy (comparing tagLine) group return $ perFile sortedGroup 1 0 $ lines file perFile allTags@(tag:tags) cnt pos allLs@(l:ls) | tagLine tag > cnt = perFile allTags (cnt+1) (pos+fromIntegral(length l)) ls | tagLine tag == cnt = tag{ tagSrcInfo = Just(l,pos) } : perFile tags cnt pos allLs perFile _ _ _ _ = [] -- ctags format, for Vim et al showCTag :: TagInfo -> String showCTag ti = tagName ti ++ "\t" ++ tagFile ti ++ "\t" ++ tagCmd ++ ";\"\t" ++ tagKind ti : ( if tagExported ti then "" else "\tfile:" ) where tagCmd = case tagSrcInfo ti of Nothing -> show $tagLine ti Just (srcLine,_) -> "/^"++ foldr escapeSlashes [] srcLine ++"$/" where escapeSlashes '/' r = '\\' : '/' : r escapeSlashes '\\' r = '\\' : '\\' : r escapeSlashes c r = c : r -- etags format, for Emacs/XEmacs showETag :: TagInfo -> String showETag TagInfo{ tagName = tag, tagLine = lineNo, tagCol = colNo, tagSrcInfo = Just (srcLine,charPos) } = take (colNo - 1) srcLine ++ tag ++ "\x7f" ++ tag ++ "\x01" ++ show lineNo ++ "," ++ show charPos showETag _ = throwGhcException (CmdLineError "missing source file info in showETag")
sdiehl/ghc
ghc/GHCi/UI/Tags.hs
Haskell
bsd-3-clause
7,831
import Test.Cabal.Prelude main = setupTest $ do -- No cabal test because per-component is broken with it skipUnless =<< ghcVersionIs (>= mkVersion [8,1]) withPackageDb $ do let setup_install' args = setup_install_with_docs (["--cabal-file", "Includes2.cabal"] ++ args) setup_install' ["mylib", "--cid", "mylib-0.1.0.0"] setup_install' ["mysql", "--cid", "mysql-0.1.0.0"] setup_install' ["postgresql", "--cid", "postgresql-0.1.0.0"] setup_install' ["mylib", "--cid", "mylib-0.1.0.0", "--instantiate-with", "Database=mysql-0.1.0.0:Database.MySQL"] setup_install' ["mylib", "--cid", "mylib-0.1.0.0", "--instantiate-with", "Database=postgresql-0.1.0.0:Database.PostgreSQL"] setup_install' ["Includes2"] setup_install' ["exe"] runExe' "exe" [] >>= assertOutputContains "minemysql minepostgresql"
mydaum/cabal
cabal-testsuite/PackageTests/Backpack/Includes2/setup-per-component.test.hs
Haskell
bsd-3-clause
899
----------------------------------------------------------------------------- -- -- Module : Main -- Copyright : (c) Phil Freeman 2013 -- License : MIT -- -- Maintainer : Phil Freeman <paf31@cantab.net> -- Stability : experimental -- Portability : -- -- | -- ----------------------------------------------------------------------------- {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Main where import Control.Applicative import Control.Monad.Error import Data.Version (showVersion) import System.Console.CmdTheLine import System.Directory (doesFileExist, getModificationTime, createDirectoryIfMissing) import System.FilePath (takeDirectory) import System.Exit (exitSuccess, exitFailure) import System.IO.Error (tryIOError) import Text.Parsec (ParseError) import qualified Language.PureScript as P import qualified Paths_purescript as Paths import qualified System.IO.UTF8 as U preludeFilename :: IO FilePath preludeFilename = Paths.getDataFileName "prelude/prelude.purs" readInput :: [FilePath] -> IO (Either ParseError [(FilePath, P.Module)]) readInput input = fmap collect $ forM input $ \inputFile -> do text <- U.readFile inputFile return $ (inputFile, P.runIndentParser inputFile P.parseModules text) where collect :: [(FilePath, Either ParseError [P.Module])] -> Either ParseError [(FilePath, P.Module)] collect = fmap concat . sequence . map (\(fp, e) -> fmap (map ((,) fp)) e) newtype Make a = Make { unMake :: ErrorT String IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadError String) runMake :: Make a -> IO (Either String a) runMake = runErrorT . unMake makeIO :: IO a -> Make a makeIO = Make . ErrorT . fmap (either (Left . show) Right) . tryIOError instance P.MonadMake Make where getTimestamp path = makeIO $ do exists <- doesFileExist path case exists of True -> Just <$> getModificationTime path False -> return Nothing readTextFile path = makeIO $ do U.putStrLn $ "Reading " ++ path U.readFile path writeTextFile path text = makeIO $ do mkdirp path U.putStrLn $ "Writing " ++ path U.writeFile path text liftError = either throwError return progress = makeIO . U.putStrLn compile :: FilePath -> P.Options -> [FilePath] -> IO () compile outputDir opts input = do modules <- readInput input case modules of Left err -> do U.print err exitFailure Right ms -> do e <- runMake $ P.make outputDir opts ms case e of Left err -> do U.putStrLn err exitFailure Right _ -> do exitSuccess mkdirp :: FilePath -> IO () mkdirp = createDirectoryIfMissing True . takeDirectory inputFiles :: Term [FilePath] inputFiles = value $ posAny [] $ posInfo { posDoc = "The input .ps files" } outputDirectory :: Term FilePath outputDirectory = value $ opt "output" $ (optInfo [ "o", "output" ]) { optDoc = "The output directory" } noTco :: Term Bool noTco = value $ flag $ (optInfo [ "no-tco" ]) { optDoc = "Disable tail call optimizations" } performRuntimeTypeChecks :: Term Bool performRuntimeTypeChecks = value $ flag $ (optInfo [ "runtime-type-checks" ]) { optDoc = "Generate runtime type checks" } noPrelude :: Term Bool noPrelude = value $ flag $ (optInfo [ "no-prelude" ]) { optDoc = "Omit the Prelude" } noMagicDo :: Term Bool noMagicDo = value $ flag $ (optInfo [ "no-magic-do" ]) { optDoc = "Disable the optimization that overloads the do keyword to generate efficient code specifically for the Eff monad." } noOpts :: Term Bool noOpts = value $ flag $ (optInfo [ "no-opts" ]) { optDoc = "Skip the optimization phase." } verboseErrors :: Term Bool verboseErrors = value $ flag $ (optInfo [ "v", "verbose-errors" ]) { optDoc = "Display verbose error messages" } options :: Term P.Options options = P.Options <$> noPrelude <*> noTco <*> performRuntimeTypeChecks <*> noMagicDo <*> pure Nothing <*> noOpts <*> pure Nothing <*> pure [] <*> pure [] <*> verboseErrors inputFilesAndPrelude :: FilePath -> Term [FilePath] inputFilesAndPrelude prelude = combine <$> (not <$> noPrelude) <*> inputFiles where combine True input = prelude : input combine False input = input term :: FilePath -> Term (IO ()) term prelude = compile <$> outputDirectory <*> options <*> inputFilesAndPrelude prelude termInfo :: TermInfo termInfo = defTI { termName = "psc-make" , version = showVersion Paths.version , termDoc = "Compiles PureScript to Javascript" } main :: IO () main = do prelude <- preludeFilename run (term prelude, termInfo)
bergmark/purescript
psc-make/Main.hs
Haskell
mit
4,586
module Graphics.CG.Algorithms.PointInTriangle(pointInTriangle) where import Graphics.CG.Algorithms.Rotate import Graphics.CG.Primitives.Triangle import Graphics.Gloss.Data.Point pointInTriangle :: Point -> Triangle -> Bool pointInTriangle p (p1, p2, p3) = (c1 >= 0 && c2 >= 0 && c3 >= 0) || (c1 <= 0 && c2 <= 0 && c3 <= 0) where c1 = fromEnum $ orientation p p1 p2 c2 = fromEnum $ orientation p p2 p3 c3 = fromEnum $ orientation p p3 p1
jagajaga/CG-Haskell
Graphics/CG/Algorithms/PointInTriangle.hs
Haskell
mit
497
{-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds, PolyKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE RankNTypes, ScopedTypeVariables #-} {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TemplateHaskell #-} module List where import Data.Vinyl import Data.Type.Equality import Nats import Data.Singletons.Prelude import Data.Singletons.TH {- data SList l where SNil' :: SList '[] SCons' :: Sing a -> SList l -> SList (a ': l) slist :: forall l. SingI l => SList l slist = case sing :: Sing l of SNil -> SNil' SCons -> SCons' sing slist -} --class Offset -- an index n into l such that l[n] = a data Index (l :: [k]) a where ZIndex :: Index (t ': l) t SIndex :: Index l t -> Index (a ': l) t index :: Index l a -> Rec f l -> f a index ZIndex (a :& _) = a index (SIndex i) (_ :& l) = index i l instance TestEquality (Index l) where testEquality ZIndex ZIndex = Just Refl testEquality (SIndex i) (SIndex j) = do Refl <- testEquality i j return Refl testEquality _ _ = Nothing indices :: SList l -> Rec (Index l) l indices SNil = RNil indices (SCons _ l) = ZIndex :& rmap SIndex (indices l) class Find l a where find :: Index l a instance {-# OVERLAPS #-} Find (a ': l) a where find = ZIndex instance Find l a => Find (b ': l) a where find = SIndex find $(singletons [d| len :: [a] -> Nat len [] = Z len (x:xs) = S (len xs) |])
vladfi1/hs-misc
List.hs
Haskell
mit
1,470
import Base.Scene import Base.Camera import Base.Image import SphereScene main = do save 500 500 5
burz/Rayzer
Rayzer.hs
Haskell
mit
106
module Main where import Parser import Environment import Eval import PrettyPrint import System.Environment import Text.PrettyPrint.ANSI.Leijen import System.Exit import System.Directory main :: IO () main = do args <- getArgs if null args then do putDoc $ red (text "Error") <> text ": you did not enter a filename\n" exitFailure else do let file = head args found <- doesFileExist file if found then do process file exitSuccess else do putDoc $ red (text "Error") <> text ": file " <> dullgreen (text file) <> text " does not exist\n" exitFailure process :: FilePath -> IO () process path = do contents <- readFile path let res = parseProgram contents (lines contents) case res of Left err -> print err Right r' -> mapM_ (\(x, y) -> putDoc $ display x <> red (text " ⇒ ") <> display (eval' y) <> hardline) (zip (lines contents) r') where eval' = typeAndEval emptyEnv
kellino/TypeSystems
fullSimple/Main.hs
Haskell
mit
1,099
module Exploration.Logic.ManyValued where -- | A Many Valued logic is an algebraic -- | structure (m, (^), not, false), satisfying: -- (^) associative, commutative -- false neutral to (^) -- not (not x) = x -- x ^ (not false) = not false -- not (not x ^ y) ^ y = not (not y ^ x) ^ x class ManyValued m where (<+>) :: m -> m -> m false :: m not :: m -> m
SamuelSchlesinger/Exploration
Exploration/Logic/ManyValued.hs
Haskell
mit
396
module Coins where import Data.Ord import Data.Set (Set) import qualified Data.Set as Set ---------------------------------------- type Coin = Integer data CoinSet = CoinSet { face :: Coin, count :: Integer } instance Show CoinSet where show (CoinSet face count) = show face ++ "x" ++ show count instance Eq CoinSet where x == y = (face x == face y && count x == count y) instance Ord CoinSet where compare = (comparing face) `mappend` (comparing count) ---------------------------------------- type Change = Set CoinSet -- instance Ord CoinSet where -- compare = (comparing face) `mappend` (comparing count)
kirhgoff/haskell-sandbox
euler31/Coins.hs
Haskell
mit
629
{-# LANGUAGE TypeOperators , FlexibleContexts , TypeFamilies , UndecidableInstances #-} module Calculus.Connectives.Linear where import Calculus.Expr import Calculus.Connectives.Simple import Auxiliary.NameSource import Data.Functor import Control.Monad.State -- Simultaneous conjunction data SimConj f = SimConj f f -- Alternative conjunction data AltConj f = AltConj f f -- Disjunction (external choice) data Disj f = Disj f f -- Linear implication (resource implication) data ResImpl f = ResImpl f f -- Unrestricted implication data ValImpl f = ValImpl f f -- Unit (trivial goal which requires no resources) data Unit f = Unit -- Top (trivial goal which consumes all resources) data Top f = Top -- Zero (impossibility) data Zero f = Zero -- Modal operation (states that `f` is valid) data Modal f = Modal f {- LinearInput. -} type LinearInput = SimConj :+: AltConj :+: Disj :+: ResImpl :+: ValImpl :+: Unit :+: Top :+: Zero :+: Modal :+: SimpleInput type LinearFormula = Formula LinearInput {- Functor instances. -} instance Functor SimConj where fmap f (SimConj a b) = SimConj (f a) (f b) instance Functor AltConj where fmap f (AltConj a b) = AltConj (f a) (f b) instance Functor Disj where fmap f (Disj a b) = Disj (f a) (f b) instance Functor ResImpl where fmap f (ResImpl a b) = ResImpl (f a) (f b) instance Functor ValImpl where fmap f (ValImpl a b) = ValImpl (f a) (f b) instance Functor Unit where fmap _ Unit = Unit instance Functor Top where fmap _ Top = Top instance Functor Zero where fmap _ Zero = Zero instance Functor Modal where fmap f (Modal g) = Modal (f g) {- Smart constructors. -} (&&:) :: (SimConj :<: f) => Expr f -> Expr f -> Expr f (&&:) f = inject . SimConj f ($$:) :: (AltConj :<: f) => Expr f -> Expr f -> Expr f ($$:) f = inject . AltConj f (||:) :: (Disj :<: f) => Expr f -> Expr f -> Expr f (||:) f = inject . Disj f (->:) :: (ResImpl :<: f) => Expr f -> Expr f -> Expr f (->:) f = inject . ResImpl f (=>:) :: (ValImpl :<: f) => Expr f -> Expr f -> Expr f (=>:) f = inject . ValImpl f unit :: (Unit :<: f) => Expr f unit = inject Unit top :: (Top :<: f) => Expr f top = inject Top zero :: (Zero :<: f) => Expr f zero = inject Zero modal :: (Modal :<: f) => Expr f -> Expr f modal = inject . Modal {- Lists of synchronious and asynchronious connectives -} type RightAsyncInput = ResImpl :+: ValImpl :+: AltConj :+: Top :+: ForAll type RightSyncInput = SimConj :+: Unit :+: Disj :+: Zero :+: Modal :+: Exists type LeftAsyncInput = RightSyncInput type LeftSyncInput = RightAsyncInput {- Render -} instance Render SimConj where render (SimConj a b) = renderBinOp "&&" (a, b) instance Render AltConj where render (AltConj a b) = renderBinOp "$$" (a, b) instance Render Disj where render (Disj a b) = renderBinOp "||" (a, b) instance Render ResImpl where render (ResImpl a b) = renderBinOp "->" (a, b) instance Render ValImpl where render (ValImpl a b) = renderBinOp "=>" (a, b) instance Render Unit where render Unit = return "1" instance Render Top where render Top = return "T" instance Render Zero where render Zero = return "0" instance Render Modal where render (Modal a) = do ns <- get return $ "!" ++ pretty ns a
wowofbob/calculus
Calculus/Connectives/Linear.hs
Haskell
mit
3,367
module Jira.API.Authentication.KeyUtils where import Control.Applicative import Crypto.Types.PubKey.RSA (PrivateKey (..), PublicKey (..)) import Data.Maybe import OpenSSL.EVP.PKey (toKeyPair, toPublicKey) import OpenSSL.PEM (PemPasswordSupply (..), readPrivateKey, readPublicKey) import OpenSSL.RSA openSslRsaPrivateKeyFromPem :: String -> IO RSAKeyPair openSslRsaPrivateKeyFromPem pemString = fromJust . toKeyPair <$> readPrivateKey pemString PwNone openSslRsaPublicKeyFromPem :: String -> IO RSAPubKey openSslRsaPublicKeyFromPem pemString = fromJust . toPublicKey <$> readPublicKey pemString fromOpenSslPrivateKey :: RSAKeyPair -> PrivateKey fromOpenSslPrivateKey rsaKey = let publicKey = fromOpenSslPublicKey rsaKey in PrivateKey publicKey (rsaD rsaKey) 0 0 0 0 0 fromOpenSslPublicKey :: RSAKey k => k -> PublicKey fromOpenSslPublicKey rsaKey = PublicKey (rsaSize rsaKey) (rsaN rsaKey) (rsaE rsaKey) readPemPrivateKey :: String -> IO PrivateKey readPemPrivateKey = fmap fromOpenSslPrivateKey . openSslRsaPrivateKeyFromPem readPemPublicKey :: String -> IO PublicKey readPemPublicKey = fmap fromOpenSslPublicKey . openSslRsaPublicKeyFromPem
dsmatter/jira-api
src/Jira/API/Authentication/KeyUtils.hs
Haskell
mit
1,275
module PutJson where import Data.List (intercalate) import SimpleJSON renderJValue :: JValue -> String renderJValue (JString s) = show s renderJValue (JNumber n) = show n renderJValue (JBool True) = "true" renderJValue (JBool False) = "false" renderJValue JNull = "null" renderJValue (JObject o) = "{" ++ pairs o ++ "}" where pairs [] = "" pairs ps = intercalate ", " $ map renderPair ps renderPair (k, v) = show k ++ ": " ++ renderJValue v renderJValue (JArray a) = "[" ++ values a ++ "]" where values [] = "" values vs = intercalate ", " $ map renderJValue vs putJValue :: JValue -> IO() putJValue v = putStrLn (renderJValue v)
EricYT/Haskell
src/real_haskell/chapter-5/PutJSON.hs
Haskell
apache-2.0
682
module Code30_Parity where import Code30_Loopless hiding (bop,wop) data Spider' = Node' (Bool,Bool) Int [Leg'] data Leg' = Dn' Spider' | Up' Spider' decorate :: Spider -> Spider' decorate (Node a legs) = node' a (map (mapLeg decorate) legs) mapLeg :: (Spider -> Spider') -> Leg -> Leg' mapLeg f (Up x) = Up' (f x) mapLeg f (Dn x) = Dn' (f x) node' :: Int -> [Leg'] -> Spider' node' a legs = Node' (foldr op (True,True) legs) a legs op :: Leg' -> (Bool, Bool) -> (Bool, Bool) op (Up' (Node' (w,b) _ _)) (w',b') = (w /= b && w', b && b') op (Dn' (Node' (w,b) _ _)) (w',b') = (w && w', w /= b && b') bop,wop :: Leg' -> [Int] -> [Int] bop (Up' (Node' (_,b) _ legs)) cs = reverse (foldr bop (revif b cs) legs) bop (Dn' (Node' (w,_) a legs)) cs = foldr wop (revif (not w ) cs) legs ++ [a] ++ foldr bop (revif w cs) legs wop (Up' (Node' (_,b) a legs)) cs = foldr wop (revif b cs) legs ++ [a] ++ foldr bop (revif (not b) cs) legs wop (Dn' (Node' (w,_) _ legs)) cs = reverse (foldr wop (revif w cs) legs) revif :: Bool -> [a] -> [a] revif b cs = if b then reverse cs else cs
sampou-org/pfad
Code/Code30_Parity.hs
Haskell
bsd-3-clause
1,164
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} -- | This module contains responses from Telegram Bot API module Web.Telegram.API.Bot.Responses ( -- * Types Response (..) , ResponseParameters (..) , GetMeResponse , MessageResponse , ChatActionResponse , UpdatesResponse , FileResponse , UserProfilePhotosResponse , SetWebhookResponse , InlineQueryResponse , CallbackQueryResponse , KickChatMemberResponse , LeaveChatResponse , UnbanChatMemberResponse , GetChatResponse , GetChatAdministratorsResponse , GetChatMembersCountResponse , GetChatMemberResponse , GetWebhookInfoResponse ) where import Data.Aeson import GHC.Generics import Web.Telegram.API.Bot.Data import Web.Telegram.API.Bot.JsonExt data Response a = Response { result :: a , parameters :: Maybe ResponseParameters } deriving (Show, Generic, FromJSON) data ResponseParameters = ResponseParameters { res_migrate_to_chat_id :: Maybe Int -- ^ The group has been migrated to a supergroup with the specified identifier. This number may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier. , res_retry_after :: Maybe Int -- ^ In case of exceeding flood control, the number of seconds left to wait before the request can be repeated } deriving (Show, Generic) instance FromJSON ResponseParameters where parseJSON = parseJsonDrop 4 -- | This object represents 'getMe' response type GetMeResponse = Response User -- | This object represents message response type MessageResponse = Response Message -- | This object represents 'sendChatAction' response type ChatActionResponse = Response Bool -- | This object represents 'getUpdates' response type UpdatesResponse = Response [Update] -- | This object represents file response type FileResponse = Response File -- | This object represents user profile photos response type UserProfilePhotosResponse = Response UserProfilePhotos -- | This object represents 'setWebhook' response type SetWebhookResponse = Response Bool -- | This object represents 'answerInlineQuery' response type InlineQueryResponse = Response Bool -- | This object represents 'answerCallbackQuery' response type CallbackQueryResponse = Response Bool -- | This object represents 'kickChatMember' response type KickChatMemberResponse = Response Bool type LeaveChatResponse = Response Bool -- | This object represents 'unbanChatMember' response type UnbanChatMemberResponse = Response Bool type GetChatResponse = Response Chat type GetChatAdministratorsResponse = Response [ChatMember] type GetChatMembersCountResponse = Response Int type GetChatMemberResponse = Response ChatMember type GetWebhookInfoResponse = Response WebhookInfo
cblp/haskell-telegram-api
src/Web/Telegram/API/Bot/Responses.hs
Haskell
bsd-3-clause
3,059
module Graphics.UI.WX.Turtle.Move( -- * types Field, Coordinates(..), -- * process Field openField, closeField, waitField, topleft, center, coordinates, fieldSize, -- * draws forkField, flushField, clearLayer, clearCharacter, moveTurtle, -- * event oninputtext, onclick, onrelease, ondrag, onmotion, onkeypress, ontimer, addLayer, addCharacter ) where import Graphics.UI.WX.Turtle.State(TurtleState(..), makeShape) import Graphics.UI.WX.Turtle.Field( Field, Layer, Character, Coordinates(..), openField, closeField, waitField, coordinates, topleft, center, fieldSize, forkField, flushField, clearLayer, clearCharacter, addLayer, addCharacter, oninputtext, onclick, onrelease, ondrag, onmotion, onkeypress, ontimer, fieldColor, drawLine, fillRectangle, fillPolygon, writeString, drawImage, undoField, undoLayer, drawCharacter, drawCharacterAndLine) import Text.XML.YJSVG(SVG(..), Position(..), Font(..), FontWeight(..)) import qualified Text.XML.YJSVG as S(topleft) import Control.Concurrent(threadDelay) import Control.Monad(when, unless, forM_) import Control.Monad.Tools(unlessM) import Data.Maybe(isJust) -------------------------------------------------------------------------------- moveTurtle :: Field -> Character -> Layer -> TurtleState -> TurtleState -> IO () moveTurtle _ _ _ _ TurtleState{sleep = Just t} = threadDelay $ 1000 * t moveTurtle f _ _ _ TurtleState{flush = True} = flushField f True $ return () moveTurtle f c l t0 t1 = do (w, h) <- fieldSize f when (undo t1) $ fl $ do when (clear t0) redraw when (isJust $ draw t0) $ do -- unlessM (undoLayer l) $ clearLayer l >> redraw undoField f when (visible t1) $ drawTtl (direction t0) $ position t0 when (visible t1) $ do forM_ (directions t0 t1) $ \dir -> fl $ drawTtl dir (position t0) >> threadDelay (interval t0) forM_ (positions w h t0 t1) $ \p -> fl $ drawTtl (direction t1) p >> threadDelay (interval t0) fl $ drawTtl (direction t1) $ position t1 when (visible t0 && not (visible t1)) $ fl $ clearCharacter c when (clear t1) $ fl $ clearLayer l unless (undo t1) $ fl $ maybe (return ()) (drawSVG f l) (draw t1) where fl = flushField f $ stepbystep t0 redraw = mapM_ (drawSVG f l) $ reverse $ drawed t1 drawTtl dir pos = drawTurtle f c t1 dir pos begin begin | undo t1 && pendown t0 = Just $ position t1 | pendown t1 = Just $ position t0 | otherwise = Nothing drawSVG :: Field -> Layer -> SVG -> IO () drawSVG f l (Line p0 p1 clr lw) = drawLine f l lw clr p0 p1 drawSVG f l (Rect pos w h 0 fc _) = fillRectangle f l pos w h fc drawSVG f l (Polyline ps fc lc lw) = fillPolygon f l ps fc lc lw drawSVG f l (Fill clr) = fieldColor f l clr drawSVG f l (Text pos sz clr fnt str) = writeString f l fnt sz clr pos str drawSVG f l (Image pos w h fp) = drawImage f l fp pos w h drawSVG _ _ _ = error "not implemented" positions :: Double -> Double -> TurtleState -> TurtleState -> [Position] positions w h t0 t1 = maybe [] (mkPositions w h (position t0) (position t1)) $ positionStep t0 mkPositions :: Double -> Double -> Position -> Position -> Double -> [Position] mkPositions w h p1 p2 step = case (p1, p2) of (Center x0 y0, Center x1 y1) -> map (uncurry Center) $ mp x0 y0 x1 y1 (TopLeft x0 y0, TopLeft x1 y1) -> map (uncurry TopLeft) $ mp x0 y0 x1 y1 _ -> mkPositions w h (S.topleft w h p1) (S.topleft w h p2) step where mp x0 y0 x1 y1 = let dist = ((x1 - x0) ** 2 + (y1 - y0) ** 2) ** (1 / 2) in take (floor $ dist / step) $ zip [x0, x0 + step * (x1 - x0) / dist .. ] [y0, y0 + step * (y1 - y0) / dist .. ] directions :: TurtleState -> TurtleState -> [Double] directions t0 t1 = case directionStep t0 of Nothing -> [] Just step -> [ds, ds + dd .. de - dd] where dd = if de > ds then step else - step ds = direction t0 de = direction t1 drawTurtle :: Field -> Character -> TurtleState -> Double -> Position -> Maybe Position -> IO () drawTurtle f c ts@TurtleState{fillcolor = fclr, pencolor = clr} dir pos = maybe (drawCharacter f c fclr clr (makeShape ts dir pos) (pensize ts)) (drawCharacterAndLine f c fclr clr (makeShape ts dir pos) (pensize ts) pos)
YoshikuniJujo/wxturtle
src/Graphics/UI/WX/Turtle/Move.hs
Haskell
bsd-3-clause
4,135
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeOperators #-} module Data.FAlgebra.Hole ( module Data.FAlgebra.Base , HoleF(..) , HoleM(..) ) where import Data.FAlgebra.Base import Data.Functor -- |Transform a functor to allow holes of type a data HoleF a f r = Hole a | Full (f r) deriving (Eq, Show, Functor) instance Natural f f' => Natural f (HoleF a f') where nat = Full . nat instance RestrictedNatural s f f' => RestrictedNatural s f (HoleF a f') where rnat s = Full . rnat s -- |Hole filling structure -- This isn't quite the dual of what I have for annotations -- But it definitely makes more sense here so maybe I was wrong -- with annotations. -- Note that when a is an f-coalgebra we can make a -> f r -- from a -> t through a -> f a -> f r newtype HoleM a f r = HoleM { runHoleM :: a -> f r } instance (Functor f, Conatural f f') => RestrictedConatural (HoleM a f) f (HoleF a f') where rconat (HoleM fillHole) (Hole a) = fillHole a rconat (HoleM fillHole) (Full bs) = conat bs instance (Functor f, RestrictedConatural s f f') => RestrictedConatural (s :*: HoleM a f) f (HoleF a f') where rconat (s :*: HoleM fillHole) (Hole a) = fillHole a rconat (s :*: _) (Full bs) = rconat s bs -- Does this instance make sense? instance Functor f => Preserving (HoleM a f) (HoleF a f) where trans (HoleM fillHole) = HoleM (\a -> const (Hole a) <$> fillHole a)
bhamrick/fixalgs
Data/FAlgebra/Hole.hs
Haskell
bsd-3-clause
1,496
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- | -- Module : Travis.Meta -- Description : Travis preprocessor -- Copyright : (c) Oleg Grenrus, 2005 -- License : BSD3 -- Maintainer : Oleg Grenrus <oleg.grenrus@iki.fi> module Travis.Meta ( -- * High level preprocessIO , preprocess , preprocessYaml -- * Internal , Env , parseEnv , interpolateEnv , unlinesShell , shellScripts , languageTemplates , encode' ) where import Control.Category hiding ((.)) import Control.Arrow (second) import Control.Lens hiding ((.=)) import Control.Monad hiding (sequence) import Data.Aeson.Lens import Data.Aeson.Merge import Data.Aeson.Types import Data.ByteString as BS import Data.Char import Data.FileEmbed import Data.Foldable import Data.Function (on) import Data.List as L (map, elemIndex, filter) import Data.Maybe import Data.Monoid import Data.String import Data.Text as T import Data.Traversable import Data.Vector.Lens (vector) import Data.Version import Data.Yaml import Data.Yaml.Pretty import Prelude hiding (sequence) import Text.Regex.Applicative.Text as RE import qualified Paths_travis_meta_yaml as Meta type Env = [(Text, Text)] -- | Parse environment string. -- -- > >>> parseEnv "CABALVER=1.18 GHCVER=7.8.4" -- > Right [("CABALVER","1.18"),("GHCVER","7.8.4")] parseEnv :: Text -> Either String Env parseEnv = traverse (f . T.splitOn "=") . T.words where f [k, n] = Right (k, n) f _ = Left "Cannot parse" -- > match (interpolationRe $ flip lookup [("foo", "bar")]) "$foo" -- Just (Just "bar") interpolationRe :: (Text -> Maybe Text) -> RE' (Maybe Text) interpolationRe l = comb <$> many (interpolationChar l) where comb :: [Maybe Text] -> Maybe Text comb = fmap T.concat . sequence isVarChar :: Char -> Bool isVarChar = (||) <$> isAlpha <*> (=='_') interpolationChar :: (Text -> Maybe Text) -> RE' (Maybe Text) interpolationChar l = var <|> other where var = l . T.pack <$ sym '$' <*> many (psym isVarChar) other = Just . T.singleton <$> anySym -- | Interpolate env. Substitute all @$VAR@ occurrences with values from 'Env'. -- If variable is not in the environment, return 'Nothing'. -- -- > >>> interpolateEnv [("FOO", "foo")] "res-$FOO-bar" -- > Just "res-foo-bar" -- -- > >>> interpolateEnv [("FOO","foo")] "yes-$FOOBAR-$FOO" -- > Nothing interpolateEnv :: Env -> Text -> Maybe Text interpolateEnv env = join . match (interpolationRe l) where l = flip lookup env -- | Like 'interpolateEnv' but substitue non-existing variables with empty string. -- -- > >>> interpolateEnv [("FOO","foo")] "yes-$FOOBAR-$FOO" -- > "yes--foo" interpolateEnv' :: Env -> Text -> Text interpolateEnv' env = RE.replace (f <$ sym '$' <*> many (psym isVarChar)) where f :: String -> Text f = fromMaybe "" . flip lookup env . T.pack preprocessYaml :: Value -> Either String Value preprocessYaml = preprocessYaml' . processMeta . processLanguage processMeta :: Value -> Value processMeta v = v''' where v' = v & _Object . at "meta" .~ Nothing v'' = case (v ^? key "meta" . key "pre") of Just meta -> merge meta v' Nothing -> v' v''' = case (v ^? key "meta" . key "post") of Just meta -> merge v'' meta Nothing -> v'' preprocessYaml' :: Value -> Either String Value preprocessYaml' v = do assertNoMatrixInclude v matrixInclude <- buildMatrixInclude v let v' = v & deep _String %~ embedShellScripts & _Object . at "env" .~ Nothing & _Object . at "addons" .~ Nothing & _Object . at "compiler" .~ Nothing & _Object . at "meta" .~ Nothing & _Object . at "matrix" ?~ (fromMaybe (Object mempty) (v ^? key "matrix")) & key "matrix" . _Object . at "include" ?~ matrixInclude return v' processLanguage :: Value -> Value processLanguage v = case (v ^? key "language" . _String) >>= flip lookup languageTemplates of Just template -> merge (v & _Object . at "language" .~ Nothing) template Nothing -> v buildMatrixInclude :: Value -> Either String Value buildMatrixInclude v = toJSON <$> mk `traverse` envs where addons = v ^? key "addons" compiler = v ^? key "compiler" . _String envs = v ^.. key "env" . values . _String mk env = do env' <- parseEnv env let interpolate = traverseOf _String (interpolateEnv env') addons' = addons & _Just . key "apt" . key "packages" . _Array . from vector %~ mapMaybe interpolate compiler' = compiler & _Just %~ T.strip . interpolateEnv' env' return $ object $ catMaybes [ Just $ "env" .= env , ("addons" .=) <$> addons' , ("compiler" .=) <$> compiler' ] assertNoMatrixInclude :: Value -> Either String () assertNoMatrixInclude v = case v ^? key "matrix" . key "include" of Nothing -> Right () Just v' -> Left $ "matrix.include specified: " ++ show v' header :: ByteString header = "# This file has been generated by travis-meta-yaml " <> fromString (showVersion Meta.version) <> "\n# see https://github.com/phadej/travis-meta-yaml\n" preprocess :: ByteString -> Either String ByteString preprocess = fmap ((header <>) . encode') . preprocessYaml <=< decodeEither preprocessIO :: FilePath -> FilePath -> IO () preprocessIO source target = do contents <- BS.readFile source case preprocess contents of Left err -> error err Right bs -> BS.writeFile target bs -- | name and contents pairs shellScripts :: [(Text, Text)] shellScripts = [ ("multi-ghc-install.sh", $(embedStringFile "data/multi-ghc-install.sh")) ] languageTemplates :: [(Text, Value)] languageTemplates = [ t "haskell-stack" $(embedFile "data/stack.yml") , t "haskell-multi-ghc" $(embedFile "data/multi-ghc.yml") ] where t name bs = (name, fromJust' (T.unpack name) $ decode bs) embedShellScripts :: Text -> Text embedShellScripts = appEndo $ foldMap (Endo . uncurry embedShellFile . second unlinesShell) shellScripts fromJust' :: String -> Maybe a -> a fromJust' _ (Just x) = x fromJust' e Nothing = error $ "fromJust: Nothing -- " <> e embedShellFile :: Text -> Text -> Text -> Text embedShellFile filename contents = RE.replace (contents <$ string "sh" <* some (sym ' ') <* string filename) unlinesShell :: Text -> Text unlinesShell = T.lines >>> L.map (strip . stripComments) >>> L.filter (not . T.null) >>> L.map (fixSemiColonThenElse . (<> ";")) >>> T.intercalate " " where stripComments = RE.replace ("" <$ sym '#' <* many anySym) fixSemiColonThenElse = RE.replace ((string "then" <|> string "else") <* sym ';') -- Right v <- decodeEither <$> BS.readFile ".travis.meta.yml" :: IO (Either String Value) -- BS.putStr $ encode $ preprocessYaml v -- Nothing is smaller then Just -- We also swap params. elemIndexE :: Eq a => [a] -> a -> Either Int () elemIndexE l e = maybe (Right ()) Left (L.elemIndex e l) listCompare :: Eq a => [a] -> a -> a -> Ordering listCompare l = compare `on` elemIndexE l preferredOrder :: [Text] preferredOrder = ["sudo", "language", "before_install", "install", "script", "matrix"] encode' :: ToJSON a => a -> ByteString encode' = encodePretty cfg where cfg = setConfCompare (listCompare preferredOrder) defConfig
phadej/travis-meta-yaml
src/Travis/Meta.hs
Haskell
bsd-3-clause
7,438
-- | Helper for writing tests for numeric code module Test.QuickCheck.Numeric ( -- * Approximate equality eq , eqC -- * Function monotonicity , Monotonicity(..) , monotonicFunction , monotonicFunctionIEEE -- * Inverse function , checkInverse , checkInverse2 ) where import Data.Complex import qualified Numeric.IEEE as IEEE ---------------------------------------------------------------- -- Approximate equality ---------------------------------------------------------------- -- | Approximate equality for 'Double'. Doesn't work well for numbers -- which are almost zero. eq :: Double -- ^ Relative error -> Double -> Double -> Bool eq eps a b | a == 0 && b == 0 = True | otherwise = abs (a - b) <= eps * max (abs a) (abs b) -- | Approximate equality for 'Complex Double' eqC :: Double -- ^ Relative error -> Complex Double -> Complex Double -> Bool eqC eps a@(ar :+ ai) b@(br :+ bi) | a == 0 && b == 0 = True | otherwise = abs (ar - br) <= eps * d && abs (ai - bi) <= eps * d where d = max (realPart $ abs a) (realPart $ abs b) ---------------------------------------------------------------- -- Function monotonicity ---------------------------------------------------------------- -- | Function monotonicity type. data Monotonicity = StrictInc -- ^ Strictly increasing function | MonotoneInc -- ^ Monotonically increasing function | StrictDec -- ^ Strictly decreasing function | MonotoneDec -- ^ Monotonically decreasing function deriving (Show,Eq,Ord) -- | Check that function is nondecreasing. For floating point number -- it may give spurious failures so 'monotonicFunction' -- should be used in this case. monotonicFunction :: (Ord a, Ord b) => Monotonicity -> (a -> b) -> a -> a -> Bool monotonicFunction cmp f x1 x2 = f (min x1 x2) `op` f (max x1 x2) where op = case cmp of StrictInc -> (< ) MonotoneInc -> (<=) StrictDec -> (> ) MonotoneDec -> (>=) -- | Check that function is nondecreasing taking rounding errors into -- account. This function makes no distinction between strictly -- increasing function and monotonically increasing function since -- distinction is pointless for floating point. -- -- In fact funstion is allowed to decrease less than one ulp in order -- to guard againist problems with excess precision. On x86 FPU works -- with 80-bit numbers but doubles are 64-bit so rounding happens -- whenever values are moved from registers to memory monotonicFunctionIEEE :: (Ord a, IEEE.IEEE b) => Monotonicity -> (a -> b) -> a -> a -> Bool monotonicFunctionIEEE cmp f x1 x2 = y1 `op` y2 || abs (y1 - y2) < abs (y2 * IEEE.epsilon) where y1 = f (min x1 x2) y2 = f (max x1 x2) op = case cmp of StrictInc -> (<=) MonotoneInc -> (<=) StrictDec -> (>=) MonotoneDec -> (>=) ---------------------------------------------------------------- -- Function and its inverse ---------------------------------------------------------------- -- | Check that function is inverse. Breaks down near zero. checkInverse :: (Double -> Double) -- ^ Function @f(x)@ -> (Double -> Double) -- ^ Inverse function @g@, @g(f(x)) = x@ -> (Double -> Double) -- ^ Derivative of function @f(x)@ -> Double -- ^ Relative error for -- @f(x)@. Usually is machine epsilon. -> Double -- ^ Relative error for inverse function -- @g(x)@. Usually is machine epsilon. -> Double -> Bool checkInverse f invF f' eps eps' x = x ~= invF y where (~=) = eq (eps' + abs (y / f' x * eps)) y = f x -- | Check that function is inverse. Breaks down near zero. checkInverse2 :: (Double -> Double) -- ^ Function @f(x)@ -> (Double -> Double) -- ^ Inverse function @g@, @g(f(x)) = x@ -> (Double -> Double) -- ^ Derivative of function @g(x)@ -> Double -- ^ Relative error for -- @f(x)@. Usually is machine epsilon. -> Double -- ^ Relative error for inverse function -- @g(x)@. Usually is machine epsilon. -> Double -> Bool checkInverse2 f invF invF' eps eps' x = x ~= invF y where (~=) = eq (eps' + abs (y * (invF' y * eps))) y = f x
Shimuuar/quickcheck-numeric
Test/QuickCheck/Numeric.hs
Haskell
bsd-3-clause
4,416
{-# LANGUAGE GADTs, RankNTypes, TupleSections #-} module QnA4 where data Q1i data Q1o data Q2i data Q2o data Q3i data Q3o data Q4i data Q4o data Graph s a s' where Graph :: (s -> a) -> (s -> a -> s') -> Graph s a s' runGraph :: Graph s a s' -> s -> (a, s') runGraph (Graph f q) s = (f s, q s (f s)) (~:>) :: Graph s a s' -> Graph s' a' s'' -> Graph s a' s'' Graph f1 q1 ~:> Graph f2 q2 = Graph (\s -> f2 $ q1 s (f1 s)) (\s a' -> q2 (q1 s (f1 s)) a') n1 :: Graph () Int String n1 = Graph (const 42) (const . show) n2 :: Graph String Bool Int n2 = Graph ("42"==) (\s b -> if b then length s else -1 * length s) n3 :: Graph () Bool Int n3 = n1 ~:> n2 n4 :: Graph () Bool Int n4 = let (a, s) = runGraph n1 () in undefined type Input = String type Prompt = String type Color = String data Question a = Question Prompt (Input -> a) data Link a s s' = Link (Question a) (s -> a -> s') data Edge sf where Edge :: Link a s s' -> (s' -> a -> Edge sf) -> Edge sf Final :: Link a s s' -> (s' -> a -> sf) -> Edge sf doYouKnowYourSizeQ :: Question Bool doYouKnowYourSizeQ = Question "Do you know your size?" read whatIsYourSizeQ :: Question Int whatIsYourSizeQ = Question "What is your size?" read whatIsYourWeightQ :: Question Int whatIsYourWeightQ = Question "What is your weight?" read whatIsYourHeightQ :: Question Int whatIsYourHeightQ = Question "What is your height?" read whatIsYourFavColorQ :: Question Color whatIsYourFavColorQ = Question "What is your fav color?" id l5 :: Link Color (Bool, Int) (Bool, Int, Color) l5 = Link whatIsYourFavColorQ (\(b, i) c -> (b, i, c)) l1 :: Link Bool () Bool l1 = Link doYouKnowYourSizeQ (const id) l2 :: Link Int Bool (Bool, Int) l2 = Link whatIsYourSizeQ (\ b s -> (b, s)) l3 :: Link Int Bool (Bool, Int) l3 = Link whatIsYourWeightQ (,) l4 :: Link Int (Bool, Int) (Bool, Int) l4 = Link whatIsYourHeightQ (\ (b, w) h -> (b, w * h)) e1 = Edge l1 (const $ \ b -> if b then e2 else e3) e2 = Edge l2 (const $ const ef) e3 = Edge l3 (const $ const e4) e4 = Edge l4 (const $ const ef) ef = Final l5 const
homam/fsm-conversational-ui
src/QnA4.hs
Haskell
bsd-3-clause
2,065
{-# LANGUAGE NoImplicitPrelude #-} ------------------------------------------------------------------- -- | -- Module : Irreverent.Bitucket.Core.Data.Pipelines.SSHKeyPair -- Copyright : (C) 2017 - 2018 Irreverent Pixel Feats -- License : BSD-style (see the file /LICENSE.md) -- Maintainer : Dom De Re -- ------------------------------------------------------------------- module Irreverent.Bitbucket.Core.Data.Pipelines.SSHKeyPair ( -- * Types PipelinesSSHKeyPair(..) ) where import Irreverent.Bitbucket.Core.Data.Common ( PublicSSHKey(..) ) import Preamble data PipelinesSSHKeyPair = PipelinesSSHKeyPair { pskpPublicKey :: !PublicSSHKey } deriving (Show, Eq)
irreverent-pixel-feats/bitbucket
bitbucket-core/src/Irreverent/Bitbucket/Core/Data/Pipelines/SSHKeyPair.hs
Haskell
bsd-3-clause
700
module System.IO.Jail.ByteString ( packCString , packCStringLen , useAsCString , useAsCStringLen , getLine , getContents , putStr , putStrLn , interact , readFile , writeFile , appendFile , hGetLine , hGetContents , hGet , hGetNonBlocking , hPut , hPutStr , hPutStrLn ) where import Prelude hiding (IO, getLine, getContents, putStr, putStrLn, interact, readFile, writeFile, appendFile) import System.IO.Jail.Unsafe import Foreign.C.String import System.IO (Handle) import Data.ByteString (ByteString) import qualified Data.ByteString as B packCString :: CString -> IO ByteString packCString c = io (B.packCString c) packCStringLen :: CStringLen -> IO ByteString packCStringLen c = io (B.packCStringLen c) useAsCString :: ByteString -> (CString -> IO a) -> IO a useAsCString b f = do r <- mkCallback io (B.useAsCString b (r . f)) useAsCStringLen :: ByteString -> (CStringLen -> IO a) -> IO a useAsCStringLen b f = do r <- mkCallback io (B.useAsCStringLen b (r . f)) getLine :: IO ByteString getLine = io B.getLine getContents :: IO ByteString getContents = io B.getContents putStr :: ByteString -> IO () putStr b = io (B.putStr b) putStrLn :: ByteString -> IO () putStrLn b = io (B.putStrLn b) interact :: (ByteString -> ByteString) -> IO () interact f = io (B.interact f) readFile :: FilePath -> IO ByteString readFile = embedPath "readFile" B.readFile writeFile :: FilePath -> ByteString -> IO () writeFile f b = embedPath "writeFile" (flip B.writeFile b) f appendFile :: FilePath -> ByteString -> IO () appendFile f b = embedPath "appendFile" (flip B.appendFile b) f hGetLine :: Handle -> IO ByteString hGetLine = embedHandle "hGetLine" B.hGetLine hGetContents :: Handle -> IO ByteString hGetContents = embedHandle "hGetContents" B.hGetContents hGet :: Handle -> Int -> IO ByteString hGet h i = embedHandle "hGet" (flip B.hGet i) h hGetNonBlocking :: Handle -> Int -> IO ByteString hGetNonBlocking h i = embedHandle "hGetNonBlocking" (flip B.hGetNonBlocking i) h hPut :: Handle -> ByteString -> IO () hPut h b = embedHandle "hPut" (flip B.hPut b) h hPutStr :: Handle -> ByteString -> IO () hPutStr h b = embedHandle "hPutStr" (flip B.hPutStr b) h hPutStrLn :: Handle -> ByteString -> IO () hPutStrLn h b = embedHandle "hPutStrLn" (flip B.hPutStrLn b) h
sebastiaanvisser/jail
src/System/IO/Jail/ByteString.hs
Haskell
bsd-3-clause
2,293