code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE OverloadedStrings, NoImplicitPrelude #-}
module Weight.PlateCalc(displayPlateCalc,Plate(..),plateCalc, Plates(Plates,getPlates), BarType(..)) where
import BasicPrelude
newtype Plates = Plates {
getPlates :: [Plate]
}
--instance Show Plates where
-- show = displayPlates
data BarType = Barbell | Dumbbell deriving (Show)
data Plate = P45 Int | P25 Int | P10 Int | P5 Int | P2p5 Int | TooLight deriving Show
displayPlateCalc :: BarType -> Rational -> Text
displayPlateCalc ctype = displayPlates . plateCalc ctype
displayPlates :: Plates -> Text
displayPlates (Plates []) = "just the bar"
displayPlates (Plates ps) = dPlates ps
where
dPlates :: [Plate] -> Text
dPlates = mconcat . intersperse "," . fmap dPlate
dPlate :: Plate -> Text
dPlate (TooLight) = "less than a bar"
dPlate (P45 n) = "45x" <> show n
dPlate (P25 n) = "25x" <> show n
dPlate (P10 n) = "10x" <> show n
dPlate (P5 n) = "5x" <> show n
dPlate (P2p5 n) = "2.5x" <> show n
plateCalc :: BarType -> Rational -> Plates
plateCalc ctype lbs | lbs < barWeight ctype = Plates [TooLight]
| otherwise = Plates $ minimize $ plateCalc' (lbs - barWeight ctype)
where
barWeight Barbell = 45
barWeight Dumbbell = 2.5
plateCalc' :: Rational -> [Plate]
plateCalc' lbs | lbs >= 90 = P45 2:plateCalc' (lbs - 90)
| lbs >= 50 = P25 2:plateCalc' (lbs - 50)
| lbs >= 20 = P10 2:plateCalc' (lbs - 20)
| lbs >= 10 = P5 2:plateCalc' (lbs - 10)
| lbs >= 5 = P2p5 2:plateCalc' (lbs - 5)
| lbs >= 2.5 = P2p5 2:plateCalc' (lbs - 5) -- round up
| otherwise = []
minimize :: [Plate] -> [Plate]
minimize [] = []
minimize [p] = [p]
minimize ((P45 w1):(P45 w2):ps) = minimize $ P45 (w1+w2):ps
minimize ((P25 w1):(P25 w2):ps) = minimize $ P25 (w1+w2):ps
minimize ((P10 w1):(P10 w2):ps) = minimize $ P10 (w1+w2):ps
minimize ((P5 w1):(P5 w2):ps) = minimize $ P5 (w1+w2):ps
minimize ((P2p5 w1):(P2p5 w2):ps) = minimize $ P2p5 (w1+w2):ps
minimize (p:ps) = p:minimize ps
| mindreader/iron-tracker | Weight/PlateCalc.hs | bsd-3-clause | 2,190 | 0 | 12 | 617 | 946 | 487 | 459 | 46 | 9 |
{-# LANGUAGE FlexibleContexts, TypeFamilies #-}
module Language.Lc.Interpreter.Dynamic
( dynamicInterpreter
) where
import Language.Lc
--------------------------------------------------------------
-- Dynamic interpreter
--------------------------------------------------------------
-- | dynamic interpreter, it uses 'dynamicBetaReduce'
-- This is a dynamic interpreter because the variable is retrieved only when it's needed even
-- though it might not be in scope when defining the expression. It is not a totally valid
-- interpreter but it is interesting to have.
-- For example, `(λfoo. (foo x) b) (λx y. y (x x))` eventually betaReduces to `b (b b)` since
-- the `x` inside `(foo x) b` eventually resolves to `b`
dynamicInterpreter :: DynamicInterpreter
dynamicInterpreter = DynamicInterpreter
data DynamicInterpreter =
DynamicInterpreter
instance Interpreter DynamicInterpreter where
type InternalLc DynamicInterpreter = Lc
fromLc _ = id
toLc _ = id
betaReduceI _ = dynamicBetaReduce
-- | dynamic 'betaReduce'
dynamicBetaReduce :: Lc -> Lc
dynamicBetaReduce (LcApp (LcAbs p fn) arg) = substitute fn p arg
dynamicBetaReduce mainApp@(LcApp fn arg) =
let fn' = dynamicBetaReduce fn
arg' = dynamicBetaReduce arg
in if fn /= fn' || arg /= arg' -- ensure both fn and arg have already been reduced
then LcApp fn' arg'
else mainApp
dynamicBetaReduce lc = lc
-- | substitute in the given 'Lc' the LcVars with the given name
-- with the given 'Lc'
substitute :: Lc -> String -> Lc -> Lc
substitute v@(LcVar var) param new | var == param = new
| otherwise = v
substitute lcAbs@(LcAbs newParam fn) oldParam new
| newParam /= oldParam = LcAbs newParam $ substitute fn oldParam new
| otherwise = lcAbs -- oldParam has been shadowed in this case
substitute (LcApp fn arg) param new = LcApp (substitute fn param new) (substitute arg param new)
| d-dorazio/lc | src/Language/Lc/Interpreter/Dynamic.hs | bsd-3-clause | 1,941 | 0 | 10 | 382 | 363 | 191 | 172 | 29 | 2 |
{-# LANGUAGE RankNTypes, FlexibleInstances, UndecidableInstances, OverloadedStrings #-}
module Main where
import Data.Text (Text)
import Text.AFrame
import Text.AFrame.DSL
import Web.AFrame.GHCi
import Web.AFrame
import Lens.Micro
example :: AFrame
example = scene $ do
c <- colorSelector "color" "#123456"
h <- numberSelector "height" 1 $ return (0,5)
r <- numberSelector "rot" 0 $ return (0,360)
-- xyz <- vec3Selector "position" (-1,0.5,1) (-5,5)
mt <- numberSelector "metalness" 0.0 $ return (0,1)
op <- numberSelector "opacity" 1.0 $ return (0,1)
ro <- numberSelector "roughness" 0.5 $ return (0,1)
sphere $ do
position (0,1.25,-1)
radius 1.25
color "#EF2D5E"
-- metalness mt
-- opacity op
-- roughness ro
box $ do
attribute "id" ("box" :: Text)
position (-1,0.5,1) -- xyz
rotation (r,45,0)
width 1
height h
scale ?(1,1,1)
color c
attribute "shader" ("noise"::Text)
-- component "segments" (1::Int)
cylinder $ do
position (1,0.75+sin(now / 1000),1)
radius 0.5
height 1.5
color "#FFC65D"
attribute "shader" ("noise"::Text)
plane $ do
rotation (-90,0,0)
width 4
height 4
color "#7BC8A4"
attribute "shader" ("noise"::Text)
component "segments" (10::Int)
sky $ color "#ECECEC"
-- entity $ template $ src "#x"
{-
>>> start
>>> s example
>>> u (elementById "animation-1" . attributeByName "dur) "300"
>>> g (^. singular (elementById "animation-1" . attributeByName "dur"))
>>> u (set (nthOfType "a-box" 1 . attributeByName "position" . triple . _3) (-5))
-}
main = aframeStart opts $ example
where opts = defaultOptions
{ jsFiles =
[ "/examples/js/aframe-frp.js"
, "/examples/js/aframe-my-test.js"
, "https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.5.1/dat.gui.min.js"
]
}
| ku-fpg/aframe-server | DSL/Example.hs | bsd-3-clause | 1,930 | 0 | 16 | 490 | 522 | 261 | 261 | 49 | 1 |
module Test.Hspec.Expectations.Matcher (matchList) where
import Prelude hiding (showList)
import Data.List
matchList :: (Show a, Eq a) => [a] -> [a] -> Maybe String
xs `matchList` ys
| null extra && null missing = Nothing
| otherwise = Just (err "")
where
extra = xs \\ ys
missing = ys \\ xs
msgAndList msg zs = showString msg . showList zs . showString "\n"
optMsgList msg zs = if null zs then id else msgAndList msg zs
err :: ShowS
err =
showString "Actual list is not a permutation of expected list!\n"
. msgAndList " expected elements: " ys
. msgAndList " actual elements: " xs
. optMsgList " missing elements: " missing
. optMsgList " extra elements: " extra
showList :: Show a => [a] -> ShowS
showList xs = showChar '[' . foldr (.) (showChar ']') (intersperse (showString ", ") $ map shows xs)
| hspec/hspec-expectations | src/Test/Hspec/Expectations/Matcher.hs | mit | 899 | 0 | 11 | 244 | 303 | 153 | 150 | 20 | 2 |
-- |
-- Module: Math.NumberTheory.Moduli.Equations
-- Copyright: (c) 2018 Andrew Lelechenko
-- Licence: MIT
-- Maintainer: Andrew Lelechenko <[email protected]>
--
-- Polynomial modular equations.
--
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns #-}
module Math.NumberTheory.Moduli.Equations
( solveLinear
, solveQuadratic
) where
import Data.Constraint
import Data.Maybe
import Data.Mod
import GHC.Integer.GMP.Internals
import GHC.TypeNats (KnownNat, natVal)
import Math.NumberTheory.Moduli.Chinese
import Math.NumberTheory.Moduli.Singleton
import Math.NumberTheory.Moduli.Sqrt
import Math.NumberTheory.Primes
import Math.NumberTheory.Utils (recipMod)
-------------------------------------------------------------------------------
-- Linear equations
-- | Find all solutions of ax + b ≡ 0 (mod m).
--
-- >>> :set -XDataKinds
-- >>> solveLinear (6 :: Mod 10) 4 -- solving 6x + 4 ≡ 0 (mod 10)
-- [(1 `modulo` 10),(6 `modulo` 10)]
solveLinear
:: KnownNat m
=> Mod m -- ^ a
-> Mod m -- ^ b
-> [Mod m] -- ^ list of x
solveLinear a b = map fromInteger $ solveLinear' (toInteger (natVal a)) (toInteger (unMod a)) (toInteger (unMod b))
solveLinear' :: Integer -> Integer -> Integer -> [Integer]
solveLinear' m a b = case solveLinearCoprime m' (a `quot` d) (b `quot` d) of
Nothing -> []
Just x -> map (\i -> x + m' * i) [0 .. d - 1]
where
d = m `gcd` a `gcd` b
m' = m `quot` d
solveLinearCoprime :: Integer -> Integer -> Integer -> Maybe Integer
solveLinearCoprime 1 _ _ = Just 0
solveLinearCoprime m a b = (\a1 -> negate b * a1 `mod` m) <$> recipMod a m
-------------------------------------------------------------------------------
-- Quadratic equations
-- | Find all solutions of ax² + bx + c ≡ 0 (mod m).
--
-- >>> :set -XDataKinds
-- >>> solveQuadratic sfactors (1 :: Mod 32) 0 (-17) -- solving x² - 17 ≡ 0 (mod 32)
-- [(9 `modulo` 32),(25 `modulo` 32),(7 `modulo` 32),(23 `modulo` 32)]
solveQuadratic
:: SFactors Integer m
-> Mod m -- ^ a
-> Mod m -- ^ b
-> Mod m -- ^ c
-> [Mod m] -- ^ list of x
solveQuadratic sm a b c = case proofFromSFactors sm of
Sub Dict ->
map fromInteger
$ fst
$ combine
$ map (\(p, n) -> (solveQuadraticPrimePower a' b' c' p n, unPrime p ^ n))
$ unSFactors sm
where
a' = toInteger $ unMod a
b' = toInteger $ unMod b
c' = toInteger $ unMod c
combine :: [([Integer], Integer)] -> ([Integer], Integer)
combine = foldl
(\(xs, xm) (ys, ym) -> ([ fst $ fromJust $ chinese (x, xm) (y, ym) | x <- xs, y <- ys ], xm * ym))
([0], 1)
solveQuadraticPrimePower
:: Integer
-> Integer
-> Integer
-> Prime Integer
-> Word
-> [Integer]
solveQuadraticPrimePower a b c p = go
where
go :: Word -> [Integer]
go 0 = [0]
go 1 = solveQuadraticPrime a b c p
go k = concatMap (liftRoot k) (go (k - 1))
-- Hensel lifting
-- https://en.wikipedia.org/wiki/Hensel%27s_lemma#Hensel_lifting
liftRoot :: Word -> Integer -> [Integer]
liftRoot k r = case recipMod (2 * a * r + b) pk of
Nothing -> case fr of
0 -> map (\i -> r + pk `quot` p' * i) [0 .. p' - 1]
_ -> []
Just invDeriv -> [(r - fr * invDeriv) `mod` pk]
where
pk = p' ^ k
fr = (a * r * r + b * r + c) `mod` pk
p' :: Integer
p' = unPrime p
solveQuadraticPrime
:: Integer
-> Integer
-> Integer
-> Prime Integer
-> [Integer]
solveQuadraticPrime a b c (unPrime -> 2 :: Integer)
= case (even c, even (a + b)) of
(True, True) -> [0, 1]
(True, _) -> [0]
(_, False) -> [1]
_ -> []
solveQuadraticPrime a b c p
| a `rem` p' == 0
= solveLinear' p' b c
| otherwise
= map (\n -> (n - b) * recipModInteger (2 * a) p' `mod` p')
$ sqrtsModPrime (b * b - 4 * a * c) p
where
p' :: Integer
p' = unPrime p
| Bodigrim/arithmoi | Math/NumberTheory/Moduli/Equations.hs | mit | 3,890 | 0 | 18 | 969 | 1,304 | 717 | 587 | 92 | 5 |
{-# Language RebindableSyntax #-}
{-# Language ScopedTypeVariables #-}
{-# Language FlexibleContexts #-}
module Main where
import Prelude hiding ((>>=), (>>), fail, return)
import Symmetry.Language
import Symmetry.Verify
pingServer :: (DSL repr) => repr (Process repr ())
pingServer = do myPid <- self
-- yield G: PtrR[p] = 0
-- R: PtrW[p] > 0
p <- recv
send p myPid
-- exit G: PtrW[p] > 0
master :: (DSL repr) => repr
(RSing -> Process repr ())
master = lam $ \r -> do p <- spawn r pingServer
myPid <- self
_ <- send p myPid
-- yield G: PtrW[p] > 0, PtrR[master] = 0
-- R: PtrW[master] > 0
_ :: repr (Pid RSing) <- recv
return tt
-- exit G: PtrR[master] = 1...
mainProc :: (DSL repr) => repr ()
mainProc = exec $ do r <- newRSing
r |> master
main :: IO ()
main = checkerMain mainProc
| gokhankici/symmetry | checker/tests/pos/Ping00.hs | mit | 1,093 | 0 | 13 | 458 | 261 | 138 | 123 | 23 | 1 |
{- Copyright 2013 Gabriel Gonzalez
This file is part of the Suns Search Engine
The Suns Search Engine is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or (at your
option) any later version.
The Suns Search Engine is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
the Suns Search Engine. If not, see <http://www.gnu.org/licenses/>.
-}
module Util (groupOn) where
import Control.Arrow ((&&&))
import Data.List (sortBy)
import Data.Ord (comparing)
factor :: (Ord a) => [(a, b)] -> [(a, [b])]
factor abs_ = case abs_ of
[] -> []
(k, _):_ -> let (abs1, abs2) = span (\a -> fst a == k) abs_
in (k, map snd abs1):factor abs2
groupOn :: (Ord a) => (b -> a) -> [b] -> [[b]]
groupOn toOrd = map snd . factor . sortBy (comparing fst) . map (toOrd &&& id)
| Gabriel439/suns-search | src/Util.hs | gpl-3.0 | 1,204 | 0 | 16 | 275 | 255 | 141 | 114 | 11 | 2 |
{-
Copyright 2010-2012 Cognimeta Inc.
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 FlexibleContexts, TypeFamilies #-}
module Database.Perdure.WordNArrayRef (
WordNArrayRef(..),
WordNValidator,
module Database.Perdure.ArrayRef
) where
import Prelude()
import Cgm.Prelude
import Database.Perdure.ArrayRef
import Database.Perdure.Persistent
import Cgm.Data.Word
import Cgm.System.Endian
import Database.Perdure.WValidator
class (Validator v, Persistent v, LgMultiple Word64 (ValidatedElem v), Endian (ValidatedElem v), LgMultiple (ValidatedElem v) Word8) => WordNValidator v
instance WordNValidator W32Validator
instance WordNValidator W64Validator
instance WordNValidator v => ArrayRef (WordNArrayRef v) where
type ArrayRefElem (WordNArrayRef v) = ValidatedElem v
writeArrayRef l b = do
let (v, buf) = mkValidationInput b
r <- allocWrite l platformWordEndianness buf
return $ WordNArrayRef v r platformWordEndianness
derefArrayRef f (WordNArrayRef v r e) = fmap primArrayMatchAllocation <$> await1 (storeFileRead f r e v)
arrayRefAddr (WordNArrayRef _ r _) = refStart r
arrayRefSize (WordNArrayRef _ r _) = coarsenLen $ fmap fromIntegral $ refSize r
| Cognimeta/perdure | src/Database/Perdure/WordNArrayRef.hs | apache-2.0 | 1,724 | 0 | 11 | 299 | 336 | 174 | 162 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE ScopedTypeVariables #-}
#ifdef TRUSTWORTHY
{-# LANGUAGE Trustworthy #-}
#endif
#if __GLASGOW_HASKELL__ >= 710
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ViewPatterns #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Cons
-- Copyright : (C) 2012-16 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-----------------------------------------------------------------------------
module Control.Lens.Cons
(
-- * Cons
Cons(..)
, (<|)
, cons
, uncons
, _head, _tail
#if __GLASGOW_HASKELL__ >= 710
, pattern (:<)
#endif
-- * Snoc
, Snoc(..)
, (|>)
, snoc
, unsnoc
, _init, _last
#if __GLASGOW_HASKELL__ >= 710
, pattern (:>)
#endif
) where
import Control.Lens.Equality (simply)
import Control.Lens.Fold
import Control.Lens.Prism
import Control.Lens.Review
import Control.Lens.Tuple
import Control.Lens.Type
import Control.Lens.Internal.Coerce
import qualified Data.ByteString as StrictB
import qualified Data.ByteString.Lazy as LazyB
import Data.Monoid
import qualified Data.Sequence as Seq
import Data.Sequence hiding ((<|), (|>), (:<), (:>))
import qualified Data.Text as StrictT
import qualified Data.Text.Lazy as LazyT
import Data.Vector (Vector)
import qualified Data.Vector as Vector
import Data.Vector.Storable (Storable)
import qualified Data.Vector.Storable as Storable
import Data.Vector.Primitive (Prim)
import qualified Data.Vector.Primitive as Prim
import Data.Vector.Unboxed (Unbox)
import qualified Data.Vector.Unboxed as Unbox
import Data.Word
import Control.Applicative (ZipList(..))
import Prelude
#ifdef HLINT
{-# ANN module "HLint: ignore Eta reduce" #-}
#endif
-- $setup
-- >>> :set -XNoOverloadedStrings
-- >>> import Control.Lens
-- >>> import Debug.SimpleReflect.Expr
-- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g)
-- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f
-- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g
infixr 5 <|, `cons`
infixl 5 |>, `snoc`
#if __GLASGOW_HASKELL__ >= 710
pattern (:<) a s <- (preview _Cons -> Just (a,s)) where
(:<) a s = _Cons # (a,s)
infixr 5 :<
infixl 5 :>
pattern (:>) s a <- (preview _Snoc -> Just (s,a)) where
(:>) a s = _Snoc # (a,s)
#endif
------------------------------------------------------------------------------
-- Cons
------------------------------------------------------------------------------
-- | This class provides a way to attach or detach elements on the left
-- side of a structure in a flexible manner.
class Cons s t a b | s -> a, t -> b, s b -> t, t a -> s where
-- |
--
-- @
-- '_Cons' :: 'Prism' [a] [b] (a, [a]) (b, [b])
-- '_Cons' :: 'Prism' ('Seq' a) ('Seq' b) (a, 'Seq' a) (b, 'Seq' b)
-- '_Cons' :: 'Prism' ('Vector' a) ('Vector' b) (a, 'Vector' a) (b, 'Vector' b)
-- '_Cons' :: 'Prism'' 'String' ('Char', 'String')
-- '_Cons' :: 'Prism'' 'StrictT.Text' ('Char', 'StrictT.Text')
-- '_Cons' :: 'Prism'' 'StrictB.ByteString' ('Word8', 'StrictB.ByteString')
-- @
_Cons :: Prism s t (a,s) (b,t)
instance Cons [a] [b] a b where
_Cons = prism (uncurry (:)) $ \ aas -> case aas of
(a:as) -> Right (a, as)
[] -> Left []
{-# INLINE _Cons #-}
instance Cons (ZipList a) (ZipList b) a b where
_Cons = withPrism listCons $ \listReview listPreview ->
prism (coerce' listReview) (coerce' listPreview) where
listCons :: Prism [a] [b] (a, [a]) (b, [b])
listCons = _Cons
{-# INLINE _Cons #-}
instance Cons (Seq a) (Seq b) a b where
_Cons = prism (uncurry (Seq.<|)) $ \aas -> case viewl aas of
a Seq.:< as -> Right (a, as)
EmptyL -> Left mempty
{-# INLINE _Cons #-}
instance Cons StrictB.ByteString StrictB.ByteString Word8 Word8 where
_Cons = prism' (uncurry StrictB.cons) StrictB.uncons
{-# INLINE _Cons #-}
instance Cons LazyB.ByteString LazyB.ByteString Word8 Word8 where
_Cons = prism' (uncurry LazyB.cons) LazyB.uncons
{-# INLINE _Cons #-}
instance Cons StrictT.Text StrictT.Text Char Char where
_Cons = prism' (uncurry StrictT.cons) StrictT.uncons
{-# INLINE _Cons #-}
instance Cons LazyT.Text LazyT.Text Char Char where
_Cons = prism' (uncurry LazyT.cons) LazyT.uncons
{-# INLINE _Cons #-}
instance Cons (Vector a) (Vector b) a b where
_Cons = prism (uncurry Vector.cons) $ \v ->
if Vector.null v
then Left Vector.empty
else Right (Vector.unsafeHead v, Vector.unsafeTail v)
{-# INLINE _Cons #-}
instance (Prim a, Prim b) => Cons (Prim.Vector a) (Prim.Vector b) a b where
_Cons = prism (uncurry Prim.cons) $ \v ->
if Prim.null v
then Left Prim.empty
else Right (Prim.unsafeHead v, Prim.unsafeTail v)
{-# INLINE _Cons #-}
instance (Storable a, Storable b) => Cons (Storable.Vector a) (Storable.Vector b) a b where
_Cons = prism (uncurry Storable.cons) $ \v ->
if Storable.null v
then Left Storable.empty
else Right (Storable.unsafeHead v, Storable.unsafeTail v)
{-# INLINE _Cons #-}
instance (Unbox a, Unbox b) => Cons (Unbox.Vector a) (Unbox.Vector b) a b where
_Cons = prism (uncurry Unbox.cons) $ \v ->
if Unbox.null v
then Left Unbox.empty
else Right (Unbox.unsafeHead v, Unbox.unsafeTail v)
{-# INLINE _Cons #-}
-- | 'cons' an element onto a container.
--
-- This is an infix alias for 'cons'.
--
-- >>> a <| []
-- [a]
--
-- >>> a <| [b, c]
-- [a,b,c]
--
-- >>> a <| Seq.fromList []
-- fromList [a]
--
-- >>> a <| Seq.fromList [b, c]
-- fromList [a,b,c]
(<|) :: Cons s s a a => a -> s -> s
(<|) = curry (simply review _Cons)
{-# INLINE (<|) #-}
-- | 'cons' an element onto a container.
--
-- >>> cons a []
-- [a]
--
-- >>> cons a [b, c]
-- [a,b,c]
--
-- >>> cons a (Seq.fromList [])
-- fromList [a]
--
-- >>> cons a (Seq.fromList [b, c])
-- fromList [a,b,c]
cons :: Cons s s a a => a -> s -> s
cons = curry (simply review _Cons)
{-# INLINE cons #-}
-- | Attempt to extract the left-most element from a container, and a version of the container without that element.
--
-- >>> uncons []
-- Nothing
--
-- >>> uncons [a, b, c]
-- Just (a,[b,c])
uncons :: Cons s s a a => s -> Maybe (a, s)
uncons = simply preview _Cons
{-# INLINE uncons #-}
-- | A 'Traversal' reading and writing to the 'head' of a /non-empty/ container.
--
-- >>> [a,b,c]^? _head
-- Just a
--
-- >>> [a,b,c] & _head .~ d
-- [d,b,c]
--
-- >>> [a,b,c] & _head %~ f
-- [f a,b,c]
--
-- >>> [] & _head %~ f
-- []
--
-- >>> [1,2,3]^?!_head
-- 1
--
-- >>> []^?_head
-- Nothing
--
-- >>> [1,2]^?_head
-- Just 1
--
-- >>> [] & _head .~ 1
-- []
--
-- >>> [0] & _head .~ 2
-- [2]
--
-- >>> [0,1] & _head .~ 2
-- [2,1]
--
-- This isn't limited to lists.
--
-- For instance you can also 'Data.Traversable.traverse' the head of a 'Seq':
--
-- >>> Seq.fromList [a,b,c,d] & _head %~ f
-- fromList [f a,b,c,d]
--
-- >>> Seq.fromList [] ^? _head
-- Nothing
--
-- >>> Seq.fromList [a,b,c,d] ^? _head
-- Just a
--
-- @
-- '_head' :: 'Traversal'' [a] a
-- '_head' :: 'Traversal'' ('Seq' a) a
-- '_head' :: 'Traversal'' ('Vector' a) a
-- @
_head :: Cons s s a a => Traversal' s a
_head = _Cons._1
{-# INLINE _head #-}
-- | A 'Traversal' reading and writing to the 'tail' of a /non-empty/ container.
--
-- >>> [a,b] & _tail .~ [c,d,e]
-- [a,c,d,e]
--
-- >>> [] & _tail .~ [a,b]
-- []
--
-- >>> [a,b,c,d,e] & _tail.traverse %~ f
-- [a,f b,f c,f d,f e]
--
-- >>> [1,2] & _tail .~ [3,4,5]
-- [1,3,4,5]
--
-- >>> [] & _tail .~ [1,2]
-- []
--
-- >>> [a,b,c]^?_tail
-- Just [b,c]
--
-- >>> [1,2]^?!_tail
-- [2]
--
-- >>> "hello"^._tail
-- "ello"
--
-- >>> ""^._tail
-- ""
--
-- This isn't limited to lists. For instance you can also 'Control.Traversable.traverse' the tail of a 'Seq'.
--
-- >>> Seq.fromList [a,b] & _tail .~ Seq.fromList [c,d,e]
-- fromList [a,c,d,e]
--
-- >>> Seq.fromList [a,b,c] ^? _tail
-- Just (fromList [b,c])
--
-- >>> Seq.fromList [] ^? _tail
-- Nothing
--
-- @
-- '_tail' :: 'Traversal'' [a] [a]
-- '_tail' :: 'Traversal'' ('Seq' a) ('Seq' a)
-- '_tail' :: 'Traversal'' ('Vector' a) ('Vector' a)
-- @
_tail :: Cons s s a a => Traversal' s s
_tail = _Cons._2
{-# INLINE _tail #-}
------------------------------------------------------------------------------
-- Snoc
------------------------------------------------------------------------------
-- | This class provides a way to attach or detach elements on the right
-- side of a structure in a flexible manner.
class Snoc s t a b | s -> a, t -> b, s b -> t, t a -> s where
-- |
--
-- @
-- '_Snoc' :: 'Prism' [a] [b] ([a], a) ([b], b)
-- '_Snoc' :: 'Prism' ('Seq' a) ('Seq' b) ('Seq' a, a) ('Seq' b, b)
-- '_Snoc' :: 'Prism' ('Vector' a) ('Vector' b) ('Vector' a, a) ('Vector' b, b)
-- '_Snoc' :: 'Prism'' 'String' ('String', 'Char')
-- '_Snoc' :: 'Prism'' 'StrictT.Text' ('StrictT.Text', 'Char')
-- '_Snoc' :: 'Prism'' 'StrictB.ByteString' ('StrictB.ByteString', 'Word8')
-- @
_Snoc :: Prism s t (s,a) (t,b)
instance Snoc [a] [b] a b where
_Snoc = prism (\(as,a) -> as Prelude.++ [a]) $ \aas -> if Prelude.null aas
then Left []
else Right (Prelude.init aas, Prelude.last aas)
{-# INLINE _Snoc #-}
instance Snoc (ZipList a) (ZipList b) a b where
_Snoc = withPrism listSnoc $ \listReview listPreview ->
prism (coerce' listReview) (coerce' listPreview) where
listSnoc :: Prism [a] [b] ([a], a) ([b], b)
listSnoc = _Snoc
{-# INLINE _Snoc #-}
instance Snoc (Seq a) (Seq b) a b where
_Snoc = prism (uncurry (Seq.|>)) $ \aas -> case viewr aas of
as Seq.:> a -> Right (as, a)
EmptyR -> Left mempty
{-# INLINE _Snoc #-}
instance Snoc (Vector a) (Vector b) a b where
_Snoc = prism (uncurry Vector.snoc) $ \v -> if Vector.null v
then Left Vector.empty
else Right (Vector.unsafeInit v, Vector.unsafeLast v)
{-# INLINE _Snoc #-}
instance (Prim a, Prim b) => Snoc (Prim.Vector a) (Prim.Vector b) a b where
_Snoc = prism (uncurry Prim.snoc) $ \v -> if Prim.null v
then Left Prim.empty
else Right (Prim.unsafeInit v, Prim.unsafeLast v)
{-# INLINE _Snoc #-}
instance (Storable a, Storable b) => Snoc (Storable.Vector a) (Storable.Vector b) a b where
_Snoc = prism (uncurry Storable.snoc) $ \v -> if Storable.null v
then Left Storable.empty
else Right (Storable.unsafeInit v, Storable.unsafeLast v)
{-# INLINE _Snoc #-}
instance (Unbox a, Unbox b) => Snoc (Unbox.Vector a) (Unbox.Vector b) a b where
_Snoc = prism (uncurry Unbox.snoc) $ \v -> if Unbox.null v
then Left Unbox.empty
else Right (Unbox.unsafeInit v, Unbox.unsafeLast v)
{-# INLINE _Snoc #-}
instance Snoc StrictB.ByteString StrictB.ByteString Word8 Word8 where
_Snoc = prism (uncurry StrictB.snoc) $ \v -> if StrictB.null v
then Left StrictB.empty
else Right (StrictB.init v, StrictB.last v)
{-# INLINE _Snoc #-}
instance Snoc LazyB.ByteString LazyB.ByteString Word8 Word8 where
_Snoc = prism (uncurry LazyB.snoc) $ \v -> if LazyB.null v
then Left LazyB.empty
else Right (LazyB.init v, LazyB.last v)
{-# INLINE _Snoc #-}
instance Snoc StrictT.Text StrictT.Text Char Char where
_Snoc = prism (uncurry StrictT.snoc) $ \v -> if StrictT.null v
then Left StrictT.empty
else Right (StrictT.init v, StrictT.last v)
{-# INLINE _Snoc #-}
instance Snoc LazyT.Text LazyT.Text Char Char where
_Snoc = prism (uncurry LazyT.snoc) $ \v -> if LazyT.null v
then Left LazyT.empty
else Right (LazyT.init v, LazyT.last v)
{-# INLINE _Snoc #-}
-- | A 'Traversal' reading and replacing all but the a last element of a /non-empty/ container.
--
-- >>> [a,b,c,d]^?_init
-- Just [a,b,c]
--
-- >>> []^?_init
-- Nothing
--
-- >>> [a,b] & _init .~ [c,d,e]
-- [c,d,e,b]
--
-- >>> [] & _init .~ [a,b]
-- []
--
-- >>> [a,b,c,d] & _init.traverse %~ f
-- [f a,f b,f c,d]
--
-- >>> [1,2,3]^?_init
-- Just [1,2]
--
-- >>> [1,2,3,4]^?!_init
-- [1,2,3]
--
-- >>> "hello"^._init
-- "hell"
--
-- >>> ""^._init
-- ""
--
-- @
-- '_init' :: 'Traversal'' [a] [a]
-- '_init' :: 'Traversal'' ('Seq' a) ('Seq' a)
-- '_init' :: 'Traversal'' ('Vector' a) ('Vector' a)
-- @
_init :: Snoc s s a a => Traversal' s s
_init = _Snoc._1
{-# INLINE _init #-}
-- | A 'Traversal' reading and writing to the last element of a /non-empty/ container.
--
-- >>> [a,b,c]^?!_last
-- c
--
-- >>> []^?_last
-- Nothing
--
-- >>> [a,b,c] & _last %~ f
-- [a,b,f c]
--
-- >>> [1,2]^?_last
-- Just 2
--
-- >>> [] & _last .~ 1
-- []
--
-- >>> [0] & _last .~ 2
-- [2]
--
-- >>> [0,1] & _last .~ 2
-- [0,2]
--
-- This 'Traversal' is not limited to lists, however. We can also work with other containers, such as a 'Vector'.
--
-- >>> Vector.fromList "abcde" ^? _last
-- Just 'e'
--
-- >>> Vector.empty ^? _last
-- Nothing
--
-- >>> (Vector.fromList "abcde" & _last .~ 'Q') == Vector.fromList "abcdQ"
-- True
--
-- @
-- '_last' :: 'Traversal'' [a] a
-- '_last' :: 'Traversal'' ('Seq' a) a
-- '_last' :: 'Traversal'' ('Vector' a) a
-- @
_last :: Snoc s s a a => Traversal' s a
_last = _Snoc._2
{-# INLINE _last #-}
-- | 'snoc' an element onto the end of a container.
--
-- This is an infix alias for 'snoc'.
--
-- >>> Seq.fromList [] |> a
-- fromList [a]
--
-- >>> Seq.fromList [b, c] |> a
-- fromList [b,c,a]
--
-- >>> LazyT.pack "hello" |> '!'
-- "hello!"
(|>) :: Snoc s s a a => s -> a -> s
(|>) = curry (simply review _Snoc)
{-# INLINE (|>) #-}
-- | 'snoc' an element onto the end of a container.
--
-- >>> snoc (Seq.fromList []) a
-- fromList [a]
--
-- >>> snoc (Seq.fromList [b, c]) a
-- fromList [b,c,a]
--
-- >>> snoc (LazyT.pack "hello") '!'
-- "hello!"
snoc :: Snoc s s a a => s -> a -> s
snoc = curry (simply review _Snoc)
{-# INLINE snoc #-}
-- | Attempt to extract the right-most element from a container, and a version of the container without that element.
--
-- >>> unsnoc (LazyT.pack "hello!")
-- Just ("hello",'!')
--
-- >>> unsnoc (LazyT.pack "")
-- Nothing
--
-- >>> unsnoc (Seq.fromList [b,c,a])
-- Just (fromList [b,c],a)
--
-- >>> unsnoc (Seq.fromList [])
-- Nothing
unsnoc :: Snoc s s a a => s -> Maybe (s, a)
unsnoc s = simply preview _Snoc s
{-# INLINE unsnoc #-}
| ddssff/lens | src/Control/Lens/Cons.hs | bsd-3-clause | 14,364 | 0 | 12 | 2,904 | 3,153 | 1,860 | 1,293 | -1 | -1 |
{-# LANGUAGE CPP, FlexibleInstances, IncoherentInstances, NamedFieldPuns,
NoImplicitPrelude, OverlappingInstances, TemplateHaskell,
UndecidableInstances #-}
{-|
Module: Data.Aeson.TH
Copyright: (c) 2011, 2012 Bryan O'Sullivan
(c) 2011 MailRank, Inc.
License: Apache
Stability: experimental
Portability: portable
Functions to mechanically derive 'ToJSON' and 'FromJSON' instances. Note that
you need to enable the @TemplateHaskell@ language extension in order to use this
module.
An example shows how instances are generated for arbitrary data types. First we
define a data type:
@
data D a = Nullary
| Unary Int
| Product String Char a
| Record { testOne :: Double
, testTwo :: Bool
, testThree :: D a
} deriving Eq
@
Next we derive the necessary instances. Note that we make use of the
feature to change record field names. In this case we drop the first 4
characters of every field name. We also modify constructor names by
lower-casing them:
@
$('deriveJSON' 'defaultOptions'{'fieldLabelModifier' = 'drop' 4, 'constructorTagModifier' = map toLower} ''D)
@
Now we can use the newly created instances.
@
d :: D 'Int'
d = Record { testOne = 3.14159
, testTwo = 'True'
, testThree = Product \"test\" \'A\' 123
}
@
>>> fromJSON (toJSON d) == Success d
> True
Please note that you can derive instances for tuples using the following syntax:
@
-- FromJSON and ToJSON instances for 4-tuples.
$('deriveJSON' 'defaultOptions' ''(,,,))
@
-}
module Data.Aeson.TH
( -- * Encoding configuration
Options(..), SumEncoding(..), defaultOptions, defaultTaggedObject
-- * FromJSON and ToJSON derivation
, deriveJSON
, deriveToJSON
, deriveFromJSON
, mkToJSON
, mkParseJSON
) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
-- from aeson:
import Data.Aeson ( toJSON, Object, object, (.=), (.:), (.:?)
, ToJSON, toJSON
, FromJSON, parseJSON
)
import Data.Aeson.Types ( Value(..), Parser
, Options(..)
, SumEncoding(..)
, defaultOptions
, defaultTaggedObject
)
-- from base:
import Control.Applicative ( pure, (<$>), (<*>) )
import Control.Monad ( return, mapM, liftM2, fail )
import Data.Bool ( Bool(False, True), otherwise, (&&) )
import Data.Eq ( (==) )
import Data.Function ( ($), (.) )
import Data.Functor ( fmap )
import Data.Int ( Int )
import Data.Either ( Either(Left, Right) )
import Data.List ( (++), foldl, foldl', intercalate
, length, map, zip, genericLength, all, partition
)
import Data.Maybe ( Maybe(Nothing, Just), catMaybes )
import Prelude ( String, (-), Integer, fromIntegral, error )
import Text.Printf ( printf )
import Text.Show ( show )
-- from unordered-containers:
import qualified Data.HashMap.Strict as H ( lookup, toList )
-- from template-haskell:
import Language.Haskell.TH
import Language.Haskell.TH.Syntax ( VarStrictType )
-- from text:
import qualified Data.Text as T ( Text, pack, unpack )
-- from vector:
import qualified Data.Vector as V ( unsafeIndex, null, length, create, fromList )
import qualified Data.Vector.Mutable as VM ( unsafeNew, unsafeWrite )
--------------------------------------------------------------------------------
-- Convenience
--------------------------------------------------------------------------------
-- | Generates both 'ToJSON' and 'FromJSON' instance declarations for the given
-- data type.
--
-- This is a convienience function which is equivalent to calling both
-- 'deriveToJSON' and 'deriveFromJSON'.
deriveJSON :: Options
-- ^ Encoding options.
-> Name
-- ^ Name of the type for which to generate 'ToJSON' and 'FromJSON'
-- instances.
-> Q [Dec]
deriveJSON opts name =
liftM2 (++)
(deriveToJSON opts name)
(deriveFromJSON opts name)
--------------------------------------------------------------------------------
-- ToJSON
--------------------------------------------------------------------------------
{-
TODO: Don't constrain phantom type variables.
data Foo a = Foo Int
instance (ToJSON a) ⇒ ToJSON Foo where ...
The above (ToJSON a) constraint is not necessary and perhaps undesirable.
-}
-- | Generates a 'ToJSON' instance declaration for the given data type.
deriveToJSON :: Options
-- ^ Encoding options.
-> Name
-- ^ Name of the type for which to generate a 'ToJSON' instance
-- declaration.
-> Q [Dec]
deriveToJSON opts name =
withType name $ \tvbs cons -> fmap (:[]) $ fromCons tvbs cons
where
fromCons :: [TyVarBndr] -> [Con] -> Q Dec
fromCons tvbs cons =
instanceD (applyCon ''ToJSON typeNames)
(classType `appT` instanceType)
[ funD 'toJSON
[ clause []
(normalB $ consToJSON opts cons)
[]
]
]
where
classType = conT ''ToJSON
typeNames = map tvbName tvbs
instanceType = foldl' appT (conT name) $ map varT typeNames
-- | Generates a lambda expression which encodes the given data type as JSON.
mkToJSON :: Options -- ^ Encoding options.
-> Name -- ^ Name of the type to encode.
-> Q Exp
mkToJSON opts name = withType name (\_ cons -> consToJSON opts cons)
-- | Helper function used by both 'deriveToJSON' and 'mkToJSON'. Generates code
-- to generate the JSON encoding of a number of constructors. All constructors
-- must be from the same type.
consToJSON :: Options
-- ^ Encoding options.
-> [Con]
-- ^ Constructors for which to generate JSON generating code.
-> Q Exp
consToJSON _ [] = error $ "Data.Aeson.TH.consToJSON: "
++ "Not a single constructor given!"
-- A single constructor is directly encoded. The constructor itself may be
-- forgotten.
consToJSON opts [con] = do
value <- newName "value"
lam1E (varP value) $ caseE (varE value) [encodeArgs opts False con]
consToJSON opts cons = do
value <- newName "value"
lam1E (varP value) $ caseE (varE value) matches
where
matches
| allNullaryToStringTag opts && all isNullary cons =
[ match (conP conName []) (normalB $ conStr opts conName) []
| con <- cons
, let conName = getConName con
]
| otherwise = [encodeArgs opts True con | con <- cons]
conStr :: Options -> Name -> Q Exp
conStr opts = appE [|String|] . conTxt opts
conTxt :: Options -> Name -> Q Exp
conTxt opts = appE [|T.pack|] . conStringE opts
conStringE :: Options -> Name -> Q Exp
conStringE opts = stringE . constructorTagModifier opts . nameBase
-- | If constructor is nullary.
isNullary :: Con -> Bool
isNullary (NormalC _ []) = True
isNullary _ = False
encodeSum :: Options -> Bool -> Name -> Q Exp -> Q Exp
encodeSum opts multiCons conName exp
| multiCons =
case sumEncoding opts of
TwoElemArray ->
[|Array|] `appE` ([|V.fromList|] `appE` listE [conStr opts conName, exp])
TaggedObject{tagFieldName, contentsFieldName} ->
[|object|] `appE` listE
[ infixApp [|T.pack tagFieldName|] [|(.=)|] (conStr opts conName)
, infixApp [|T.pack contentsFieldName|] [|(.=)|] exp
]
ObjectWithSingleField ->
[|object|] `appE` listE
[ infixApp (conTxt opts conName) [|(.=)|] exp
]
| otherwise = exp
-- | Generates code to generate the JSON encoding of a single constructor.
encodeArgs :: Options -> Bool -> Con -> Q Match
-- Nullary constructors. Generates code that explicitly matches against the
-- constructor even though it doesn't contain data. This is useful to prevent
-- type errors.
encodeArgs opts multiCons (NormalC conName []) =
match (conP conName [])
(normalB (encodeSum opts multiCons conName [e|toJSON ([] :: [()])|]))
[]
-- Polyadic constructors with special case for unary constructors.
encodeArgs opts multiCons (NormalC conName ts) = do
let len = length ts
args <- mapM newName ["arg" ++ show n | n <- [1..len]]
js <- case [[|toJSON|] `appE` varE arg | arg <- args] of
-- Single argument is directly converted.
[e] -> return e
-- Multiple arguments are converted to a JSON array.
es -> do
mv <- newName "mv"
let newMV = bindS (varP mv)
([|VM.unsafeNew|] `appE`
litE (integerL $ fromIntegral len))
stmts = [ noBindS $
[|VM.unsafeWrite|] `appE`
(varE mv) `appE`
litE (integerL ix) `appE`
e
| (ix, e) <- zip [(0::Integer)..] es
]
ret = noBindS $ [|return|] `appE` varE mv
return $ [|Array|] `appE`
(varE 'V.create `appE`
doE (newMV:stmts++[ret]))
match (conP conName $ map varP args)
(normalB $ encodeSum opts multiCons conName js)
[]
-- Records.
encodeArgs opts multiCons (RecC conName ts) = do
args <- mapM newName ["arg" ++ show n | (_, n) <- zip ts [1 :: Integer ..]]
let exp = [|object|] `appE` pairs
pairs | omitNothingFields opts = infixApp maybeFields
[|(++)|]
restFields
| otherwise = listE $ map toPair argCons
argCons = zip args ts
maybeFields = [|catMaybes|] `appE` listE (map maybeToPair maybes)
restFields = listE $ map toPair rest
(maybes, rest) = partition isMaybe argCons
isMaybe (_, (_, _, AppT (ConT t) _)) = t == ''Maybe
isMaybe _ = False
maybeToPair (arg, (field, _, _)) =
infixApp (infixE (Just $ toFieldName field)
[|(.=)|]
Nothing)
[|(<$>)|]
(varE arg)
toPair (arg, (field, _, _)) =
infixApp (toFieldName field)
[|(.=)|]
(varE arg)
toFieldName field = [|T.pack|] `appE` fieldLabelExp opts field
match (conP conName $ map varP args)
( normalB
$ if multiCons
then case sumEncoding opts of
TwoElemArray -> [|toJSON|] `appE` tupE [conStr opts conName, exp]
TaggedObject{tagFieldName} ->
[|object|] `appE`
-- TODO: Maybe throw an error in case
-- tagFieldName overwrites a field in pairs.
infixApp (infixApp [|T.pack tagFieldName|]
[|(.=)|]
(conStr opts conName))
[|(:)|]
pairs
ObjectWithSingleField ->
[|object|] `appE` listE
[ infixApp (conTxt opts conName) [|(.=)|] exp ]
else exp
) []
-- Infix constructors.
encodeArgs opts multiCons (InfixC _ conName _) = do
al <- newName "argL"
ar <- newName "argR"
match (infixP (varP al) conName (varP ar))
( normalB
$ encodeSum opts multiCons conName
$ [|toJSON|] `appE` listE [ [|toJSON|] `appE` varE a
| a <- [al,ar]
]
)
[]
-- Existentially quantified constructors.
encodeArgs opts multiCons (ForallC _ _ con) =
encodeArgs opts multiCons con
--------------------------------------------------------------------------------
-- FromJSON
--------------------------------------------------------------------------------
-- | Generates a 'FromJSON' instance declaration for the given data type.
deriveFromJSON :: Options
-- ^ Encoding options.
-> Name
-- ^ Name of the type for which to generate a 'FromJSON' instance
-- declaration.
-> Q [Dec]
deriveFromJSON opts name =
withType name $ \tvbs cons -> fmap (:[]) $ fromCons tvbs cons
where
fromCons :: [TyVarBndr] -> [Con] -> Q Dec
fromCons tvbs cons =
instanceD (applyCon ''FromJSON typeNames)
(classType `appT` instanceType)
[ funD 'parseJSON
[ clause []
(normalB $ consFromJSON name opts cons)
[]
]
]
where
classType = conT ''FromJSON
typeNames = map tvbName tvbs
instanceType = foldl' appT (conT name) $ map varT typeNames
-- | Generates a lambda expression which parses the JSON encoding of the given
-- data type.
mkParseJSON :: Options -- ^ Encoding options.
-> Name -- ^ Name of the encoded type.
-> Q Exp
mkParseJSON opts name =
withType name (\_ cons -> consFromJSON name opts cons)
-- | Helper function used by both 'deriveFromJSON' and 'mkParseJSON'. Generates
-- code to parse the JSON encoding of a number of constructors. All constructors
-- must be from the same type.
consFromJSON :: Name
-- ^ Name of the type to which the constructors belong.
-> Options
-- ^ Encoding options
-> [Con]
-- ^ Constructors for which to generate JSON parsing code.
-> Q Exp
consFromJSON _ _ [] = error $ "Data.Aeson.TH.consFromJSON: "
++ "Not a single constructor given!"
consFromJSON tName opts [con] = do
value <- newName "value"
lam1E (varP value) (parseArgs tName opts con (Right value))
consFromJSON tName opts cons = do
value <- newName "value"
lam1E (varP value) $ caseE (varE value) $
if allNullaryToStringTag opts && all isNullary cons
then allNullaryMatches
else mixedMatches
where
allNullaryMatches =
[ do txt <- newName "txt"
match (conP 'String [varP txt])
(guardedB $
[ liftM2 (,) (normalG $
infixApp (varE txt)
[|(==)|]
([|T.pack|] `appE`
conStringE opts conName)
)
([|pure|] `appE` conE conName)
| con <- cons
, let conName = getConName con
]
++
[ liftM2 (,)
(normalG [|otherwise|])
( [|noMatchFail|]
`appE` (litE $ stringL $ show tName)
`appE` ([|T.unpack|] `appE` varE txt)
)
]
)
[]
, do other <- newName "other"
match (varP other)
(normalB $ [|noStringFail|]
`appE` (litE $ stringL $ show tName)
`appE` ([|valueConName|] `appE` varE other)
)
[]
]
mixedMatches =
case sumEncoding opts of
TaggedObject {tagFieldName, contentsFieldName} ->
parseObject $ parseTaggedObject tagFieldName contentsFieldName
ObjectWithSingleField ->
parseObject $ parseObjectWithSingleField
TwoElemArray ->
[ do arr <- newName "array"
match (conP 'Array [varP arr])
(guardedB $
[ liftM2 (,) (normalG $ infixApp ([|V.length|] `appE` varE arr)
[|(==)|]
(litE $ integerL 2))
(parse2ElemArray arr)
, liftM2 (,) (normalG [|otherwise|])
(([|not2ElemArray|]
`appE` (litE $ stringL $ show tName)
`appE` ([|V.length|] `appE` varE arr)))
]
)
[]
, do other <- newName "other"
match (varP other)
( normalB
$ [|noArrayFail|]
`appE` (litE $ stringL $ show tName)
`appE` ([|valueConName|] `appE` varE other)
)
[]
]
parseObject f =
[ do obj <- newName "obj"
match (conP 'Object [varP obj]) (normalB $ f obj) []
, do other <- newName "other"
match (varP other)
( normalB
$ [|noObjectFail|]
`appE` (litE $ stringL $ show tName)
`appE` ([|valueConName|] `appE` varE other)
)
[]
]
parseTaggedObject typFieldName valFieldName obj = do
conKey <- newName "conKey"
doE [ bindS (varP conKey)
(infixApp (varE obj)
[|(.:)|]
([|T.pack|] `appE` stringE typFieldName))
, noBindS $ parseContents conKey (Left (valFieldName, obj)) 'conNotFoundFailTaggedObject
]
parse2ElemArray arr = do
conKey <- newName "conKey"
conVal <- newName "conVal"
let letIx n ix =
valD (varP n)
(normalB ([|V.unsafeIndex|] `appE`
varE arr `appE`
litE (integerL ix)))
[]
letE [ letIx conKey 0
, letIx conVal 1
]
(caseE (varE conKey)
[ do txt <- newName "txt"
match (conP 'String [varP txt])
(normalB $ parseContents txt
(Right conVal)
'conNotFoundFail2ElemArray
)
[]
, do other <- newName "other"
match (varP other)
( normalB
$ [|firstElemNoStringFail|]
`appE` (litE $ stringL $ show tName)
`appE` ([|valueConName|] `appE` varE other)
)
[]
]
)
parseObjectWithSingleField obj = do
conKey <- newName "conKey"
conVal <- newName "conVal"
caseE ([e|H.toList|] `appE` varE obj)
[ match (listP [tupP [varP conKey, varP conVal]])
(normalB $ parseContents conKey (Right conVal) 'conNotFoundFailObjectSingleField)
[]
, do other <- newName "other"
match (varP other)
(normalB $ [|wrongPairCountFail|]
`appE` (litE $ stringL $ show tName)
`appE` ([|show . length|] `appE` varE other)
)
[]
]
parseContents conKey contents errorFun =
caseE (varE conKey)
[ match wildP
( guardedB $
[ do g <- normalG $ infixApp (varE conKey)
[|(==)|]
([|T.pack|] `appE`
conNameExp opts con)
e <- parseArgs tName opts con contents
return (g, e)
| con <- cons
]
++
[ liftM2 (,)
(normalG [e|otherwise|])
( varE errorFun
`appE` (litE $ stringL $ show tName)
`appE` listE (map ( litE
. stringL
. constructorTagModifier opts
. nameBase
. getConName
) cons
)
`appE` ([|T.unpack|] `appE` varE conKey)
)
]
)
[]
]
parseNullaryMatches :: Name -> Name -> [Q Match]
parseNullaryMatches tName conName =
[ do arr <- newName "arr"
match (conP 'Array [varP arr])
(guardedB $
[ liftM2 (,) (normalG $ [|V.null|] `appE` varE arr)
([|pure|] `appE` conE conName)
, liftM2 (,) (normalG [|otherwise|])
(parseTypeMismatch tName conName
(litE $ stringL "an empty Array")
(infixApp (litE $ stringL $ "Array of length ")
[|(++)|]
([|show . V.length|] `appE` varE arr)
)
)
]
)
[]
, matchFailed tName conName "Array"
]
parseUnaryMatches :: Name -> [Q Match]
parseUnaryMatches conName =
[ do arg <- newName "arg"
match (varP arg)
( normalB $ infixApp (conE conName)
[|(<$>)|]
([|parseJSON|] `appE` varE arg)
)
[]
]
parseRecord :: Options -> Name -> Name -> [VarStrictType] -> Name -> ExpQ
parseRecord opts tName conName ts obj =
foldl' (\a b -> infixApp a [|(<*>)|] b)
(infixApp (conE conName) [|(<$>)|] x)
xs
where
x:xs = [ [|lookupField|]
`appE` (litE $ stringL $ show tName)
`appE` (litE $ stringL $ constructorTagModifier opts $ nameBase conName)
`appE` (varE obj)
`appE` ( [|T.pack|] `appE` fieldLabelExp opts field
)
| (field, _, _) <- ts
]
getValField :: Name -> String -> [MatchQ] -> Q Exp
getValField obj valFieldName matches = do
val <- newName "val"
doE [ bindS (varP val) $ infixApp (varE obj)
[|(.:)|]
([|T.pack|] `appE`
(litE $ stringL valFieldName))
, noBindS $ caseE (varE val) matches
]
-- | Generates code to parse the JSON encoding of a single constructor.
parseArgs :: Name -- ^ Name of the type to which the constructor belongs.
-> Options -- ^ Encoding options.
-> Con -- ^ Constructor for which to generate JSON parsing code.
-> Either (String, Name) Name -- ^ Left (valFieldName, objName) or
-- Right valName
-> Q Exp
-- Nullary constructors.
parseArgs tName _ (NormalC conName []) (Left (valFieldName, obj)) =
getValField obj valFieldName $ parseNullaryMatches tName conName
parseArgs tName _ (NormalC conName []) (Right valName) =
caseE (varE valName) $ parseNullaryMatches tName conName
-- Unary constructors.
parseArgs _ _ (NormalC conName [_]) (Left (valFieldName, obj)) =
getValField obj valFieldName $ parseUnaryMatches conName
parseArgs _ _ (NormalC conName [_]) (Right valName) =
caseE (varE valName) $ parseUnaryMatches conName
-- Polyadic constructors.
parseArgs tName _ (NormalC conName ts) (Left (valFieldName, obj)) =
getValField obj valFieldName $ parseProduct tName conName $ genericLength ts
parseArgs tName _ (NormalC conName ts) (Right valName) =
caseE (varE valName) $ parseProduct tName conName $ genericLength ts
-- Records.
parseArgs tName opts (RecC conName ts) (Left (_, obj)) =
parseRecord opts tName conName ts obj
parseArgs tName opts (RecC conName ts) (Right valName) = do
obj <- newName "recObj"
caseE (varE valName)
[ match (conP 'Object [varP obj]) (normalB $ parseRecord opts tName conName ts obj) []
, matchFailed tName conName "Object"
]
-- Infix constructors. Apart from syntax these are the same as
-- polyadic constructors.
parseArgs tName _ (InfixC _ conName _) (Left (valFieldName, obj)) =
getValField obj valFieldName $ parseProduct tName conName 2
parseArgs tName _ (InfixC _ conName _) (Right valName) =
caseE (varE valName) $ parseProduct tName conName 2
-- Existentially quantified constructors. We ignore the quantifiers
-- and proceed with the contained constructor.
parseArgs tName opts (ForallC _ _ con) contents =
parseArgs tName opts con contents
-- | Generates code to parse the JSON encoding of an n-ary
-- constructor.
parseProduct :: Name -- ^ Name of the type to which the constructor belongs.
-> Name -- ^ 'Con'structor name.
-> Integer -- ^ 'Con'structor arity.
-> [Q Match]
parseProduct tName conName numArgs =
[ do arr <- newName "arr"
-- List of: "parseJSON (arr `V.unsafeIndex` <IX>)"
let x:xs = [ [|parseJSON|]
`appE`
infixApp (varE arr)
[|V.unsafeIndex|]
(litE $ integerL ix)
| ix <- [0 .. numArgs - 1]
]
match (conP 'Array [varP arr])
(normalB $ condE ( infixApp ([|V.length|] `appE` varE arr)
[|(==)|]
(litE $ integerL numArgs)
)
( foldl' (\a b -> infixApp a [|(<*>)|] b)
(infixApp (conE conName) [|(<$>)|] x)
xs
)
( parseTypeMismatch tName conName
(litE $ stringL $ "Array of length " ++ show numArgs)
( infixApp (litE $ stringL $ "Array of length ")
[|(++)|]
([|show . V.length|] `appE` varE arr)
)
)
)
[]
, matchFailed tName conName "Array"
]
--------------------------------------------------------------------------------
-- Parsing errors
--------------------------------------------------------------------------------
matchFailed :: Name -> Name -> String -> MatchQ
matchFailed tName conName expected = do
other <- newName "other"
match (varP other)
( normalB $ parseTypeMismatch tName conName
(litE $ stringL expected)
([|valueConName|] `appE` varE other)
)
[]
parseTypeMismatch :: Name -> Name -> ExpQ -> ExpQ -> ExpQ
parseTypeMismatch tName conName expected actual =
foldl appE
[|parseTypeMismatch'|]
[ litE $ stringL $ nameBase conName
, litE $ stringL $ show tName
, expected
, actual
]
class (FromJSON a) => LookupField a where
lookupField :: String -> String -> Object -> T.Text -> Parser a
instance (FromJSON a) => LookupField a where
lookupField tName rec obj key =
case H.lookup key obj of
Nothing -> unknownFieldFail tName rec (T.unpack key)
Just v -> parseJSON v
instance (FromJSON a) => LookupField (Maybe a) where
lookupField _ _ = (.:?)
unknownFieldFail :: String -> String -> String -> Parser fail
unknownFieldFail tName rec key =
fail $ printf "When parsing the record %s of type %s the key %s was not present."
rec tName key
noArrayFail :: String -> String -> Parser fail
noArrayFail t o = fail $ printf "When parsing %s expected Array but got %s." t o
noObjectFail :: String -> String -> Parser fail
noObjectFail t o = fail $ printf "When parsing %s expected Object but got %s." t o
firstElemNoStringFail :: String -> String -> Parser fail
firstElemNoStringFail t o = fail $ printf "When parsing %s expected an Array of 2 elements where the first element is a String but got %s at the first element." t o
wrongPairCountFail :: String -> String -> Parser fail
wrongPairCountFail t n =
fail $ printf "When parsing %s expected an Object with a single tag/contents pair but got %s pairs."
t n
noStringFail :: String -> String -> Parser fail
noStringFail t o = fail $ printf "When parsing %s expected String but got %s." t o
noMatchFail :: String -> String -> Parser fail
noMatchFail t o =
fail $ printf "When parsing %s expected a String with the tag of a constructor but got %s." t o
not2ElemArray :: String -> Int -> Parser fail
not2ElemArray t i = fail $ printf "When parsing %s expected an Array of 2 elements but got %i elements" t i
conNotFoundFail2ElemArray :: String -> [String] -> String -> Parser fail
conNotFoundFail2ElemArray t cs o =
fail $ printf "When parsing %s expected a 2-element Array with a tag and contents element where the tag is one of [%s], but got %s."
t (intercalate ", " cs) o
conNotFoundFailObjectSingleField :: String -> [String] -> String -> Parser fail
conNotFoundFailObjectSingleField t cs o =
fail $ printf "When parsing %s expected an Object with a single tag/contents pair where the tag is one of [%s], but got %s."
t (intercalate ", " cs) o
conNotFoundFailTaggedObject :: String -> [String] -> String -> Parser fail
conNotFoundFailTaggedObject t cs o =
fail $ printf "When parsing %s expected an Object with a tag field where the value is one of [%s], but got %s."
t (intercalate ", " cs) o
parseTypeMismatch' :: String -> String -> String -> String -> Parser fail
parseTypeMismatch' tName conName expected actual =
fail $ printf "When parsing the constructor %s of type %s expected %s but got %s."
conName tName expected actual
--------------------------------------------------------------------------------
-- Utility functions
--------------------------------------------------------------------------------
-- | Boilerplate for top level splices.
--
-- The given 'Name' must be from a type constructor. Furthermore, the
-- type constructor must be either a data type or a newtype. Any other
-- value will result in an exception.
withType :: Name
-> ([TyVarBndr] -> [Con] -> Q a)
-- ^ Function that generates the actual code. Will be applied
-- to the type variable binders and constructors extracted
-- from the given 'Name'.
-> Q a
-- ^ Resulting value in the 'Q'uasi monad.
withType name f = do
info <- reify name
case info of
TyConI dec ->
case dec of
DataD _ _ tvbs cons _ -> f tvbs cons
NewtypeD _ _ tvbs con _ -> f tvbs [con]
other -> error $ "Data.Aeson.TH.withType: Unsupported type: "
++ show other
_ -> error "Data.Aeson.TH.withType: I need the name of a type."
-- | Extracts the name from a constructor.
getConName :: Con -> Name
getConName (NormalC name _) = name
getConName (RecC name _) = name
getConName (InfixC _ name _) = name
getConName (ForallC _ _ con) = getConName con
-- | Extracts the name from a type variable binder.
tvbName :: TyVarBndr -> Name
tvbName (PlainTV name ) = name
tvbName (KindedTV name _) = name
-- | Makes a string literal expression from a constructor's name.
conNameExp :: Options -> Con -> Q Exp
conNameExp opts = litE
. stringL
. constructorTagModifier opts
. nameBase
. getConName
-- | Creates a string literal expression from a record field label.
fieldLabelExp :: Options -- ^ Encoding options
-> Name
-> Q Exp
fieldLabelExp opts = litE . stringL . fieldLabelModifier opts . nameBase
-- | The name of the outermost 'Value' constructor.
valueConName :: Value -> String
valueConName (Object _) = "Object"
valueConName (Array _) = "Array"
valueConName (String _) = "String"
valueConName (Number _) = "Number"
valueConName (Bool _) = "Boolean"
valueConName Null = "Null"
applyCon :: Name -> [Name] -> Q [Pred]
applyCon con typeNames = return (map apply typeNames)
where apply t =
#if MIN_VERSION_template_haskell(2,10,0)
AppT (ConT con) (VarT t)
#else
ClassP con [VarT t]
#endif
| maximkulkin/aeson | Data/Aeson/TH.hs | bsd-3-clause | 33,875 | 0 | 24 | 13,014 | 7,561 | 4,077 | 3,484 | 554 | 6 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.AutoScaling.DescribeAutoScalingInstances
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Describes one or more Auto Scaling instances. If a list is not provided, the
-- call describes all instances.
--
-- You can describe up to a maximum of 50 instances with a single call. By
-- default, a call returns up to 20 instances. If there are more items to
-- return, the call returns a token. To get the next set of items, repeat the
-- call with the returned token in the 'NextToken' parameter.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeAutoScalingInstances.html>
module Network.AWS.AutoScaling.DescribeAutoScalingInstances
(
-- * Request
DescribeAutoScalingInstances
-- ** Request constructor
, describeAutoScalingInstances
-- ** Request lenses
, dasiInstanceIds
, dasiMaxRecords
, dasiNextToken
-- * Response
, DescribeAutoScalingInstancesResponse
-- ** Response constructor
, describeAutoScalingInstancesResponse
-- ** Response lenses
, dasirAutoScalingInstances
, dasirNextToken
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.AutoScaling.Types
import qualified GHC.Exts
data DescribeAutoScalingInstances = DescribeAutoScalingInstances
{ _dasiInstanceIds :: List "member" Text
, _dasiMaxRecords :: Maybe Int
, _dasiNextToken :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'DescribeAutoScalingInstances' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dasiInstanceIds' @::@ ['Text']
--
-- * 'dasiMaxRecords' @::@ 'Maybe' 'Int'
--
-- * 'dasiNextToken' @::@ 'Maybe' 'Text'
--
describeAutoScalingInstances :: DescribeAutoScalingInstances
describeAutoScalingInstances = DescribeAutoScalingInstances
{ _dasiInstanceIds = mempty
, _dasiMaxRecords = Nothing
, _dasiNextToken = Nothing
}
-- | One or more Auto Scaling instances to describe, up to 50 instances. If you
-- omit this parameter, all Auto Scaling instances are described. If you specify
-- an ID that does not exist, it is ignored with no error.
dasiInstanceIds :: Lens' DescribeAutoScalingInstances [Text]
dasiInstanceIds = lens _dasiInstanceIds (\s a -> s { _dasiInstanceIds = a }) . _List
-- | The maximum number of items to return with this call.
dasiMaxRecords :: Lens' DescribeAutoScalingInstances (Maybe Int)
dasiMaxRecords = lens _dasiMaxRecords (\s a -> s { _dasiMaxRecords = a })
-- | The token for the next set of items to return. (You received this token from
-- a previous call.)
dasiNextToken :: Lens' DescribeAutoScalingInstances (Maybe Text)
dasiNextToken = lens _dasiNextToken (\s a -> s { _dasiNextToken = a })
data DescribeAutoScalingInstancesResponse = DescribeAutoScalingInstancesResponse
{ _dasirAutoScalingInstances :: List "member" AutoScalingInstanceDetails
, _dasirNextToken :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'DescribeAutoScalingInstancesResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dasirAutoScalingInstances' @::@ ['AutoScalingInstanceDetails']
--
-- * 'dasirNextToken' @::@ 'Maybe' 'Text'
--
describeAutoScalingInstancesResponse :: DescribeAutoScalingInstancesResponse
describeAutoScalingInstancesResponse = DescribeAutoScalingInstancesResponse
{ _dasirAutoScalingInstances = mempty
, _dasirNextToken = Nothing
}
-- | The instances.
dasirAutoScalingInstances :: Lens' DescribeAutoScalingInstancesResponse [AutoScalingInstanceDetails]
dasirAutoScalingInstances =
lens _dasirAutoScalingInstances
(\s a -> s { _dasirAutoScalingInstances = a })
. _List
-- | The token to use when requesting the next set of items. If there are no
-- additional items to return, the string is empty.
dasirNextToken :: Lens' DescribeAutoScalingInstancesResponse (Maybe Text)
dasirNextToken = lens _dasirNextToken (\s a -> s { _dasirNextToken = a })
instance ToPath DescribeAutoScalingInstances where
toPath = const "/"
instance ToQuery DescribeAutoScalingInstances where
toQuery DescribeAutoScalingInstances{..} = mconcat
[ "InstanceIds" =? _dasiInstanceIds
, "MaxRecords" =? _dasiMaxRecords
, "NextToken" =? _dasiNextToken
]
instance ToHeaders DescribeAutoScalingInstances
instance AWSRequest DescribeAutoScalingInstances where
type Sv DescribeAutoScalingInstances = AutoScaling
type Rs DescribeAutoScalingInstances = DescribeAutoScalingInstancesResponse
request = post "DescribeAutoScalingInstances"
response = xmlResponse
instance FromXML DescribeAutoScalingInstancesResponse where
parseXML = withElement "DescribeAutoScalingInstancesResult" $ \x -> DescribeAutoScalingInstancesResponse
<$> x .@? "AutoScalingInstances" .!@ mempty
<*> x .@? "NextToken"
instance AWSPager DescribeAutoScalingInstances where
page rq rs
| stop (rs ^. dasirNextToken) = Nothing
| otherwise = (\x -> rq & dasiNextToken ?~ x)
<$> (rs ^. dasirNextToken)
| kim/amazonka | amazonka-autoscaling/gen/Network/AWS/AutoScaling/DescribeAutoScalingInstances.hs | mpl-2.0 | 6,046 | 0 | 12 | 1,175 | 726 | 431 | 295 | 78 | 1 |
-- c.f #3613
module T3613 where
import Control.Monad
foo :: Maybe ()
foo = return ()
bar :: IO ()
bar = return ()
fun1 = let fooThen m = foo>> m
in fooThen (bar>> undefined)
fun2 = let fooThen m = foo>> m
in fooThen (do {bar; undefined})
| sdiehl/ghc | testsuite/tests/typecheck/should_fail/T3613.hs | bsd-3-clause | 260 | 0 | 10 | 71 | 121 | 62 | 59 | 10 | 1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
-- | Provide the user with a rich text editor.
module Yesod.Form.Nic
( YesodNic (..)
, nicHtmlField
) where
import Yesod.Core
import Yesod.Form
import Text.HTML.SanitizeXSS (sanitizeBalance)
import Text.Hamlet (shamlet)
import Text.Julius (julius, rawJS)
import Text.Blaze.Html.Renderer.String (renderHtml)
import Data.Text (Text, pack)
import Data.Maybe (listToMaybe)
class Yesod a => YesodNic a where
-- | NIC Editor Javascript file.
urlNicEdit :: a -> Either (Route a) Text
urlNicEdit _ = Right "http://js.nicedit.com/nicEdit-latest.js"
nicHtmlField :: YesodNic site => Field (HandlerT site IO) Html
nicHtmlField = Field
{ fieldParse = \e _ -> return . Right . fmap (preEscapedToMarkup . sanitizeBalance) . listToMaybe $ e
, fieldView = \theId name attrs val _isReq -> do
toWidget [shamlet|
$newline never
<textarea id="#{theId}" *{attrs} name="#{name}" .html>#{showVal val}
|]
addScript' urlNicEdit
master <- getYesod
toWidget $
case jsLoader master of
BottomOfHeadBlocking -> [julius|
bkLib.onDomLoaded(function(){new nicEditor({fullPanel:true}).panelInstance("#{rawJS theId}")});
|]
_ -> [julius|
(function(){new nicEditor({fullPanel:true}).panelInstance("#{rawJS theId}")})();
|]
, fieldEnctype = UrlEncoded
}
where
showVal = either id (pack . renderHtml)
addScript' :: (MonadWidget m, HandlerSite m ~ site)
=> (site -> Either (Route site) Text)
-> m ()
addScript' f = do
y <- getYesod
addScriptEither $ f y
| Daniel-Diaz/yesod | yesod-form/Yesod/Form/Nic.hs | mit | 1,714 | 0 | 13 | 358 | 402 | 222 | 180 | 38 | 2 |
{-# LANGUAGE DeriveFunctor #-}
module Type where
import qualified Data.List as List
import qualified Data.Set as Set
import Data.Set(Set)
import Expr(Expr(..))
import FreeVars
-- Data definitions
type TyVar = String
data BaseType a =
TBool |
TInt |
TFun a (BaseType a) (BaseType a) |
TVar TyVar
deriving (Eq, Functor)
type Type = BaseType AnVar
type AnVar = String
data Annotation = AFun | AClo deriving (Eq, Ord, Show)
type Type2 = BaseType (Set Annotation)
data BaseTypeSchema ty =
TSType ty |
TSForall TyVar (BaseTypeSchema ty)
deriving (Eq, Functor)
type TypeSchema = BaseTypeSchema Type
type TypeSchema2 = BaseTypeSchema Type2
type TyExpr = Expr TypeSchema Type
type TyExpr2 = Expr TypeSchema2 Type2
-- Type classes instances
instance Show a => Show (BaseType a) where
show TBool = "bool"
show TInt = "int"
show (TFun b t1 t2) =
"(" ++ show t1 ++ " ->{" ++ show b ++ "} " ++ show t2 ++ ")"
show (TVar x) = x
instance Show a => Show (BaseTypeSchema a) where
show (TSType t) = show t
show (TSForall x t) = "forall " ++ x ++ ". " ++ show t
instance FreeVars (BaseType a) where
freeVars TBool = []
freeVars TInt = []
freeVars (TFun _ t1 t2) = List.union (freeVars t1) (freeVars t2)
freeVars (TVar x) = [x]
instance FreeVars ty => FreeVars (BaseTypeSchema ty) where
freeVars (TSType ty) = freeVars ty
freeVars (TSForall x ty) = List.delete x (freeVars ty)
| authchir/mini-ml | src/Type.hs | isc | 1,418 | 0 | 12 | 303 | 557 | 295 | 262 | 43 | 0 |
module Constants where
timestep = 0.01
updatesPerFrame = 1 :: Int
numStars = 1000
massOfStar = 1.0
goldenAngle = pi * (3.0 - (sqrt 5.0))
softeningLength = 0.01
forgetDistance = 10.0
treeForceAccuracy = 0.1
bigG = 0.001
| pauldoo/scratch | NBody/Constants.hs | isc | 221 | 0 | 9 | 39 | 69 | 41 | 28 | 10 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
module Network.API.Mandrill.Messages.Types where
import Data.Char
import Data.Time
import qualified Data.Text as T
import Control.Monad
import Data.Monoid
import Data.Aeson
import Data.Aeson.Types
import Data.Aeson.TH
import Lens.Micro.TH (makeLenses)
import Network.API.Mandrill.Types
--------------------------------------------------------------------------------
data MessagesSendRq = MessagesSendRq {
_msrq_key :: MandrillKey
, _msrq_message :: MandrillMessage
, _msrq_async :: Maybe Bool
, _msrq_ip_pool :: Maybe T.Text
, _msrq_send_at :: Maybe UTCTime
} deriving Show
makeLenses ''MessagesSendRq
deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''MessagesSendRq
--------------------------------------------------------------------------------
data MessagesSendTemplateRq = MessagesSendTemplateRq {
_mstrq_key :: MandrillKey
, _mstrq_template_name :: T.Text
, _mstrq_template_content :: [MandrillTemplateContent]
, _mstrq_message :: MandrillMessage
, _mstrq_async :: Maybe Bool
, _mstrq_ip_pool :: Maybe T.Text
, _mstrq_send_at :: Maybe UTCTime
} deriving Show
makeLenses ''MessagesSendTemplateRq
deriveJSON defaultOptions { fieldLabelModifier = drop 7 } ''MessagesSendTemplateRq
--------------------------------------------------------------------------------
data MessagesResponse = MessagesResponse {
_mres_email :: !T.Text
-- ^ The email address of the recipient
, _mres_status :: MandrillEmailStatus
-- ^ The sending status of the recipient
, _mres_reject_reason :: Maybe MandrillRejectReason
-- ^ The reason for the rejection if the recipient status is "rejected"
, _mres__id :: !T.Text
-- ^ The message's unique id
} deriving Show
makeLenses ''MessagesResponse
deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''MessagesResponse
| adinapoli/mandrill | src/Network/API/Mandrill/Messages/Types.hs | mit | 2,044 | 0 | 10 | 414 | 336 | 195 | 141 | 45 | 0 |
module Occupation where
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.List as List
{--
-
- From 101 Puzzles in Thought and Logic, problem 6.
-
- Clark, Jones, Morgan, and Smith are four men whose occupation are
- butcher,
- druggist, grocer, and policeman, though not necessarily respectively.
-
- * Clark and Jones are neighbors and take turns driving each other to work
- * Jones makes more money than Morgan
- * Clark beats Smith regularly at bowling
- * The butcher always walks to work
- * The policeman does not live near the druggist
- * The only time the grocer and the policeman ever met was when the
- policeman
- arrested the grocer for speeding
- * The policeman makes more money than the druggist or the grocer
-
- WHAT IS EACH MAN'S OCCUPATION?
-
- --}
data Man = Clark | Jones | Morgan | Smith
deriving (Eq, Ord, Enum, Show, Read)
data Job = Butcher | Druggist | Grocer | Policeman
deriving (Eq, Ord, Enum, Show, Read)
men :: [Man]
men = [Clark, Jones, Morgan, Smith]
jobs :: [Job]
jobs = [Butcher, Druggist, Grocer, Policeman]
pairs :: [[(Man, Job)]]
pairs = map (zip men) $ List.permutations jobs
pairsSet :: Set (Set (Man, Job))
pairsSet = Set.fromList $ map Set.fromList pairs
invalid :: [(Man, Job)] -> Set (Man, Job) -> Bool
invalid ps s = not $ any ((flip Set.member) s) ps
occupation :: Set (Set (Man, Job))
occupation = Set.filter (invalid [(Clark, Butcher), (Jones, Butcher)]) pairsSet
dcfM :: Double -> Int -> Double -> Double -> Double
dcfM interestRate growthYears growth termalGrowth = growthValue + terminalValue where
growthValue :: Double
growthValue = sum $ take growthYears $ List.iterate (* (discount * growth)) 1.0
terminalValue = sum $ take 1000 $ List.iterate (* (discount * termalGrowth)) terminalEarning
terminalEarning :: Double
terminalEarning = (discount * growth) ** (fromIntegral growthYears)
discount :: Double
discount = 1.0 - interestRate
dcfM2 :: Double -> Double -> Double -> Double
dcfM2 _ _ n | n <= 0 = 0.0
dcfM2 d g n = ((g ** n) * ((1.0 - d) ** n)) + (dcfM2 d g (n-1))
newtype StartingAmount = StartingAmount { unStarting :: Double }
newtype TargetAmount = TargetAmount { unTarget :: Double }
newtype GrowthRate = GrowthRate{ unGrowth:: Double }
newtype CashFlow = CashFlow { unCashFlow :: Double }
netWorthsAfterYears :: StartingAmount -> GrowthRate -> CashFlow -> Int -> [Double]
netWorthsAfterYears (StartingAmount sa) (GrowthRate gr) (CashFlow cf) y =
List.scanl (\a i -> a * gr + cf) sa [1..y]
netWorths :: StartingAmount -> TargetAmount -> GrowthRate -> CashFlow -> [Int]
netWorths (StartingAmount c) (TargetAmount t) (GrowthRate r) (CashFlow s) =
if (nextValue < c)
then [round nextValue]
else (round nextValue) : netWorths (StartingAmount c) (TargetAmount nextValue) (GrowthRate r) (CashFlow s) where
nextValue = (t / r) - s
| nlim/haskell-playground | src/Occupation.hs | mit | 2,910 | 0 | 11 | 571 | 896 | 498 | 398 | 45 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module CountdownGame.Actions
( anleitung
, play
, register
, postRegister
, admin
, highScores
, getPlayers
, getSnapshot
, evalFormula
, isLocalhost
)where
import Debug.Trace (trace)
import Control.Monad.IO.Class(liftIO)
import Data.Char (toLower)
import Data.List(isPrefixOf)
import Data.Maybe(isNothing, fromJust, isJust)
import Data.Text.Lazy (Text, unpack)
import qualified Data.Text as T
import Web.Scotty
import qualified Web.Scotty as S
import Text.Blaze.Html (Html)
import Text.Blaze.Html.Renderer.Text (renderHtml)
import Text.Blaze.Html5 (link, (!))
import Text.Blaze.Html5.Attributes
import Network.Socket (SockAddr(..))
import Network.Wai (remoteHost)
import Countdown.Game (PlayerId)
import qualified Countdown.Game as G
import CountdownGame.Spiel (State)
import qualified CountdownGame.Spiel as Spiel
import qualified CountdownGame.Players as Players
import qualified CountdownGame.Database as Rep
import qualified CountdownGame.Views.Anleitung as AnleitungView
import qualified CountdownGame.Views.Play as PlayView
import qualified CountdownGame.Views.Register as RegisterView
import qualified CountdownGame.Views.Admin as AdminView
import qualified CountdownGame.Views.Highscores as ScoresView
-- * controller actions
anleitung :: ActionM ()
anleitung = render AnleitungView.render
play :: State -> ActionM ()
play state = do
player <- Players.registeredPlayer state
if isNothing player
then redirect "/register"
else render $ PlayView.render (fromJust player)
register :: ActionM ()
register = render RegisterView.render
postRegister :: State -> ActionM ()
postRegister state = do
name <- param "nickName"
Players.registerPlayer name state
redirect "/play"
admin :: State -> ActionM ()
admin state = do
localhost <- isLocalhost
if not localhost
then raise "you are not allowed"
else render (AdminView.render state)
highScores :: State -> ActionM ()
highScores state = do
scores <- liftIO $ Rep.getHighscores (Spiel.connectionPool state)
render (ScoresView.render scores)
-- * Web-API Part
getPlayers :: State -> ActionM ()
getPlayers state = do
players <- liftIO $ Rep.getPlayers (Spiel.connectionPool state)
localhost <- isLocalhost
if not localhost
then raise "you are not allowed to do that"
else json players
getSnapshot :: State -> ActionM ()
getSnapshot state = do
isHost <- isLocalhost
regPlayer <- isJust <$> Players.registeredPlayer state
if not regPlayer
then raise "you are not allowed to do that"
else do
snap <- liftIO $ Spiel.takeSnapshot state
json snap
evalFormula :: State -> ActionM ()
evalFormula state = do
formula <- param "formula"
pl <- Players.registeredPlayer state
case pl of
Just pl' -> do
att <- liftIO $ Spiel.versuchHinzufuegen (Spiel.aktuellePhase state) (Rep.setPlayerScore (Spiel.connectionPool state)) pl' formula
json att
Nothing -> raise "kein Spieler registriert"
-- * Helpers
-- ** rendering
render :: Html -> ActionM ()
render html = do
blaze $ do
link ! rel "stylesheet" ! href "styles.css" ! type_ "text/css"
html
blaze :: Html -> ActionM ()
blaze = S.html . renderHtml
-- ** access checks
isLocalhost :: ActionM Bool
isLocalhost = do
remote <- remoteHost <$> request
return $ hostnameIsLocal remote
where hostnameIsLocal sockAdr =
"127.0.0.1" `isPrefixOf` show sockAdr ||
"localhost" `isPrefixOf` (map toLower . show) sockAdr
| CarstenKoenig/Countdown | src/web/CountdownGame/Actions.hs | mit | 3,608 | 0 | 19 | 726 | 1,011 | 539 | 472 | 102 | 2 |
import System.IO
import System.Exit
import System.Environment(getArgs)
import Data.List
import Data.Char
-- General functions
genBigPuzzle :: [Int] -> [[Int]]
genBigPuzzle [] = []
genBigPuzzle lst
| ((head lst) == 0) = [[0..9]] ++ (genBigPuzzle (tail lst))
| otherwise = [ [head lst] ] ++ (genBigPuzzle (tail lst))
genSmallPuzzle :: [[Int]] -> [Int]
genSmallPuzzle [] = []
genSmallPuzzle lst = [head (head lst)] ++ genSmallPuzzle (tail lst)
accessCell row col = (row*9) + col
rowAccess accnum = accnum `quot` 9
colAccess accnum = (accnum - (9*(rowAccess accnum)))
startnum n = ((n `quot` 3) * 3)
endnum n = (startnum n) + 2
reduceSolved (0:x:[]) = [x]
reduceSolved xs = xs
countPossib [ ] = 0
countPossib pzl = (length (tail (head pzl))) + (countPossib (tail pzl))
countUnknown pzl = countUnknown' pzl 0
countUnknown' [] n = n
countUnknown' pzl n
| ((head (head pzl)) == 0) = countUnknown' (tail pzl) (n+1)
| otherwise = countUnknown' (tail pzl) n
countMatches lst x = countMatches' lst x 0
countMatches' [] _ n = n
countMatches' (x:xs) y n
| (x == y) = countMatches' xs y (n+1)
| otherwise = countMatches' xs y n
onlyUnique lst = onlyUnique' lst (nub lst)
onlyUnique' lst [] = []
onlyUnique' lst (x:xs)
| ((countMatches lst x) > 1) = onlyUnique' lst xs
| otherwise = [x] ++ onlyUnique' lst xs
transRowCol :: [[Int]] -> [[Int]]
transRowCol pzl = transRowCol' pzl 0
transRowCol' pzl 81 = []
transRowCol' pzl n = [( pzl !! (accessCell (colAccess n) (rowAccess n)) )] ++ transRowCol' pzl (n+1)
trans3x3Row :: [[Int]] -> [[Int]]
trans3x3Row pzl = trans3x3Row' pzl [0..2] [0..2]
trans3x3Row' pzl [ ] _ = []
trans3x3Row' pzl (x:xs) [ ] = trans3x3Row' pzl xs [0..2]
trans3x3Row' pzl (x:xs) (y:ys) = trans3x3Row'' pzl [(x*3)..((x*3)+2)] [(y*3)..((y*3)+2)] (y*3) ++ trans3x3Row' pzl (x:xs) ys
trans3x3Row'' pzl [ ] _ _ = []
trans3x3Row'' pzl (x:xs) [ ] m = trans3x3Row'' pzl (xs) [m..(m+2)] m
trans3x3Row'' pzl (x:xs) (y:ys) m = [(pzl !! (accessCell x y))] ++ trans3x3Row'' pzl (x:xs) (ys) m
-- Rule 1
rule1Row pzl row = nub $ filter (>0) $ rule1Row' pzl row 0 8
rule1Row' pzl row n maxx
| (n > maxx) = []
| otherwise = (head (pzl !! (accessCell row n))) : (rule1Row' pzl row (n + 1) maxx)
checkRule1' pzl = checkRule1'' pzl pzl 0
checkRule1'' _ [] _ = []
checkRule1'' ppzl pzl n
| ((head (head pzl)) == 0) = [(reduceSolved . filter f) (head pzl)] ++ (checkRule1'' ppzl (tail pzl) (n+1))
| otherwise = [head pzl] ++ (checkRule1'' ppzl (tail pzl) (n+1))
where
f x = x `notElem` (rule1Row ppzl (rowAccess n))
checkRule1 pzl = do
n <- return $ countUnknown pzl
pzl1 <- return $ trans3x3Row $ checkRule1' $ trans3x3Row $ transRowCol $ checkRule1' $ transRowCol $ checkRule1' pzl
m <- return $ countUnknown pzl1
putStrLn $ "checkRule1, unknowns = " ++ (show m)
if (n == m)
then
do
return $ pzl1
else
do
checkRule1 pzl1
-- Rule 2
rule2RowReduce pzl row lst = rule2RowReduce' pzl [0..8] [0..8] lst row
rule2RowReduce' pzl [] _ _ _ = []
rule2RowReduce' pzl (x:xs) [] lst row = rule2RowReduce' pzl xs [0..8] lst row
rule2RowReduce' pzl (x:xs) (y:ys) [] row = [(pzl !! (accessCell x y))] ++ rule2RowReduce' pzl (x:xs) ys [] row
rule2RowReduce' pzl (x:xs) (y:ys) (z:zs) row
| (x == row)&&(z `elem` (tail (pzl !! (accessCell x y)))) = [[z]] ++ rule2RowReduce' pzl (x:xs) ys [] row
| otherwise = [(pzl !! (accessCell x y))] ++ rule2RowReduce' pzl (x:xs) ys (z:zs) row
rule2Row pzl = rule2Row' pzl [0..8] [0..8] []
rule2Row' pzl [ ] _ _ = pzl
rule2Row' pzl (x:xs) [ ] [ ] = rule2Row' pzl xs [0..8] []
rule2Row' pzl (x:xs) [ ] lst
| (uniqlst == []) = rule2Row' pzl xs [0..8] []
| otherwise = rule2RowReduce pzl x uniqlst
where
uniqlst = onlyUnique lst
rule2Row' pzl (x:xs) (y:ys) lst = rule2Row' pzl (x:xs) ys (lst ++ tail (pzl !! (accessCell x y) ))
checkRule2 pzl = do
n <- return $ countUnknown pzl
pzl1 <- return $ rule2Row pzl
m <- return $ countUnknown pzl1
putStrLn $ "checkRule2 rows, unknowns = " ++ (show m)
if (m == n)
then
do
pzl2 <- return $ transRowCol $ rule2Row $ transRowCol pzl1
k <- return $ countUnknown pzl2
putStrLn $ "checkRule2 cols, unknowns = " ++ (show k)
if (k == n)
then
do
pzl3 <- return $ trans3x3Row $ rule2Row $ trans3x3Row pzl2
p <- return $ countUnknown pzl3
putStrLn $ "checkRule2 3x3s, unknowns = " ++ (show p)
return $ pzl3
else
do
return $ pzl2
else
do
return $ pzl1
-- Rule 3
singleNumIn3sGroup pzl row = onlyUnique $ singleNumIn3sGroup' pzl row [0..8] []
singleNumIn3sGroup' _ _ [] _ = []
singleNumIn3sGroup' pzl row (x:xs) lst
| ((x+1) `mod` 3 == 0) = (nub addTailToLst) ++ singleNumIn3sGroup' pzl row xs []
| otherwise = singleNumIn3sGroup' pzl row xs addTailToLst
where
addTailToLst = lst ++ (tail $ pzl !! (accessCell row x))
findColWithElem pzl row elm = findColWithElem' pzl row [0..8] elm
-- should not reach xs == []
findColWithElem' pzl row (x:xs) elm
| (elm `elem` (cell pzl row x)) = x
| otherwise = findColWithElem' pzl row xs elm
where
cell pzl a b
| (length (pzl !! (accessCell a b))) > 1 = tail (pzl !! (accessCell a b))
| otherwise = [0]
reduceElements elm (x:[]) = [x]
reduceElements elm (x:xs) = [x] ++ (filter (/= elm) xs)
removeFromOthers pzl row col elm = removeFromOthers' pzl row col elm 0
removeFromOthers' _ _ _ _ 81 = []
removeFromOthers' pzl row col elm n
| (r == row) = [(pzl !! n)] ++ nxt
| ((checkx r row) && (checkx c col)) = [reduceElements elm (pzl !! n)] ++ nxt
| otherwise = [(pzl !! n)] ++ nxt
where
r = rowAccess n
c = colAccess n
checkx x y = (x >= startnum y) && (x <= endnum y)
nxt = removeFromOthers' pzl row col elm (n+1)
head'' [] = 19
head'' (x:xs) = x
chkChanged p1 p2 xs
| (countPossib p1) == (countPossib p2) = xs
| otherwise = []
checkRule3' pzl = checkRule3'' pzl [0..8]
checkRule3'' pzl [] = pzl
checkRule3'' pzl (row:xs)
| elme /= 19 = checkRule3'' rfo (chkChanged rfo pzl xs)
| otherwise = checkRule3'' pzl xs
where
elme = head'' $ singleNumIn3sGroup pzl row
rfo = (removeFromOthers pzl row (findColWithElem pzl row elme) elme)
checkRule3 pzl = do
n <- return $ countPossib pzl
pzl1 <- return $ checkRule3' pzl
m <- return $ countPossib pzl1
putStrLn $ "checkRule3 rows, possib = " ++ (show n) ++ " --> " ++ (show m)
if (m == n)
then
do
pzl2 <- return $ transRowCol $ checkRule3' $ transRowCol pzl1
k <- return $ countPossib pzl2
putStrLn $ "checkRule3 cols, possib = " ++ (show m) ++ " --> " ++ (show k)
if (k == n)
then
do
pzl3 <- return $ trans3x3Row $ checkRule3' $ trans3x3Row pzl2
p <- return $ countPossib pzl3
putStrLn $ "checkRule3 3x3s, possib = " ++ (show k) ++ " --> " ++ (show p)
return $ pzl3
else
do
return $ pzl2
else
do
return $ pzl1
-- I/O and main
solve pzl = do
n <- return $ countUnknown pzl
putStrLn $ "Solving ... " ++ (show n) ++ " unknowns remaining"
pzl1 <- checkRule1 pzl
pzl2 <- checkRule2 pzl1
m <- return $ countUnknown pzl2
if (m /= 0)
then
do
if (m == n)
then
do
k1 <- return $ countPossib pzl2
pzl3 <- checkRule3 pzl2
k2 <- return $ countPossib pzl3
if (k1 == k2)
then
do
return $ pzl3
else
do
solve pzl3
else
do
solve pzl2
else
do
return $ pzl2
prettyprint chs = prettyprint' chs 0
prettyprint' [] _ = do
putStrLn ""
prettyprint' chs n = do
putStr $ [intToDigit (head chs)]
m <- return $ n + 1
if (m `mod` 3 == 0)
then
do
putStr " "
else
do
return ()
if (m `mod` 9 == 0)
then
do
putStrLn ""
else
do
return ()
if (m `mod` 27 == 0)
then
do
putStrLn ""
prettyprint' (tail chs) m
else
do
prettyprint' (tail chs) m
checkSolved 0 = "Success!"
checkSolved _ = "Failed!"
main = do
args <- getArgs
puzzle <- return $ map (digitToInt) (head args)
if ((length puzzle) == 81)
then
do
a <- return $ genBigPuzzle $ puzzle
prettyprint $ genSmallPuzzle a
b <- solve a
n <- return $ countUnknown b
putStrLn ""
prettyprint $ genSmallPuzzle b
putStrLn $ checkSolved n
putStrLn ""
return ()
else
do
putStrLn "Number of integers entered was not 81"
return ()
| ruben2020/small-haskell-proj | sudoku_solver/sudsolv.hs | mit | 9,479 | 13 | 17 | 3,191 | 4,020 | 2,019 | 2,001 | 224 | 4 |
module Network.Freddy.CorrelationIdGenerator (CorrelationId, generateCorrelationId) where
import System.Random (randomIO)
import qualified Data.UUID as UUID
import Data.UUID (UUID)
import Data.Text (Text)
type CorrelationId = Text
generateCorrelationId :: IO CorrelationId
generateCorrelationId = do
uuid <- newUUID
return $ UUID.toText uuid
newUUID :: IO UUID
newUUID = randomIO
| salemove/freddy-hs | src/Network/Freddy/CorrelationIdGenerator.hs | mit | 388 | 0 | 9 | 52 | 104 | 60 | 44 | 12 | 1 |
{-# Language RankNTypes #-}
module Unison.Runtime.Journal where
import Control.Concurrent (forkIO)
import Control.Concurrent.STM (STM, atomically)
import Control.Concurrent.STM.TSem
import Control.Concurrent.STM.TVar
import Control.Concurrent.STM.TQueue
import Control.Exception
import Control.Monad
import Data.List
import Data.Maybe
import Unison.BlockStore (BlockStore)
import Unison.Runtime.Block (Block)
import qualified Unison.Runtime.Block as Block
type VisibleNow = Bool
-- | `flush` flushes the updates to the store
data Updates u = Updates { flush :: STM (), append :: VisibleNow -> u -> STM (STM ()) }
-- | A sequentially-updated, persistent `a` value. `get` obtains the current value.
-- `updates` can be used to append updates to the value. `recordAsync` produces a new
-- checkpoint and clears `updates`. It is guaranteed durable when the inner `STM ()` completes.
data Journal a u = Journal { get :: STM a
, updates :: Updates u
, recordAsync :: STM (STM ())
}
-- | Record a new checkpoint synchronously. When the returned `STM` completes,
-- the checkpoint is durable.
record :: Journal a u -> IO ()
record j = atomically (recordAsync j) >>= atomically
-- | Updates the journal; invariant here is that after inner `STM ()` is run, updates are durable
-- and also visible in memory. Updates _may_ be durable and visible before
-- that but this isn't guaranteed.
updateAsync :: u -> Journal a u -> STM (STM ())
updateAsync u j = append (updates j) False u
-- | Updates the journal; updates are visible immediately, but aren't necessarily
-- durable until the `STM ()` is run.
updateNowAsyncFlush :: u -> Journal a u -> STM (STM ())
updateNowAsyncFlush u j = append (updates j) True u
-- | Updates the journal; updates are visible and durable when this function returns.
update :: u -> Journal a u -> IO ()
update u j = do
force <- atomically $ updateNowAsyncFlush u j
atomically force
-- | Create a Journal from two blocks, an identity update, and a function for applying
-- an update to the state.
fromBlocks :: Eq h => BlockStore h -> (u -> a -> a) -> Block a -> Block (Maybe u) -> IO (Journal a u)
fromBlocks bs apply checkpoint us = do
current <- Block.get bs checkpoint
us' <- (pure . catMaybes) =<< sequenceA =<< Block.gets bs us
current <- atomically $ newTVar (foldl' (flip apply) current us')
updateQ <- atomically $ newTQueue
latestEnqueue <- atomically $ newTVar (pure ())
err <- atomically $ newTVar Nothing
get <- pure $ readTVar err >>= maybe (readTVar current) fail
let flush = join $ get >> readTVar latestEnqueue
append <- pure $ \vnow u -> do
cur <- get
done <- newTSem 0
writeTVar latestEnqueue (waitTSem done <* get)
writeTQueue updateQ (Just (u, vnow), signalTSem done)
let cur' = apply u cur --maybe cur (`apply` cur) u
(waitTSem done <* get) <$
if vnow then cur' `seq` writeTVar current cur'
else pure ()
_ <- forkIO . forever $ do
-- write updates to BlockStore asynchronously, notifying of completion or errors
(uvnow, done) <- atomically $ readTQueue updateQ -- will die when the `Journal` gets GC'd
id $
let
handle :: SomeException -> IO ()
handle e = atomically $ modifyTVar' err (const (Just . show $ e))
in case uvnow of
Nothing -> do
now <- atomically get
_ <- catch (Block.modify' bs checkpoint (const now) >>
Block.modify' bs us (const Nothing) >>
pure ())
handle
atomically done
Just (u, vnow) ->
catch (Block.append bs us (Just u) >> update) handle
where
update | not vnow = atomically $ done >> modifyTVar' current (apply u)
| otherwise = atomically done
pure $ Journal get (Updates flush append) (record updateQ get)
where
record updateQ get = do
done <- newTSem 0
writeTQueue updateQ (Nothing, signalTSem done)
pure $ waitTSem done <* get
-- | Log a new checkpoint every `updateCount` updates made to the returned journal
checkpointEvery :: Int -> Journal a u -> STM (Journal a u)
checkpointEvery updateCount (Journal get updates record) = tweak <$> newTVar 0 where
tweak count =
let
record' = writeTVar count (0 :: Int) >> record
append' vnow u = do
done <- modifyTVar' count (1+) >> append updates vnow u
count' <- readTVar count
case count' of
_ | count' >= updateCount -> record'
| otherwise -> pure done
in Journal get (Updates (flush updates) append') record'
| nightscape/platform | node/src/Unison/Runtime/Journal.hs | mit | 4,654 | 0 | 26 | 1,156 | 1,347 | 670 | 677 | 83 | 3 |
doubleMe x = x + x
doubleUs x y = doubleMe x + doubleMe y {- x y = x * 2 + y * 2 -}
doubleSmallNumber x = if x > 100 then x else x*2
doubleSmallNumber' x = (if x > 100 then x else x*2) + 2
a'B = "A'B cd"
{- リスト内包表記 -}
boomBangs xs = [ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x, x /= 9] {- odd(奇数) even(偶数)-}
length' xs = sum [1 | _ <- xs]{- length関数を独自に定義。同じ挙動。使い捨ての関数_を1にして全て足す。 -}
{- 関数に明示的に型宣言を与えることができる。型がわからない場合は:t で調べれる。 -}
removeNonUppercase :: [Char] -> [Char] {- 一つの文字列を引数として取り、別の文字列を結果として返す -}
removeNonUppercase st = [c | c <- st, c `elem` ['A'..'Z']]{- 大文字だけを残す -}
removeNonEven xxs = [[x | x <- xs, even x] | xs <- xxs]{- (例)removeNonEven [[1,2,3,4],[10,11,12,13]]で奇数を除いたリストのリスト作成。
(偶数だけを取り出した) -}
{- [1,2,3] リスト , (1,'a',"hello") タプル -}
{- [(1,2),(3,4,5),(6,7)] ペアとトリプルを混在させるとエラーとなる。数のリストの場合[[1,2],[3,4,5],[6,7]]はエラーなし。 -}
{- ペアを操作するための関数。fst(ペアの一つ目の要素を返す)、snd(ペアの二つ目の要素を返す)。 -}
{- zip [1..5] ['a'..'e'] ペアのリストを簡単に作るzip関数。長さが違う型同士なら余りは省かれる。
zip [1..] ['a'..'e'] 無限リストと有限リストをzipすることもできる。 -}
{- 直角三角形を見つけるプログラム (cが斜辺、3辺は全て整数、各辺は10以下、周囲の長さは24に等しい。)-}
{- まず各要素が10以下になるようなトリプルを生成(10^3で1000通り) -> 次にピタゴラスの定理が成り立つかを調べる述語を追加し、
直角三角形でないものをフィルタリング(aが斜辺cを超えないように、直角三角形は必ず斜辺が一番長いので。bがaを超えないように、b>a,a>b本質的には同じ三角形が
含まれてしまうので。) -> 周囲の長さが24のものだけを出力 -}
triangles = [(a,b,c) | c <- [1..10], a <- [1..c], b <- [1..a], a^2 + b^2 == c^2, a+b+c == 24]
{- Haskellの型について -}
factorial :: Integer -> Integer {- Integer(有界ではない 7.2)、Int(有界である 7) -}
factorial n = product [1..n] {- product(階乗をする関数) -}
circumference :: Float -> Float {- Float(単精度浮動小数点数) -}
circumference r = 2 * pi * r {- 円周を求める式 -}
circumference' :: Double -> Double {- Double(倍精度浮動小数点数。Floatの2倍。) -}
circumference' r = 2 * pi * r
{- 型クラス -}
{- ghci> :t (==) 「型を調べたい場合、他の関数に渡したい場合、前置関数として呼び出したい場合は()で囲む」
(==) :: (Eq a) => a -> a -> Bool 「等値性関数は、同じ型の任意の2つの引数を取り、Boolを返す。引数の2つの値の型は
Eqクラスのインスタンスでなければならい。と読む。」 -}
{- Eq型クラス -> 等値性をテストできる型に使われる。==, /= -}
{- Ord型クラス -> 大小比較をテストする。>, <, >=, <=, compare(5 `compare` 3 -> GT「Greater Than:5は3より大きい」, 3 `compare` 5 -> LT「Less Than:3は5より小さい」) -}
{- Show型クラス -> 文字列として表現する。show :: Show a => a -> String -}
{- Read型クラス -> showの対をなす型クラス。文字列を受け取り、readのインスタンスの型の値を返す。Read a => String -> a -}
{- read "4"と書いたのでは型を推論できないので何を返せばいいのかわからずエラーとなる。問題を解決するためには”型注釈”を用いる。
式の終わりに::を追記し明示的に型を教えてあげる手段。例)read "5" :: Int -}
{- Enum型クラス -> 順番に並んだ型、つまり要素の値を列挙できる型。例)['a'..'e'], succ 'B'(後者関数), pred 'C'(前者関数) -}
{- Bounded型クラス -> 上限下限を持ちそれぞれminBound, maxBound関数で調べることができる。maxBound :: Bounded a => a という型を持っている。いわば多相定数。 -}
{- maxBound :: (Bool, Int, Char) -> (True, 2147483647, '\1114111') タプル全ての構成要素がBoundedインスタンスならばタプル自身もBoundedになる。 -}
{- Num型クラス -> 数の型クラス。1, 2, 3(:t 20 -> 20 :: Num a => a 多相定数として表現されていてNum型クラスの任意のインスタンス[Int, Integer, Float, Double]として
振る舞うことができる。) -}
{- *(2つの数を受け取って1つの数を返すNum型クラス、これら3つの数は全て同じ型であることを示す。)
なので、(5 :: Int) * (6 :: Integer)は型エラーになり、5 * (6 :: Integer)は正しく動く。5はIntegerやIntとして振る舞うことができるが同時に両方にはなれない。 -}
{- Float型クラス -> FloatとDoubleが含まれる。浮動小数点数に使う。sin、cos、sqrt -}
{- Integral型クラス -> 数の型クラス。Numが実数を含む全ての数を含む一方、Integralには整数(全体)のみが含まれる。Int、Integer、fromIntegral(fromIntegral :: (Integral a, Num b) => a -> b
複数の型クラス制約があることに注目。複数の型クラス制約を書くときはカンマ(,)で区切って括弧で囲む。) -}
{- fromIntegralは何らかの整数を引数に取り、もっと一般的な数を返す。整数と浮動小数点数を一緒に使いたい時にとても役たつ。
例えば、length関数はa -> Intのような型宣言を持っています。そのためリストの長さを取得してそれに3.2を加えるような式はエラーになる。(IntとFloatを足し合わせるため。)
それを解決するためにflomIntegralを使ってこうする。fromIntegral (length [1,2,3,4]) + 3.2 -> 7.2 -}
{- パターンマッチ -> パターンは上から下の順に試される-}
lucky :: Int -> String
lucky 7 = "LUCKY NUMBER SEVEN!"
lucky x = "Sorry, you're out of luck,pal!"
{- それぞれ数字を文字で出力しそれ以外を別の文章で出力する -}
{- パターンマッチ版 -}
sayMe :: Int -> String
sayMe 1 = "One!"
sayMe 2 = "Two!"
sayMe 3 = "Three!"
sayMe 4 = "Four!"
sayMe 5 = "Five!"
sayMe x = "Not between 1 and 5"
{- if/then/else版 -}
sayMe' :: Int -> String
sayMe' x = if x == 1 then "One!"
else if x == 2 then "Two!"
else if x == 3 then "Three!"
else if x == 4 then "Four!"
else if x == 5 then "Five!"
else "Not between 1 and 5"
{- ポイントはパターンマッチの方が単純に書ける点と"Not bet..."を先頭に持ってこないこと。先頭に持ってきた場合この関数は常に"Not bet..."を出力する。 -}
{- 階乗 product[1..n]を再帰的(その関数の定義の中で自分自身を呼び出す)に定義する。
まず「0の階乗は1」と定義。次に「すべての正の整数の階乗は、その整数とそれから1を引いたものの階乗の積」と定義。 -}
factorial' :: Int -> Int
factorial' 0 = 1
factorial' n = n * factorial' (n - 1)
{- パターンマッチ失敗例 -}
charName :: Char -> String
charName 'a' = "Albert"
charName 'b' = "Broseph"
charName 'c' = "Cecil"
{- この関数は予期しない値が入力されるとエラーとなる。 -}
{- ghci> charName 'h'などa,b,c以外でエラー。Non-exhaustive patterns(パターンが網羅的でない) -}
charName x = "UNKNOWN"{- これでエラーを回避できる。 -}
{- タプルのパターンマッチ -}
{- パターンマッチでない場合 -}
addVectors :: (Double, Double) -> (Double, Double) -> (Double, Double)
addVectors a b = (fst a + fst b, snd a + snd b)
{- aというタプルの最初の値(2番目の値)と、bというタプルの最初の値(2番目の値)を足す関数。引数がaとかbとかじゃなんなのか解らない(タプルなのに)。 -}
{- これをパターンマッチを使って置き換える。↓ -}
addVectors' :: (Double, Double) -> (Double, Double) -> (Double, Double)
addVectors' (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
{- こちらの方が引数がタプルであることがわかりやすく、タプルの要素に適切な名前が付いているので読みやすい。これで全てに合致するパターンになっている。 -}
{- Doubleのペアが2つ引数に来ることは保証済み。 -}
{- fst, sndとペアの要素を分解できるがトリプルに対しては?トリプル以降は独自に定義する。 -}
first :: (a, b, c, d) -> a
first (x, _, _, _) = x
second :: (a, b, c, d) -> b
second (_, y, _, _) = y
third :: (a, b, c, d) -> c
third (_, _, z, _) = z
fourth :: (a, b, c, d) -> d
fourth (_, _, _, s) = s
{- リスト内包表記の時にも触れたが、_は使い捨ての変数を表すために用いる。 -}
{- リストのパターンマッチとリスト内包表記 -}
{- リスト内包表記でもパターンマッチ
ghci> let xs = [(1,3),(4,3),(2,4),(5,3),(5,6),(3,1)]
ghci> [a+b | (a,b) <- xs]
[4,7,6,8,11,4] -}
{- リスト内包表記のパターンマッチでは失敗したら単に次の要素に進み、失敗した要素は結果のリストに含まれません。
ghci> [x*100+3 | (x, 3) <- xs](リストxsの(x,3)に該当するペアのxの値を利用する。それ以外のペアはスルー。)
[103,403,503] -}
{- [1,2,3]は(1:(2:(3:[])))の構文糖衣 -}
{- リストに対するパターンマッチを使って独自にhead関数を実装する -}
head' :: [a] -> a
head' [] = error "Can't call head on an empty list, dummy!"
head' (x:_) = x {- x:xsというパターンを再起関数と一緒によく使いますが、:を含むパターンは長さが1以上のリストに対してしか合致しない。 -}
{- 定義にあるように複数の変数(そのうちの1つが_の場合も)に束縛したい時は丸括弧で囲まなければシンタックスエラーになる。error関数はみだりに使わないほうがいい。 -}
{- リストの要素を回りくどく出力する関数 -}
tell :: (Show a) => [a] -> String
tell [] = "The list is empty"
tell (x:[]) = "The list has one element: " ++ show x
tell (x:y:[]) = "The list has two element: " ++ show x ++ " and " ++ show y
tell (x:y:_) = "This list is long. The first two elements are: " ++ show x ++ " and " ++ show y
{- (x:[])と(x:y:[])はそれぞれ[x]及び[x,y]と書くこともできる。しかし(x:y:_)を角括弧を使って書き直すことはできない。このパターンは長さが2以上の任意のリストと合致するため。 -}
{- tell関数は、空のリストにも、単一要素のリストにも、2要素のリストにも、あるいはもっと多くの要素のリストにも合致するので安全に使える。 -}
{- 予期しないリストが与えられた時何が起こるのか?例えば3要素のリストを扱う方法しか知らない関数を定義した場合どうなるか。 -}
badAdd :: (Num a) => [a] -> a
badAdd (x:y:z:[]) = x + y + z
{- 3要素以外はエラーになる。 -}
{- リストに対するパターンマッチの注意として++演算子(二つをつなげる演算子)は使えないということ。例えばパターン(xs ++ ys)に対して合致させようにも、
リストのどの部分をxsに合致させて、どの部分をysに合致させればいいかHaskellに伝えようがないから。-}
{- asパターン -> パターンを分解しつつ、パターンマッチの対象になった値自体も参照にしたい時に使う。普通のパターンの前に名前と@を追加する。 -}
{- xs@(x:y:ys)のようなasパターンを作れる。x:y:ysに合致するものと全く同じものに合致しつつ、x:y:ysとタイプしなくても、xsで元のリスト全体にアクセスすることもできる。 -}
firstLetter :: String -> String
firstLetter "" = "Empty string, whoops!"
firstLetter all@(x:y:xs) = "The first letter of " ++ all ++ " is " ++ [x]{- x -> 'D', y -> 'r' -}
{- *Main> firstLetter "Dracula"
"The first letter of Dracula is D" -}
{- 場合分けして、きっちりガード! -> 関数を定義する際、引数の構造で場合分けする時にはパターンを使う。引数の値が満たす性質で場合分けする時には、ガードを使う。性質で場合分け
とういう点でifとガードは似ている。ただし、複数の条件がある時にはガードの方がifより可読性が高く、パターンマッチとの相性も抜群。 -}
{- BMIを計算する関数ではなく、計算済みのBMIを受け取って忠告するだけの関数。Doubleだと数が多くて面倒なのでFloatに変更。 -}
bmiTell :: Float -> String
bmiTell bmi
| bmi <= 18.5 = "You're underweight, you emo, you!"
| bmi <= 25.0 = "You're supposedly normal. Pffft, I bet you're ugly!"
| bmi <= 30.0 = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulation!"
{- ガードには、パイプ文字(|)とそれに続く『真理値式』、さらにその式がTrueに評価された時に使われる関数の本体が続く。
式がFalseに評価されたら、その次のガードの評価に移る。この繰り返し。インデントする。
関数の定義からして、長いif/elseの連鎖になるような書き方が避けられない場合などはifよりガードを使うと可読性が高い。
大抵関数の最後のガードは全てをキャッチするotherwiseになっている。全てのガードがFalseに評価されて最後にotherwiseもなかったなら
評価は失敗して次のパターンに移る。(これがパターンとガードの相性が悪い理由。)適切なパターンが見つからなければエラーが投げられる。 -}
{- 身長と体重を受け取ってBMIの計算もするように変更した関数。プラス、show関数でBMIの結果も表示するようにした。 -}
bmiTell' :: Float -> Float -> String
bmiTell' weight height
| weight / height ^ 2 <= 18.5 = show (weight / height ^ 2) ++ "! You're underweight, you emo, you!"
| weight / height ^ 2 <= 25.0 = show (weight / height ^ 2) ++ ". You're supposedly normal. Pffft , I bet you're ugly!"
| weight / height ^ 2 <= 30.0 = show (weight / height ^ 2) ++ "? You're fat! Lose some weight, fatty!"
| otherwise = show (weight / height ^ 2) ++ "!? You're whale, congratulation!"
{- max関数(大小比較Ord型クラス)を独自に定義。 -}
max' :: (Ord a) => a -> a -> a
max' a b
| a <= b = b
| otherwise = a
{- compare関数(同じく比較)を独自に定義。 -}
a `myCompare` b
| a == b = EQ {- a is EQual to b -}
| a <= b = LT {- a is Less Than b -}
| otherwise = GT {- a is Greater Than b -}
{- where -}
{- 上のBMI計算関数を繰り返しを避けるため、whereキーワードを使って変数に値を束縛して無駄を省く。 -}
bmiTell2 :: Float -> Float -> String
bmiTell2 weight height
| bmi <= skinny = show bmi ++ "! You're underweight, you emo, you!"
| bmi <= normal = show bmi ++ ". You're supposedly normal. Pffft , I bet you're ugly!"
| bmi <= fat = show bmi ++ "? You're fat! Lose some weight, fatty!"
| otherwise = show bmi ++ "!? You're whale, congratulation!"
where bmi = weight / height ^ 2
skinny = 18.5
normal = 25.0
fat = 30.0
{- BMIの計算方法を変えたくなっても一箇所を変えるだけで済む。それから値に名前がつくので可読性も上がり、値が一度しか計算されないのでプログラムが早くなる。 -}
{- whereブロックの中の全ての変数のインデントは揃える。ずれるとHaskellが混乱してしまい、ブロックの範囲を正しく認識してくれない。 -}
{- whereのスコープ -> where節で定義した変数は、その関数からしか見えないので、他の関数の名前空間を汚染する心配がない。
複数の異なる関数から見える必要のある変数を定義したい場合は、グローバルに定義する必要がある。また、whereによる束縛は関数の違うパターンの本体では共有されない。 -}
{- 名前を引数に取り、その名前を認識できた場合には上品な挨拶を、そうでなければ下品な挨拶を返す関数。
greet :: String -> String
greet "Juan" = niceGreeting ++ " Juan!"
greet "Fernando" = niceGreeting ++ " Fernando!"
greet name = badGreeting ++ " " ++ name
where niceGreeting = "Hello! So very nice to see you,"
badGreeting = "Oh! Pfft. It's you."
この関数は書いた通りには動かない。whereの束縛は違うパターンの関数本体で共有されず、whereの束縛での名前は最後の本体からしか見えないから。
この関数を正しく動くようにするには、badとniceはグローバルに定義しなくてはならない。 -}
badGreeting :: String
badGreeting = "Oh! Pfft. It's you."
niceGreeting :: String
niceGreeting = "Hello! So very nice to see you,"
greet :: String -> String
greet "Juan" = niceGreeting ++ " Juan!"
greet "Fernando" = niceGreeting ++ " Fernando!"
greet name = badGreeting ++ " " ++ name
{- 論理和(A||B,AがTrueの時常にTrue、AがFalseの時Bに等しい、Aがundefinedの時常にundefined。) -}
logicalSum :: Int -> Int -> String
logicalSum x y = if x == 1 then "1"
else if x == 0 then show y
else "Undefined" {- x == undefined -> undefined -}
{- 論理積(A&&B,AがTrueの時Bに等しい、AがFalseの時常にFalse、Aがundefinedの時常にundefined。) -}
logicalProduct :: Int -> Int -> String
logicalProduct x y = if x == 1 then show y
else if x == 0 then "0"
else "Undefined" {- x == undefined -> undefined -}
{- 曜日計算関数(x日と7の剰余) -}
dayofFuture :: Int -> String
dayofFuture x
| dayCalc == 0 = "Sunday"
| dayCalc == 1 = "Monday"
| dayCalc == 2 = "Tuesday"
| dayCalc == 3 = "Wednesday"
| dayCalc == 4 = "Thursday"
| dayCalc == 5 = "Friday"
| dayCalc == 6 = "Saturday"
| otherwise = "Woops!"
where dayCalc = x `mod` 7
{- パターンマッチとwhere -}
{- whereの束縛の中でもパターンマッチを使うことができる。上のBMI関数のwhere節を次のように書ける。
where bmi = weight / height ^ 2
(skinny, normal, fat) = (18.5, 25.0, 30.0) -}
{- ファーストネームとラストネームを受け取ってイニシャルを返す関数(関数を呼び出す際に名前を""をつけずに引数として書いてしまいエラー。文字列なので"Yusuke" "Tanabe"
としないとダメ。)エラー"Not in scope: 'Yusuke' -> 変数が見当たらない。" -}
initials :: String -> String -> String
initials firstname lastname = [f] ++ ". " ++ [l] ++ "."
where (f:_) = firstname
(l:_) = lastname
{- 下の例のように関数の引数のところで直接パターンマッチすることもでき、その方が短くて可読性も高くなる可能性があるが、この上の例のようにwhereの束縛でもパターンマッチが使える。 -}
initials' :: String -> String -> String
initials' (f:_) (l:_) = [f] ++ ". " ++ [l] ++ "."
{- whereブロックの中では定数だけではなく関数も定義できる。体重と身長のペアのリスト[(Double,Double)]を受け取ってBMIのリスト[Double]を返す関数。 -}
{- この例でbmiを定数ではなく関数として導入したのは、calcBmis関数の引数に対して1つのBMIを計算するのではなく、関数に渡されたリストの要素それぞれに
対して、異なるBMIを計算する必要があるから。 -}
calcBmis :: [(Double,Double)] -> [Double]
calcBmis xs = [bmi w h | (w, h) <- xs]
where bmi weight height = weight / height ^ 2
{- *Main> calcBmis[(55, 1.74),(95,1.65)]
[18.166204254194742,34.894398530762174] -}
{- let It Be -> let式はwhere節に似ている。whereは関数の終わりで変数を束縛し、その変数はガードを含む関数全体から見える。
それに対してlet式はどこでも変数を束縛でき、let自身も式になる。しかし、let式が作る束縛は局所的で、ガード間で共有されない。
let式でもパターンマッチが使える。 -}
{- 円柱の表面積を高さと半径から求める関数 -}
cylinder :: Double -> Double -> Double
cylinder r h =
let sideArea = 2 * pi * r * h
topArea = pi * r ^ 2
in sideArea + 2 * topArea
{- let式は let bindings in expressionという形をとる。letで定義した変数はそのlet式全体から見える。もちろんwhereでも同じものが定義できる。
letとwhereの違いとは?let式はその名の通り「式」で、where節はそうじゃないというところ。「式である」ということはそれが「値を持つ」ということ。
つまりlet式はコード中のほとんどどんな場所でも使えるということ。使い方の例 ↓ -}
{- letはローカルスコープに関数を作るのに使える
ghci> [let square x = x * x in (square 5, square 3, square 2)]
[(25,9,4)] -}
{- letではセミコロン(;)区切りを使える。インデントみたいに間延びした構文を使わずにすみ、複数の変数を一行で束縛したい時に便利。
ghci> (let a = 100; b = 200; c = 300 in a*b*c, let foo = "Hey "; bar = "there!" in foo ++ bar)
(6000000,"Hey there!") -}
{- let式とパターンマッチがあれば、あっという間にタプルを要素に分解してそれぞれ名前に束縛できる
ghci> (let (a, b, c) = (1, 2, 3) in a+b+c) * 100
600
ここではトリプル(1,2,3)を分解するのにletを使った。最初の要素をa、2つ目の要素をb、3つ目の要素をcと読んでいる。in a+b+cの部分は、
let式全体が値a+b+cを持つ、と言っている。最後にその値に100をかけている。 -}
{- 使い勝手がいいものの、いつでもlet式を使えばいいとは言えない。まずlet式は「式」であり、そのスコープに局所的なので、ガードをまたいでは
使えない。また、関数の前ではなく後ろで部品を定義することで、関数の本体が名前と型宣言に近くなりコードが読みやすくなるのでwhereを使う人もいる。 -}
{- リスト内包表記でのlet -}
{- BMI計算する例をwhereで関数を定義するのではなく、リスト内包表記中のletを使って書き換えてみる。 -}
calcBmis' :: [(Double, Double)] -> [Double]
calcBmis' xs = [bmi | (w, h) <- xs, let bmi = w / h ^2]
{- リスト内包表記が元のリストからタプルを受け取り、その要素をwとhに束縛するたびに、let式はw / h ^ 2を変数bmiに束縛する。
それからbmiをリスト内包表記の出力として書き出しているだけ。 -}
{- リスト内包表記の中のletを述語のように使っているが、これはリストをフィルタするわけではなく、名前を束縛しているだけ。letで定義された名前は
出力(|より前の部分)とそのletより後ろのリスト内包表記のすべてから見える。ただ、ジェネレータと呼ばれるリスト内包表記の(w,h) <- xsの部分は
letの束縛よりも前に定義されているので、変数bmiはジェネレータからは参照できない。このテクニックを使って肥満な人のBMIのみを
返すように関数を変えてみる。 -}
calcBmis'' :: [(Double,Double)] -> [Double]
calcBmis'' xs = [bmi | (w,h) <- xs, let bmi = w / h ^ 2, bmi > 25.0]
| INALOW/Haskell | baby.hs | mit | 24,255 | 0 | 11 | 2,180 | 2,484 | 1,361 | 1,123 | 142 | 6 |
-- |
-- Module : Initial.AST
-- Copyright : © 2019 Elias Castegren and Kiko Fernandez-Reyes
-- License : MIT
--
-- Stability : experimental
-- Portability : portable
--
-- This module includes functionality for creating an Abstract Syntax Tree (AST),
-- as well as helper functions for checking different
-- aspects of the AST.
{-# LANGUAGE NamedFieldPuns #-}
module Initial.AST where
import Data.Maybe
import Data.List
import Text.Printf (printf)
-- * AST declarations
-- $
-- Declaration for the Abstract Syntax Tree of the language. This section
-- contains the type, class, methods, fields and expressions represented
-- as an AST. The AST is produced by a parser. For more information on
-- building parsers, we recommend to read
-- <https://hackage.haskell.org/package/megaparsec-7.0.5 megaparsec>.
type Name = String
-- | Check if a name is a constructor name
isConstructorName = (=="init")
-- | Representation of types
data Type =
ClassType Name
| IntType
| BoolType
| Arrow {tparams :: [Type], tresult :: Type}
| UnitType
deriving (Eq)
instance Show Type where
show (ClassType c) = c
show IntType = "int"
show BoolType = "bool"
show (Arrow ts t) = "(" ++ commaSep ts ++ ")" ++ " -> " ++ show t
show UnitType = "unit"
-- | The representation of a program in the form of an AST node.
newtype Program =
-- | Programs are simply a list of class definitions ('ClassDef')
Program [ClassDef] deriving (Show)
-- | A representation of a class in the form of an AST node. As an example:
--
-- > class Foo:
-- > val x: Int
-- > var y: Bool
-- > def main(): Int
-- > 42
--
-- the code above, after parsing, would generate the following AST:
--
-- > ClassDef {cname = "Foo"
-- > ,fields = [FieldDef {fname = "x"
-- > ,ftype = IntType
-- > ,fmod = Val}]
-- > ,methods = [MethodDef {mname = "main"
-- > ,mparams = []
-- > ,mtype = IntType
-- > ,mbody = [IntLit {etype = Nothing, ival = 42}]
-- > }]}
data ClassDef =
ClassDef {cname :: Name
,fields :: [FieldDef]
,methods :: [MethodDef]
}
instance Show ClassDef where
show ClassDef {cname, fields, methods} =
"class " ++ cname ++ concatMap show fields ++ concatMap show methods ++ "end"
-- | Field qualifiers in a class. It is thought for a made up syntax such as:
--
-- > class Foo:
-- > val x: Int
-- > var y: Bool
--
-- This indicates that the variable @x@ is immutable, and @y@ can be mutated.
--
data Mod = Var -- ^ Indicates that the field can be mutated
| Val -- ^ Indicates that the field is immutable
deriving (Eq)
instance Show Mod where
show Var = "var"
show Val = "val"
-- | Representation of a field declaration in the form of an AST node.
-- As an example, the following code:
--
-- > class Foo:
-- > val x: Int
--
-- could be parsed to the following field representation:
--
-- > FieldDef {fname = "x"
-- > ,ftype = IntType
-- > ,fmod = Val}
--
data FieldDef =
FieldDef {fname :: Name
,ftype :: Type
,fmod :: Mod
}
-- | Helper function to check whether a 'FieldDef' is immutable.
isValField :: FieldDef -> Bool
isValField FieldDef{fmod} = fmod == Val
-- | Helper function to check whether a 'FieldDef' is mutable.
isVarField :: FieldDef -> Bool
isVarField = not . isValField
instance Show FieldDef where
show FieldDef{fname, ftype, fmod} =
show fmod ++ " " ++ fname ++ " : " ++ show ftype
-- | Representation of parameters in the form of an AST.
data Param = Param {pname :: Name
,ptype :: Type
}
instance Show Param where
show Param{pname, ptype} = pname ++ " : " ++ show ptype
-- | Representation of a method declaration in the form of an AST. For example:
--
-- > class Foo:
-- > def main(): Int
-- > 42
--
-- the code above, after parsing, would generate the following AST:
--
-- > ClassDef {cname = "Foo"
-- > ,fields = []
-- > ,methods = [MethodDef {mname = "main"
-- > ,mparams = []
-- > ,mtype = IntType
-- > ,mbody = [IntLit {etype = Nothing, ival = 42}]
-- > }]}
--
data MethodDef =
MethodDef {mname :: Name
,mparams :: [Param]
,mtype :: Type
,mbody :: Expr
}
-- | Takes a list of things that can be shown, and creates a comma
-- separated string.
commaSep :: Show t => [t] -> String
commaSep = intercalate ", " . map show
instance Show MethodDef where
show MethodDef{mname, mparams, mtype, mbody} =
"def " ++ mname ++ "(" ++ commaSep mparams ++ ") : " ++
show mtype ++ show mbody
-- | Representation of integer operations
data Op = Add | Sub | Mul | Div deriving (Eq)
instance Show Op where
show Add = "+"
show Sub = "-"
show Mul = "*"
show Div = "/"
-- | Representation of expressions in the form of an AST node. The language
-- is expression-based, so there are no statements. As an example, the following
-- identity function:
--
-- > let id = \x: Int -> x
-- > in id 42
--
-- generates this 'Expr':
--
-- > Let {etype = Nothing
-- > ,name = "id"
-- > ,val = Lambda {etype = Nothing
-- > ,params = [Param "x" IntType]
-- > ,body = FunctionCall {etype = Nothing
-- > ,target = VarAccess Nothing "id"
-- > ,args = [IntLit Nothing 42]}
-- > }
-- > ,body :: Expr p1
-- > }
-- >
data Expr =
-- | Representation of a boolean literal
BoolLit {etype :: Maybe Type -- ^ Type of the expression
,bval :: Bool
}
-- | Representation of an integer literal
| IntLit {etype :: Maybe Type -- ^ Type of the expression
,ival :: Int
}
-- | Representation of a null expression
| Null {etype :: Maybe Type -- ^ Type of the null expression
}
-- | Representation of a null expression
| Lambda {etype :: Maybe Type -- ^ Type of the expression
,params :: [Param] -- ^ List of arguments with their types ('Param')
,body :: Expr -- ^ The body of the lambda abstraction
}
| VarAccess {etype :: Maybe Type -- ^ Type of the expression
,name :: Name -- ^ Variable name
}
-- ^ Representation of a variable access
| FieldAccess {etype :: Maybe Type -- ^ Type of the expression
,target :: Expr -- ^ The target in a field access, e.g., @x.foo@, then @x@ is the target.
,name :: Name -- ^ Field name, e.g., @x.foo@, then @foo@ is the 'Name'
}
| Assignment {etype :: Maybe Type -- ^ Type of the expression
,lhs :: Expr -- ^ Left-hand side expression
,rhs :: Expr -- ^ Left-hand side expression
}
| MethodCall {etype :: Maybe Type -- ^ Type of the expression
,target :: Expr -- ^ The target of a method call, e.g., @x.bar()@, then @x@ is the target
,name :: Name -- ^ The method name
,args :: [Expr] -- ^ The arguments of the method call
}
| FunctionCall {etype :: Maybe Type -- ^ Type of the expression
,target :: Expr -- ^ The target of the function call, e.g., @bar()@, then @bar@ is the target
,args :: [Expr] -- ^ The function arguments
}
| If {etype :: Maybe Type -- ^ Type of the expression
,cond :: Expr -- ^ The condition in the @if-else@ expression
,thn :: Expr -- ^ The body of the @then@ branch
,els :: Expr -- ^ The body of the @else@ branch
}
| Let {etype :: Maybe Type -- ^ Type of the expression
,name :: Name -- ^ Variable name to bound a value to
,val :: Expr -- ^ Expression that will bound variable @name@ with value @val@
,body :: Expr -- ^ Body of the let expression
}
| BinOp {etype :: Maybe Type -- ^ Type of the expression
,op :: Op -- ^ Binary operation
,lhs :: Expr -- ^ Left-hand side expression
,rhs :: Expr -- ^ Right-hand side expression
}
| New {etype :: Maybe Type -- ^ The type of the expression
,ty :: Type -- ^ The class that one instantiates, e.g., `new C`
,args :: [Expr] -- ^ Constructor arguments
}
-- ^ It is useful to decouple the type of the expression from the type of the
-- instantiated class. This distinction becomes important whenever we have
-- subtyping, e.g., an interface `Animal` where `Animal x = new Dog`
| Cast {etype :: Maybe Type -- ^ Type of the expression
,body :: Expr -- ^ Body that will be casted to type @ty@
,ty :: Type -- ^ The casting type
}
-- * Helper functions
-- $helper-functions
-- The helper functions of this section operate on AST nodes to check
-- for different properties. As an example, to check whether an expression
-- is a field, instead of having to pattern match in all places, i.e.,
--
-- > exampleFunction :: Expr -> Bool
-- > exampleFunction expr =
-- > -- does some stuff
-- > ...
-- > case expr of
-- > FieldAccess expr -> True
-- > _ -> False
-- >
-- we define the 'isFieldAccess' helper function, which checks
-- whether a given expression is a 'FieldAccess':
--
-- > exampleFunction :: Expr -> Bool
-- > exampleFunction expr =
-- > -- does some stuff
-- > ...
-- > isFieldAccess expr
-- >
-- | Constant for the name @this@, commonly used in object-oriented languages.
thisName :: Name
thisName = "this"
-- | Checks whether a 'Type' is a function (arrow) type
isArrowType :: Type -> Bool
isArrowType Arrow {} = True
isArrowType _ = False
-- | Checks whether an expression is a 'FieldAccess'.
isFieldAccess :: Expr -> Bool
isFieldAccess FieldAccess{} = True
isFieldAccess _ = False
-- | Checks whether an expression is a 'VarAccess'.
isVarAccess :: Expr -> Bool
isVarAccess VarAccess{} = True
isVarAccess _ = False
-- | Checks whether an expression is a 'VarAccess' of 'this'.
isThisAccess :: Expr -> Bool
isThisAccess VarAccess{name} = name == thisName
isThisAccess _ = False
-- | Checks whether an expression is an lval.
isLVal :: Expr -> Bool
isLVal e = isFieldAccess e || isVarAccess e
instance Show Expr where
show BoolLit{bval} = show bval
show IntLit{ival} = show ival
show Null{} = "null"
show Lambda{params, body} =
printf "fun (%s) => %s" (commaSep params) (show body)
show VarAccess{name} = name
show FieldAccess{target, name} =
printf "%s.%s" (show target) name
show Assignment{lhs, rhs} =
printf "%s = %s" (show lhs) (show rhs)
show MethodCall{target, name, args} =
printf "%s.%s(%s)" (show target) name (commaSep args)
show FunctionCall{target, args} =
printf "%s(%s)" (show target) (commaSep args)
show If{cond, thn, els} =
printf "if %s then %s else %s" (show cond) (show thn) (show els)
show Let{name, val, body} =
printf "let %s = %s in %s" name (show val) (show body)
show BinOp{op, lhs, rhs} =
printf "%s %s %s" (show lhs) (show op) (show rhs)
show New {ty, args} =
printf "new %s(%s)" (show ty) (commaSep args)
show Cast{body, ty} =
printf "%s : %s" (show body) (show ty)
-- | Helper function to check whether a 'Type' is a class
isClassType :: Type -> Bool
isClassType (ClassType _) = True
isClassType _ = False
-- | Helper function to extract the type from an expression.
getType :: Expr -> Type
getType = fromJust . etype
-- | Sets the type of an expression @e@ to @t@.
setType :: Type -> Expr -> Expr
setType t e = e{etype = Just t}
| kikofernandez/kikofernandez.github.io | files/monadic-typechecker/typechecker/src/Initial/AST.hs | mit | 11,891 | 0 | 11 | 3,500 | 1,947 | 1,148 | 799 | 157 | 1 |
module Main ( main ) where
import qualified Example2 as Ex2
main :: IO()
main = Ex2.main
| fehu/h-logic-einstein | example-2/Main.hs | mit | 91 | 0 | 6 | 19 | 32 | 20 | 12 | 4 | 1 |
module Tree where
import Test.QuickCheck
import Test.QuickCheck.Checkers
import Data.Monoid
data Tree a =
Empty
| Leaf a
| Node (Tree a) a (Tree a)
deriving (Eq, Show)
instance Functor Tree where
fmap _ Empty = Empty
fmap f (Leaf x) = Leaf $ f x
fmap f (Node t1 x t2) = Node (fmap f t1) (f x) (fmap f t2)
instance Foldable Tree where
foldMap f Empty = mempty
foldMap f (Leaf x) = f x
foldMap f (Node t1 x t2) = foldMap f t1 <> f x <> foldMap f t2
instance Traversable Tree where
traverse _ Empty = pure Empty
traverse f (Leaf x) = Leaf <$> f x
traverse f (Node t1 x t2) = Node <$> traverse f t1 <*> f x <*> traverse f t2
--
genTree :: Arbitrary a => Gen (Tree a)
genTree = do
x <- arbitrary
t1 <- genTree
t2 <- genTree
frequency [ (1, return Empty)
, (2, return $ Leaf x)
, (2, return $ Node t1 x t2)
]
instance (Arbitrary a) => Arbitrary (Tree a) where
arbitrary = genTree
instance (Eq a) => EqProp (Tree a) where
(=-=) = eq
| NickAger/LearningHaskell | HaskellProgrammingFromFirstPrinciples/Chapter21/Exercises/src/Tree.hs | mit | 1,013 | 0 | 11 | 282 | 482 | 245 | 237 | 33 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
module SchemaQuickCheck
(schemaCGRQuickCheck)
where
import qualified Data.ByteString as BS
import Capnp.Convert (bsToParsed)
import Capnp.Errors (Error)
import Capnp.TraversalLimit (defaultLimit, evalLimitT)
import qualified Capnp.Gen.Capnp.Schema.New as Schema
-- Testing framework imports
import Test.Hspec
import Test.QuickCheck
-- Schema generation imports
import SchemaGeneration
import Util
-- Schema validation imports
import Control.Monad.Catch as C
-- Functions to generate valid CGRs
generateCGR :: Schema -> IO BS.ByteString
generateCGR schema = capnpCompile (show schema) "-"
-- Functions to validate CGRs
decodeCGR :: BS.ByteString -> IO ()
decodeCGR bytes = do
_ <- evalLimitT defaultLimit (bsToParsed @Schema.CodeGeneratorRequest bytes)
pure ()
-- QuickCheck properties
prop_schemaValid :: Schema -> Property
prop_schemaValid schema = ioProperty $ do
compiled <- generateCGR schema
decoded <- try $ decodeCGR compiled
return $ case (decoded :: Either Error ()) of
Left _ -> False
Right _ -> True
schemaCGRQuickCheck :: Spec
schemaCGRQuickCheck =
describe "generateCGR an decodeCGR agree" $
it "successfully decodes generated schema" $
property $ prop_schemaValid <$> genSchema
| zenhack/haskell-capnp | tests/SchemaQuickCheck.hs | mit | 1,400 | 0 | 12 | 276 | 302 | 165 | 137 | 33 | 2 |
module Solidran.Revp.Detail where
import Solidran.Revc.Detail (complementDna)
isReversePalindrome :: String -> Bool
isReversePalindrome s = complementDna s == s
findSequencesOfLengthFrom :: Int -> Int -> [a] -> [(Int, [a])]
findSequencesOfLengthFrom _ _ [] = []
findSequencesOfLengthFrom i n s
| length s < n = []
| otherwise = (i, current) : recursive
where
current = take n s
recursive = findSequencesOfLengthFrom (i + 1) n (drop 1 s)
findSequencesOfLength :: Int -> [a] -> [(Int, [a])]
findSequencesOfLength = findSequencesOfLengthFrom 1
findReversePalindromes :: [Int] -> String -> [(Int, Int)]
findReversePalindromes ls s =
let allSequences = concat . map (\l -> findSequencesOfLength l s) $ ls
revPSequences = filter (isReversePalindrome . snd) allSequences
in map (\(i, ss) -> (i, length ss)) revPSequences
| Jefffrey/Solidran | src/Solidran/Revp/Detail.hs | mit | 892 | 0 | 14 | 199 | 326 | 176 | 150 | 18 | 1 |
-- Binomial coefficient. General Recursion.
module BinomialCoefficient where
bc :: Integer -> Integer -> Integer
bc _ 0 = 1
-- bc n 1 = n -- There would be an attempt to match this in every recursion step.
-- Under what condition(s) could this mathching be an advantage?
-- Under what condition(s) could this matching be a disadvantage?
-- (Keywords: recursion pattern, parallelism, complex data structures ...)
bc n k
| n == k = 1
| otherwise = bc (n - 1) (k - 1)
+ bc (n - 1) k
{- GHCi>
bc 1 0
bc 2 1
bc 2 2
bc 4 2
-}
-- 1
-- 2
-- 1
-- 6
| pascal-knodel/haskell-craft | Examples/· Recursion/· General Recursion/Calculations/BinomialCoefficient.hs | mit | 620 | 0 | 9 | 196 | 101 | 56 | 45 | 7 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
{-# LANGUAGE MultiWayIf #-}
-- |
-- Module : Yi.Buffer.HighLevel
-- License : GPL-2
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- High level operations on buffers.
module Yi.Buffer.HighLevel
( atEof
, atEol
, atLastLine
, atSol
, atSof
, bdeleteB
, bdeleteLineB
, bkillWordB
, botB
, bufInfoB
, BufferFileInfo (..)
, capitaliseWordB
, deleteBlankLinesB
, deleteHorizontalSpaceB
, deleteRegionWithStyleB
, deleteToEol
, deleteTrailingSpaceB
, downFromTosB
, downScreenB
, downScreensB
, exchangePointAndMarkB
, fillParagraph
, findMatchingPairB
, firstNonSpaceB
, flipRectangleB
, getBookmarkB
, getLineAndCol
, getLineAndColOfPoint
, getNextLineB
, getNextNonBlankLineB
, getRawestSelectRegionB
, getSelectionMarkPointB
, getSelectRegionB
, gotoCharacterB
, hasWhiteSpaceBefore
, incrementNextNumberByB
, insertRopeWithStyleB
, isCurrentLineAllWhiteSpaceB
, isCurrentLineEmptyB
, isNumberB
, killWordB
, lastNonSpaceB
, leftEdgesOfRegionB
, leftOnEol
, lineMoveVisRel
, linePrefixSelectionB
, lineStreamB
, lowercaseWordB
, middleB
, modifyExtendedSelectionB
, moveNonspaceOrSol
, movePercentageFileB
, moveToMTB
, moveToEol
, moveToSol
, moveXorEol
, moveXorSol
, nextCExc
, nextCInc
, nextCInLineExc
, nextCInLineInc
, nextNParagraphs
, nextWordB
, prevCExc
, prevCInc
, prevCInLineExc
, prevCInLineInc
, prevNParagraphs
, prevWordB
, readCurrentWordB
, readLnB
, readPrevWordB
, readRegionRopeWithStyleB
, replaceBufferContent
, revertB
, rightEdgesOfRegionB
, scrollB
, scrollCursorToBottomB
, scrollCursorToTopB
, scrollScreensB
, scrollToCursorB
, scrollToLineAboveWindowB
, scrollToLineBelowWindowB
, selectNParagraphs
, setSelectionMarkPointB
, setSelectRegionB
, shapeOfBlockRegionB
, sortLines
, sortLinesWithRegion
, snapInsB
, snapScreenB
, splitBlockRegionToContiguousSubRegionsB
, swapB
, switchCaseChar
, test3CharB
, testHexB
, toggleCommentB
, topB
, unLineCommentSelectionB
, upFromBosB
, uppercaseWordB
, upScreenB
, upScreensB
, vimScrollB
, vimScrollByB
, markWord
) where
import Lens.Micro.Platform (over, use, (%=), (.=), _last)
import Control.Monad (forM, forM_, replicateM_, unless, void, when)
import Control.Monad.RWS.Strict (ask)
import Control.Monad.State (gets)
import Data.Char (isDigit, isHexDigit, isOctDigit, isSpace, isUpper, toLower, toUpper)
import Data.List (intersperse, sort)
import Data.Maybe (catMaybes, fromMaybe, listToMaybe)
import Data.Monoid ((<>))
import qualified Data.Set as Set
import qualified Data.Text as T (Text, toLower, toUpper, unpack)
import Data.Time (UTCTime)
import Data.Tuple (swap)
import Numeric (readHex, readOct, showHex, showOct)
import Yi.Buffer.Basic (Direction (..), Mark, Point (..), Size (Size))
import Yi.Buffer.Misc
import Yi.Buffer.Normal
import Yi.Buffer.Region
import Yi.Config.Misc (ScrollStyle (SingleLine))
import Yi.Rope (YiString)
import qualified Yi.Rope as R
import Yi.String (capitalizeFirst, fillText, isBlank, mapLines, onLines, overInit)
import Yi.Utils (SemiNum ((+~), (-~)))
import Yi.Window (Window (actualLines, width, wkey))
-- ---------------------------------------------------------------------
-- Movement operations
-- | Move point between the middle, top and bottom of the screen
-- If the point stays at the middle, it'll be gone to the top
-- else if the point stays at the top, it'll be gone to the bottom
-- else it'll be gone to the middle
moveToMTB :: BufferM ()
moveToMTB = (==) <$> curLn <*> screenMidLn >>= \case
True -> downFromTosB 0
_ -> (==) <$> curLn <*> screenTopLn >>= \case
True -> upFromBosB 0
_ -> downFromTosB =<< (-) <$> screenMidLn <*> screenTopLn
-- | Move point to start of line
moveToSol :: BufferM ()
moveToSol = maybeMoveB Line Backward
-- | Move point to end of line
moveToEol :: BufferM ()
moveToEol = maybeMoveB Line Forward
-- | Move cursor to origin
topB :: BufferM ()
topB = moveTo 0
-- | Move cursor to end of buffer
botB :: BufferM ()
botB = moveTo =<< sizeB
-- | Move left if on eol, but not on blank line
leftOnEol :: BufferM ()
-- @savingPrefCol@ is needed, because deep down @leftB@ contains @forgetPrefCol@
-- which messes up vertical cursor motion in Vim normal mode
leftOnEol = savingPrefCol $ do
eol <- atEol
sol <- atSol
when (eol && not sol) leftB
-- | Move @x@ chars back, or to the sol, whichever is less
moveXorSol :: Int -> BufferM ()
moveXorSol x = replicateM_ x $ do c <- atSol; unless c leftB
-- | Move @x@ chars forward, or to the eol, whichever is less
moveXorEol :: Int -> BufferM ()
moveXorEol x = replicateM_ x $ do c <- atEol; unless c rightB
-- | Move to first char of next word forwards
nextWordB :: BufferM ()
nextWordB = moveB unitWord Forward
-- | Move to first char of next word backwards
prevWordB :: BufferM ()
prevWordB = moveB unitWord Backward
-- * Char-based movement actions.
gotoCharacterB :: Char -> Direction -> RegionStyle -> Bool -> BufferM ()
gotoCharacterB c dir style stopAtLineBreaks = do
start <- pointB
let predicate = if stopAtLineBreaks then (`elem` [c, '\n']) else (== c)
(move, moveBack) = if dir == Forward then (rightB, leftB) else (leftB, rightB)
doUntilB_ (predicate <$> readB) move
b <- readB
if stopAtLineBreaks && b == '\n'
then moveTo start
else when (style == Exclusive && b == c) moveBack
-- | Move to the next occurence of @c@
nextCInc :: Char -> BufferM ()
nextCInc c = gotoCharacterB c Forward Inclusive False
nextCInLineInc :: Char -> BufferM ()
nextCInLineInc c = gotoCharacterB c Forward Inclusive True
-- | Move to the character before the next occurence of @c@
nextCExc :: Char -> BufferM ()
nextCExc c = gotoCharacterB c Forward Exclusive False
nextCInLineExc :: Char -> BufferM ()
nextCInLineExc c = gotoCharacterB c Forward Exclusive True
-- | Move to the previous occurence of @c@
prevCInc :: Char -> BufferM ()
prevCInc c = gotoCharacterB c Backward Inclusive False
prevCInLineInc :: Char -> BufferM ()
prevCInLineInc c = gotoCharacterB c Backward Inclusive True
-- | Move to the character after the previous occurence of @c@
prevCExc :: Char -> BufferM ()
prevCExc c = gotoCharacterB c Backward Exclusive False
prevCInLineExc :: Char -> BufferM ()
prevCInLineExc c = gotoCharacterB c Backward Exclusive True
-- | Move to first non-space character in this line
firstNonSpaceB :: BufferM ()
firstNonSpaceB = do
moveToSol
untilB_ ((||) <$> atEol <*> ((not . isSpace) <$> readB)) rightB
-- | Move to the last non-space character in this line
lastNonSpaceB :: BufferM ()
lastNonSpaceB = do
moveToEol
untilB_ ((||) <$> atSol <*> ((not . isSpace) <$> readB)) leftB
-- | Go to the first non space character in the line;
-- if already there, then go to the beginning of the line.
moveNonspaceOrSol :: BufferM ()
moveNonspaceOrSol = do
prev <- readPreviousOfLnB
if R.all isSpace prev then moveToSol else firstNonSpaceB
-- | True if current line consists of just a newline (no whitespace)
isCurrentLineEmptyB :: BufferM Bool
isCurrentLineEmptyB = savingPointB $ moveToSol >> atEol
-- | Note: Returns False if line doesn't have any characters besides a newline
isCurrentLineAllWhiteSpaceB :: BufferM Bool
isCurrentLineAllWhiteSpaceB = savingPointB $ do
isEmpty <- isCurrentLineEmptyB
if isEmpty
then return False
else do
let go = do
eol <- atEol
if eol
then return True
else do
c <- readB
if isSpace c
then rightB >> go
else return False
moveToSol
go
------------
-- | Move down next @n@ paragraphs
nextNParagraphs :: Int -> BufferM ()
nextNParagraphs n = replicateM_ n $ moveB unitEmacsParagraph Forward
-- | Move up prev @n@ paragraphs
prevNParagraphs :: Int -> BufferM ()
prevNParagraphs n = replicateM_ n $ moveB unitEmacsParagraph Backward
-- | Select next @n@ paragraphs
selectNParagraphs :: Int -> BufferM ()
selectNParagraphs n = do
getVisibleSelection >>= \case
True -> exchangePointAndMarkB
>> nextNParagraphs n >> (setVisibleSelection True)
>> exchangePointAndMarkB
False -> nextNParagraphs n >> (setVisibleSelection True)
>> pointB >>= setSelectionMarkPointB >> prevNParagraphs n
-- ! Examples:
-- @goUnmatchedB Backward '(' ')'@
-- Move to the previous unmatched '('
-- @goUnmatchedB Forward '{' '}'@
-- Move to the next unmatched '}'
goUnmatchedB :: Direction -> Char -> Char -> BufferM ()
goUnmatchedB dir cStart' cStop' = getLineAndCol >>= \position ->
stepB >> readB >>= go position (0::Int)
where
go pos opened c
| c == cStop && opened == 0 = return ()
| c == cStop = goIfNotEofSof pos (opened-1)
| c == cStart = goIfNotEofSof pos (opened+1)
| otherwise = goIfNotEofSof pos opened
goIfNotEofSof pos opened = atEof >>= \eof -> atSof >>= \sof ->
if not eof && not sof
then stepB >> readB >>= go pos opened
else gotoLn (fst pos) >> moveToColB (snd pos)
(stepB, cStart, cStop) | dir == Forward = (rightB, cStart', cStop')
| otherwise = (leftB, cStop', cStart')
-----------------------------------------------------------------------
-- Queries
-- | Return true if the current point is the start of a line
atSol :: BufferM Bool
atSol = atBoundaryB Line Backward
-- | Return true if the current point is the end of a line
atEol :: BufferM Bool
atEol = atBoundaryB Line Forward
-- | True if point at start of file
atSof :: BufferM Bool
atSof = atBoundaryB Document Backward
-- | True if point at end of file
atEof :: BufferM Bool
atEof = atBoundaryB Document Forward
-- | True if point at the last line
atLastLine :: BufferM Bool
atLastLine = savingPointB $ do
moveToEol
(==) <$> sizeB <*> pointB
-- | Get the current line and column number
getLineAndCol :: BufferM (Int, Int)
getLineAndCol = (,) <$> curLn <*> curCol
getLineAndColOfPoint :: Point -> BufferM (Int, Int)
getLineAndColOfPoint p = savingPointB $ moveTo p >> getLineAndCol
-- | Read the line the point is on
readLnB :: BufferM YiString
readLnB = readUnitB Line
-- | Read from point to beginning of line
readPreviousOfLnB :: BufferM YiString
readPreviousOfLnB = readRegionB =<< regionOfPartB Line Backward
hasWhiteSpaceBefore :: BufferM Bool
hasWhiteSpaceBefore = fmap isSpace (prevPointB >>= readAtB)
-- | Get the previous point, unless at the beginning of the file
prevPointB :: BufferM Point
prevPointB = do
sof <- atSof
if sof then pointB
else do p <- pointB
return $ Point (fromPoint p - 1)
-- | Reads in word at point.
readCurrentWordB :: BufferM YiString
readCurrentWordB = readUnitB unitWord
-- | Reads in word before point.
readPrevWordB :: BufferM YiString
readPrevWordB = readPrevUnitB unitViWordOnLine
-------------------------
-- Deletes
-- | Delete one character backward
bdeleteB :: BufferM ()
bdeleteB = deleteB Character Backward
-- | Delete forward whitespace or non-whitespace depending on
-- the character under point.
killWordB :: BufferM ()
killWordB = deleteB unitWord Forward
-- | Delete backward whitespace or non-whitespace depending on
-- the character before point.
bkillWordB :: BufferM ()
bkillWordB = deleteB unitWord Backward
-- | Delete backward to the sof or the new line character
bdeleteLineB :: BufferM ()
bdeleteLineB = atSol >>= \sol -> if sol then bdeleteB else deleteB Line Backward
-- UnivArgument is in Yi.Keymap.Emacs.Utils but we can't import it due
-- to cyclic imports.
-- | emacs' @delete-horizontal-space@ with the optional argument.
deleteHorizontalSpaceB :: Maybe Int -> BufferM ()
deleteHorizontalSpaceB u = do
c <- curCol
reg <- regionOfB Line
text <- readRegionB reg
let (r, jb) = deleteSpaces c text
modifyRegionB (const r) reg
-- Jump backwards to where the now-deleted spaces have started so
-- it's consistent and feels natural instead of leaving us somewhere
-- in the text.
moveToColB $ c - jb
where
deleteSpaces :: Int -> R.YiString -> (R.YiString, Int)
deleteSpaces c l =
let (f, b) = R.splitAt c l
f' = R.dropWhileEnd isSpace f
cleaned = f' <> case u of
Nothing -> R.dropWhile isSpace b
Just _ -> b
-- We only want to jump back the number of spaces before the
-- point, not the total number of characters we're removing.
in (cleaned, R.length f - R.length f')
----------------------------------------
-- Transform operations
-- | capitalise the word under the cursor
uppercaseWordB :: BufferM ()
uppercaseWordB = transformB (R.withText T.toUpper) unitWord Forward
-- | lowerise word under the cursor
lowercaseWordB :: BufferM ()
lowercaseWordB = transformB (R.withText T.toLower) unitWord Forward
-- | capitalise the first letter of this word
capitaliseWordB :: BufferM ()
capitaliseWordB = transformB capitalizeFirst unitWord Forward
switchCaseChar :: Char -> Char
switchCaseChar c = if isUpper c then toLower c else toUpper c
-- | Delete to the end of line, excluding it.
deleteToEol :: BufferM ()
deleteToEol = deleteRegionB =<< regionOfPartB Line Forward
-- | Transpose two characters, (the Emacs C-t action)
swapB :: BufferM ()
swapB = do eol <- atEol
when eol leftB
transposeB Character Forward
-- | Delete trailing whitespace from all lines. Uses 'savingPositionB'
-- to get back to where it was.
deleteTrailingSpaceB :: BufferM ()
deleteTrailingSpaceB =
regionOfB Document >>=
savingPositionB . modifyRegionB (tru . mapLines stripEnd)
where
-- Strips the space from the end of each line, preserving
-- newlines.
stripEnd :: R.YiString -> R.YiString
stripEnd x = case R.last x of
Nothing -> x
Just '\n' -> (`R.snoc` '\n') $ R.dropWhileEnd isSpace x
_ -> R.dropWhileEnd isSpace x
-- | Cut off trailing newlines, making sure to preserve one.
tru :: R.YiString -> R.YiString
tru x = if R.length x == 0
then x
else (`R.snoc` '\n') $ R.dropWhileEnd (== '\n') x
-- ----------------------------------------------------
-- | Marks
-- | Set the current buffer selection mark
setSelectionMarkPointB :: Point -> BufferM ()
setSelectionMarkPointB p = (.= p) . markPointA =<< selMark <$> askMarks
-- | Get the current buffer selection mark
getSelectionMarkPointB :: BufferM Point
getSelectionMarkPointB = use . markPointA =<< selMark <$> askMarks
-- | Exchange point & mark.
exchangePointAndMarkB :: BufferM ()
exchangePointAndMarkB = do m <- getSelectionMarkPointB
p <- pointB
setSelectionMarkPointB p
moveTo m
getBookmarkB :: String -> BufferM Mark
getBookmarkB = getMarkB . Just
-- ---------------------------------------------------------------------
-- Buffer operations
data BufferFileInfo =
BufferFileInfo { bufInfoFileName :: FilePath
, bufInfoSize :: Int
, bufInfoLineNo :: Int
, bufInfoColNo :: Int
, bufInfoCharNo :: Point
, bufInfoPercent :: T.Text
, bufInfoModified :: Bool
}
-- | File info, size in chars, line no, col num, char num, percent
bufInfoB :: BufferM BufferFileInfo
bufInfoB = do
s <- sizeB
p <- pointB
m <- gets isUnchangedBuffer
l <- curLn
c <- curCol
nm <- gets identString
let bufInfo = BufferFileInfo { bufInfoFileName = T.unpack nm
, bufInfoSize = fromIntegral s
, bufInfoLineNo = l
, bufInfoColNo = c
, bufInfoCharNo = p
, bufInfoPercent = getPercent p s
, bufInfoModified = not m
}
return bufInfo
-----------------------------
-- Window-related operations
upScreensB :: Int -> BufferM ()
upScreensB = scrollScreensB . negate
downScreensB :: Int -> BufferM ()
downScreensB = scrollScreensB
-- | Scroll up 1 screen
upScreenB :: BufferM ()
upScreenB = scrollScreensB (-1)
-- | Scroll down 1 screen
downScreenB :: BufferM ()
downScreenB = scrollScreensB 1
-- | Scroll by n screens (negative for up)
scrollScreensB :: Int -> BufferM ()
scrollScreensB n = do
h <- askWindow actualLines
scrollB $ n * max 0 (h - 1) -- subtract some amount to get some overlap (emacs-like).
-- | Same as scrollB, but also moves the cursor
vimScrollB :: Int -> BufferM ()
vimScrollB n = do scrollB n
void $ lineMoveRel n
-- | Same as scrollByB, but also moves the cursor
vimScrollByB :: (Int -> Int) -> Int -> BufferM ()
vimScrollByB f n = do h <- askWindow actualLines
vimScrollB $ n * f h
-- | Move to middle line in screen
scrollToCursorB :: BufferM ()
scrollToCursorB = do
MarkSet f i _ <- markLines
h <- askWindow actualLines
let m = f + (h `div` 2)
scrollB $ i - m
-- | Move cursor to the top of the screen
scrollCursorToTopB :: BufferM ()
scrollCursorToTopB = do
MarkSet f i _ <- markLines
scrollB $ i - f
-- | Move cursor to the bottom of the screen
scrollCursorToBottomB :: BufferM ()
scrollCursorToBottomB = do
-- NOTE: This is only an approximation.
-- The correct scroll amount depends on how many lines just above
-- the current viewport are going to be wrapped. We don't have this
-- information here as wrapping is done in the frontend.
MarkSet f i _ <- markLines
h <- askWindow actualLines
scrollB $ i - f - h + 1
-- | Scroll by n lines.
scrollB :: Int -> BufferM ()
scrollB n = do
MarkSet fr _ _ <- askMarks
savingPointB $ do
moveTo =<< use (markPointA fr)
void $ gotoLnFrom n
(markPointA fr .=) =<< pointB
w <- askWindow wkey
pointFollowsWindowA %= Set.insert w
-- Scroll line above window to the bottom.
scrollToLineAboveWindowB :: BufferM ()
scrollToLineAboveWindowB = do
downFromTosB 0
replicateM_ 1 lineUp
scrollCursorToBottomB
-- Scroll line below window to the top.
scrollToLineBelowWindowB :: BufferM ()
scrollToLineBelowWindowB = do
upFromBosB 0
replicateM_ 1 lineDown
scrollCursorToTopB
-- | Move the point to inside the viewable region
snapInsB :: BufferM ()
snapInsB = do
w <- askWindow wkey
movePoint <- Set.member w <$> use pointFollowsWindowA
when movePoint $ do
r <- winRegionB
p <- pointB
moveTo $ max (regionStart r) $ min (regionEnd r) p
-- | return index of Sol on line @n@ above current line
indexOfSolAbove :: Int -> BufferM Point
indexOfSolAbove n = pointAt $ gotoLnFrom (negate n)
data RelPosition = Above | Below | Within
deriving (Show)
-- | return relative position of the point @p@
-- relative to the region defined by the points @rs@ and @re@
pointScreenRelPosition :: Point -> Point -> Point -> RelPosition
pointScreenRelPosition p rs re
| rs > p && p > re = Within
| p < rs = Above
| p > re = Below
pointScreenRelPosition _ _ _ = Within -- just to disable the non-exhaustive pattern match warning
-- | Move the visible region to include the point
snapScreenB :: Maybe ScrollStyle -> BufferM Bool
snapScreenB style = do
w <- askWindow wkey
movePoint <- Set.member w <$> use pointFollowsWindowA
if movePoint then return False else do
inWin <- pointInWindowB =<< pointB
if inWin then return False else do
h <- askWindow actualLines
r <- winRegionB
p <- pointB
let gap = case style of
Just SingleLine -> case pointScreenRelPosition p (regionStart r) (regionEnd r) of
Above -> 0
Below -> h - 1
Within -> 0 -- Impossible but handle it anyway
_ -> h `div` 2
i <- indexOfSolAbove gap
f <- fromMark <$> askMarks
markPointA f .= i
return True
-- | Move to @n@ lines down from top of screen
downFromTosB :: Int -> BufferM ()
downFromTosB n = do
moveTo =<< use . markPointA =<< fromMark <$> askMarks
replicateM_ n lineDown
-- | Move to @n@ lines up from the bottom of the screen
upFromBosB :: Int -> BufferM ()
upFromBosB n = do
r <- winRegionB
moveTo (regionEnd r - 1)
moveToSol
replicateM_ n lineUp
-- | Move to middle line in screen
middleB :: BufferM ()
middleB = do
w <- ask
f <- fromMark <$> askMarks
moveTo =<< use (markPointA f)
replicateM_ (actualLines w `div` 2) lineDown
pointInWindowB :: Point -> BufferM Bool
pointInWindowB p = nearRegion p <$> winRegionB
-----------------------------
-- Region-related operations
-- | Return the region between point and mark
getRawestSelectRegionB :: BufferM Region
getRawestSelectRegionB = do
m <- getSelectionMarkPointB
p <- pointB
return $ mkRegion p m
-- | Return the empty region if the selection is not visible.
getRawSelectRegionB :: BufferM Region
getRawSelectRegionB = do
s <- use highlightSelectionA
if s then getRawestSelectRegionB else do
p <- pointB
return $ mkRegion p p
-- | Get the current region boundaries. Extended to the current selection unit.
getSelectRegionB :: BufferM Region
getSelectRegionB = do
regionStyle <- getRegionStyle
r <- getRawSelectRegionB
convertRegionToStyleB r regionStyle
-- | Select the given region: set the selection mark at the 'regionStart'
-- and the current point at the 'regionEnd'.
setSelectRegionB :: Region -> BufferM ()
setSelectRegionB region = do
highlightSelectionA .= True
setSelectionMarkPointB $ regionStart region
moveTo $ regionEnd region
------------------------------------------
-- Some line related movements/operations
deleteBlankLinesB :: BufferM ()
deleteBlankLinesB = do
isThisBlank <- isBlank <$> readLnB
when isThisBlank $ do
p <- pointB
-- go up to the 1st blank line in the group
void $ whileB (R.null <$> getNextLineB Backward) lineUp
q <- pointB
-- delete the whole blank region.
deleteRegionB $ mkRegion p q
-- | Get a (lazy) stream of lines in the buffer, starting at the /next/ line
-- in the given direction.
lineStreamB :: Direction -> BufferM [YiString]
lineStreamB dir = fmap rev . R.lines <$> (streamB dir =<< pointB)
where
rev = case dir of
Forward -> id
Backward -> R.reverse
-- | Get the next line of text in the given direction. This returns
-- simply 'Nothing' if there no such line.
getMaybeNextLineB :: Direction -> BufferM (Maybe YiString)
getMaybeNextLineB dir = listToMaybe <$> lineStreamB dir
-- | The same as 'getMaybeNextLineB' but avoids the use of the 'Maybe'
-- type in the return by returning the empty string if there is no
-- next line.
getNextLineB :: Direction -> BufferM YiString
getNextLineB dir = fromMaybe R.empty <$> getMaybeNextLineB dir
-- | Get closest line to the current line (not including the current
-- line) in the given direction which satisfies the given condition.
-- Returns 'Nothing' if there is no line which satisfies the
-- condition.
getNextLineWhichB :: Direction -> (YiString -> Bool) -> BufferM (Maybe YiString)
getNextLineWhichB dir cond = listToMaybe . filter cond <$> lineStreamB dir
-- | Returns the closest line to the current line which is non-blank,
-- in the given direction. Returns the empty string if there is no
-- such line (for example if we are on the top line already).
getNextNonBlankLineB :: Direction -> BufferM YiString
getNextNonBlankLineB dir =
fromMaybe R.empty <$> getNextLineWhichB dir (not . R.null)
------------------------------------------------
-- Some more utility functions involving
-- regions (generally that which is selected)
modifyExtendedSelectionB :: TextUnit -> (R.YiString -> R.YiString) -> BufferM ()
modifyExtendedSelectionB unit transform
= modifyRegionB transform =<< unitWiseRegion unit =<< getSelectRegionB
-- | Prefix each line in the selection using the given string.
linePrefixSelectionB :: R.YiString -- ^ The string that starts a line comment
-> BufferM ()
linePrefixSelectionB s =
modifyExtendedSelectionB Line . overInit $ mapLines (s <>)
-- | Uncomments the selection using the given line comment
-- starting string. This only works for the comments which
-- begin at the start of the line.
unLineCommentSelectionB :: R.YiString -- ^ The string which begins a
-- line comment
-> R.YiString -- ^ A potentially shorter
-- string that begins a comment
-> BufferM ()
unLineCommentSelectionB s1 s2 =
modifyExtendedSelectionB Line $ mapLines unCommentLine
where
(l1, l2) = (R.length s1, R.length s2)
unCommentLine :: R.YiString -> R.YiString
unCommentLine line = case (R.splitAt l1 line, R.splitAt l2 line) of
((f, s) , (f', s')) | s1 == f -> s
| s2 == f' -> s'
| otherwise -> line
-- | Just like 'toggleCommentSelectionB' but automatically inserts a
-- whitespace suffix to the inserted comment string. In fact:
toggleCommentB :: R.YiString -> BufferM ()
toggleCommentB c = toggleCommentSelectionB (c `R.snoc` ' ') c
-- | Toggle line comments in the selection by adding or removing a
-- prefix to each line.
toggleCommentSelectionB :: R.YiString -> R.YiString -> BufferM ()
toggleCommentSelectionB insPrefix delPrefix = do
l <- readUnitB Line
if delPrefix == R.take (R.length delPrefix) l
then unLineCommentSelectionB insPrefix delPrefix
else linePrefixSelectionB insPrefix
-- | Replace the contents of the buffer with some string
replaceBufferContent :: YiString -> BufferM ()
replaceBufferContent newvalue = do
r <- regionOfB Document
replaceRegionB r newvalue
-- | Fill the text in the region so it fits nicely 80 columns.
fillRegion :: Region -> BufferM ()
fillRegion = modifyRegionB (R.unlines . fillText 80)
fillParagraph :: BufferM ()
fillParagraph = fillRegion =<< regionOfB unitParagraph
-- | Sort the lines of the region.
sortLines :: BufferM ()
sortLines = modifyExtendedSelectionB Line (onLines sort)
-- | Forces an extra newline into the region (if one exists)
modifyExtendedLRegion :: Region -> (R.YiString -> R.YiString) -> BufferM ()
modifyExtendedLRegion region transform = do
reg <- unitWiseRegion Line region
modifyRegionB transform (fixR reg)
where fixR reg = mkRegion (regionStart reg) $ regionEnd reg + 1
sortLinesWithRegion :: Region -> BufferM ()
sortLinesWithRegion region = modifyExtendedLRegion region (onLines sort')
where sort' [] = []
sort' lns =
if hasnl (last lns)
then sort lns
else over _last
-- should be completely safe since every element contains newline
(fromMaybe (error "sortLinesWithRegion fromMaybe") . R.init) . sort $
over _last (`R.snoc` '\n') lns
hasnl t | R.last t == Just '\n' = True
| otherwise = False
-- | Helper function: revert the buffer contents to its on-disk version
revertB :: YiString -> Maybe R.ConverterName -> UTCTime -> BufferM ()
revertB s cn now = do
r <- regionOfB Document
replaceRegionB r s
encodingConverterNameA .= cn
markSavedB now
-- get lengths of parts covered by block region
--
-- Consider block region starting at 'o' and ending at 'z':
--
-- start
-- |
-- \|/
-- def foo(bar):
-- baz
--
-- ab
-- xyz0
-- /|\
-- |
-- finish
--
-- shapeOfBlockRegionB returns (regionStart, [2, 2, 0, 1, 2])
-- TODO: accept stickToEol flag
shapeOfBlockRegionB :: Region -> BufferM (Point, [Int])
shapeOfBlockRegionB reg = savingPointB $ do
(l0, c0) <- getLineAndColOfPoint $ regionStart reg
(l1, c1) <- getLineAndColOfPoint $ regionEnd reg
let (left, top, bottom, right) = (min c0 c1, min l0 l1, max l0 l1, max c0 c1)
lengths <- forM [top .. bottom] $ \l -> do
void $ gotoLn l
moveToColB left
currentLeft <- curCol
if currentLeft /= left
then return 0
else do
moveToColB right
rightAtEol <- atEol
leftOnEol
currentRight <- curCol
return $ if currentRight == 0 && rightAtEol
then 0
else currentRight - currentLeft + 1
startingPoint <- pointOfLineColB top left
return (startingPoint, lengths)
leftEdgesOfRegionB :: RegionStyle -> Region -> BufferM [Point]
leftEdgesOfRegionB Block reg = savingPointB $ do
(l0, _) <- getLineAndColOfPoint $ regionStart reg
(l1, _) <- getLineAndColOfPoint $ regionEnd reg
moveTo $ regionStart reg
fmap catMaybes $ forM [0 .. abs (l0 - l1)] $ \i -> savingPointB $ do
void $ lineMoveRel i
p <- pointB
eol <- atEol
return (if not eol then Just p else Nothing)
leftEdgesOfRegionB LineWise reg = savingPointB $ do
lastSol <- do
moveTo $ regionEnd reg
moveToSol
pointB
let go acc p = do moveTo p
moveToSol
edge <- pointB
if edge >= lastSol
then return $ reverse (edge:acc)
else do
void $ lineMoveRel 1
go (edge:acc) =<< pointB
go [] (regionStart reg)
leftEdgesOfRegionB _ r = return [regionStart r]
rightEdgesOfRegionB :: RegionStyle -> Region -> BufferM [Point]
rightEdgesOfRegionB Block reg = savingPointB $ do
(l0, _) <- getLineAndColOfPoint $ regionStart reg
(l1, _) <- getLineAndColOfPoint $ regionEnd reg
moveTo $ 1 + regionEnd reg
fmap reverse $ forM [0 .. abs (l0 - l1)] $ \i -> savingPointB $ do
void $ lineMoveRel $ -i
pointB
rightEdgesOfRegionB LineWise reg = savingPointB $ do
lastEol <- do
moveTo $ regionEnd reg
moveToEol
pointB
let go acc p = do moveTo p
moveToEol
edge <- pointB
if edge >= lastEol
then return $ reverse (edge:acc)
else do
void $ lineMoveRel 1
go (edge:acc) =<< pointB
go [] (regionStart reg)
rightEdgesOfRegionB _ reg = savingPointB $ do
moveTo $ regionEnd reg
leftOnEol
fmap return pointB
splitBlockRegionToContiguousSubRegionsB :: Region -> BufferM [Region]
splitBlockRegionToContiguousSubRegionsB reg = savingPointB $ do
(start, lengths) <- shapeOfBlockRegionB reg
forM (zip [0..] lengths) $ \(i, l) -> do
moveTo start
void $ lineMoveRel i
p0 <- pointB
moveXorEol l
p1 <- pointB
let subRegion = mkRegion p0 p1
return subRegion
deleteRegionWithStyleB :: Region -> RegionStyle -> BufferM Point
deleteRegionWithStyleB reg Block = savingPointB $ do
(start, lengths) <- shapeOfBlockRegionB reg
moveTo start
forM_ (zip [1..] lengths) $ \(i, l) -> do
deleteN l
moveTo start
lineMoveRel i
return start
deleteRegionWithStyleB reg style = savingPointB $ do
effectiveRegion <- convertRegionToStyleB reg style
deleteRegionB effectiveRegion
return $! regionStart effectiveRegion
readRegionRopeWithStyleB :: Region -> RegionStyle -> BufferM YiString
readRegionRopeWithStyleB reg Block = savingPointB $ do
(start, lengths) <- shapeOfBlockRegionB reg
moveTo start
chunks <- forM lengths $ \l ->
if l == 0
then lineMoveRel 1 >> return mempty
else do
p <- pointB
r <- readRegionB $ mkRegion p (p +~ Size l)
void $ lineMoveRel 1
return r
return $ R.intersperse '\n' chunks
readRegionRopeWithStyleB reg style = readRegionB =<< convertRegionToStyleB reg style
insertRopeWithStyleB :: YiString -> RegionStyle -> BufferM ()
insertRopeWithStyleB rope Block = savingPointB $ do
let ls = R.lines rope
advanceLine = atLastLine >>= \case
False -> void $ lineMoveRel 1
True -> do
col <- curCol
moveToEol
newlineB
insertN $ R.replicateChar col ' '
sequence_ $ intersperse advanceLine $ fmap (savingPointB . insertN) ls
insertRopeWithStyleB rope LineWise = do
moveToSol
savingPointB $ insertN rope
insertRopeWithStyleB rope _ = insertN rope
-- consider the following buffer content
--
-- 123456789
-- qwertyuio
-- asdfgh
--
-- The following examples use characters from that buffer as points.
-- h' denotes the newline after h
--
-- 1 r -> 4 q
-- 9 q -> 1 o
-- q h -> y a
-- a o -> h' q
-- o a -> q h'
-- 1 a -> 1 a
--
-- property: fmap swap (flipRectangleB a b) = flipRectangleB b a
flipRectangleB :: Point -> Point -> BufferM (Point, Point)
flipRectangleB p0 p1 = savingPointB $ do
(_, c0) <- getLineAndColOfPoint p0
(_, c1) <- getLineAndColOfPoint p1
case compare c0 c1 of
EQ -> return (p0, p1)
GT -> swap <$> flipRectangleB p1 p0
LT -> do
-- now we know that c0 < c1
moveTo p0
moveXorEol $ c1 - c0
flippedP0 <- pointB
return (flippedP0, p1 -~ Size (c1 - c0))
movePercentageFileB :: Int -> BufferM ()
movePercentageFileB i = do
let f :: Double
f = case fromIntegral i / 100.0 of
x | x > 1.0 -> 1.0
| x < 0.0 -> 0.0 -- Impossible?
| otherwise -> x
lineCount <- lineCountB
void $ gotoLn $ floor (fromIntegral lineCount * f)
firstNonSpaceB
findMatchingPairB :: BufferM ()
findMatchingPairB = do
let go dir a b = goUnmatchedB dir a b >> return True
goToMatch = do
c <- readB
case c of '(' -> go Forward '(' ')'
')' -> go Backward '(' ')'
'{' -> go Forward '{' '}'
'}' -> go Backward '{' '}'
'[' -> go Forward '[' ']'
']' -> go Backward '[' ']'
_ -> otherChar
otherChar = do eof <- atEof
eol <- atEol
if eof || eol
then return False
else rightB >> goToMatch
p <- pointB
foundMatch <- goToMatch
unless foundMatch $ moveTo p
-- Vim numbers
-- | Increase (or decrease if negative) next number on line by n.
incrementNextNumberByB :: Int -> BufferM ()
incrementNextNumberByB n = do
start <- pointB
untilB_ (not <$> isNumberB) $ moveXorSol 1
untilB_ isNumberB $ moveXorEol 1
begin <- pointB
beginIsEol <- atEol
untilB_ (not <$> isNumberB) $ moveXorEol 1
end <- pointB
if beginIsEol then moveTo start
else do modifyRegionB (increment n) (mkRegion begin end)
moveXorSol 1
-- | Increment number in string by n.
increment :: Int -> R.YiString -> R.YiString
increment n l = R.fromString $ go (R.toString l)
where
go ('0':'x':xs) = (\ys -> '0':'x':ys) . (`showHex` "") . (+ n) . fst . head . readHex $ xs
go ('0':'o':xs) = (\ys -> '0':'o':ys) . (`showOct` "") . (+ n) . fst . head . readOct $ xs
go s = show . (+ n) . (\x -> read x :: Int) $ s
-- | Is character under cursor a number.
isNumberB :: BufferM Bool
isNumberB = do
eol <- atEol
sol <- atSol
if sol then isDigit <$> readB
else if eol then return False
else test3CharB
-- | Used by isNumber to test if current character under cursor is a number.
test3CharB :: BufferM Bool
test3CharB = do
moveXorSol 1
previous <- readB
moveXorEol 2
next <- readB
moveXorSol 1
current <- readB
if | previous == '0' && current == 'o' && isOctDigit next -> return True -- octal format
| previous == '0' && current == 'x' && isHexDigit next -> return True -- hex format
| current == '-' && isDigit next -> return True -- negative numbers
| isDigit current -> return True -- all decimal digits
| isHexDigit current -> testHexB -- ['a'..'f'] for hex
| otherwise -> return False
-- | Characters ['a'..'f'] are part of a hex number only if preceded by 0x.
-- Test if the current occurence of ['a'..'f'] is part of a hex number.
testHexB :: BufferM Bool
testHexB = savingPointB $ do
untilB_ (not . isHexDigit <$> readB) (moveXorSol 1)
leftChar <- readB
moveXorSol 1
leftToLeftChar <- readB
if leftChar == 'x' && leftToLeftChar == '0'
then return True
else return False
-- | Move point down by @n@ lines
-- If line extends past width of window, count moving
-- a single line as moving width points to the right.
lineMoveVisRel :: Int -> BufferM ()
lineMoveVisRel = movingToPrefVisCol . lineMoveVisRelUp
lineMoveVisRelUp :: Int -> BufferM ()
lineMoveVisRelUp 0 = return ()
lineMoveVisRelUp n | n < 0 = lineMoveVisRelDown $ negate n
| otherwise = do
wid <- width <$> use lastActiveWindowA
col <- curCol
len <- pointB >>= eolPointB >>= colOf
let jumps = (len `div` wid) - (col `div` wid)
next = n - jumps
if next <= 0
then moveXorEol (n * wid)
else do moveXorEol (jumps * wid)
void $ gotoLnFrom 1
lineMoveVisRelUp $ next - 1
lineMoveVisRelDown :: Int -> BufferM ()
lineMoveVisRelDown 0 = return ()
lineMoveVisRelDown n | n < 0 = lineMoveVisRelUp $ negate n
| otherwise = do
wid <- width <$> use lastActiveWindowA
col <- curCol
let jumps = col `div` wid
next = n - jumps
if next <= 0
then leftN (n * wid)
else do leftN (jumps * wid)
void $ gotoLnFrom $ -1
moveToEol
lineMoveVisRelDown $ next - 1
-- | Implements the same logic that emacs' `mark-word` does.
-- Checks the mark point and moves it forth (or backward) for one word.
markWord :: BufferM ()
markWord = do
curPos <- pointB
curMark <- getSelectionMarkPointB
isVisible <- getVisibleSelection
savingPointB $ do
if not isVisible
then nextWordB
else do
moveTo curMark
if curMark < curPos
then prevWordB
else nextWordB
setVisibleSelection True
pointB >>= setSelectionMarkPointB
| ethercrow/yi | yi-core/src/Yi/Buffer/HighLevel.hs | gpl-2.0 | 39,767 | 0 | 22 | 11,084 | 9,520 | 4,847 | 4,673 | 830 | 8 |
{-# LANGUAGE DeriveDataTypeable #-}
module ArrayBonn.Expression where
import ArrayBonn.Operator
import Autolib.TES.Identifier
import Autolib.Reader
import Autolib.ToDoc
import Autolib.Size
import Autolib.Util.Zufall
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr hiding ( Operator )
import Data.Typeable
-- | access to array element
data Access = Access Identifier [ Expression ]
deriving Typeable
instance Size Access where
size ( Access name inds ) = 1 + sum ( map size inds )
instance ToDoc Access where
toDoc ( Access name inds ) =
toDoc name <> hsep ( do ind <- inds ; return $ brackets $ toDoc ind )
instance Reader Access where
reader = do
name <- reader
inds <- many $ my_brackets $ reader
return $ Access name inds
-- | arithmetical expression, with multi-dimensional array access
data Expression = Reference Access
| Literal Integer
| Binary Operator Expression Expression
deriving Typeable
instance Size Expression where
size exp = case exp of
Reference acc -> size acc
Literal i -> 1
Binary op l r -> 1 + size l + size r
instance ToDoc Expression where
toDocPrec p e = case e of
Reference acc -> toDoc acc
Literal i -> toDoc i
Binary op l r ->
case op of
Add -> docParen ( p > 1 )
$ hsep [ toDocPrec 1 l , text "+" , toDocPrec 2 r ]
Subtract -> docParen ( p > 3 )
$ hsep [ toDocPrec 3 l , text "-" , toDocPrec 4 r ]
Multiply -> docParen ( p > 5 )
$ hsep [ toDocPrec 5 l , text "*" , toDocPrec 6 r ]
Divide -> docParen ( p > 7 )
$ hsep [ toDocPrec 7 l , text "/" , toDocPrec 8 r ]
instance Reader Expression where
reader = buildExpressionParser operators atomic
operators =
[ [ op "*" Multiply AssocLeft
, op "/" Divide AssocLeft
]
, [ op "+" Add AssocLeft
, op "-" Subtract AssocLeft
]
]
where
op name f assoc =
Infix ( do { my_symbol name; return $ Binary f } ) assoc
atomic :: Parser Expression
atomic = my_parens reader
<|> do i <- my_integer ; return $ Literal i
<|> do a <- reader ; return $ Reference a
| Erdwolf/autotool-bonn | src/ArrayBonn/Expression.hs | gpl-2.0 | 2,259 | 10 | 14 | 674 | 705 | 361 | 344 | 59 | 1 |
module Web.Scotty.Login.Internal.Cookies where
import qualified Data.Text as T
import Data.Time.Clock
import Web.Cookie
import Web.Scotty.Cookie
import Web.Scotty.Trans
setSimpleCookieExpr :: (Monad m, ScottyError e)
=> T.Text
-> T.Text
-> UTCTime
-> ActionT e m ()
setSimpleCookieExpr n v t = setCookie
((makeSimpleCookie n v) { setCookieExpires = Just t})
| asg0451/scotty-login-session | src/Web/Scotty/Login/Internal/Cookies.hs | gpl-2.0 | 501 | 0 | 10 | 190 | 122 | 70 | 52 | 13 | 1 |
{- |
Module : $Header$
Description : Compute the composition table of a relational algebra
Copyright : (c) Till Mossakowski, Uni Bremen 2002-2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
Compute the composition table of a relational algebra
that isspecified in a particular way in a CASL theory.
-}
module CASL.CompositionTable.ComputeTable where
import CASL.CompositionTable.CompositionTable
import CASL.AS_Basic_CASL
import CASL.Sign
import Common.AS_Annotation
import Common.Id
import Common.IRI (IRI)
import Common.DocUtils
import Common.Result
import qualified Common.Lib.Rel as Rel
import Data.Maybe
import qualified Data.Set as Set
-- | given a specfication (name and theory), compute the composition table
computeCompTable :: IRI -> (Sign f e, [Named (FORMULA f)])
-> Result Table
computeCompTable spName (sig,nsens) = do
{- look for something isomorphic to
sorts BaseRel < Rel
ops
id : BaseRel;
0,1 : Rel;
inv__ : BaseRel -> BaseRel;
__cmps__: BaseRel * BaseRel -> Rel;
compl__: Rel -> Rel;
__cup__ : Rel * Rel -> Rel, assoc, idem, comm, unit 1
forall x:BaseRel
. x cmps id = x
. id cmps x = x
. inv(id) = id
-}
let name = showDoc spName ""
errmsg = "cannot determine composition table of specification "++name
errSorts = errmsg
++ "\nneed exactly two sorts s,t, with s<t, but found:\n"
++ showDoc ((emptySign ()::Sign () ())
{ sortRel = sortRel sig }) ""
errOps ops prof =
errmsg ++ "\nneed exactly one operation "++prof++", but found:\n"
++ showDoc ops ""
-- look for sorts
(baseRel,rel) <-
case map Set.toList $ Rel.topSort $ sortRel sig of
[[b],[r]] -> return (b,r)
_ -> fail errSorts
-- types of operation symbols
let opTypes = mapSetToList (opMap sig)
invt = mkTotOpType [baseRel] baseRel
cmpt = mkTotOpType [baseRel, baseRel] rel
complt = mkTotOpType [rel] rel
cupt = mkTotOpType [rel, rel] rel
-- look for operation symbols
let mlookup t = map fst $ filter ((== t) . snd) opTypes
let oplookup typ msg =
case mlookup typ of
[op] -> return op
ops -> fail (errOps ops msg )
cmps <- oplookup cmpt "__cmps__: BaseRel * BaseRel -> Rel"
_cmpl <- oplookup complt "compl__: Rel -> Rel"
inv <- oplookup invt "inv__ : BaseRel -> BaseRel"
cup <- oplookup cupt "__cup__ : Rel * Rel -> Rel"
{- look for
forall x:BaseRel
. x cmps id = x
. id cmps x = x
. inv(id) = id -}
-- let idaxioms idt =
-- [Quantification Universal [Var_decl [x] baseRel nullRange ....
-- let ids = mlookup idt
let sens = map (stripQuant . sentence) nsens
let cmpTab sen = case sen of
Strong_equation (Application (Qual_op_name c _ _)
[Application (Qual_op_name arg1 _ _) [] _,
Application (Qual_op_name arg2 _ _) [] _] _)
res _ ->
if c==cmps
then
Just (Cmptabentry
(Cmptabentry_Attrs {
cmptabentryArgBaserel1 = Baserel (showDoc arg1 ""),
cmptabentryArgBaserel2 = Baserel (showDoc arg2 "") })
(extractRel cup res) )
else Nothing
_ -> Nothing
let invTab sen = case sen of
Strong_equation (Application (Qual_op_name i _ _)
[Application (Qual_op_name arg _ _) [] _] _)
(Application (Qual_op_name res _ _) [] _) _ ->
if i==inv
then
Just (Contabentry {
contabentryArgBaseRel = Baserel (showDoc arg ""),
contabentryConverseBaseRel = Baserel (showDoc res "") } )
else Nothing
_ -> Nothing
let attrs = Table_Attrs
{ tableName = name
, tableIdentity = Baserel "id"
, baseRelations = []
}
compTable = Compositiontable (mapMaybe cmpTab sens)
convTable = Conversetable (mapMaybe invTab sens)
models = Models []
return $ Table attrs compTable convTable (Reflectiontable []) models
stripQuant :: FORMULA f -> FORMULA f
stripQuant (Quantification _ _ f _) = stripQuant f
stripQuant f = f
extractRel :: Id -> TERM f -> [Baserel]
extractRel cup (Application (Qual_op_name cup' _ _) [arg1,arg2] _) =
if cup==cup'
then extractRel cup arg1 ++ extractRel cup arg2
else []
extractRel _ (Application (Qual_op_name b _ _) [] _) =
[Baserel (showDoc b "")]
extractRel _ _ = []
| nevrenato/Hets_Fork | CASL/CompositionTable/ComputeTable.hs | gpl-2.0 | 4,785 | 0 | 22 | 1,516 | 1,158 | 596 | 562 | 85 | 7 |
-- |
-- Module : Tests.Lexer
-- Copyright : (c) 2013 Rémy Oudompheng
-- License : GPLv3 (see COPYING)
--
-- This module provides tests for the lexer.
module Tests.Lexer (testsLexer) where
import Test.Tasty
import Test.Tasty.HUnit
import Language.Go.Parser.Lexer
import Language.Go.Parser.Tokens (
GoToken(..)
, GoTokenPos(..)
, insertSemi
)
testLex :: String -> String -> [GoToken] -> TestTree
testLex desc text ref = testCase desc $ assertEqual desc ref toks
where toks = map strip $ insertSemi $ alexScanTokens text
strip (GoTokenPos _ tok) = tok
testRawString1 = testLex "raw string"
"`hello`"
[ GoTokStr (Just "`hello`") "hello"
, GoTokSemicolon]
testRawString2 = testLex "raw multiline string"
"`hello\n\tworld`"
[ GoTokStr (Just "`hello\n\tworld`") "hello\n\tworld"
, GoTokSemicolon]
testCharLit1 = testLex "rune literal for backslash"
"'\\\\'"
[ GoTokChar (Just "'\\\\'") '\\'
, GoTokSemicolon]
testCharLit2 = testLex "rune literal for newline"
"'\\n'"
[ GoTokChar (Just "'\\n'") '\n'
, GoTokSemicolon]
testCharLit3 = testLex "rune literal for e-acute"
"'é'"
[ GoTokChar (Just "'é'") 'é'
, GoTokSemicolon]
testCharLit4 = testLex "rune literal with octal escaping"
"'\\377'"
[ GoTokChar (Just "'\\377'") '\xff'
, GoTokSemicolon]
testString1 = testLex "string with backslash"
"\"\\\\\""
[ GoTokStr (Just "\"\\\\\"") "\\"
, GoTokSemicolon]
testString2 = testLex "long string with backslash"
"{\"\\\\\", \"a\", false, ErrBadPattern},"
[ GoTokLBrace
, GoTokStr (Just "\"\\\\\"") "\\"
, GoTokComma,GoTokStr (Just "\"a\"") "a"
, GoTokComma
, GoTokId "false"
, GoTokComma
, GoTokId "ErrBadPattern"
, GoTokRBrace
, GoTokComma
]
testString3 = testLex "string with tab"
"\"\t\""
[ GoTokStr (Just "\"\t\"") "\t"
, GoTokSemicolon]
testString4 = testLex "string literal with octal escaping"
"\"\\377\""
[ GoTokStr (Just "\"\\377\"") "\xff"
, GoTokSemicolon]
testFloat1 = testLex "floating point"
"11."
[ GoTokReal (Just "11.") 11
, GoTokSemicolon]
testFloat2 = testLex "floating point"
"11.e+3"
[ GoTokReal (Just "11.e+3") 11e+3
, GoTokSemicolon]
testFloat3 = testLex "floating point"
".5"
[ GoTokReal (Just ".5") 0.5
, GoTokSemicolon]
testId1 = testLex "non-ASCII identifier"
"α := 2"
[ GoTokId "α"
, GoTokColonEq
, GoTokInt (Just "2") 2
, GoTokSemicolon
]
testComment1 = testLex "comment with non-ASCII characters"
"/* αβ */"
[ GoTokComment True " αβ " ]
testComment2 = testLex "comment with non-ASCII characters"
"/*\n\tαβ\n*/"
[ GoTokComment True "\n\tαβ\n" ]
testComment3 = testLex "comment with odd number of stars"
"/***/"
[ GoTokComment True "*" ]
testComment4 = testLex "comment with many stars"
"/******\n ******/"
[ GoTokComment True "*****\n *****" ]
testsLexer :: TestTree
testsLexer = testGroup "lexer tests"
[ testRawString1
, testRawString2
, testCharLit1
, testCharLit2
, testCharLit3
, testCharLit4
, testString1
, testString2
, testString3
, testString4
, testFloat1
, testFloat2
, testFloat3
, testId1
, testComment1
, testComment2
, testComment3
, testComment4
]
| remyoudompheng/hs-language-go | tests/Tests/Lexer.hs | gpl-3.0 | 3,202 | 0 | 9 | 630 | 749 | 406 | 343 | 109 | 1 |
module Model.Types where
import ClassyPrelude.Yesod
type ControlIO m = (MonadIO m, MonadBaseControl IO m)
type DBM m a =
(ControlIO m, MonadThrow m, Monad m) => SqlPersistT m a
type DB a = forall m. DBM m a
type DBVal val =
( PersistEntity val
, PersistEntityBackend val ~ SqlBackend
, PersistStore (PersistEntityBackend val))
fetchThingByField
:: (PersistField typ, DBVal val)
=> EntityField val typ -> typ -> DB (Maybe (Entity val))
fetchThingByField field u =
selectFirst [field ==. u] []
| alexeyzab/cards-with-comrades | backend/src/Model/Types.hs | gpl-3.0 | 522 | 0 | 12 | 110 | 190 | 103 | 87 | -1 | -1 |
-- | Parsers for P
-- | Juan García Garland (Nov. 2016)
module Parser where
import Lexer
import Language
import Exception
import ParserCombinators
-- | The type of P Parser
type PParser = Parser [Token]
pToken :: Token -> PParser Token
pToken t = Parser $ \s -> case s of
[] -> []
(t':ts) -> if t==t'
then [(t,ts)]
else []
-- | Parsers for P tokens
-- | values of type :: PParser Token
pTProgram = pToken TProgram
pTResult = pToken TResult
pTLParen = pToken TLParen
pTRParen = pToken TRParen
pTWhile = pToken TWhile
pTDo = pToken TDo
pTEnd = pToken TEnd
pTSemicol = pToken TSemicol
pTSuc = pToken TSuc
pTPred = pToken TPred
pTZero = pToken TZero
pTNeq0 = pToken TNeq0
pTAssignSym
= pToken TAssignSym
pTVar :: PParser Int
pTVar = Parser $ \ts -> case ts of
(TVar s):ts' -> [((read.tail) s,ts')]
_ -> []
-- | generating AST
pSec = Sec <$> pList pSent
pCond = (\var _ -> Nonzero var) <$> pTVar <*> pTNeq0
pWhile
= (\_ c _ s _-> While c s ) <$> pTWhile <*> pCond <*> pTDo <*> pSec <*> pTEnd
pExpr = const Zero <$> pTZero
<|> (\_ _ v _ -> Succ v) <$> pTSuc <*> pTLParen <*> pTVar <*> pTRParen
<|> (\_ _ v _ -> Pred v) <$> pTPred <*> pTLParen <*> pTVar <*> pTRParen
pAssign = (\v _ e -> Assign v e) <$> pTVar <*> pTAssignSym <*> pExpr
pSent = pAssign
<|> pWhile
pProgram = (\_ _ vi _ s _ _ vo _ -> Program vi s vo) <$> pTProgram
<*> pTLParen
<*> pTVar
<*> pTRParen
<*> pSec
<*> pTResult
<*> pTLParen
<*> pTVar
<*> pTRParen
| jota191/PLang | src/Parser.hs | gpl-3.0 | 2,158 | 0 | 17 | 1,022 | 569 | 303 | 266 | 49 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-|
Module : Hypercube.Shaders
Description : The shaders
Copyright : (c) Jaro Reinders, 2017
License : GPL-3
Maintainer : [email protected]
This module contains the shaders as bytestrings and a function that produces an OpenGL @Program@ that uses those shaders.
The shaders are embedded to make sure that they are present when running the game.
-}
module Hypercube.Shaders (shaders) where
import qualified Graphics.Rendering.OpenGL as GL
import qualified Data.ByteString as B
import System.Exit
import Control.Monad
import Data.FileEmbed
shaders :: IO GL.Program
shaders = do
v <- GL.createShader GL.VertexShader
GL.shaderSourceBS v GL.$= vector
GL.compileShader v
vs <- GL.get (GL.compileStatus v)
unless vs $ do
print =<< GL.get (GL.shaderInfoLog v)
exitFailure
f <- GL.createShader GL.FragmentShader
GL.shaderSourceBS f GL.$= fragment
GL.compileShader f
fs <- GL.get (GL.compileStatus f)
unless fs $ do
putStrLn =<< GL.get (GL.shaderInfoLog f)
exitFailure
p <- GL.createProgram
GL.attachShader p v
GL.attachShader p f
GL.linkProgram p
return p
vector :: B.ByteString
vector = $(embedFile "vertex.glsl")
fragment :: B.ByteString
fragment = $(embedFile "fragment.glsl")
| noughtmare/hypercube | src/Hypercube/Shaders.hs | gpl-3.0 | 1,313 | 0 | 14 | 232 | 320 | 153 | 167 | 33 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
-- Module : Khan.Model.IAM.ServerCertificate
-- Copyright : (c) 2013 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
module Khan.Model.IAM.ServerCertificate
( find
, upload
, delete
) where
import qualified Filesystem as FS
import Khan.Internal
import Khan.Prelude hiding (find)
import Network.AWS.IAM
find :: Text -> AWS (Maybe ServerCertificateMetadata)
find dom = do
say "Searching for Certificate {}" [dom]
sendCatch (GetServerCertificate dom) >>= verify
where
verify (Right x) = return $ Just (unwrap x)
verify (Left e)
| "NoSuchEntity" == etCode (erError e) = return Nothing
| otherwise = throwError (toError e)
unwrap = scServerCertificateMetadata
. gscrServerCertificate
. gscrGetServerCertificateResult
upload :: Text -> FilePath -> FilePath -> Maybe FilePath -> AWS ()
upload dom pubp privp chainp = do
(pub, priv, chain) <- liftAWS $
(,,) <$> loadKey pubp "Reading public key from {}"
<*> loadKey privp "Reading private key from {}"
<*> loadChain chainp
say "Upload Certificate {}" [dom]
send_ UploadServerCertificate
{ uscCertificateBody = pub
, uscPrivateKey = priv
, uscCertificateChain = chain
, uscPath = Nothing
, usdServerCertificateName = dom
}
say "Created Certificate {}" [dom]
where
loadKey path fmt = FS.readTextFile path <* say fmt [path]
loadChain (Just p) = Just <$> loadKey p "Reading certificate chain from {}"
loadChain Nothing = return Nothing
delete :: Text -> AWS ()
delete dom = do
say "Deleting Certificate {}" [dom]
send_ (DeleteServerCertificate dom)
| brendanhay/khan | khan/Khan/Model/IAM/ServerCertificate.hs | mpl-2.0 | 2,222 | 0 | 13 | 618 | 467 | 243 | 224 | 42 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Games.Snapshots.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves the metadata for a given snapshot ID.
--
-- /See:/ <https://developers.google.com/games/services/ Google Play Game Services API Reference> for @games.snapshots.get@.
module Network.Google.Resource.Games.Snapshots.Get
(
-- * REST Resource
SnapshotsGetResource
-- * Creating a Request
, snapshotsGet
, SnapshotsGet
-- * Request Lenses
, sConsistencyToken
, sLanguage
, sSnapshotId
) where
import Network.Google.Games.Types
import Network.Google.Prelude
-- | A resource alias for @games.snapshots.get@ method which the
-- 'SnapshotsGet' request conforms to.
type SnapshotsGetResource =
"games" :>
"v1" :>
"snapshots" :>
Capture "snapshotId" Text :>
QueryParam "consistencyToken" (Textual Int64) :>
QueryParam "language" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Snapshot
-- | Retrieves the metadata for a given snapshot ID.
--
-- /See:/ 'snapshotsGet' smart constructor.
data SnapshotsGet = SnapshotsGet'
{ _sConsistencyToken :: !(Maybe (Textual Int64))
, _sLanguage :: !(Maybe Text)
, _sSnapshotId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'SnapshotsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sConsistencyToken'
--
-- * 'sLanguage'
--
-- * 'sSnapshotId'
snapshotsGet
:: Text -- ^ 'sSnapshotId'
-> SnapshotsGet
snapshotsGet pSSnapshotId_ =
SnapshotsGet'
{ _sConsistencyToken = Nothing
, _sLanguage = Nothing
, _sSnapshotId = pSSnapshotId_
}
-- | The last-seen mutation timestamp.
sConsistencyToken :: Lens' SnapshotsGet (Maybe Int64)
sConsistencyToken
= lens _sConsistencyToken
(\ s a -> s{_sConsistencyToken = a})
. mapping _Coerce
-- | The preferred language to use for strings returned by this method.
sLanguage :: Lens' SnapshotsGet (Maybe Text)
sLanguage
= lens _sLanguage (\ s a -> s{_sLanguage = a})
-- | The ID of the snapshot.
sSnapshotId :: Lens' SnapshotsGet Text
sSnapshotId
= lens _sSnapshotId (\ s a -> s{_sSnapshotId = a})
instance GoogleRequest SnapshotsGet where
type Rs SnapshotsGet = Snapshot
type Scopes SnapshotsGet =
'["https://www.googleapis.com/auth/drive.appdata",
"https://www.googleapis.com/auth/games",
"https://www.googleapis.com/auth/plus.login"]
requestClient SnapshotsGet'{..}
= go _sSnapshotId _sConsistencyToken _sLanguage
(Just AltJSON)
gamesService
where go
= buildClient (Proxy :: Proxy SnapshotsGetResource)
mempty
| rueshyna/gogol | gogol-games/gen/Network/Google/Resource/Games/Snapshots/Get.hs | mpl-2.0 | 3,548 | 0 | 14 | 842 | 487 | 287 | 200 | 73 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances #-}
-- Currently this file is buggy and poorly written--it is being used for
-- testing and prototyping. It will be rewritten.
module Api.Services.LokaService where
------------------------------------------------------------------------------
import Data.Aeson
import Data.ByteString hiding (map, length)
import Control.Lens
import Control.Monad.IO.Class
import Snap.Core
import Snap.Snaplet
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as LB
import qualified Data.Text.Lazy.IO as T
import qualified Data.Text.Lazy.Encoding as T
import Loka
import Types
import Api.Database
import Jsonify
------------------------------------------------------------------------------
data LokaService = LokaService
makeLenses ''LokaService
------------------------------------------------------------------------------
lokaRoutes :: [(B.ByteString, Handler b LokaService ())]
lokaRoutes = [("/game/:gameId/state", method GET gameStateHandler),
("/game/:gameId/action", method POST gameActionHandler),
("/game/:gameId/allmoves", method GET gameAllMovesHandler)]
------------------------------------------------------------------------------
-- | Handles and responds to a request to read the game state. This will read
-- the state from the PostgreSQL database, format it to JSON, and send it back
-- to the client.
gameStateHandler :: Handler b LokaService ()
gameStateHandler = do
gameId <- getParam "gameId"
maybe (writeBS $ jsonError "Invalid game ID") (\gameIdValid -> do
gameState <- liftIO . getGameState $ ((read $ B.unpack gameIdValid) :: Integer)
writeBS $ LB.toStrict $ encode $ JsonGameState (map (uncurry JsonAction) gameState)
$ collapseGameState gameState)
gameId
------------------------------------------------------------------------------
-- | Handles and responds to a request to make an action. This takes in the
-- current game state from the PostgreSQL database, adds an action if the
-- action is valid, writes the new action the database, and then sends back
-- the updated state.
gameActionHandler :: Handler b LokaService ()
gameActionHandler = do
gameId <- getParam "gameId"
maybe (writeBS $ jsonError "Invalid game ID") (\gameIdValid -> do
gameState <- liftIO . getGameState $ ((read $ B.unpack gameIdValid) :: Integer)
body <- readRequestBody 16384
maybe (writeBS $ jsonError "Parse error") (\action -> do
maybe (writeBS $ jsonError "Invalid game move") (\newGameState -> do
liftIO $ addAction ((read $ B.unpack gameIdValid) :: Integer)
(actor action)
(Jsonify.move action)
writeBS $ LB.toStrict $ encode $ JsonGameState (map
(uncurry JsonAction)
newGameState) $ collapseGameState gameState) $
appendGameMove (actor action) (Jsonify.move action) gameState)
$ decode body)
gameId
------------------------------------------------------------------------------
-- | Handles and responds to a request to get all possible moves for a given
-- color.
gameAllMovesHandler :: Handler b LokaService ()
gameAllMovesHandler = do
gameId <- getParam "gameId"
colorParam <- getQueryParam "color"
maybe (writeBS $ jsonError "Invalid game ID") (\gameIdValid -> do
maybe (writeBS $ jsonError "Invalid color") (\colorValid -> do
gameState <- liftIO . getGameState $ ((read $ B.unpack gameIdValid) :: Integer)
writeBS $ LB.toStrict $ encode $ allPossibleMoves
(collapseGameState gameState)
(read (B.unpack colorValid) :: PieceColor)) colorParam) gameId
------------------------------------------------------------------------------
-- | Called by Snap to create the Loka service snaplet
lokaServiceInit :: SnapletInit b LokaService
lokaServiceInit = makeSnaplet "loka" "Loka Service" Nothing $ do
addRoutes lokaRoutes
return $ LokaService
| jakespringer/loka | Server/src/api/services/LokaService.hs | lgpl-3.0 | 3,998 | 0 | 30 | 675 | 824 | 440 | 384 | 63 | 1 |
module StackVM (StackVal(..), StackExp(..), Stack, Program, stackVM) where
-- Values that may appear in the stack. Such a value will also be
-- returned by the stackVM program execution function.
data StackVal = IVal Integer | BVal Bool | Void deriving Show
-- The various expressions our VM understands.
data StackExp = PushI Integer
| PushB Bool
| Add
| Mul
| And
| Or
deriving Show
type Stack = [StackVal]
type Program = [StackExp]
-- Execute the given program. Returns either an error message or the
-- value on top of the stack after execution.
stackVM :: Program -> Either String StackVal
stackVM = execute []
errType :: String -> Either String a
errType op = Left $ "Encountered '" ++ op ++ "' opcode with ill-typed stack."
errUnderflow :: String -> Either String a
errUnderflow op = Left $ "Stack underflow with '" ++ op ++ "' opcode."
-- Execute a program against a given stack.
execute :: Stack -> Program -> Either String StackVal
execute [] [] = Right Void
execute (s : _ ) [] = Right s
execute s (PushI x : xs) = execute (IVal x : s ) xs
execute s (PushB x : xs) = execute (BVal x : s ) xs
execute (IVal s1 : IVal s2 : ss) (Add : xs) = execute (s' : ss) xs where s' = IVal (s1 + s2)
execute (_ : _ : _ ) (Add : _ ) = errType "Add"
execute _ (Add : _ ) = errUnderflow "Add"
execute (IVal s1 : IVal s2 : ss) (Mul : xs) = execute (s' : ss) xs where s' = IVal (s1 * s2)
execute (_ : _ : _ ) (Mul : _ ) = errType "Mul"
execute _ (Mul : _ ) = errUnderflow "Mul"
execute (BVal s1 : BVal s2 : ss) (And : xs) = execute (s' : ss) xs where s' = BVal (s1 && s2)
execute (_ : _ : _ ) (And : _ ) = errType "And"
execute _ (And : _ ) = errUnderflow "And"
execute (BVal s1 : BVal s2 : ss) (Or : xs) = execute (s' : ss) xs where s' = BVal (s1 || s2)
execute (_ : _ : _ ) (Or : _ ) = errType "Or"
execute _ (Or : _ ) = errUnderflow "Or"
test :: Either String StackVal
test = stackVM [PushI 3, PushI 5, Add]
| spanners/cis194 | 05-type-classes/StackVM.hs | unlicense | 2,363 | 0 | 9 | 872 | 810 | 425 | 385 | 36 | 1 |
module Sandbox.CycleStructure where
import Data.Set (Set)
import qualified Data.Set as Set
import Data.List (permutations, (\\))
type PermutationWord = [Int]
type Cycle = [Int]
type CycleStructure = [[Int]]
fromWord p = recurse 1 [] (Set.fromList [1..length p]) where
recurse x currentCycle unseen
| null unseen = [reverse currentCycle]
| x `Set.member` unseen = recurse (p !! (x-1)) (x:currentCycle) (Set.delete x unseen)
| otherwise = reverse currentCycle : recurse (minimum unseen) [] unseen
fromCycleStructure c = map findValue [1..n] where
n = maximum $ concat c
findValue = recurse c where
recurse (c':cs') i
| i `notElem` c' = recurse cs' i
| otherwise = case dropWhile (/= i) c' of [_] -> head c'
(_:a:_) -> a
rescale :: Int -> CycleStructure -> CycleStructure
rescale k pi
| k `notElem` concat pi = pi
| otherwise = map rescale' pi where
rescale' = map (\i -> if i >=k then i + 1 else i)
phi :: Int -> Int -> CycleStructure -> CycleStructure
phi k i pi = phi' $ rescale i pi where
phi' [] = [[i]]
phi' pi'@(c1:cs)
| i < head c1 = [i]:c1:cs
| length c1 == k = case c1 of (a1:a2:as) -> (a1:i:as) : phi k a2 cs
| length c1 == k - 1 = p i $ psi k c1 cs
| otherwise = p i pi'
psi :: Int -> Cycle -> CycleStructure -> CycleStructure
psi k a's [] = [a's]
psi k (a'1:a's) pi@([a1]:cs) = (a'1:a1:a's) : cs
psi k (a'1:a's) (c1@(a1:a2:as):cs)
| length c1 == k = (a'1:a2:a's) : psi k (a1:as) cs
| length c1 == k + 1 = (a'1:a2:a's) : init (a1:as) : phi k (last as) cs
| otherwise = (a'1:a2:a's) : (a1:as) : cs
p :: Int -> CycleStructure -> CycleStructure
p i ((a1:as):cs) = (a1:i:as):cs
-- How to invert this?
| peterokagey/haskellOEIS | src/Sandbox/Sami/Bijection2.hs | apache-2.0 | 1,793 | 0 | 15 | 494 | 948 | 489 | 459 | 41 | 2 |
{-# LANGUAGE RankNTypes #-}
module HepMC.Pipes where
import Control.Monad.IO.Class
import Control.Monad.Trans
import Data.ByteString (ByteString)
import Data.Maybe (fromMaybe)
import HepMC.Event
import HepMC.Parse
import Pipes
import qualified Pipes.Attoparsec as PA
import qualified Pipes.Parse as PP
-- TODO
-- this doesn't exit cleanly....
fromStream :: MonadIO m => Producer ByteString m x -> Producer Event m ()
fromStream p = do
(evers, p') <- lift $ PP.runStateT (parseOne hmcvers) p
case evers of
Left s -> liftIO $ print s
Right v -> do
liftIO . putStrLn $ "hepmc version: " ++ show v
ex <- PA.parsed parserEvent p'
case ex of
Right _ -> liftIO $ print "no hepmc footer?!"
Left (_, p'') -> do
(exxx, _) <- lift $ PP.runStateT (parseOne hmcend) p''
case exxx of
Right _ -> liftIO $ putStrLn "finished."
Left x -> liftIO $ print x
parseOne
:: Monad m
=> Parser b
-> PP.Parser ByteString m (Either PA.ParsingError b)
parseOne p = do
mex <- PA.parse p
return $ fromMaybe (Left $ PA.ParsingError [] "no input!") mex
| cspollard/HHepMC | src/HepMC/Pipes.hs | apache-2.0 | 1,241 | 0 | 21 | 392 | 398 | 200 | 198 | 33 | 4 |
module Main where
import RestrictionTests(restrictionTests)
import JEPFormulaTests(formulaTests)
import BonusTests(bonusTests)
import Test.HUnit
import Control.Monad
import System.Exit
tests :: [Test]
tests = [ formulaTests
, restrictionTests
, bonusTests
]
validate :: Test -> IO ()
validate t = do
c <- runTestTT t
when (errors c /= 0 || failures c /= 0)
exitFailure
return ()
main :: IO ()
main = forM_ tests validate
| gamelost/pcgen-rules | test/Main.hs | apache-2.0 | 459 | 0 | 12 | 101 | 154 | 82 | 72 | 19 | 1 |
{-# LANGUAGE TemplateHaskell, UndecidableInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Type.Binary
-- Copyright : (C) 2006 Edward Kmett
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable (MPTC, FD, TH, undecidable instances, and missing constructors)
--
-- Simple type-level binary numbers, positive and negative with infinite
-- precision. This forms a nice commutative ring with multiplicative identity
-- like we would expect from a representation for Z.
--
-- The numbers are represented as a Boolean Ring over a countable set of
-- variables, in which for every element in the set there exists an n in N
-- and a b in {T,F} such that forall n' >= n in N, x_i = b.
--
-- For uniqueness we always choose the least such n when representing numbers
-- this allows us to run most computations backwards. When we can't, and such
-- a fundep would be implied, we obtain it by combining semi-operations that
-- together yield the appropriate class fundep list.
--
-- The goal here was to pull together many of the good ideas I've seen from
-- various sources, and sprinkle a two's complement negative number
-- representation on top.
--
-- Reuses T and F from the Type.Boolean as the infinite tail of the 2s
-- complement binary number. I'm particularly fond of the symmetry exhibited
-- in the full adder.
--
-- TODO: @TDivMod, TImplies, TGCD, TBit, TComplementBit, TSetBit@
----------------------------------------------------------------------------
module Data.Type.Binary
( module Data.Type.Binary.Internals
, module Data.Type.Boolean
, module Data.Type.Ord
, module Data.Type.Binary.TH
) where
import Data.Type.Boolean
import Data.Type.Ord
import Data.Type.Binary.Internals
import Data.Type.Binary.TH
| ekmett/type-int | Data/Type/Binary.hs | bsd-2-clause | 1,934 | 0 | 5 | 319 | 99 | 80 | 19 | 10 | 0 |
module Graphics.GL.Low.Blending (
-- | When blending is enabled, colors written to the color buffer will be
-- blended using a formula with the color already there. The three options
-- for the formula are:
--
-- - S*s + D*d ('FuncAdd', the default)
-- - S*s - D*d ('FuncSubtract')
-- - D*d - S*s ('FuncReverseSubtract')
--
-- where S and D are source and destination color components respectively. The
-- factors s and d are computed blending factors which can depend on the alpha
-- component of the source pixel, the destination pixel, or a specified
-- constant color. See 'basicBlending' for a common choice.
enableBlending,
disableBlending,
basicBlending,
Blending(..),
BlendFactor(..),
BlendEquation(..)
-- * Example
-- $example
) where
import Control.Monad.IO.Class
import Data.Default
import Graphics.GL
import Graphics.GL.Low.Classes
-- | Enable blending with the specified blending parameters.
enableBlending :: (MonadIO m) => Blending -> m ()
enableBlending (Blending s d f (r,g,b,a)) = do
glBlendFunc (toGL s) (toGL d)
glBlendEquation (toGL f)
let c = realToFrac
glBlendColor (c r) (c g) (c b) (c a)
glEnable GL_BLEND
-- | Disable alpha blending.
disableBlending :: (MonadIO m) => m ()
disableBlending = glDisable GL_BLEND
-- | This blending configuration is suitable for ordinary alpha blending
-- transparency effects.
--
-- @
-- Blending
-- { sFactor = BlendSourceAlpha
-- , dFactor = BlendOneMinusSourceAlpha
-- , blendFunc = FuncAdd }
-- @
basicBlending :: Blending
basicBlending = def
{ sFactor = BlendSourceAlpha
, dFactor = BlendOneMinusSourceAlpha }
-- | Blending parameters.
data Blending = Blending
{ sFactor :: BlendFactor
, dFactor :: BlendFactor
, blendFunc :: BlendEquation
, blendColor :: (Float,Float,Float,Float) }
-- | The default blending parameters have no effect if enabled. The result
-- will be no blending effect.
instance Default Blending where
def = Blending
{ sFactor = BlendOne
, dFactor = BlendZero
, blendFunc = FuncAdd
, blendColor = (0,0,0,0) }
-- | Blending functions.
data BlendEquation =
FuncAdd | -- ^ the default
FuncSubtract |
FuncReverseSubtract
deriving (Eq, Ord, Show, Read)
instance Default BlendEquation where
def = FuncAdd
instance ToGL BlendEquation where
toGL FuncAdd = GL_FUNC_ADD
toGL FuncSubtract = GL_FUNC_SUBTRACT
toGL FuncReverseSubtract = GL_FUNC_REVERSE_SUBTRACT
-- | Blending factors.
data BlendFactor =
BlendOne |
BlendZero |
BlendSourceColor |
BlendOneMinusSourceColor |
BlendDestColor |
BlendOneMinusDestColor |
BlendSourceAlpha |
BlendOneMinusSourceAlpha |
BlendDestAlpha |
BlendOneMinusDestAlpha |
BlendConstantColor |
BlendOneMinusConstantColor |
BlendConstantAlpha |
BlendOneMinusConstantAlpha
deriving Show
instance ToGL BlendFactor where
toGL BlendOne = GL_ONE
toGL BlendZero = GL_ZERO
toGL BlendSourceColor = GL_SRC_COLOR
toGL BlendOneMinusSourceColor = GL_ONE_MINUS_SRC_COLOR
toGL BlendDestColor = GL_DST_COLOR
toGL BlendOneMinusDestColor = GL_ONE_MINUS_DST_COLOR
toGL BlendSourceAlpha = GL_SRC_ALPHA
toGL BlendOneMinusSourceAlpha = GL_ONE_MINUS_SRC_ALPHA
toGL BlendDestAlpha = GL_DST_ALPHA
toGL BlendOneMinusDestAlpha = GL_ONE_MINUS_DST_ALPHA
toGL BlendConstantColor = GL_ONE_MINUS_CONSTANT_COLOR
toGL BlendOneMinusConstantColor = GL_ONE_MINUS_CONSTANT_COLOR
toGL BlendConstantAlpha = GL_CONSTANT_ALPHA
toGL BlendOneMinusConstantAlpha = GL_ONE_MINUS_CONSTANT_ALPHA
-- $example
--
-- <<blending1.png Blending Before>> <<blending2.png Blending After>>
--
-- This program draws two half-transparent shapes. When you press a key they
-- are rendered in the opposite order. This makes one appear as if it were in
-- front of the other. Because the depth test (see "Graphics.GL.Low.Depth")
-- must be disabled while using this kind of blending, there may be significant
-- overdraw in areas with many blending layers. This can harm performance.
-- Also the order-dependency can make using alpha blending in a 3D scene
-- complex or impossible. It may make more sense to use an off-screen render
-- pass (see "Graphics.GL.Low.Framebuffer") and an appropriate shader to
-- simulate transparency effects.
--
-- @
-- module Main where
--
-- import Control.Monad.Loops (whileM_)
-- import Data.Functor ((\<$\>))
-- import qualified Data.Vector.Storable as V
-- import Control.Concurrent.STM
--
-- import qualified Graphics.UI.GLFW as GLFW
-- import Linear
-- import Graphics.GL.Low
--
-- main = do
-- GLFW.init
-- GLFW.windowHint (GLFW.WindowHint'ContextVersionMajor 3)
-- GLFW.windowHint (GLFW.WindowHint'ContextVersionMinor 2)
-- GLFW.windowHint (GLFW.WindowHint'OpenGLForwardCompat True)
-- GLFW.windowHint (GLFW.WindowHint'OpenGLProfile GLFW.OpenGLProfile'Core)
-- mwin <- GLFW.createWindow 640 480 \"Blending\" Nothing Nothing
-- case mwin of
-- Nothing -> putStrLn "createWindow failed"
-- Just win -> do
-- GLFW.makeContextCurrent (Just win)
-- GLFW.swapInterval 1
-- shouldSwap <- newTVarIO False
-- (GLFW.setKeyCallback win . Just)
-- (\_ _ _ _ _ -> atomically (modifyTVar shouldSwap not))
-- (vao, prog) <- setup
-- whileM_ (not \<$\> GLFW.windowShouldClose win) $ do
-- GLFW.pollEvents
-- draw vao prog shouldSwap
-- GLFW.swapBuffers win
--
-- setup = do
-- vao <- newVAO
-- bindVAO vao
-- vsource <- readFile "blending.vert"
-- fsource <- readFile "blending.frag"
-- prog <- newProgram vsource fsource
-- useProgram prog
-- let blob = V.fromList
-- [ -0.5, 0.5
-- , 0.5, 0
-- , -0.5, -0.5 ] :: V.Vector Float
-- vbo <- newVBO blob StaticDraw
-- bindVBO vbo
-- setVertexLayout [Attrib "position" 2 GLFloat]
-- enableBlending basicBlending
-- return (vao, prog)
--
-- draw vao prog shouldSwap = do
-- clearColorBuffer (0,0,0)
-- yes <- readTVarIO shouldSwap
-- if yes
-- then sequence [drawRed, drawGreen]
-- else sequence [drawGreen, drawRed]
--
-- drawGreen = do
-- setUniform3f "color" [V3 0 1 0]
-- setUniform1f "alpha" [0.5]
-- setUniform44 "move" [eye4]
-- drawTriangles 3
--
-- drawRed = do
-- let ninety = pi/2
-- let move = mkTransformation (axisAngle (V3 0 0 1) ninety) (V3 0.25 0.5 0)
-- setUniform3f "color" [V3 1 0 0]
-- setUniform1f "alpha" [0.5]
-- setUniform44 "move" [transpose move]
-- drawTriangles 3
-- @
--
-- blending.vert
--
-- @
-- #version 150
--
-- in vec3 Color;
-- in float Alpha;
-- out vec4 outColor;
--
-- void main()
-- {
-- outColor = vec4(Color, Alpha);
-- }
-- @
--
-- blending.frag
--
-- @
-- #version 150
--
-- uniform vec3 color;
-- uniform float alpha;
-- uniform mat4 move;
--
-- in vec2 position;
-- out vec3 Color;
-- out float Alpha;
--
-- void main()
-- {
-- gl_Position = move * vec4(position, 0.0, 1.0);
-- Color = color;
-- Alpha = alpha;
-- }
-- @
| sgraf812/lowgl | Graphics/GL/Low/Blending.hs | bsd-2-clause | 6,946 | 0 | 9 | 1,345 | 747 | 486 | 261 | 77 | 1 |
{-# LANGUAGE TypeOperators, DataKinds #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Metrology.SI.PolyTypes
-- Copyright : (C) 2013 Richard Eisenberg
-- License : BSD-style (see LICENSE)
-- Maintainer : Richard Eisenberg ([email protected])
-- Stability : experimental
-- Portability : non-portable
--
-- This module defines type synonyms for dimensions based on the seven
-- SI dimensions, for arbitrary choice of system of units and numerical values.
-----------------------------------------------------------------------------
module Data.Metrology.SI.PolyTypes where
import Data.Metrology
import qualified Data.Dimensions.SI as D
type Length = MkQu_DLN D.Length
type Mass = MkQu_DLN D.Mass
type Time = MkQu_DLN D.Time
type Current = MkQu_DLN D.Current
type Temperature = MkQu_DLN D.Temperature
type AmountOfSubstance = MkQu_DLN D.AmountOfSubstance
type LuminousIntensity = MkQu_DLN D.LuminousIntensity
type PlaneAngle = MkQu_D D.PlaneAngle
type SolidAngle = MkQu_D D.SolidAngle
type Area = MkQu_DLN D.Area
type Volume = MkQu_DLN D.Volume
type Velocity = MkQu_DLN D.Velocity
type Acceleration = MkQu_DLN D.Acceleration
type Wavenumber = MkQu_DLN D.Wavenumber
type Density = MkQu_DLN D.Density
type SurfaceDensity = MkQu_DLN D.SurfaceDensity
type SpecificVolume = MkQu_DLN D.SpecificVolume
type CurrentDensity = MkQu_DLN D.CurrentDensity
type MagneticStrength = MkQu_DLN D.MagneticStrength
type Concentration = MkQu_DLN D.Concentration
type Luminance = MkQu_DLN D.Luminance
type Frequency = MkQu_DLN D.Frequency
type Force = MkQu_DLN D.Force
type Pressure = MkQu_DLN D.Pressure
type Energy = MkQu_DLN D.Energy
type Power = MkQu_DLN D.Power
type Charge = MkQu_DLN D.Charge
type ElectricPotential = MkQu_DLN D.ElectricPotential
type Capacitance = MkQu_DLN D.Capacitance
type Resistance = MkQu_DLN D.Resistance
type Conductance = MkQu_DLN D.Conductance
type MagneticFlux = MkQu_DLN D.MagneticFlux
type MagneticFluxDensity = MkQu_DLN D.MagneticFluxDensity
type Inductance = MkQu_DLN D.Inductance
type LuminousFlux = MkQu_DLN D.LuminousFlux
type Illuminance = MkQu_DLN D.Illuminance
type Kerma = MkQu_DLN D.Kerma
type CatalyticActivity = MkQu_DLN D.CatalyticActivity
type Momentum = MkQu_DLN D.Momentum
type AngularVelocity = MkQu_DLN D.AngularVelocity
| goldfirere/units | units-defs/Data/Metrology/SI/PolyTypes.hs | bsd-3-clause | 2,685 | 0 | 6 | 651 | 475 | 269 | 206 | 44 | 0 |
module Graphics.XHB.Connection.Open (open, DispName(..)) where
import System.Environment(getEnv)
import System.IO
import Control.Exception hiding (try)
import Control.Monad
import Control.Applicative((<$>))
import Data.Foldable (foldrM)
import Network.Socket
import Graphics.X11.Xauth
import Data.Maybe (fromMaybe)
import Text.ParserCombinators.Parsec
import Graphics.XHB.Connection.Auth
data DispName = DispName { proto :: String
, host :: String
, display :: Int
, screen :: Int
} deriving Show
-- | Open a Handle to the X11 server specified in the argument. The DISPLAY
-- environment variable is consulted if the argument is null.
open :: String -> IO (Handle , Maybe Xauth, DispName)
open [] = (getEnv "DISPLAY") >>= open
open disp
| take 11 disp == "/tmp/launch" = do
fd <- fromMaybe (error "couldn't open socket") <$> openUnix "" disp
hndl <- socketToHandle fd ReadWriteMode
return (hndl, Nothing, launchDDisplayInfo disp)
open xs = let
cont (DispName p h d s)
| null h || null p && h == "unix" = openUnix p
("/tmp/.X11-unix/X" ++ show d)
| otherwise = openTCP p h (6000 + d)
openTCP proto host port
| proto == [] || proto == "tcp" =
let addrInfo = defaultHints { addrFlags = [ AI_ADDRCONFIG
, AI_NUMERICSERV
]
, addrFamily = AF_UNSPEC
, addrSocketType = Stream
}
conn (AddrInfo _ fam socktype proto addr _) Nothing = do
fd <- socket fam socktype proto
connect fd addr
return $ Just fd
conn _ x = return x
in getAddrInfo (Just addrInfo) (Just host) (Just (show port))
>>= foldrM conn Nothing
| otherwise = error "'protocol' should be empty or 'tcp'"
in case parseDisplay xs of
(Left e) -> error (show e)
(Right x) -> do
socket <- cont x >>= return . fromMaybe
(error "couldn't open socket")
auth <- getAuthInfo socket (display x)
hndl <- socketToHandle socket ReadWriteMode
return (hndl, auth, x)
openUnix proto file
| proto == [] || proto == "unix" = do
fd <- socket AF_UNIX Stream defaultProtocol
connect fd (SockAddrUnix file)
return $ Just fd
| otherwise = error "'protocol' should be empty or 'unix'"
-- | Parse the contents of an X11 DISPLAY environment variable.
-- TODO: make a public version (see xcb_parse_display)
parseDisplay :: String -> Either ParseError DispName
parseDisplay [] = Right defaultDisplayInfo
parseDisplay xs = parse exp "" xs where
exp = do
p <- option "" (try $ skip '/') <?> "protocol"
h <- option "" ((try ipv6) <|> (try host)) <?> "host"
d <- char ':' >> integer <?> "display"
s <- option 0 (char '.' >> integer <?> "screen")
return $ DispName p h d s
eat c s = char c >> return s
anyExcept c = many1 (noneOf [c])
skip c = anyExcept c >>= eat c
ipv6 = char '[' >> skip ']'
host = anyExcept ':'
integer :: Parser Int
integer = many1 digit >>= \x -> return $ read x
-- | Given a launchd display-string, return the appropriate
-- DispName structure for it.
launchDDisplayInfo :: String -> DispName
launchDDisplayInfo str = case parseDisplay (dropWhile (/= ':') str) of
Left{} -> defaultDisplayInfo
Right d -> d
defaultDisplayInfo = DispName "" "" 0 0 | aslatter/xhb | Graphics/XHB/Connection/Open.hs | bsd-3-clause | 3,778 | 0 | 17 | 1,299 | 1,103 | 549 | 554 | 78 | 3 |
module Zero.Index
(
Index(..)
) where
------------------------------------------------------------------------------
import Data.Aeson
import Zero.View
------------------------------------------------------------------------------
data Index = Index
deriving (Show, Generic)
instance ToJSON Index
instance ToSchema Index where
declareNamedSchema proxy = genericDeclareNamedSchema defaultSchemaOptions proxy
& mapped.schema.description ?~ "The root of the project."
& mapped.schema.example ?~ toJSON Index
instance ToHtml Index where
toHtml i = do
head_ $ do
meta_ [charset_ "utf-8"]
meta_ [httpEquiv_ "x-ua-compatible", content_ "IE=edge"]
meta_ [name_ "viewport", content_ "width=device-width,initial-scale=1"]
script_ "" `with` [src_ "/static/js/rts.js"]
script_ "" `with` [src_ "/static/js/lib.js"]
script_ "" `with` [src_ "/static/js/out.js"]
body_ $ return ()
script_ "" `with` [src_ "/static/js/runmain.js", defer_ "true"]
toHtmlRaw = toHtml
| et4te/zero | src-shared/Zero/Index.hs | bsd-3-clause | 1,052 | 0 | 13 | 202 | 266 | 133 | 133 | -1 | -1 |
module Hack2.Contrib.Middleware.NotFound (not_found) where
import Hack2
import Hack2.Contrib.Response
import Hack2.Contrib.Constants
import Air.Light
import Prelude hiding ((.), (^), (>), (+))
import Data.Default
not_found :: Middleware
not_found _ = \_ -> return $
def
.set_status 404
.set_content_type _TextHtml
.set_content_length 0
| nfjinjing/hack2-contrib | src/Hack2/Contrib/Middleware/NotFound.hs | bsd-3-clause | 354 | 3 | 7 | 56 | 105 | 66 | 39 | 13 | 1 |
-- | Support for providing a Frame-based API on top of an unreliable bytestream.
module Network.LambdaBridge.Frame
( frameProtocol
, maxFrameSize
, crc
) where
import Control.Exception as E
import Data.Word
import Data.Bits
import Control.Concurrent
import Control.Concurrent.MVar
import qualified Data.ByteString as BS
import System.Timeout
import Numeric
import Data.Char
import Data.Default
import Data.Digest.CRC16
import Numeric
import Network.LambdaBridge.Logging (debugM)
import Network.LambdaBridge.Bridge
import System.Random
import Debug.Trace
{-
From http://en.wikipedia.org/wiki/Computation_of_CRC
If the data is destined for serial communication, it is best to use the bit ordering the data
will ultimately be sent in. This is because a CRC's ability to detect burst errors is based on
proximity in the message polynomial M(x); if adjacent polynomial terms are not transmitted
sequentially, a physical error burst of one length may be seen as a longer burst due to the
rearrangement of bits.
For example, both IEEE 802 (ethernet) and RS-232 (serial port) standards specify
least-significant bit first (little-endian) transmission, so a software CRC implementation to
protect data sent across such a link should map the least significant bits in each byte to
coefficients of the highest powers of x. On the other hand, floppy disks and most hard drives
write the most significant bit of each byte first.
We can test things with:
http://www.lammertbies.nl/comm/info/crc-calculation.html
CRC-CCITT (0xFFFF)
-}
-- | Compute the crc for a sequence of bytes.
-- The arguments for 'crc' are the crc code, and the initial value, often -1.
--
-- For example, CRC-16-CCITT, which is used for 'Frame', is crc 0x1021 0xffff.
-- Here we *explictly* use LSB first, which involved requesting that crc16Update
-- reverse the order of bits.
crc :: [Word8] -> Word16
crc = foldl (crc16Update 0x1021 True) 0xffff
-- | The maximum frame payload size, not including CRCs or headers, pre-stuffed.
maxFrameSize :: Int
maxFrameSize = 239
-----------------------------------------------------------------------
-- | 'frameProtocol' provides a Bridge Frame Frame from the services of a 'Bridge Byte'.
-- It is thread safe (two Frame writes to the same bridge will not garble each other)
{- |
It uses the following Frame format:
> <- sync+size -><- payload ... ->|
> +------+------+----------------+------+------+
> | 0xfe | sz | ... DATA .... | CRC-16 |
> +------+------+----------------+------+------+
The '0xfe' is the sync marker starter; then comes the size (0 ...253)
then the CRC-16 for the [0xfe,sz]. This means that
when looking for a header, if a 0xfe is found in the sz position,
this marks a candidate for a new sync marker, and the one being
processed in corrupt.
Furthermore, the data is byte-stuffed
(<http://en.wikipedia.org/wiki/Bit_stuffing>)
for 0xfe, so 0xfe in DATA and the DATA-CRC is represented
using the pair of bytes 0xfe 0xff (which will never occur in a header).
In this way, if a byte is lost, the next header can be found
by scaning for 0xfe N, where N <= 253.
The arguments for 'frameProtocol' is the 'Bridge Byte' we uses to send the byte stream .
-}
frameProtocol :: Bridge Bytes -> IO (Bridge Frame)
frameProtocol bytes_bridge = do
let debug = debugM "lambda-bridge.frame"
let tag = 0xf0 :: Word8
tag_stuffing = 0xff :: Word8
-----------------------------------------------------------------------------
sending <- newEmptyMVar
let write wd = do
debug $ "write 0x" ++ showHex wd ""
toBridge bytes_bridge (Bytes $ BS.pack [wd])
let writeWithCRC xs = do
let crc_val = crc xs
debug $ "crc = " ++ showHex crc_val ""
sequence_ [ do write x
| x <- xs ++ [ reverseBits $ fromIntegral $ crc_val `div` 256
, reverseBits $ fromIntegral $ crc_val `mod` 256
]
]
let stuff x | x == tag = [ tag, tag_stuffing ]
| otherwise = [ x ]
let sender = do
bs <- takeMVar sending
debug $ "sending " ++ show bs
write 0x0 -- to reset the RS232 stop bit alignment
writeWithCRC
[ tag
, fromIntegral $ BS.length bs
]
writeWithCRC (concatMap stuff (BS.unpack bs))
sender
forkIO $ sender
-----------------------------------------------------------------------------
recving <- newEmptyMVar
ch <- newChan
forkIO $ let loop [] = do
Bytes wds <- fromBridge bytes_bridge
loop (BS.unpack wds)
loop (c:cs) = do
debug $ "read 0x" ++ showHex c ""
writeChan ch c
in loop []
let read = readChan ch
let checkCRC xs = crc xs == 0
let findHeader0 :: IO ()
findHeader0 = do
wd0 <- read -- the first byte of a packet can wait as long as you like
if wd0 == tag then findHeader1
else findHeader0
-- found the tag byte; find the length
findHeader1 :: IO ()
findHeader1 = do
wd1 <- read
findHeader2 wd1
-- you already have the two bytes,
-- and the first one was the tag
findHeader2 :: Word8 -> IO ()
findHeader2 wd1
| fromIntegral wd1 <= maxFrameSize
= do debug $ "found header, len = " ++ show wd1
findHeaderCRC0 wd1
| otherwise = do
debug $ "rejected header " ++ show [wd1]
if wd1 == tag then findHeader1
else findHeader0
readWithPadding :: IO Word8
readWithPadding = do
wd1 <- read
if wd1 == tag then
do wd2 <- read
if wd2 == tag_stuffing then return wd1 else do
-- aborting this packet, start new packet
-- print ("aborting packet (bad stuffing)")
debug $ "found non-stuffed tag inside packet"
findHeader2 wd2
fail "trampoline"
else do
return wd1
findHeaderCRC0 :: Word8 -> IO ()
findHeaderCRC0 len = do
crc1 <- read
if crc1 == tag then findHeader1
else findHeaderCRC1 len crc1
findHeaderCRC1 :: Word8 -> Word8 -> IO ()
findHeaderCRC1 len crc1 = do
crc2 <- read
case () of
_ | crc1 == tag -> findHeader1
| checkCRC [tag,len,crc1,crc2] -> do
debug $ "accepted header"
findPayload (fromIntegral len)
| otherwise -> do
debug $ "header crc failed (expecting " ++ show (crc [tag,len]) ++ ")"
findHeader0
findPayload :: Int -> IO ()
findPayload sz = do
-- TODO: consider byte stuffing for 0xf1
xs <- sequence [ readWithPadding
| i <- [1..(sz + 2)]
]
if checkCRC (concatMap stuff xs) then do
let frame = Frame (BS.pack (take sz xs))
debug $ "received packet " ++ show frame
putMVar recving frame
debug $ "forwarded packet"
else do
debug $ "crc failure 0x" ++ showHex (crc $ concatMap stuff xs) ""
return ()
-- print xs
return ()
let readBridge = do
findHeader0 `E.catch` \ SomeException {} -> do
-- print msg
return ()
readBridge
forkIO $ readBridge
return $ Bridge
{ toBridge = \ (Frame bs) ->
if BS.length bs > maxFrameSize
then fail ("packet exceeded max frame size of " ++ show maxFrameSize)
else putMVar sending bs
, fromBridge = takeMVar recving
}
-- Used to find the tag number (0xf0)
find = [ (tag,misses)
| tag <- [1..255]
, let misses = length
[ ()
| len <- [0..(tag - 1)]
, let x = crc [tag,len]
, let hi = reverseBits $ fromIntegral $ x `div` 256
, let low = reverseBits $ fromIntegral $ x `mod` 256
, hi /= tag && low /= tag
]
, misses == fromIntegral tag
]
reverseBits :: Word8 -> Word8
reverseBits x = sum [ 2^(7-i)
| i <- [0..7]
, x `testBit` i
]
-- x^16 + x^12 + x^5 + 1
crcMe :: [Word8] -> Word16
crcMe cs = loop 0xffff cs
where
loop r (c:cs) = loop (loop2 (r `xor` fromIntegral c) c 0) cs
loop r [] = r
loop2 r c 8 = r
loop2 r c i = if r `testBit` i
then loop2 ((r `shiftR` 1) `xor` 0x8408) c (i+1)
else loop2 (r `shiftR` 1) c (i+1)
-- 0x1021
-- 0x8408
{-
function crc(byte array string[1..len], int len) {
rem := 0
// A popular variant complements rem here
for i from 1 to len {
rem := rem xor string[i]
for j from 1 to 8 { // Assuming 8 bits per byte
if rem and 0x0001 { // if rightmost (least significant) bit is set
rem := (rem rightShift 1) xor 0x8408
} else {
rem := rem rightShift 1
}
}
}
// A popular variant complements rem here
return rem
-}
data BOOL = B String Bool
instance Show BOOL where
-- show (B xs True) = xs ++ "<1>"
-- show (B xs False) = xs ++ "<0>"
show (B xs True) = "1"
show (B xs False) = "0"
xOR :: BOOL -> BOOL -> BOOL
xOR (B x x') (B y y') = B (par x ++ "^" ++ par y) (x' /= y')
where par [x] = [x]
par other = "(" ++ other ++ ")"
false = B "0" False
true = B "1" True
str = map (\ x -> if x == '0' then false else true)
-- 0x1021
-- 0x8408
--crc_spec :: [Bool] -> Bool -> [Bool]
-- You need to step this 8 times; after xoring the low bits with the input byte.
crc_spec :: [BOOL] -> [BOOL]
crc_spec bs = [ if x `elem` [12,5,0]
then xOR b (last bs) -- b /= last bs
else b
| (x,b) <- [0..] `zip` (false : init bs)
]
-- test txt n = reverse $ foldl crc_spec (reverse (str txt)) (replicate n false)
--test n t = reverse $ foldl crc_spec (replicate 16 true) (replicate n false ++ [t]) | andygill/lambda-bridge | Network/LambdaBridge/Frame.hs | bsd-3-clause | 10,387 | 129 | 21 | 3,421 | 2,080 | 1,108 | 972 | 169 | 9 |
{-# LANGUAGE BangPatterns, RecordWildCards, NamedFieldPuns,
DeriveGeneric, DeriveDataTypeable, GeneralizedNewtypeDeriving,
ScopedTypeVariables #-}
-- | An experimental new UI for cabal for working with multiple packages
-----------------------------------------------------------------------------
module Distribution.Client.ProjectPlanOutput (
writePlanExternalRepresentation,
) where
import Distribution.Client.ProjectPlanning.Types
import Distribution.Client.DistDirLayout
import Distribution.Client.Types
import qualified Distribution.Client.InstallPlan as InstallPlan
import qualified Distribution.Client.Utils.Json as J
import qualified Distribution.Simple.InstallDirs as InstallDirs
import qualified Distribution.Solver.Types.ComponentDeps as ComponentDeps
import Distribution.Package
import qualified Distribution.PackageDescription as PD
import Distribution.Text
import Distribution.Simple.Utils
import qualified Paths_cabal_install as Our (version)
import Data.Monoid
import qualified Data.ByteString.Builder as BB
import System.FilePath
-- | Write out a representation of the elaborated install plan.
--
-- This is for the benefit of debugging and external tools like editors.
--
writePlanExternalRepresentation :: DistDirLayout
-> ElaboratedInstallPlan
-> ElaboratedSharedConfig
-> IO ()
writePlanExternalRepresentation distDirLayout elaboratedInstallPlan
elaboratedSharedConfig =
writeFileAtomic (distProjectCacheFile distDirLayout "plan.json") $
BB.toLazyByteString
. J.encodeToBuilder
$ encodePlanAsJson distDirLayout elaboratedInstallPlan elaboratedSharedConfig
-- | Renders a subset of the elaborated install plan in a semi-stable JSON
-- format.
--
encodePlanAsJson :: DistDirLayout -> ElaboratedInstallPlan -> ElaboratedSharedConfig -> J.Value
encodePlanAsJson distDirLayout elaboratedInstallPlan elaboratedSharedConfig =
--TODO: [nice to have] include all of the sharedPackageConfig and all of
-- the parts of the elaboratedInstallPlan
J.object [ "cabal-version" J..= jdisplay Our.version
, "cabal-lib-version" J..= jdisplay cabalVersion
, "install-plan" J..= jsonIPlan
]
where
jsonIPlan = map toJ (InstallPlan.toList elaboratedInstallPlan)
-- ipi :: InstalledPackageInfo
toJ (InstallPlan.PreExisting ipi) =
-- installed packages currently lack configuration information
-- such as their flag settings or non-lib components.
--
-- TODO: how to find out whether package is "local"?
J.object
[ "type" J..= J.String "pre-existing"
, "id" J..= jdisplay (installedUnitId ipi)
, "depends" J..= map jdisplay (installedDepends ipi)
]
-- pkg :: ElaboratedPackage
toJ (InstallPlan.Configured elab) =
J.object $
[ "type" J..= J.String "configured"
, "id" J..= (jdisplay . installedUnitId) elab
, "flags" J..= J.object [ fn J..= v
| (PD.FlagName fn,v) <-
elabFlagAssignment elab ]
, "style" J..= J.String (style2str (elabLocalToProject elab) (elabBuildStyle elab))
] ++
(case elabBuildStyle elab of
BuildInplaceOnly ->
["dist-dir" J..= J.String dist_dir]
BuildAndInstall ->
-- TODO: install dirs?
[]
) ++
case elabPkgOrComp elab of
ElabPackage pkg ->
let components = J.object $
[ comp2str c J..= (J.object $
[ "depends" J..= map (jdisplay . confInstId) ldeps
, "exe-depends" J..= map (jdisplay . confInstId) edeps ] ++
bin_file c)
| (c,(ldeps,edeps))
<- ComponentDeps.toList $
ComponentDeps.zip (pkgLibDependencies pkg)
(pkgExeDependencies pkg) ]
in ["components" J..= components]
ElabComponent comp ->
["depends" J..= map (jdisplay . confInstId) (elabLibDependencies elab)
,"exe-depends" J..= map jdisplay (elabExeDependencies elab)
,"component-name" J..= J.String (comp2str (compSolverName comp))
] ++
bin_file (compSolverName comp)
where
dist_dir = distBuildDirectory distDirLayout
(elabDistDirParams elaboratedSharedConfig elab)
bin_file c = case c of
ComponentDeps.ComponentExe s -> bin_file' s
ComponentDeps.ComponentTest s -> bin_file' s
ComponentDeps.ComponentBench s -> bin_file' s
_ -> []
bin_file' s =
["bin-file" J..= J.String bin]
where
bin = if elabBuildStyle elab == BuildInplaceOnly
then dist_dir </> "build" </> s </> s
else InstallDirs.bindir (elabInstallDirs elab) </> s
-- TODO: maybe move this helper to "ComponentDeps" module?
-- Or maybe define a 'Text' instance?
comp2str :: ComponentDeps.Component -> String
comp2str c = case c of
ComponentDeps.ComponentLib -> "lib"
ComponentDeps.ComponentSubLib s -> "lib:" <> s
ComponentDeps.ComponentExe s -> "exe:" <> s
ComponentDeps.ComponentTest s -> "test:" <> s
ComponentDeps.ComponentBench s -> "bench:" <> s
ComponentDeps.ComponentSetup -> "setup"
style2str :: Bool -> BuildStyle -> String
style2str True _ = "local"
style2str False BuildInplaceOnly = "inplace"
style2str False BuildAndInstall = "global"
jdisplay :: Text a => a -> J.Value
jdisplay = J.String . display
| sopvop/cabal | cabal-install/Distribution/Client/ProjectPlanOutput.hs | bsd-3-clause | 5,998 | 1 | 25 | 1,814 | 1,134 | 602 | 532 | 100 | 15 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE CPP #-}
module BuildTyCl (
buildDataCon,
buildPatSyn,
TcMethInfo, buildClass,
mkNewTyConRhs, mkDataTyConRhs,
newImplicitBinder, newTyConRepName
) where
#include "HsVersions.h"
import GhcPrelude
import IfaceEnv
import FamInstEnv( FamInstEnvs, mkNewTypeCoAxiom )
import TysWiredIn( isCTupleTyConName )
import TysPrim ( voidPrimTy )
import DataCon
import PatSyn
import Var
import VarSet
import BasicTypes
import Name
import MkId
import Class
import TyCon
import Type
import Id
import TcType
import SrcLoc( SrcSpan, noSrcSpan )
import DynFlags
import TcRnMonad
import UniqSupply
import Util
import Outputable
mkDataTyConRhs :: [DataCon] -> AlgTyConRhs
mkDataTyConRhs cons
= DataTyCon {
data_cons = cons,
is_enum = not (null cons) && all is_enum_con cons
-- See Note [Enumeration types] in TyCon
}
where
is_enum_con con
| (_univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _res)
<- dataConFullSig con
= null ex_tvs && null eq_spec && null theta && null arg_tys
mkNewTyConRhs :: Name -> TyCon -> DataCon -> TcRnIf m n AlgTyConRhs
-- ^ Monadic because it makes a Name for the coercion TyCon
-- We pass the Name of the parent TyCon, as well as the TyCon itself,
-- because the latter is part of a knot, whereas the former is not.
mkNewTyConRhs tycon_name tycon con
= do { co_tycon_name <- newImplicitBinder tycon_name mkNewTyCoOcc
; let nt_ax = mkNewTypeCoAxiom co_tycon_name tycon etad_tvs etad_roles etad_rhs
; traceIf (text "mkNewTyConRhs" <+> ppr nt_ax)
; return (NewTyCon { data_con = con,
nt_rhs = rhs_ty,
nt_etad_rhs = (etad_tvs, etad_rhs),
nt_co = nt_ax } ) }
-- Coreview looks through newtypes with a Nothing
-- for nt_co, or uses explicit coercions otherwise
where
tvs = tyConTyVars tycon
roles = tyConRoles tycon
con_arg_ty = case dataConRepArgTys con of
[arg_ty] -> arg_ty
tys -> pprPanic "mkNewTyConRhs" (ppr con <+> ppr tys)
rhs_ty = substTyWith (dataConUnivTyVars con)
(mkTyVarTys tvs) con_arg_ty
-- Instantiate the newtype's RHS with the
-- type variables from the tycon
-- NB: a newtype DataCon has a type that must look like
-- forall tvs. <arg-ty> -> T tvs
-- Note that we *can't* use dataConInstOrigArgTys here because
-- the newtype arising from class Foo a => Bar a where {}
-- has a single argument (Foo a) that is a *type class*, so
-- dataConInstOrigArgTys returns [].
etad_tvs :: [TyVar] -- Matched lazily, so that mkNewTypeCo can
etad_roles :: [Role] -- return a TyCon without pulling on rhs_ty
etad_rhs :: Type -- See Note [Tricky iface loop] in LoadIface
(etad_tvs, etad_roles, etad_rhs) = eta_reduce (reverse tvs) (reverse roles) rhs_ty
eta_reduce :: [TyVar] -- Reversed
-> [Role] -- also reversed
-> Type -- Rhs type
-> ([TyVar], [Role], Type) -- Eta-reduced version
-- (tyvars in normal order)
eta_reduce (a:as) (_:rs) ty | Just (fun, arg) <- splitAppTy_maybe ty,
Just tv <- getTyVar_maybe arg,
tv == a,
not (a `elemVarSet` tyCoVarsOfType fun)
= eta_reduce as rs fun
eta_reduce tvs rs ty = (reverse tvs, reverse rs, ty)
------------------------------------------------------
buildDataCon :: FamInstEnvs
-> Name
-> Bool -- Declared infix
-> TyConRepName
-> [HsSrcBang]
-> Maybe [HsImplBang]
-- See Note [Bangs on imported data constructors] in MkId
-> [FieldLabel] -- Field labels
-> [TyVar] -- Universals
-> [TyVar] -- Existentials
-> [TyVarBinder] -- User-written 'TyVarBinder's
-> [EqSpec] -- Equality spec
-> ThetaType -- Does not include the "stupid theta"
-- or the GADT equalities
-> [Type] -> Type -- Argument and result types
-> TyCon -- Rep tycon
-> TcRnIf m n DataCon
-- A wrapper for DataCon.mkDataCon that
-- a) makes the worker Id
-- b) makes the wrapper Id if necessary, including
-- allocating its unique (hence monadic)
buildDataCon fam_envs src_name declared_infix prom_info src_bangs impl_bangs field_lbls
univ_tvs ex_tvs user_tvbs eq_spec ctxt arg_tys res_ty rep_tycon
= do { wrap_name <- newImplicitBinder src_name mkDataConWrapperOcc
; work_name <- newImplicitBinder src_name mkDataConWorkerOcc
-- This last one takes the name of the data constructor in the source
-- code, which (for Haskell source anyway) will be in the DataName name
-- space, and puts it into the VarName name space
; traceIf (text "buildDataCon 1" <+> ppr src_name)
; us <- newUniqueSupply
; dflags <- getDynFlags
; let stupid_ctxt = mkDataConStupidTheta rep_tycon arg_tys univ_tvs
data_con = mkDataCon src_name declared_infix prom_info
src_bangs field_lbls
univ_tvs ex_tvs user_tvbs eq_spec ctxt
arg_tys res_ty NoRRI rep_tycon
stupid_ctxt dc_wrk dc_rep
dc_wrk = mkDataConWorkId work_name data_con
dc_rep = initUs_ us (mkDataConRep dflags fam_envs wrap_name
impl_bangs data_con)
; traceIf (text "buildDataCon 2" <+> ppr src_name)
; return data_con }
-- The stupid context for a data constructor should be limited to
-- the type variables mentioned in the arg_tys
-- ToDo: Or functionally dependent on?
-- This whole stupid theta thing is, well, stupid.
mkDataConStupidTheta :: TyCon -> [Type] -> [TyVar] -> [PredType]
mkDataConStupidTheta tycon arg_tys univ_tvs
| null stupid_theta = [] -- The common case
| otherwise = filter in_arg_tys stupid_theta
where
tc_subst = zipTvSubst (tyConTyVars tycon)
(mkTyVarTys univ_tvs)
stupid_theta = substTheta tc_subst (tyConStupidTheta tycon)
-- Start by instantiating the master copy of the
-- stupid theta, taken from the TyCon
arg_tyvars = tyCoVarsOfTypes arg_tys
in_arg_tys pred = not $ isEmptyVarSet $
tyCoVarsOfType pred `intersectVarSet` arg_tyvars
------------------------------------------------------
buildPatSyn :: Name -> Bool
-> (Id,Bool) -> Maybe (Id, Bool)
-> ([TyVarBinder], ThetaType) -- ^ Univ and req
-> ([TyVarBinder], ThetaType) -- ^ Ex and prov
-> [Type] -- ^ Argument types
-> Type -- ^ Result type
-> [FieldLabel] -- ^ Field labels for
-- a record pattern synonym
-> PatSyn
buildPatSyn src_name declared_infix matcher@(matcher_id,_) builder
(univ_tvs, req_theta) (ex_tvs, prov_theta) arg_tys
pat_ty field_labels
= -- The assertion checks that the matcher is
-- compatible with the pattern synonym
ASSERT2((and [ univ_tvs `equalLength` univ_tvs1
, ex_tvs `equalLength` ex_tvs1
, pat_ty `eqType` substTy subst pat_ty1
, prov_theta `eqTypes` substTys subst prov_theta1
, req_theta `eqTypes` substTys subst req_theta1
, compareArgTys arg_tys (substTys subst arg_tys1)
])
, (vcat [ ppr univ_tvs <+> twiddle <+> ppr univ_tvs1
, ppr ex_tvs <+> twiddle <+> ppr ex_tvs1
, ppr pat_ty <+> twiddle <+> ppr pat_ty1
, ppr prov_theta <+> twiddle <+> ppr prov_theta1
, ppr req_theta <+> twiddle <+> ppr req_theta1
, ppr arg_tys <+> twiddle <+> ppr arg_tys1]))
mkPatSyn src_name declared_infix
(univ_tvs, req_theta) (ex_tvs, prov_theta)
arg_tys pat_ty
matcher builder field_labels
where
((_:_:univ_tvs1), req_theta1, tau) = tcSplitSigmaTy $ idType matcher_id
([pat_ty1, cont_sigma, _], _) = tcSplitFunTys tau
(ex_tvs1, prov_theta1, cont_tau) = tcSplitSigmaTy cont_sigma
(arg_tys1, _) = (tcSplitFunTys cont_tau)
twiddle = char '~'
subst = zipTvSubst (univ_tvs1 ++ ex_tvs1)
(mkTyVarTys (binderVars (univ_tvs ++ ex_tvs)))
-- For a nullary pattern synonym we add a single void argument to the
-- matcher to preserve laziness in the case of unlifted types.
-- See #12746
compareArgTys :: [Type] -> [Type] -> Bool
compareArgTys [] [x] = x `eqType` voidPrimTy
compareArgTys arg_tys matcher_arg_tys = arg_tys `eqTypes` matcher_arg_tys
------------------------------------------------------
type TcMethInfo -- A temporary intermediate, to communicate
-- between tcClassSigs and buildClass.
= ( Name -- Name of the class op
, Type -- Type of the class op
, Maybe (DefMethSpec (SrcSpan, Type)))
-- Nothing => no default method
--
-- Just VanillaDM => There is an ordinary
-- polymorphic default method
--
-- Just (GenericDM (loc, ty)) => There is a generic default metho
-- Here is its type, and the location
-- of the type signature
-- We need that location /only/ to attach it to the
-- generic default method's Name; and we need /that/
-- only to give the right location of an ambiguity error
-- for the generic default method, spat out by checkValidClass
buildClass :: Name -- Name of the class/tycon (they have the same Name)
-> [TyConBinder] -- Of the tycon
-> [Role]
-> [FunDep TyVar] -- Functional dependencies
-- Super classes, associated types, method info, minimal complete def.
-- This is Nothing if the class is abstract.
-> Maybe (ThetaType, [ClassATItem], [TcMethInfo], ClassMinimalDef)
-> TcRnIf m n Class
buildClass tycon_name binders roles fds Nothing
= fixM $ \ rec_clas -> -- Only name generation inside loop
do { traceIf (text "buildClass")
; tc_rep_name <- newTyConRepName tycon_name
; let univ_bndrs = tyConTyVarBinders binders
univ_tvs = binderVars univ_bndrs
tycon = mkClassTyCon tycon_name binders roles
AbstractTyCon rec_clas tc_rep_name
result = mkAbstractClass tycon_name univ_tvs fds tycon
; traceIf (text "buildClass" <+> ppr tycon)
; return result }
buildClass tycon_name binders roles fds
(Just (sc_theta, at_items, sig_stuff, mindef))
= fixM $ \ rec_clas -> -- Only name generation inside loop
do { traceIf (text "buildClass")
; datacon_name <- newImplicitBinder tycon_name mkClassDataConOcc
; tc_rep_name <- newTyConRepName tycon_name
; op_items <- mapM (mk_op_item rec_clas) sig_stuff
-- Build the selector id and default method id
-- Make selectors for the superclasses
; sc_sel_names <- mapM (newImplicitBinder tycon_name . mkSuperDictSelOcc)
(takeList sc_theta [fIRST_TAG..])
; let sc_sel_ids = [ mkDictSelId sc_name rec_clas
| sc_name <- sc_sel_names]
-- We number off the Dict superclass selectors, 1, 2, 3 etc so that we
-- can construct names for the selectors. Thus
-- class (C a, C b) => D a b where ...
-- gives superclass selectors
-- D_sc1, D_sc2
-- (We used to call them D_C, but now we can have two different
-- superclasses both called C!)
; let use_newtype = isSingleton arg_tys
-- Use a newtype if the data constructor
-- (a) has exactly one value field
-- i.e. exactly one operation or superclass taken together
-- (b) that value is of lifted type (which they always are, because
-- we box equality superclasses)
-- See note [Class newtypes and equality predicates]
-- We treat the dictionary superclasses as ordinary arguments.
-- That means that in the case of
-- class C a => D a
-- we don't get a newtype with no arguments!
args = sc_sel_names ++ op_names
op_tys = [ty | (_,ty,_) <- sig_stuff]
op_names = [op | (op,_,_) <- sig_stuff]
arg_tys = sc_theta ++ op_tys
rec_tycon = classTyCon rec_clas
univ_bndrs = tyConTyVarBinders binders
univ_tvs = binderVars univ_bndrs
; rep_nm <- newTyConRepName datacon_name
; dict_con <- buildDataCon (panic "buildClass: FamInstEnvs")
datacon_name
False -- Not declared infix
rep_nm
(map (const no_bang) args)
(Just (map (const HsLazy) args))
[{- No fields -}]
univ_tvs
[{- no existentials -}]
univ_bndrs
[{- No GADT equalities -}]
[{- No theta -}]
arg_tys
(mkTyConApp rec_tycon (mkTyVarTys univ_tvs))
rec_tycon
; rhs <- case () of
_ | use_newtype
-> mkNewTyConRhs tycon_name rec_tycon dict_con
| isCTupleTyConName tycon_name
-> return (TupleTyCon { data_con = dict_con
, tup_sort = ConstraintTuple })
| otherwise
-> return (mkDataTyConRhs [dict_con])
; let { tycon = mkClassTyCon tycon_name binders roles
rhs rec_clas tc_rep_name
-- A class can be recursive, and in the case of newtypes
-- this matters. For example
-- class C a where { op :: C b => a -> b -> Int }
-- Because C has only one operation, it is represented by
-- a newtype, and it should be a *recursive* newtype.
-- [If we don't make it a recursive newtype, we'll expand the
-- newtype like a synonym, but that will lead to an infinite
-- type]
; result = mkClass tycon_name univ_tvs fds
sc_theta sc_sel_ids at_items
op_items mindef tycon
}
; traceIf (text "buildClass" <+> ppr tycon)
; return result }
where
no_bang = HsSrcBang NoSourceText NoSrcUnpack NoSrcStrict
mk_op_item :: Class -> TcMethInfo -> TcRnIf n m ClassOpItem
mk_op_item rec_clas (op_name, _, dm_spec)
= do { dm_info <- mk_dm_info op_name dm_spec
; return (mkDictSelId op_name rec_clas, dm_info) }
mk_dm_info :: Name -> Maybe (DefMethSpec (SrcSpan, Type))
-> TcRnIf n m (Maybe (Name, DefMethSpec Type))
mk_dm_info _ Nothing
= return Nothing
mk_dm_info op_name (Just VanillaDM)
= do { dm_name <- newImplicitBinder op_name mkDefaultMethodOcc
; return (Just (dm_name, VanillaDM)) }
mk_dm_info op_name (Just (GenericDM (loc, dm_ty)))
= do { dm_name <- newImplicitBinderLoc op_name mkDefaultMethodOcc loc
; return (Just (dm_name, GenericDM dm_ty)) }
{-
Note [Class newtypes and equality predicates]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
class (a ~ F b) => C a b where
op :: a -> b
We cannot represent this by a newtype, even though it's not
existential, because there are two value fields (the equality
predicate and op. See Trac #2238
Moreover,
class (a ~ F b) => C a b where {}
Here we can't use a newtype either, even though there is only
one field, because equality predicates are unboxed, and classes
are boxed.
-}
newImplicitBinder :: Name -- Base name
-> (OccName -> OccName) -- Occurrence name modifier
-> TcRnIf m n Name -- Implicit name
-- Called in BuildTyCl to allocate the implicit binders of type/class decls
-- For source type/class decls, this is the first occurrence
-- For iface ones, the LoadIface has already allocated a suitable name in the cache
newImplicitBinder base_name mk_sys_occ
= newImplicitBinderLoc base_name mk_sys_occ (nameSrcSpan base_name)
newImplicitBinderLoc :: Name -- Base name
-> (OccName -> OccName) -- Occurrence name modifier
-> SrcSpan
-> TcRnIf m n Name -- Implicit name
-- Just the same, but lets you specify the SrcSpan
newImplicitBinderLoc base_name mk_sys_occ loc
| Just mod <- nameModule_maybe base_name
= newGlobalBinder mod occ loc
| otherwise -- When typechecking a [d| decl bracket |],
-- TH generates types, classes etc with Internal names,
-- so we follow suit for the implicit binders
= do { uniq <- newUnique
; return (mkInternalName uniq occ loc) }
where
occ = mk_sys_occ (nameOccName base_name)
-- | Make the 'TyConRepName' for this 'TyCon'
newTyConRepName :: Name -> TcRnIf gbl lcl TyConRepName
newTyConRepName tc_name
| Just mod <- nameModule_maybe tc_name
, (mod, occ) <- tyConRepModOcc mod (nameOccName tc_name)
= newGlobalBinder mod occ noSrcSpan
| otherwise
= newImplicitBinder tc_name mkTyConRepOcc
| ezyang/ghc | compiler/iface/BuildTyCl.hs | bsd-3-clause | 18,946 | 0 | 20 | 6,801 | 3,096 | 1,678 | 1,418 | 259 | 3 |
{-# LANGUAGE CPP #-}
module TcCanonical(
canonicalize,
unifyDerived,
makeSuperClasses, mkGivensWithSuperClasses,
StopOrContinue(..), stopWith, continueWith
) where
#include "HsVersions.h"
import TcRnTypes
import TcType
import Type
import TcFlatten
import TcSMonad
import TcEvidence
import Class
import TyCon
import TyCoRep -- cleverly decomposes types, good for completeness checking
import Coercion
import FamInstEnv ( FamInstEnvs )
import FamInst ( tcTopNormaliseNewTypeTF_maybe )
import Var
import Name( isSystemName )
import OccName( OccName )
import Outputable
import DynFlags( DynFlags )
import VarSet
import NameSet
import RdrName
import Pair
import Util
import Bag
import MonadUtils
import Control.Monad
import Data.List ( zip4, foldl' )
import BasicTypes
import Data.Bifunctor ( bimap )
{-
************************************************************************
* *
* The Canonicaliser *
* *
************************************************************************
Note [Canonicalization]
~~~~~~~~~~~~~~~~~~~~~~~
Canonicalization converts a simple constraint to a canonical form. It is
unary (i.e. treats individual constraints one at a time), does not do
any zonking, but lives in TcS monad because it needs to create fresh
variables (for flattening) and consult the inerts (for efficiency).
The execution plan for canonicalization is the following:
1) Decomposition of equalities happens as necessary until we reach a
variable or type family in one side. There is no decomposition step
for other forms of constraints.
2) If, when we decompose, we discover a variable on the head then we
look at inert_eqs from the current inert for a substitution for this
variable and contine decomposing. Hence we lazily apply the inert
substitution if it is needed.
3) If no more decomposition is possible, we deeply apply the substitution
from the inert_eqs and continue with flattening.
4) During flattening, we examine whether we have already flattened some
function application by looking at all the CTyFunEqs with the same
function in the inert set. The reason for deeply applying the inert
substitution at step (3) is to maximise our chances of matching an
already flattened family application in the inert.
The net result is that a constraint coming out of the canonicalization
phase cannot be rewritten any further from the inerts (but maybe /it/ can
rewrite an inert or still interact with an inert in a further phase in the
simplifier.
Note [Caching for canonicals]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Our plan with pre-canonicalization is to be able to solve a constraint
really fast from existing bindings in TcEvBinds. So one may think that
the condition (isCNonCanonical) is not necessary. However consider
the following setup:
InertSet = { [W] d1 : Num t }
WorkList = { [W] d2 : Num t, [W] c : t ~ Int}
Now, we prioritize equalities, but in our concrete example
(should_run/mc17.hs) the first (d2) constraint is dealt with first,
because (t ~ Int) is an equality that only later appears in the
worklist since it is pulled out from a nested implication
constraint. So, let's examine what happens:
- We encounter work item (d2 : Num t)
- Nothing is yet in EvBinds, so we reach the interaction with inerts
and set:
d2 := d1
and we discard d2 from the worklist. The inert set remains unaffected.
- Now the equation ([W] c : t ~ Int) is encountered and kicks-out
(d1 : Num t) from the inerts. Then that equation gets
spontaneously solved, perhaps. We end up with:
InertSet : { [G] c : t ~ Int }
WorkList : { [W] d1 : Num t}
- Now we examine (d1), we observe that there is a binding for (Num
t) in the evidence binds and we set:
d1 := d2
and end up in a loop!
Now, the constraints that get kicked out from the inert set are always
Canonical, so by restricting the use of the pre-canonicalizer to
NonCanonical constraints we eliminate this danger. Moreover, for
canonical constraints we already have good caching mechanisms
(effectively the interaction solver) and we are interested in reducing
things like superclasses of the same non-canonical constraint being
generated hence I don't expect us to lose a lot by introducing the
(isCNonCanonical) restriction.
A similar situation can arise in TcSimplify, at the end of the
solve_wanteds function, where constraints from the inert set are
returned as new work -- our substCt ensures however that if they are
not rewritten by subst, they remain canonical and hence we will not
attempt to solve them from the EvBinds. If on the other hand they did
get rewritten and are now non-canonical they will still not match the
EvBinds, so we are again good.
-}
-- Top-level canonicalization
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
canonicalize :: Ct -> TcS (StopOrContinue Ct)
canonicalize ct@(CNonCanonical { cc_ev = ev })
= do { traceTcS "canonicalize (non-canonical)" (ppr ct)
; {-# SCC "canEvVar" #-}
canEvNC ev }
canonicalize (CDictCan { cc_ev = ev, cc_class = cls
, cc_tyargs = xis, cc_pend_sc = pend_sc })
= {-# SCC "canClass" #-}
canClass ev cls xis pend_sc
canonicalize (CTyEqCan { cc_ev = ev
, cc_tyvar = tv
, cc_rhs = xi
, cc_eq_rel = eq_rel })
= {-# SCC "canEqLeafTyVarEq" #-}
canEqNC ev eq_rel (mkTyVarTy tv) xi
-- NB: Don't use canEqTyVar because that expects flattened types,
-- and tv and xi may not be flat w.r.t. an updated inert set
canonicalize (CFunEqCan { cc_ev = ev
, cc_fun = fn
, cc_tyargs = xis1
, cc_fsk = fsk })
= {-# SCC "canEqLeafFunEq" #-}
canCFunEqCan ev fn xis1 fsk
canonicalize (CIrredEvCan { cc_ev = ev })
= canIrred ev
canonicalize (CHoleCan { cc_ev = ev, cc_occ = occ, cc_hole = hole })
= canHole ev occ hole
canEvNC :: CtEvidence -> TcS (StopOrContinue Ct)
-- Called only for non-canonical EvVars
canEvNC ev
= case classifyPredType (ctEvPred ev) of
ClassPred cls tys -> do traceTcS "canEvNC:cls" (ppr cls <+> ppr tys)
canClassNC ev cls tys
EqPred eq_rel ty1 ty2 -> do traceTcS "canEvNC:eq" (ppr ty1 $$ ppr ty2)
canEqNC ev eq_rel ty1 ty2
IrredPred {} -> do traceTcS "canEvNC:irred" (ppr (ctEvPred ev))
canIrred ev
{-
************************************************************************
* *
* Class Canonicalization
* *
************************************************************************
-}
canClassNC :: CtEvidence -> Class -> [Type] -> TcS (StopOrContinue Ct)
-- Precondition: EvVar is class evidence
canClassNC ev cls tys = canClass ev cls tys (has_scs cls)
where
has_scs cls = not (null (classSCTheta cls))
canClass :: CtEvidence -> Class -> [Type] -> Bool -> TcS (StopOrContinue Ct)
-- Precondition: EvVar is class evidence
canClass ev cls tys pend_sc
= -- all classes do *nominal* matching
ASSERT2( ctEvRole ev == Nominal, ppr ev $$ ppr cls $$ ppr tys )
do { (xis, cos) <- flattenManyNom ev tys
; let co = mkTcTyConAppCo Nominal (classTyCon cls) cos
xi = mkClassPred cls xis
mk_ct new_ev = CDictCan { cc_ev = new_ev
, cc_tyargs = xis
, cc_class = cls
, cc_pend_sc = pend_sc }
; mb <- rewriteEvidence ev xi co
; traceTcS "canClass" (vcat [ ppr ev
, ppr xi, ppr mb ])
; return (fmap mk_ct mb) }
{- Note [The superclass story]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to add superclass constraints for two reasons:
* For givens, they give us a route to to proof. E.g.
f :: Ord a => a -> Bool
f x = x == x
We get a Wanted (Eq a), which can only be solved from the superclass
of the Given (Ord a).
* For wanteds, they may give useful functional dependencies. E.g.
class C a b | a -> b where ...
class C a b => D a b where ...
Now a Wanted constraint (D Int beta) has (C Int beta) as a superclass
and that might tell us about beta, via C's fundeps. We can get this
by generateing a Derived (C Int beta) constraint. It's derived because
we don't actually have to cough up any evidence for it; it's only there
to generate fundep equalities.
See Note [Why adding superclasses can help].
For these reasons we want to generate superclass constraints for both
Givens and Wanteds. But:
* (Minor) they are often not needed, so generating them aggressively
is a waste of time.
* (Major) if we want recursive superclasses, there would be an infinite
number of them. Here is a real-life example (Trac #10318);
class (Frac (Frac a) ~ Frac a,
Fractional (Frac a),
IntegralDomain (Frac a))
=> IntegralDomain a where
type Frac a :: *
Notice that IntegralDomain has an associated type Frac, and one
of IntegralDomain's superclasses is another IntegralDomain constraint.
So here's the plan:
1. Generate superclasses for given (but not wanted) constraints;
see Note [Aggressively expand given superclasses]. However
stop if you encounter the same class twice. That is, expand
eagerly, but have a conservative termination condition: see
Note [Expanding superclasses] in TcType.
2. Solve the wanteds as usual, but do /no/ expansion of superclasses
in solveSimpleGivens or solveSimpleWanteds.
See Note [Danger of adding superclasses during solving]
3. If we have any remaining unsolved wanteds
(see Note [When superclasses help] in TcRnTypes)
try harder: take both the Givens and Wanteds, and expand
superclasses again. This may succeed in generating (a finite
number of) extra Givens, and extra Deriveds. Both may help the
proof. This is done in TcSimplify.expandSuperClasses.
4. Go round to (2) again. This loop (2,3,4) is implemented
in TcSimplify.simpl_loop.
We try to terminate the loop by flagging which class constraints
(given or wanted) are potentially un-expanded. This is what the
cc_pend_sc flag is for in CDictCan. So in Step 3 we only expand
superclasses for constraints with cc_pend_sc set to true (i.e.
isPendingScDict holds).
When we take a CNonCanonical or CIrredCan, but end up classifying it
as a CDictCan, we set the cc_pend_sc flag to False.
Note [Aggressively expand given superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In step (1) of Note [The superclass story], why do we aggressively
expand Given superclasses by one layer? Mainly because of some very
obscure cases like this:
instance Bad a => Eq (T a)
f :: (Ord (T a)) => blah
f x = ....needs Eq (T a), Ord (T a)....
Here if we can't satisfy (Eq (T a)) from the givens we'll use the
instance declaration; but then we are stuck with (Bad a). Sigh.
This is really a case of non-confluent proofs, but to stop our users
complaining we expand one layer in advance.
Note [Why adding superclasses can help]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Examples of how adding superclasses can help:
--- Example 1
class C a b | a -> b
Suppose we want to solve
[G] C a b
[W] C a beta
Then adding [D] beta~b will let us solve it.
-- Example 2 (similar but using a type-equality superclass)
class (F a ~ b) => C a b
And try to sllve:
[G] C a b
[W] C a beta
Follow the superclass rules to add
[G] F a ~ b
[D] F a ~ beta
Now we we get [D] beta ~ b, and can solve that.
-- Example (tcfail138)
class L a b | a -> b
class (G a, L a b) => C a b
instance C a b' => G (Maybe a)
instance C a b => C (Maybe a) a
instance L (Maybe a) a
When solving the superclasses of the (C (Maybe a) a) instance, we get
[G] C a b, and hance by superclasses, [G] G a, [G] L a b
[W] G (Maybe a)
Use the instance decl to get
[W] C a beta
Generate its derived superclass
[D] L a beta. Now using fundeps, combine with [G] L a b to get
[D] beta ~ b
which is what we want.
Note [Danger of adding superclasses during solving]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here's a serious, but now out-dated example, from Trac #4497:
class Num (RealOf t) => Normed t
type family RealOf x
Assume the generated wanted constraint is:
[W] RealOf e ~ e
[W] Normed e
If we were to be adding the superclasses during simplification we'd get:
[W] RealOf e ~ e
[W] Normed e
[D] RealOf e ~ fuv
[D] Num fuv
==>
e := fuv, Num fuv, Normed fuv, RealOf fuv ~ fuv
While looks exactly like our original constraint. If we add the
superclass of (Normed fuv) again we'd loop. By adding superclasses
definitely only once, during canonicalisation, this situation can't
happen.
Mind you, now that Wanteds cannot rewrite Derived, I think this particular
situation can't happen.
-}
mkGivensWithSuperClasses :: CtLoc -> [EvId] -> TcS [Ct]
-- From a given EvId, make its Ct, plus the Ct's of its superclasses
-- See Note [The superclass story]
-- The loop-breaking here follows Note [Expanding superclasses] in TcType
--
-- Example: class D a => C a
-- class C [a] => D a
-- makeGivensWithSuperClasses (C x) will return (C x, D x, C[x])
-- i.e. up to and including the first repetition of C
mkGivensWithSuperClasses loc ev_ids = concatMapM go ev_ids
where
go ev_id = mk_superclasses emptyNameSet this_ev
where
this_ev = CtGiven { ctev_evar = ev_id
, ctev_pred = evVarPred ev_id
, ctev_loc = loc }
makeSuperClasses :: [Ct] -> TcS [Ct]
-- Returns strict superclasses, transitively, see Note [The superclasses story]
-- See Note [The superclass story]
-- The loop-breaking here follows Note [Expanding superclasses] in TcType
-- Specifically, for an incoming (C t) constraint, we return all of (C t)'s
-- superclasses, up to /and including/ the first repetition of C
--
-- Example: class D a => C a
-- class C [a] => D a
-- makeSuperClasses (C x) will return (D x, C [x])
--
-- NB: the incoming constraints have had their cc_pend_sc flag already
-- flipped to False, by isPendingScDict, so we are /obliged/ to at
-- least produce the immediate superclasses
makeSuperClasses cts = concatMapM go cts
where
go (CDictCan { cc_ev = ev, cc_class = cls, cc_tyargs = tys })
= mk_strict_superclasses (unitNameSet (className cls)) ev cls tys
go ct = pprPanic "makeSuperClasses" (ppr ct)
mk_superclasses :: NameSet -> CtEvidence -> TcS [Ct]
-- Return this constraint, plus its superclasses, if any
mk_superclasses rec_clss ev
| ClassPred cls tys <- classifyPredType (ctEvPred ev)
= mk_superclasses_of rec_clss ev cls tys
| otherwise -- Superclass is not a class predicate
= return [mkNonCanonical ev]
mk_superclasses_of :: NameSet -> CtEvidence -> Class -> [Type] -> TcS [Ct]
-- Always return this class constraint,
-- and expand its superclasses
mk_superclasses_of rec_clss ev cls tys
| loop_found = return [this_ct] -- cc_pend_sc of this_ct = True
| otherwise = do { sc_cts <- mk_strict_superclasses rec_clss' ev cls tys
; return (this_ct : sc_cts) }
-- cc_pend_sc of this_ct = False
where
cls_nm = className cls
loop_found = cls_nm `elemNameSet` rec_clss
rec_clss' | isCTupleClass cls = rec_clss -- Never contribute to recursion
| otherwise = rec_clss `extendNameSet` cls_nm
this_ct = CDictCan { cc_ev = ev, cc_class = cls, cc_tyargs = tys
, cc_pend_sc = loop_found }
-- NB: If there is a loop, we cut off, so we have not
-- added the superclasses, hence cc_pend_sc = True
mk_strict_superclasses :: NameSet -> CtEvidence -> Class -> [Type] -> TcS [Ct]
-- Always return the immediate superclasses of (cls tys);
-- and expand their superclasses, provided none of them are in rec_clss
-- nor are repeated
mk_strict_superclasses rec_clss ev cls tys
| CtGiven { ctev_evar = evar, ctev_loc = loc } <- ev
= do { sc_evs <- newGivenEvVars (mk_given_loc loc)
(mkEvScSelectors (EvId evar) cls tys)
; concatMapM (mk_superclasses rec_clss) sc_evs }
| isEmptyVarSet (tyCoVarsOfTypes tys)
= return [] -- Wanteds with no variables yield no deriveds.
-- See Note [Improvement from Ground Wanteds]
| otherwise -- Wanted/Derived case, just add those SC that can lead to improvement.
= do { let loc = ctEvLoc ev
; sc_evs <- mapM (newDerivedNC loc) (immSuperClasses cls tys)
; concatMapM (mk_superclasses rec_clss) sc_evs }
where
size = sizeTypes tys
mk_given_loc loc
| isCTupleClass cls
= loc -- For tuple predicates, just take them apart, without
-- adding their (large) size into the chain. When we
-- get down to a base predicate, we'll include its size.
-- Trac #10335
| GivenOrigin skol_info <- ctLocOrigin loc
-- See Note [Solving superclass constraints] in TcInstDcls
-- for explantation of this transformation for givens
= case skol_info of
InstSkol -> loc { ctl_origin = GivenOrigin (InstSC size) }
InstSC n -> loc { ctl_origin = GivenOrigin (InstSC (n `max` size)) }
_ -> loc
| otherwise -- Probably doesn't happen, since this function
= loc -- is only used for Givens, but does no harm
{-
************************************************************************
* *
* Irreducibles canonicalization
* *
************************************************************************
-}
canIrred :: CtEvidence -> TcS (StopOrContinue Ct)
-- Precondition: ty not a tuple and no other evidence form
canIrred old_ev
= do { let old_ty = ctEvPred old_ev
; traceTcS "can_pred" (text "IrredPred = " <+> ppr old_ty)
; (xi,co) <- flatten FM_FlattenAll old_ev old_ty -- co :: xi ~ old_ty
; rewriteEvidence old_ev xi co `andWhenContinue` \ new_ev ->
do { -- Re-classify, in case flattening has improved its shape
; case classifyPredType (ctEvPred new_ev) of
ClassPred cls tys -> canClassNC new_ev cls tys
EqPred eq_rel ty1 ty2 -> canEqNC new_ev eq_rel ty1 ty2
_ -> continueWith $
CIrredEvCan { cc_ev = new_ev } } }
canHole :: CtEvidence -> OccName -> HoleSort -> TcS (StopOrContinue Ct)
canHole ev occ hole_sort
= do { let ty = ctEvPred ev
; (xi,co) <- flatten FM_SubstOnly ev ty -- co :: xi ~ ty
; rewriteEvidence ev xi co `andWhenContinue` \ new_ev ->
do { emitInsoluble (CHoleCan { cc_ev = new_ev
, cc_occ = occ
, cc_hole = hole_sort })
; stopWith new_ev "Emit insoluble hole" } }
{-
************************************************************************
* *
* Equalities
* *
************************************************************************
Note [Canonicalising equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In order to canonicalise an equality, we look at the structure of the
two types at hand, looking for similarities. A difficulty is that the
types may look dissimilar before flattening but similar after flattening.
However, we don't just want to jump in and flatten right away, because
this might be wasted effort. So, after looking for similarities and failing,
we flatten and then try again. Of course, we don't want to loop, so we
track whether or not we've already flattened.
It is conceivable to do a better job at tracking whether or not a type
is flattened, but this is left as future work. (Mar '15)
-}
canEqNC :: CtEvidence -> EqRel -> Type -> Type -> TcS (StopOrContinue Ct)
canEqNC ev eq_rel ty1 ty2
= do { result <- zonk_eq_types ty1 ty2
; case result of
Left (Pair ty1' ty2') -> can_eq_nc False ev eq_rel ty1' ty1 ty2' ty2
Right ty -> canEqReflexive ev eq_rel ty }
can_eq_nc
:: Bool -- True => both types are flat
-> CtEvidence
-> EqRel
-> Type -> Type -- LHS, after and before type-synonym expansion, resp
-> Type -> Type -- RHS, after and before type-synonym expansion, resp
-> TcS (StopOrContinue Ct)
can_eq_nc flat ev eq_rel ty1 ps_ty1 ty2 ps_ty2
= do { traceTcS "can_eq_nc" $
vcat [ ppr ev, ppr eq_rel, ppr ty1, ppr ps_ty1, ppr ty2, ppr ps_ty2 ]
; rdr_env <- getGlobalRdrEnvTcS
; fam_insts <- getFamInstEnvs
; can_eq_nc' flat rdr_env fam_insts ev eq_rel ty1 ps_ty1 ty2 ps_ty2 }
can_eq_nc'
:: Bool -- True => both input types are flattened
-> GlobalRdrEnv -- needed to see which newtypes are in scope
-> FamInstEnvs -- needed to unwrap data instances
-> CtEvidence
-> EqRel
-> Type -> Type -- LHS, after and before type-synonym expansion, resp
-> Type -> Type -- RHS, after and before type-synonym expansion, resp
-> TcS (StopOrContinue Ct)
-- Expand synonyms first; see Note [Type synonyms and canonicalization]
can_eq_nc' flat _rdr_env _envs ev eq_rel ty1 ps_ty1 ty2 ps_ty2
| Just ty1' <- coreView ty1 = can_eq_nc flat ev eq_rel ty1' ps_ty1 ty2 ps_ty2
| Just ty2' <- coreView ty2 = can_eq_nc flat ev eq_rel ty1 ps_ty1 ty2' ps_ty2
-- need to check for reflexivity in the ReprEq case.
-- See Note [Eager reflexivity check]
-- Check only when flat because the zonk_eq_types check in canEqNC takes
-- care of the non-flat case.
can_eq_nc' True _rdr_env _envs ev ReprEq ty1 _ ty2 _
| ty1 `eqType` ty2
= canEqReflexive ev ReprEq ty1
-- When working with ReprEq, unwrap newtypes.
can_eq_nc' _flat rdr_env envs ev ReprEq ty1 _ ty2 ps_ty2
| Just (co, ty1') <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty1
= can_eq_newtype_nc rdr_env ev NotSwapped co ty1 ty1' ty2 ps_ty2
can_eq_nc' _flat rdr_env envs ev ReprEq ty1 ps_ty1 ty2 _
| Just (co, ty2') <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty2
= can_eq_newtype_nc rdr_env ev IsSwapped co ty2 ty2' ty1 ps_ty1
-- Then, get rid of casts
can_eq_nc' flat _rdr_env _envs ev eq_rel (CastTy ty1 co1) _ ty2 ps_ty2
= canEqCast flat ev eq_rel NotSwapped ty1 co1 ty2 ps_ty2
can_eq_nc' flat _rdr_env _envs ev eq_rel ty1 ps_ty1 (CastTy ty2 co2) _
= canEqCast flat ev eq_rel IsSwapped ty2 co2 ty1 ps_ty1
----------------------
-- Otherwise try to decompose
----------------------
-- Literals
can_eq_nc' _flat _rdr_env _envs ev eq_rel ty1@(LitTy l1) _ (LitTy l2) _
| l1 == l2
= do { setEqIfWanted ev (mkReflCo (eqRelRole eq_rel) ty1)
; stopWith ev "Equal LitTy" }
-- Try to decompose type constructor applications
-- Including FunTy (s -> t)
can_eq_nc' _flat _rdr_env _envs ev eq_rel ty1 _ ty2 _
| Just (tc1, tys1) <- tcRepSplitTyConApp_maybe ty1
, Just (tc2, tys2) <- tcRepSplitTyConApp_maybe ty2
, not (isTypeFamilyTyCon tc1)
, not (isTypeFamilyTyCon tc2)
= canTyConApp ev eq_rel tc1 tys1 tc2 tys2
can_eq_nc' _flat _rdr_env _envs ev eq_rel
s1@(ForAllTy (Named {}) _) _ s2@(ForAllTy (Named {}) _) _
| CtWanted { ctev_loc = loc, ctev_dest = orig_dest } <- ev
= do { let (bndrs1,body1) = tcSplitNamedPiTys s1
(bndrs2,body2) = tcSplitNamedPiTys s2
; if not (equalLength bndrs1 bndrs2)
|| not (map binderVisibility bndrs1 == map binderVisibility bndrs2)
then canEqHardFailure ev s1 s2
else
do { traceTcS "Creating implication for polytype equality" $ ppr ev
; kind_cos <- zipWithM (unifyWanted loc Nominal)
(map binderType bndrs1) (map binderType bndrs2)
; all_co <- deferTcSForAllEq (eqRelRole eq_rel) loc
kind_cos (bndrs1,body1) (bndrs2,body2)
; setWantedEq orig_dest all_co
; stopWith ev "Deferred polytype equality" } }
| otherwise
= do { traceTcS "Omitting decomposition of given polytype equality" $
pprEq s1 s2 -- See Note [Do not decompose given polytype equalities]
; stopWith ev "Discard given polytype equality" }
-- See Note [Canonicalising type applications] about why we require flat types
can_eq_nc' True _rdr_env _envs ev eq_rel (AppTy t1 s1) _ ty2 _
| Just (t2, s2) <- tcSplitAppTy_maybe ty2
= can_eq_app ev eq_rel t1 s1 t2 s2
can_eq_nc' True _rdr_env _envs ev eq_rel ty1 _ (AppTy t2 s2) _
| Just (t1, s1) <- tcSplitAppTy_maybe ty1
= can_eq_app ev eq_rel t1 s1 t2 s2
-- No similarity in type structure detected. Flatten and try again.
can_eq_nc' False rdr_env envs ev eq_rel _ ps_ty1 _ ps_ty2
= do { (xi1, co1) <- flatten FM_FlattenAll ev ps_ty1
; (xi2, co2) <- flatten FM_FlattenAll ev ps_ty2
; rewriteEqEvidence ev NotSwapped xi1 xi2 co1 co2
`andWhenContinue` \ new_ev ->
can_eq_nc' True rdr_env envs new_ev eq_rel xi1 xi1 xi2 xi2 }
-- Type variable on LHS or RHS are last. We want only flat types sent
-- to canEqTyVar.
-- See also Note [No top-level newtypes on RHS of representational equalities]
can_eq_nc' True _rdr_env _envs ev eq_rel (TyVarTy tv1) _ _ ps_ty2
= canEqTyVar ev eq_rel NotSwapped tv1 ps_ty2
can_eq_nc' True _rdr_env _envs ev eq_rel _ ps_ty1 (TyVarTy tv2) _
= canEqTyVar ev eq_rel IsSwapped tv2 ps_ty1
-- We've flattened and the types don't match. Give up.
can_eq_nc' True _rdr_env _envs ev _eq_rel _ ps_ty1 _ ps_ty2
= do { traceTcS "can_eq_nc' catch-all case" (ppr ps_ty1 $$ ppr ps_ty2)
; canEqHardFailure ev ps_ty1 ps_ty2 }
---------------------------------
-- | Compare types for equality, while zonking as necessary. Gives up
-- as soon as it finds that two types are not equal.
-- This is quite handy when some unification has made two
-- types in an inert wanted to be equal. We can discover the equality without
-- flattening, which is sometimes very expensive (in the case of type functions).
-- In particular, this function makes a ~20% improvement in test case
-- perf/compiler/T5030.
--
-- Returns either the (partially zonked) types in the case of
-- inequality, or the one type in the case of equality. canEqReflexive is
-- a good next step in the 'Right' case. Returning 'Left' is always safe.
--
-- NB: This does *not* look through type synonyms. In fact, it treats type
-- synonyms as rigid constructors. In the future, it might be convenient
-- to look at only those arguments of type synonyms that actually appear
-- in the synonym RHS. But we're not there yet.
zonk_eq_types :: TcType -> TcType -> TcS (Either (Pair TcType) TcType)
zonk_eq_types = go
where
go (TyVarTy tv1) (TyVarTy tv2) = tyvar_tyvar tv1 tv2
go (TyVarTy tv1) ty2 = tyvar NotSwapped tv1 ty2
go ty1 (TyVarTy tv2) = tyvar IsSwapped tv2 ty1
go ty1 ty2
| Just (tc1, tys1) <- tcRepSplitTyConApp_maybe ty1
, Just (tc2, tys2) <- tcRepSplitTyConApp_maybe ty2
, tc1 == tc2
= tycon tc1 tys1 tys2
go ty1 ty2
| Just (ty1a, ty1b) <- tcRepSplitAppTy_maybe ty1
, Just (ty2a, ty2b) <- tcRepSplitAppTy_maybe ty2
= do { res_a <- go ty1a ty2a
; res_b <- go ty1b ty2b
; return $ combine_rev mkAppTy res_b res_a }
go ty1@(LitTy lit1) (LitTy lit2)
| lit1 == lit2
= return (Right ty1)
go ty1 ty2 = return $ Left (Pair ty1 ty2)
-- we don't handle more complex forms here
tyvar :: SwapFlag -> TcTyVar -> TcType
-> TcS (Either (Pair TcType) TcType)
-- try to do as little as possible, as anything we do here is redundant
-- with flattening. In particular, no need to zonk kinds. That's why
-- we don't use the already-defined zonking functions
tyvar swapped tv ty
= case tcTyVarDetails tv of
MetaTv { mtv_ref = ref }
-> do { cts <- readTcRef ref
; case cts of
Flexi -> give_up
Indirect ty' -> unSwap swapped go ty' ty }
_ -> give_up
where
give_up = return $ Left $ unSwap swapped Pair (mkTyVarTy tv) ty
tyvar_tyvar tv1 tv2
| tv1 == tv2 = return (Right (mkTyVarTy tv1))
| otherwise = do { (ty1', progress1) <- quick_zonk tv1
; (ty2', progress2) <- quick_zonk tv2
; if progress1 || progress2
then go ty1' ty2'
else return $ Left (Pair (TyVarTy tv1) (TyVarTy tv2)) }
quick_zonk tv = case tcTyVarDetails tv of
MetaTv { mtv_ref = ref }
-> do { cts <- readTcRef ref
; case cts of
Flexi -> return (TyVarTy tv, False)
Indirect ty' -> return (ty', True) }
_ -> return (TyVarTy tv, False)
-- This happens for type families, too. But recall that failure
-- here just means to try harder, so it's OK if the type function
-- isn't injective.
tycon :: TyCon -> [TcType] -> [TcType]
-> TcS (Either (Pair TcType) TcType)
tycon tc tys1 tys2
= do { results <- zipWithM go tys1 tys2
; return $ case combine_results results of
Left tys -> Left (mkTyConApp tc <$> tys)
Right tys -> Right (mkTyConApp tc tys) }
combine_results :: [Either (Pair TcType) TcType]
-> Either (Pair [TcType]) [TcType]
combine_results = bimap (fmap reverse) reverse .
foldl' (combine_rev (:)) (Right [])
-- combine (in reverse) a new result onto an already-combined result
combine_rev :: (a -> b -> c)
-> Either (Pair b) b
-> Either (Pair a) a
-> Either (Pair c) c
combine_rev f (Left list) (Left elt) = Left (f <$> elt <*> list)
combine_rev f (Left list) (Right ty) = Left (f <$> pure ty <*> list)
combine_rev f (Right tys) (Left elt) = Left (f <$> elt <*> pure tys)
combine_rev f (Right tys) (Right ty) = Right (f ty tys)
{-
Note [Newtypes can blow the stack]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have
newtype X = MkX (Int -> X)
newtype Y = MkY (Int -> Y)
and now wish to prove
[W] X ~R Y
This Wanted will loop, expanding out the newtypes ever deeper looking
for a solid match or a solid discrepancy. Indeed, there is something
appropriate to this looping, because X and Y *do* have the same representation,
in the limit -- they're both (Fix ((->) Int)). However, no finitely-sized
coercion will ever witness it. This loop won't actually cause GHC to hang,
though, because we check our depth when unwrapping newtypes.
Note [Eager reflexivity check]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have
newtype X = MkX (Int -> X)
and
[W] X ~R X
Naively, we would start unwrapping X and end up in a loop. Instead,
we do this eager reflexivity check. This is necessary only for representational
equality because the flattener technology deals with the similar case
(recursive type families) for nominal equality.
Note that this check does not catch all cases, but it will catch the cases
we're most worried about, types like X above that are actually inhabited.
Here's another place where this reflexivity check is key:
Consider trying to prove (f a) ~R (f a). The AppTys in there can't
be decomposed, because representational equality isn't congruent with respect
to AppTy. So, when canonicalising the equality above, we get stuck and
would normally produce a CIrredEvCan. However, we really do want to
be able to solve (f a) ~R (f a). So, in the representational case only,
we do a reflexivity check.
(This would be sound in the nominal case, but unnecessary, and I [Richard
E.] am worried that it would slow down the common case.)
-}
------------------------
-- | We're able to unwrap a newtype. Update the bits accordingly.
can_eq_newtype_nc :: GlobalRdrEnv
-> CtEvidence -- ^ :: ty1 ~ ty2
-> SwapFlag
-> TcCoercion -- ^ :: ty1 ~ ty1'
-> TcType -- ^ ty1
-> TcType -- ^ ty1'
-> TcType -- ^ ty2
-> TcType -- ^ ty2, with type synonyms
-> TcS (StopOrContinue Ct)
can_eq_newtype_nc rdr_env ev swapped co ty1 ty1' ty2 ps_ty2
= do { traceTcS "can_eq_newtype_nc" $
vcat [ ppr ev, ppr swapped, ppr co, ppr ty1', ppr ty2 ]
-- check for blowing our stack:
-- See Note [Newtypes can blow the stack]
; checkReductionDepth (ctEvLoc ev) ty1
; addUsedDataCons rdr_env (tyConAppTyCon ty1)
-- we have actually used the newtype constructor here, so
-- make sure we don't warn about importing it!
; rewriteEqEvidence ev swapped ty1' ps_ty2
(mkTcSymCo co) (mkTcReflCo Representational ps_ty2)
`andWhenContinue` \ new_ev ->
can_eq_nc False new_ev ReprEq ty1' ty1' ty2 ps_ty2 }
---------
-- ^ Decompose a type application.
-- All input types must be flat. See Note [Canonicalising type applications]
can_eq_app :: CtEvidence -- :: s1 t1 ~r s2 t2
-> EqRel -- r
-> Xi -> Xi -- s1 t1
-> Xi -> Xi -- s2 t2
-> TcS (StopOrContinue Ct)
-- AppTys only decompose for nominal equality, so this case just leads
-- to an irreducible constraint; see typecheck/should_compile/T10494
-- See Note [Decomposing equality], note {4}
can_eq_app ev ReprEq _ _ _ _
= do { traceTcS "failing to decompose representational AppTy equality" (ppr ev)
; continueWith (CIrredEvCan { cc_ev = ev }) }
-- no need to call canEqFailure, because that flattens, and the
-- types involved here are already flat
can_eq_app ev NomEq s1 t1 s2 t2
| CtDerived { ctev_loc = loc } <- ev
= do { unifyDeriveds loc [Nominal, Nominal] [s1, t1] [s2, t2]
; stopWith ev "Decomposed [D] AppTy" }
| CtWanted { ctev_dest = dest, ctev_loc = loc } <- ev
= do { co_s <- unifyWanted loc Nominal s1 s2
; co_t <- unifyWanted loc Nominal t1 t2
; let co = mkAppCo co_s co_t
; setWantedEq dest co
; stopWith ev "Decomposed [W] AppTy" }
| CtGiven { ctev_evar = evar, ctev_loc = loc } <- ev
= do { let co = mkTcCoVarCo evar
co_s = mkTcLRCo CLeft co
co_t = mkTcLRCo CRight co
; evar_s <- newGivenEvVar loc ( mkTcEqPredLikeEv ev s1 s2
, EvCoercion co_s )
; evar_t <- newGivenEvVar loc ( mkTcEqPredLikeEv ev t1 t2
, EvCoercion co_t )
; emitWorkNC [evar_t]
; canEqNC evar_s NomEq s1 s2 }
| otherwise -- Can't happen
= error "can_eq_app"
-----------------------
-- | Break apart an equality over a casted type
canEqCast :: Bool -- are both types flat?
-> CtEvidence
-> EqRel
-> SwapFlag
-> TcType -> Coercion -- LHS (res. RHS), the casted type
-> TcType -> TcType -- RHS (res. LHS), both normal and pretty
-> TcS (StopOrContinue Ct)
canEqCast flat ev eq_rel swapped ty1 co1 ty2 ps_ty2
= do { traceTcS "Decomposing cast" (vcat [ ppr ev
, ppr ty1 <+> text "|>" <+> ppr co1
, ppr ps_ty2 ])
; rewriteEqEvidence ev swapped ty1 ps_ty2
(mkTcReflCo role ty1
`mkTcCoherenceRightCo` co1)
(mkTcReflCo role ps_ty2)
`andWhenContinue` \ new_ev ->
can_eq_nc flat new_ev eq_rel ty1 ty1 ty2 ps_ty2 }
where
role = eqRelRole eq_rel
------------------------
canTyConApp :: CtEvidence -> EqRel
-> TyCon -> [TcType]
-> TyCon -> [TcType]
-> TcS (StopOrContinue Ct)
-- See Note [Decomposing TyConApps]
canTyConApp ev eq_rel tc1 tys1 tc2 tys2
| tc1 == tc2
, length tys1 == length tys2
= do { inerts <- getTcSInerts
; if can_decompose inerts
then do { traceTcS "canTyConApp"
(ppr ev $$ ppr eq_rel $$ ppr tc1 $$ ppr tys1 $$ ppr tys2)
; canDecomposableTyConAppOK ev eq_rel tc1 tys1 tys2
; stopWith ev "Decomposed TyConApp" }
else canEqFailure ev eq_rel ty1 ty2 }
-- Fail straight away for better error messages
-- See Note [Use canEqFailure in canDecomposableTyConApp]
| eq_rel == ReprEq && not (isGenerativeTyCon tc1 Representational &&
isGenerativeTyCon tc2 Representational)
= canEqFailure ev eq_rel ty1 ty2
| otherwise
= canEqHardFailure ev ty1 ty2
where
ty1 = mkTyConApp tc1 tys1
ty2 = mkTyConApp tc2 tys2
loc = ctEvLoc ev
pred = ctEvPred ev
-- See Note [Decomposing equality]
can_decompose inerts
= isInjectiveTyCon tc1 (eqRelRole eq_rel)
|| (ctEvFlavour ev /= Given && isEmptyBag (matchableGivens loc pred inerts))
{-
Note [Use canEqFailure in canDecomposableTyConApp]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We must use canEqFailure, not canEqHardFailure here, because there is
the possibility of success if working with a representational equality.
Here is one case:
type family TF a where TF Char = Bool
data family DF a
newtype instance DF Bool = MkDF Int
Suppose we are canonicalising (Int ~R DF (TF a)), where we don't yet
know `a`. This is *not* a hard failure, because we might soon learn
that `a` is, in fact, Char, and then the equality succeeds.
Here is another case:
[G] Age ~R Int
where Age's constructor is not in scope. We don't want to report
an "inaccessible code" error in the context of this Given!
For example, see typecheck/should_compile/T10493, repeated here:
import Data.Ord (Down) -- no constructor
foo :: Coercible (Down Int) Int => Down Int -> Int
foo = coerce
That should compile, but only because we use canEqFailure and not
canEqHardFailure.
Note [Decomposing equality]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we have a constraint (of any flavour and role) that looks like
T tys1 ~ T tys2, what can we conclude about tys1 and tys2? The answer,
of course, is "it depends". This Note spells it all out.
In this Note, "decomposition" refers to taking the constraint
[fl] (T tys1 ~X T tys2)
(for some flavour fl and some role X) and replacing it with
[fls'] (tys1 ~Xs' tys2)
where that notation indicates a list of new constraints, where the
new constraints may have different flavours and different roles.
The key property to consider is injectivity. When decomposing a Given the
decomposition is sound if and only if T is injective in all of its type
arguments. When decomposing a Wanted, the decomposition is sound (assuming the
correct roles in the produced equality constraints), but it may be a guess --
that is, an unforced decision by the constraint solver. Decomposing Wanteds
over injective TyCons does not entail guessing. But sometimes we want to
decompose a Wanted even when the TyCon involved is not injective! (See below.)
So, in broad strokes, we want this rule:
(*) Decompose a constraint (T tys1 ~X T tys2) if and only if T is injective
at role X.
Pursuing the details requires exploring three axes:
* Flavour: Given vs. Derived vs. Wanted
* Role: Nominal vs. Representational
* TyCon species: datatype vs. newtype vs. data family vs. type family vs. type variable
(So a type variable isn't a TyCon, but it's convenient to put the AppTy case
in the same table.)
Right away, we can say that Derived behaves just as Wanted for the purposes
of decomposition. The difference between Derived and Wanted is the handling of
evidence. Since decomposition in these cases isn't a matter of soundness but of
guessing, we want the same behavior regardless of evidence.
Here is a table (discussion following) detailing where decomposition of
(T s1 ... sn) ~r (T t1 .. tn)
is allowed. The first four lines (Data types ... type family) refer
to TyConApps with various TyCons T; the last line is for AppTy, where
there is presumably a type variable at the head, so it's actually
(s s1 ... sn) ~r (t t1 .. tn)
NOMINAL GIVEN WANTED
Datatype YES YES
Newtype YES YES
Data family YES YES
Type family YES, in injective args{1} YES, in injective args{1}
Type variable YES YES
REPRESENTATIONAL GIVEN WANTED
Datatype YES YES
Newtype NO{2} MAYBE{2}
Data family NO{3} MAYBE{3}
Type family NO NO
Type variable NO{4} NO{4}
{1}: Type families can be injective in some, but not all, of their arguments,
so we want to do partial decomposition. This is quite different than the way
other decomposition is done, where the decomposed equalities replace the original
one. We thus proceed much like we do with superclasses: emitting new Givens
when "decomposing" a partially-injective type family Given and new Deriveds
when "decomposing" a partially-injective type family Wanted. (As of the time of
writing, 13 June 2015, the implementation of injective type families has not
been merged, but it should be soon. Please delete this parenthetical if the
implementation is indeed merged.)
{2}: See Note [Decomposing newtypes at representational role]
{3}: Because of the possibility of newtype instances, we must treat
data families like newtypes. See also Note [Decomposing newtypes at
representational role]. See #10534 and test case
typecheck/should_fail/T10534.
{4}: Because type variables can stand in for newtypes, we conservatively do not
decompose AppTys over representational equality.
In the implementation of can_eq_nc and friends, we don't directly pattern
match using lines like in the tables above, as those tables don't cover
all cases (what about PrimTyCon? tuples?). Instead we just ask about injectivity,
boiling the tables above down to rule (*). The exceptions to rule (*) are for
injective type families, which are handled separately from other decompositions,
and the MAYBE entries above.
Note [Decomposing newtypes at representational role]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This note discusses the 'newtype' line in the REPRESENTATIONAL table
in Note [Decomposing equality]. (At nominal role, newtypes are fully
decomposable.)
Here is a representative example of why representational equality over
newtypes is tricky:
newtype Nt a = Mk Bool -- NB: a is not used in the RHS,
type role Nt representational -- but the user gives it an R role anyway
If we have [W] Nt alpha ~R Nt beta, we *don't* want to decompose to
[W] alpha ~R beta, because it's possible that alpha and beta aren't
representationally equal. Here's another example.
newtype Nt a = MkNt (Id a)
type family Id a where Id a = a
[W] Nt Int ~R Nt Age
Because of its use of a type family, Nt's parameter will get inferred to have
a nominal role. Thus, decomposing the wanted will yield [W] Int ~N Age, which
is unsatisfiable. Unwrapping, though, leads to a solution.
Conclusion:
* Unwrap newtypes before attempting to decompose them.
This is done in can_eq_nc'.
It all comes from the fact that newtypes aren't necessarily injective
w.r.t. representational equality.
Furthermore, as explained in Note [NthCo and newtypes] in TyCoRep, we can't use
NthCo on representational coercions over newtypes. NthCo comes into play
only when decomposing givens.
Conclusion:
* Do not decompose [G] N s ~R N t
Is it sensible to decompose *Wanted* constraints over newtypes? Yes!
It's the only way we could ever prove (IO Int ~R IO Age), recalling
that IO is a newtype.
However we must be careful. Consider
type role Nt representational
[G] Nt a ~R Nt b (1)
[W] NT alpha ~R Nt b (2)
[W] alpha ~ a (3)
If we focus on (3) first, we'll substitute in (2), and now it's
identical to the given (1), so we succeed. But if we focus on (2)
first, and decompose it, we'll get (alpha ~R b), which is not soluble.
This is exactly like the question of overlapping Givens for class
constraints: see Note [Instance and Given overlap] in TcInteract.
Conclusion:
* Decompose [W] N s ~R N t iff there no given constraint that could
later solve it.
-}
canDecomposableTyConAppOK :: CtEvidence -> EqRel
-> TyCon -> [TcType] -> [TcType]
-> TcS ()
-- Precondition: tys1 and tys2 are the same length, hence "OK"
canDecomposableTyConAppOK ev eq_rel tc tys1 tys2
= case ev of
CtDerived {}
-> unifyDeriveds loc tc_roles tys1 tys2
CtWanted { ctev_dest = dest }
-> do { cos <- zipWith4M unifyWanted new_locs tc_roles tys1 tys2
; setWantedEq dest (mkTyConAppCo role tc cos) }
CtGiven { ctev_evar = evar }
-> do { let ev_co = mkCoVarCo evar
; given_evs <- newGivenEvVars loc $
[ ( mkPrimEqPredRole r ty1 ty2
, EvCoercion (mkNthCo i ev_co) )
| (r, ty1, ty2, i) <- zip4 tc_roles tys1 tys2 [0..]
, r /= Phantom
, not (isCoercionTy ty1) && not (isCoercionTy ty2) ]
; emitWorkNC given_evs }
where
loc = ctEvLoc ev
role = eqRelRole eq_rel
tc_roles = tyConRolesX role tc
-- the following makes a better distinction between "kind" and "type"
-- in error messages
bndrs = tyConBinders tc
kind_loc = toKindLoc loc
is_kinds = map isNamedBinder bndrs
new_locs | Just KindLevel <- ctLocTypeOrKind_maybe loc
= repeat loc
| otherwise
= map (\is_kind -> if is_kind then kind_loc else loc) is_kinds
-- | Call when canonicalizing an equality fails, but if the equality is
-- representational, there is some hope for the future.
-- Examples in Note [Use canEqFailure in canDecomposableTyConApp]
canEqFailure :: CtEvidence -> EqRel
-> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqFailure ev NomEq ty1 ty2
= canEqHardFailure ev ty1 ty2
canEqFailure ev ReprEq ty1 ty2
= do { (xi1, co1) <- flatten FM_FlattenAll ev ty1
; (xi2, co2) <- flatten FM_FlattenAll ev ty2
-- We must flatten the types before putting them in the
-- inert set, so that we are sure to kick them out when
-- new equalities become available
; traceTcS "canEqFailure with ReprEq" $
vcat [ ppr ev, ppr ty1, ppr ty2, ppr xi1, ppr xi2 ]
; rewriteEqEvidence ev NotSwapped xi1 xi2 co1 co2
`andWhenContinue` \ new_ev ->
continueWith (CIrredEvCan { cc_ev = new_ev }) }
-- | Call when canonicalizing an equality fails with utterly no hope.
canEqHardFailure :: CtEvidence
-> TcType -> TcType -> TcS (StopOrContinue Ct)
-- See Note [Make sure that insolubles are fully rewritten]
canEqHardFailure ev ty1 ty2
= do { (s1, co1) <- flatten FM_SubstOnly ev ty1
; (s2, co2) <- flatten FM_SubstOnly ev ty2
; rewriteEqEvidence ev NotSwapped s1 s2 co1 co2
`andWhenContinue` \ new_ev ->
do { emitInsoluble (mkNonCanonical new_ev)
; stopWith new_ev "Definitely not equal" }}
{-
Note [Decomposing TyConApps]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we see (T s1 t1 ~ T s2 t2), then we can just decompose to
(s1 ~ s2, t1 ~ t2)
and push those back into the work list. But if
s1 = K k1 s2 = K k2
then we will just decomopose s1~s2, and it might be better to
do so on the spot. An important special case is where s1=s2,
and we get just Refl.
So canDecomposableTyCon is a fast-path decomposition that uses
unifyWanted etc to short-cut that work.
Note [Canonicalising type applications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Given (s1 t1) ~ ty2, how should we proceed?
The simple things is to see if ty2 is of form (s2 t2), and
decompose. By this time s1 and s2 can't be saturated type
function applications, because those have been dealt with
by an earlier equation in can_eq_nc, so it is always sound to
decompose.
However, over-eager decomposition gives bad error messages
for things like
a b ~ Maybe c
e f ~ p -> q
Suppose (in the first example) we already know a~Array. Then if we
decompose the application eagerly, yielding
a ~ Maybe
b ~ c
we get an error "Can't match Array ~ Maybe",
but we'd prefer to get "Can't match Array b ~ Maybe c".
So instead can_eq_wanted_app flattens the LHS and RHS, in the hope of
replacing (a b) by (Array b), before using try_decompose_app to
decompose it.
Note [Make sure that insolubles are fully rewritten]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When an equality fails, we still want to rewrite the equality
all the way down, so that it accurately reflects
(a) the mutable reference substitution in force at start of solving
(b) any ty-binds in force at this point in solving
See Note [Kick out insolubles] in TcSMonad.
And if we don't do this there is a bad danger that
TcSimplify.applyTyVarDefaulting will find a variable
that has in fact been substituted.
Note [Do not decompose Given polytype equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider [G] (forall a. t1 ~ forall a. t2). Can we decompose this?
No -- what would the evidence look like? So instead we simply discard
this given evidence.
Note [Combining insoluble constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As this point we have an insoluble constraint, like Int~Bool.
* If it is Wanted, delete it from the cache, so that subsequent
Int~Bool constraints give rise to separate error messages
* But if it is Derived, DO NOT delete from cache. A class constraint
may get kicked out of the inert set, and then have its functional
dependency Derived constraints generated a second time. In that
case we don't want to get two (or more) error messages by
generating two (or more) insoluble fundep constraints from the same
class constraint.
Note [No top-level newtypes on RHS of representational equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we're in this situation:
work item: [W] c1 : a ~R b
inert: [G] c2 : b ~R Id a
where
newtype Id a = Id a
We want to make sure canEqTyVar sees [W] a ~R a, after b is flattened
and the Id newtype is unwrapped. This is assured by requiring only flat
types in canEqTyVar *and* having the newtype-unwrapping check above
the tyvar check in can_eq_nc.
Note [Occurs check error]
~~~~~~~~~~~~~~~~~~~~~~~~~
If we have an occurs check error, are we necessarily hosed? Say our
tyvar is tv1 and the type it appears in is xi2. Because xi2 is function
free, then if we're computing w.r.t. nominal equality, then, yes, we're
hosed. Nothing good can come from (a ~ [a]). If we're computing w.r.t.
representational equality, this is a little subtler. Once again, (a ~R [a])
is a bad thing, but (a ~R N a) for a newtype N might be just fine. This
means also that (a ~ b a) might be fine, because `b` might become a newtype.
So, we must check: does tv1 appear in xi2 under any type constructor that
is generative w.r.t. representational equality? That's what isTyVarUnderDatatype
does. (The other name I considered, isTyVarUnderTyConGenerativeWrtReprEq was
a bit verbose. And the shorter name gets the point across.)
See also #10715, which induced this addition.
Note [No derived kind equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we're working with a heterogeneous derived equality
[D] (t1 :: k1) ~ (t2 :: k2)
we want to homogenise to establish the kind invariant on CTyEqCans.
But we can't emit [D] k1 ~ k2 because we wouldn't then be able to
use the evidence in the homogenised types. So we emit a wanted
constraint, because we do really need the evidence here.
Thus: no derived kind equalities.
-}
canCFunEqCan :: CtEvidence
-> TyCon -> [TcType] -- LHS
-> TcTyVar -- RHS
-> TcS (StopOrContinue Ct)
-- ^ Canonicalise a CFunEqCan. We know that
-- the arg types are already flat,
-- and the RHS is a fsk, which we must *not* substitute.
-- So just substitute in the LHS
canCFunEqCan ev fn tys fsk
= do { (tys', cos) <- flattenManyNom ev tys
-- cos :: tys' ~ tys
; let lhs_co = mkTcTyConAppCo Nominal fn cos
-- :: F tys' ~ F tys
new_lhs = mkTyConApp fn tys'
fsk_ty = mkTyVarTy fsk
; rewriteEqEvidence ev NotSwapped new_lhs fsk_ty
lhs_co (mkTcNomReflCo fsk_ty)
`andWhenContinue` \ ev' ->
do { extendFlatCache fn tys' (ctEvCoercion ev', fsk_ty, ctEvFlavour ev')
; continueWith (CFunEqCan { cc_ev = ev', cc_fun = fn
, cc_tyargs = tys', cc_fsk = fsk }) } }
---------------------
canEqTyVar :: CtEvidence -> EqRel -> SwapFlag
-> TcTyVar -- already flat
-> TcType -- already flat
-> TcS (StopOrContinue Ct)
-- A TyVar on LHS, but so far un-zonked
canEqTyVar ev eq_rel swapped tv1 ps_ty2 -- ev :: tv ~ s2
= do { traceTcS "canEqTyVar" (ppr tv1 $$ ppr ps_ty2 $$ ppr swapped)
-- FM_Avoid commented out: see Note [Lazy flattening] in TcFlatten
-- let fmode = FE { fe_ev = ev, fe_mode = FM_Avoid tv1' True }
-- Flatten the RHS less vigorously, to avoid gratuitous flattening
-- True <=> xi2 should not itself be a type-function application
; dflags <- getDynFlags
; canEqTyVar2 dflags ev eq_rel swapped tv1 ps_ty2 }
canEqTyVar2 :: DynFlags
-> CtEvidence -- lhs ~ rhs (or, if swapped, orhs ~ olhs)
-> EqRel
-> SwapFlag
-> TcTyVar -- lhs, flat
-> TcType -- rhs, flat
-> TcS (StopOrContinue Ct)
-- LHS is an inert type variable,
-- and RHS is fully rewritten, but with type synonyms
-- preserved as much as possible
canEqTyVar2 dflags ev eq_rel swapped tv1 xi2
| Just (tv2, kco2) <- getCastedTyVar_maybe xi2
= canEqTyVarTyVar ev eq_rel swapped tv1 tv2 kco2
| OC_OK xi2' <- occurCheckExpand dflags tv1 xi2 -- No occurs check
-- We use xi2' on the RHS of the new CTyEqCan, a ~ xi2'
-- to establish the invariant that a does not appear in the
-- rhs of the CTyEqCan. This is guaranteed by occurCheckExpand;
-- see Note [Occurs check expansion] in TcType
= rewriteEqEvidence ev swapped xi1 xi2' co1 (mkTcReflCo role xi2')
`andWhenContinue` \ new_ev ->
homogeniseRhsKind new_ev eq_rel xi1 xi2' $ \new_new_ev xi2'' ->
CTyEqCan { cc_ev = new_new_ev, cc_tyvar = tv1
, cc_rhs = xi2'', cc_eq_rel = eq_rel }
| otherwise -- Occurs check error
= do { traceTcS "canEqTyVar2 occurs check error" (ppr tv1 $$ ppr xi2)
; rewriteEqEvidence ev swapped xi1 xi2 co1 co2
`andWhenContinue` \ new_ev ->
if eq_rel == NomEq || isTyVarUnderDatatype tv1 xi2
then do { emitInsoluble (mkNonCanonical new_ev)
-- If we have a ~ [a], it is not canonical, and in particular
-- we don't want to rewrite existing inerts with it, otherwise
-- we'd risk divergence in the constraint solver
; stopWith new_ev "Occurs check" }
-- A representational equality with an occurs-check problem isn't
-- insoluble! For example:
-- a ~R b a
-- We might learn that b is the newtype Id.
-- But, the occurs-check certainly prevents the equality from being
-- canonical, and we might loop if we were to use it in rewriting.
else do { traceTcS "Occurs-check in representational equality"
(ppr xi1 $$ ppr xi2)
; continueWith (CIrredEvCan { cc_ev = new_ev }) } }
where
role = eqRelRole eq_rel
xi1 = mkTyVarTy tv1
co1 = mkTcReflCo role xi1
co2 = mkTcReflCo role xi2
canEqTyVarTyVar :: CtEvidence -- tv1 ~ rhs (or rhs ~ tv1, if swapped)
-> EqRel
-> SwapFlag
-> TcTyVar -> TcTyVar -- tv1, tv2
-> Coercion -- the co in (rhs = tv2 |> co)
-> TcS (StopOrContinue Ct)
-- Both LHS and RHS rewrote to a type variable
-- See Note [Canonical orientation for tyvar/tyvar equality constraints]
canEqTyVarTyVar ev eq_rel swapped tv1 tv2 kco2
| tv1 == tv2
= do { let mk_coh = case swapped of IsSwapped -> mkTcCoherenceLeftCo
NotSwapped -> mkTcCoherenceRightCo
; setEvBindIfWanted ev (EvCoercion $ mkTcReflCo role xi1 `mk_coh` kco2)
; stopWith ev "Equal tyvars" }
-- We don't do this any more
-- See Note [Orientation of equalities with fmvs] in TcFlatten
-- | isFmvTyVar tv1 = do_fmv swapped tv1 xi1 xi2 co1 co2
-- | isFmvTyVar tv2 = do_fmv (flipSwap swapped) tv2 xi2 xi1 co2 co1
| swap_over = do_swap
| otherwise = no_swap
where
role = eqRelRole eq_rel
xi1 = mkTyVarTy tv1
co1 = mkTcReflCo role xi1
xi2 = mkTyVarTy tv2
co2 = mkTcReflCo role xi2 `mkTcCoherenceRightCo` kco2
no_swap = canon_eq swapped tv1 xi1 xi2 co1 co2
do_swap = canon_eq (flipSwap swapped) tv2 xi2 xi1 co2 co1
canon_eq swapped tv1 ty1 ty2 co1 co2
-- ev : tv1 ~ orhs (not swapped) or orhs ~ tv1 (swapped)
-- co1 : xi1 ~ tv1
-- co2 : xi2 ~ tv2
= do { traceTcS "canEqTyVarTyVar"
(vcat [ ppr swapped
, ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1)
, ppr ty1 <+> dcolon <+> ppr (typeKind ty1)
, ppr ty2 <+> dcolon <+> ppr (typeKind ty2)
, ppr co1 <+> dcolon <+> ppr (tcCoercionKind co1)
, ppr co2 <+> dcolon <+> ppr (tcCoercionKind co2) ])
; rewriteEqEvidence ev swapped ty1 ty2 co1 co2
`andWhenContinue` \ new_ev ->
homogeniseRhsKind new_ev eq_rel ty1 ty2 $ \new_new_ev ty2' ->
CTyEqCan { cc_ev = new_new_ev, cc_tyvar = tv1
, cc_rhs = ty2', cc_eq_rel = eq_rel } }
{- We don't do this any more
See Note [Orientation of equalities with fmvs] in TcFlatten
-- tv1 is the flatten meta-var
do_fmv swapped tv1 xi1 xi2 co1 co2
| same_kind
= canon_eq swapped tv1 xi1 xi2 co1 co2
| otherwise -- Presumably tv1 :: *, since it is a flatten meta-var,
-- at a kind that has some interesting sub-kind structure.
-- Since the two kinds are not the same, we must have
-- tv1 `subKind` tv2, which is the wrong way round
-- e.g. (fmv::*) ~ (a::OpenKind)
-- So make a new meta-var and use that:
-- fmv ~ (beta::*)
-- (a::OpenKind) ~ (beta::*)
= ASSERT2( k1_sub_k2,
ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1) $$
ppr xi2 <+> dcolon <+> ppr (typeKind xi2) )
ASSERT2( isWanted ev, ppr ev ) -- Only wanteds have flatten meta-vars
do { tv_ty <- newFlexiTcSTy (tyVarKind tv1)
; new_ev <- newWantedEvVarNC (ctEvLoc ev)
(mkPrimEqPredRole (eqRelRole eq_rel)
g tv_ty xi2)
; emitWorkNC [new_ev]
; canon_eq swapped tv1 xi1 tv_ty co1 (ctEvCoercion new_ev) }
-}
swap_over
-- If tv1 is touchable, swap only if tv2 is also
-- touchable and it's strictly better to update the latter
-- But see Note [Avoid unnecessary swaps]
| Just lvl1 <- metaTyVarTcLevel_maybe tv1
= case metaTyVarTcLevel_maybe tv2 of
Nothing -> False
Just lvl2 | lvl2 `strictlyDeeperThan` lvl1 -> True
| lvl1 `strictlyDeeperThan` lvl2 -> False
| otherwise -> nicer_to_update_tv2
-- So tv1 is not a meta tyvar
-- If only one is a meta tyvar, put it on the left
-- This is not because it'll be solved; but because
-- the floating step looks for meta tyvars on the left
| isMetaTyVar tv2 = True
-- So neither is a meta tyvar (including FlatMetaTv)
-- If only one is a flatten skolem, put it on the left
-- See Note [Eliminate flat-skols]
| not (isFlattenTyVar tv1), isFlattenTyVar tv2 = True
| otherwise = False
nicer_to_update_tv2
= (isSigTyVar tv1 && not (isSigTyVar tv2))
|| (isSystemName (Var.varName tv2) && not (isSystemName (Var.varName tv1)))
-- | Solve a reflexive equality constraint
canEqReflexive :: CtEvidence -- ty ~ ty
-> EqRel
-> TcType -- ty
-> TcS (StopOrContinue Ct) -- always Stop
canEqReflexive ev eq_rel ty
= do { setEvBindIfWanted ev (EvCoercion $
mkTcReflCo (eqRelRole eq_rel) ty)
; stopWith ev "Solved by reflexivity" }
-- See Note [Equalities with incompatible kinds]
homogeniseRhsKind :: CtEvidence -- ^ the evidence to homogenise
-> EqRel
-> TcType -- ^ original LHS
-> Xi -- ^ original RHS
-> (CtEvidence -> Xi -> Ct)
-- ^ how to build the homogenised constraint;
-- the 'Xi' is the new RHS
-> TcS (StopOrContinue Ct)
homogeniseRhsKind ev eq_rel lhs rhs build_ct
| k1 `eqType` k2
= continueWith (build_ct ev rhs)
| CtGiven { ctev_evar = evar } <- ev
-- tm :: (lhs :: k1) ~ (rhs :: k2)
= do { kind_ev_id <- newBoundEvVarId kind_pty
(EvCoercion $
mkTcKindCo $ mkTcCoVarCo evar)
-- kind_ev_id :: (k1 :: *) ~# (k2 :: *)
; let kind_ev = CtGiven { ctev_pred = kind_pty
, ctev_evar = kind_ev_id
, ctev_loc = kind_loc }
homo_co = mkSymCo $ mkCoVarCo kind_ev_id
rhs' = mkCastTy rhs homo_co
; traceTcS "Hetero equality gives rise to given kind equality"
(ppr kind_ev_id <+> dcolon <+> ppr kind_pty)
; emitWorkNC [kind_ev]
; type_ev <- newGivenEvVar loc
( mkTcEqPredLikeEv ev lhs rhs'
, EvCoercion $
mkTcCoherenceRightCo (mkTcCoVarCo evar) homo_co )
-- type_ev :: (lhs :: k1) ~ ((rhs |> sym kind_ev_id) :: k1)
; continueWith (build_ct type_ev rhs') }
| otherwise -- Wanted and Derived. See Note [No derived kind equalities]
-- evar :: (lhs :: k1) ~ (rhs :: k2)
= do { (kind_ev, kind_co) <- newWantedEq kind_loc Nominal k1 k2
-- kind_ev :: (k1 :: *) ~ (k2 :: *)
; traceTcS "Hetero equality gives rise to wanted kind equality" $
ppr (kind_ev)
; emitWorkNC [kind_ev]
; let homo_co = mkSymCo kind_co
-- homo_co :: k2 ~ k1
rhs' = mkCastTy rhs homo_co
; case ev of
CtGiven {} -> panic "homogeniseRhsKind"
CtDerived {} -> continueWith (build_ct (ev { ctev_pred = homo_pred })
rhs')
where homo_pred = mkTcEqPredLikeEv ev lhs rhs'
CtWanted { ctev_dest = dest } -> do
{ (type_ev, hole_co) <- newWantedEq loc role lhs rhs'
-- type_ev :: (lhs :: k1) ~ (rhs |> sym kind_ev :: k1)
; setWantedEq dest
(hole_co `mkTransCo`
(mkReflCo role rhs
`mkCoherenceLeftCo` homo_co))
-- dest := hole ; <rhs> |> homo_co :: (lhs :: k1) ~ (rhs :: k2)
; continueWith (build_ct type_ev rhs') }}
where
k1 = typeKind lhs
k2 = typeKind rhs
kind_pty = mkHeteroPrimEqPred liftedTypeKind liftedTypeKind k1 k2
kind_loc = mkKindLoc lhs rhs loc
loc = ctev_loc ev
role = eqRelRole eq_rel
{-
Note [Canonical orientation for tyvar/tyvar equality constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we have a ~ b where both 'a' and 'b' are TcTyVars, which way
round should be oriented in the CTyEqCan? The rules, implemented by
canEqTyVarTyVar, are these
* If either is a flatten-meta-variables, it goes on the left.
* If one is a strict sub-kind of the other e.g.
(alpha::?) ~ (beta::*)
orient them so RHS is a subkind of LHS. That way we will replace
'a' with 'b', correctly narrowing the kind.
This establishes the subkind invariant of CTyEqCan.
* Put a meta-tyvar on the left if possible
alpha[3] ~ r
* If both are meta-tyvars, put the more touchable one (deepest level
number) on the left, so there is the best chance of unifying it
alpha[3] ~ beta[2]
* If both are meta-tyvars and both at the same level, put a SigTv
on the right if possible
alpha[2] ~ beta[2](sig-tv)
That way, when we unify alpha := beta, we don't lose the SigTv flag.
* Put a meta-tv with a System Name on the left if possible so it
gets eliminated (improves error messages)
* If one is a flatten-skolem, put it on the left so that it is
substituted out Note [Elminate flat-skols]
fsk ~ a
Note [Avoid unnecessary swaps]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we swap without actually improving matters, we can get an infnite loop.
Consider
work item: a ~ b
inert item: b ~ c
We canonicalise the work-time to (a ~ c). If we then swap it before
aeding to the inert set, we'll add (c ~ a), and therefore kick out the
inert guy, so we get
new work item: b ~ c
inert item: c ~ a
And now the cycle just repeats
Note [Eliminate flat-skols]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have [G] Num (F [a])
then we flatten to
[G] Num fsk
[G] F [a] ~ fsk
where fsk is a flatten-skolem (FlatSkol). Suppose we have
type instance F [a] = a
then we'll reduce the second constraint to
[G] a ~ fsk
and then replace all uses of 'a' with fsk. That's bad because
in error messages intead of saying 'a' we'll say (F [a]). In all
places, including those where the programmer wrote 'a' in the first
place. Very confusing! See Trac #7862.
Solution: re-orient a~fsk to fsk~a, so that we preferentially eliminate
the fsk.
Note [Equalities with incompatible kinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
canEqLeaf is about to make a CTyEqCan or CFunEqCan; but both have the
invariant that LHS and RHS satisfy the kind invariants for CTyEqCan,
CFunEqCan. What if we try to unify two things with incompatible
kinds?
eg a ~ b where a::*, b::*->*
or a ~ b where a::*, b::k, k is a kind variable
The CTyEqCan compatKind invariant is important. If we make a CTyEqCan
for a~b, then we might well *substitute* 'b' for 'a', and that might make
a well-kinded type ill-kinded; and that is bad (eg typeKind can crash, see
Trac #7696).
So instead for these ill-kinded equalities we homogenise the RHS of the
equality, emitting new constraints as necessary.
Note [Type synonyms and canonicalization]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We treat type synonym applications as xi types, that is, they do not
count as type function applications. However, we do need to be a bit
careful with type synonyms: like type functions they may not be
generative or injective. However, unlike type functions, they are
parametric, so there is no problem in expanding them whenever we see
them, since we do not need to know anything about their arguments in
order to expand them; this is what justifies not having to treat them
as specially as type function applications. The thing that causes
some subtleties is that we prefer to leave type synonym applications
*unexpanded* whenever possible, in order to generate better error
messages.
If we encounter an equality constraint with type synonym applications
on both sides, or a type synonym application on one side and some sort
of type application on the other, we simply must expand out the type
synonyms in order to continue decomposing the equality constraint into
primitive equality constraints. For example, suppose we have
type F a = [Int]
and we encounter the equality
F a ~ [b]
In order to continue we must expand F a into [Int], giving us the
equality
[Int] ~ [b]
which we can then decompose into the more primitive equality
constraint
Int ~ b.
However, if we encounter an equality constraint with a type synonym
application on one side and a variable on the other side, we should
NOT (necessarily) expand the type synonym, since for the purpose of
good error messages we want to leave type synonyms unexpanded as much
as possible. Hence the ps_ty1, ps_ty2 argument passed to canEqTyVar.
-}
{-
************************************************************************
* *
Evidence transformation
* *
************************************************************************
-}
data StopOrContinue a
= ContinueWith a -- The constraint was not solved, although it may have
-- been rewritten
| Stop CtEvidence -- The (rewritten) constraint was solved
SDoc -- Tells how it was solved
-- Any new sub-goals have been put on the work list
instance Functor StopOrContinue where
fmap f (ContinueWith x) = ContinueWith (f x)
fmap _ (Stop ev s) = Stop ev s
instance Outputable a => Outputable (StopOrContinue a) where
ppr (Stop ev s) = text "Stop" <> parens s <+> ppr ev
ppr (ContinueWith w) = text "ContinueWith" <+> ppr w
continueWith :: a -> TcS (StopOrContinue a)
continueWith = return . ContinueWith
stopWith :: CtEvidence -> String -> TcS (StopOrContinue a)
stopWith ev s = return (Stop ev (text s))
andWhenContinue :: TcS (StopOrContinue a)
-> (a -> TcS (StopOrContinue b))
-> TcS (StopOrContinue b)
andWhenContinue tcs1 tcs2
= do { r <- tcs1
; case r of
Stop ev s -> return (Stop ev s)
ContinueWith ct -> tcs2 ct }
infixr 0 `andWhenContinue` -- allow chaining with ($)
rewriteEvidence :: CtEvidence -- old evidence
-> TcPredType -- new predicate
-> TcCoercion -- Of type :: new predicate ~ <type of old evidence>
-> TcS (StopOrContinue CtEvidence)
-- Returns Just new_ev iff either (i) 'co' is reflexivity
-- or (ii) 'co' is not reflexivity, and 'new_pred' not cached
-- In either case, there is nothing new to do with new_ev
{-
rewriteEvidence old_ev new_pred co
Main purpose: create new evidence for new_pred;
unless new_pred is cached already
* Returns a new_ev : new_pred, with same wanted/given/derived flag as old_ev
* If old_ev was wanted, create a binding for old_ev, in terms of new_ev
* If old_ev was given, AND not cached, create a binding for new_ev, in terms of old_ev
* Returns Nothing if new_ev is already cached
Old evidence New predicate is Return new evidence
flavour of same flavor
-------------------------------------------------------------------
Wanted Already solved or in inert Nothing
or Derived Not Just new_evidence
Given Already in inert Nothing
Not Just new_evidence
Note [Rewriting with Refl]
~~~~~~~~~~~~~~~~~~~~~~~~~~
If the coercion is just reflexivity then you may re-use the same
variable. But be careful! Although the coercion is Refl, new_pred
may reflect the result of unification alpha := ty, so new_pred might
not _look_ the same as old_pred, and it's vital to proceed from now on
using new_pred.
The flattener preserves type synonyms, so they should appear in new_pred
as well as in old_pred; that is important for good error messages.
-}
rewriteEvidence old_ev@(CtDerived {}) new_pred _co
= -- If derived, don't even look at the coercion.
-- This is very important, DO NOT re-order the equations for
-- rewriteEvidence to put the isTcReflCo test first!
-- Why? Because for *Derived* constraints, c, the coercion, which
-- was produced by flattening, may contain suspended calls to
-- (ctEvTerm c), which fails for Derived constraints.
-- (Getting this wrong caused Trac #7384.)
continueWith (old_ev { ctev_pred = new_pred })
rewriteEvidence old_ev new_pred co
| isTcReflCo co -- See Note [Rewriting with Refl]
= continueWith (old_ev { ctev_pred = new_pred })
rewriteEvidence ev@(CtGiven { ctev_evar = old_evar , ctev_loc = loc }) new_pred co
= do { new_ev <- newGivenEvVar loc (new_pred, new_tm)
; continueWith new_ev }
where
-- mkEvCast optimises ReflCo
new_tm = mkEvCast (EvId old_evar) (tcDowngradeRole Representational
(ctEvRole ev)
(mkTcSymCo co))
rewriteEvidence ev@(CtWanted { ctev_dest = dest
, ctev_loc = loc }) new_pred co
= do { mb_new_ev <- newWanted loc new_pred
; MASSERT( tcCoercionRole co == ctEvRole ev )
; setWantedEvTerm dest
(mkEvCast (getEvTerm mb_new_ev)
(tcDowngradeRole Representational (ctEvRole ev) co))
; case mb_new_ev of
Fresh new_ev -> continueWith new_ev
Cached _ -> stopWith ev "Cached wanted" }
rewriteEqEvidence :: CtEvidence -- Old evidence :: olhs ~ orhs (not swapped)
-- or orhs ~ olhs (swapped)
-> SwapFlag
-> TcType -> TcType -- New predicate nlhs ~ nrhs
-- Should be zonked, because we use typeKind on nlhs/nrhs
-> TcCoercion -- lhs_co, of type :: nlhs ~ olhs
-> TcCoercion -- rhs_co, of type :: nrhs ~ orhs
-> TcS (StopOrContinue CtEvidence) -- Of type nlhs ~ nrhs
-- For (rewriteEqEvidence (Given g olhs orhs) False nlhs nrhs lhs_co rhs_co)
-- we generate
-- If not swapped
-- g1 : nlhs ~ nrhs = lhs_co ; g ; sym rhs_co
-- If 'swapped'
-- g1 : nlhs ~ nrhs = lhs_co ; Sym g ; sym rhs_co
--
-- For (Wanted w) we do the dual thing.
-- New w1 : nlhs ~ nrhs
-- If not swapped
-- w : olhs ~ orhs = sym lhs_co ; w1 ; rhs_co
-- If swapped
-- w : orhs ~ olhs = sym rhs_co ; sym w1 ; lhs_co
--
-- It's all a form of rewwriteEvidence, specialised for equalities
rewriteEqEvidence old_ev swapped nlhs nrhs lhs_co rhs_co
| CtDerived {} <- old_ev -- Don't force the evidence for a Derived
= continueWith (old_ev { ctev_pred = new_pred })
| NotSwapped <- swapped
, isTcReflCo lhs_co -- See Note [Rewriting with Refl]
, isTcReflCo rhs_co
= continueWith (old_ev { ctev_pred = new_pred })
| CtGiven { ctev_evar = old_evar } <- old_ev
= do { let new_tm = EvCoercion (lhs_co
`mkTcTransCo` maybeSym swapped (mkTcCoVarCo old_evar)
`mkTcTransCo` mkTcSymCo rhs_co)
; new_ev <- newGivenEvVar loc' (new_pred, new_tm)
; continueWith new_ev }
| CtWanted { ctev_dest = dest } <- old_ev
= do { (new_ev, hole_co) <- newWantedEq loc' (ctEvRole old_ev) nlhs nrhs
; let co = maybeSym swapped $
mkSymCo lhs_co
`mkTransCo` hole_co
`mkTransCo` rhs_co
; setWantedEq dest co
; traceTcS "rewriteEqEvidence" (vcat [ppr old_ev, ppr nlhs, ppr nrhs, ppr co])
; continueWith new_ev }
| otherwise
= panic "rewriteEvidence"
where
new_pred = mkTcEqPredLikeEv old_ev nlhs nrhs
-- equality is like a type class. Bumping the depth is necessary because
-- of recursive newtypes, where "reducing" a newtype can actually make
-- it bigger. See Note [Newtypes can blow the stack].
loc = ctEvLoc old_ev
loc' = bumpCtLocDepth loc
{- Note [unifyWanted and unifyDerived]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When decomposing equalities we often create new wanted constraints for
(s ~ t). But what if s=t? Then it'd be faster to return Refl right away.
Similar remarks apply for Derived.
Rather than making an equality test (which traverses the structure of the
type, perhaps fruitlessly, unifyWanted traverses the common structure, and
bales out when it finds a difference by creating a new Wanted constraint.
But where it succeeds in finding common structure, it just builds a coercion
to reflect it.
-}
unifyWanted :: CtLoc -> Role
-> TcType -> TcType -> TcS Coercion
-- Return coercion witnessing the equality of the two types,
-- emitting new work equalities where necessary to achieve that
-- Very good short-cut when the two types are equal, or nearly so
-- See Note [unifyWanted and unifyDerived]
-- The returned coercion's role matches the input parameter
unifyWanted loc Phantom ty1 ty2
= do { kind_co <- unifyWanted loc Nominal (typeKind ty1) (typeKind ty2)
; return (mkPhantomCo kind_co ty1 ty2) }
unifyWanted loc role orig_ty1 orig_ty2
= go orig_ty1 orig_ty2
where
go ty1 ty2 | Just ty1' <- coreView ty1 = go ty1' ty2
go ty1 ty2 | Just ty2' <- coreView ty2 = go ty1 ty2'
go (ForAllTy (Anon s1) t1) (ForAllTy (Anon s2) t2)
= do { co_s <- unifyWanted loc role s1 s2
; co_t <- unifyWanted loc role t1 t2
; return (mkTyConAppCo role funTyCon [co_s,co_t]) }
go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
| tc1 == tc2, tys1 `equalLength` tys2
, isInjectiveTyCon tc1 role -- don't look under newtypes at Rep equality
= do { cos <- zipWith3M (unifyWanted loc)
(tyConRolesX role tc1) tys1 tys2
; return (mkTyConAppCo role tc1 cos) }
go (TyVarTy tv) ty2
= do { mb_ty <- isFilledMetaTyVar_maybe tv
; case mb_ty of
Just ty1' -> go ty1' ty2
Nothing -> bale_out }
go ty1 (TyVarTy tv)
= do { mb_ty <- isFilledMetaTyVar_maybe tv
; case mb_ty of
Just ty2' -> go ty1 ty2'
Nothing -> bale_out }
go ty1@(CoercionTy {}) (CoercionTy {})
= return (mkReflCo role ty1) -- we just don't care about coercions!
go _ _ = bale_out
bale_out = do { (new_ev, co) <- newWantedEq loc role orig_ty1 orig_ty2
; emitWorkNC [new_ev]
; return co }
unifyDeriveds :: CtLoc -> [Role] -> [TcType] -> [TcType] -> TcS ()
-- See Note [unifyWanted and unifyDerived]
unifyDeriveds loc roles tys1 tys2 = zipWith3M_ (unify_derived loc) roles tys1 tys2
unifyDerived :: CtLoc -> Role -> Pair TcType -> TcS ()
-- See Note [unifyWanted and unifyDerived]
unifyDerived loc role (Pair ty1 ty2) = unify_derived loc role ty1 ty2
unify_derived :: CtLoc -> Role -> TcType -> TcType -> TcS ()
-- Create new Derived and put it in the work list
-- Should do nothing if the two types are equal
-- See Note [unifyWanted and unifyDerived]
unify_derived _ Phantom _ _ = return ()
unify_derived loc role orig_ty1 orig_ty2
= go orig_ty1 orig_ty2
where
go ty1 ty2 | Just ty1' <- coreView ty1 = go ty1' ty2
go ty1 ty2 | Just ty2' <- coreView ty2 = go ty1 ty2'
go (ForAllTy (Anon s1) t1) (ForAllTy (Anon s2) t2)
= do { unify_derived loc role s1 s2
; unify_derived loc role t1 t2 }
go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
| tc1 == tc2, tys1 `equalLength` tys2
, isInjectiveTyCon tc1 role
= unifyDeriveds loc (tyConRolesX role tc1) tys1 tys2
go (TyVarTy tv) ty2
= do { mb_ty <- isFilledMetaTyVar_maybe tv
; case mb_ty of
Just ty1' -> go ty1' ty2
Nothing -> bale_out }
go ty1 (TyVarTy tv)
= do { mb_ty <- isFilledMetaTyVar_maybe tv
; case mb_ty of
Just ty2' -> go ty1 ty2'
Nothing -> bale_out }
go _ _ = bale_out
bale_out = emitNewDerivedEq loc role orig_ty1 orig_ty2
maybeSym :: SwapFlag -> TcCoercion -> TcCoercion
maybeSym IsSwapped co = mkTcSymCo co
maybeSym NotSwapped co = co
| oldmanmike/ghc | compiler/typecheck/TcCanonical.hs | bsd-3-clause | 81,906 | 188 | 30 | 23,101 | 9,520 | 5,251 | 4,269 | -1 | -1 |
module Statsd.Test.Utils (utilsSpec) where
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
import Statsd.Utils
utilsSpec :: Spec
utilsSpec = do
describe "sanitizeKeyName" $ modifyMaxSize (+1000) sanitizeKeyNameSpec
sanitizeKeyNameSpec :: Spec
sanitizeKeyNameSpec = do
prop "never makes a key longer" $
\s -> length (sanitizeKeyName s) <= length s
prop "only returns valid chars" $ do
let validChars = "_-." ++ ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9']
all (`elem` validChars) . sanitizeKeyName
it "keeps uppercase, lowercase and numbers"
(sanitizeKeyName "aB0" `shouldBe` "aB0")
it "replaces a chain of spaces with a underscore"
(sanitizeKeyName "hello world" `shouldBe` "hello_world")
it "replaces a forwardslash with a dash"
(sanitizeKeyName "hello/world" `shouldBe` "hello-world")
| ant1441/haskell-statsd | test/Statsd/Test/Utils.hs | bsd-3-clause | 882 | 0 | 16 | 181 | 225 | 118 | 107 | 21 | 1 |
module DynamicTaskDuplicate where
import Data.ByteString.Lazy.Char8 as BLC
import Control.Distributed.Task.Types.TaskTypes
task :: Task
task = Prelude.map (\s -> s `BLC.append` (BLC.pack " - ") `BLC.append` s)
| michaxm/task-distribution | resources/DynamicTaskDuplicate.hs | bsd-3-clause | 213 | 0 | 12 | 28 | 68 | 43 | 25 | 5 | 1 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
import Language.Haskell.Liquid.Prelude
insert key value [] = [(key, value)]
insert _ _ _ = error ""
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/duplicate-bind.hs | bsd-3-clause | 163 | 1 | 6 | 35 | 52 | 27 | 25 | 5 | 1 |
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-2006
RnEnv contains functions which convert RdrNames into Names.
-}
{-# LANGUAGE CPP, MultiWayIf, NamedFieldPuns #-}
module RnEnv (
newTopSrcBinder,
lookupLocatedTopBndrRn, lookupTopBndrRn,
lookupLocatedOccRn, lookupOccRn, lookupOccRn_maybe,
lookupLocalOccRn_maybe, lookupInfoOccRn,
lookupLocalOccThLvl_maybe, lookupLocalOccRn,
lookupTypeOccRn, lookupKindOccRn,
lookupGlobalOccRn, lookupGlobalOccRn_maybe,
lookupOccRn_overloaded, lookupGlobalOccRn_overloaded, lookupExactOcc,
ChildLookupResult(..),
lookupSubBndrOcc_helper,
combineChildLookupResult, -- Called by lookupChildrenExport
HsSigCtxt(..), lookupLocalTcNames, lookupSigOccRn,
lookupSigCtxtOccRn,
lookupInstDeclBndr, lookupRecFieldOcc, lookupFamInstName,
lookupConstructorFields,
lookupGreAvailRn,
-- Rebindable Syntax
lookupSyntaxName, lookupSyntaxName', lookupSyntaxNames,
lookupIfThenElse,
-- Constructing usage information
addUsedGRE, addUsedGREs, addUsedDataCons,
dataTcOccs, --TODO: Move this somewhere, into utils?
) where
#include "HsVersions.h"
import GhcPrelude
import LoadIface ( loadInterfaceForName, loadSrcInterface_maybe )
import IfaceEnv
import HsSyn
import RdrName
import HscTypes
import TcEnv
import TcRnMonad
import RdrHsSyn ( setRdrNameSpace )
import TysWiredIn
import Name
import NameSet
import NameEnv
import Avail
import Module
import ConLike
import DataCon
import TyCon
import ErrUtils ( MsgDoc )
import PrelNames ( rOOT_MAIN )
import BasicTypes ( pprWarningTxtForMsg, TopLevelFlag(..))
import SrcLoc
import Outputable
import Util
import Maybes
import DynFlags
import FastString
import Control.Monad
import ListSetOps ( minusList )
import qualified GHC.LanguageExtensions as LangExt
import RnUnbound
import RnUtils
import Data.Maybe (isJust)
import qualified Data.Semigroup as Semi
{-
*********************************************************
* *
Source-code binders
* *
*********************************************************
Note [Signature lazy interface loading]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC's lazy interface loading can be a bit confusing, so this Note is an
empirical description of what happens in one interesting case. When
compiling a signature module against an its implementation, we do NOT
load interface files associated with its names until after the type
checking phase. For example:
module ASig where
data T
f :: T -> T
Suppose we compile this with -sig-of "A is ASig":
module B where
data T = T
f T = T
module A(module B) where
import B
During type checking, we'll load A.hi because we need to know what the
RdrEnv for the module is, but we DO NOT load the interface for B.hi!
It's wholly unnecessary: our local definition 'data T' in ASig is all
the information we need to finish type checking. This is contrast to
type checking of ordinary Haskell files, in which we would not have the
local definition "data T" and would need to consult B.hi immediately.
(Also, this situation never occurs for hs-boot files, since you're not
allowed to reexport from another module.)
After type checking, we then check that the types we provided are
consistent with the backing implementation (in checkHiBootOrHsigIface).
At this point, B.hi is loaded, because we need something to compare
against.
I discovered this behavior when trying to figure out why type class
instances for Data.Map weren't in the EPS when I was type checking a
test very much like ASig (sigof02dm): the associated interface hadn't
been loaded yet! (The larger issue is a moot point, since an instance
declared in a signature can never be a duplicate.)
This behavior might change in the future. Consider this
alternate module B:
module B where
{-# DEPRECATED T, f "Don't use" #-}
data T = T
f T = T
One might conceivably want to report deprecation warnings when compiling
ASig with -sig-of B, in which case we need to look at B.hi to find the
deprecation warnings during renaming. At the moment, you don't get any
warning until you use the identifier further downstream. This would
require adjusting addUsedGRE so that during signature compilation,
we do not report deprecation warnings for LocalDef. See also
Note [Handling of deprecations]
-}
newTopSrcBinder :: Located RdrName -> RnM Name
newTopSrcBinder (L loc rdr_name)
| Just name <- isExact_maybe rdr_name
= -- This is here to catch
-- (a) Exact-name binders created by Template Haskell
-- (b) The PrelBase defn of (say) [] and similar, for which
-- the parser reads the special syntax and returns an Exact RdrName
-- We are at a binding site for the name, so check first that it
-- the current module is the correct one; otherwise GHC can get
-- very confused indeed. This test rejects code like
-- data T = (,) Int Int
-- unless we are in GHC.Tup
if isExternalName name then
do { this_mod <- getModule
; unless (this_mod == nameModule name)
(addErrAt loc (badOrigBinding rdr_name))
; return name }
else -- See Note [Binders in Template Haskell] in Convert.hs
do { this_mod <- getModule
; externaliseName this_mod name }
| Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
= do { this_mod <- getModule
; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
(addErrAt loc (badOrigBinding rdr_name))
-- When reading External Core we get Orig names as binders,
-- but they should agree with the module gotten from the monad
--
-- We can get built-in syntax showing up here too, sadly. If you type
-- data T = (,,,)
-- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
-- uses setRdrNameSpace to make it into a data constructors. At that point
-- the nice Exact name for the TyCon gets swizzled to an Orig name.
-- Hence the badOrigBinding error message.
--
-- Except for the ":Main.main = ..." definition inserted into
-- the Main module; ugh!
-- Because of this latter case, we call newGlobalBinder with a module from
-- the RdrName, not from the environment. In principle, it'd be fine to
-- have an arbitrary mixture of external core definitions in a single module,
-- (apart from module-initialisation issues, perhaps).
; newGlobalBinder rdr_mod rdr_occ loc }
| otherwise
= do { when (isQual rdr_name)
(addErrAt loc (badQualBndrErr rdr_name))
-- Binders should not be qualified; if they are, and with a different
-- module name, we we get a confusing "M.T is not in scope" error later
; stage <- getStage
; if isBrackStage stage then
-- We are inside a TH bracket, so make an *Internal* name
-- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
do { uniq <- newUnique
; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
else
do { this_mod <- getModule
; traceRn "newTopSrcBinder" (ppr this_mod $$ ppr rdr_name $$ ppr loc)
; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }
}
{-
*********************************************************
* *
Source code occurrences
* *
*********************************************************
Looking up a name in the RnEnv.
Note [Type and class operator definitions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We want to reject all of these unless we have -XTypeOperators (Trac #3265)
data a :*: b = ...
class a :*: b where ...
data (:*:) a b = ....
class (:*:) a b where ...
The latter two mean that we are not just looking for a
*syntactically-infix* declaration, but one that uses an operator
OccName. We use OccName.isSymOcc to detect that case, which isn't
terribly efficient, but there seems to be no better way.
-}
-- Can be made to not be exposed
-- Only used unwrapped in rnAnnProvenance
lookupTopBndrRn :: RdrName -> RnM Name
lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
case nopt of
Just n' -> return n'
Nothing -> do traceRn "lookupTopBndrRn fail" (ppr n)
unboundName WL_LocalTop n
lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
-- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
-- and there may be several imported 'f's too, which must not confuse us.
-- For example, this is OK:
-- import Foo( f )
-- infix 9 f -- The 'f' here does not need to be qualified
-- f x = x -- Nor here, of course
-- So we have to filter out the non-local ones.
--
-- A separate function (importsFromLocalDecls) reports duplicate top level
-- decls, so here it's safe just to choose an arbitrary one.
--
-- There should never be a qualified name in a binding position in Haskell,
-- but there can be if we have read in an external-Core file.
-- The Haskell parser checks for the illegal qualified name in Haskell
-- source files, so we don't need to do so here.
lookupTopBndrRn_maybe rdr_name =
lookupExactOrOrig rdr_name Just $
do { -- Check for operators in type or class declarations
-- See Note [Type and class operator definitions]
let occ = rdrNameOcc rdr_name
; when (isTcOcc occ && isSymOcc occ)
(do { op_ok <- xoptM LangExt.TypeOperators
; unless op_ok (addErr (opDeclErr rdr_name)) })
; env <- getGlobalRdrEnv
; case filter isLocalGRE (lookupGRE_RdrName rdr_name env) of
[gre] -> return (Just (gre_name gre))
_ -> return Nothing -- Ambiguous (can't happen) or unbound
}
-----------------------------------------------
-- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
-- This adds an error if the name cannot be found.
lookupExactOcc :: Name -> RnM Name
lookupExactOcc name
= do { result <- lookupExactOcc_either name
; case result of
Left err -> do { addErr err
; return name }
Right name' -> return name' }
-- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
-- This never adds an error, but it may return one.
lookupExactOcc_either :: Name -> RnM (Either MsgDoc Name)
-- See Note [Looking up Exact RdrNames]
lookupExactOcc_either name
| Just thing <- wiredInNameTyThing_maybe name
, Just tycon <- case thing of
ATyCon tc -> Just tc
AConLike (RealDataCon dc) -> Just (dataConTyCon dc)
_ -> Nothing
, isTupleTyCon tycon
= do { checkTupSize (tyConArity tycon)
; return (Right name) }
| isExternalName name
= return (Right name)
| otherwise
= do { env <- getGlobalRdrEnv
; let -- See Note [Splicing Exact names]
main_occ = nameOccName name
demoted_occs = case demoteOccName main_occ of
Just occ -> [occ]
Nothing -> []
gres = [ gre | occ <- main_occ : demoted_occs
, gre <- lookupGlobalRdrEnv env occ
, gre_name gre == name ]
; case gres of
[gre] -> return (Right (gre_name gre))
[] -> -- See Note [Splicing Exact names]
do { lcl_env <- getLocalRdrEnv
; if name `inLocalRdrEnvScope` lcl_env
then return (Right name)
else
do { th_topnames_var <- fmap tcg_th_topnames getGblEnv
; th_topnames <- readTcRef th_topnames_var
; if name `elemNameSet` th_topnames
then return (Right name)
else return (Left exact_nm_err)
}
}
gres -> return (Left (sameNameErr gres)) -- Ugh! See Note [Template Haskell ambiguity]
}
where
exact_nm_err = hang (text "The exact Name" <+> quotes (ppr name) <+> ptext (sLit "is not in scope"))
2 (vcat [ text "Probable cause: you used a unique Template Haskell name (NameU), "
, text "perhaps via newName, but did not bind it"
, text "If that's it, then -ddump-splices might be useful" ])
sameNameErr :: [GlobalRdrElt] -> MsgDoc
sameNameErr [] = panic "addSameNameErr: empty list"
sameNameErr gres@(_ : _)
= hang (text "Same exact name in multiple name-spaces:")
2 (vcat (map pp_one sorted_names) $$ th_hint)
where
sorted_names = sortWith nameSrcLoc (map gre_name gres)
pp_one name
= hang (pprNameSpace (occNameSpace (getOccName name))
<+> quotes (ppr name) <> comma)
2 (text "declared at:" <+> ppr (nameSrcLoc name))
th_hint = vcat [ text "Probable cause: you bound a unique Template Haskell name (NameU),"
, text "perhaps via newName, in different name-spaces."
, text "If that's it, then -ddump-splices might be useful" ]
-----------------------------------------------
lookupInstDeclBndr :: Name -> SDoc -> RdrName -> RnM Name
-- This is called on the method name on the left-hand side of an
-- instance declaration binding. eg. instance Functor T where
-- fmap = ...
-- ^^^^ called on this
-- Regardless of how many unqualified fmaps are in scope, we want
-- the one that comes from the Functor class.
--
-- Furthermore, note that we take no account of whether the
-- name is only in scope qualified. I.e. even if method op is
-- in scope as M.op, we still allow plain 'op' on the LHS of
-- an instance decl
--
-- The "what" parameter says "method" or "associated type",
-- depending on what we are looking up
lookupInstDeclBndr cls what rdr
= do { when (isQual rdr)
(addErr (badQualBndrErr rdr))
-- In an instance decl you aren't allowed
-- to use a qualified name for the method
-- (Although it'd make perfect sense.)
; mb_name <- lookupSubBndrOcc
False -- False => we don't give deprecated
-- warnings when a deprecated class
-- method is defined. We only warn
-- when it's used
cls doc rdr
; case mb_name of
Left err -> do { addErr err; return (mkUnboundNameRdr rdr) }
Right nm -> return nm }
where
doc = what <+> text "of class" <+> quotes (ppr cls)
-----------------------------------------------
lookupFamInstName :: Maybe Name -> Located RdrName
-> RnM (Located Name)
-- Used for TyData and TySynonym family instances only,
-- See Note [Family instance binders]
lookupFamInstName (Just cls) tc_rdr -- Associated type; c.f RnBinds.rnMethodBind
= wrapLocM (lookupInstDeclBndr cls (text "associated type")) tc_rdr
lookupFamInstName Nothing tc_rdr -- Family instance; tc_rdr is an *occurrence*
= lookupLocatedOccRn tc_rdr
-----------------------------------------------
lookupConstructorFields :: Name -> RnM [FieldLabel]
-- Look up the fields of a given constructor
-- * For constructors from this module, use the record field env,
-- which is itself gathered from the (as yet un-typechecked)
-- data type decls
--
-- * For constructors from imported modules, use the *type* environment
-- since imported modles are already compiled, the info is conveniently
-- right there
lookupConstructorFields con_name
= do { this_mod <- getModule
; if nameIsLocalOrFrom this_mod con_name then
do { field_env <- getRecFieldEnv
; traceTc "lookupCF" (ppr con_name $$ ppr (lookupNameEnv field_env con_name) $$ ppr field_env)
; return (lookupNameEnv field_env con_name `orElse` []) }
else
do { con <- tcLookupConLike con_name
; traceTc "lookupCF 2" (ppr con)
; return (conLikeFieldLabels con) } }
-- In CPS style as `RnM r` is monadic
lookupExactOrOrig :: RdrName -> (Name -> r) -> RnM r -> RnM r
lookupExactOrOrig rdr_name res k
| Just n <- isExact_maybe rdr_name -- This happens in derived code
= res <$> lookupExactOcc n
| Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
= res <$> lookupOrig rdr_mod rdr_occ
| otherwise = k
-----------------------------------------------
-- Used for record construction and pattern matching
-- When the -XDisambiguateRecordFields flag is on, take account of the
-- constructor name to disambiguate which field to use; it's just the
-- same as for instance decls
--
-- NB: Consider this:
-- module Foo where { data R = R { fld :: Int } }
-- module Odd where { import Foo; fld x = x { fld = 3 } }
-- Arguably this should work, because the reference to 'fld' is
-- unambiguous because there is only one field id 'fld' in scope.
-- But currently it's rejected.
lookupRecFieldOcc :: Maybe Name -- Nothing => just look it up as usual
-- Just tycon => use tycon to disambiguate
-> SDoc -> RdrName
-> RnM Name
lookupRecFieldOcc parent doc rdr_name
| Just tc_name <- parent
= do { mb_name <- lookupSubBndrOcc True tc_name doc rdr_name
; case mb_name of
Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) }
Right n -> return n }
| otherwise
-- This use of Global is right as we are looking up a selector which
-- can only be defined at the top level.
= lookupGlobalOccRn rdr_name
-- | Used in export lists to lookup the children.
lookupSubBndrOcc_helper :: Bool -> Bool -> Name -> RdrName
-> RnM ChildLookupResult
lookupSubBndrOcc_helper must_have_parent warn_if_deprec parent rdr_name
| isUnboundName parent
-- Avoid an error cascade
= return (FoundName NoParent (mkUnboundNameRdr rdr_name))
| otherwise = do
gre_env <- getGlobalRdrEnv
let original_gres = lookupGlobalRdrEnv gre_env (rdrNameOcc rdr_name)
-- Disambiguate the lookup based on the parent information.
-- The remaining GREs are things that we *could* export here, note that
-- this includes things which have `NoParent`. Those are sorted in
-- `checkPatSynParent`.
traceRn "parent" (ppr parent)
traceRn "lookupExportChild original_gres:" (ppr original_gres)
traceRn "lookupExportChild picked_gres:" (ppr $ picked_gres original_gres)
case picked_gres original_gres of
NoOccurrence ->
noMatchingParentErr original_gres
UniqueOccurrence g ->
if must_have_parent then noMatchingParentErr original_gres
else checkFld g
DisambiguatedOccurrence g ->
checkFld g
AmbiguousOccurrence gres ->
mkNameClashErr gres
where
-- Convert into FieldLabel if necessary
checkFld :: GlobalRdrElt -> RnM ChildLookupResult
checkFld g@GRE{gre_name, gre_par} = do
addUsedGRE warn_if_deprec g
return $ case gre_par of
FldParent _ mfs ->
FoundFL (fldParentToFieldLabel gre_name mfs)
_ -> FoundName gre_par gre_name
fldParentToFieldLabel :: Name -> Maybe FastString -> FieldLabel
fldParentToFieldLabel name mfs =
case mfs of
Nothing ->
let fs = occNameFS (nameOccName name)
in FieldLabel fs False name
Just fs -> FieldLabel fs True name
-- Called when we find no matching GREs after disambiguation but
-- there are three situations where this happens.
-- 1. There were none to begin with.
-- 2. None of the matching ones were the parent but
-- a. They were from an overloaded record field so we can report
-- a better error
-- b. The original lookup was actually ambiguous.
-- For example, the case where overloading is off and two
-- record fields are in scope from different record
-- constructors, neither of which is the parent.
noMatchingParentErr :: [GlobalRdrElt] -> RnM ChildLookupResult
noMatchingParentErr original_gres = do
overload_ok <- xoptM LangExt.DuplicateRecordFields
case original_gres of
[] -> return NameNotFound
[g] -> return $ IncorrectParent parent
(gre_name g) (ppr $ gre_name g)
[p | Just p <- [getParent g]]
gss@(g:_:_) ->
if all isRecFldGRE gss && overload_ok
then return $
IncorrectParent parent
(gre_name g)
(ppr $ expectJust "noMatchingParentErr" (greLabel g))
[p | x <- gss, Just p <- [getParent x]]
else mkNameClashErr gss
mkNameClashErr :: [GlobalRdrElt] -> RnM ChildLookupResult
mkNameClashErr gres = do
addNameClashErrRn rdr_name gres
return (FoundName (gre_par (head gres)) (gre_name (head gres)))
getParent :: GlobalRdrElt -> Maybe Name
getParent (GRE { gre_par = p } ) =
case p of
ParentIs cur_parent -> Just cur_parent
FldParent { par_is = cur_parent } -> Just cur_parent
NoParent -> Nothing
picked_gres :: [GlobalRdrElt] -> DisambigInfo
picked_gres gres
| isUnqual rdr_name
= mconcat (map right_parent gres)
| otherwise
= mconcat (map right_parent (pickGREs rdr_name gres))
right_parent :: GlobalRdrElt -> DisambigInfo
right_parent p
| Just cur_parent <- getParent p
= if parent == cur_parent
then DisambiguatedOccurrence p
else NoOccurrence
| otherwise
= UniqueOccurrence p
-- This domain specific datatype is used to record why we decided it was
-- possible that a GRE could be exported with a parent.
data DisambigInfo
= NoOccurrence
-- The GRE could never be exported. It has the wrong parent.
| UniqueOccurrence GlobalRdrElt
-- The GRE has no parent. It could be a pattern synonym.
| DisambiguatedOccurrence GlobalRdrElt
-- The parent of the GRE is the correct parent
| AmbiguousOccurrence [GlobalRdrElt]
-- For example, two normal identifiers with the same name are in
-- scope. They will both be resolved to "UniqueOccurrence" and the
-- monoid will combine them to this failing case.
instance Outputable DisambigInfo where
ppr NoOccurrence = text "NoOccurence"
ppr (UniqueOccurrence gre) = text "UniqueOccurrence:" <+> ppr gre
ppr (DisambiguatedOccurrence gre) = text "DiambiguatedOccurrence:" <+> ppr gre
ppr (AmbiguousOccurrence gres) = text "Ambiguous:" <+> ppr gres
instance Semi.Semigroup DisambigInfo where
-- This is the key line: We prefer disambiguated occurrences to other
-- names.
_ <> DisambiguatedOccurrence g' = DisambiguatedOccurrence g'
DisambiguatedOccurrence g' <> _ = DisambiguatedOccurrence g'
NoOccurrence <> m = m
m <> NoOccurrence = m
UniqueOccurrence g <> UniqueOccurrence g'
= AmbiguousOccurrence [g, g']
UniqueOccurrence g <> AmbiguousOccurrence gs
= AmbiguousOccurrence (g:gs)
AmbiguousOccurrence gs <> UniqueOccurrence g'
= AmbiguousOccurrence (g':gs)
AmbiguousOccurrence gs <> AmbiguousOccurrence gs'
= AmbiguousOccurrence (gs ++ gs')
instance Monoid DisambigInfo where
mempty = NoOccurrence
mappend = (Semi.<>)
-- Lookup SubBndrOcc can never be ambiguous
--
-- Records the result of looking up a child.
data ChildLookupResult
= NameNotFound -- We couldn't find a suitable name
| IncorrectParent Name -- Parent
Name -- Name of thing we were looking for
SDoc -- How to print the name
[Name] -- List of possible parents
| FoundName Parent Name -- We resolved to a normal name
| FoundFL FieldLabel -- We resolved to a FL
-- | Specialised version of msum for RnM ChildLookupResult
combineChildLookupResult :: [RnM ChildLookupResult] -> RnM ChildLookupResult
combineChildLookupResult [] = return NameNotFound
combineChildLookupResult (x:xs) = do
res <- x
case res of
NameNotFound -> combineChildLookupResult xs
_ -> return res
instance Outputable ChildLookupResult where
ppr NameNotFound = text "NameNotFound"
ppr (FoundName p n) = text "Found:" <+> ppr p <+> ppr n
ppr (FoundFL fls) = text "FoundFL:" <+> ppr fls
ppr (IncorrectParent p n td ns) = text "IncorrectParent"
<+> hsep [ppr p, ppr n, td, ppr ns]
lookupSubBndrOcc :: Bool
-> Name -- Parent
-> SDoc
-> RdrName
-> RnM (Either MsgDoc Name)
-- Find all the things the rdr-name maps to
-- and pick the one with the right parent namep
lookupSubBndrOcc warn_if_deprec the_parent doc rdr_name = do
res <-
lookupExactOrOrig rdr_name (FoundName NoParent) $
-- This happens for built-in classes, see mod052 for example
lookupSubBndrOcc_helper True warn_if_deprec the_parent rdr_name
case res of
NameNotFound -> return (Left (unknownSubordinateErr doc rdr_name))
FoundName _p n -> return (Right n)
FoundFL fl -> return (Right (flSelector fl))
IncorrectParent {} -> return $ Left (unknownSubordinateErr doc rdr_name)
{-
Note [Family instance binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data family F a
data instance F T = X1 | X2
The 'data instance' decl has an *occurrence* of F (and T), and *binds*
X1 and X2. (This is unlike a normal data type declaration which would
bind F too.) So we want an AvailTC F [X1,X2].
Now consider a similar pair:
class C a where
data G a
instance C S where
data G S = Y1 | Y2
The 'data G S' *binds* Y1 and Y2, and has an *occurrence* of G.
But there is a small complication: in an instance decl, we don't use
qualified names on the LHS; instead we use the class to disambiguate.
Thus:
module M where
import Blib( G )
class C a where
data G a
instance C S where
data G S = Y1 | Y2
Even though there are two G's in scope (M.G and Blib.G), the occurrence
of 'G' in the 'instance C S' decl is unambiguous, because C has only
one associated type called G. This is exactly what happens for methods,
and it is only consistent to do the same thing for types. That's the
role of the function lookupTcdName; the (Maybe Name) give the class of
the encloseing instance decl, if any.
Note [Looking up Exact RdrNames]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Exact RdrNames are generated by Template Haskell. See Note [Binders
in Template Haskell] in Convert.
For data types and classes have Exact system Names in the binding
positions for constructors, TyCons etc. For example
[d| data T = MkT Int |]
when we splice in and Convert to HsSyn RdrName, we'll get
data (Exact (system Name "T")) = (Exact (system Name "MkT")) ...
These System names are generated by Convert.thRdrName
But, constructors and the like need External Names, not System Names!
So we do the following
* In RnEnv.newTopSrcBinder we spot Exact RdrNames that wrap a
non-External Name, and make an External name for it. This is
the name that goes in the GlobalRdrEnv
* When looking up an occurrence of an Exact name, done in
RnEnv.lookupExactOcc, we find the Name with the right unique in the
GlobalRdrEnv, and use the one from the envt -- it will be an
External Name in the case of the data type/constructor above.
* Exact names are also use for purely local binders generated
by TH, such as \x_33. x_33
Both binder and occurrence are Exact RdrNames. The occurrence
gets looked up in the LocalRdrEnv by RnEnv.lookupOccRn, and
misses, because lookupLocalRdrEnv always returns Nothing for
an Exact Name. Now we fall through to lookupExactOcc, which
will find the Name is not in the GlobalRdrEnv, so we just use
the Exact supplied Name.
Note [Splicing Exact names]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the splice $(do { x <- newName "x"; return (VarE x) })
This will generate a (HsExpr RdrName) term that mentions the
Exact RdrName "x_56" (or whatever), but does not bind it. So
when looking such Exact names we want to check that it's in scope,
otherwise the type checker will get confused. To do this we need to
keep track of all the Names in scope, and the LocalRdrEnv does just that;
we consult it with RdrName.inLocalRdrEnvScope.
There is another wrinkle. With TH and -XDataKinds, consider
$( [d| data Nat = Zero
data T = MkT (Proxy 'Zero) |] )
After splicing, but before renaming we get this:
data Nat_77{tc} = Zero_78{d}
data T_79{tc} = MkT_80{d} (Proxy 'Zero_78{tc}) |] )
The occurrence of 'Zero in the data type for T has the right unique,
but it has a TcClsName name-space in its OccName. (This is set by
the ctxt_ns argument of Convert.thRdrName.) When we check that is
in scope in the GlobalRdrEnv, we need to look up the DataName namespace
too. (An alternative would be to make the GlobalRdrEnv also have
a Name -> GRE mapping.)
Note [Template Haskell ambiguity]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The GlobalRdrEnv invariant says that if
occ -> [gre1, ..., gren]
then the gres have distinct Names (INVARIANT 1 of GlobalRdrEnv).
This is guaranteed by extendGlobalRdrEnvRn (the dups check in add_gre).
So how can we get multiple gres in lookupExactOcc_maybe? Because in
TH we might use the same TH NameU in two different name spaces.
eg (Trac #7241):
$(newName "Foo" >>= \o -> return [DataD [] o [] [RecC o []] [''Show]])
Here we generate a type constructor and data constructor with the same
unique, but different name spaces.
It'd be nicer to rule this out in extendGlobalRdrEnvRn, but that would
mean looking up the OccName in every name-space, just in case, and that
seems a bit brutal. So it's just done here on lookup. But we might
need to revisit that choice.
Note [Usage for sub-bndrs]
~~~~~~~~~~~~~~~~~~~~~~~~~~
If you have this
import qualified M( C( f ) )
instance M.C T where
f x = x
then is the qualified import M.f used? Obviously yes.
But the RdrName used in the instance decl is unqualified. In effect,
we fill in the qualification by looking for f's whose class is M.C
But when adding to the UsedRdrNames we must make that qualification
explicit (saying "used M.f"), otherwise we get "Redundant import of M.f".
So we make up a suitable (fake) RdrName. But be careful
import qualified M
import M( C(f) )
instance C T where
f x = x
Here we want to record a use of 'f', not of 'M.f', otherwise
we'll miss the fact that the qualified import is redundant.
--------------------------------------------------
-- Occurrences
--------------------------------------------------
-}
lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
lookupLocatedOccRn = wrapLocM lookupOccRn
lookupLocalOccRn_maybe :: RdrName -> RnM (Maybe Name)
-- Just look in the local environment
lookupLocalOccRn_maybe rdr_name
= do { local_env <- getLocalRdrEnv
; return (lookupLocalRdrEnv local_env rdr_name) }
lookupLocalOccThLvl_maybe :: Name -> RnM (Maybe (TopLevelFlag, ThLevel))
-- Just look in the local environment
lookupLocalOccThLvl_maybe name
= do { lcl_env <- getLclEnv
; return (lookupNameEnv (tcl_th_bndrs lcl_env) name) }
-- lookupOccRn looks up an occurrence of a RdrName
lookupOccRn :: RdrName -> RnM Name
lookupOccRn rdr_name
= do { mb_name <- lookupOccRn_maybe rdr_name
; case mb_name of
Just name -> return name
Nothing -> reportUnboundName rdr_name }
-- Only used in one place, to rename pattern synonym binders.
-- See Note [Renaming pattern synonym variables] in RnBinds
lookupLocalOccRn :: RdrName -> RnM Name
lookupLocalOccRn rdr_name
= do { mb_name <- lookupLocalOccRn_maybe rdr_name
; case mb_name of
Just name -> return name
Nothing -> unboundName WL_LocalOnly rdr_name }
lookupKindOccRn :: RdrName -> RnM Name
-- Looking up a name occurring in a kind
lookupKindOccRn rdr_name
| isVarOcc (rdrNameOcc rdr_name) -- See Note [Promoted variables in types]
= badVarInType rdr_name
| otherwise
= do { typeintype <- xoptM LangExt.TypeInType
; if | typeintype -> lookupTypeOccRn rdr_name
-- With -XNoTypeInType, treat any usage of * in kinds as in scope
-- this is a dirty hack, but then again so was the old * kind.
| isStar rdr_name -> return starKindTyConName
| isUniStar rdr_name -> return unicodeStarKindTyConName
| otherwise -> lookupOccRn rdr_name }
-- lookupPromotedOccRn looks up an optionally promoted RdrName.
lookupTypeOccRn :: RdrName -> RnM Name
-- see Note [Demotion]
lookupTypeOccRn rdr_name
| isVarOcc (rdrNameOcc rdr_name) -- See Note [Promoted variables in types]
= badVarInType rdr_name
| otherwise
= do { mb_name <- lookupOccRn_maybe rdr_name
; case mb_name of {
Just name -> return name ;
Nothing -> do { dflags <- getDynFlags
; lookup_demoted rdr_name dflags } } }
lookup_demoted :: RdrName -> DynFlags -> RnM Name
lookup_demoted rdr_name dflags
| Just demoted_rdr <- demoteRdrName rdr_name
-- Maybe it's the name of a *data* constructor
= do { data_kinds <- xoptM LangExt.DataKinds
; if data_kinds
then do { mb_demoted_name <- lookupOccRn_maybe demoted_rdr
; case mb_demoted_name of
Nothing -> unboundNameX WL_Any rdr_name star_info
Just demoted_name ->
do { whenWOptM Opt_WarnUntickedPromotedConstructors $
addWarn
(Reason Opt_WarnUntickedPromotedConstructors)
(untickedPromConstrWarn demoted_name)
; return demoted_name } }
else do { -- We need to check if a data constructor of this name is
-- in scope to give good error messages. However, we do
-- not want to give an additional error if the data
-- constructor happens to be out of scope! See #13947.
mb_demoted_name <- discardErrs $
lookupOccRn_maybe demoted_rdr
; let suggestion | isJust mb_demoted_name = suggest_dk
| otherwise = star_info
; unboundNameX WL_Any rdr_name suggestion } }
| otherwise
= reportUnboundName rdr_name
where
suggest_dk = text "A data constructor of that name is in scope; did you mean DataKinds?"
untickedPromConstrWarn name =
text "Unticked promoted constructor" <> colon <+> quotes (ppr name) <> dot
$$
hsep [ text "Use"
, quotes (char '\'' <> ppr name)
, text "instead of"
, quotes (ppr name) <> dot ]
star_info
| isStar rdr_name || isUniStar rdr_name
= if xopt LangExt.TypeInType dflags
then text "NB: With TypeInType, you must import" <+>
ppr rdr_name <+> text "from Data.Kind"
else empty
| otherwise
= empty
badVarInType :: RdrName -> RnM Name
badVarInType rdr_name
= do { addErr (text "Illegal promoted term variable in a type:"
<+> ppr rdr_name)
; return (mkUnboundNameRdr rdr_name) }
{- Note [Promoted variables in types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this (Trac #12686):
x = True
data Bad = Bad 'x
The parser treats the quote in 'x as saying "use the term
namespace", so we'll get (Bad x{v}), with 'x' in the
VarName namespace. If we don't test for this, the renamer
will happily rename it to the x bound at top level, and then
the typecheck falls over because it doesn't have 'x' in scope
when kind-checking.
Note [Demotion]
~~~~~~~~~~~~~~~
When the user writes:
data Nat = Zero | Succ Nat
foo :: f Zero -> Int
'Zero' in the type signature of 'foo' is parsed as:
HsTyVar ("Zero", TcClsName)
When the renamer hits this occurrence of 'Zero' it's going to realise
that it's not in scope. But because it is renaming a type, it knows
that 'Zero' might be a promoted data constructor, so it will demote
its namespace to DataName and do a second lookup.
The final result (after the renamer) will be:
HsTyVar ("Zero", DataName)
-}
lookupOccRnX_maybe :: (RdrName -> RnM (Maybe r)) -> (Name -> r) -> RdrName
-> RnM (Maybe r)
lookupOccRnX_maybe globalLookup wrapper rdr_name
= runMaybeT . msum . map MaybeT $
[ fmap wrapper <$> lookupLocalOccRn_maybe rdr_name
, globalLookup rdr_name ]
lookupOccRn_maybe :: RdrName -> RnM (Maybe Name)
lookupOccRn_maybe = lookupOccRnX_maybe lookupGlobalOccRn_maybe id
lookupOccRn_overloaded :: Bool -> RdrName
-> RnM (Maybe (Either Name [Name]))
lookupOccRn_overloaded overload_ok
= lookupOccRnX_maybe global_lookup Left
where
global_lookup :: RdrName -> RnM (Maybe (Either Name [Name]))
global_lookup n =
runMaybeT . msum . map MaybeT $
[ lookupGlobalOccRn_overloaded overload_ok n
, fmap Left . listToMaybe <$> lookupQualifiedNameGHCi n ]
lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
-- Looks up a RdrName occurrence in the top-level
-- environment, including using lookupQualifiedNameGHCi
-- for the GHCi case
-- No filter function; does not report an error on failure
-- Uses addUsedRdrName to record use and deprecations
lookupGlobalOccRn_maybe rdr_name =
lookupExactOrOrig rdr_name Just $
runMaybeT . msum . map MaybeT $
[ fmap gre_name <$> lookupGreRn_maybe rdr_name
, listToMaybe <$> lookupQualifiedNameGHCi rdr_name ]
-- This test is not expensive,
-- and only happens for failed lookups
lookupGlobalOccRn :: RdrName -> RnM Name
-- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
-- environment. Adds an error message if the RdrName is not in scope.
-- You usually want to use "lookupOccRn" which also looks in the local
-- environment.
lookupGlobalOccRn rdr_name
= do { mb_name <- lookupGlobalOccRn_maybe rdr_name
; case mb_name of
Just n -> return n
Nothing -> do { traceRn "lookupGlobalOccRn" (ppr rdr_name)
; unboundName WL_Global rdr_name } }
lookupInfoOccRn :: RdrName -> RnM [Name]
-- lookupInfoOccRn is intended for use in GHCi's ":info" command
-- It finds all the GREs that RdrName could mean, not complaining
-- about ambiguity, but rather returning them all
-- C.f. Trac #9881
lookupInfoOccRn rdr_name =
lookupExactOrOrig rdr_name (:[]) $
do { rdr_env <- getGlobalRdrEnv
; let ns = map gre_name (lookupGRE_RdrName rdr_name rdr_env)
; qual_ns <- lookupQualifiedNameGHCi rdr_name
; return (ns ++ (qual_ns `minusList` ns)) }
-- | Like 'lookupOccRn_maybe', but with a more informative result if
-- the 'RdrName' happens to be a record selector:
--
-- * Nothing -> name not in scope (no error reported)
-- * Just (Left x) -> name uniquely refers to x,
-- or there is a name clash (reported)
-- * Just (Right xs) -> name refers to one or more record selectors;
-- if overload_ok was False, this list will be
-- a singleton.
lookupGlobalOccRn_overloaded :: Bool -> RdrName
-> RnM (Maybe (Either Name [Name]))
lookupGlobalOccRn_overloaded overload_ok rdr_name =
lookupExactOrOrig rdr_name (Just . Left) $
do { res <- lookupGreRn_helper rdr_name
; case res of
GreNotFound -> return Nothing
OneNameMatch gre -> do
let wrapper = if isRecFldGRE gre then Right . (:[]) else Left
return $ Just (wrapper (gre_name gre))
MultipleNames gres | all isRecFldGRE gres && overload_ok ->
-- Don't record usage for ambiguous selectors
-- until we know which is meant
return $ Just (Right (map gre_name gres))
MultipleNames gres -> do
addNameClashErrRn rdr_name gres
return (Just (Left (gre_name (head gres)))) }
--------------------------------------------------
-- Lookup in the Global RdrEnv of the module
--------------------------------------------------
data GreLookupResult = GreNotFound
| OneNameMatch GlobalRdrElt
| MultipleNames [GlobalRdrElt]
lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
-- Look up the RdrName in the GlobalRdrEnv
-- Exactly one binding: records it as "used", return (Just gre)
-- No bindings: return Nothing
-- Many bindings: report "ambiguous", return an arbitrary (Just gre)
-- Uses addUsedRdrName to record use and deprecations
lookupGreRn_maybe rdr_name
= do
res <- lookupGreRn_helper rdr_name
case res of
OneNameMatch gre -> return $ Just gre
MultipleNames gres -> do
traceRn "lookupGreRn_maybe:NameClash" (ppr gres)
addNameClashErrRn rdr_name gres
return $ Just (head gres)
GreNotFound -> return Nothing
{-
Note [ Unbound vs Ambiguous Names ]
lookupGreRn_maybe deals with failures in two different ways. If a name
is unbound then we return a `Nothing` but if the name is ambiguous
then we raise an error and return a dummy name.
The reason for this is that when we call `lookupGreRn_maybe` we are
speculatively looking for whatever we are looking up. If we don't find it,
then we might have been looking for the wrong thing and can keep trying.
On the other hand, if we find a clash then there is no way to recover as
we found the thing we were looking for but can no longer resolve which
the correct one is.
One example of this is in `lookupTypeOccRn` which first looks in the type
constructor namespace before looking in the data constructor namespace to
deal with `DataKinds`.
There is however, as always, one exception to this scheme. If we find
an ambiguous occurence of a record selector and DuplicateRecordFields
is enabled then we defer the selection until the typechecker.
-}
-- Internal Function
lookupGreRn_helper :: RdrName -> RnM GreLookupResult
lookupGreRn_helper rdr_name
= do { env <- getGlobalRdrEnv
; case lookupGRE_RdrName rdr_name env of
[] -> return GreNotFound
[gre] -> do { addUsedGRE True gre
; return (OneNameMatch gre) }
gres -> return (MultipleNames gres) }
lookupGreAvailRn :: RdrName -> RnM (Name, AvailInfo)
-- Used in export lists
-- If not found or ambiguous, add error message, and fake with UnboundName
-- Uses addUsedRdrName to record use and deprecations
lookupGreAvailRn rdr_name
= do
mb_gre <- lookupGreRn_helper rdr_name
case mb_gre of
GreNotFound ->
do
traceRn "lookupGreAvailRn" (ppr rdr_name)
name <- unboundName WL_Global rdr_name
return (name, avail name)
MultipleNames gres ->
do
addNameClashErrRn rdr_name gres
let unbound_name = mkUnboundNameRdr rdr_name
return (unbound_name, avail unbound_name)
-- Returning an unbound name here prevents an error
-- cascade
OneNameMatch gre ->
return (gre_name gre, availFromGRE gre)
{-
*********************************************************
* *
Deprecations
* *
*********************************************************
Note [Handling of deprecations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* We report deprecations at each *occurrence* of the deprecated thing
(see Trac #5867)
* We do not report deprecations for locally-defined names. For a
start, we may be exporting a deprecated thing. Also we may use a
deprecated thing in the defn of another deprecated things. We may
even use a deprecated thing in the defn of a non-deprecated thing,
when changing a module's interface.
* addUsedGREs: we do not report deprecations for sub-binders:
- the ".." completion for records
- the ".." in an export item 'T(..)'
- the things exported by a module export 'module M'
-}
addUsedDataCons :: GlobalRdrEnv -> TyCon -> RnM ()
-- Remember use of in-scope data constructors (Trac #7969)
addUsedDataCons rdr_env tycon
= addUsedGREs [ gre
| dc <- tyConDataCons tycon
, Just gre <- [lookupGRE_Name rdr_env (dataConName dc)] ]
addUsedGRE :: Bool -> GlobalRdrElt -> RnM ()
-- Called for both local and imported things
-- Add usage *and* warn if deprecated
addUsedGRE warn_if_deprec gre
= do { when warn_if_deprec (warnIfDeprecated gre)
; unless (isLocalGRE gre) $
do { env <- getGblEnv
; traceRn "addUsedGRE" (ppr gre)
; updMutVar (tcg_used_gres env) (gre :) } }
addUsedGREs :: [GlobalRdrElt] -> RnM ()
-- Record uses of any *imported* GREs
-- Used for recording used sub-bndrs
-- NB: no call to warnIfDeprecated; see Note [Handling of deprecations]
addUsedGREs gres
| null imp_gres = return ()
| otherwise = do { env <- getGblEnv
; traceRn "addUsedGREs" (ppr imp_gres)
; updMutVar (tcg_used_gres env) (imp_gres ++) }
where
imp_gres = filterOut isLocalGRE gres
warnIfDeprecated :: GlobalRdrElt -> RnM ()
warnIfDeprecated gre@(GRE { gre_name = name, gre_imp = iss })
| (imp_spec : _) <- iss
= do { dflags <- getDynFlags
; this_mod <- getModule
; when (wopt Opt_WarnWarningsDeprecations dflags &&
not (nameIsLocalOrFrom this_mod name)) $
-- See Note [Handling of deprecations]
do { iface <- loadInterfaceForName doc name
; case lookupImpDeprec iface gre of
Just txt -> addWarn (Reason Opt_WarnWarningsDeprecations)
(mk_msg imp_spec txt)
Nothing -> return () } }
| otherwise
= return ()
where
occ = greOccName gre
name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name
doc = text "The name" <+> quotes (ppr occ) <+> ptext (sLit "is mentioned explicitly")
mk_msg imp_spec txt
= sep [ sep [ text "In the use of"
<+> pprNonVarNameSpace (occNameSpace occ)
<+> quotes (ppr occ)
, parens imp_msg <> colon ]
, pprWarningTxtForMsg txt ]
where
imp_mod = importSpecModule imp_spec
imp_msg = text "imported from" <+> ppr imp_mod <> extra
extra | imp_mod == moduleName name_mod = Outputable.empty
| otherwise = text ", but defined in" <+> ppr name_mod
lookupImpDeprec :: ModIface -> GlobalRdrElt -> Maybe WarningTxt
lookupImpDeprec iface gre
= mi_warn_fn iface (greOccName gre) `mplus` -- Bleat if the thing,
case gre_par gre of -- or its parent, is warn'd
ParentIs p -> mi_warn_fn iface (nameOccName p)
FldParent { par_is = p } -> mi_warn_fn iface (nameOccName p)
NoParent -> Nothing
{-
Note [Used names with interface not loaded]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's (just) possible to find a used
Name whose interface hasn't been loaded:
a) It might be a WiredInName; in that case we may not load
its interface (although we could).
b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
These are seen as "used" by the renamer (if -XRebindableSyntax)
is on), but the typechecker may discard their uses
if in fact the in-scope fromRational is GHC.Read.fromRational,
(see tcPat.tcOverloadedLit), and the typechecker sees that the type
is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
In that obscure case it won't force the interface in.
In both cases we simply don't permit deprecations;
this is, after all, wired-in stuff.
*********************************************************
* *
GHCi support
* *
*********************************************************
A qualified name on the command line can refer to any module at
all: we try to load the interface if we don't already have it, just
as if there was an "import qualified M" declaration for every
module.
For example, writing `Data.List.sort` will load the interface file for
`Data.List` as if the user had written `import qualified Data.List`.
If we fail we just return Nothing, rather than bleating
about "attempting to use module ‘D’ (./D.hs) which is not loaded"
which is what loadSrcInterface does.
It is enabled by default and disabled by the flag
`-fno-implicit-import-qualified`.
Note [Safe Haskell and GHCi]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We DON'T do this Safe Haskell as we need to check imports. We can
and should instead check the qualified import but at the moment
this requires some refactoring so leave as a TODO
-}
lookupQualifiedNameGHCi :: RdrName -> RnM [Name]
lookupQualifiedNameGHCi rdr_name
= -- We want to behave as we would for a source file import here,
-- and respect hiddenness of modules/packages, hence loadSrcInterface.
do { dflags <- getDynFlags
; is_ghci <- getIsGHCi
; go_for_it dflags is_ghci }
where
go_for_it dflags is_ghci
| Just (mod,occ) <- isQual_maybe rdr_name
, is_ghci
, gopt Opt_ImplicitImportQualified dflags -- Enables this GHCi behaviour
, not (safeDirectImpsReq dflags) -- See Note [Safe Haskell and GHCi]
= do { res <- loadSrcInterface_maybe doc mod False Nothing
; case res of
Succeeded iface
-> return [ name
| avail <- mi_exports iface
, name <- availNames avail
, nameOccName name == occ ]
_ -> -- Either we couldn't load the interface, or
-- we could but we didn't find the name in it
do { traceRn "lookupQualifiedNameGHCi" (ppr rdr_name)
; return [] } }
| otherwise
= do { traceRn "lookupQualifiedNameGHCi: off" (ppr rdr_name)
; return [] }
doc = text "Need to find" <+> ppr rdr_name
{-
Note [Looking up signature names]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
lookupSigOccRn is used for type signatures and pragmas
Is this valid?
module A
import M( f )
f :: Int -> Int
f x = x
It's clear that the 'f' in the signature must refer to A.f
The Haskell98 report does not stipulate this, but it will!
So we must treat the 'f' in the signature in the same way
as the binding occurrence of 'f', using lookupBndrRn
However, consider this case:
import M( f )
f :: Int -> Int
g x = x
We don't want to say 'f' is out of scope; instead, we want to
return the imported 'f', so that later on the reanamer will
correctly report "misplaced type sig".
Note [Signatures for top level things]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
data HsSigCtxt = ... | TopSigCtxt NameSet | ....
* The NameSet says what is bound in this group of bindings.
We can't use isLocalGRE from the GlobalRdrEnv, because of this:
f x = x
$( ...some TH splice... )
f :: Int -> Int
When we encounter the signature for 'f', the binding for 'f'
will be in the GlobalRdrEnv, and will be a LocalDef. Yet the
signature is mis-placed
* For type signatures the NameSet should be the names bound by the
value bindings; for fixity declarations, the NameSet should also
include class sigs and record selectors
infix 3 `f` -- Yes, ok
f :: C a => a -> a -- No, not ok
class C a where
f :: a -> a
-}
data HsSigCtxt
= TopSigCtxt NameSet -- At top level, binding these names
-- See Note [Signatures for top level things]
| LocalBindCtxt NameSet -- In a local binding, binding these names
| ClsDeclCtxt Name -- Class decl for this class
| InstDeclCtxt NameSet -- Instance decl whose user-written method
-- bindings are for these methods
| HsBootCtxt NameSet -- Top level of a hs-boot file, binding these names
| RoleAnnotCtxt NameSet -- A role annotation, with the names of all types
-- in the group
instance Outputable HsSigCtxt where
ppr (TopSigCtxt ns) = text "TopSigCtxt" <+> ppr ns
ppr (LocalBindCtxt ns) = text "LocalBindCtxt" <+> ppr ns
ppr (ClsDeclCtxt n) = text "ClsDeclCtxt" <+> ppr n
ppr (InstDeclCtxt ns) = text "InstDeclCtxt" <+> ppr ns
ppr (HsBootCtxt ns) = text "HsBootCtxt" <+> ppr ns
ppr (RoleAnnotCtxt ns) = text "RoleAnnotCtxt" <+> ppr ns
lookupSigOccRn :: HsSigCtxt
-> Sig GhcPs
-> Located RdrName -> RnM (Located Name)
lookupSigOccRn ctxt sig = lookupSigCtxtOccRn ctxt (hsSigDoc sig)
-- | Lookup a name in relation to the names in a 'HsSigCtxt'
lookupSigCtxtOccRn :: HsSigCtxt
-> SDoc -- ^ description of thing we're looking up,
-- like "type family"
-> Located RdrName -> RnM (Located Name)
lookupSigCtxtOccRn ctxt what
= wrapLocM $ \ rdr_name ->
do { mb_name <- lookupBindGroupOcc ctxt what rdr_name
; case mb_name of
Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) }
Right name -> return name }
lookupBindGroupOcc :: HsSigCtxt
-> SDoc
-> RdrName -> RnM (Either MsgDoc Name)
-- Looks up the RdrName, expecting it to resolve to one of the
-- bound names passed in. If not, return an appropriate error message
--
-- See Note [Looking up signature names]
lookupBindGroupOcc ctxt what rdr_name
| Just n <- isExact_maybe rdr_name
= lookupExactOcc_either n -- allow for the possibility of missing Exacts;
-- see Note [dataTcOccs and Exact Names]
-- Maybe we should check the side conditions
-- but it's a pain, and Exact things only show
-- up when you know what you are doing
| Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
= do { n' <- lookupOrig rdr_mod rdr_occ
; return (Right n') }
| otherwise
= case ctxt of
HsBootCtxt ns -> lookup_top (`elemNameSet` ns)
TopSigCtxt ns -> lookup_top (`elemNameSet` ns)
RoleAnnotCtxt ns -> lookup_top (`elemNameSet` ns)
LocalBindCtxt ns -> lookup_group ns
ClsDeclCtxt cls -> lookup_cls_op cls
InstDeclCtxt ns -> lookup_top (`elemNameSet` ns)
where
lookup_cls_op cls
= lookupSubBndrOcc True cls doc rdr_name
where
doc = text "method of class" <+> quotes (ppr cls)
lookup_top keep_me
= do { env <- getGlobalRdrEnv
; let all_gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
; case filter (keep_me . gre_name) all_gres of
[] | null all_gres -> bale_out_with Outputable.empty
| otherwise -> bale_out_with local_msg
(gre:_) -> return (Right (gre_name gre)) }
lookup_group bound_names -- Look in the local envt (not top level)
= do { mname <- lookupLocalOccRn_maybe rdr_name
; case mname of
Just n
| n `elemNameSet` bound_names -> return (Right n)
| otherwise -> bale_out_with local_msg
Nothing -> bale_out_with Outputable.empty }
bale_out_with msg
= return (Left (sep [ text "The" <+> what
<+> text "for" <+> quotes (ppr rdr_name)
, nest 2 $ text "lacks an accompanying binding"]
$$ nest 2 msg))
local_msg = parens $ text "The" <+> what <+> ptext (sLit "must be given where")
<+> quotes (ppr rdr_name) <+> text "is declared"
---------------
lookupLocalTcNames :: HsSigCtxt -> SDoc -> RdrName -> RnM [(RdrName, Name)]
-- GHC extension: look up both the tycon and data con or variable.
-- Used for top-level fixity signatures and deprecations.
-- Complain if neither is in scope.
-- See Note [Fixity signature lookup]
lookupLocalTcNames ctxt what rdr_name
= do { mb_gres <- mapM lookup (dataTcOccs rdr_name)
; let (errs, names) = splitEithers mb_gres
; when (null names) $ addErr (head errs) -- Bleat about one only
; return names }
where
lookup rdr = do { name <- lookupBindGroupOcc ctxt what rdr
; return (fmap ((,) rdr) name) }
dataTcOccs :: RdrName -> [RdrName]
-- Return both the given name and the same name promoted to the TcClsName
-- namespace. This is useful when we aren't sure which we are looking at.
-- See also Note [dataTcOccs and Exact Names]
dataTcOccs rdr_name
| isDataOcc occ || isVarOcc occ
= [rdr_name, rdr_name_tc]
| otherwise
= [rdr_name]
where
occ = rdrNameOcc rdr_name
rdr_name_tc = setRdrNameSpace rdr_name tcName
{-
Note [dataTcOccs and Exact Names]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Exact RdrNames can occur in code generated by Template Haskell, and generally
those references are, well, exact. However, the TH `Name` type isn't expressive
enough to always track the correct namespace information, so we sometimes get
the right Unique but wrong namespace. Thus, we still have to do the double-lookup
for Exact RdrNames.
There is also an awkward situation for built-in syntax. Example in GHCi
:info []
This parses as the Exact RdrName for nilDataCon, but we also want
the list type constructor.
Note that setRdrNameSpace on an Exact name requires the Name to be External,
which it always is for built in syntax.
-}
{-
************************************************************************
* *
Rebindable names
Dealing with rebindable syntax is driven by the
Opt_RebindableSyntax dynamic flag.
In "deriving" code we don't want to use rebindable syntax
so we switch off the flag locally
* *
************************************************************************
Haskell 98 says that when you say "3" you get the "fromInteger" from the
Standard Prelude, regardless of what is in scope. However, to experiment
with having a language that is less coupled to the standard prelude, we're
trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
happens to be in scope. Then you can
import Prelude ()
import MyPrelude as Prelude
to get the desired effect.
At the moment this just happens for
* fromInteger, fromRational on literals (in expressions and patterns)
* negate (in expressions)
* minus (arising from n+k patterns)
* "do" notation
We store the relevant Name in the HsSyn tree, in
* HsIntegral/HsFractional/HsIsString
* NegApp
* NPlusKPat
* HsDo
respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
fromRationalName etc), but the renamer changes this to the appropriate user
name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
We treat the original (standard) names as free-vars too, because the type checker
checks the type of the user thing against the type of the standard thing.
-}
lookupIfThenElse :: RnM (Maybe (SyntaxExpr GhcRn), FreeVars)
-- Different to lookupSyntaxName because in the non-rebindable
-- case we desugar directly rather than calling an existing function
-- Hence the (Maybe (SyntaxExpr GhcRn)) return type
lookupIfThenElse
= do { rebindable_on <- xoptM LangExt.RebindableSyntax
; if not rebindable_on
then return (Nothing, emptyFVs)
else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse"))
; return ( Just (mkRnSyntaxExpr ite)
, unitFV ite ) } }
lookupSyntaxName' :: Name -- ^ The standard name
-> RnM Name -- ^ Possibly a non-standard name
lookupSyntaxName' std_name
= do { rebindable_on <- xoptM LangExt.RebindableSyntax
; if not rebindable_on then
return std_name
else
-- Get the similarly named thing from the local environment
lookupOccRn (mkRdrUnqual (nameOccName std_name)) }
lookupSyntaxName :: Name -- The standard name
-> RnM (SyntaxExpr GhcRn, FreeVars) -- Possibly a non-standard
-- name
lookupSyntaxName std_name
= do { rebindable_on <- xoptM LangExt.RebindableSyntax
; if not rebindable_on then
return (mkRnSyntaxExpr std_name, emptyFVs)
else
-- Get the similarly named thing from the local environment
do { usr_name <- lookupOccRn (mkRdrUnqual (nameOccName std_name))
; return (mkRnSyntaxExpr usr_name, unitFV usr_name) } }
lookupSyntaxNames :: [Name] -- Standard names
-> RnM ([HsExpr GhcRn], FreeVars) -- See comments with HsExpr.ReboundNames
-- this works with CmdTop, which wants HsExprs, not SyntaxExprs
lookupSyntaxNames std_names
= do { rebindable_on <- xoptM LangExt.RebindableSyntax
; if not rebindable_on then
return (map (HsVar . noLoc) std_names, emptyFVs)
else
do { usr_names <- mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names
; return (map (HsVar . noLoc) usr_names, mkFVs usr_names) } }
-- Error messages
opDeclErr :: RdrName -> SDoc
opDeclErr n
= hang (text "Illegal declaration of a type or class operator" <+> quotes (ppr n))
2 (text "Use TypeOperators to declare operators in type and declarations")
badOrigBinding :: RdrName -> SDoc
badOrigBinding name
| Just _ <- isBuiltInOcc_maybe occ
= text "Illegal binding of built-in syntax:" <+> ppr occ
-- Use an OccName here because we don't want to print Prelude.(,)
| otherwise
= text "Cannot redefine a Name retrieved by a Template Haskell quote:"
<+> ppr name
-- This can happen when one tries to use a Template Haskell splice to
-- define a top-level identifier with an already existing name, e.g.,
--
-- $(pure [ValD (VarP 'succ) (NormalB (ConE 'True)) []])
--
-- (See Trac #13968.)
where
occ = rdrNameOcc name
| ezyang/ghc | compiler/rename/RnEnv.hs | bsd-3-clause | 64,166 | 69 | 22 | 17,961 | 8,661 | 4,440 | 4,221 | 721 | 13 |
module Turbinado.Server.Network (
receiveRequest -- :: Handle -> IO Request
, sendResponse -- :: Handle -> Response -> IO ()
) where
import Data.Maybe
import Network.Socket
import Turbinado.Controller.Monad
import Turbinado.Server.Exception
import Turbinado.Environment.Logger
import Turbinado.Environment.Types
import Turbinado.Environment.Request
import Turbinado.Environment.Response
import Turbinado.Utility.Data
import Network.HTTP
-- | Read the request from client.
receiveRequest :: Socket -> Controller ()
receiveRequest sock = do
req <- liftIO $ receiveHTTP sock
case req of
Left e -> throwTurbinado $ BadRequest $ "In receiveRequest : " ++ show e
Right r -> do e <- get
put $ e {getRequest = Just r}
-- | Get the 'Response' from the 'Environment' and send
-- it back to the client.
sendResponse :: Socket -> Environment -> IO ()
sendResponse sock e = respondHTTP sock $ fromJust' "Network : sendResponse" $ getResponse e
| abuiles/turbinado-blog | Turbinado/Server/Network.hs | bsd-3-clause | 1,024 | 0 | 15 | 227 | 223 | 120 | 103 | 22 | 2 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.EXT.VertexWeighting
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.EXT.VertexWeighting (
-- * Extension Support
glGetEXTVertexWeighting,
gl_EXT_vertex_weighting,
-- * Enums
pattern GL_CURRENT_VERTEX_WEIGHT_EXT,
pattern GL_MODELVIEW0_EXT,
pattern GL_MODELVIEW0_MATRIX_EXT,
pattern GL_MODELVIEW0_STACK_DEPTH_EXT,
pattern GL_MODELVIEW1_EXT,
pattern GL_MODELVIEW1_MATRIX_EXT,
pattern GL_MODELVIEW1_STACK_DEPTH_EXT,
pattern GL_VERTEX_WEIGHTING_EXT,
pattern GL_VERTEX_WEIGHT_ARRAY_EXT,
pattern GL_VERTEX_WEIGHT_ARRAY_POINTER_EXT,
pattern GL_VERTEX_WEIGHT_ARRAY_SIZE_EXT,
pattern GL_VERTEX_WEIGHT_ARRAY_STRIDE_EXT,
pattern GL_VERTEX_WEIGHT_ARRAY_TYPE_EXT,
-- * Functions
glVertexWeightPointerEXT,
glVertexWeightfEXT,
glVertexWeightfvEXT
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| haskell-opengl/OpenGLRaw | src/Graphics/GL/EXT/VertexWeighting.hs | bsd-3-clause | 1,248 | 0 | 5 | 155 | 123 | 83 | 40 | 23 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MonadComprehensions #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main (main) where
import Test.Hspec
import qualified GHC.Exts as GHC
import Streamly
#ifdef USE_STREAMLY_LIST
import Data.Functor.Identity
import Streamly.Internal.Data.List (List(..), pattern Cons, pattern Nil, ZipList(..),
fromZipList, toZipList)
import qualified Streamly.Prelude as S
#else
import Prelude -- to suppress compiler warning
type List = []
pattern Nil :: [a]
pattern Nil <- [] where Nil = []
pattern Cons :: a -> [a] -> [a]
pattern Cons x xs = x : xs
infixr 5 `Cons`
{-# COMPLETE Nil, Cons #-}
#endif
main :: IO ()
main = hspec $ do
#ifdef USE_STREAMLY_LIST
describe "OverloadedLists for 'SerialT Identity' type" $ do
it "Overloaded lists" $ do
([1..3] :: SerialT Identity Int) `shouldBe` S.fromList [1..3]
GHC.toList ([1..3] :: SerialT Identity Int) `shouldBe` [1..3]
it "Show instance" $ do
show (S.fromList [1..3] :: SerialT Identity Int)
`shouldBe` "fromList [1,2,3]"
it "Read instance" $ do
(read "fromList [1,2,3]" :: SerialT Identity Int) `shouldBe` [1..3]
it "Eq instance" $ do
([1,2,3] :: SerialT Identity Int) == [1,2,3] `shouldBe` True
it "Ord instance" $ do
([1,2,3] :: SerialT Identity Int) > [1,2,1] `shouldBe` True
it "Monad comprehension" $ do
[(x,y) | x <- [1..2], y <- [1..2]] `shouldBe`
([(1,1), (1,2), (2,1), (2,2)] :: SerialT Identity (Int, Int))
it "Foldable (sum)" $ sum ([1..3] :: SerialT Identity Int)
`shouldBe` 6
it "Traversable (mapM)" $
mapM return ([1..10] :: SerialT Identity Int)
`shouldReturn` [1..10]
describe "OverloadedStrings for 'SerialT Identity' type" $ do
it "overloaded strings" $ do
("hello" :: SerialT Identity Char) `shouldBe` S.fromList "hello"
#endif
describe "OverloadedLists for List type" $ do
it "overloaded lists" $ do
([1..3] :: List Int) `shouldBe` GHC.fromList [1..3]
GHC.toList ([1..3] :: List Int) `shouldBe` [1..3]
it "Construct empty list" $ (Nil :: List Int) `shouldBe` []
it "Construct a list" $ do
(Nil :: List Int) `shouldBe` []
('x' `Cons` Nil) `shouldBe` ['x']
(1 `Cons` [2 :: Int]) `shouldBe` [1,2]
(1 `Cons` 2 `Cons` 3 `Cons` Nil :: List Int) `shouldBe` [1,2,3]
it "pattern matches" $ do
case [] of
Nil -> return ()
_ -> expectationFailure "not reached"
case ['x'] of
Cons 'x' Nil -> return ()
_ -> expectationFailure "not reached"
case [1..10 :: Int] of
Cons x xs -> do
x `shouldBe` 1
xs `shouldBe` [2..10]
_ -> expectationFailure "not reached"
case [1..10 :: Int] of
x `Cons` y `Cons` xs -> do
x `shouldBe` 1
y `shouldBe` 2
xs `shouldBe` [3..10]
_ -> expectationFailure "not reached"
it "Show instance" $ do
show ([1..3] :: List Int) `shouldBe`
#ifdef USE_STREAMLY_LIST
"List {toSerial = fromList [1,2,3]}"
#else
"[1,2,3]"
#endif
it "Read instance" $ do
(read
#ifdef USE_STREAMLY_LIST
"List {toSerial = fromList [1,2,3]}"
#else
"[1,2,3]"
#endif
:: List Int) `shouldBe` [1..3]
it "Eq instance" $ do
([1,2,3] :: List Int) == [1,2,3] `shouldBe` True
it "Ord instance" $ do
([1,2,3] :: List Int) > [1,2,1] `shouldBe` True
it "Monad comprehension" $ do
[(x,y) | x <- [1..2], y <- [1..2]] `shouldBe`
([(1,1), (1,2), (2,1), (2,2)] :: List (Int, Int))
it "Foldable (sum)" $ sum ([1..3] :: List Int) `shouldBe` 6
it "Traversable (mapM)" $
mapM return ([1..10] :: List Int)
`shouldReturn` [1..10]
describe "OverloadedStrings for List type" $ do
it "overloaded strings" $ do
("hello" :: List Char) `shouldBe` GHC.fromList "hello"
it "pattern matches" $ do
#if __GLASGOW_HASKELL__ >= 802
case "" of
#else
case "" :: List Char of
#endif
Nil -> return ()
_ -> expectationFailure "not reached"
case "a" of
Cons x Nil -> x `shouldBe` 'a'
_ -> expectationFailure "not reached"
case "hello" <> "world" of
Cons x1 (Cons x2 xs) -> do
x1 `shouldBe` 'h'
x2 `shouldBe` 'e'
xs `shouldBe` "lloworld"
_ -> expectationFailure "not reached"
#ifdef USE_STREAMLY_LIST
describe "OverloadedLists for ZipList type" $ do
it "overloaded lists" $ do
([1..3] :: ZipList Int) `shouldBe` GHC.fromList [1..3]
GHC.toList ([1..3] :: ZipList Int) `shouldBe` [1..3]
it "toZipList" $ do
toZipList (Nil :: List Int) `shouldBe` []
toZipList ('x' `Cons` Nil) `shouldBe` ['x']
toZipList (1 `Cons` [2 :: Int]) `shouldBe` [1,2]
toZipList (1 `Cons` 2 `Cons` 3 `Cons` Nil :: List Int) `shouldBe` [1,2,3]
it "fromZipList" $ do
case fromZipList [] of
Nil -> return ()
_ -> expectationFailure "not reached"
case fromZipList ['x'] of
Cons 'x' Nil -> return ()
_ -> expectationFailure "not reached"
case fromZipList [1..10 :: Int] of
Cons x xs -> do
x `shouldBe` 1
xs `shouldBe` [2..10]
_ -> expectationFailure "not reached"
case fromZipList [1..10 :: Int] of
x `Cons` y `Cons` xs -> do
x `shouldBe` 1
y `shouldBe` 2
xs `shouldBe` [3..10]
_ -> expectationFailure "not reached"
it "Show instance" $ do
show ([1..3] :: ZipList Int) `shouldBe`
"ZipList {toZipSerial = fromList [1,2,3]}"
it "Read instance" $ do
(read "ZipList {toZipSerial = fromList [1,2,3]}" :: ZipList Int)
`shouldBe` [1..3]
it "Eq instance" $ do
([1,2,3] :: ZipList Int) == [1,2,3] `shouldBe` True
it "Ord instance" $ do
([1,2,3] :: ZipList Int) > [1,2,1] `shouldBe` True
it "Foldable (sum)" $ sum ([1..3] :: ZipList Int) `shouldBe` 6
it "Traversable (mapM)" $
mapM return ([1..10] :: ZipList Int)
`shouldReturn` [1..10]
it "Applicative Zip" $ do
(,) <$> "abc" <*> [1..3] `shouldBe`
([('a',1),('b',2),('c',3)] :: ZipList (Char, Int))
#endif
| harendra-kumar/asyncly | test/PureStreams.hs | bsd-3-clause | 7,277 | 0 | 20 | 2,626 | 2,364 | 1,276 | 1,088 | 85 | 8 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.ShadowAmbient
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/ARB/shadow_ambient.txt ARB_shadow_ambient> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.ShadowAmbient (
-- * Enums
gl_TEXTURE_COMPARE_FAIL_VALUE_ARB
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/ARB/ShadowAmbient.hs | bsd-3-clause | 666 | 0 | 4 | 78 | 37 | 31 | 6 | 3 | 0 |
{-# LANGUAGE TemplateHaskell, PolyKinds, DataKinds, TypeFamilies, TypeInType,
TypeOperators, GADTs, ScopedTypeVariables, UndecidableInstances,
DefaultSignatures, FlexibleContexts
#-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Singletons.Prelude.Num
-- Copyright : (C) 2014 Richard Eisenberg
-- License : BSD-style (see LICENSE)
-- Maintainer : Richard Eisenberg ([email protected])
-- Stability : experimental
-- Portability : non-portable
--
-- Defines and exports promoted and singleton versions of definitions from
-- GHC.Num.
--
----------------------------------------------------------------------------
module Data.Singletons.Prelude.Num (
PNum(..), SNum(..), Subtract, sSubtract,
-- ** Defunctionalization symbols
(:+$), (:+$$), (:+$$$),
(:-$), (:-$$), (:-$$$),
(:*$), (:*$$), (:*$$$),
NegateSym0, NegateSym1,
AbsSym0, AbsSym1,
SignumSym0, SignumSym1,
FromIntegerSym0, FromIntegerSym1,
SubtractSym0, SubtractSym1, SubtractSym2
) where
import Data.Singletons.Single
import Data.Singletons
import Data.Singletons.TypeLits.Internal
import Data.Singletons.Decide
import GHC.TypeLits
import Unsafe.Coerce
$(singletonsOnly [d|
-- Basic numeric class.
--
-- Minimal complete definition: all except 'negate' or @(-)@
class Num a where
(+), (-), (*) :: a -> a -> a
infixl 6 +
infixl 6 -
infixl 7 *
-- Unary negation.
negate :: a -> a
-- Absolute value.
abs :: a -> a
-- Sign of a number.
-- The functions 'abs' and 'signum' should satisfy the law:
--
-- > abs x * signum x == x
--
-- For real numbers, the 'signum' is either @-1@ (negative), @0@ (zero)
-- or @1@ (positive).
signum :: a -> a
-- Conversion from a 'Nat'.
fromInteger :: Nat -> a
x - y = x + negate y
negate x = 0 - x
|])
-- PNum instance
type family SignumNat (a :: Nat) :: Nat where
SignumNat 0 = 0
SignumNat x = 1
instance PNum Nat where
type a :+ b = a + b
type a :- b = a - b
type a :* b = a * b
type Negate (a :: Nat) = Error "Cannot negate a natural number"
type Abs (a :: Nat) = a
type Signum a = SignumNat a
type FromInteger a = a
-- SNum instance
instance SNum Nat where
sa %:+ sb =
let a = fromSing sa
b = fromSing sb
ex = someNatVal (a + b)
in
case ex of
Just (SomeNat (_ :: Proxy ab)) -> unsafeCoerce (SNat :: Sing ab)
Nothing -> error "Two naturals added to a negative?"
sa %:- sb =
let a = fromSing sa
b = fromSing sb
ex = someNatVal (a - b)
in
case ex of
Just (SomeNat (_ :: Proxy ab)) -> unsafeCoerce (SNat :: Sing ab)
Nothing ->
error "Negative natural-number singletons are naturally not allowed."
sa %:* sb =
let a = fromSing sa
b = fromSing sb
ex = someNatVal (a * b)
in
case ex of
Just (SomeNat (_ :: Proxy ab)) -> unsafeCoerce (SNat :: Sing ab)
Nothing ->
error "Two naturals multiplied to a negative?"
sNegate _ = error "Cannot call sNegate on a natural number singleton."
sAbs x = x
sSignum sx =
case sx %~ (sing :: Sing 0) of
Proved Refl -> sing :: Sing 0
Disproved _ -> unsafeCoerce (sing :: Sing 1)
sFromInteger x = x
$(singletonsOnly [d|
subtract :: Num a => a -> a -> a
subtract x y = y - x
|])
| int-index/singletons | src/Data/Singletons/Prelude/Num.hs | bsd-3-clause | 3,604 | 5 | 16 | 1,078 | 726 | 399 | 327 | 76 | 0 |
module REPL.Set (set) where
import Rating
import REPL.NPC (npcLookup)
import REPL.Util
set :: [String] -> Rating -> Either String Rating
set [] _ = Left "使い方: 'set NPC名 番号'"
set [_] _ = Left "使い方: 'set NPC名 番号'"
set (name:pos:_) r = case npcLookup name of
"dai" -> Right $ r {dai = newIndex n}
"kaour" -> Right $ r {kaour = newIndex n}
"elsie" -> Right $ r {elsie = newIndex n}
"eirlys" -> Right $ r {eirlys = newIndex n}
s -> Left $ "'" ++ s ++ "' could not be found."
where n = string2int pos
| sandmark/AlbanKnights | src/REPL/Set.hs | bsd-3-clause | 549 | 0 | 11 | 130 | 221 | 116 | 105 | 14 | 5 |
module EvalM where
import Control.Parallel
import Control.Parallel.Strategies hiding (parMap, parList)
import Sudoku (Grid, solve)
import Data.List (splitAt)
import Control.DeepSeq (force)
import Control.Monad
import Strategy (parList, badParList)
-- parMap abstraction enables us to apply parallelism to
-- all the elements of a list.
parMap :: (a -> b) -> [a] -> Eval [b]
parMap f xs = mapM (rpar . f) xs
-- Multiple solutions without parallelism
sudoku1 :: [String] -> [Maybe Grid]
sudoku1 = fmap solve
-- Parallelism with fixed division of work.
sudoku2 :: [String] -> Eval [Maybe Grid]
sudoku2 puzzles = do
let (as, bs) = splitAt (length puzzles `div` 2) puzzles
as' <- rpar (force $ solve <$> as)
bs' <- rpar (force $ solve <$> bs)
rseq as'
rseq bs'
return (as' ++ bs')
-- Parallelism with dynamic division of work.
sudoku3 :: [String] -> Eval [Maybe Grid]
sudoku3 = parMap solve
-- Refactoring with strategies
sudoku4 :: [String] -> [Maybe Grid]
sudoku4 xs = (solve <$> xs) `using` (parList rseq)
-- Bad parList
sudoku5 :: [String] -> [Maybe Grid]
sudoku5 xs = (solve <$> xs) `using` (badParList rseq)
| sebashack/EvalMonadExample | src/EvalM.hs | bsd-3-clause | 1,136 | 0 | 13 | 210 | 403 | 220 | 183 | 26 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE UndecidableInstances #-}
-- | Representations for tuple types
--
-- The reason for using symbol names ending with @_t@ is that 'deriveRender'
-- uses everything that comes before @_@ when rendering the constructor.
module Data.TypeRep.Types.Tuple where
import Data.List (intercalate)
import qualified Data.Typeable as Typeable
#if __GLASGOW_HASKELL__ < 710
import Data.Orphans ()
#endif
import Language.Syntactic
import Data.TypeRep.Representation
import Data.TypeRep.TH
data TupleType a
where
Tup2_t :: TupleType (a :-> b :-> Full (a,b))
Tup3_t :: TupleType (a :-> b :-> c :-> Full (a,b,c))
Tup4_t :: TupleType (a :-> b :-> c :-> d :-> Full (a,b,c,d))
Tup5_t :: TupleType (a :-> b :-> c :-> d :-> e :-> Full (a,b,c,d,e))
Tup6_t :: TupleType (a :-> b :-> c :-> d :-> e :-> f :-> Full (a,b,c,d,e,f))
Tup7_t :: TupleType (a :-> b :-> c :-> d :-> e :-> f :-> g :-> Full (a,b,c,d,e,f,g))
Tup8_t :: TupleType (a :-> b :-> c :-> d :-> e :-> f :-> g :-> h :-> Full (a,b,c,d,e,f,g,h))
Tup9_t :: TupleType (a :-> b :-> c :-> d :-> e :-> f :-> g :-> h :-> i :-> Full (a,b,c,d,e,f,g,h,i))
Tup10_t :: TupleType (a :-> b :-> c :-> d :-> e :-> f :-> g :-> h :-> i :-> j :-> Full (a,b,c,d,e,f,g,h,i,j))
Tup11_t :: TupleType (a :-> b :-> c :-> d :-> e :-> f :-> g :-> h :-> i :-> j :-> k :-> Full (a,b,c,d,e,f,g,h,i,j,k))
Tup12_t :: TupleType (a :-> b :-> c :-> d :-> e :-> f :-> g :-> h :-> i :-> j :-> k :-> l :-> Full (a,b,c,d,e,f,g,h,i,j,k,l))
Tup13_t :: TupleType (a :-> b :-> c :-> d :-> e :-> f :-> g :-> h :-> i :-> j :-> k :-> l :-> m :-> Full (a,b,c,d,e,f,g,h,i,j,k,l,m))
Tup14_t :: TupleType (a :-> b :-> c :-> d :-> e :-> f :-> g :-> h :-> i :-> j :-> k :-> l :-> m :-> n :-> Full (a,b,c,d,e,f,g,h,i,j,k,l,m,n))
Tup15_t :: TupleType (a :-> b :-> c :-> d :-> e :-> f :-> g :-> h :-> i :-> j :-> k :-> l :-> m :-> n :-> o :-> Full (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o))
-- The smart constructors are not overloaded using `Syntactic` as this would
-- lead to gigantic type signatures.
tup2Type :: (TupleType :<: t)
=> TypeRep t a -> TypeRep t b -> TypeRep t (a,b)
tup2Type = sugarSym Tup2_t
tup3Type :: (TupleType :<: t)
=> TypeRep t a -> TypeRep t b -> TypeRep t c -> TypeRep t (a,b,c)
tup3Type = sugarSym Tup3_t
tup4Type :: (TupleType :<: t)
=> TypeRep t a -> TypeRep t b -> TypeRep t c -> TypeRep t d -> TypeRep t (a,b,c,d)
tup4Type = sugarSym Tup4_t
tup5Type :: (TupleType :<: t)
=> TypeRep t a -> TypeRep t b -> TypeRep t c -> TypeRep t d -> TypeRep t e
-> TypeRep t (a,b,c,d,e)
tup5Type = sugarSym Tup5_t
tup6Type :: (TupleType :<: t)
=> TypeRep t a -> TypeRep t b -> TypeRep t c -> TypeRep t d -> TypeRep t e
-> TypeRep t f-> TypeRep t (a,b,c,d,e,f)
tup6Type = sugarSym Tup6_t
tup7Type :: (TupleType :<: t)
=> TypeRep t a -> TypeRep t b -> TypeRep t c -> TypeRep t d -> TypeRep t e
-> TypeRep t f -> TypeRep t g -> TypeRep t (a,b,c,d,e,f,g)
tup7Type = sugarSym Tup7_t
tup8Type :: (TupleType :<: t)
=> TypeRep t a -> TypeRep t b -> TypeRep t c -> TypeRep t d -> TypeRep t e
-> TypeRep t f -> TypeRep t g -> TypeRep t h -> TypeRep t (a,b,c,d,e,f,g,h)
tup8Type = sugarSym Tup8_t
tup9Type :: (TupleType :<: t)
=> TypeRep t a -> TypeRep t b -> TypeRep t c -> TypeRep t d -> TypeRep t e
-> TypeRep t f -> TypeRep t g -> TypeRep t h -> TypeRep t i -> TypeRep t (a,b,c,d,e,f,g,h,i)
tup9Type = sugarSym Tup9_t
tup10Type :: (TupleType :<: t)
=> TypeRep t a -> TypeRep t b -> TypeRep t c -> TypeRep t d -> TypeRep t e
-> TypeRep t f -> TypeRep t g -> TypeRep t h -> TypeRep t i -> TypeRep t j
-> TypeRep t (a,b,c,d,e,f,g,h,i,j)
tup10Type = sugarSym Tup10_t
tup11Type :: (TupleType :<: t)
=> TypeRep t a -> TypeRep t b -> TypeRep t c -> TypeRep t d -> TypeRep t e
-> TypeRep t f -> TypeRep t g -> TypeRep t h -> TypeRep t i -> TypeRep t j
-> TypeRep t k -> TypeRep t (a,b,c,d,e,f,g,h,i,j,k)
tup11Type = sugarSym Tup11_t
tup12Type :: (TupleType :<: t)
=> TypeRep t a -> TypeRep t b -> TypeRep t c -> TypeRep t d -> TypeRep t e
-> TypeRep t f -> TypeRep t g -> TypeRep t h -> TypeRep t i -> TypeRep t j
-> TypeRep t k -> TypeRep t l -> TypeRep t (a,b,c,d,e,f,g,h,i,j,k,l)
tup12Type = sugarSym Tup12_t
tup13Type :: (TupleType :<: t)
=> TypeRep t a -> TypeRep t b -> TypeRep t c -> TypeRep t d -> TypeRep t e
-> TypeRep t f -> TypeRep t g -> TypeRep t h -> TypeRep t i -> TypeRep t j
-> TypeRep t k -> TypeRep t l -> TypeRep t m -> TypeRep t (a,b,c,d,e,f,g,h,i,j,k,l,m)
tup13Type = sugarSym Tup13_t
tup14Type :: (TupleType :<: t)
=> TypeRep t a -> TypeRep t b -> TypeRep t c -> TypeRep t d -> TypeRep t e
-> TypeRep t f -> TypeRep t g -> TypeRep t h -> TypeRep t i -> TypeRep t j
-> TypeRep t k -> TypeRep t l -> TypeRep t m -> TypeRep t n
-> TypeRep t (a,b,c,d,e,f,g,h,i,j,k,l,m,n)
tup14Type = sugarSym Tup14_t
tup15Type :: (TupleType :<: t)
=> TypeRep t a -> TypeRep t b -> TypeRep t c -> TypeRep t d -> TypeRep t e
-> TypeRep t f -> TypeRep t g -> TypeRep t h -> TypeRep t i -> TypeRep t j
-> TypeRep t k -> TypeRep t l -> TypeRep t m -> TypeRep t n
-> TypeRep t o -> TypeRep t (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o)
tup15Type = sugarSym Tup15_t
tupWidth :: TupleType a -> Int
tupWidth Tup2_t = 2
tupWidth Tup3_t = 3
tupWidth Tup4_t = 4
tupWidth Tup5_t = 5
tupWidth Tup6_t = 6
tupWidth Tup7_t = 7
tupWidth Tup8_t = 8
tupWidth Tup9_t = 9
tupWidth Tup10_t = 10
tupWidth Tup11_t = 11
tupWidth Tup12_t = 12
tupWidth Tup13_t = 13
tupWidth Tup14_t = 14
tupWidth Tup15_t = 15
instance Render TupleType
where
renderSym tup = "(" ++ replicate (tupWidth tup - 1) ',' ++ ")"
renderArgs as _ = "(" ++ intercalate "," as ++ ")"
deriveTypeEq ''TupleType
deriveWitnessAny ''TupleType
deriveWitness ''Typeable.Typeable ''TupleType
deriveWitness ''Eq ''TupleType
deriveWitness ''Ord ''TupleType
deriveWitness ''Show ''TupleType
derivePWitnessAny ''TupleType
derivePWitness ''Typeable.Typeable ''TupleType
derivePWitness ''Eq ''TupleType
derivePWitness ''Ord ''TupleType
derivePWitness ''Show ''TupleType
instance PWitness Num TupleType t
instance PWitness Integral TupleType t
| emilaxelsson/open-typerep | src/Data/TypeRep/Types/Tuple.hs | bsd-3-clause | 6,264 | 0 | 24 | 1,448 | 3,262 | 1,700 | 1,562 | -1 | -1 |
{-# LANGUAGE FlexibleContexts, RankNTypes, CPP #-}
module AWS.EC2.Subnets
( describeSubnets
, createSubnet
, deleteSubnet
) where
import Data.Text (Text)
import Data.XML.Types (Event)
import Data.Conduit
import Control.Applicative
#if MIN_VERSION_conduit(1,1,0)
import Control.Monad.Trans.Resource (MonadThrow, MonadBaseControl, MonadResource)
#endif
import AWS.EC2.Internal
import AWS.EC2.Types
import AWS.EC2.Query
import AWS.Lib.Parser
import AWS.Util
------------------------------------------------------------
-- DescribeSubnets
------------------------------------------------------------
describeSubnets
:: (MonadResource m, MonadBaseControl IO m)
=> [Text] -- ^ SubnetIds
-> [Filter] -- ^ Filters
-> EC2 m (ResumableSource m Subnet)
describeSubnets subnets filters = do
ec2QuerySource "DescribeSubnets" params $
itemConduit "subnetSet" subnetSink
where
params =
[ "SubnetId" |.#= subnets
, filtersParam filters
]
subnetSink :: MonadThrow m
=> Consumer Event m Subnet
subnetSink = Subnet
<$> getT "subnetId"
<*> getT "state"
<*> getT "vpcId"
<*> getT "cidrBlock"
<*> getT "availableIpAddressCount"
<*> getT "availabilityZone"
<*> getT "defaultForAz"
<*> getT "mapPublicIpOnLaunch"
<*> resourceTagSink
------------------------------------------------------------
-- CreateSubnet
------------------------------------------------------------
createSubnet
:: (MonadResource m, MonadBaseControl IO m)
=> CreateSubnetRequest
-> EC2 m Subnet
createSubnet param =
ec2Query "CreateSubnet" params $
element "subnet" subnetSink
where
params = createSubnetParams param
createSubnetParams :: CreateSubnetRequest -> [QueryParam]
createSubnetParams (CreateSubnetRequest vid cidr zone) =
[ "VpcId" |= vid
, "CidrBlock" |= toText cidr
, "AvailabilityZone" |=? zone
]
------------------------------------------------------------
-- DeleteSubnet
------------------------------------------------------------
deleteSubnet
:: (MonadResource m, MonadBaseControl IO m)
=> Text -- ^ SubnetId
-> EC2 m Bool
deleteSubnet = ec2Delete "DeleteSubnet" "SubnetId"
| IanConnolly/aws-sdk-fork | AWS/EC2/Subnets.hs | bsd-3-clause | 2,222 | 0 | 14 | 396 | 449 | 245 | 204 | 55 | 1 |
module RecordExplicitUsed where
import Language.Haskell.Names (Symbol (Value, symbolModule))
foo = Value {symbolModule = undefined}
| serokell/importify | test/test-data/haskell-names@records/03-RecordExplicitUsed.hs | mit | 144 | 0 | 6 | 26 | 34 | 23 | 11 | 3 | 1 |
import Test.HUnit (Assertion, (@=?), runTestTT, Test(..), Counts(..))
import System.Exit (ExitCode(..), exitWith)
import Binary (toDecimal)
exitProperly :: IO Counts -> IO ()
exitProperly m = do
counts <- m
exitWith $ if failures counts /= 0 || errors counts /= 0 then ExitFailure 1 else ExitSuccess
testCase :: String -> Assertion -> Test
testCase label assertion = TestLabel label (TestCase assertion)
main :: IO ()
main = exitProperly $ runTestTT $ TestList
[ TestList binaryTests ]
binaryTests :: [Test]
binaryTests = map TestCase
[ 1 @=? toDecimal "1"
, 2 @=? toDecimal "10"
, 3 @=? toDecimal "11"
, 4 @=? toDecimal "100"
, 9 @=? toDecimal "1001"
, 26 @=? toDecimal "11010"
, 1128 @=? toDecimal "10001101000"
, 0 @=? toDecimal "carrot"
, 0 @=? toDecimal "carrot123"
]
| pminten/xhaskell | binary/binary_test.hs | mit | 808 | 0 | 12 | 163 | 300 | 158 | 142 | 23 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : $Header$
Description : abstract syntax of CASL specification libraries
Copyright : (c) Klaus Luettich, Uni Bremen 2002-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable(Grothendieck)
Abstract syntax of HetCASL specification libraries
Follows Sect. II:2.2.5 of the CASL Reference Manual.
-}
module Syntax.AS_Library where
-- DrIFT command:
{-! global: GetRange !-}
import Common.Id
import Common.IRI
import Common.AS_Annotation
import Common.LibName
import Data.Maybe
import Data.Typeable
import Logic.Grothendieck
import Logic.Logic
import Syntax.AS_Architecture
import Syntax.AS_Structured
import Framework.AS
import Framework.ATC_Framework ()
data LIB_DEFN = Lib_defn LibName [Annoted LIB_ITEM] Range [Annotation]
{- pos: "library"
list of annotations is parsed preceding the first LIB_ITEM
the last LIB_ITEM may be annotated with a following comment
the first LIB_ITEM cannot be annotated -}
deriving (Show, Typeable)
{- for information on the list of Pos see the documentation in
AS_Structured.hs and AS_Architecture.hs -}
data LIB_ITEM = Spec_defn SPEC_NAME GENERICITY (Annoted SPEC) Range
-- pos: "spec", "=", opt "end"
| View_defn IRI GENERICITY VIEW_TYPE [G_mapping] Range
-- pos: "view", ":", opt "=", opt "end"
| Entail_defn IRI ENTAIL_TYPE Range
-- pos: "entailment", "=", opt "end"
| Equiv_defn IRI EQUIV_TYPE OmsOrNetwork Range
-- pos: "equivalence", ":", "=", opt "end"
| Align_defn IRI (Maybe ALIGN_ARITIES) VIEW_TYPE
[CORRESPONDENCE] AlignSem Range
| Module_defn IRI MODULE_TYPE G_symb_items_list Range
{- G_symb_items_list is RESTRICTION-SIGNATURE
TODO: CONSERVATIVE? -}
| Query_defn IRI G_symb_items_list G_basic_spec (Annoted SPEC)
(Maybe IRI) Range
-- pos: "query", "=", "select", "where", "in", "along"
| Subst_defn IRI VIEW_TYPE G_symb_map_items_list Range
-- pos: "substitution", ":", "=", opt "end"
| Result_defn IRI [IRI] IRI Bool Range
-- pos: "result", commas, "for", "%complete", opt "end"
| Arch_spec_defn ARCH_SPEC_NAME (Annoted ARCH_SPEC) Range
-- pos: "arch", "spec", "=", opt "end"
| Unit_spec_defn SPEC_NAME UNIT_SPEC Range
-- pos: "unit", "spec", "=", opt "end"
| Ref_spec_defn SPEC_NAME REF_SPEC Range
-- pos: "refinement", "=", opt "end"
| Graph_defn IRI Network Range
-- pos: "network", "=", opt "end"
| Download_items LibName DownloadItems Range
-- pos: "from", "get", "|->", commas, opt "end"
| Logic_decl LogicDescr Range
-- pos: "logic", Logic_name
| Newlogic_defn LogicDef Range
-- pos: "newlogic", Logic_name, "=", opt "end"
| Newcomorphism_defn ComorphismDef Range
-- pos: "newcomorphism", Comorphism_name, "=", opt "end"
deriving (Show, Typeable)
data AlignSem = SingleDomain | GlobalDomain | ContextualizedDomain
deriving (Show, Typeable, Bounded, Enum)
{- Item maps are the documented CASL renamed entities whereas a unique item
contains the new target name of the single arbitrarily named item from the
downloaded library. -}
data DownloadItems =
ItemMaps [ItemNameMap]
| UniqueItem IRI
deriving (Show, Typeable)
addDownload :: Bool -> SPEC_NAME -> Annoted LIB_ITEM
addDownload unique = emptyAnno . addDownloadAux unique
addDownloadAux :: Bool -> SPEC_NAME -> LIB_ITEM
addDownloadAux unique j =
let libPath = deleteQuery j
query = abbrevQuery j -- this used to be the fragment
i = case query of
"" -> j
"?" -> libPath
_ : r -> fromMaybe libPath $ parseIRICurie r
in Download_items (iriLibName i)
(if unique then UniqueItem i else ItemMaps [ItemNameMap i Nothing])
$ iriPos i
data GENERICITY = Genericity PARAMS IMPORTED Range deriving (Show, Typeable)
-- pos: many of "[","]" opt ("given", commas)
emptyGenericity :: GENERICITY
emptyGenericity = Genericity (Params []) (Imported []) nullRange
data PARAMS = Params [Annoted SPEC] deriving (Show, Typeable)
data IMPORTED = Imported [Annoted SPEC] deriving (Show, Typeable)
data VIEW_TYPE = View_type (Annoted SPEC) (Annoted SPEC) Range
deriving (Show, Typeable)
-- pos: "to"
data EQUIV_TYPE = Equiv_type OmsOrNetwork OmsOrNetwork Range
deriving (Show, Typeable)
-- pos: "<->"
data MODULE_TYPE = Module_type (Annoted SPEC) (Annoted SPEC) Range
deriving (Show, Typeable)
data ALIGN_ARITIES = Align_arities ALIGN_ARITY ALIGN_ARITY
deriving (Show, Typeable)
data ALIGN_ARITY = AA_InjectiveAndTotal | AA_Injective | AA_Total
| AA_NeitherInjectiveNorTotal
deriving (Show, Enum, Bounded, Typeable)
data OmsOrNetwork = MkOms (Annoted SPEC)
| MkNetwork Network
deriving (Show, Typeable)
data ENTAIL_TYPE = Entail_type OmsOrNetwork OmsOrNetwork Range
| OMSInNetwork IRI Network SPEC Range
deriving (Show, Typeable)
-- pos "entails"
showAlignArity :: ALIGN_ARITY -> String
showAlignArity ar = case ar of
AA_InjectiveAndTotal -> "1"
AA_Injective -> "?"
AA_Total -> "+"
AA_NeitherInjectiveNorTotal -> "*"
data ItemNameMap =
ItemNameMap IRI (Maybe IRI)
deriving (Show, Eq, Typeable)
makeLogicItem :: Language lid => lid -> Annoted LIB_ITEM
makeLogicItem lid = emptyAnno $ Logic_decl
(nameToLogicDescr $ Logic_name
(language_name lid) Nothing Nothing) nullRange
makeSpecItem :: SPEC_NAME -> Annoted SPEC -> Annoted LIB_ITEM
makeSpecItem sn as =
emptyAnno $ Spec_defn sn emptyGenericity as nullRange
fromBasicSpec :: LibName -> SPEC_NAME -> G_basic_spec -> LIB_DEFN
fromBasicSpec ln sn gbs =
Lib_defn ln [makeSpecItem sn $ makeSpec gbs] nullRange []
getDeclSpecNames :: LIB_ITEM -> [IRI]
getDeclSpecNames li = case li of
Spec_defn sn _ _ _ -> [sn]
Download_items _ di _ -> getImportNames di
_ -> []
getImportNames :: DownloadItems -> [IRI]
getImportNames di = case di of
ItemMaps im -> map (\ (ItemNameMap i mi) -> fromMaybe i mi) im
UniqueItem i -> [i]
getOms :: OmsOrNetwork -> [SPEC]
getOms o = case o of
MkOms s -> [item s]
MkNetwork _ -> []
getSpecDef :: LIB_ITEM -> [SPEC]
getSpecDef li = case li of
Spec_defn _ _ as _ -> [item as]
View_defn _ _ (View_type s1 s2 _) _ _ -> [item s1, item s2]
Entail_defn _ (Entail_type s1 s2 _) _ -> getOms s1 ++ getOms s2
Equiv_defn _ (Equiv_type s1 s2 _) as _ ->
getOms s1 ++ getOms s2 ++ getOms as
Align_defn _ _ (View_type s1 s2 _) _ _ _ -> [item s1, item s2]
Module_defn _ (Module_type s1 s2 _) _ _ -> [item s1, item s2]
_ -> []
| keithodulaigh/Hets | Syntax/AS_Library.der.hs | gpl-2.0 | 7,047 | 0 | 13 | 1,758 | 1,569 | 828 | 741 | 119 | 7 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.StorageGateway.UpdateGatewaySoftwareNow
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | This operation updates the gateway virtual machine (VM) software. The request
-- immediately triggers the software update.
--
-- When you make this request, you get a '200 OK' success response immediately.
-- However, it might take some time for the update to complete. You can call 'DescribeGatewayInformation' to verify the gateway is in the 'STATE_RUNNING' state. A software update
-- forces a system restart of your gateway. You can minimize the chance of any
-- disruption to your applications by increasing your iSCSI Initiators'
-- timeouts. For more information about increasing iSCSI Initiator timeouts for
-- Windows and Linux, see <http://docs.aws.amazon.com/storagegateway/latest/userguide/ConfiguringiSCSIClientInitiatorWindowsClient.html#CustomizeWindowsiSCSISettings Customizing Your Windows iSCSI Settings> and <http://docs.aws.amazon.com/storagegateway/latest/userguide/ConfiguringiSCSIClientInitiatorRedHatClient.html#CustomizeLinuxiSCSISettings Customizing Your Linux iSCSI Settings>, respectively.
--
-- <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateGatewaySoftwareNow.html>
module Network.AWS.StorageGateway.UpdateGatewaySoftwareNow
(
-- * Request
UpdateGatewaySoftwareNow
-- ** Request constructor
, updateGatewaySoftwareNow
-- ** Request lenses
, ugsnGatewayARN
-- * Response
, UpdateGatewaySoftwareNowResponse
-- ** Response constructor
, updateGatewaySoftwareNowResponse
-- ** Response lenses
, ugsnrGatewayARN
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.StorageGateway.Types
import qualified GHC.Exts
newtype UpdateGatewaySoftwareNow = UpdateGatewaySoftwareNow
{ _ugsnGatewayARN :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'UpdateGatewaySoftwareNow' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ugsnGatewayARN' @::@ 'Text'
--
updateGatewaySoftwareNow :: Text -- ^ 'ugsnGatewayARN'
-> UpdateGatewaySoftwareNow
updateGatewaySoftwareNow p1 = UpdateGatewaySoftwareNow
{ _ugsnGatewayARN = p1
}
ugsnGatewayARN :: Lens' UpdateGatewaySoftwareNow Text
ugsnGatewayARN = lens _ugsnGatewayARN (\s a -> s { _ugsnGatewayARN = a })
newtype UpdateGatewaySoftwareNowResponse = UpdateGatewaySoftwareNowResponse
{ _ugsnrGatewayARN :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'UpdateGatewaySoftwareNowResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ugsnrGatewayARN' @::@ 'Maybe' 'Text'
--
updateGatewaySoftwareNowResponse :: UpdateGatewaySoftwareNowResponse
updateGatewaySoftwareNowResponse = UpdateGatewaySoftwareNowResponse
{ _ugsnrGatewayARN = Nothing
}
ugsnrGatewayARN :: Lens' UpdateGatewaySoftwareNowResponse (Maybe Text)
ugsnrGatewayARN = lens _ugsnrGatewayARN (\s a -> s { _ugsnrGatewayARN = a })
instance ToPath UpdateGatewaySoftwareNow where
toPath = const "/"
instance ToQuery UpdateGatewaySoftwareNow where
toQuery = const mempty
instance ToHeaders UpdateGatewaySoftwareNow
instance ToJSON UpdateGatewaySoftwareNow where
toJSON UpdateGatewaySoftwareNow{..} = object
[ "GatewayARN" .= _ugsnGatewayARN
]
instance AWSRequest UpdateGatewaySoftwareNow where
type Sv UpdateGatewaySoftwareNow = StorageGateway
type Rs UpdateGatewaySoftwareNow = UpdateGatewaySoftwareNowResponse
request = post "UpdateGatewaySoftwareNow"
response = jsonResponse
instance FromJSON UpdateGatewaySoftwareNowResponse where
parseJSON = withObject "UpdateGatewaySoftwareNowResponse" $ \o -> UpdateGatewaySoftwareNowResponse
<$> o .:? "GatewayARN"
| kim/amazonka | amazonka-storagegateway/gen/Network/AWS/StorageGateway/UpdateGatewaySoftwareNow.hs | mpl-2.0 | 4,801 | 0 | 9 | 850 | 463 | 283 | 180 | 56 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="id-ID">
<title>Laporan ekspor | ZAP Ekstensi</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Isi</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Indeks</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Mencari</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorit</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/exportreport/src/main/javahelp/org/zaproxy/zap/extension/exportreport/resources/help_id_ID/helpset_id_ID.hs | apache-2.0 | 970 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ru-RU">
<title>ToDo-List</title>
<maps>
<homeID>todo</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> | denniskniep/zap-extensions | addOns/todo/src/main/javahelp/help_ru_RU/helpset_ru_RU.hs | apache-2.0 | 955 | 77 | 67 | 155 | 408 | 207 | 201 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PolyKinds #-}
#ifdef USE_TEMPLATE_HASKELL
{-# LANGUAGE TemplateHaskell #-}
#endif
{-# LANGUAGE TypeFamilies #-}
module Reflex.Dom.Builder.Class.Events where
#ifdef USE_TEMPLATE_HASKELL
import Data.GADT.Compare.TH
#else
import Data.GADT.Compare
(GOrdering(..), (:~:)(..), GEq(..), GCompare(..))
#endif
import Data.Text (Text)
data EventTag
= AbortTag
| BlurTag
| ChangeTag
| ClickTag
| ContextmenuTag
| DblclickTag
| DragTag
| DragendTag
| DragenterTag
| DragleaveTag
| DragoverTag
| DragstartTag
| DropTag
| ErrorTag
| FocusTag
| InputTag
| InvalidTag
| KeydownTag
| KeypressTag
| KeyupTag
| LoadTag
| MousedownTag
| MouseenterTag
| MouseleaveTag
| MousemoveTag
| MouseoutTag
| MouseoverTag
| MouseupTag
| MousewheelTag
| ScrollTag
| SelectTag
| SubmitTag
| WheelTag
| BeforecutTag
| CutTag
| BeforecopyTag
| CopyTag
| BeforepasteTag
| PasteTag
| ResetTag
| SearchTag
| SelectstartTag
| TouchstartTag
| TouchmoveTag
| TouchendTag
| TouchcancelTag
data EventName :: EventTag -> * where
Abort :: EventName 'AbortTag
Blur :: EventName 'BlurTag
Change :: EventName 'ChangeTag
Click :: EventName 'ClickTag
Contextmenu :: EventName 'ContextmenuTag
Dblclick :: EventName 'DblclickTag
Drag :: EventName 'DragTag
Dragend :: EventName 'DragendTag
Dragenter :: EventName 'DragenterTag
Dragleave :: EventName 'DragleaveTag
Dragover :: EventName 'DragoverTag
Dragstart :: EventName 'DragstartTag
Drop :: EventName 'DropTag
Error :: EventName 'ErrorTag
Focus :: EventName 'FocusTag
Input :: EventName 'InputTag
Invalid :: EventName 'InvalidTag
Keydown :: EventName 'KeydownTag
Keypress :: EventName 'KeypressTag
Keyup :: EventName 'KeyupTag
Load :: EventName 'LoadTag
Mousedown :: EventName 'MousedownTag
Mouseenter :: EventName 'MouseenterTag
Mouseleave :: EventName 'MouseleaveTag
Mousemove :: EventName 'MousemoveTag
Mouseout :: EventName 'MouseoutTag
Mouseover :: EventName 'MouseoverTag
Mouseup :: EventName 'MouseupTag
Mousewheel :: EventName 'MousewheelTag
Scroll :: EventName 'ScrollTag
Select :: EventName 'SelectTag
Submit :: EventName 'SubmitTag
Wheel :: EventName 'WheelTag
Beforecut :: EventName 'BeforecutTag
Cut :: EventName 'CutTag
Beforecopy :: EventName 'BeforecopyTag
Copy :: EventName 'CopyTag
Beforepaste :: EventName 'BeforepasteTag
Paste :: EventName 'PasteTag
Reset :: EventName 'ResetTag
Search :: EventName 'SearchTag
Selectstart :: EventName 'SelectstartTag
Touchstart :: EventName 'TouchstartTag
Touchmove :: EventName 'TouchmoveTag
Touchend :: EventName 'TouchendTag
Touchcancel :: EventName 'TouchcancelTag
newtype EventResult en = EventResult { unEventResult :: EventResultType en }
type family EventResultType (en :: EventTag) :: * where
EventResultType 'ClickTag = ()
EventResultType 'DblclickTag = (Int, Int)
EventResultType 'KeypressTag = Word
EventResultType 'KeydownTag = Word
EventResultType 'KeyupTag = Word
EventResultType 'ScrollTag = Double
EventResultType 'MousemoveTag = (Int, Int)
EventResultType 'MousedownTag = (Int, Int)
EventResultType 'MouseupTag = (Int, Int)
EventResultType 'MouseenterTag = ()
EventResultType 'MouseleaveTag = ()
EventResultType 'FocusTag = ()
EventResultType 'BlurTag = ()
EventResultType 'ChangeTag = ()
EventResultType 'DragTag = ()
EventResultType 'DragendTag = ()
EventResultType 'DragenterTag = ()
EventResultType 'DragleaveTag = ()
EventResultType 'DragoverTag = ()
EventResultType 'DragstartTag = ()
EventResultType 'DropTag = ()
EventResultType 'AbortTag = ()
EventResultType 'ContextmenuTag = ()
EventResultType 'ErrorTag = ()
EventResultType 'InputTag = ()
EventResultType 'InvalidTag = ()
EventResultType 'LoadTag = ()
EventResultType 'MouseoutTag = ()
EventResultType 'MouseoverTag = ()
EventResultType 'MousewheelTag = ()
EventResultType 'SelectTag = ()
EventResultType 'SubmitTag = ()
EventResultType 'BeforecutTag = ()
EventResultType 'CutTag = ()
EventResultType 'BeforecopyTag = ()
EventResultType 'CopyTag = ()
EventResultType 'BeforepasteTag = ()
EventResultType 'PasteTag = Maybe Text
EventResultType 'ResetTag = ()
EventResultType 'SearchTag = ()
EventResultType 'SelectstartTag = ()
EventResultType 'TouchstartTag = TouchEventResult
EventResultType 'TouchmoveTag = TouchEventResult
EventResultType 'TouchendTag = TouchEventResult
EventResultType 'TouchcancelTag = TouchEventResult
EventResultType 'WheelTag = WheelEventResult
data DeltaMode = DeltaPixel | DeltaLine | DeltaPage
deriving (Show, Read, Eq, Ord, Bounded, Enum)
data WheelEventResult = WheelEventResult
{ _wheelEventResult_deltaX :: Double
, _wheelEventResult_deltaY :: Double
, _wheelEventResult_deltaZ :: Double
, _wheelEventResult_deltaMode :: DeltaMode
} deriving (Show, Read, Eq, Ord)
data TouchEventResult = TouchEventResult
{ _touchEventResult_altKey :: Bool
, _touchEventResult_changedTouches :: [TouchResult]
, _touchEventResult_ctrlKey :: Bool
, _touchEventResult_metaKey :: Bool
, _touchEventResult_shiftKey :: Bool
, _touchEventResult_targetTouches :: [TouchResult]
, _touchEventResult_touches :: [TouchResult]
}
deriving (Show, Read, Eq, Ord)
data TouchResult = TouchResult
{ _touchResult_identifier :: Word
, _touchResult_screenX :: Int
, _touchResult_screenY :: Int
, _touchResult_clientX :: Int
, _touchResult_clientY :: Int
, _touchResult_pageX :: Int
, _touchResult_pageY :: Int
}
deriving (Show, Read, Eq, Ord)
#ifdef USE_TEMPLATE_HASKELL
deriveGEq ''EventName
deriveGCompare ''EventName
#else
instance GEq EventName
where geq Abort Abort = return Refl
geq Blur Blur = return Refl
geq Change Change = return Refl
geq Click Click = return Refl
geq Contextmenu Contextmenu = return Refl
geq Dblclick Dblclick = return Refl
geq Drag Drag = return Refl
geq Dragend Dragend = return Refl
geq Dragenter Dragenter = return Refl
geq Dragleave Dragleave = return Refl
geq Dragover Dragover = return Refl
geq Dragstart Dragstart = return Refl
geq Drop Drop = return Refl
geq Error Error = return Refl
geq Focus Focus = return Refl
geq Input Input = return Refl
geq Invalid Invalid = return Refl
geq Keydown Keydown = return Refl
geq Keypress Keypress = return Refl
geq Keyup Keyup = return Refl
geq Load Load = return Refl
geq Mousedown Mousedown = return Refl
geq Mouseenter Mouseenter = return Refl
geq Mouseleave Mouseleave = return Refl
geq Mousemove Mousemove = return Refl
geq Mouseout Mouseout = return Refl
geq Mouseover Mouseover = return Refl
geq Mouseup Mouseup = return Refl
geq Mousewheel Mousewheel = return Refl
geq Scroll Scroll = return Refl
geq Select Select = return Refl
geq Submit Submit = return Refl
geq Wheel Wheel = return Refl
geq Beforecut Beforecut = return Refl
geq Cut Cut = return Refl
geq Beforecopy Beforecopy = return Refl
geq Copy Copy = return Refl
geq Beforepaste Beforepaste = return Refl
geq Paste Paste = return Refl
geq Reset Reset = return Refl
geq Search Search = return Refl
geq Selectstart Selectstart = return Refl
geq Touchstart Touchstart = return Refl
geq Touchmove Touchmove = return Refl
geq Touchend Touchend = return Refl
geq Touchcancel Touchcancel = return Refl
geq _ _ = Nothing
instance GCompare EventName
where gcompare Abort Abort = GEQ
gcompare Abort _ = GLT
gcompare _ Abort = GGT
gcompare Blur Blur = GEQ
gcompare Blur _ = GLT
gcompare _ Blur = GGT
gcompare Change Change = GEQ
gcompare Change _ = GLT
gcompare _ Change = GGT
gcompare Click Click = GEQ
gcompare Click _ = GLT
gcompare _ Click = GGT
gcompare Contextmenu Contextmenu = GEQ
gcompare Contextmenu _ = GLT
gcompare _ Contextmenu = GGT
gcompare Dblclick Dblclick = GEQ
gcompare Dblclick _ = GLT
gcompare _ Dblclick = GGT
gcompare Drag Drag = GEQ
gcompare Drag _ = GLT
gcompare _ Drag = GGT
gcompare Dragend Dragend = GEQ
gcompare Dragend _ = GLT
gcompare _ Dragend = GGT
gcompare Dragenter Dragenter = GEQ
gcompare Dragenter _ = GLT
gcompare _ Dragenter = GGT
gcompare Dragleave Dragleave = GEQ
gcompare Dragleave _ = GLT
gcompare _ Dragleave = GGT
gcompare Dragover Dragover = GEQ
gcompare Dragover _ = GLT
gcompare _ Dragover = GGT
gcompare Dragstart Dragstart = GEQ
gcompare Dragstart _ = GLT
gcompare _ Dragstart = GGT
gcompare Drop Drop = GEQ
gcompare Drop _ = GLT
gcompare _ Drop = GGT
gcompare Error Error = GEQ
gcompare Error _ = GLT
gcompare _ Error = GGT
gcompare Focus Focus = GEQ
gcompare Focus _ = GLT
gcompare _ Focus = GGT
gcompare Input Input = GEQ
gcompare Input _ = GLT
gcompare _ Input = GGT
gcompare Invalid Invalid = GEQ
gcompare Invalid _ = GLT
gcompare _ Invalid = GGT
gcompare Keydown Keydown = GEQ
gcompare Keydown _ = GLT
gcompare _ Keydown = GGT
gcompare Keypress Keypress = GEQ
gcompare Keypress _ = GLT
gcompare _ Keypress = GGT
gcompare Keyup Keyup = GEQ
gcompare Keyup _ = GLT
gcompare _ Keyup = GGT
gcompare Load Load = GEQ
gcompare Load _ = GLT
gcompare _ Load = GGT
gcompare Mousedown Mousedown = GEQ
gcompare Mousedown _ = GLT
gcompare _ Mousedown = GGT
gcompare Mouseenter Mouseenter = GEQ
gcompare Mouseenter _ = GLT
gcompare _ Mouseenter = GGT
gcompare Mouseleave Mouseleave = GEQ
gcompare Mouseleave _ = GLT
gcompare _ Mouseleave = GGT
gcompare Mousemove Mousemove = GEQ
gcompare Mousemove _ = GLT
gcompare _ Mousemove = GGT
gcompare Mouseout Mouseout = GEQ
gcompare Mouseout _ = GLT
gcompare _ Mouseout = GGT
gcompare Mouseover Mouseover = GEQ
gcompare Mouseover _ = GLT
gcompare _ Mouseover = GGT
gcompare Mouseup Mouseup = GEQ
gcompare Mouseup _ = GLT
gcompare _ Mouseup = GGT
gcompare Mousewheel Mousewheel = GEQ
gcompare Mousewheel _ = GLT
gcompare _ Mousewheel = GGT
gcompare Scroll Scroll = GEQ
gcompare Scroll _ = GLT
gcompare _ Scroll = GGT
gcompare Select Select = GEQ
gcompare Select _ = GLT
gcompare _ Select = GGT
gcompare Submit Submit = GEQ
gcompare Submit _ = GLT
gcompare _ Submit = GGT
gcompare Wheel Wheel = GEQ
gcompare Wheel _ = GLT
gcompare _ Wheel = GGT
gcompare Beforecut Beforecut = GEQ
gcompare Beforecut _ = GLT
gcompare _ Beforecut = GGT
gcompare Cut Cut = GEQ
gcompare Cut _ = GLT
gcompare _ Cut = GGT
gcompare Beforecopy Beforecopy = GEQ
gcompare Beforecopy _ = GLT
gcompare _ Beforecopy = GGT
gcompare Copy Copy = GEQ
gcompare Copy _ = GLT
gcompare _ Copy = GGT
gcompare Beforepaste Beforepaste = GEQ
gcompare Beforepaste _ = GLT
gcompare _ Beforepaste = GGT
gcompare Paste Paste = GEQ
gcompare Paste _ = GLT
gcompare _ Paste = GGT
gcompare Reset Reset = GEQ
gcompare Reset _ = GLT
gcompare _ Reset = GGT
gcompare Search Search = GEQ
gcompare Search _ = GLT
gcompare _ Search = GGT
gcompare Selectstart Selectstart = GEQ
gcompare Selectstart _ = GLT
gcompare _ Selectstart = GGT
gcompare Touchstart Touchstart = GEQ
gcompare Touchstart _ = GLT
gcompare _ Touchstart = GGT
gcompare Touchmove Touchmove = GEQ
gcompare Touchmove _ = GLT
gcompare _ Touchmove = GGT
gcompare Touchend Touchend = GEQ
gcompare Touchend _ = GLT
gcompare _ Touchend = GGT
gcompare Touchcancel Touchcancel = GEQ
#endif
| reflex-frp/reflex-dom | reflex-dom-core/src/Reflex/Dom/Builder/Class/Events.hs | bsd-3-clause | 14,967 | 0 | 9 | 5,783 | 1,494 | 815 | 679 | 362 | 0 |
{-
(c) The GRASP/AQUA Project, Glasgow University, 1993-1998
\section[StgLint]{A ``lint'' pass to check for Stg correctness}
-}
{-# LANGUAGE CPP #-}
module Eta.StgSyn.StgLint ( lintStgBindings ) where
import Eta.StgSyn.StgSyn
import Eta.Utils.Bag ( Bag, emptyBag, isEmptyBag, snocBag, bagToList )
import Eta.BasicTypes.Id ( Id, idType, isLocalId )
import Eta.BasicTypes.VarSet
import Eta.BasicTypes.DataCon
import Eta.Core.CoreSyn ( AltCon(..) )
import Eta.Prelude.PrimOp ( primOpType )
import Eta.BasicTypes.Literal ( literalType )
import Eta.Utils.Maybes
import Eta.BasicTypes.Name ( getSrcLoc )
import Eta.Main.ErrUtils ( MsgDoc, Severity(..), mkLocMessage )
import Eta.Types.TypeRep
import Eta.Types.Type
import Eta.Types.TyCon
import Eta.Utils.Util
import Eta.BasicTypes.SrcLoc
import Eta.Utils.Outputable
import qualified Eta.Utils.Outputable as Outputable
import Eta.Utils.FastString
import Control.Monad
import Data.Function
#include "HsVersions.h"
{-
Checks for
(a) *some* type errors
(b) locally-defined variables used but not defined
Note: unless -dverbose-stg is on, display of lint errors will result
in "panic: bOGUS_LVs".
WARNING:
~~~~~~~~
This module has suffered bit-rot; it is likely to yield lint errors
for Stg code that is currently perfectly acceptable for code
generation. Solution: don't use it! (KSW 2000-05).
************************************************************************
* *
\subsection{``lint'' for various constructs}
* *
************************************************************************
@lintStgBindings@ is the top-level interface function.
-}
lintStgBindings :: String -> [StgBinding] -> [StgBinding]
lintStgBindings whodunnit binds
= {-# SCC "StgLint" #-}
case (initL (lint_binds binds)) of
Nothing -> binds
Just msg -> pprPanic "" (vcat [
ptext (sLit "*** Stg Lint ErrMsgs: in") <+>
text whodunnit <+> ptext (sLit "***"),
msg,
ptext (sLit "*** Offending Program ***"),
pprStgBindings binds,
ptext (sLit "*** End of Offense ***")])
where
lint_binds :: [StgBinding] -> LintM ()
lint_binds [] = return ()
lint_binds (bind:binds) = do
binders <- lintStgBinds bind
addInScopeVars binders $
lint_binds binds
lintStgArg :: StgArg -> LintM (Maybe Type)
lintStgArg (StgLitArg lit) = return (Just (literalType lit))
lintStgArg (StgVarArg v) = lintStgVar v
lintStgVar :: Id -> LintM (Maybe Kind)
lintStgVar v = do checkInScope v
return (Just (idType v))
lintStgBinds :: StgBinding -> LintM [Id] -- Returns the binders
lintStgBinds (StgNonRec binder rhs) = do
lint_binds_help (binder,rhs)
return [binder]
lintStgBinds (StgRec pairs)
= addInScopeVars binders $ do
mapM_ lint_binds_help pairs
return binders
where
binders = [b | (b,_) <- pairs]
lint_binds_help :: (Id, StgRhs) -> LintM ()
lint_binds_help (binder, rhs)
= addLoc (RhsOf binder) $ do
-- Check the rhs
_maybe_rhs_ty <- lintStgRhs rhs
-- Check binder doesn't have unlifted type
checkL (not (isUnLiftedType binder_ty))
(mkUnLiftedTyMsg binder rhs)
-- Check match to RHS type
-- Actually we *can't* check the RHS type, because
-- unsafeCoerce means it really might not match at all
-- notably; eg x::Int = (error @Bool "urk") |> unsafeCoerce...
-- case maybe_rhs_ty of
-- Nothing -> return ()
-- Just rhs_ty -> checkTys binder_ty
-- rhs_ty
--- (mkRhsMsg binder rhs_ty)
return ()
where
binder_ty = idType binder
lintStgRhs :: StgRhs -> LintM (Maybe Type) -- Just ty => type is exact
lintStgRhs (StgRhsClosure _ _ _ _ _ [] expr)
= lintStgExpr expr
lintStgRhs (StgRhsClosure _ _ _ _ _ binders expr)
= addLoc (LambdaBodyOf binders) $
addInScopeVars binders $ runMaybeT $ do
body_ty <- MaybeT $ lintStgExpr expr
return (mkFunTys (map idType binders) body_ty)
lintStgRhs (StgRhsCon _ con args) = runMaybeT $ do
arg_tys <- mapM (MaybeT . lintStgArg) args
MaybeT $ checkFunApp con_ty arg_tys (mkRhsConMsg con_ty arg_tys)
where
con_ty = dataConRepType con
lintStgExpr :: StgExpr -> LintM (Maybe Type) -- Just ty => type is exact
lintStgExpr (StgLit l) = return (Just (literalType l))
lintStgExpr e@(StgApp fun args) = runMaybeT $ do
fun_ty <- MaybeT $ lintStgVar fun
arg_tys <- mapM (MaybeT . lintStgArg) args
MaybeT $ checkFunApp fun_ty arg_tys (mkFunAppMsg fun_ty arg_tys e)
lintStgExpr e@(StgConApp con args) = runMaybeT $ do
arg_tys <- mapM (MaybeT . lintStgArg) args
MaybeT $ checkFunApp con_ty arg_tys (mkFunAppMsg con_ty arg_tys e)
where
con_ty = dataConRepType con
lintStgExpr e@(StgOpApp (StgPrimOp op) args _) = runMaybeT $ do
arg_tys <- mapM (MaybeT . lintStgArg) args
MaybeT $ checkFunApp op_ty arg_tys (mkFunAppMsg op_ty arg_tys e)
where
op_ty = primOpType op
lintStgExpr (StgOpApp _ args res_ty) = runMaybeT $ do
-- We don't have enough type information to check
-- the application for StgFCallOp and StgPrimCallOp; ToDo
_maybe_arg_tys <- mapM (MaybeT . lintStgArg) args
return res_ty
lintStgExpr (StgLam bndrs _) = do
addErrL (ptext (sLit "Unexpected StgLam") <+> ppr bndrs)
return Nothing
lintStgExpr (StgLet binds body) = do
binders <- lintStgBinds binds
addLoc (BodyOfLetRec binders) $
addInScopeVars binders $
lintStgExpr body
lintStgExpr (StgLetNoEscape _ _ binds body) = do
binders <- lintStgBinds binds
addLoc (BodyOfLetRec binders) $
addInScopeVars binders $
lintStgExpr body
lintStgExpr (StgTick _ expr) = lintStgExpr expr
lintStgExpr (StgCase scrut _ _ bndr _ alts_type alts) = runMaybeT $ do
_ <- MaybeT $ lintStgExpr scrut
in_scope <- MaybeT $ liftM Just $
case alts_type of
AlgAlt tc -> check_bndr tc >> return True
PrimAlt tc -> check_bndr tc >> return True
UbxTupAlt _ -> return False -- Binder is always dead in this case
PolyAlt -> return True
MaybeT $ addInScopeVars [bndr | in_scope] $
lintStgAlts alts scrut_ty
where
scrut_ty = idType bndr
UnaryRep scrut_rep = repType scrut_ty -- Not used if scrutinee is unboxed tuple
check_bndr tc = case tyConAppTyCon_maybe scrut_rep of
Just bndr_tc -> checkL (tc == bndr_tc) bad_bndr
Nothing -> addErrL bad_bndr
where
bad_bndr = mkDefltMsg bndr tc
lintStgAlts :: [StgAlt]
-> Type -- Type of scrutinee
-> LintM (Maybe Type) -- Just ty => type is accurage
lintStgAlts alts scrut_ty = do
maybe_result_tys <- mapM (lintAlt scrut_ty) alts
-- Check the result types
case catMaybes (maybe_result_tys) of
[] -> return Nothing
(first_ty:_tys) -> do -- mapM_ check tys
return (Just first_ty)
where
-- check ty = checkTys first_ty ty (mkCaseAltMsg alts)
-- We can't check that the alternatives have the
-- same type, because they don't, with unsafeCoerce#
lintAlt :: Type -> (AltCon, [Id], [Bool], StgExpr) -> LintM (Maybe Type)
lintAlt _ (DEFAULT, _, _, rhs)
= lintStgExpr rhs
lintAlt scrut_ty (LitAlt lit, _, _, rhs) = do
checkTys (literalType lit) scrut_ty (mkAltMsg1 scrut_ty)
lintStgExpr rhs
lintAlt scrut_ty (DataAlt con, args, _, rhs) = do
case splitTyConApp_maybe scrut_ty of
Just (tycon, tys_applied) | isAlgTyCon tycon &&
not (isNewTyCon tycon) -> do
let
cons = tyConDataCons tycon
arg_tys = dataConInstArgTys con tys_applied
-- This does not work for existential constructors
checkL (con `elem` cons) (mkAlgAltMsg2 scrut_ty con)
checkL (length args == dataConRepArity con) (mkAlgAltMsg3 con args)
when (isVanillaDataCon con) $
mapM_ check (zipEqual "lintAlgAlt:stg" arg_tys args)
return ()
_ ->
addErrL (mkAltMsg1 scrut_ty)
addInScopeVars args $
lintStgExpr rhs
where
check (ty, arg) = checkTys ty (idType arg) (mkAlgAltMsg4 ty arg)
-- elem: yes, the elem-list here can sometimes be long-ish,
-- but as it's use-once, probably not worth doing anything different
-- We give it its own copy, so it isn't overloaded.
elem _ [] = False
elem x (y:ys) = x==y || elem x ys
{-
************************************************************************
* *
\subsection[lint-monad]{The Lint monad}
* *
************************************************************************
-}
newtype LintM a = LintM
{ unLintM :: [LintLocInfo] -- Locations
-> IdSet -- Local vars in scope
-> Bag MsgDoc -- Error messages so far
-> (a, Bag MsgDoc) -- Result and error messages (if any)
}
data LintLocInfo
= RhsOf Id -- The variable bound
| LambdaBodyOf [Id] -- The lambda-binder
| BodyOfLetRec [Id] -- One of the binders
dumpLoc :: LintLocInfo -> (SrcSpan, SDoc)
dumpLoc (RhsOf v) =
(srcLocSpan (getSrcLoc v), ptext (sLit " [RHS of ") <> pp_binders [v] <> char ']' )
dumpLoc (LambdaBodyOf bs) =
(srcLocSpan (getSrcLoc (head bs)), ptext (sLit " [in body of lambda with binders ") <> pp_binders bs <> char ']' )
dumpLoc (BodyOfLetRec bs) =
(srcLocSpan (getSrcLoc (head bs)), ptext (sLit " [in body of letrec with binders ") <> pp_binders bs <> char ']' )
pp_binders :: [Id] -> SDoc
pp_binders bs
= sep (punctuate comma (map pp_binder bs))
where
pp_binder b
= hsep [ppr b, dcolon, ppr (idType b)]
initL :: LintM a -> Maybe MsgDoc
initL (LintM m)
= case (m [] emptyVarSet emptyBag) of { (_, errs) ->
if isEmptyBag errs then
Nothing
else
Just (vcat (punctuate blankLine (bagToList errs)))
}
instance Functor LintM where
fmap = liftM
instance Applicative LintM where
pure = return
(<*>) = ap
instance Monad LintM where
return a = LintM $ \_loc _scope errs -> (a, errs)
(>>=) = thenL
(>>) = thenL_
thenL :: LintM a -> (a -> LintM b) -> LintM b
thenL m k = LintM $ \loc scope errs
-> case unLintM m loc scope errs of
(r, errs') -> unLintM (k r) loc scope errs'
thenL_ :: LintM a -> LintM b -> LintM b
thenL_ m k = LintM $ \loc scope errs
-> case unLintM m loc scope errs of
(_, errs') -> unLintM k loc scope errs'
checkL :: Bool -> MsgDoc -> LintM ()
checkL True _ = return ()
checkL False msg = addErrL msg
addErrL :: MsgDoc -> LintM ()
addErrL msg = LintM $ \loc _scope errs -> ((), addErr errs msg loc)
addErr :: Bag MsgDoc -> MsgDoc -> [LintLocInfo] -> Bag MsgDoc
addErr errs_so_far msg locs
= errs_so_far `snocBag` mk_msg locs
where
mk_msg (loc:_) = let (l,hdr) = dumpLoc loc
in mkLocMessage SevWarning l (hdr $$ msg)
mk_msg [] = msg
addLoc :: LintLocInfo -> LintM a -> LintM a
addLoc extra_loc m = LintM $ \loc scope errs
-> unLintM m (extra_loc:loc) scope errs
addInScopeVars :: [Id] -> LintM a -> LintM a
addInScopeVars ids m = LintM $ \loc scope errs
-> -- We check if these "new" ids are already
-- in scope, i.e., we have *shadowing* going on.
-- For now, it's just a "trace"; we may make
-- a real error out of it...
let
new_set = mkVarSet ids
in
-- After adding -fliberate-case, Simon decided he likes shadowed
-- names after all. WDP 94/07
-- (if isEmptyVarSet shadowed
-- then id
-- else pprTrace "Shadowed vars:" (ppr (varSetElems shadowed))) $
unLintM m loc (scope `unionVarSet` new_set) errs
{-
Checking function applications: we only check that the type has the
right *number* of arrows, we don't actually compare the types. This
is because we can't expect the types to be equal - the type
applications and type lambdas that we use to calculate accurate types
have long since disappeared.
-}
checkFunApp :: Type -- The function type
-> [Type] -- The arg type(s)
-> MsgDoc -- Error message
-> LintM (Maybe Type) -- Just ty => result type is accurate
checkFunApp fun_ty arg_tys msg
= do { case mb_msg of
Just msg -> addErrL msg
Nothing -> return ()
; return mb_ty }
where
(mb_ty, mb_msg) = cfa True fun_ty arg_tys
cfa :: Bool -> Type -> [Type] -> (Maybe Type -- Accurate result?
, Maybe MsgDoc) -- Errors?
cfa accurate fun_ty [] -- Args have run out; that's fine
= (if accurate then Just fun_ty else Nothing, Nothing)
cfa accurate fun_ty arg_tys@(arg_ty':arg_tys')
| Just (arg_ty, res_ty) <- splitFunTy_maybe fun_ty
= if accurate && not (arg_ty `stgEqType` arg_ty')
then (Nothing, Just msg) -- Arg type mismatch
else cfa accurate res_ty arg_tys'
| Just (_, fun_ty') <- splitForAllTy_maybe fun_ty
= cfa False fun_ty' arg_tys
| Just (tc,tc_args) <- splitTyConApp_maybe fun_ty
, isNewTyCon tc
= if length tc_args < tyConArity tc
then WARN( True, text "cfa: unsaturated newtype" <+> ppr fun_ty $$ msg )
(Nothing, Nothing) -- This is odd, but I've seen it
else cfa False (newTyConInstRhs tc tc_args) arg_tys
| Just tc <- tyConAppTyCon_maybe fun_ty
, not (isTypeFamilyTyCon tc) -- Definite error
= (Nothing, Just msg) -- Too many args
| otherwise
= (Nothing, Nothing)
stgEqType :: Type -> Type -> Bool
-- Compare types, but crudely because we have discarded
-- both casts and type applications, so types might look
-- different but be the same. So reply "True" if in doubt.
-- "False" means that the types are definitely different.
--
-- Fundamentally this is a losing battle because of unsafeCoerce
stgEqType orig_ty1 orig_ty2
= gos (repType orig_ty1) (repType orig_ty2)
where
gos :: RepType -> RepType -> Bool
gos (UbxTupleRep tys1) (UbxTupleRep tys2)
= equalLength tys1 tys2 && and (zipWith go tys1 tys2)
gos (UnaryRep ty1) (UnaryRep ty2) = go ty1 ty2
gos _ _ = False
go :: UnaryType -> UnaryType -> Bool
go ty1 ty2
| Just (tc1, tc_args1) <- splitTyConApp_maybe ty1
, Just (tc2, tc_args2) <- splitTyConApp_maybe ty2
, let res = if tc1 == tc2
then equalLength tc_args1 tc_args2 && and (zipWith (gos `on` repType) tc_args1 tc_args2)
else -- TyCons don't match; but don't bleat if either is a
-- family TyCon because a coercion might have made it
-- equal to something else
(isFamilyTyCon tc1 || isFamilyTyCon tc2)
= if res then True
else
pprTrace "stgEqType: unequal" (vcat [ppr ty1, ppr ty2])
False
| otherwise = True -- Conservatively say "fine".
-- Type variables in particular
checkInScope :: Id -> LintM ()
checkInScope id = LintM $ \loc scope errs
-> if isLocalId id && not (id `elemVarSet` scope) then
((), addErr errs (hsep [ppr id, ptext (sLit "is out of scope")]) loc)
else
((), errs)
checkTys :: Type -> Type -> MsgDoc -> LintM ()
checkTys ty1 ty2 msg = LintM $ \loc _scope errs
-> if (ty1 `stgEqType` ty2)
then ((), errs)
else ((), addErr errs msg loc)
_mkCaseAltMsg :: [StgAlt] -> MsgDoc
_mkCaseAltMsg _alts
= ($$) (text "In some case alternatives, type of alternatives not all same:")
(Outputable.empty) -- LATER: ppr alts
mkDefltMsg :: Id -> TyCon -> MsgDoc
mkDefltMsg bndr tc
= ($$) (ptext (sLit "Binder of a case expression doesn't match type of scrutinee:"))
(ppr bndr $$ ppr (idType bndr) $$ ppr tc)
mkFunAppMsg :: Type -> [Type] -> StgExpr -> MsgDoc
mkFunAppMsg fun_ty arg_tys expr
= vcat [text "In a function application, function type doesn't match arg types:",
hang (ptext (sLit "Function type:")) 4 (ppr fun_ty),
hang (ptext (sLit "Arg types:")) 4 (vcat (map (ppr) arg_tys)),
hang (ptext (sLit "Expression:")) 4 (ppr expr)]
mkRhsConMsg :: Type -> [Type] -> MsgDoc
mkRhsConMsg fun_ty arg_tys
= vcat [text "In a RHS constructor application, con type doesn't match arg types:",
hang (ptext (sLit "Constructor type:")) 4 (ppr fun_ty),
hang (ptext (sLit "Arg types:")) 4 (vcat (map (ppr) arg_tys))]
mkAltMsg1 :: Type -> MsgDoc
mkAltMsg1 ty
= ($$) (text "In a case expression, type of scrutinee does not match patterns")
(ppr ty)
mkAlgAltMsg2 :: Type -> DataCon -> MsgDoc
mkAlgAltMsg2 ty con
= vcat [
text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
ppr ty,
ppr con
]
mkAlgAltMsg3 :: DataCon -> [Id] -> MsgDoc
mkAlgAltMsg3 con alts
= vcat [
text "In some algebraic case alternative, number of arguments doesn't match constructor:",
ppr con,
ppr alts
]
mkAlgAltMsg4 :: Type -> Id -> MsgDoc
mkAlgAltMsg4 ty arg
= vcat [
text "In some algebraic case alternative, type of argument doesn't match data constructor:",
ppr ty,
ppr arg
]
_mkRhsMsg :: Id -> Type -> MsgDoc
_mkRhsMsg binder ty
= vcat [hsep [ptext (sLit "The type of this binder doesn't match the type of its RHS:"),
ppr binder],
hsep [ptext (sLit "Binder's type:"), ppr (idType binder)],
hsep [ptext (sLit "Rhs type:"), ppr ty]
]
mkUnLiftedTyMsg :: Id -> StgRhs -> SDoc
mkUnLiftedTyMsg binder rhs
= (ptext (sLit "Let(rec) binder") <+> quotes (ppr binder) <+>
ptext (sLit "has unlifted type") <+> quotes (ppr (idType binder)))
$$
(ptext (sLit "RHS:") <+> ppr rhs)
| rahulmutt/ghcvm | compiler/Eta/StgSyn/StgLint.hs | bsd-3-clause | 18,470 | 0 | 19 | 5,281 | 4,948 | 2,530 | 2,418 | -1 | -1 |
{-# Language PatternGuards #-}
module Blub
( blub
, foo
, bar
) where
import Ugah.Foo
import Control.Applicative
import Ugah.Blub (a, b, c, d, e, f, g)
f :: Int -> Int
f = (+ 3)
g :: Int
g =
where
| jystic/hsimport | tests/goldenFiles/SymbolTest27.hs | bsd-3-clause | 213 | 0 | 5 | 58 | 82 | 52 | 30 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
module Main(main) where
import Data.Int
import DNA
import DDP
import DDP_Slice
----------------------------------------------------------------
-- Distributed dot product
----------------------------------------------------------------
-- | Actor for calculating dot product
ddpDotProduct :: Actor Int64 Double
ddpDotProduct = actor $ \size -> do
-- Chunk & send out
shell <- startGroup (Frac 1) (NNodes 1) $ do
useLocal
return $(mkStaticClosure 'ddpProductSlice)
broadcast (Slice 0 size) shell
-- Collect results
partials <- delayGroup shell
x <- duration "collecting vectors" $ gather partials (+) 0
return x
main :: IO ()
main = dnaRun rtable $ do
-- Vector size:
--
-- > 100e4 doubles per node = 800 MB per node
-- > 4 nodes
let n = 4*1000*1000
expected = fromIntegral n*(fromIntegral n-1)/2 * 0.1
-- Run it
b <- eval ddpDotProduct n
unboundKernel "output" [] $ liftIO $ putStrLn $ concat
[ "RESULT: ", show b
, " EXPECTED: ", show expected
, if b == expected then " -- ok" else " -- WRONG!"
]
where
rtable = DDP.__remoteTable
. DDP_Slice.__remoteTable
| SKA-ScienceDataProcessor/RC | MS6/dna/core/dna-programs/ddp-in-memory.hs | apache-2.0 | 1,231 | 0 | 16 | 311 | 313 | 161 | 152 | 26 | 2 |
-- Time-stamp: <2010-03-10 17:33:14 cklin>
module Common where
import Control.Monad (liftM)
import Data.List ((\\), nub, nubBy)
import Data.Map (Map, findWithDefault, fromList, toList)
type Endo a = a -> a
bug :: String -> a
bug msg = error ("BUG: " ++ msg)
same :: Eq a => [a] -> Bool
same [] = True
same xs = and (zipWith (==) (tail xs) xs)
unique :: [a] -> Maybe a
unique [x] = Just x
unique _ = Nothing
unions :: Eq a => [[a]] -> [a]
unions = nub . concat
unionMap :: Eq b => (a -> [b]) -> [a] -> [b]
unionMap f = unions . map f
map1st :: (a -> b) -> [(a, c)] -> [(b, c)]
map1st f = map (\(u, v) -> (f u, v))
nub1st :: Eq a => Endo [(a, b)]
nub1st = nubBy (\(a, _) (c, _) -> a == c)
overlaps :: Ord a => [a] -> [a] -> Bool
overlaps = any . flip elem
subset :: Eq a => [a] -> [a] -> Bool
subset ux wx = null (ux \\ wx)
lookupX :: Ord k => k -> Map k a -> a
lookupX = findWithDefault (bug "Missing key in lookupX")
lookupZ :: Ord k => k -> Map k k -> k
lookupZ k = findWithDefault k k
-- This is a version of Map.fromList that checks that there are no
-- duplicate keys in the input association list.
toMap :: (Ord k, Show k) => [(k, a)] -> Map k a
toMap assoc =
let keys = map fst assoc
dups = nub (keys \\ nub keys)
in if null dups then fromList assoc
else bug ("Duplicate keys " ++ show dups)
| minad/omega | vendor/algorithm-p/Common.hs | bsd-3-clause | 1,338 | 0 | 12 | 327 | 670 | 362 | 308 | 35 | 2 |
module Main where
import Control.Monad
import HROOT
main :: IO ()
main = do
tcanvas <- newTCanvas "Test" "Test" 640 480
h1 <- newTH1D "test" "test" 100 (-5.0) 5.0
let bx = [-11,-5,-3,-1,1,2,3,4]
setBins1 h1 7 bx
tRandom <- newTRandom 65535
let generator = gaus tRandom 0 2
let go n | n < 0 = return ()
| otherwise = do
histfill generator h1
go (n-1)
go 1000000
draw h1 ""
saveAs tcanvas "variablebins.pdf" ""
delete h1
delete tcanvas
histfill :: IO Double -> TH1D -> IO ()
histfill gen hist = do
x <- gen
fill1 hist x
return ()
| wavewave/HROOT | examples/variablebins.hs | gpl-3.0 | 624 | 0 | 15 | 198 | 290 | 134 | 156 | 25 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeOperators #-}
module T13333 where
import Data.Data
import GHC.Exts (Constraint)
data T (phantom :: k) = T
data D (p :: k -> Constraint) (x :: j) where
D :: forall k (p :: k -> Constraint) (x :: k). p x => D p x
class Possibly p x where
possibly :: proxy1 p -> proxy2 x -> Maybe (D p x)
dataCast1T :: forall k c t (phantom :: k).
(Typeable k, Typeable t, Typeable phantom, Possibly Data phantom)
=> (forall d. Data d => c (t d))
-> Maybe (c (T phantom))
dataCast1T f = case possibly (Proxy :: Proxy Data) (Proxy :: Proxy phantom) of
Nothing -> Nothing
Just D -> gcast1 f
| sdiehl/ghc | testsuite/tests/typecheck/should_compile/T13333.hs | bsd-3-clause | 888 | 0 | 13 | 227 | 288 | 161 | 127 | 23 | 2 |
<?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="pt-BR">
<title>Automation Framework</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> | thc202/zap-extensions | addOns/automation/src/main/javahelp/org/zaproxy/addon/automation/resources/help_pt_BR/helpset_pt_BR.hs | apache-2.0 | 965 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
module HOSubtype where
{-@ foo :: f:(x:{v:Int | false} -> {v:Int | v = x}) -> () @-}
foo :: (Int -> Int) -> ()
foo pf = ()
test0 :: ()
test0 = foo useless_proof
{-@ generic_accept_stable ::
f:(x:a -> {v:a | (v = x)}) ->
()
@-}
generic_accept_stable :: (a -> a) -> ()
generic_accept_stable pf = ()
{-@ useless_proof :: x:{v:Int | v > 0} -> {v:Int | v > 0} @-}
useless_proof :: Int -> Int
useless_proof _ = 5
test :: ()
test = generic_accept_stable useless_proof
| ssaavedra/liquidhaskell | tests/todo/SubType.hs | bsd-3-clause | 530 | 0 | 7 | 160 | 110 | 61 | 49 | 11 | 1 |
{-|
Module : Idris.DSL
Description : Code to deal with DSL blocks.
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE PatternGuards #-}
module Idris.DSL (debindApp, desugar) where
import Idris.AbsSyntax
import Idris.Core.TT
import Control.Monad.State.Strict
import Data.Generics.Uniplate.Data (transform)
debindApp :: SyntaxInfo -> PTerm -> PTerm
debindApp syn t = debind (dsl_bind (dsl_info syn)) t
dslify :: SyntaxInfo -> IState -> PTerm -> PTerm
dslify syn i = transform dslifyApp
where
dslifyApp (PApp fc (PRef _ _ f) [a])
| [d] <- lookupCtxt f (idris_dsls i)
= desugar (syn { dsl_info = d }) i (getTm a)
dslifyApp t = t
desugar :: SyntaxInfo -> IState -> PTerm -> PTerm
desugar syn i t = let t' = expandSugar (dsl_info syn) t
in dslify syn i t'
mkTTName :: FC -> Name -> PTerm
mkTTName fc n =
let mkList fc [] = PRef fc [] (sNS (sUN "Nil") ["List", "Prelude"])
mkList fc (x:xs) = PApp fc (PRef fc [] (sNS (sUN "::") ["List", "Prelude"]))
[ pexp (stringC x)
, pexp (mkList fc xs)]
stringC = PConstant fc . Str . str
intC = PConstant fc . I
reflm n = sNS (sUN n) ["Reflection", "Language"]
in case n of
UN nm -> PApp fc (PRef fc [] (reflm "UN")) [ pexp (stringC nm)]
NS nm ns -> PApp fc (PRef fc [] (reflm "NS")) [ pexp (mkTTName fc nm)
, pexp (mkList fc ns)]
MN i nm -> PApp fc (PRef fc [] (reflm "MN")) [ pexp (intC i)
, pexp (stringC nm)]
_ -> error "Invalid name from user syntax for DSL name"
expandSugar :: DSL -> PTerm -> PTerm
expandSugar dsl (PLam fc n nfc ty tm)
| Just lam <- dsl_lambda dsl
= PApp fc lam [ pexp (mkTTName fc n)
, pexp (expandSugar dsl (var dsl n tm 0))]
expandSugar dsl (PLam fc n nfc ty tm) = PLam fc n nfc (expandSugar dsl ty) (expandSugar dsl tm)
expandSugar dsl (PLet fc rc n nfc ty v tm)
| Just letb <- dsl_let dsl
= PApp (fileFC "(dsl)") letb [ pexp (mkTTName fc n)
, pexp (expandSugar dsl v)
, pexp (expandSugar dsl (var dsl n tm 0))]
expandSugar dsl (PLet fc rc n nfc ty v tm) = PLet fc rc n nfc (expandSugar dsl ty) (expandSugar dsl v) (expandSugar dsl tm)
expandSugar dsl (PPi p n fc ty tm)
| Just pi <- dsl_pi dsl
= PApp (fileFC "(dsl)") pi [ pexp (mkTTName (fileFC "(dsl)") n)
, pexp (expandSugar dsl ty)
, pexp (expandSugar dsl (var dsl n tm 0))]
expandSugar dsl (PPi p n fc ty tm) = PPi p n fc (expandSugar dsl ty) (expandSugar dsl tm)
expandSugar dsl (PApp fc t args) = PApp fc (expandSugar dsl t)
(map (fmap (expandSugar dsl)) args)
expandSugar dsl (PWithApp fc t arg) = PWithApp fc (expandSugar dsl t)
(expandSugar dsl arg)
expandSugar dsl (PAppBind fc t args) = PAppBind fc (expandSugar dsl t)
(map (fmap (expandSugar dsl)) args)
expandSugar dsl (PCase fc s opts) = PCase fc (expandSugar dsl s)
(map (pmap (expandSugar dsl)) opts)
expandSugar dsl (PIfThenElse fc c t f) =
PApp fc (PRef NoFC [] (sUN "ifThenElse"))
[ PExp 0 [] (sMN 0 "condition") $ expandSugar dsl c
, PExp 0 [] (sMN 0 "whenTrue") $ expandSugar dsl t
, PExp 0 [] (sMN 0 "whenFalse") $ expandSugar dsl f
]
expandSugar dsl (PPair fc hls p l r) = PPair fc hls p (expandSugar dsl l) (expandSugar dsl r)
expandSugar dsl (PDPair fc hls p l t r) = PDPair fc hls p (expandSugar dsl l) (expandSugar dsl t)
(expandSugar dsl r)
expandSugar dsl (PAlternative ms a as) = PAlternative ms a (map (expandSugar dsl) as)
expandSugar dsl (PHidden t) = PHidden (expandSugar dsl t)
expandSugar dsl (PNoImplicits t) = PNoImplicits (expandSugar dsl t)
expandSugar dsl (PUnifyLog t) = PUnifyLog (expandSugar dsl t)
expandSugar dsl (PDisamb ns t) = PDisamb ns (expandSugar dsl t)
expandSugar dsl (PRewrite fc by r t ty)
= PRewrite fc by r (expandSugar dsl t) ty
expandSugar dsl (PGoal fc r n sc)
= PGoal fc (expandSugar dsl r) n (expandSugar dsl sc)
expandSugar dsl (PDoBlock ds)
= expandSugar dsl $ debind (dsl_bind dsl) (block (dsl_bind dsl) ds)
where
block b [DoExp fc tm] = tm
block b [a] = PElabError (Msg "Last statement in do block must be an expression")
block b (DoBind fc n nfc tm : rest)
= PApp fc b [pexp tm, pexp (PLam fc n nfc Placeholder (block b rest))]
block b (DoBindP fc p tm alts : rest)
= PApp fc b [pexp tm, pexp (PLam fc (sMN 0 "__bpat") NoFC Placeholder
(PCase fc (PRef fc [] (sMN 0 "__bpat"))
((p, block b rest) : alts)))]
block b (DoLet fc rc n nfc ty tm : rest)
= PLet fc rc n nfc ty tm (block b rest)
block b (DoLetP fc p tm alts : rest)
= PCase fc tm ((p, block b rest) : alts)
block b (DoRewrite fc h : rest)
= PRewrite fc Nothing h (block b rest) Nothing
block b (DoExp fc tm : rest)
= PApp fc b
[pexp tm,
pexp (PLam fc (sMN 0 "__bindx") NoFC (mkTy tm) (block b rest))]
where mkTy (PCase _ _ _) = PRef fc [] unitTy
mkTy (PMetavar _ _) = PRef fc [] unitTy
mkTy _ = Placeholder
block b _ = PElabError (Msg "Invalid statement in do block")
expandSugar dsl (PIdiom fc e) = expandSugar dsl $ unIdiom (dsl_apply dsl) (dsl_pure dsl) fc e
expandSugar dsl (PRunElab fc tm ns) = PRunElab fc (expandSugar dsl tm) ns
expandSugar dsl (PConstSugar fc tm) = PConstSugar fc (expandSugar dsl tm)
expandSugar dsl t = t
-- | Replace DSL-bound variable in a term
var :: DSL -> Name -> PTerm -> Int -> PTerm
var dsl n t i = v' i t where
v' i (PRef fc hl x) | x == n =
case dsl_var dsl of
Nothing -> PElabError (Msg "No 'variable' defined in dsl")
Just v -> PApp fc v [pexp (mkVar fc i)]
v' i (PLam fc n nfc ty sc)
| Nothing <- dsl_lambda dsl
= PLam fc n nfc ty (v' i sc)
| otherwise = PLam fc n nfc (v' i ty) (v' (i + 1) sc)
v' i (PLet fc rc n nfc ty val sc)
| Nothing <- dsl_let dsl
= PLet fc rc n nfc (v' i ty) (v' i val) (v' i sc)
| otherwise = PLet fc rc n nfc (v' i ty) (v' i val) (v' (i + 1) sc)
v' i (PPi p n fc ty sc)
| Nothing <- dsl_pi dsl
= PPi p n fc (v' i ty) (v' i sc)
| otherwise = PPi p n fc (v' i ty) (v' (i+1) sc)
v' i (PTyped l r) = PTyped (v' i l) (v' i r)
v' i (PApp f x as) = PApp f (v' i x) (fmap (fmap (v' i)) as)
v' i (PWithApp f x a) = PWithApp f (v' i x) (v' i a)
v' i (PCase f t as) = PCase f (v' i t) (fmap (pmap (v' i)) as)
v' i (PPair f hls p l r) = PPair f hls p (v' i l) (v' i r)
v' i (PDPair f hls p l t r) = PDPair f hls p (v' i l) (v' i t) (v' i r)
v' i (PAlternative ms a as) = PAlternative ms a $ map (v' i) as
v' i (PHidden t) = PHidden (v' i t)
v' i (PIdiom f t) = PIdiom f (v' i t)
v' i (PDoBlock ds) = PDoBlock (map (fmap (v' i)) ds)
v' i (PNoImplicits t) = PNoImplicits (v' i t)
v' i t = t
mkVar fc 0 = case index_first dsl of
Nothing -> PElabError (Msg "No index_first defined")
Just f -> setFC fc f
mkVar fc n = case index_next dsl of
Nothing -> PElabError (Msg "No index_next defined")
Just f -> PApp fc f [pexp (mkVar fc (n-1))]
setFC fc (PRef _ _ n) = PRef fc [] n
setFC fc (PApp _ f xs) = PApp fc (setFC fc f) (map (fmap (setFC fc)) xs)
setFC fc t = t
unIdiom :: PTerm -> PTerm -> FC -> PTerm -> PTerm
unIdiom ap pure fc e@(PApp _ _ _) = mkap (getFn e)
where
getFn (PApp fc f args) = (PApp fc pure [pexp f], args)
getFn f = (f, [])
mkap (f, []) = f
mkap (f, a:as) = mkap (PApp fc ap [pexp f, a], as)
unIdiom ap pure fc e = PApp fc pure [pexp e]
debind :: PTerm -> PTerm -> PTerm
-- For every arg which is an AppBind, lift it out
debind b tm = let (tm', (bs, _)) = runState (db' tm) ([], 0) in
bindAll (reverse bs) tm'
where
db' :: PTerm -> State ([(Name, FC, PTerm)], Int) PTerm
db' (PAppBind _ (PApp fc t args) [])
= db' (PAppBind fc t args)
db' (PAppBind fc t args)
= do args' <- dbs args
(bs, n) <- get
let nm = sUN ("_bindApp" ++ show n)
put ((nm, fc, PApp fc t args') : bs, n+1)
return (PRef fc [] nm)
db' (PApp fc t args)
= do t' <- db' t
args' <- mapM dbArg args
return (PApp fc t' args')
db' (PWithApp fc t arg)
= do t' <- db' t
arg' <- db' arg
return (PWithApp fc t' arg')
db' (PLam fc n nfc ty sc) = return (PLam fc n nfc ty (debind b sc))
db' (PLet fc rc n nfc ty v sc)
= do v' <- db' v
return (PLet fc rc n nfc ty v' (debind b sc))
db' (PCase fc s opts) = do s' <- db' s
return (PCase fc s' (map (pmap (debind b)) opts))
db' (PPair fc hls p l r) = do l' <- db' l
r' <- db' r
return (PPair fc hls p l' r')
db' (PDPair fc hls p l t r) = do l' <- db' l
r' <- db' r
return (PDPair fc hls p l' t r')
db' (PRunElab fc t ns) = fmap (\tm -> PRunElab fc tm ns) (db' t)
db' (PConstSugar fc tm) = liftM (PConstSugar fc) (db' tm)
db' t = return t
dbArg a = do t' <- db' (getTm a)
return (a { getTm = t' })
dbs [] = return []
dbs (a : as) = do let t = getTm a
t' <- db' t
as' <- dbs as
return (a { getTm = t' } : as')
bindAll [] tm = tm
bindAll ((n, fc, t) : bs) tm
= PApp fc b [pexp t, pexp (PLam fc n NoFC Placeholder (bindAll bs tm))]
| kojiromike/Idris-dev | src/Idris/DSL.hs | bsd-3-clause | 10,286 | 0 | 17 | 3,694 | 4,873 | 2,387 | 2,486 | 195 | 22 |
module Dummy where
main :: IO ()
main = error ""
| mydaum/cabal | cabal-testsuite/PackageTests/AutogenModules/SrcDist/Dummy.hs | bsd-3-clause | 50 | 0 | 6 | 12 | 22 | 12 | 10 | 3 | 1 |
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Hadoop.Protos.ClientNamenodeProtocolProtos.FinalizeUpgradeRequestProto (FinalizeUpgradeRequestProto(..)) where
import Prelude ((+), (/))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data FinalizeUpgradeRequestProto = FinalizeUpgradeRequestProto{}
deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable FinalizeUpgradeRequestProto where
mergeAppend FinalizeUpgradeRequestProto FinalizeUpgradeRequestProto = FinalizeUpgradeRequestProto
instance P'.Default FinalizeUpgradeRequestProto where
defaultValue = FinalizeUpgradeRequestProto
instance P'.Wire FinalizeUpgradeRequestProto where
wireSize ft' self'@(FinalizeUpgradeRequestProto)
= case ft' of
10 -> calc'Size
11 -> P'.prependMessageSize calc'Size
_ -> P'.wireSizeErr ft' self'
where
calc'Size = 0
wirePut ft' self'@(FinalizeUpgradeRequestProto)
= case ft' of
10 -> put'Fields
11 -> do
P'.putSize (P'.wireSize 10 self')
put'Fields
_ -> P'.wirePutErr ft' self'
where
put'Fields
= do
Prelude'.return ()
wireGet ft'
= case ft' of
10 -> P'.getBareMessageWith update'Self
11 -> P'.getMessageWith update'Self
_ -> P'.wireGetErr ft'
where
update'Self wire'Tag old'Self
= case wire'Tag of
_ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
instance P'.MessageAPI msg' (msg' -> FinalizeUpgradeRequestProto) FinalizeUpgradeRequestProto where
getVal m' f' = f' m'
instance P'.GPB FinalizeUpgradeRequestProto
instance P'.ReflectDescriptor FinalizeUpgradeRequestProto where
getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList [])
reflectDescriptorInfo _
= Prelude'.read
"DescriptorInfo {descName = ProtoName {protobufName = FIName \".hadoop.hdfs.FinalizeUpgradeRequestProto\", haskellPrefix = [MName \"Hadoop\",MName \"Protos\"], parentModule = [MName \"ClientNamenodeProtocolProtos\"], baseName = MName \"FinalizeUpgradeRequestProto\"}, descFilePath = [\"Hadoop\",\"Protos\",\"ClientNamenodeProtocolProtos\",\"FinalizeUpgradeRequestProto.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
instance P'.TextType FinalizeUpgradeRequestProto where
tellT = P'.tellSubMessage
getT = P'.getSubMessage
instance P'.TextMsg FinalizeUpgradeRequestProto where
textPut msg = Prelude'.return ()
textGet = Prelude'.return P'.defaultValue | alexbiehl/hoop | hadoop-protos/src/Hadoop/Protos/ClientNamenodeProtocolProtos/FinalizeUpgradeRequestProto.hs | mit | 2,999 | 1 | 16 | 537 | 554 | 291 | 263 | 53 | 0 |
#!/usr/bin/env runhaskell
import Control.Concurrent (threadDelay)
import Control.Monad (void)
import Data.Int (Int32)
import System.Libnotify
main :: IO ()
main = void $ withNotifications Nothing $ (homogeneous >> geterogeneous)
homogeneous = do new "Same title" "line 1" "" $ do addHint (HintString "append" "allowed")
render
new "Same title" "line 2" "" $ do addHint (HintString "append" "allowed")
render
new "Same title" "line 3" "" $ do addHint (HintString "append" "allowed")
render
geterogeneous = do new "Bar" "" "dialog-information" $
do mapM_ addHint
[ HintInt "value" 33
, HintString "synchronous" "volume"
]
render
threadDelay timeout
new "Bar" "" "dialog-information" $
do mapM_ addHint
[ HintInt "value" 66
, HintString "synchronous" "volume"
]
render
threadDelay timeout
new "Bar" "" "dialog-information" $
do mapM_ addHint
[ HintInt "value" 100
, HintString "synchronous" "volume"
]
render
timeout = 500000
| supki/libnotify | tests/add-hint-test.hs | mit | 1,560 | 0 | 12 | 770 | 313 | 145 | 168 | 30 | 1 |
module Parser
(assert_, isComment
, LineRule, parseRuleFile
, parseTupleFile
, Error, runParser, lhs_, lexLine, line_, lexFile
) where
import Data.Char (isSpace)
import Types hiding (T)
import Parse hiding (string, identifier, char, token, int_)
data Lex a = Token a | Comment a | String a
deriving (Show, Eq, Ord)
-- TODO use Text?
type L = Lex String
type LParser = ParseEither [L] Error
type LineRule = (Int, Rule)
ppLex :: [L] -> String
ppLex = unwords . map fix
where
fix (Token s) = s
fix (String s) = "\"" ++ s ++ "\""
fix (Comment s) = "#" ++ s
isComment (Comment _) = True
isComment _ = False
forbidden_characters :: String
forbidden_characters = " \t\n,.;:@()[]{}!"
-- ... and \" implicitly
forbidden_identifier = ["~>", "=>", ",", "!"]
spaceout :: [L] -> [L]
spaceout = concatMap fm
where
split p = words . concatMap fix
where
fix c | p c = [' ', c, ' ']
fix c = [c]
fm (Token s) = map Token . split (`elem` forbidden_characters) $ s
fm v = [v]
lexLine :: String -> Either Error [L]
lexLine str = spaceout <$> fix [] empty str
where
empty = []
emit acc ls = Token (reverse acc) : ls
finish = Right . reverse
fix ls acc s | null s = finish $ emit acc ls
fix ls acc s | isSpace (head s) = fix (emit acc ls) empty (tail s)
fix ls acc s | '\"' == head s =
let l' = emit acc ls in
case reads s of
[(str, rest)] -> fix (String str : l') empty rest
_ -> Left $ "error parsing string: " ++ s
fix ls acc s | '#' == head s =
finish . (Comment (tail s) :) . (emit acc) $ ls
fix ls acc s = fix ls (head s : acc) (tail s)
-- TODO support multiline strings?
lexFile :: String -> Either Error [[L]]
lexFile = mapM step . zip [1..] . lines
where
step (i, l) =
case lexLine l of
Left err -> Left ("line " ++ show i ++": " ++ err)
Right v -> Right v
int_ :: LParser Int
int_ = ParseEither step
where
step ts0@(Token s : ts) =
case reads s of
(i, "") : _ -> Right (i, ts)
_ -> Left (msg, ts0)
step s = Left (msg, s)
msg = "expected integer"
char :: Char -> LParser Char
char c = ParseEither (char' c)
where
char' :: Char -> [L] -> Either (Error, [L]) (Char, [L])
char' c (Token (c' : cs) : ts) | c == c' = Right (c, Token cs : ts)
char' c s@(Token [] : ts) = err s
char' c s = err s
err s = Left ("expected char: " ++ [c], s)
token :: LParser String
token = ParseEither ok
where
ok ts@(Token t : _) | t `elem` map (:[]) forbidden_characters = Left ("invalid token: " ++ t, ts)
ok (Token t : ts) = Right (t, ts)
ok ts@(t:_) = Left $ ("expected token, got: " ++ show t, ts)
ok [] = Left ("expected token, got EOF.", [])
identifier :: LParser String
identifier = ParseEither ok
where
ok ts@(Token t : _) | t `elem` map (:[]) forbidden_characters = Left ("invalid token: " ++ t, ts)
ok ts@(Token t : _) | t `elem` forbidden_identifier = Left ("invalid token: " ++ t, ts)
ok ts@(Token t : _) | head t == '\'' = Left ("invalid token: " ++ t, ts)
ok (Token t : ts) = Right (t, ts)
ok ts@(t:_) = Left $ ("expected token, got: " ++ show t, ts)
ok [] = Left ("expected token, got EOF.", [])
stringLiteral :: LParser String
stringLiteral = ParseEither ok
where
ok (String s : ts) = Right (s, ts)
ok ts = Left ("expected string literal", ts)
string :: String -> LParser String
string str = ParseEither go
where
go (Token s : ts) | s == str = Right (s, ts)
go s = Left ("expected token: " ++ str, s)
comma_ = string ","
symbol_ = char '\'' *> token
hole_ = string "_"
q_ = (NVal <$>
((NSymbol <$> symbol_)
<|> (NInt <$> int_)
<|> (NString <$> stringLiteral)))
<|> (pure NHole <* hole_)
<|> (NVar <$> identifier)
rel_ = L <$> identifier
ineq_ =
(string "=" *> return QEq) <|>
(string "/=" *> return QDisEq) <|>
(string "<=" *> return QLessEq) <|>
(string ">=" *> return QMoreEq) <|>
(string "<" *> return QLess) <|>
(string ">" *> return QMore)
qbin_ = flip QBinOp <$> expr_ <*> ineq_ <*> expr_
--ep_ lin = EP lin <$> rel_ <*> many q_
--lp_ p = LP p <$> rel_ <*> many q_
query_ = Query <$> ((string "@" *> pure High) <|> pure Low) <*> pattern_
--query_ = Query Low <$> ep_ NonLinear
--dotquery_ = string "." *> (Query High <$> ep_ NonLinear)
--linearquery_ = string ".." *> (Query Low <$> ep_ Linear)
--dotlinearquery_ = string "..." *> (Query High <$> ep_ Linear)
--lnlogicquery_ = string "!" *> (Query Low <$> lp_ Negative)
--hnlogicquery_ = string ".!" *> (Query High <$> lp_ Negative)
polarity_ = (string "!" *> string ":" *> pure Negative) <|> (string ":" *> pure Positive)
linearity_ = (string "." *> string "." *> pure Linear) <|> (pure NonLinear)
rp_ = VP <$> (q_ <* string ":" ) <*> rel_ <*> many q_
lp_ = LP <$> polarity_ <*> rel_ <*> many q_
ep_ = EP <$> linearity_ <*> rel_ <*> many q_
pattern_ = rp_ <|> lp_ <|> ep_
clause_ = qbin_ <|> query_
--clause_ = qbin_ <|> dotquery_ <|> linearquery_ <|> dotlinearquery_ <|> query_
-- <|> lnlogicquery_ <|> hnlogicquery_
lhs_ = sepBy comma_ clause_
wrap_ p = (string "(") *> p <* (string ")")
binOp_ =
((string "+") *> return Sum)
<|> ((string "*") *> return Mul)
<|> ((string "-") *> return Sub)
expr_ =
(ELit <$> int_)
<|> (ENamed <$> symbol_)
<|> (pure EHole <* hole_)
<|> (EVar <$> identifier)
<|> (EString <$> stringLiteral)
<|> (wrap_ $ flip EBinOp <$> expr_ <*> binOp_ <*> expr_)
<|> (wrap_ $ EConcat <$> expr_ <*> (string "++" *> expr_))
-- allow trailing whitespace?
assert_ = Assert <$> rel_ <*> many expr_
vassert_ = do
val <- (TValExpr <$> expr_) <|> (pure TValNull)
string ":"
VAssert val <$> rel_ <*> many expr_
rclause_ = vassert_ <|> assert_
rhs_ = sepBy comma_ rclause_
arrow_ = string "=>"
larrow_ = string "~>"
rule_ = (Rule Nothing Nothing Event <$> lhs_ <*> (arrow_ *> rhs_))
lrule_ = (Rule Nothing Nothing View <$> lhs_ <*> (larrow_ *> rhs_))
line_ = rule_ <|> lrule_
parseLine line s =
let str = ppLex s in
case runParser line_ s of
Right (r, []) -> (line, r { rule_str = Just str })
p -> error $ "line " ++ show line ++ ": incomplete parse.\n " ++ show p
removeComments = filter (not . isComment)
parseTuple :: [L] -> Either Error Assert
parseTuple ls =
case runParser rclause_ ls of
Left (err, _) -> Left err
Right (v, []) -> Right v
Right v -> Left $ "incomplete parse: " ++ show v
parseTupleFile :: String -> Either Error [[Assert]]
parseTupleFile f = do
ls <- lexFile f
let bs = filter (not . null) . map fixBlock . blocks $ ls
mapM (mapM parseTuple) bs
where
blocks :: [[L]] -> [[[L]]]
blocks [] = []
blocks xs = let (x, r) = span (not . null) xs in x : blocks (st r)
where
st [] = []
st (_:a) = a
fixBlock :: [[L]] -> [[L]]
fixBlock = nonEmpty . map removeComments
nonEmpty = filter (not . null)
parseRuleFile :: String -> Either Error [LineRule]
parseRuleFile x = do
ls <- lexFile x
let numbered = zip [1..] ls
let nonEmptyLines = filter (not . null . snd) . map (second removeComments) $ numbered
return $ map (uncurry parseLine) nonEmptyLines
| kovach/web2 | src/Parser.hs | mit | 7,216 | 0 | 16 | 1,842 | 3,098 | 1,595 | 1,503 | 171 | 6 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.HTMLDirectoryElement (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.HTMLDirectoryElement
#else
module Graphics.UI.Gtk.WebKit.DOM.HTMLDirectoryElement
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.HTMLDirectoryElement
#else
import Graphics.UI.Gtk.WebKit.DOM.HTMLDirectoryElement
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/HTMLDirectoryElement.hs | mit | 485 | 0 | 5 | 39 | 33 | 26 | 7 | 4 | 0 |
module D20.Internal.Character.Age (Age, IsAging (..)) where
import D20.Internal.Character.Ability
import Data.Map
import Data.Maybe
import Data.List
data Age
= Child
| YoungAdult
| Adult
| MiddleAged
| Old
| Venerable
deriving (Show,Eq,Enum,Ord)
type AgeBounds = (Int,Int)
class IsAging a where
getAge :: a -> Int
getAgingEffect :: a -> Map Ability Int
getAgingEffect a =
fromJust $
Data.Map.lookup (getAgingStage a)
agingEffects
getAgingStage :: a -> Age
getAgingStage a =
let age = getAge a
in snd $
fromJust $
find (\((lo,hi),_) -> age >= lo && age <= hi) agingStages
agingStages :: [(AgeBounds,Age)]
agingStages =
[((1,11),Child)
,((12,15),YoungAdult)
,((16,39),Adult)
,((40,59),MiddleAged)
,((60,79),Old)
,((80,200),Venerable)]
agingEffects :: Map Age (Map Ability Int)
agingEffects =
fromList [(Child
,fromList [(Strength,-3)
,(Constitution,-3)
,(Dexterity,-1)
,(Intelligence,-1)
,(Wisdom,-1)
,(Charisma,-1)])
,(MiddleAged
,fromList [(Strength,-1)
,(Constitution,-1)
,(Dexterity,-1)
,(Intelligence,1)
,(Wisdom,1)
,(Charisma,1)])
,(Old
,fromList [(Strength,-1)
,(Constitution,-1)
,(Dexterity,-1)
,(Intelligence,1)
,(Wisdom,1)
,(Charisma,1)])
,(Venerable
,fromList [(Strength,-1)
,(Constitution,-1)
,(Dexterity,-1)
,(Intelligence,1)
,(Wisdom,1)
,(Charisma,1)])]
| elkorn/d20 | src/D20/Internal/Character/Age.hs | mit | 1,883 | 0 | 15 | 758 | 658 | 401 | 257 | 65 | 1 |
module Colors.Nord where
colorScheme = "nord"
colorBack = "#2E3440"
colorFore = "#D8DEE9"
-- Black
color00 = "#343d46"
color08 = "#343d46"
-- Red
color01 = "#EC5f67"
color09 = "#EC5f67"
-- Green
color02 = "#99C794"
color10 = "#99C794"
-- Yellow
color03 = "#FAC863"
color11 = "#FAC863"
-- Blue
color04 = "#6699cc"
color12 = "#6699cc"
-- Magenta
color05 = "#c594c5"
color13 = "#c594c5"
-- Cyan
color06 = "#5fb3b3"
color14 = "#5fb3b3"
-- White
color07 = "#d8dee9"
color15 = "#d8dee9"
colorTrayer :: String
colorTrayer = "--tint 0x2E3440"
| phdenzel/dotfiles | .config/xmonad/lib/Colors/Nord.hs | mit | 539 | 0 | 4 | 87 | 119 | 75 | 44 | 22 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Y2020.M11.D12.Solution where
-- Well, howdy! Yesterday, ...
import Y2020.M11.D11.Solution (allianceGraph)
{--
... we were all: "We're gonna upload alliances to the graph-store!"
But we didn't because the day ended in an unicode-error. *sad-face*
So, today, let's:
1. first, identify the values that have unicode-points outside ASCII
2. then, replace those values with plain-vanilla ASCII values
3. finally, upload the newly updated AllianceMap to the graph
(which we tried yesterday, so this step should be easy).
--}
import Y2020.M10.D23.Solution (unicodePoints)
import Y2020.M10.D30.Solution -- for AllianceMap
import Y2020.M11.D10.Solution (go)
import Graph.Query
import Control.Arrow (second)
import Data.Char (ord)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
-- for Step 1, look at, e.g. Y2020.M10.D23.Solution.stripNonAscii
isNonAscii :: Text -> Bool
isNonAscii = any ((> 127) . ord) . T.unpack
-- How many thingies (that's a technical term) are non-ascii?
-- for Step 2, we can do this generically or we can do it specifically.
cleanText :: Text -> Text
cleanText = T.concat . unicodePoints
-- `cleanText` given text isNonAscii replace it with Text value that is ASCII
-- So, then, we cleanify (that's a word, now) the AllianceMap thusly:
-- ... but first: I want to see what works and what doesn't UTF8-wise
whatify :: AllianceMap -> IO AllianceMap
whatify am = Map.fromList <$> mapM (sequence . second ally) (Map.toList am)
ally :: Alliance -> IO Alliance
ally a =
putStrLn (concat ["For ", T.unpack $ name a, ":"]) >>
let b = Set.filter isNonAscii (countries a) in
putStrLn (show b) >>
return a { countries = b }
{--
>>> whatify am
For 2001 Sino-Russian Treaty of Friendship:
fromList []
For ANZAC:
fromList []
For ANZUS:
fromList []
For African Union:
fromList ["C\244te d'Ivoire (Ivory Coast)","S\227o Tom\233 and Pr\237ncipe"]
For Agreement on Strategic Partnership and Mutual Support:
fromList []
For Anglo-Portuguese Alliance:
fromList []
For Arab League:
fromList []
For Association of South-East Asian Nations:
fromList []
For Axis of Resistance:
fromList []
For BALTRON:
fromList []
For Caribbean Community|Caribbean Community (CARICOM):
fromList []
For Collective Security Treaty Organization:
fromList []
For Economic Community of Central African States:
fromList []
For Economic Community of West African States:
fromList []
For Entente Cordiale:
fromList []
For European Union:
fromList []
For Five Eyes:
fromList []
For Five Power Defence Arrangements:
fromList []
For Forum for the Progress and Development of South America:
fromList []
For Franco-German Brigade:
fromList []
For GUAM Organization for Democracy and Economic Development:
fromList []
For International Association of Gendarmeries and Police Forces with Military Status:
fromList []
For International Maritime Security Construct:
fromList []
For Islamic Military Alliance:
fromList []
For Major non-NATO Ally:
fromList []
For Moroccan-American Treaty of Friendship:
fromList []
For Mutual Defense Treaty (United States-Philippines):
fromList []
For Mutual Defense Treaty (United States-South Korea):
fromList []
For North American Aerospace Defense Command:
fromList []
For North Atlantic Treaty Organization:
fromList []
For Organization of American States:
fromList []
For Organization of the Eurasian Law Enforcement Agencies with Military Status:
fromList []
For Pakistan-United States military relations:
fromList []
For Peninsula Shield Force:
fromList []
For Rio Pact:
fromList []
For Russia-Syria-Iran-Iraq Coalition|RSII Coalition:
fromList []
For Shanghai Cooperation Organisation:
fromList []
For Sino-North Korean Mutual Aid and Cooperation Friendship Treaty:
fromList []
For South Atlantic Peace and Cooperation Zone:
fromList []
For Treaty of Mutual Cooperation and Security between the United States and Japan:
fromList []
For U.S.-Afghanistan Strategic Partnership Agreement:
fromList []
For US-Israel Strategic Partnership:
fromList []
For Union State:
fromList []
For Union of South American Nations:
fromList []
For United Nations:
fromList []
... so it's a rare issue, not a profligate one. Let's examine the cases, and
see how the countries are represented in the graph-store.
match (n:Continent {name: "Africa"})<-[:IN]-(c:Country) return c.name
São Tomé and Príncipe
Côte d'Ivoire (Ivory Coast)
Okay, the what? :<
Shuckaroos! I'm just going to drop those two countries.
--}
cleanify :: AllianceMap -> AllianceMap
cleanify = Map.fromList . map (second allu) . Map.toList
allu :: Alliance -> Alliance
allu a =
let b = Set.filter (not . isNonAscii) (countries a) in
a { countries = b }
-- now upload the alliances to the graph (as yesterday).
{--
>>> go
>>> let am = it
>>> let cleaned = cleanify am
>>> graphEndpoint
>>> let url = it
>>> cyphIt url (allianceGraph cleaned)
...,\"errors\":[]}"
--}
| geophf/1HaskellADay | exercises/HAD/Y2020/M11/D12/Solution.hs | mit | 5,000 | 0 | 12 | 804 | 416 | 237 | 179 | 31 | 1 |
--константа в Хаскел
--можем изрично да посочим типа й, ако не - компилаторът ще се досети кой е
mypi :: Double
mypi = 3.141592
--Сигнатурата на ф-ия - ако я напишем, трябва да е пълна, т.е или да пише
--конкретните типове (Int,Float,Double,Bool,Char,String,...), или да включва
--ограничения за тях в зависимост кои други ф-ии използват тези аргументи.
--Ако не я напишем, интерпретаторът ще я deduce-не вместо нас, със все ограничения.
--Точна сигнатура (ще работи само с Double):
--f :: Double -> Double -> Double
--Обща, но грешна сигнатура (ще работи със всякакви типове - добре, но + и sqrt не работят със всякакви):
--f :: a -> a -> a
--Правилна сигнатура с ограничения за типа:
--f :: (Floating a) => a -> a -> a
f :: (Floating a) => a -> a -> a
f x y = sqrt (x*x + y*y)
abc :: Int
abc = 3
b :: Float
b = 4.0
--Task 1
--Функция, която приема някакво число и изписва какъв му е знака. Извиква оператора <,
--който изисква типът да е "сравним", значи и нашата функция трябва да има същото ограничение.
--Guard-овете трябва да се индентирани спрямо дефиницията на функцията (няма значение с колко)
saySign :: (Num a, Ord a) => a -> String
saySign x
| x < 0 = "Negative"
| x == 0 = "Zero"
| otherwise = "Positive"
--Task 2
--Тривиално рекурсивно изчисление на n-тото число на Фибоначи.
--Integral класът се включва в Ord, значи няма нужда да пишем (Ord a, Integral a)
fib :: (Integral a) => a -> a
fib n = if (n < 2)
then n
else (fib (n-1)) + (fib (n-2))
--Изчисление с помощна функция, която дефинираме локално с where дефиниция (също индентирана)
fib' :: (Integral a) => a -> a
fib' n
| n < 0 = 0
| otherwise = fibHelper 0 1 startIdx
where fibHelper f1 f2 i
| i == n = f1
| otherwise = fibHelper f2 (f1+f2) (i+1)
startIdx = 0
--Pattern matching - разписваме граничните случаи като отделни дефиниции.
--Искаме те да бъдат преди "общия случай" на функцията по същата логика,
--по която правим първо проверките в рекурсивната функция - нов е само синтаксиса.
fib'' :: (Integral a) => a -> a
fib'' 0 = 0
fib'' 1 = 1
fib'' n = fib'' (n-1) + fib'' (n-2)
--Task 3
--Функция, която брои колко корена има квадратно уравнение по дадени коефициенти
countRoots :: (Ord a, Floating a) => a -> a -> a -> String
countRoots a b c
| d < 0 = "no roots"
| d == 0 = "one root"
| otherwise = "two roots"
where d = b*b - 4*a*c
--Task 4
--Отделните аргументи може да са различни типове с различни ограничения.
power :: (Num a, Integral b) => a -> b -> a
power base n
| n == 0 = 1
| even n = square (power base (div n 2))
| otherwise = base * square (power base (div n 2))
where square x = x*x
--Task 5
cylinderVolume :: Floating a => a -> a -> a
cylinderVolume r h = pi * r^2 * h
| pepincho/Functional-Programming | haskell/ex-1.hs | mit | 3,859 | 0 | 11 | 645 | 687 | 360 | 327 | 43 | 2 |
-- My smallest code interpreter (aka Brainf**k)
-- https://www.codewars.com/kata/526156943dfe7ce06200063e
module Brainfuck (executeString) where
import Data.Char (chr, ord)
import Data.Maybe (mapMaybe)
data BFCommand = GoR | GoL | Inc | Dec | Print | Read | LoopL | LoopR deriving (Eq)
data Tape a = Tape [a] a [a]
type BFSource = [BFCommand]
moveRight :: Tape a -> Tape a
moveRight (Tape ls p (r:rs)) = Tape (p:ls) r rs
moveLeft :: Tape a -> Tape a
moveLeft (Tape (l:ls) p rs) = Tape ls l (p:rs)
emptyTape :: Tape Int
emptyTape = Tape zeros 0 zeros
where zeros = repeat 0
syntax = [('>', GoR), ('<', GoL), ('+', Inc), ('-', Dec), ('.', Print), (',', Read), ('[', LoopL), (']', LoopR)]
validate :: BFSource -> Maybe BFSource
validate source = if validParentheses . filter (`elem` [LoopL, LoopR]) $ source then Just source else Nothing
where validParentheses :: BFSource -> Bool
validParentheses xs = vp xs 0
vp [] 0 = True
vp [] _ = False
vp (LoopL:xs) n = vp xs (n+1)
vp (LoopR:xs) n | n > 0 = vp xs (n-1)
| otherwise = False
parse :: String -> Maybe BFSource
parse = validate . mapMaybe (`lookup` syntax)
executeString :: String -> String -> Maybe String
executeString source input = parse source >>= ( fmap reverse . run input [] emptyTape . bfSource2Tape)
where bfSource2Tape (b:bs) = Tape [] b bs
toChar :: Int -> Char
toChar = chr . (`mod` 256)
run :: String -> String -> Tape Int -> Tape BFCommand -> Maybe String
run i o d s @ (Tape _ GoR _) = advance i o (moveRight d) s
run i o d s @ (Tape _ GoL _) = advance i o (moveLeft d) s
run i o (Tape l p r) s @ (Tape _ Inc _) = advance i o (Tape l (p+1) r) s
run i o (Tape l p r) s @ (Tape _ Dec _) = advance i o (Tape l (p-1) r) s
run i o d @ (Tape _ p _) s @ (Tape _ Print _) = advance i (toChar p : o) d s
run i o d @ (Tape _ p _) s @ (Tape _ LoopL _) | p == 0 = seekLoopR i o 0 d s
| otherwise = advance i o d s
run i o d @ (Tape _ p _) s @ (Tape _ LoopR _) | p /= 0 = seekLoopL i o 0 d s
| otherwise = advance i o d s
run i o d @ (Tape l _ r) s @ (Tape _ Read _) | null i = Nothing
| otherwise = advance (tail i) o (Tape l (ord . head $ i) r) s
advance :: String -> String -> Tape Int -> Tape BFCommand -> Maybe String
advance _ o _ (Tape _ _ []) = Just o
advance i o d s = run i o d (moveRight s)
seekLoopR :: String -> String -> Int -> Tape Int -> Tape BFCommand -> Maybe String
seekLoopR i o 1 d s @ (Tape _ LoopR _) = advance i o d s
seekLoopR i o b d s @ (Tape _ LoopR _) = seekLoopR i o (b-1) d (moveRight s)
seekLoopR i o b d s @ (Tape _ LoopL _) = seekLoopR i o (b+1) d (moveRight s)
seekLoopR i o b d s = seekLoopR i o b d (moveRight s)
seekLoopL :: String -> String -> Int -> Tape Int -> Tape BFCommand -> Maybe String
seekLoopL i o 1 d s @ (Tape _ LoopL _) = advance i o d s
seekLoopL i o b d s @ (Tape _ LoopL _) = seekLoopL i o (b-1) d (moveLeft s)
seekLoopL i o b d s @ (Tape _ LoopR _) = seekLoopL i o (b+1) d (moveLeft s)
seekLoopL i o b d s = seekLoopL i o b d (moveLeft s)
| gafiatulin/codewars | src/2 kyu/Brainfuck.hs | mit | 3,288 | 10 | 10 | 1,010 | 1,113 | 649 | 464 | 55 | 5 |
--------------------------------------------------------------------------------
-- (c) Tsitsimpis Ilias, 2011-2012
--
-- Typed Abstract Syntax Tree for the Alan Language
--
-- Since the LLVM API is typed it's much easier to translate a typed abstract
-- syntax tree than an untyped abstract syntax tree. The TypedAst module
-- contains the definition of the typed AST. There are many ways to formulate
-- type safe abstract syntax trees.
-- I've chosen to use GADTs.
--
--------------------------------------------------------------------------------
{-# LANGUAGE GADTs, ExistentialQuantification, PatternGuards #-}
{-# LANGUAGE TypeFamilies, FlexibleContexts, FlexibleInstances, UndecidableInstances #-}
module TypedAst where
import UnTypedAst (Ide, Op)
import Outputable (panic)
import Data.Int
import Data.Word
import Foreign.Ptr
import Control.Monad
import LLVM.Core (IsFunction, IsFirstClass, CodeGenFunction, FunctionArgs, Value)
-- ---------------------------
--
type TAst = ADefFun
type ADef = Either ADefFun ADefVar
-- ---------------------------
data TDefFun a where
TDefFun :: (IsFirstClass a, Translate (IO a)) =>
Ide -> TType a -> ([ADefFun], [ADefVar]) -> TStmt -> TDefFun (IO a)
TDefProt :: (IsFirstClass a, Translate (IO a)) =>
Ide -> TType a -> TDefFun (IO a)
TDefPar :: (IsFirstClass a, IsFunction b, Translate b) =>
Ide -> TType a -> TDefFun b -> TDefFun (a->b)
data ADefFun = forall a. (IsFunction a, Translate a) => ADefFun (TDefFun a) (TType a)
-- ---------------------------
data TDefVar a where
TDefVar :: (IsFirstClass a) => Ide -> TType a -> TDefVar a
data ADefVar = forall a. (IsFirstClass a) => ADefVar (TDefVar a) (TType a)
-- ---------------------------
data TStmt
= TStmtNothing
| TStmtAssign AVariable AExpr
| TStmtCompound Bool [TStmt] -- true if there is a return
| TStmtFun AFuncCall
| TStmtIf ACond TStmt (Maybe TStmt)
| TStmtWhile ACond TStmt
| TStmtReturn (Maybe AExpr)
-- ---------------------------
data TExpr a where
TExprInt :: Int32 -> TExpr Int32
TExprChar :: Word8 -> TExpr Word8
TExprString :: String -> TExpr (Ptr Word8)
TExprVar :: (IsFirstClass a) => TVariable a -> TExpr a
TExprFun :: (IsFirstClass a) => TFuncCall (IO a) -> TExpr a
TExprMinus :: TExpr Int32 -> TExpr Int32
TExprOp :: (IsFirstClass a) =>
TExpr a -> Op -> TExpr a -> TType a -> TExpr a
data AExpr = forall a. (IsFirstClass a) => AExpr (TExpr a) (TType a)
-- ---------------------------
data TCond a where
TCondTrue :: TCond Bool
TCondFalse :: TCond Bool
TCondNot :: TCond Bool -> TCond Bool
TCondOp :: (IsFirstClass a) =>
TExpr a -> Op -> TExpr a -> TType a -> TCond Bool
TCondLog :: TCond Bool -> Op -> TCond Bool -> TCond Bool
data ACond = ACond (TCond Bool)
-- ---------------------------
data TVariable a where
TVar :: (IsFirstClass a) => Ide -> TType a -> TVariable a
TVarArray :: (IsFirstClass a) => TVariable a -> TExpr Int32 -> TVariable a
-- pointer to one variable
TVarPtr :: (IsFirstClass a) => TVariable a -> TVariable (Ptr a)
data AVariable = forall a. (IsFirstClass a) => AVariable (TVariable a) (TType a)
-- ---------------------------
data TType a where
TTypeInt :: TType Int32
TTypeChar :: TType Word8
TTypeProc :: TType ()
TTypePtr :: (IsFirstClass a) => TType a -> TType (Ptr a)
TTypeUnknown :: TType ()
TTypeFunc :: (IsFirstClass a, IsFunction b) =>
TType a -> TType b -> TType (a->b)
TTypeFuncR :: (IsFirstClass a, IsFunction b, Translate b) =>
TType a -> TType b -> TType (a->b)
TTypeRetIO :: (IsFirstClass a) => TType a -> TType (IO a)
TTypeArr :: (IsFirstClass a) => TType a -> Maybe Int32 -> TType a
data AType = forall a. (IsFirstClass a) => AType (TType a)
data ATypeF = forall a. (IsFunction a) => ATypeF (TType a)
data ATypeR = forall a. (IsFirstClass a, Translate (IO a)) => ATypeR (TType a)
instance Eq AType where
(AType TTypeUnknown) == (AType TTypeUnknown) = True
(AType TTypeInt) == (AType TTypeInt) = True
(AType TTypeChar) == (AType TTypeChar) = True
(AType TTypeProc) == (AType TTypeProc) = True
(AType (TTypePtr a)) == (AType (TTypePtr b)) = AType a == AType b
(AType (TTypeArr a sa)) == (AType (TTypeArr b sb)) =
(AType a == AType b) && (sa==sb || sa==Nothing || sb==Nothing)
(AType _) == (AType _) = False
instance Eq ATypeF where
(ATypeF (TTypeRetIO a)) == (ATypeF (TTypeRetIO b)) = AType a == AType b
(ATypeF _) == (ATypeF _) = False
instance Show AType where
show (AType TTypeInt) = "int"
show (AType TTypeChar) = "byte"
show (AType TTypeProc) = "proc"
show (AType (TTypePtr t)) = show (AType t)
show (AType TTypeUnknown) = "unknown"
show (AType (TTypeArr a s)) =
showType a ++ " " ++ showArray (TTypeArr a s)
show (AType _) = panic "TypedAst.show got unexpected input"
showType :: (IsFirstClass a) => TType a -> String
showType (TTypeArr t _) = showType t
showType t = show $ AType t
showArray :: (IsFirstClass a) => TType a -> String
showArray (TTypeArr a (Just s)) =
"[" ++ show s ++ "]" ++ showArray a
showArray (TTypeArr a Nothing) =
"(*)" ++ showArray a
showArray _ = ""
-- ---------------------------
data TFuncCall a where
TFuncCall :: (IsFunction a) => Ide -> TType a -> TFuncCall a
TParamCall :: (IsFirstClass a, IsFunction b) =>
TExpr a -> TType a -> TFuncCall (a->b) -> TFuncCall b
data AFuncCall = forall a. (IsFunction a) => AFuncCall (TFuncCall a) (TType a)
-- -------------------------------------------------------------------
-- We need to do the equality test so that it reflects the equality
-- on the type level. There's a standard trick for this.
-- If you ever have a value (which must be Eq) of type
-- Equal foo bar then the type checker will know that foo and
-- bar are actually the same type.
data Equal a b where
Eq :: Equal a a
test :: TType a -> TType b -> Maybe (Equal a b)
test TTypeInt TTypeInt = return Eq
test TTypeChar TTypeChar = return Eq
test TTypeProc TTypeProc = return Eq
test TTypeUnknown TTypeUnknown = return Eq
test (TTypePtr a) (TTypePtr b) = do
Eq <- test a b
return Eq
test (TTypeArr a _) (TTypeArr b _) = do
Eq <- test a b
return Eq
test (TTypeRetIO a) (TTypeRetIO b) = do
Eq <- test a b
return Eq
test (TTypeFuncR t1 t2) (TTypeFunc t3 t4) = do
Eq <- test t1 t3
Eq <- test t2 t4
return Eq
test (TTypeFuncR t1 t2) (TTypeFuncR t3 t4) = do
Eq <- test t1 t3
Eq <- test t2 t4
return Eq
test _ _ = mzero
-- -------------------------------------------------------------------
-- We need this type families for FunctionArgs class
type family Returns a
type instance Returns (IO Int32) = Int32
type instance Returns (IO Word8) = Word8
type instance Returns (IO ()) = ()
type instance Returns (a->b) = Returns b
type family CG a
type instance CG (IO Int32) = CodeGenFunction Int32 ()
type instance CG (IO Word8) = CodeGenFunction Word8 ()
type instance CG (IO ()) = CodeGenFunction () ()
type instance CG (a->b) = Value a -> CG b
class (FunctionArgs a (CG a) (Returns a))
=> Translate a
instance (FunctionArgs a (CG a) (Returns a))
=> Translate a
| iliastsi/gac | src/basicTypes/TypedAst.hs | mit | 7,484 | 0 | 12 | 1,794 | 2,569 | 1,320 | 1,249 | -1 | -1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
-----------------------------------------------------------------------------
-- |
-- Module : Network.Better.Types
-- Copyright : (c) 2015, Jakub Dominik Kozlowski
-- License : MIT
--
-- Maintainer : [email protected]
--
-- Contains types for interacting with the API.
-----------------------------------------------------------------------------
module Network.Better.Types (
Booking, _Booking, emptyBooking
, bookingParentId, bookingParentTitle, bookingName
, bookingId, bookingRemainingSlots, bookingInstructor
, bookingLocation, bookingFacility, bookingFacilityId
, bookingDate, bookingStartTime, bookingEndTime
, bookingCanCancel, bookingStatus, bookingCanSelectCourt
, FacilityId(..), Facility, _Facility, emptyFacility
, facilityName, facilityId, facilityIsHomeClub, facilityLocationId
, BasketCount, _BasketCount, emptyBasketCount
, basketBasketCount
, ActivityTypeId(..), ActivityTypeBookingId(..), ActivityType
, _ActivityType, emptyActivityType
, activityTypeName, activityTypeId, activityTypeFacilityId
, activityTypeBookingType, activityTypeBookingTypeName
, ActivityId(..), Activity, _Activity, emptyActivity
, activityName, activityId, activityActivityTypeId
, TimetableEntryId(..), TimetableEntry, _TimetableEntry, emptyTimetableEntry
, timetableEntryParentId, timetableEntryId, timetableEntryRemainingSlots
, timetableEntryDate, timetableEntryStartTime, timetableEntryEndTime
, BookingCreditStatus(..)
, _Allocated, bookingCreditStatusAllocateUrl
, _Unallocated, bookingCreditStatusUnallocateUrl
, BasketItem, _BasketItem, emptyBasketItem
, basketItemCreditStatus, basketItemRemoveUrl
, ScrapingException(..), _ScrapingException
) where
import Control.Exception (Exception, SomeException)
import Control.Exception.Lens
import Control.Lens (Prism', makeClassy, makePrisms)
import Data.Aeson (FromJSON (..), ToJSON (..),
Value (Object), object, pairs, (.:),
(.=))
import Data.Aeson.TH (defaultOptions, deriveJSON,
fieldLabelModifier)
import qualified Data.ByteString.Lazy as B
import Data.Monoid ((<>))
import Data.Text (Text)
import Data.Typeable
import Network.Better.Aeson (decapitalizeJsonOptions, jsonOptions,
jsonOptionsRemovePrefix)
import Network.HTTP.Client (Response)
-- | User's booking.
data Booking = Booking
{ _bookingParentId :: {-# UNPACK #-} !Int
, _bookingParentTitle :: !(Maybe Text)
, _bookingName :: {-# UNPACK #-} !Text
, _bookingId :: {-# UNPACK #-} !Int
, _bookingRemainingSlots :: {-# UNPACK #-} !Int
, _bookingInstructor :: {-# UNPACK #-} !Text
, _bookingLocation :: {-# UNPACK #-} !Text
, _bookingFacility :: {-# UNPACK #-} !Text
, _bookingFacilityId :: {-# UNPACK #-} !Int
, _bookingDate :: {-# UNPACK #-} !Text -- Change to Day
, _bookingStartTime :: {-# UNPACK #-} !Text -- Change to Time
, _bookingEndTime :: {-# UNPACK #-} !Text -- Change to Time
, _bookingCanCancel :: !Bool
, _bookingStatus :: {-# UNPACK #-} !Text -- Change to some enum maybe
-- , _bookingExcerciseCategory :: Maybe Text -- Don't actually know what that is
, _bookingCanSelectCourt :: Bool
-- , _bookingDescription :: Maybe Text
-- , _bookingItems :: [] -- Not sure what this is
} deriving (Show, Eq)
$(makeClassy ''Booking)
$(deriveJSON jsonOptions ''Booking)
$(makePrisms ''Booking)
emptyBooking = Booking
{ _bookingParentId = 0
, _bookingParentTitle = Nothing
, _bookingName = ""
, _bookingId = 0
, _bookingRemainingSlots = 0
, _bookingInstructor = ""
, _bookingLocation = ""
, _bookingFacility = ""
, _bookingFacilityId = 0
, _bookingDate = ""
, _bookingStartTime = ""
, _bookingEndTime = ""
, _bookingCanCancel = False
, _bookingStatus = ""
, _bookingCanSelectCourt = False
}
-- | Id of Facility.
newtype FacilityId = FacilityId Int
deriving (Show, Eq, FromJSON, ToJSON)
-- | Facility details.
data Facility = Facility
{ _facilityName :: {-# UNPACK #-} !Text
, _facilityId :: {-# UNPACK #-} !FacilityId
, _facilityIsHomeClub :: !Bool
, _facilityAddress1 :: !(Maybe Text)
, _facilityAddress2 :: !(Maybe Text)
, _facilityAddress3 :: !(Maybe Text)
, _facilityCity :: !(Maybe Text)
, _facilityPostCode :: !(Maybe Text)
, _facilityPhone :: !(Maybe Text)
, _facilityLocationId :: {-# UNPACK #-} !Int
} deriving (Show, Eq)
$(makeClassy ''Facility)
$(deriveJSON jsonOptions ''Facility)
$(makePrisms ''Facility)
emptyFacility = Facility
{ _facilityName = ""
, _facilityId = FacilityId 0
, _facilityIsHomeClub = False
, _facilityAddress1 = Nothing
, _facilityAddress2 = Nothing
, _facilityAddress3 = Nothing
, _facilityCity = Nothing
, _facilityPostCode = Nothing
, _facilityPhone = Nothing
, _facilityLocationId = 0
}
-- | Count of items in the basket.
data BasketCount = BasketCount
{ _basketBasketCount :: {-# UNPACK #-} !Int
} deriving (Show, Eq)
$(makeClassy ''BasketCount)
$(deriveJSON decapitalizeJsonOptions ''BasketCount)
$(makePrisms ''BasketCount)
emptyBasketCount = BasketCount
{ _basketBasketCount = 0
}
-- | Id of ActivityType.
newtype ActivityTypeId = ActivityTypeId Int
deriving (Show, Eq, FromJSON, ToJSON)
-- | Id of ActivityTypeBookingId.
newtype ActivityTypeBookingId = ActivityTypeBookingId Int
deriving (Show, Eq, FromJSON, ToJSON)
-- | Type of activity in a facility.
data ActivityType = ActivityType
{ _activityTypeName :: {-# UNPACK #-} !Text
, _activityTypeId :: {-# UNPACK #-} !ActivityTypeId
, _activityTypeFacilityId :: {-# UNPACK #-} !FacilityId
, _activityTypeBookingType :: {-# UNPACK #-} !ActivityTypeBookingId
, _activityTypeBookingTypeName :: {-# UNPACK #-} !Text
} deriving (Show, Eq)
$(makeClassy ''ActivityType)
$(deriveJSON (jsonOptionsRemovePrefix "_activityType") ''ActivityType)
$(makePrisms ''ActivityType)
emptyActivityType = ActivityType
{ _activityTypeName = ""
, _activityTypeId = ActivityTypeId 0
, _activityTypeFacilityId = FacilityId 0
, _activityTypeBookingType = ActivityTypeBookingId 0
, _activityTypeBookingTypeName = ""
}
-- | Id of specific Activity.
newtype ActivityId = ActivityId Int
deriving (Show, Eq, FromJSON, ToJSON)
-- | Specific activity.
data Activity = Activity
{ _activityName :: {-# UNPACK #-} !Text
, _activityId :: {-# UNPACK #-} !ActivityId
, _activityActivityTypeId :: {-# UNPACK #-} !ActivityTypeId
} deriving (Show, Eq)
$(makeClassy ''Activity)
$(deriveJSON (jsonOptionsRemovePrefix "_activity") ''Activity)
$(makePrisms ''Activity)
emptyActivity = Activity
{ _activityName = ""
, _activityId = ActivityId 0
, _activityActivityTypeId = ActivityTypeId 0
}
-- | Id of TimetableEntry.
newtype TimetableEntryId = TimetableEntryId Int
deriving (Show, Eq, FromJSON, ToJSON)
-- | Entry in a timetable.
data TimetableEntry = TimetableEntry
{ _timetableEntryParentId :: {-# UNPACK #-} !Int
-- , _timetableEntryParentTitle :: Maybe Text
-- , _timetableEntryName :: Text
, _timetableEntryId :: {-# UNPACK #-} !TimetableEntryId
, _timetableEntryRemainingSlots :: {-# UNPACK #-} !Int
-- , _timetableEntryInstructor :: Maybe Text
-- , _timetableEntryLocation :: Text
-- , _timetableEntryFacility :: Text
-- , _timetableEntryFacilityIt :: FacilityId
, _timetableEntryDate :: {-# UNPACK #-} !Text
, _timetableEntryStartTime :: {-# UNPACK #-} !Text
, _timetableEntryEndTime :: {-# UNPACK #-} !Text
-- , _timetableEntryCanCancel :: Bool
-- , _timetableEntryStatus :: Maybe Text
-- , _timetableEntryExerciseCategory :: Maybe Text
-- , _timetableEntryCanSelectCourt :: Bool
-- , _timetableEntryDescription :: Maybe Text
-- , _timetableEntryItems :: [Text]
} deriving (Show, Eq)
$(makeClassy ''TimetableEntry)
$(deriveJSON (jsonOptionsRemovePrefix "_timetableEntry") ''TimetableEntry)
$(makePrisms ''TimetableEntry)
emptyTimetableEntry = TimetableEntry
{ _timetableEntryParentId = 0
, _timetableEntryId = TimetableEntryId 0
, _timetableEntryRemainingSlots = 0
, _timetableEntryDate = ""
, _timetableEntryStartTime = ""
, _timetableEntryEndTime = ""
}
-- | Status of BasketItem credit allocation
data BookingCreditStatus =
Allocated
{ _bookingCreditStatusUnallocateUrl :: {-# UNPACK #-} !Text
}
| Unallocated
{ _bookingCreditStatusAllocateUrl :: {-# UNPACK #-} !Text
} deriving (Show, Eq)
$(makeClassy ''BookingCreditStatus)
$(deriveJSON (jsonOptionsRemovePrefix "_bookingCredit") ''BookingCreditStatus)
$(makePrisms ''BookingCreditStatus)
-- | Item in a basket.
data BasketItem = BasketItem
{ _basketItemCreditStatus :: !BookingCreditStatus
, _basketItemRemoveUrl :: {-# UNPACK #-} !Text
} deriving (Show, Eq)
$(makeClassy ''BasketItem)
$(deriveJSON (jsonOptionsRemovePrefix "_basketItem") ''BasketItem)
$(makePrisms ''BasketItem)
emptyBasketItem = BasketItem
{ _basketItemCreditStatus = Unallocated ""
, _basketItemRemoveUrl = ""
}
data ScrapingException = ScrapingException (Response B.ByteString)
deriving (Show, Typeable)
instance Exception ScrapingException
_ScrapingException :: Prism' SomeException ScrapingException
_ScrapingException = exception
| jkozlowski/better-bot | src/Network/Better/Types.hs | mit | 10,299 | 0 | 11 | 2,452 | 1,842 | 1,087 | 755 | 216 | 1 |
{-# LANGUAGE BangPatterns #-}
import Data.STRef
import Control.Monad
import Control.Monad.ST
import Control.Monad.State.Strict
example1 :: Int
example1 = runST $ do
x <- newSTRef 0
forM_ [1..1000] $ \j -> do
writeSTRef x j
readSTRef x
example2 :: Int
example2 = runST $ do
count <- newSTRef 0
replicateM_ (10^6) $ modifySTRef' count (+1)
readSTRef count
example3 :: Int
example3 = flip evalState 0 $ do
replicateM_ (10^6) $ modify' (+1)
get
modify' :: MonadState a m => (a -> a) -> m ()
modify' f = get >>= (\x -> put $! f x)
| riwsky/wiwinwlh | src/st.hs | mit | 553 | 0 | 12 | 121 | 242 | 122 | 120 | 22 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : App.Combo
-- Copyright : Soostone Inc
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Following the Haskell philosophy of least context needed, this
-- module is meant to encapsulate the common computation context used
-- in your application, independent of the web front-end. It will be
-- present both within the Web layer, but also within the
-- web-independent background processing layer.
--
-- As an example, you may keep several database/API connections within
-- the state here: Groundhog, postgresql-simple, redis, cassandra,
-- twitter API, etc.
----------------------------------------------------------------------------
module App.Combo where
-------------------------------------------------------------------------------
import Control.Applicative
import Control.Monad.Base
import Control.Monad.Logger
import Control.Monad.Reader
import Control.Monad.Trans.Control
import qualified Data.ByteString.Char8 as B
import qualified Data.Configurator as C
import qualified Data.Configurator.Types as C
import Data.Monoid
import Data.Pool
import qualified Database.Groundhog.Postgresql as GH
import Snap.Snaplet.PostgresqlSimple (getConnectionString)
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- | A monad that has access to all the common environment we
-- typically need in this application, including redis, postgres, an
-- RNG, etc.
newtype Combo m a = Combo { unCombo :: ReaderT ComboState m a }
deriving (MonadReader ComboState, Monad, MonadIO,
MonadTrans, Functor, Applicative)
instance MonadTransControl Combo where
newtype StT Combo a = StCombo {unStCombo :: StT (ReaderT ComboState) a}
liftWith = defaultLiftWith Combo unCombo StCombo
restoreT = defaultRestoreT Combo unStCombo
instance MonadBase b m => MonadBase b (Combo m) where
liftBase = liftBaseDefault
instance MonadBaseControl b m => MonadBaseControl b (Combo m) where
newtype StM (Combo m) a = StMCombo {unStMCombo :: ComposeSt Combo m a}
liftBaseWith = defaultLiftBaseWith StMCombo
restoreM = defaultRestoreM unStMCombo
-------------------------------------------------------------------------------
-- | Run a Combo computation
runCombo :: ComboState -> Combo m a -> m a
runCombo cs f = runReaderT (unCombo f) cs
-------------------------------------------------------------------------------
-- | Execute a Combo computation within given Environment.
execCombo :: String -> Combo IO b -> IO b
execCombo env f = mkComboStateEnv env >>= flip runCombo f
-------------------------------------------------------------------------------
-- | Add all the state needed to perform common computations in your
-- application. Some valid examples are intentionally commented out to
-- guide you.
data ComboState = ComboState {
csGH :: Pool GH.Postgresql
-- , csRedis :: H.Connection
-- , csRNG :: RNG
-- , csMgr :: Manager
}
-------------------------------------------------------------------------------
-- | Configure ComboState from given Environment.
--
-- Example: @devel@ if you want to load a 'devel.conf'
mkComboStateEnv :: String -> IO ComboState
mkComboStateEnv env = do
conf <- C.load [C.Required (env <> ".cfg")]
mkComboState conf
-------------------------------------------------------------------------------
-- | Configure ComboState from given 'Config'; helpful for loading as
-- part of the Snap app. It will look for a 'postgresql-simple'
-- portion within the 'Config' given.
mkComboState :: C.Config -> IO ComboState
mkComboState conf = do
let cfg = C.subconfig "postgresql-simple" conf
connstr <- liftIO $ getConnectionString cfg
ghPool <- liftIO $ GH.withPostgresqlPool (B.unpack connstr) 3 return
return $ ComboState ghPool
-------------------------------------------------------------------------------
-- | Perform groundhog op within Combo.
cGH :: (MonadIO m, MonadReader ComboState m)
=> GH.DbPersist GH.Postgresql (NoLoggingT IO) b
-> m b
cGH f = do
c <- asks csGH
liftIO $ GH.runDbConn f c
| katychuang/raw-pixels | src/App/Combo.hs | gpl-2.0 | 4,720 | 0 | 12 | 860 | 685 | 383 | 302 | 55 | 1 |
-- | Boot process of Yi, as an instanciation of Dyre
module Yi.Boot (yi, yiDriver, reload) where
import qualified Config.Dyre as Dyre
import Config.Dyre.Relaunch
import Control.Monad.State
import Control.Monad.Trans
import qualified Data.Rope as R
import System.Directory
import Yi.Config
import Yi.Editor
import Yi.Keymap
import qualified Yi.Main
import qualified Yi.UI.Common as UI
realMain :: Config -> IO ()
realMain config = do
editor <- restoreBinaryState $ Nothing
Yi.Main.main config editor
showErrorsInConf :: Config -> String -> Config
showErrorsInConf conf errs
= conf {startActions = [makeAction $ newBufferE (Left "errors") (R.fromString errs)] ++ startActions conf}
yi, yiDriver :: Config -> IO ()
(yiDriver, yi) = (Dyre.wrapMain yiParams, Dyre.wrapMain yiParams {Dyre.configCheck = False})
where yiParams = Dyre.defaultParams
{ Dyre.projectName = "yi"
, Dyre.realMain = realMain
, Dyre.showError = showErrorsInConf
, Dyre.configDir = Just . getAppUserDataDirectory $ "yi"
, Dyre.hidePackages = ["mtl"]
, Dyre.ghcOpts = ["-threaded", "-O2"]
}
reload :: YiM ()
reload = do
editor <- withEditor get
withUI (\ui -> UI.end ui False)
liftIO $ relaunchWithBinaryState (Just editor) Nothing
| codemac/yi-editor | src/Yi/Boot.hs | gpl-2.0 | 1,334 | 0 | 13 | 301 | 389 | 219 | 170 | 33 | 1 |
{-# LANGUAGE ScopedTypeVariables, FlexibleInstances #-}
{-
Copyright (C) 2006-2016 John MacFarlane <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc
Copyright : Copyright (C) 2006-2016 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <[email protected]>
Stability : alpha
Portability : portable
This helper module exports the main writers, readers, and data
structure definitions from the Pandoc libraries.
A typical application will chain together a reader and a writer
to convert strings from one format to another. For example, the
following simple program will act as a filter converting markdown
fragments to reStructuredText, using reference-style links instead of
inline links:
> module Main where
> import Text.Pandoc
> import Text.Pandoc.Error (handleError)
>
> markdownToRST :: String -> String
> markdownToRST = handleError .
> writeRST def {writerReferenceLinks = True} .
> readMarkdown def
>
> main = getContents >>= putStrLn . markdownToRST
Note: all of the readers assume that the input text has @'\n'@
line endings. So if you get your input text from a web form,
you should remove @'\r'@ characters using @filter (/='\r')@.
-}
module Text.Pandoc
(
-- * Definitions
module Text.Pandoc.Definition
-- * Generics
, module Text.Pandoc.Generic
-- * Options
, module Text.Pandoc.Options
-- * Lists of readers and writers
, readers
, writers
-- * Readers: converting /to/ Pandoc format
, Reader (..)
, mkStringReader
, readDocx
, readOdt
, readMarkdown
, readCommonMark
, readMediaWiki
, readRST
, readOrg
, readLaTeX
, readHtml
, readTextile
, readDocBook
, readOPML
, readHaddock
, readNative
, readJSON
, readTWiki
, readTxt2Tags
, readTxt2TagsNoMacros
, readEPUB
-- * Writers: converting /from/ Pandoc format
, Writer (..)
, writeNative
, writeJSON
, writeMarkdown
, writePlain
, writeRST
, writeLaTeX
, writeConTeXt
, writeTexinfo
, writeHtml
, writeHtmlString
, writeICML
, writeDocbook
, writeOPML
, writeOpenDocument
, writeMan
, writeMediaWiki
, writeDokuWiki
, writeTextile
, writeRTF
, writeODT
, writeDocx
, writeEPUB
, writeFB2
, writeOrg
, writeAsciiDoc
, writeHaddock
, writeCommonMark
, writeCustom
, writeTEI
-- * Rendering templates and default templates
, module Text.Pandoc.Templates
-- * Miscellaneous
, getReader
, getWriter
, ToJsonFilter(..)
, pandocVersion
) where
import Text.Pandoc.Definition
import Text.Pandoc.Generic
import Text.Pandoc.JSON
import Text.Pandoc.Readers.Markdown
import Text.Pandoc.Readers.CommonMark
import Text.Pandoc.Readers.MediaWiki
import Text.Pandoc.Readers.RST
import Text.Pandoc.Readers.Org
import Text.Pandoc.Readers.DocBook
import Text.Pandoc.Readers.OPML
import Text.Pandoc.Readers.LaTeX
import Text.Pandoc.Readers.HTML
import Text.Pandoc.Readers.Textile
import Text.Pandoc.Readers.Native
import Text.Pandoc.Readers.Haddock
import Text.Pandoc.Readers.TWiki
import Text.Pandoc.Readers.Docx
import Text.Pandoc.Readers.Odt
import Text.Pandoc.Readers.Txt2Tags
import Text.Pandoc.Readers.EPUB
import Text.Pandoc.Writers.Native
import Text.Pandoc.Writers.Markdown
import Text.Pandoc.Writers.RST
import Text.Pandoc.Writers.LaTeX
import Text.Pandoc.Writers.ConTeXt
import Text.Pandoc.Writers.Texinfo
import Text.Pandoc.Writers.HTML
import Text.Pandoc.Writers.ODT
import Text.Pandoc.Writers.Docx
import Text.Pandoc.Writers.EPUB
import Text.Pandoc.Writers.FB2
import Text.Pandoc.Writers.ICML
import Text.Pandoc.Writers.Docbook
import Text.Pandoc.Writers.OPML
import Text.Pandoc.Writers.OpenDocument
import Text.Pandoc.Writers.Man
import Text.Pandoc.Writers.RTF
import Text.Pandoc.Writers.MediaWiki
import Text.Pandoc.Writers.DokuWiki
import Text.Pandoc.Writers.Textile
import Text.Pandoc.Writers.Org
import Text.Pandoc.Writers.AsciiDoc
import Text.Pandoc.Writers.Haddock
import Text.Pandoc.Writers.CommonMark
import Text.Pandoc.Writers.Custom
import Text.Pandoc.Writers.TEI
import Text.Pandoc.Templates
import Text.Pandoc.Options
import Text.Pandoc.Shared (safeRead, warn, mapLeft, pandocVersion)
import Text.Pandoc.MediaBag (MediaBag)
import Text.Pandoc.Error
import Data.Aeson
import qualified Data.ByteString.Lazy as BL
import Data.List (intercalate)
import Data.Set (Set)
import qualified Data.Set as Set
import Text.Parsec
import Text.Parsec.Error
import qualified Text.Pandoc.UTF8 as UTF8
parseFormatSpec :: String
-> Either ParseError (String, Set Extension -> Set Extension)
parseFormatSpec = parse formatSpec ""
where formatSpec = do
name <- formatName
extMods <- many extMod
return (name, foldl (.) id extMods)
formatName = many1 $ noneOf "-+"
extMod = do
polarity <- oneOf "-+"
name <- many $ noneOf "-+"
ext <- case safeRead ("Ext_" ++ name) of
Just n -> return n
Nothing
| name == "lhs" -> return Ext_literate_haskell
| otherwise -> fail $ "Unknown extension: " ++ name
return $ case polarity of
'-' -> Set.delete ext
_ -> Set.insert ext
data Reader = StringReader (ReaderOptions -> String -> IO (Either PandocError Pandoc))
| ByteStringReader (ReaderOptions -> BL.ByteString -> IO (Either PandocError (Pandoc,MediaBag)))
mkStringReader :: (ReaderOptions -> String -> Either PandocError Pandoc) -> Reader
mkStringReader r = StringReader (\o s -> return $ r o s)
mkStringReaderWithWarnings :: (ReaderOptions -> String -> Either PandocError (Pandoc, [String])) -> Reader
mkStringReaderWithWarnings r = StringReader $ \o s ->
case r o s of
Left err -> return $ Left err
Right (doc, warnings) -> do
mapM_ warn warnings
return (Right doc)
mkBSReader :: (ReaderOptions -> BL.ByteString -> Either PandocError (Pandoc, MediaBag)) -> Reader
mkBSReader r = ByteStringReader (\o s -> return $ r o s)
mkBSReaderWithWarnings :: (ReaderOptions -> BL.ByteString -> Either PandocError (Pandoc, MediaBag, [String])) -> Reader
mkBSReaderWithWarnings r = ByteStringReader $ \o s ->
case r o s of
Left err -> return $ Left err
Right (doc, mediaBag, warnings) -> do
mapM_ warn warnings
return $ Right (doc, mediaBag)
-- | Association list of formats and readers.
readers :: [(String, Reader)]
readers = [ ("native" , StringReader $ \_ s -> return $ readNative s)
,("json" , mkStringReader readJSON )
,("markdown" , mkStringReaderWithWarnings readMarkdownWithWarnings)
,("markdown_strict" , mkStringReaderWithWarnings readMarkdownWithWarnings)
,("markdown_phpextra" , mkStringReaderWithWarnings readMarkdownWithWarnings)
,("markdown_github" , mkStringReaderWithWarnings readMarkdownWithWarnings)
,("markdown_mmd", mkStringReaderWithWarnings readMarkdownWithWarnings)
,("commonmark" , mkStringReader readCommonMark)
,("rst" , mkStringReaderWithWarnings readRSTWithWarnings )
,("mediawiki" , mkStringReader readMediaWiki)
,("docbook" , mkStringReader readDocBook)
,("opml" , mkStringReader readOPML)
,("org" , mkStringReader readOrg)
,("textile" , mkStringReader readTextile) -- TODO : textile+lhs
,("html" , mkStringReader readHtml)
,("latex" , mkStringReader readLaTeX)
,("haddock" , mkStringReader readHaddock)
,("twiki" , mkStringReader readTWiki)
,("docx" , mkBSReaderWithWarnings readDocxWithWarnings)
,("odt" , mkBSReader readOdt)
,("t2t" , mkStringReader readTxt2TagsNoMacros)
,("epub" , mkBSReader readEPUB)
]
data Writer = PureStringWriter (WriterOptions -> Pandoc -> String)
| IOStringWriter (WriterOptions -> Pandoc -> IO String)
| IOByteStringWriter (WriterOptions -> Pandoc -> IO BL.ByteString)
-- | Association list of formats and writers.
writers :: [ ( String, Writer ) ]
writers = [
("native" , PureStringWriter writeNative)
,("json" , PureStringWriter writeJSON)
,("docx" , IOByteStringWriter writeDocx)
,("odt" , IOByteStringWriter writeODT)
,("epub" , IOByteStringWriter $ \o ->
writeEPUB o{ writerEpubVersion = Just EPUB2 })
,("epub3" , IOByteStringWriter $ \o ->
writeEPUB o{ writerEpubVersion = Just EPUB3 })
,("fb2" , IOStringWriter writeFB2)
,("html" , PureStringWriter writeHtmlString)
,("html5" , PureStringWriter $ \o ->
writeHtmlString o{ writerHtml5 = True })
,("icml" , IOStringWriter writeICML)
,("s5" , PureStringWriter $ \o ->
writeHtmlString o{ writerSlideVariant = S5Slides
, writerTableOfContents = False })
,("slidy" , PureStringWriter $ \o ->
writeHtmlString o{ writerSlideVariant = SlidySlides })
,("slideous" , PureStringWriter $ \o ->
writeHtmlString o{ writerSlideVariant = SlideousSlides })
,("dzslides" , PureStringWriter $ \o ->
writeHtmlString o{ writerSlideVariant = DZSlides
, writerHtml5 = True })
,("revealjs" , PureStringWriter $ \o ->
writeHtmlString o{ writerSlideVariant = RevealJsSlides
, writerHtml5 = True })
,("docbook" , PureStringWriter writeDocbook)
,("opml" , PureStringWriter writeOPML)
,("opendocument" , PureStringWriter writeOpenDocument)
,("latex" , PureStringWriter writeLaTeX)
,("beamer" , PureStringWriter $ \o ->
writeLaTeX o{ writerBeamer = True })
,("context" , PureStringWriter writeConTeXt)
,("texinfo" , PureStringWriter writeTexinfo)
,("man" , PureStringWriter writeMan)
,("markdown" , PureStringWriter writeMarkdown)
,("markdown_strict" , PureStringWriter writeMarkdown)
,("markdown_phpextra" , PureStringWriter writeMarkdown)
,("markdown_github" , PureStringWriter writeMarkdown)
,("markdown_mmd" , PureStringWriter writeMarkdown)
,("plain" , PureStringWriter writePlain)
,("rst" , PureStringWriter writeRST)
,("mediawiki" , PureStringWriter writeMediaWiki)
,("dokuwiki" , PureStringWriter writeDokuWiki)
,("textile" , PureStringWriter writeTextile)
,("rtf" , IOStringWriter writeRTFWithEmbeddedImages)
,("org" , PureStringWriter writeOrg)
,("asciidoc" , PureStringWriter writeAsciiDoc)
,("haddock" , PureStringWriter writeHaddock)
,("commonmark" , PureStringWriter writeCommonMark)
,("tei" , PureStringWriter writeTEI)
]
getDefaultExtensions :: String -> Set Extension
getDefaultExtensions "markdown_strict" = strictExtensions
getDefaultExtensions "markdown_phpextra" = phpMarkdownExtraExtensions
getDefaultExtensions "markdown_mmd" = multimarkdownExtensions
getDefaultExtensions "markdown_github" = githubMarkdownExtensions
getDefaultExtensions "markdown" = pandocExtensions
getDefaultExtensions "plain" = plainExtensions
getDefaultExtensions "org" = Set.fromList [Ext_citations,
Ext_auto_identifiers]
getDefaultExtensions "textile" = Set.fromList [Ext_auto_identifiers]
getDefaultExtensions "html" = Set.fromList [Ext_auto_identifiers,
Ext_native_divs,
Ext_native_spans]
getDefaultExtensions "html5" = getDefaultExtensions "html"
getDefaultExtensions "epub" = Set.fromList [Ext_raw_html,
Ext_native_divs,
Ext_native_spans,
Ext_epub_html_exts]
getDefaultExtensions _ = Set.fromList [Ext_auto_identifiers]
-- | Retrieve reader based on formatSpec (format+extensions).
getReader :: String -> Either String Reader
getReader s =
case parseFormatSpec s of
Left e -> Left $ intercalate "\n" [m | Message m <- errorMessages e]
Right (readerName, setExts) ->
case lookup readerName readers of
Nothing -> Left $ "Unknown reader: " ++ readerName
Just (StringReader r) -> Right $ StringReader $ \o ->
r o{ readerExtensions = setExts $
getDefaultExtensions readerName }
Just (ByteStringReader r) -> Right $ ByteStringReader $ \o ->
r o{ readerExtensions = setExts $
getDefaultExtensions readerName }
-- | Retrieve writer based on formatSpec (format+extensions).
getWriter :: String -> Either String Writer
getWriter s
= case parseFormatSpec s of
Left e -> Left $ intercalate "\n" [m | Message m <- errorMessages e]
Right (writerName, setExts) ->
case lookup writerName writers of
Nothing -> Left $ "Unknown writer: " ++ writerName
Just (PureStringWriter r) -> Right $ PureStringWriter $
\o -> r o{ writerExtensions = setExts $
getDefaultExtensions writerName }
Just (IOStringWriter r) -> Right $ IOStringWriter $
\o -> r o{ writerExtensions = setExts $
getDefaultExtensions writerName }
Just (IOByteStringWriter r) -> Right $ IOByteStringWriter $
\o -> r o{ writerExtensions = setExts $
getDefaultExtensions writerName }
{-# DEPRECATED toJsonFilter "Use 'toJSONFilter' from 'Text.Pandoc.JSON' instead" #-}
-- | Deprecated. Use @toJSONFilter@ from @Text.Pandoc.JSON@ instead.
class ToJSONFilter a => ToJsonFilter a
where toJsonFilter :: a -> IO ()
toJsonFilter = toJSONFilter
readJSON :: ReaderOptions -> String -> Either PandocError Pandoc
readJSON _ = mapLeft ParseFailure . eitherDecode' . UTF8.fromStringLazy
writeJSON :: WriterOptions -> Pandoc -> String
writeJSON _ = UTF8.toStringLazy . encode
| fibsifan/pandoc | src/Text/Pandoc.hs | gpl-2.0 | 16,216 | 0 | 17 | 4,889 | 3,043 | 1,735 | 1,308 | 297 | 5 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Convert.Type where
import Autolib.Reader
import Autolib.ToDoc
import Data.Typeable
import qualified Convert.Input
import qualified CSP.Trace
import Autolib.Exp.Inter
import Autolib.Exp
import Autolib.NFA hiding ( alphabet )
import Autolib.Set
data Convert =
Convert { name :: Maybe [String]
-- ^ if Nothing, use (show input)
, input :: Convert.Input.Input Char
}
deriving ( Typeable , Show )
$(derives [makeReader, makeToDoc] [''Convert])
form :: Convert -> Doc
form conv = case name conv of
Nothing -> Convert.Input.lang $ input conv
Just css -> vcat $ map text css
eval :: Set Char -> Convert -> NFA Char Int
eval alpha conv = case input conv of
Convert.Input.NFA aut -> aut
Convert.Input.Exp exp ->
inter ( std_sigma $ setToList alpha ) exp
Convert.Input.Process p ->
Autolib.NFA.minimize0
$ Autolib.NFA.normalize
$ CSP.Trace.auto p
| marcellussiegburg/autotool | collection/src/Convert/Type.hs | gpl-2.0 | 1,035 | 18 | 10 | 258 | 270 | 159 | 111 | 30 | 3 |
module HLinear.Hook.EchelonForm.SmallCheck
where
import HLinear.Utility.Prelude
import Math.Structure ( isZero, nonZero, DecidableZero )
import Test.SmallCheck.Series ( Serial, Series(..), series, decDepth )
import qualified Data.Vector as V
import HLinear.Hook.EchelonForm.Basic
import HLinear.Hook.EchelonForm.Definition
import HLinear.Hook.EchelonForm.Row
instance (Monad m, Serial m a, DecidableZero a)
=> Serial m (EchelonForm a)
where
series = do
lrs <- series
guard $ lrs >= 0
nrs <- series
guard $ nrs >= lrs
ncs <- series
EchelonForm nrs ncs <$>
( V.replicateM lrs $ decDepth $ do
o <- series
guard $ 0 >= 0 && ncs >= o
EchelonFormRow o <$>
( V.replicateM (ncs-o) $
decDepth $ decDepth series
)
)
| martinra/hlinear | src/HLinear/Hook/EchelonForm/SmallCheck.hs | gpl-3.0 | 834 | 0 | 19 | 231 | 260 | 141 | 119 | -1 | -1 |
Subsets and Splits