code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Person where
data Person = Person { firstName :: String
, lastName :: String
, age :: Int
, height :: Float
, phoneNumber :: String
, flavor :: String
} deriving (Show)
| fredmorcos/attic | snippets/haskell/Person.hs | isc | 326 | 0 | 8 | 184 | 56 | 36 | 20 | 8 | 0 |
module Cli.Cli (listen, prompt, say) where
listen :: IO String
listen = getLine
prompt :: (Read a) => String -> IO a
prompt s = putStr s >> getLine >>= return . read
say :: String -> IO ()
say x = putStrLn x | korczis/skull-haskell | src/Lib/Cli/Cli.hs | mit | 211 | 0 | 8 | 47 | 99 | 52 | 47 | 7 | 1 |
-- ghci
-- :load C:\Users\Thomas\Documents\GitHub\haskell.practice\PE\Problem0016.hs
-- :r
-- :set +s
module Problem16 where
import Data.Char
twoToThePowerOf n =
2 ^ n
sumOfDigits n =
sum
$ map digitToInt
$ show n
sumOfDigitsForTwoToThePowerOf n =
sumOfDigits
$ twoToThePowerOf n
--Tests
sumOfDigitsForTwoToThePowerOfTests = and
[
sumOfDigitsForTwoToThePowerOf 2 == 4,
sumOfDigitsForTwoToThePowerOf 15 == 26,
sumOfDigitsForTwoToThePowerOf 45 == 62
]
sumOfDigitsTests = and
[
sumOfDigits 10 == 1,
sumOfDigits 5555555555 == 50
]
twoToThePowerOfTests = and
[
twoToThePowerOf 2 == 4,
twoToThePowerOf 15 == 32768,
twoToThePowerOf 30 == 1073741824,
twoToThePowerOf 35 == 34359738368,
twoToThePowerOf 45 == 35184372088832
]
tests = and
[
twoToThePowerOfTests,
sumOfDigitsTests,
sumOfDigitsForTwoToThePowerOfTests
]
answer = sumOfDigitsForTwoToThePowerOf 1000 | Sobieck00/practice | pe/nonvisualstudio/haskell/OldWork/Implementation/Problem0016.hs | mit | 965 | 78 | 9 | 219 | 265 | 145 | 120 | 33 | 1 |
module Euler.P002 (sumEvenFib,
sumEvenFib') where
-- Problem 2
--
-- Each new term in the Fibonacci sequence is generated by adding the previous
-- two terms. By starting with 1 and 2, the first 10 terms will be:
--
-- 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
--
-- By considering the terms in the Fibonacci sequence whose values do not
-- exceed four million, find the sum of the even-valued terms.
sumEvenFib :: Int -> Int
sumEvenFib = sum . evenFib
evenFib :: Int -> [Int]
evenFib n = filter even $ takeWhile (<= n) $ map fib [1..]
fib :: (Integral a) => a -> a
fib 0 = 0
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)
sumEvenFib' :: Int -> Int
sumEvenFib' = sum . evenFib'
evenFib' :: Int -> [Int]
evenFib' n = filter even $ takeWhile (<= n) fib'
fib' :: [Int]
fib' = 0 : scanl (+) 1 fib'
| arnau/haskell-euler | src/Euler/P002.hs | mit | 819 | 0 | 8 | 199 | 233 | 130 | 103 | 16 | 1 |
{-
Copyright (c) 2015 Nils 'bash0r' Jonsson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-}
{- |
Module : $Header$
Description : An expression in the PolyDSL language.
Author : Nils 'bash0r' Jonsson
Copyright : (c) 2015 Nils 'bash0r' Jonsson
License : MIT
Maintainer : aka.bash0r@gmail.com
Stability : unstable
Portability : non-portable (Portability is untested.)
An expression in the PolyDSL language.
-}
module Language.PolyDSL.DOM.Expression
( Expression (..)
) where
-- | A PolyDSL expression.
data Expression
-- | A numeric value in the PolyDSL language.
= NumberLiteral Rational
-- | A string value in the PolyDSL language.
| StringLiteral String
-- | A char value in the PolyDSL language.
| CharLiteral Char
-- | An identifier in the PolyDSL language.
| Identifier String
-- | A binary operator expression in the PolyDSL language.
| BinaryExpression String Expression Expression
-- | A function call expression in the PolyDSL language.
| FunctionCall Expression Expression
deriving (Show, Eq)
| project-horizon/framework | src/lib/Language/PolyDSL/DOM/Expression.hs | mit | 2,058 | 0 | 6 | 391 | 77 | 50 | 27 | 10 | 0 |
-- Enumerator and iteratee
-- ref: https://wiki.haskell.org/Enumerator_and_iteratee
-- okmij: http://okmij.org/ftp/Haskell/Iteratee/describe.pdf
-- An enumerator is something that knows how to generate a list
-- An iteratee is something that does one step in processing another piece of the big list.
-- foldl (+) 0 xs
-- foldl : enumerator
-- ((+), 0) iteratee
-- Separation of concerns
-- fold(enumerator) has the intimate knowledge of the collection and how to get to the next element
-- iteratee knows what to do with the current element
-- (+) not to care which collection the element from
-- 0 unware of the collection
-- F-algebra
-- ((+), 0) is an F-algebra
-- foldl (+) 0 is a catamorphism
-- iteratee is an automaton
-- From this point of view, the enumerator sends elements of a list sequentially, from head to tail, as input messages to the iteratee. If the iteratee finishes, it outputs an accumulator. If the iteratee continues, it outputs nothing (i.e., ()).
-- a set of states of iteratee is divided into subsets "Done" and "Next".
-- Done-state means that automaton finished consuming a list, i.e., the automaton is dead.
-- Next-state means that you can give an input message and obtain the same automaton in a new state.
data Iteratee i o = Done o | Next (i -> Iteratee i o)
-- i is the type of the iteratee's input messages (or list elements)-- o is a type of the output message (an accumulator).
-- Iteratee stores not an automaton, but an automaton in some state, an automaton with distinguished state.
-- The distinct feature of iteratee is that it can say after which list element an iteratee finishes. An iteratee says this by sending "Done" to an enumerator. Then the enumerator can, for example, close a file or a socket (a stream) where a list of characters is read from. Lazy I/O, which uses lazy lists, closes a stream only when the stream is exhausted.
-- The drawback is that an enumerator can not tell an iteratee that an input is exhausted — an Iteratee consumes only infinite lists. You can remedy this by assuming
-- i == Maybe i' (That's just fix)
-- sample enumerator that takes input messages from a file
enumerator :: FilePath -> Iteratee (Maybe Char) o -> IO o
enumerator file it = withFile file ReadMode
$ \h -> fix (\rc it -> case it of
Done o -> return o
Next f -> do
eof <- hIsEOF h
case eof of
False -> do
c <- hGetChar h
rc (f (Just c))
True -> rc (f Nothing)
) it
-- 2. Functions
-- pi-calculus notation
-- Monadic parsing (it0 -> it1)
-- You can compose iteratees sequentially in time. This is done by (>>). it0 >> it1 means that when it0 finishes, it1 starts. Generally speaking, Iteratee i is a Monad, and it works exactly like a monadic parser.
{- s = state -}
instance Functor (Iteratee input) where
fmap f = fix $ \rc s -> case s of
Done o -> Done (f o)
Next g -> Next (rc . g)
instance Monad (Iteratee input) where
return = Done
it0 >>= it1 = fix (\rc s -> case s of
Done o -> it1 o
Next g -> Next (rc . g)
) it0
-- Repetitive parsing (it1 | !it0)
-- You can also compose iteratees sequentially in space. it0's output messages become it1's input messages, so it0 and it1 work in parallel. Their composition is denoted it1 . it0. If it0 finishes, it is resurrected to its original state. If it1 finishes, it1 . it0 finishes — The main feature here is that it0 is restarted, as this is used for repetitive parsing.
arr0 f = Next $ \i -> Done (f i)
instance Category Iteratee where
id = arr0 id
it1 . it0 = fix (\rc1 it1 -> case it1 of
Done c -> Done c
Next f1 -> fix (\rc0 it0 -> case it0 of
Done b -> rc1 (f1 b)
Next f0 -> Next (rc0 . f0)
) it0
) it1
-- 3. Generalization
-- You may note that Iteratee is a final coalgebra. Other kinds of automata can be described with other F-coalgebras. In practice such automata can handle network protocols or interactive user input. See for example papers by Bart Jacobs for theoretical discussion.
{-
type Iteratee el m a −− a processor of the stream of els
−− in a monad m yielding the result of type a
instance Monad m ⇒ Monad (Iteratee el m)
instance MonadTrans (Iteratee el )
getchar :: Monad m ⇒ Iteratee el m (Maybe el) −− cf. IO.getChar, List . head
count_i :: Monad m ⇒ Iteratee el m Int −− cf. List . length
run :: Monad m ⇒ Iteratee el m a → m a −− extract Iteratee ’ s result
−− A producer of the stream of els in a monad m
type Enumerator el m a = Iteratee el m a → m (Iteratee el m a)
enum file :: FilePath → Enumerator Char IO a −− Enumerator of a file
−− A transformer of the stream of elo to the stream of eli
−− (a producer of the stream eli and a consumer of the stream elo )
type Enumeratee elo eli m a =
Iteratee eli m a → Iteratee elo m (Iteratee eli m a)
en_filter :: Monad m ⇒ (el → Bool) → Enumeratee el el m a
take :: Monad m ⇒ Int → Enumeratee el el m a −− cf. List . take
enum_words :: Monad m ⇒ Enumeratee Char String m a −− cf. List.words
−− Kleisli (monadic function) composition: composing enumerators
(>>>) :: Monad m ⇒ (a → m b) → (b → m c) → (a → m c)
−− Connecting producers with transformers (cf . (= ))
infixr 1 . | −− right−associative
(.|) :: Monad m ⇒
(Iteratee el m a → w) → Iteratee el m (Iteratee el ’ m a) → w
−− Parallel composition of iteratees (cf . List . zip )
en_pair :: Monad m ⇒
Iteratee el m a → Iteratee el m b → Iteratee el m (a,b)
-} | Airtnp/Freshman_Simple_Haskell_Lib | Idioms/Enumerator-Iteratee.hs | mit | 5,808 | 0 | 24 | 1,442 | 526 | 273 | 253 | 33 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : StandardLibrary
-- Copyright : (c) University of Saskatchewan 2013
--
-- Maintainer : ivan.vendrov@usask.ca
--
-- The Frabjous standard library
--------------------------------------------------------------------------
module Frabjous.StdLib
(Real,
-- * Utility Functions
clip,
length,
count,
fraction,
average,
stepWire,
-- * Random Numbers
uniform,
frequencies,
draw,
-- * Wire Combinators
-- ** simple combinators
constant,
function,
-- ** event combinators
(<|>),
edge,
changed,
andThen,
never,
after,
for,
delay,
-- ** real numbers
integrate,
randomWalk,
-- ** randomness
noise,
poisson,
countingPoisson,
rate,
-- ** functions that take wires as parameters & analyze them somehow
accumulate,
countEvents,
onChange,
internalStateT,
internalState,
-- ** switches
switch,
stateDiagram,
-- * Networks
-- ** static networks
emptyNetwork,
randomNetwork,
predicate,
gridWithDiags,
{-
randomSymmetricNetwork,
poissonSymmetricNetwork,
-- ** dynamic networks
memorylessSymmetric,
randomSymmetric,
poissonRandomSymmetric,
distanceBased,
-}
-- ** auxiliary functions
manhattan,
euclidean,
normed)
where
import Frabjous.StdLib.Internal hiding (edge)
import qualified Frabjous.Compiler.Syntax as Syntax
import Prelude hiding ((.), id, length, Real)
import Control.Monad.Random hiding (uniform)
import Data.Traversable as Traversable hiding (for)
import Control.Wire (mkGen, mkState, (.), Wire, WireM, EventM, LastException,
(<|>), after, delay, for, andThen, edge,
changed)
import qualified Control.Wire as Wire
import Data.Monoid
import Data.Tuple (swap)
import Data.List hiding (length)
import qualified Data.List
import qualified Data.IntMap as IntMap
type Real = Double
-- -1. UTILITY FUNCTIONS
-- | the function 'clip' keeps its value in the given closed interval
clip (a,b) x = if x < a then a
else if x > b then b
else x
-- | generalizes length to any numeric type, allowing one to elide 'fromIntegral' in code
length :: (Num n) => [a] -> n
length = fromIntegral . Data.List.length
-- | counts the number of elements that satisfy the given predicate
count :: (a -> Bool) -> [a] -> Integer
count pred = length . filter pred
-- | determines the fraction of elements satisfying the given predicate
fraction :: (a -> Bool) -> [a] -> Double
fraction pred l = fromIntegral (count pred l) / length l
-- | finds the average of a list of numbers
average :: [Double] -> Double
average l = sum l / length l
-- 0. RANDOM NUMBERS
uniform :: MonadRandom m => (Double, Double) -> m Double
uniform = getRandomR
frequencies :: MonadRandom m => [(a, Double)] -> m a
frequencies probs =
let (vals, pdf) = unzip probs
cdf = scanl1 (+) pdf
in do
p <- getRandom
let Just idx = findIndex (>= p) cdf
return (vals !! idx)
draw :: MonadRandom m => Int -> m a -> m [a]
draw n rand = Traversable.sequence (replicate n rand)
stepWire :: Monad m => Wire.WireM m a b -> Wire.Time -> a -> m (Either LastException b, Wire.WireM m a b)
stepWire = Wire.stepWire
-- 1. WIRE COMBINATORS
constant :: (Monad m) => b -> Wire e m a b
constant = Wire.pure
function :: (Monad m) => (a -> b) -> Wire e m a b
function = Wire.arr
never :: (Monad m, Monoid e) => Wire e m a b
never = Wire.empty
-- | draws a value from the given distribution at every timestep
noise :: MonadRandom m => m a -> Wire LastException m input a
noise distribution = mkGen $ \_ _ -> do
val <- distribution
return (Right val, noise distribution)
-- | integrates its input with respect to time
integrate :: Monad m => Double -> Wire e m Double Double
integrate = internalStateT (\dt x -> (+ dt*x))
-- | performs a 1D random walk at the velocity specified by the given distribution
randomWalk init distribution = integrate init . noise distribution
-- | (TODO REFACTOR?) internalStateT applies the given transition function
-- | to the timestep, input, and state at every step, then outputs the new state
internalStateT ::
(Double -> a -> s -> s) -- ^ the transition function
-> s -- ^ the initial state
-> Wire e m a s
internalStateT transition init = mkState init $ \dt (x, state) ->
let newState = transition dt x state
in newState `seq` (Right newState, newState)
-- | internalState applies the given transition function
-- | to its input and state at every step, then outputs the state
internalState transition init = internalStateT (const transition) init
-- nonhomogenous poisson process
rate :: MonadRandom m => Wire LastException m Double ()
rate = mkGen $
\dt lambda -> do
e <- getRandom
return (if e < 1 - exp (-dt * lambda) then Right () else Left mempty, rate)
-- a poisson process with rate parameter lambda
poisson :: MonadRandom m => Double -> Wire LastException m a ()
poisson lambda = rate . constant lambda
-- a counting poisson process
countingPoisson :: MonadRandom m => Double -> Wire LastException m a Int
countingPoisson lambda = countEvents (poisson lambda)
-----------------------------------------------------
-- Functions that take wires as parameters
-- and analyze them somehow - ('higher order' wires)
-----------------------------------------------------
-- | orElse is a synonym for <|> (acts like the first wire if it produces; otherwise, like the second)
orElse :: Monad m => WireM m a b -> WireM m a b -> WireM m a b
orElse = (<|>)
-- | accumulates the output of a signal function by the given combining function, with the given starting state
accumulate :: Monad m => (b -> a -> b) -> b -> Wire e m c a -> Wire e m c b
accumulate binop init wire = Wire.hold init (Wire.accum binop init . wire)
-- | count the number of events of an argument wire
countEvents :: Monad m => Wire e m a b -> Wire e m a Int
countEvents wire = accumulate (+) 0 (1 . wire)
-- | produces when the argument wire changes output
onChange :: (Eq b, Monad m) => WireM m a b -> EventM m a
onChange wire = on (changed . wire)
-- | produces when the argument wire produces
on :: Monad m => WireM m a b -> EventM m a
on wire = mkGen $ \dt x -> do
(output, wire') <- stepWire wire dt x
let output' = case output of
Right _ -> Right x
Left e -> Left e
return (output', on wire')
-- | whenever producer produces a wire, that wire is switched into (and starts at time 0)
-- | (difference from Netwire is that there's no initial wire)
switch producer = Wire.switch producer never
-- statechart :: Wire a b -> Wire a (Wire a b) -> Wire a b
-- statechart state transitions is a wire whose internal state will be the most recent
-- value produced by transitions; and which is refreshed every time its internal state changes
stateDiagram state transitions = switch (transitions . onChange state) `orElse` state
-- 2. NETWORKS
-- A) Library functions for creation
pairs xs = [(u, v) | u <- xs, v <- xs, u < v]
symmetrify edges = edges ++ map swap edges
emptyNetwork :: (MonadRandom m) => [Int] -> [Int] -> m (Network e)
emptyNetwork v1 v2 = return $ Network (Syntax.Many, Syntax.Many) v1 v2 []
randomNetwork :: (MonadRandom m) => Double -> [Int] -> [Int] -> m (Network ())
-- randomNetwork rng fraction size = a random network with the given integer vertices.
-- each directed edge has a given probability of existing
randomNetwork fraction vertices1 vertices2 = do
randoms <- getRandoms
let edges = map snd . filter ((<fraction) . fst) . zip randoms $
[(u,v) | u <- vertices1,
v <- vertices2]
return $ Network (Syntax.Many, Syntax.Many) vertices1 vertices2 (zipWith Edge edges (repeat ()))
predicate :: (a -> a -> Bool) -> NetworkGenerator a () -- TODO generalize to any edge type
predicate connected pop _ =
let vertices = IntMap.toList pop
edges = [(i1, i2) | (i1, v1) <- vertices, (i2, v2) <- vertices, i1 < i2, connected v1 v2]
indices = IntMap.keys pop
in return $ Network (Syntax.Many, Syntax.Many) indices indices (zipWith Edge edges (repeat ()))
gridWithDiags :: Int -> [a -> Int] -> NetworkGenerator a () -- TODO generalize to any edge type
gridWithDiags resolution coords = predicate connected where
connected a1 a2 = let x = map ($a1) coords
y = map ($a2) coords
diffs = map abs $ zipWith (-) x y
in all (<= resolution) diffs
{-
-- poissonSymmetricNetwork is like a random network but for a single population
-- each UNDIRECTED edge has a "fraction" probability of existing
poissonSymmetricNetwork fraction vertices _ = do
randoms <- getRandoms
let edges = map snd . filter ((<fraction) . fst) . zip randoms $ pairs vertices
return $ fromEdges vertices vertices (symmetrify edges)
-- | creates a random network with each link probability calculated using the
-- | binary function prob
randomSymmetricNetwork :: ((a,a) -> Double) -> NetworkGenerator a
randomSymmetricNetwork prob pop _ = do
randoms <- getRandoms
let vertices = IntMap.toList pop
edges' = map (snd . snd) . filter (\(r, (vs, _)) -> r < prob vs) . zip randoms $
[((v1, v2), (i1, i2)) | (i1, v1) <- vertices,
(i2, v2) <- vertices, i1 < i2]
edges = edges' ++ map swap edges'
indices = map fst vertices
return $ fromEdges indices indices edges
-- B) dynamic networks
-- converts a static network generator into a dynamic one by just applying it every step
memorylessSymmetric :: NetworkGenerator a ->
(model -> ReactiveOutput a) -> ModelWire model ManyToMany
memorylessSymmetric staticCreator extractPop = helper where
helper = mkGen $ \dt model -> do
let v1 = collection . extractPop $ model
network <- staticCreator v1 v1
return (Right network, helper)
-- | have links between agents based on the given probability function
randomSymmetric :: ((a,a) -> Double) -> (model -> ReactiveOutput a) ->
ModelWire model ManyToMany
randomSymmetric prob = memorylessSymmetric (randomSymmetricNetwork prob)
poissonRandomSymmetric :: Double ->
(model -> ReactiveOutput a) ->
ModelWire model ManyToMany
poissonRandomSymmetric prob = randomSymmetric (const prob)
predicateDynamic pred = memorylessSymmetric (predicate pred)
{-
predicate :: (a -> a -> Bool) -> (model -> ReactiveOutput a) -> ModelWire model ManyToMany
predicate connected extractPop = function helper where
helper model = let pop = collection . extractPop $ model
indices = IntMap.keys pop
indexPairs = pairs indices
withinDistance (i1, i2) = connected (pop IntMap.! i1) (pop IntMap.! i2)
in fromEdges indices indices (symmetrify $ filter withinDistance indexPairs)
-}
distanceBased :: Num n => (a -> a -> n) ->
(n -> Bool) ->
(model -> ReactiveOutput a) ->
ModelWire model ManyToMany
distanceBased d pred = predicateDynamic (\ a b -> pred $ d a b)
-}
euclidean :: [a -> Double] -> a -> a -> Double
euclidean = normed 2
manhattan :: Num n => [a -> n] -> a -> a -> n
manhattan accessors p1 p2 = sum . map abs $ diffs accessors p1 p2
diffs accessors p1 p2 =
let coords1 = map ($ p1) accessors
coords2 = map ($ p2) accessors
in zipWith (-) coords1 coords2
normed :: Double -> [a -> Double] -> a -> a -> Double
normed p accessors p1 p2 = norm (diffs accessors p1 p2)
where norm diffs = sum (map (**p) diffs) ** (1/p)
{-
-- sample dynamic network specifications :
-- a. makes "v" a neighbour of "u" iff (pred u v)
predicateNetwork :: (a -> a -> Bool) -> Vector a -> Vector (Vector a)
predicateNetwork pred agents = map (\p -> filter (pred p) agents) agents
-- b . makes u and v neighbours iff label u = label v
equivalenceClass :: (Eq b) => (a :-> b) -> Vector a -> Vector (Vector a)
equivalenceClass label = predicateNetwork ((==) `on` (get label))
-- c. makes person i belong to neighbourhood j of n iff i % n = j
evenlyDistribute people nbhds = map (nbhds!) $ map (`mod` n) (fromList [0 .. nPeople-1]) where
n = length nbhds
nPeople = length people
-} | ivendrov/frabjous2 | src/Frabjous/StdLib.hs | mit | 12,883 | 0 | 16 | 3,370 | 2,601 | 1,401 | 1,200 | 162 | 3 |
{-
Package for evaluating Scheme Expressions
-}
module Scheme.Eval (
-- module Scheme.Eval.LispError,
module Scheme.Eval.Prim,
module Scheme.Eval.EvalUtil,
module Scheme.Eval.List,
module Scheme.Eval.Comp,
module Scheme.Eval.Unpack
) where
import Text.ParserCombinators.Parsec hiding (spaces)
import Control.Monad.Error
import Scheme.Lex
-- import Scheme.Eval.LispError
import Scheme.Eval.Prim
import Scheme.Eval.EvalUtil
import Scheme.Eval.List
import Scheme.Eval.Comp
import Scheme.Eval.Unpack
| johnellis1392/Haskell-Scheme | Scheme/Eval/Eval.hs | mit | 520 | 0 | 5 | 69 | 99 | 68 | 31 | 14 | 0 |
import Test.HUnit
import System.Exit
import Data.Set.Lazy
tests = TestList [basic, fizzbuzztest, infinity]
---- BASIC -----
basic = TestList [noZero, oneToTen, noEleven]
where
toTenList = [1..10]
toTenSet = fromList toTenList
noZero = TestCase $ assertBool "Zero not in there" $not (member 0 toTenSet)
oneToTen = TestCase $ assertBool "1 to 10 present in set." $ all (\i -> member i toTenSet) toTenList
noEleven = TestCase $ assertBool "11 not in there" $not (member 11 toTenSet)
----- INFINITY----
evenNumberSet = fromList $ filter even [1..]
infinity = TestList [
TestCase ( assertBool "Even numbers are in there "
(all (\i -> member i evenNumberSet) [2,4,6,100,10^4])),
TestCase ( assertBool "Odd numbers are in there "
(all (\i ->not $ member i evenNumberSet) [1,3,5,99,10^4+1]))
]
--- FizzBuzz ---
isFizzBuzz x = x `mod` 7 == 0 || '7' `elem` show x
fizzbuzzes = fromList $ filter isFizzBuzz [1..]
fizzbuzztest = TestList[
TestCase ( assertBool "fizzes"
(all (\i -> member i fizzbuzzes) [7,14,21,70,71,77])),
TestCase ( assertBool "does not fizz"
(all (\i -> not $ member i fizzbuzzes) [1,2,3,8,9,10,16,22,100])) ]
main = do
result <- runTestTT tests
let allpassed = (errors result + failures result) == 0
if allpassed then exitSuccess else exitFailure | happyherp/lazyset | LazySetTest.hs | mit | 1,490 | 0 | 15 | 430 | 526 | 285 | 241 | 27 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Codex.Config where
import qualified Data.HashMap.Strict as HM
import Snap.Util.FileServe(MimeMap, defaultMimeTypes)
-- | custom mime type mapping
mimeTypes :: MimeMap
mimeTypes
= HM.union defaultMimeTypes $
HM.fromList [(".mdown", "text/markdown"),
(".md", "text/markdown"),
(".tst", "text/plain"),
(".cfg", "text/plain")
]
| pbv/codex | src/Codex/Config.hs | mit | 452 | 0 | 8 | 125 | 91 | 58 | 33 | 11 | 1 |
-- |
-- AST traversal extracting output types.
module Hasql.TH.Extraction.OutputTypeList where
import Hasql.TH.Prelude
import PostgresqlSyntax.Ast
foldable :: Foldable f => (a -> Either Text [Typename]) -> f a -> Either Text [Typename]
foldable fn = fmap join . traverse fn . toList
preparableStmt = \case
SelectPreparableStmt a -> selectStmt a
InsertPreparableStmt a -> insertStmt a
UpdatePreparableStmt a -> updateStmt a
DeletePreparableStmt a -> deleteStmt a
-- * Insert
insertStmt (InsertStmt a b c d e) = foldable returningClause e
returningClause = targetList
-- * Update
updateStmt (UpdateStmt _ _ _ _ _ a) = foldable returningClause a
-- * Delete
deleteStmt (DeleteStmt _ _ _ _ a) = foldable returningClause a
-- * Select
selectStmt = \case
Left a -> selectNoParens a
Right a -> selectWithParens a
selectNoParens (SelectNoParens _ a _ _ _) = selectClause a
selectWithParens = \case
NoParensSelectWithParens a -> selectNoParens a
WithParensSelectWithParens a -> selectWithParens a
selectClause = either simpleSelect selectWithParens
simpleSelect = \case
NormalSimpleSelect a _ _ _ _ _ _ -> foldable targeting a
ValuesSimpleSelect a -> valuesClause a
TableSimpleSelect _ -> Left "TABLE cannot be used as a final statement, since it's impossible to specify the output types"
BinSimpleSelect _ a _ b -> do
c <- selectClause a
d <- selectClause b
if c == d
then return c
else Left "Merged queries produce results of incompatible types"
targeting = \case
NormalTargeting a -> targetList a
AllTargeting a -> foldable targetList a
DistinctTargeting _ b -> targetList b
targetList = foldable targetEl
targetEl = \case
AliasedExprTargetEl a _ -> aExpr a
ImplicitlyAliasedExprTargetEl a _ -> aExpr a
ExprTargetEl a -> aExpr a
AsteriskTargetEl ->
Left
"Target of all fields is not allowed, \
\because it leaves the output types unspecified. \
\You have to be specific."
valuesClause = foldable (foldable aExpr)
aExpr = \case
CExprAExpr a -> cExpr a
TypecastAExpr _ a -> Right [a]
a -> Left "Result expression is missing a typecast"
cExpr = \case
InParensCExpr a Nothing -> aExpr a
a -> Left "Result expression is missing a typecast"
| nikita-volkov/hasql-th | library/Hasql/TH/Extraction/OutputTypeList.hs | mit | 2,245 | 0 | 11 | 456 | 646 | 307 | 339 | -1 | -1 |
{-# LANGUAGE PackageImports #-}
{-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-}
-- | Reexports "Text.Read.Lex.Compat"
-- from a globally unique namespace.
module Text.Read.Lex.Compat.Repl.Batteries (
module Text.Read.Lex.Compat
) where
import "this" Text.Read.Lex.Compat
| haskell-compat/base-compat | base-compat-batteries/src/Text/Read/Lex/Compat/Repl/Batteries.hs | mit | 294 | 0 | 5 | 31 | 32 | 25 | 7 | 5 | 0 |
module OneDim where
import Data.Bits
import CellularAutomata2D
import GUI
initSpace1D :: Int -> [a] -> Torus (Maybe a)
initSpace1D steps initialSpace1D = setCells emptySpace (zip fstRow $ map Just initialSpace1D)
where emptySpace = initSpace (steps, length initialSpace1D) (const $ Nothing)
fstRow = zip (repeat 0) [0..length initialSpace1D - 1]
make1DRule :: Int -> ([a] -> a) -> Rule (Maybe a)
make1DRule radius rule1D = Rule
{ ruleNeighborhoodDeltas = zip (repeat $ -1) [-radius..radius]
, ruleFunction = \self maybeNeighborhood -> case self of
Just state -> return (Just state)
Nothing -> case sequence maybeNeighborhood of
Just neighborhood -> return $ Just $ rule1D neighborhood
Nothing -> return Nothing
}
instance Cell a => Cell (Maybe a) where
getColor (Just s) = getColor s
getColor Nothing = grey
getSuccState = fmap getSuccState
elementaryCellularAutomata :: Int -> Rule (Maybe Bool)
elementaryCellularAutomata ruleNumber = make1DRule 1 (\[l, c, r] ->
0 /= (ruleNumber .&. (shiftL 1 (4 * boolToInt l + 2 * boolToInt c + boolToInt r))))
where boolToInt True = 1
boolToInt False = 0
singleCell :: Int -> [Bool]
singleCell size = map isMidpoint [1..size]
where isMidpoint = (== div size 2)
main :: IO ()
main = runCellularAutomata2D (elementaryCellularAutomata 110) (initSpace1D 100 $ singleCell 100) >> return ()
| orion-42/cellular-automata-2d | OneDim.hs | mit | 1,448 | 0 | 18 | 333 | 535 | 273 | 262 | 30 | 3 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings, RecordWildCards #-}
module Main (main) where
import qualified Prelude.Compat as Prelude
import Prelude.Compat hiding (FilePath, show)
import qualified Buildsome
import Buildsome (Buildsome)
import qualified Buildsome.Chart as Chart
import qualified Buildsome.ClangCommands as ClangCommands
import qualified Buildsome.Color as Color
import qualified Buildsome.CompatMakefile as CompatMakefile
import Buildsome.Db (Db, Reason)
import qualified Buildsome.MemoParseMakefile as MemoParseMakefile
import Buildsome.Opts (Opts(..), Opt(..))
import qualified Buildsome.Opts as Opts
import qualified Control.Exception as E
import Control.Monad (unless, forM_)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS8
import Data.List (foldl')
import qualified Data.Map as M
import Data.Maybe (mapMaybe)
import Data.Monoid
import Data.String (IsString(..))
import Data.Typeable (Typeable)
import GHC.Conc (setNumCapabilities, getNumProcessors)
import Lib.ByteString (unprefixed)
import Lib.ColorText (ColorText)
import qualified Lib.ColorText as ColorText
import Lib.Directory (getMFileStatus)
import Lib.FilePath (FilePath, (</>))
import qualified Lib.FilePath as FilePath
import Lib.Makefile (Makefile)
import qualified Lib.Makefile as Makefile
import Lib.Printer (Printer)
import qualified Lib.Printer as Printer
import Lib.ScanFileUpwards (scanFileUpwards)
import Lib.Show (show)
import Lib.TimeIt (timeIt)
import qualified Lib.Version as Version
import qualified System.IO as IO
import qualified System.Posix.ByteString as Posix
import System.Posix.IO (stdOutput)
import System.Posix.Terminal (queryTerminal)
standardMakeFilename :: FilePath
standardMakeFilename = "Buildsome.mk"
data SpecifiedInexistentMakefilePath =
SpecifiedInexistentMakefilePath (ColorText -> ByteString) FilePath
deriving (Typeable)
instance Show SpecifiedInexistentMakefilePath where
show (SpecifiedInexistentMakefilePath render path) =
BS8.unpack $ render $ cError $ mconcat
["Specified makefile path: ", cPath (show path), " does not exist"]
where
Color.Scheme{..} = Color.scheme
instance E.Exception SpecifiedInexistentMakefilePath
specifiedMakefile :: Printer -> FilePath -> IO FilePath
specifiedMakefile printer path = do
mStat <- getMFileStatus path
case mStat of
Nothing -> E.throwIO $ SpecifiedInexistentMakefilePath (Printer.render printer) path
Just stat
| Posix.isDirectory stat -> return $ path </> standardMakeFilename
| otherwise -> return path
data TargetsRequest = TargetsRequest
{ targetsRequestPaths :: [FilePath]
, targetsRequestReason :: Reason
, targetsRequestExtraOutputs :: Opts.ExtraOutputs
}
ntraverseTargetsRequest ::
Applicative f =>
([FilePath] -> f [FilePath]) ->
(Reason -> f Reason) ->
(Opts.ExtraOutputs -> f Opts.ExtraOutputs) ->
TargetsRequest -> f TargetsRequest
ntraverseTargetsRequest
onTargetPaths onReason onExtraOutputs
(TargetsRequest paths reason extraOutputs)
= TargetsRequest <$> onTargetPaths paths <*> onReason reason <*> onExtraOutputs extraOutputs
data Requested = RequestedClean | RequestedTargets TargetsRequest
traverseRequested ::
Applicative f => (TargetsRequest -> f TargetsRequest) -> Requested -> f Requested
traverseRequested _ RequestedClean = pure RequestedClean
traverseRequested f (RequestedTargets x) = RequestedTargets <$> f x
data BadCommandLine = BadCommandLine (ColorText -> ByteString) String deriving (Typeable)
instance E.Exception BadCommandLine
instance Show BadCommandLine where
show (BadCommandLine render msg) =
BS8.unpack $ render $ cError $ "Invalid command line options: " <> fromString msg
where
Color.Scheme{..} = Color.scheme
getRequestedTargets :: Printer -> Opts.ExtraOutputs -> [ByteString] -> IO Requested
getRequestedTargets _ _ ["clean"] = return RequestedClean
getRequestedTargets printer extraOutputs ts
| "clean" `elem` ts =
E.throwIO $
BadCommandLine (Printer.render printer) "Clean must be requested exclusively"
| otherwise =
return $ RequestedTargets TargetsRequest
{ targetsRequestPaths = requestPaths
, targetsRequestReason = reason
, targetsRequestExtraOutputs = extraOutputs
}
where
(requestPaths, reason) = case ts of
[] -> (["default"], "implicit 'default' target" :: ColorText)
_ -> (ts, "explicit request from cmdline")
setBuffering :: IO ()
setBuffering = do
IO.hSetBuffering IO.stdout IO.LineBuffering
IO.hSetBuffering IO.stderr IO.LineBuffering
switchDirectory :: FilePath -> IO (FilePath, FilePath)
switchDirectory makefilePath = do
origCwd <- Posix.getWorkingDirectory
unless (BS8.null cwd) $ do
Posix.changeWorkingDirectory cwd
fullCwd <- FilePath.canonicalizePath $ origCwd </> cwd
BS8.putStrLn $ "make: Entering directory `" <> fullCwd <> "'"
return (origCwd, file)
where
(cwd, file) = FilePath.splitFileName makefilePath
parseMakefile :: Printer -> Db -> FilePath -> FilePath -> Makefile.Vars -> IO Makefile
parseMakefile printer db origMakefilePath finalMakefilePath vars = do
cwd <- Posix.getWorkingDirectory
let absFinalMakefilePath = cwd </> finalMakefilePath
(parseTime, (isHit, makefile)) <- timeIt $ do
(isHit, rawMakefile) <- MemoParseMakefile.memoParse db absFinalMakefilePath vars
makefile <- Makefile.onMakefilePaths FilePath.canonicalizePathAsRelative rawMakefile
Makefile.verifyPhonies makefile
return (isHit, makefile)
let msg =
case isHit of
MemoParseMakefile.Hit -> "Got makefile from cache: "
MemoParseMakefile.Miss -> "Parsed makefile: "
Printer.rawPrintStrLn printer $ mconcat
[ msg, cPath (show origMakefilePath)
, " (took ", cTiming (show parseTime <> "sec"), ")"]
return makefile
where
Color.Scheme{..} = Color.scheme
data MakefileScanFailed = MakefileScanFailed (ColorText -> ByteString) deriving (Typeable)
instance E.Exception MakefileScanFailed
instance Show MakefileScanFailed where
show (MakefileScanFailed render) =
BS8.unpack $ render $ cError $ mconcat
[ "ERROR: Cannot find a file named "
, cPath (show standardMakeFilename)
, " in this directory or any of its parents"
]
where
Color.Scheme{..} = Color.scheme
-- TODO: Extract the --enable/disable colors outside of the
-- version/etc separation.
getColorRender :: Opts -> IO (ColorText -> ByteString)
getColorRender GetVersion = return ColorText.stripColors
getColorRender (Opts opt) =
case optColor opt of
Opts.ColorDisable -> return ColorText.stripColors
Opts.ColorEnable -> return ColorText.render
Opts.ColorDefault -> do
isTty <- queryTerminal stdOutput
return $
if isTty
then ColorText.render
else ColorText.stripColors
flagPrefix :: ByteString
flagPrefix = "FLAG_"
optVars :: Opt -> Makefile.Vars
optVars opt = M.fromList $ withs ++ withouts
where
asVars val = map $ \name -> (flagPrefix <> name, val)
withs = asVars "enable" $ optWiths opt
withouts = asVars "disable" $ optWithouts opt
flagsOfVars :: Makefile.Vars -> Makefile.Vars
flagsOfVars = M.fromList . mapMaybe filterFlag . M.toList
where
filterFlag (key, value) =
fmap (flip (,) value) $ unprefixed flagPrefix key
ljust :: Int -> ByteString -> ByteString
ljust padding bs = bs <> BS8.replicate (padding - l) ' '
where
l = BS8.length bs
showHelpFlags :: Makefile.Vars -> IO ()
showHelpFlags flags = do
BS8.putStrLn "Available flags:"
-- TODO: Colors (depends on --enable/disbale color being outside)
let varNameWidth = 1 + (foldl' max 0 . map BS8.length . M.keys) flags
forM_ (M.toList flags) $ \(varName, defaultVal) ->
BS8.putStrLn $ mconcat
[" ", ljust varNameWidth varName, "(default = ", show defaultVal, ")"]
verifyValidFlags :: Makefile.Vars -> [ByteString] -> IO ()
verifyValidFlags validFlags userFlags
| null invalidUserFlags = return ()
| otherwise = fail $ "Given non-existent flags: " ++ show invalidUserFlags
where
invalidUserFlags = filter (`M.notMember` validFlags) userFlags
handleOpts ::
Printer -> Opts ->
(Db -> Opt -> Requested -> FilePath -> Makefile -> IO ()) -> IO ()
handleOpts printer GetVersion _ =
Printer.rawPrintStrLn printer $ "buildsome " <> Version.version
handleOpts printer (Opts opt) body = do
origMakefilePath <-
case optMakefilePath opt of
Nothing ->
maybe (E.throwIO (MakefileScanFailed (Printer.render printer))) return =<<
scanFileUpwards standardMakeFilename
Just path -> specifiedMakefile printer path
(origCwd, finalMakefilePath) <- switchDirectory origMakefilePath
let inOrigCwd =
FilePath.canonicalizePathAsRelative . (origCwd </>)
targetInOrigCwd =
FilePath.canonicalizePathAsRelative .
case optMakefilePath opt of
-- If we found the makefile by scanning upwards, prepend
-- original cwd to avoid losing it:
Nothing -> (origCwd </>)
-- Otherwise: there's no useful original cwd:
Just _ -> id
rawRequested <-
getRequestedTargets printer (optExtraOutputs opt) (optRequestedTargets opt)
requested <-
traverseRequested
(ntraverseTargetsRequest
(mapM targetInOrigCwd) -- <- on target paths
pure -- <- on reason
(Opts.extraOutputsAtFilePaths inOrigCwd) -- <- onExtraOutputs
) rawRequested
Buildsome.withDb finalMakefilePath $ \db -> do
makefile <-
parseMakefile printer db origMakefilePath finalMakefilePath (optVars opt)
let flags = flagsOfVars (Makefile.makefileWeakVars makefile)
if optHelpFlags opt
then showHelpFlags flags
else do
verifyValidFlags flags (optWiths opt ++ optWithouts opt)
body db opt requested finalMakefilePath makefile
handleRequested :: Buildsome -> Printer -> Requested -> IO ()
handleRequested buildsome printer RequestedClean = Buildsome.clean printer buildsome
handleRequested
buildsome printer
(RequestedTargets
(TargetsRequest requestedTargetPaths reason
(Opts.ExtraOutputs mChartPath mClangCommandsPath compatMakefile)))
= do
Buildsome.BuiltTargets rootTargets slaveStats <-
Buildsome.want printer buildsome reason requestedTargetPaths
maybe (return ()) (Chart.make slaveStats) mChartPath
cwd <- Posix.getWorkingDirectory
maybe (return ()) (ClangCommands.make cwd slaveStats rootTargets) mClangCommandsPath
case compatMakefile of
Opts.NoCompatMakefile -> return ()
Opts.CompatMakefile ->
CompatMakefile.make (Buildsome.bsPhoniesSet buildsome) cwd slaveStats rootTargets "compat-makefile"
main :: IO ()
main = do
setBuffering
setNumCapabilities =<< getNumProcessors
opts <- Opts.get
render <- getColorRender opts
printer <- Printer.new render $ Printer.Id 0
handleOpts printer opts $
\db opt requested finalMakefilePath makefile -> do
Buildsome.with printer db finalMakefilePath makefile opt $ \buildsome ->
handleRequested buildsome printer requested
| da-x/buildsome | src/Main.hs | gpl-2.0 | 11,298 | 0 | 19 | 2,189 | 2,987 | 1,548 | 1,439 | 246 | 4 |
-- MutationCount Module
-- By G.W. Schwartz
-- Collects all functions pertaining to the counting of mutations called
-- from Main
module MutationCount where
-- Built in
import Data.List
import Data.Char
import Data.Maybe
import qualified Data.Map as M
-- Local
import Types
import Mutation
-- Join together mutation lists into a MutationMap
joinMutations :: [[(Position, Mutation)]] -> MutationMap
joinMutations = groupedMutations
where
groupedMutations = M.fromListWith (++) . map (\(x, y) -> (x, [y])) . concat
-- Generate a CloneMutMap which will then be printed to save files
generateCloneMutMap :: CloneMap -> CloneMutMap
generateCloneMutMap = M.mapWithKey gatherMutations
where
gatherMutations k xs = joinMutations . map (countMutations (snd k)) $ xs
-- Generate the position to clone map that is separated by clones
generatePositionCloneMap :: CloneMutMap -> PositionCloneMap
generatePositionCloneMap = joinSilentMutations
. M.map (M.map (wrapClone . realCodon))
where
joinSilentMutations = M.unionsWith (++) . map snd . M.toAscList
wrapClone xs = [xs]
realCodon = filterMutStab (\_ -> True)
-- Return the results of the mutation or stable counts as a string
printMutCounts :: String
-> MutationType
-> Bias
-> Bool
-> CodonMut
-> MutCount
-> MutationMap
-> PositionCloneMap
-> String
printMutCounts label
mutType
bias
fourBool
codonMut
mutCount
mutationMap
mutTypeMap = header ++ body
where
header = "label,position,count,weight\n"
body = unlines
. map mapLine
. M.toAscList
$ mutationMap
mapLine (x, xs) = label
++ ","
++ show x
++ ","
++ (show . trueMutCount x $ mutTypeMap)
++ ","
++ (show . length . filterMutStab (\_ -> True) $ xs)
trueMutCount p = uniqueSynonymous mutType bias fourBool codonMut mutCount
. fromMaybe [[]]
. M.lookup p
| GregorySchwartz/count-mutations | src/MutationCount.hs | gpl-2.0 | 2,308 | 0 | 13 | 820 | 476 | 260 | 216 | 51 | 1 |
{-# LANGUAGE ParallelListComp #-}
module Examples.Primitives.Cylinders where
import Primitives.Cylindrical(cylinderSolidNoSlopeSquaredOff, cylinderSolidNoSlope, cylinderWallsNoSlopeSquaredOff,
cylinderSolidNoSlopeLengthenY, cylinderSolidNoSlopeSquaredOffLengthenY, cylinderWallsNoSlopeSquaredOffLengthenY)
import Primitives.Cylindrical(cylinderWallsNoSlope)
import CornerPoints.Radius(Radius(..))
import CornerPoints.Points(Point(..))
import Stl.StlCornerPoints((|+++^|), (||+++^||), Faces(..))
import Stl.StlBase (StlShape(..), newStlShape)
import Stl.StlFileWriter(writeStlToFile)
import CornerPoints.Create(Angle(..))
import CornerPoints.Transpose(transposeY)
angles = (map (Angle) [0,10..360])
solidCylinderSquared =
let cylinder = cylinderSolidNoSlopeSquaredOff (Radius 10) (Point 0 0 0) angles (10 :: Height) (30 :: Power)
cylinderTriangles = [FacesBackBottomFrontTop | x <- [1..35]]
|+++^|
cylinder
cylinderStl = newStlShape "cylinder" cylinderTriangles
in writeStlToFile cylinderStl
solidCylinderLengthenY =
--cylinderSolidNoSlopeLengthenY :: Radius -> Origin -> [Angle] -> Height -> LengthenFactor -> [CornerPoints]
let cylinder = cylinderSolidNoSlopeLengthenY (Radius 10) (Point 0 0 0) angles (10 :: Height) (10 :: LengthenFactor)
cylinderTriangles = [FacesBackBottomFrontTop | x <- [1..36]]
|+++^|
cylinder
cylinderStl = newStlShape "cylinder" cylinderTriangles
in writeStlToFile cylinderStl
solidCylinderSquaredOffLengthenY =
--cylinderSolidNoSlopeLengthenY :: Radius -> Origin -> [Angle] -> Height -> LengthenFactor -> [CornerPoints]
let cylinder = cylinderSolidNoSlopeSquaredOffLengthenY (Radius 10) (Point 0 0 0) angles (10 :: Height) (10 :: Power) (10::LengthenFactor)
cylinderTriangles = [FacesBackBottomFrontTop | x <- [1..36]]
|+++^|
cylinder
cylinderStl = newStlShape "cylinder" cylinderTriangles
in writeStlToFile cylinderStl
walledCylinderSquared =
let cylinder = cylinderWallsNoSlopeSquaredOff (Radius 100) (Point 0 0 0) angles (10 :: Height) (10::Thickness) (10 :: Power)
--cylinderWallsNoSlope :: Radius -> Thickness -> Origin -> [Angle] -> Height -> [CornerPoints]
cylinderTriangles = FacesBackBottomFront : [FacesBackBottomFrontTop | x <- [1..]]
|+++^|
cylinder
cylinderStl = newStlShape "cylinder" cylinderTriangles
in writeStlToFile cylinderStl
--cylinderWallsNoSlopeSquaredOffLengthenY :: Radius -> Origin -> [Angle] -> Height -> Thickness -> Power -> LengthenFactor -> [CornerPoints]
walledCylinderSquaredLengthenY =
let cylinder = cylinderWallsNoSlopeSquaredOffLengthenY (Radius 10) (Point 0 0 0) angles (10 :: Height) (10::Thickness) (10 :: Power) (10::LengthenFactor)
--cylinderWallsNoSlope :: Radius -> Thickness -> Origin -> [Angle] -> Height -> [CornerPoints]
cylinderTriangles = [FacesBackBottomFrontTop | x <- [1..]]
|+++^|
cylinder
cylinderStl = newStlShape "cylinder" cylinderTriangles
in writeStlToFile cylinderStl
walledCylinder =
let cylinder = cylinderWallsNoSlope (Radius 100) (10::Thickness) (Point 0 0 0) angles (10 :: Height)
cylinderTriangles = [FacesBackBottomFrontTop | x <- [1..35]]
|+++^|
cylinder
cylinderStl = newStlShape "cylinder" cylinderTriangles
in writeStlToFile cylinderStl
type Power = Double
type Height = Double
type Thickness = Double
type LengthenFactor = Double
| heathweiss/Tricad | src/Examples/Primitives/Cylinders.hs | gpl-2.0 | 3,677 | 0 | 14 | 790 | 789 | 444 | 345 | 59 | 1 |
{-# LANGUAGE GADTs, GeneralizedNewtypeDeriving #-}
module React where
import Control.Applicative
import Control.Monad.State
import Control.Monad.Writer hiding (listen)
import Data.IORef
import Data.Unique
import Data.Functor
import qualified Data.IntSet as IS
import qualified Data.Map as M
import qualified Data.Set as S
import System.Mem.Weak
import System.IO.Unsafe
type React = IO
newtype Moment a = Moment { runMoment:: StateT (S.Set Unique) (WriterT ([IO ()], [IO()]) IO) a }
deriving (Monad, Applicative, Functor, MonadState (S.Set Unique), MonadWriter ([IO ()], [IO ()]), MonadIO, MonadFix)
data Event a = Event { _eventRegisterListener :: (a -> Moment ()) -> IO (IO ()) }
data Behavior a = Behavior { _behaviorUpdates :: Event (), _behaviorGetValue :: Moment a }
instance Monoid (Event a) where
mempty = never
mappend = merge
instance Functor Event where
fmap f eb = Event { _eventRegisterListener = \listener -> _eventRegisterListener eb (listener . f) }
instance Functor Behavior where
fmap f x = pure f <*> x
instance Applicative Behavior where
pure a = Behavior { _behaviorUpdates = mempty
, _behaviorGetValue = return a }
bab <*> ba = Behavior { _behaviorUpdates = _behaviorUpdates bab <> _behaviorUpdates ba
, _behaviorGetValue = do ab <- _behaviorGetValue bab
a <- _behaviorGetValue ba
return (ab a) }
newEventRegistration :: React ((a -> Moment ()) -> IO (IO ()), a -> Moment ())
newEventRegistration = do listeners <- newIORef M.empty
let registerListener listener = do listenerKey <- newUnique
modifyIORef listeners $ M.insert listenerKey listener
return (modifyIORef listeners $ M.delete listenerKey)
propagateListeners x = do listeners' <- M.elems <$> liftIO (readIORef listeners)
mapM_ ($ x) listeners'
return (registerListener, propagateListeners)
newEvent :: React (Event a, a -> Moment ())
newEvent = do (registerListener, propagateListeners) <- newEventRegistration
return (Event registerListener, propagateListeners)
react :: React a -> Moment a
react = liftIO
never :: Event a
never = Event (\_ -> return (return ()))
merge :: Event a -> Event a -> Event a
merge a b = Event (\listener -> do
unregisterA <- _eventRegisterListener a listener
unregisterB <- _eventRegisterListener b listener
return (unregisterA >> unregisterB))
switchE :: Behavior (Event a) -> Event a
switchE be = Event (\listener ->
do eInitial <- sync $ sample be
unregisterV <- newIORef (return ())
unregisterListener <- _eventRegisterListener eInitial listener
let switchToNewEvent =
do readIORef unregisterV >>= id
eNext <- sync $ sample be
unregisterListener' <- _eventRegisterListener eNext listener
writeIORef unregisterV unregisterListener'
unregisterBehaviorListener <- _eventRegisterListener (_behaviorUpdates be) (\() -> tell ([], [switchToNewEvent]))
writeIORef unregisterV unregisterListener
return (readIORef unregisterV >>= id >> unregisterBehaviorListener))
execute :: Event (Moment a) -> React (Event a)
execute ema = do (registerListener, propagateListeners) <- newEventRegistration
unregisterListener <- _eventRegisterListener ema (\ma -> ma >>= propagateListeners)
addFinalizer ema unregisterListener
return (Event registerListener)
updates :: Behavior a -> React (Event a)
updates ba = do (registerListener, propagateListener) <- newEventRegistration
let propagate = sync (sample ba >>= propagateListener)
unregisterListener <- _eventRegisterListener (_behaviorUpdates ba) (\() -> tell ([], [propagate]))
addFinalizer (_behaviorUpdates ba) unregisterListener
return (Event registerListener)
(<@) :: Behavior a -> Event b -> Event a
ba <@ eb = Event (\listener -> _eventRegisterListener eb $ \_ -> sample ba >>= listener)
switch :: Behavior (Behavior a) -> Behavior a
switch bb = Behavior { _behaviorUpdates = switchE (_behaviorUpdates <$> bb)
, _behaviorGetValue = sample bb >>= sample }
accum :: a -> Event (a -> a) -> React (Event a)
accum initial updaters =
do cell <- newIORef initial
(registerListener, propagateListeners) <- newEventRegistration
let evt = Event registerListener
unregisterEventListener <- _eventRegisterListener updaters $ \updater ->
do liftIO (modifyIORef cell updater)
cellValue <- liftIO (readIORef cell)
propagateListeners cellValue
addFinalizer evt unregisterEventListener
return evt
accumB :: a -> Event (a -> a) -> React (Behavior a)
accumB initial updaters = do ea <- accum initial updaters
hold initial ea
sample :: Behavior a -> Moment a
sample = _behaviorGetValue
hold :: a -> Event a -> React (Behavior a)
hold initial updates = do cell <- newIORef initial
let behavior = Behavior { _behaviorUpdates = () <$ updates
, _behaviorGetValue = liftIO (readIORef cell) }
unregisterUpdates <- _eventRegisterListener updates (\x -> tell ([writeIORef cell x], []))
addFinalizer behavior unregisterUpdates
return behavior
calm :: Event a -> React (Event a)
calm evt = do key <- liftIO newUnique
let evt = Event $ \listener -> _eventRegisterListener evt (calmed listener)
calmed listener a =
do isMember <- S.member key <$> get
if isMember
then return () -- This listener has already run...
else do modify (S.insert key) -- Otherwise, mark that we have run, and run the listener
listener a
return evt
spill :: Event [a] -> Event a
spill eas = Event (\listener ->
_eventRegisterListener eas $
\as -> mapM_ listener as)
sync :: Moment a -> IO a
sync m = do (a, (updateHolds, afterActions)) <- runWriterT (evalStateT (runMoment m) S.empty)
sequence_ updateHolds
sequence_ afterActions
return a
listenToBehavior :: Behavior a -> (a -> Moment ()) -> IO (IO ())
listenToBehavior bb handle = do sync $ do initial <- sample bb
handle initial
listen (_behaviorUpdates bb) (\() -> let handle' = sync (sample bb >>= handle)
in tell ([],[handle']))
listen :: Event a -> (a -> Moment ()) -> IO (IO ())
listen = _eventRegisterListener
| tathougies/react.hs | src/React.hs | gpl-2.0 | 7,456 | 95 | 13 | 2,541 | 1,508 | 895 | 613 | 130 | 2 |
module ExportBasic(f, Listt((:>)) , Listt2(..), Listt3, listtest, Hello, (/**), mylist) where
f :: Int
f = 2
(/**) :: a -> Int -> Int
_ /** z = 2 * g * z -- 12 * z
where
g = 3 * k -- 6
where
k = 2
infixr 5 /**
data Listt a = a :> (Listt a) | Empt
mylist :: Listt a
mylist = Empt
data Listt2 a = a :>< (Listt2 a) | Empty
data Listt3 a = a :>>< (Listt3 a) | Emptyy
listtest :: Listt3 a
listtest = Emptyy
type Hello = Bool | Helium4Haskell/helium | test/exports/ExportBasic.hs | gpl-3.0 | 448 | 0 | 8 | 128 | 206 | 123 | 83 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude, FlexibleContexts, RecordWildCards, OverloadedStrings, TypeFamilies #-}
module Lamdu.GUI.ExpressionEdit.HoleEdit.SearchArea
( makeStdWrapped
) where
import Control.Lens.Operators
import qualified Graphics.UI.Bottle.EventMap as E
import qualified Graphics.UI.Bottle.Widgets.FocusDelegator as FocusDelegator
import qualified Graphics.UI.Bottle.Widgets.Layout as Layout
import qualified Graphics.UI.Bottle.WidgetsEnvT as WE
import qualified Lamdu.Config as Config
import Lamdu.GUI.ExpressionEdit.HoleEdit.Info (HoleInfo(..))
import Lamdu.GUI.ExpressionEdit.HoleEdit.Open (makeOpenSearchTermGui)
import qualified Lamdu.GUI.ExpressionEdit.HoleEdit.SearchTerm as SearchTerm
import Lamdu.GUI.ExpressionEdit.HoleEdit.WidgetIds (WidgetIds(..))
import Lamdu.GUI.ExpressionGui (ExpressionGui)
import qualified Lamdu.GUI.ExpressionGui as ExpressionGui
import Lamdu.GUI.ExpressionGui.Monad (ExprGuiM)
import qualified Lamdu.GUI.ExpressionGui.Monad as ExprGuiM
import qualified Lamdu.GUI.ExpressionGui.Types as ExprGuiT
import qualified Lamdu.Sugar.Types as Sugar
import Prelude.Compat
fdConfig :: Config.Hole -> FocusDelegator.Config
fdConfig Config.Hole{..} = FocusDelegator.Config
{ FocusDelegator.focusChildKeys = holeOpenKeys
, FocusDelegator.focusChildDoc = E.Doc ["Navigation", "Hole", "Open"]
, FocusDelegator.focusParentKeys = holeCloseKeys
, FocusDelegator.focusParentDoc = E.Doc ["Navigation", "Hole", "Close"]
}
-- Has an ExpressionGui.stdWrap/typeView under the search term
makeStdWrapped ::
Monad m =>
Sugar.Payload m ExprGuiT.Payload -> HoleInfo m -> ExprGuiM m (ExpressionGui m)
makeStdWrapped pl holeInfo =
do
config <- ExprGuiM.readConfig
let Config.Hole{..} = Config.hole config
WidgetIds{..} = hiIds holeInfo
fdWrap =
ExpressionGui.makeFocusDelegator (fdConfig (Config.hole config))
FocusDelegator.FocusEntryChild hidClosedSearchArea
closedSearchTermGui <-
fdWrap <*> SearchTerm.make holeInfo & ExpressionGui.stdWrap pl
isSelected <- ExprGuiM.widgetEnv $ WE.isSubCursor hidOpen
if isSelected
then -- ideally the fdWrap would be "inside" the
-- type-view addition and stdWrap, but it's not
-- important in the case the FD is selected, and
-- it is harder to implement, so just wrap it
-- here
fdWrap <*> makeOpenSearchTermGui pl holeInfo
<&> (`Layout.hoverInPlaceOf` closedSearchTermGui)
else return closedSearchTermGui
| da-x/lamdu | Lamdu/GUI/ExpressionEdit/HoleEdit/SearchArea.hs | gpl-3.0 | 2,704 | 0 | 15 | 579 | 502 | 303 | 199 | 44 | 2 |
module Export.Compress where
--------------------------------------------------------------------------------
-- AGGREGATION UTILS
--------------------------------------------------------------------------------
compressOutput :: [(Double, (Int, Int, Int))] -> [(Double, (Int, Int, Int))]
compressOutput = foldr compressOutputAux []
where
compressOutputAux :: (Double, (Int, Int, Int))
-> [(Double, (Int, Int, Int))]
-> [(Double, (Int, Int, Int))]
compressOutputAux ts [] = [ts]
compressOutputAux (t, s) ((t', s') : acc)
| t == t' = (t, s) : acc
| otherwise = (t, s) : (t', s') : acc | thalerjonathan/phd | thesis/code/sir/src/Export/Compress.hs | gpl-3.0 | 657 | 0 | 11 | 145 | 225 | 135 | 90 | 10 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Language.Haskell.TH.Utils.Unroll where
import Language.Haskell.TH
import Data.Set (member)
import Language.Haskell.TH.Utils.Defines
import Language.Haskell.TH.Utils.Substitute
import Language.Haskell.TH.Utils.Simplify
-- | Substitute a function application
-- Argument must be a literal only then it will be substituted
-- Very similar to substitute with only one difference in AppE line
-- @TODO think of a way to combine this and substitute
class SubstituteFun a where
substituteFun :: Name -> (Name -> Lit -> Exp) -> a -> a
substituteFun_list :: Name -> (Name -> Lit -> Exp) -> [a] -> [a]
substituteFun_list n l = map (substituteFun n l)
instance SubstituteFun a => SubstituteFun [a] where
substituteFun = substituteFun_list
instance SubstituteFun Exp where
substituteFun n l (AppE (VarE v) (LitE lit)) | v == n = l v lit
substituteFun n l (AppE e1 e2) = AppE (substituteFun n l e1)
(substituteFun n l e2)
substituteFun n l (InfixE me1 e me2) = InfixE (fmap (substituteFun n l) me1)
(substituteFun n l e)
(fmap (substituteFun n l) me2)
substituteFun n l (UInfixE e1 e e2) = UInfixE (substituteFun n l e1)
(substituteFun n l e)
(substituteFun n l e2)
substituteFun n l (ParensE e) = ParensE (substituteFun n l e)
substituteFun n l (LamE pat e) | member n (defines pat) = LamE pat e
| otherwise = LamE pat (substituteFun n l e)
substituteFun n l (LamCaseE m) = LamCaseE (substituteFun n l m)
substituteFun n l (TupE es) = TupE (substituteFun n l es)
substituteFun n l (UnboxedTupE es) = UnboxedTupE (substituteFun n l es)
substituteFun n l (CondE e1 e2 e3) = CondE (substituteFun n l e1)
(substituteFun n l e2)
(substituteFun n l e3)
substituteFun n l (MultiIfE ges) = MultiIfE $
map (\(g,e) -> ( substituteFun n l g
, substituteFun n l e)) ges
substituteFun n l (LetE decs expr) | member n (defines decs) = LetE decs expr
| otherwise = LetE (substituteFun n l decs)
(substituteFun n l expr)
substituteFun n l (CaseE expr m) =
CaseE (substituteFun n l expr) (substituteFun n l m)
substituteFun n l (DoE ss) = DoE (substituteFun n l ss)
substituteFun n l (CompE ss) = CompE (substituteFun n l ss)
substituteFun n l (ArithSeqE as) = ArithSeqE (substituteFun n l as)
substituteFun n l (ListE es) = ListE (map (substituteFun n l) es)
substituteFun n l (SigE e t) = SigE (substituteFun n l e) t
substituteFun n l (RecConE name fexps) =
RecConE name (map (\(a,b) -> (a,substituteFun n l b)) fexps)
substituteFun n l (RecUpdE expr fexps) =
RecUpdE (substituteFun n l expr) $
map (\(a,b) -> (a,substituteFun n l b)) fexps
substituteFun _ _ a = a
instance SubstituteFun Match where
substituteFun n l m@(Match p b decs) | member n (defines p) = m
| member n (defines decs) = m
| otherwise = Match p
(substituteFun n l b)
(substituteFun n l decs)
instance SubstituteFun Body where
substituteFun n l (GuardedB gexp) =
GuardedB $ map (\(g,e) -> (substituteFun n l g,substituteFun n l e)) gexp
substituteFun n l (NormalB expr) = NormalB (substituteFun n l expr)
instance SubstituteFun Guard where
substituteFun n l (NormalG expr) = NormalG (substituteFun n l expr)
substituteFun n l (PatG s) = PatG (substituteFun n l s)
instance SubstituteFun Stmt where
substituteFun n l (BindS p e) | member n (defines p) = BindS p e
| otherwise = BindS p (substituteFun n l e)
substituteFun n l (LetS decs) = LetS (substituteFun n l decs)
substituteFun n l (NoBindS e) = NoBindS (substituteFun n l e)
substituteFun n l (ParS e) = ParS (substituteFun n l e)
instance SubstituteFun Dec where
substituteFun n _ d | member n (defines d) = d
substituteFun n l (FunD f c) = FunD f (substituteFun n l c)
substituteFun n l (ValD p b d) =
ValD p (substituteFun n l b) (substituteFun n l d)
substituteFun n l (ClassD cntxt c ty fd d) =
ClassD cntxt c ty fd (substituteFun n l d)
substituteFun n l (InstanceD cntxt ty d) =
InstanceD cntxt ty (substituteFun n l d)
substituteFun _ _ d = d
substituteFun_list n l decs | member n (defines decs) = decs
| otherwise = map (substituteFun n l) decs
instance SubstituteFun Clause where
substituteFun n l c@(Clause pat body decs) | member n (defines pat) = c
| member n (defines decs) = c
| otherwise = Clause pat
(substituteFun n l body)
(substituteFun n l decs)
instance SubstituteFun Range where
substituteFun n l (FromR e) = FromR (substituteFun n l e)
substituteFun n l (FromThenR e1 e2) = FromThenR (substituteFun n l e1)
(substituteFun n l e2)
substituteFun n l (FromToR e1 e2) = FromToR (substituteFun n l e1)
(substituteFun n l e2)
substituteFun n l (FromThenToR e1 e2 e3) = FromThenToR (substituteFun n l e1)
(substituteFun n l e2)
(substituteFun n l e3)
-- | unroll the recursion bottom up
-- example
-- @unrollB 0 1 [d| f i = 1 |]@
-- @unrollB 2 5 [d| f i = f (i-1) + f (i-2) |]@ will produce
-- f_0 = 1
-- f_1 = 1
-- f_2 = 2
-- f_3 = 3
-- f_4 = 5
-- f_5 = 8
--
unrollB :: Int -- ^ Lower bound
-> Int -- ^ Upper bound
-> DecQ -- ^ Recursive function body to unroll
-> DecsQ
unrollB from to d = do
(FunD f [(Clause ps body decs)]) <- d
let (VarP loopVar) = head ps
return $ map (createFun f loopVar body decs) [from .. to]
where
createFun f loopVar body decs i = let fname = nameBase f in
substituteFun f (\a (IntegerL b) ->
VarE $ mkName $ nameBase a ++ "_" ++ show b )
(simplify $ ValD (VarP $ mkName (fname ++ "_" ++ show i))
(substitute loopVar (LitE $ integerL $ fromIntegral i) body)
(substitute loopVar (LitE $ integerL $ fromIntegral i) decs)) | satvikc/THUtils | Language/Haskell/TH/Utils/Unroll.hs | gpl-3.0 | 6,916 | 0 | 18 | 2,499 | 2,426 | 1,205 | 1,221 | 111 | 1 |
-----------------------------------------------------------------------------
--
-- Module : Text.Syntax.Math
-- Copyright : John Morrice <spoon@killersmurf.com>
-- License : GPL-3
--
-- Maintainer : John Morrice <spoon@killersmurf.com>
-- Stability :
-- Portability :
--
-- | Provide mathematical and logic symbols for snm
--
-----------------------------------------------------------------------------
module Text.Syntax.Math where
import Text.Syntax.Simple
import Data.Dynamic
import Text.XHtml.Strict
import Data.Either
-- | Highlight mathematical symbols
math :: Dynamic
math = highlight "snmmath:Text.Syntax.Math.math" syms
m :: String -> String -> (String, String, String)
m sym out = (sym, "math_symbol", out)
html_sym :: Char -> String
html_sym c =
if int_c > 255
then "&#" ++ show int_c ++ ";"
else
[c]
where
int_c = fromEnum c
-- | Output a string to copy-paste into the snm documentation for this plugin
doc_syms :: String
doc_syms = unlines (map doc_sym inputs)
where
doc_sym inp = " \\n" ++ inp ++ spaces inp ++ "{language " ++ inp ++ " math}"
max = maximum $ map length inputs
spaces i = replicate (5 + max - length i) ' '
inputs = map (\(i, _, _) -> i) syms
syms :: [(String, String, String)]
syms = map (\(inp, cls, out) -> (inp, cls, concatMap html_sym out)) $
[ m "forall" "∀"
, m "unique" "∃!"
, m "forsome" "∃"
, m "member" "∈"
, m "!member" "∉"
, m "subset" "⊆"
, m "ssubset" "⊂"
, m "superset" "⊇"
, m "ssuperset" "⊃"
, m "union" "∪"
, m "intersection" "∩"
, m "implies" "⇒"
, m "derives" "⊢"
, m "=>" "⇒"
, m "->" "→"
, m "|->" "↦"
, m "therefore" "∴"
, m "because" "∵"
, m "{}" "∅"
, m "empty" "∅"
, m "root" "√"
, m "!=" "≠"
, m ">=" "≥"
, m "<=" "≤"
, m "orthogonal" "⊥"
, m "or" "∨"
, m "xor" "⊕"
, m "(+)" "⊕"
, m "and" "∧"
, m "iff" "⇔"
, m "<=>" "⇔"
, m "top" "⊤"
, m "bottom" "⊥"
, m "coprime" "⊥"
, m "*" "·"
, m "<<" "≪"
, m ">>" "≫"
, m "karp" "≺"
, m "varies" "∝"
, m "o<" "∝"
, m "/" "÷"
, m "+-" "±"
, m "-+" "∓"
, m "!|" "∤"
, m "aleph" "ℵ"
, m "beth" "ℶ"
, m "approx" "≈"
, m "wreath" "≀"
, m "ideal" "◅"
, m "antijoin" "▻"
, m "semidirect_product" "⋉"
, m "semijoin" "⋊"
, m "natural_join" "⋈"
, m "|><|" "⋈"
, m "|><" "⋉"
, m "><|" "⋊"
, m "<|" "◅"
, m "|>" "▻"
, m "qed" "∎"
, m "congruent" "≅"
, m "(.)" "∘"
, m "infinity" "∞"
, m "sum" "∑"
, m "product" "∏"
, m "coproduct" "∐"
, m "integral" "∫"
, m "contour_integral" "∮"
, m "gradient" "∇"
, m "@" "∂"
, m "delta" "Δ"
, m "dirac" "δ"
, m "projection" "π"
, m "pi" "π"
, m "O~" "σ"
, m "selection" "σ"
, m "transpose" "†"
, m "entails" "⊧"
, m "|=" "⊧"
, m "(x)" "⊗"
, m "tensor_product" "⊗"
, m "(*)" "*"
]
| elginer/snm_math | Text/Syntax/Math.hs | gpl-3.0 | 3,090 | 0 | 11 | 853 | 983 | 517 | 466 | 104 | 2 |
module CombinerSpec (spec) where
import Data.Function.Extra (never)
import Test.Hspec
import Language.Mulang
import Language.Mulang.Inspector.Smell
import Language.Mulang.Parsers.Haskell
import Language.Mulang.Parsers.JavaScript
spec :: Spec
spec = do
describe "detect" $ do
it "can detect inspections" $ do
let code = hs "x = if True then True else False\n\
\y = 2\n\
\z = if True then True else False"
detect usesIf code `shouldBe` ["x", "z"]
it "can detect inspections at top level" $ do
detect doesConsolePrint (js "console.log(hello)") `shouldBe` []
describe "locate" $ do
it "can locate nested inspections" $ do
let code = hs "x = if True then True else False\n\
\y = 2\n\
\z = if True then True else False"
locate usesIf code `shouldBe` Nested ["x", "z"]
it "can locate inspections at top level" $ do
locate doesConsolePrint (js "console.log(hello)") `shouldBe` TopLevel
it "fails when inspection is not present" $ do
locate usesWhile (js "hello") `shouldBe` Nowhere
describe "never" $ do
it "is False when inspection is true" $ do
never usesIf (hs "f x = g x") `shouldBe` True
it "is True when inspection is False" $ do
never (declares (named "f")) (hs "f x = g x") `shouldBe` False
describe "transitive" $ do
it "is True when inspection can be proven transitively to be True" $ do
transitive "f" usesIf (hs "f x = g x\n\
\g x = if c x then 2 else 3") `shouldBe` True
it "is True when inspection can be proven transitively to be True\
\in several steps" $ do
transitive "f" usesIf (hs "f x = g x\n\
\g x = m x\n\
\m x = if c x then 2 else 3") `shouldBe` True
it "is True when inspection can be proven transitively to be True\
\in recursive functions" $ do
transitive "f" usesIf (hs "f x = g x\n\
\g x = m x\n\
\m x = if f x then 2 else 3") `shouldBe` True
it "is False when inspection can be proven transitively to be False\
\in recursive functions" $ do
transitive "f" usesIf (hs "f x = g x\n\
\g x = m x\n\
\m x = f x") `shouldBe` False
it "is False when inspection can not be proven transitively to be True" $ do
transitive "f" usesIf (hs "f x = g x") `shouldBe` False
it "is False when inspection can be proven transitively to be False" $ do
transitive "f" usesIf (hs "f x = g x") `shouldBe` False
| mumuki/mulang | spec/CombinerSpec.hs | gpl-3.0 | 2,744 | 0 | 18 | 940 | 544 | 264 | 280 | 48 | 1 |
{-# Language OverloadedStrings #-}
module Language.UHIM.Japanese.TransformSpec where
import Control.Monad.IO.Class
import Data.Semigroup
import Data.Set (Set)
import qualified Data.Set as S
import Data.String
import qualified Data.Text.ICU.Collate as Col
import Language.UHIM.Japanese.Adjective (JaAdjConjugation(..))
import Language.UHIM.Japanese.Verb (JaVerbConjugation(..), isClassicalVerbConjugation)
import Language.UHIM.Japanese.Prim
import qualified Hedgehog as H
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Language.UHIM.Japanese.Transform
classicalAdjClasses :: Set JaAdjConjugation
classicalAdjClasses = S.fromList
[ JaAdjKu
, JaAdjSiku
, JaAdjZiku
, JaAdjNari
, JaAdjTari
]
modernAdjClasses :: Set JaAdjConjugation
modernAdjClasses = S.fromList
[ JaAdjI
, JaAdjSii
, JaAdjZii
, JaAdjNa
]
genAdjClass :: H.MonadGen m => m JaAdjConjugation
genAdjClass = Gen.element classes
where
classes = S.toList $ modernAdjClasses <> classicalAdjClasses
genAdjClasses :: H.MonadGen m => m [JaAdjConjugation]
genAdjClasses = Gen.list (Range.linear 1 10) genAdjClass
genVerbClass :: H.MonadGen m => m JaVerbConjugation
genVerbClass = JaVerbConjugation <$> genVar <*> genStem <*> genClass
where
genVar = Gen.element [minBound..]
genStem = Gen.element [minBound..]
genClass = Gen.element [minBound..]
genVerbClasses :: H.MonadGen m => m [JaVerbConjugation]
genVerbClasses = Gen.list (Range.linear 1 10) genVerbClass
hprop_default_adjConjugationSelector_chooses_classical_conjugations :: H.Property
hprop_default_adjConjugationSelector_chooses_classical_conjugations = H.property $ do
cs <- H.forAll genAdjClasses
case S.fromList cs `S.intersection` classicalAdjClasses of
ccs | S.null ccs -> H.success
ccs -> do
let c = adjConjugationSelector defaultConfig cs
H.annotateShow $ c
(c `elem` ccs) H.=== True
hprop_default_verbConjugationSelector_chooses_classical_conjugations :: H.Property
hprop_default_verbConjugationSelector_chooses_classical_conjugations = H.property $ do
cs <- H.forAll genVerbClasses
let ccs = filter isClassicalVerbConjugation cs
if null ccs
then H.success
else do
let c = verbConjugationSelector defaultConfig cs
H.annotateShow $ c
(c `elem` ccs) H.=== True
| na4zagin3/uhim-dict | test/Language/UHIM/Japanese/TransformSpec.hs | gpl-3.0 | 2,329 | 0 | 16 | 357 | 608 | 333 | 275 | 59 | 2 |
module Header (
withSpecHead,
headerOption,
headerVersion
)
where
import Data.List (isPrefixOf)
import SimpleCmd (removePrefix)
import FileUtils (assertFileNonEmpty)
withSpecHead :: FilePath -> ([String] -> IO a) -> IO a
withSpecHead spec act = do
assertFileNonEmpty spec
readFile spec >>= (act . headerWords)
where
headerWords :: String -> [String]
headerWords = words . head . lines
headerVersion :: [String] -> String
headerVersion headerwords =
let cblrpm = filter ("cabal-rpm-" `isPrefixOf`) headerwords
in case cblrpm of
[nv] -> removePrefix "cabal-rpm-" nv
_ -> "0.9.11"
headerOption :: String -> [String] -> Maybe String
headerOption opt headerwords =
if opt `elem` headerwords
then (Just . head . tail . dropWhile (/= opt)) headerwords
else Nothing
| juhp/cabal-rpm | src/Header.hs | gpl-3.0 | 821 | 0 | 10 | 173 | 264 | 143 | 121 | 24 | 2 |
{-# LANGUAGE NoMonomorphismRestriction, OverloadedStrings #-}
module Diagram (renderTable) where
import Diagrams.Prelude
import Diagrams.Backend.SVG.CmdLine
import Diagrams.Backend.SVG
import Data.List
import Data.List.Utils (replace)
import Data.List.Split (splitOn)
import Lucid (renderText)
import Data.Text.Lazy (unpack)
days :: [String]
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
times :: [String]
times = map (\x -> show x ++ ":00") ([8..12] ++ [1..8] :: [Int])
cell :: Diagram B
cell = rect 2 0.8
makeCell :: String -> Diagram B
makeCell s =
(font "Trebuchet MS" $ text s # fontSizeO 16 # fc white) <>
cell # fc (if null s then white else blue)
# lw none
header :: String -> Diagram B
header session = (hcat $ map makeHeaderCell $ session:days) # centerX === headerBorder
headerBorder :: Diagram B
headerBorder = hrule 12 # lw medium # lc pink
makeHeaderCell :: String -> Diagram B
makeHeaderCell s =
(font "Trebuchet MS" $ text s # fontSizeO 16) <>
cell # lw none
makeTimeCell :: String -> Diagram B
makeTimeCell s =
(font "Trebuchet MS" $ text s # fontSizeO 16) <>
cell # lw none
makeRow :: [String] -> Diagram B
makeRow (x:xs) = (# centerX) . hcat $
makeTimeCell x : vrule 0.8 # lw thin : map makeCell xs
rowBorder :: Diagram B
rowBorder = hrule 12 # lw thin # lc grey
makeTable :: [[String]] -> String -> Diagram B
makeTable s session = vcat $ (header session): intersperse rowBorder (map makeRow s)
renderTable :: String -> String -> String -> IO ()
renderTable filename courses session = do
let courseTable = partition5 $ splitOn "_" courses
print courseTable
let g = makeTable (zipWith (:) times courseTable) session
let svg = renderDia SVG (SVGOptions (mkWidth 600) Nothing "") g
let txt = replace "16.0em" "16.0px" $ unpack $ renderText svg
writeFile filename txt
where
partition5 [] = []
partition5 lst = take 5 lst : partition5 (drop 5 lst)
| cchens/courseography | hs/Diagram.hs | gpl-3.0 | 1,954 | 34 | 13 | 411 | 760 | 396 | 364 | 50 | 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.AndroidEnterprise.Enterprises.SetStoreLayout
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Sets the store layout for the enterprise. By default, storeLayoutType is
-- set to \"basic\" and the basic store layout is enabled. The basic layout
-- only contains apps approved by the admin, and that have been added to
-- the available product set for a user (using the setAvailableProductSet
-- call). Apps on the page are sorted in order of their product ID value.
-- If you create a custom store layout (by setting storeLayoutType =
-- \"custom\"), the basic store layout is disabled.
--
-- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.enterprises.setStoreLayout@.
module Network.Google.Resource.AndroidEnterprise.Enterprises.SetStoreLayout
(
-- * REST Resource
EnterprisesSetStoreLayoutResource
-- * Creating a Request
, enterprisesSetStoreLayout
, EnterprisesSetStoreLayout
-- * Request Lenses
, esslEnterpriseId
, esslPayload
) where
import Network.Google.AndroidEnterprise.Types
import Network.Google.Prelude
-- | A resource alias for @androidenterprise.enterprises.setStoreLayout@ method which the
-- 'EnterprisesSetStoreLayout' request conforms to.
type EnterprisesSetStoreLayoutResource =
"androidenterprise" :>
"v1" :>
"enterprises" :>
Capture "enterpriseId" Text :>
"storeLayout" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] StoreLayout :>
Put '[JSON] StoreLayout
-- | Sets the store layout for the enterprise. By default, storeLayoutType is
-- set to \"basic\" and the basic store layout is enabled. The basic layout
-- only contains apps approved by the admin, and that have been added to
-- the available product set for a user (using the setAvailableProductSet
-- call). Apps on the page are sorted in order of their product ID value.
-- If you create a custom store layout (by setting storeLayoutType =
-- \"custom\"), the basic store layout is disabled.
--
-- /See:/ 'enterprisesSetStoreLayout' smart constructor.
data EnterprisesSetStoreLayout = EnterprisesSetStoreLayout'
{ _esslEnterpriseId :: !Text
, _esslPayload :: !StoreLayout
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'EnterprisesSetStoreLayout' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'esslEnterpriseId'
--
-- * 'esslPayload'
enterprisesSetStoreLayout
:: Text -- ^ 'esslEnterpriseId'
-> StoreLayout -- ^ 'esslPayload'
-> EnterprisesSetStoreLayout
enterprisesSetStoreLayout pEsslEnterpriseId_ pEsslPayload_ =
EnterprisesSetStoreLayout'
{ _esslEnterpriseId = pEsslEnterpriseId_
, _esslPayload = pEsslPayload_
}
-- | The ID of the enterprise.
esslEnterpriseId :: Lens' EnterprisesSetStoreLayout Text
esslEnterpriseId
= lens _esslEnterpriseId
(\ s a -> s{_esslEnterpriseId = a})
-- | Multipart request metadata.
esslPayload :: Lens' EnterprisesSetStoreLayout StoreLayout
esslPayload
= lens _esslPayload (\ s a -> s{_esslPayload = a})
instance GoogleRequest EnterprisesSetStoreLayout
where
type Rs EnterprisesSetStoreLayout = StoreLayout
type Scopes EnterprisesSetStoreLayout =
'["https://www.googleapis.com/auth/androidenterprise"]
requestClient EnterprisesSetStoreLayout'{..}
= go _esslEnterpriseId (Just AltJSON) _esslPayload
androidEnterpriseService
where go
= buildClient
(Proxy :: Proxy EnterprisesSetStoreLayoutResource)
mempty
| rueshyna/gogol | gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/Enterprises/SetStoreLayout.hs | mpl-2.0 | 4,460 | 0 | 14 | 923 | 398 | 244 | 154 | 64 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.CloudErrorReporting.Projects.Events.Report
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Report an individual error event and record the event to a log. This
-- endpoint accepts **either** an OAuth token, **or** an [API
-- key](https:\/\/support.google.com\/cloud\/answer\/6158862) for
-- authentication. To use an API key, append it to the URL as the value of
-- a \`key\` parameter. For example: \`POST
-- https:\/\/clouderrorreporting.googleapis.com\/v1beta1\/{projectName}\/events:report?key=123ABC456\`
-- **Note:** [Error Reporting]
-- (https:\/\/cloud.google.com\/error-reporting) is a global service built
-- on Cloud Logging and doesn\'t analyze logs stored in regional log
-- buckets or logs routed to other Google Cloud projects. For more
-- information, see [Using Error Reporting with regionalized logs]
-- (https:\/\/cloud.google.com\/error-reporting\/docs\/regionalization).
--
-- /See:/ <https://cloud.google.com/error-reporting/ Error Reporting API Reference> for @clouderrorreporting.projects.events.report@.
module Network.Google.Resource.CloudErrorReporting.Projects.Events.Report
(
-- * REST Resource
ProjectsEventsReportResource
-- * Creating a Request
, projectsEventsReport
, ProjectsEventsReport
-- * Request Lenses
, perXgafv
, perUploadProtocol
, perAccessToken
, perUploadType
, perPayload
, perProjectName
, perCallback
) where
import Network.Google.CloudErrorReporting.Types
import Network.Google.Prelude
-- | A resource alias for @clouderrorreporting.projects.events.report@ method which the
-- 'ProjectsEventsReport' request conforms to.
type ProjectsEventsReportResource =
"v1beta1" :>
Capture "projectName" Text :>
"events:report" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] ReportedErrorEvent :>
Post '[JSON] ReportErrorEventResponse
-- | Report an individual error event and record the event to a log. This
-- endpoint accepts **either** an OAuth token, **or** an [API
-- key](https:\/\/support.google.com\/cloud\/answer\/6158862) for
-- authentication. To use an API key, append it to the URL as the value of
-- a \`key\` parameter. For example: \`POST
-- https:\/\/clouderrorreporting.googleapis.com\/v1beta1\/{projectName}\/events:report?key=123ABC456\`
-- **Note:** [Error Reporting]
-- (https:\/\/cloud.google.com\/error-reporting) is a global service built
-- on Cloud Logging and doesn\'t analyze logs stored in regional log
-- buckets or logs routed to other Google Cloud projects. For more
-- information, see [Using Error Reporting with regionalized logs]
-- (https:\/\/cloud.google.com\/error-reporting\/docs\/regionalization).
--
-- /See:/ 'projectsEventsReport' smart constructor.
data ProjectsEventsReport =
ProjectsEventsReport'
{ _perXgafv :: !(Maybe Xgafv)
, _perUploadProtocol :: !(Maybe Text)
, _perAccessToken :: !(Maybe Text)
, _perUploadType :: !(Maybe Text)
, _perPayload :: !ReportedErrorEvent
, _perProjectName :: !Text
, _perCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsEventsReport' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'perXgafv'
--
-- * 'perUploadProtocol'
--
-- * 'perAccessToken'
--
-- * 'perUploadType'
--
-- * 'perPayload'
--
-- * 'perProjectName'
--
-- * 'perCallback'
projectsEventsReport
:: ReportedErrorEvent -- ^ 'perPayload'
-> Text -- ^ 'perProjectName'
-> ProjectsEventsReport
projectsEventsReport pPerPayload_ pPerProjectName_ =
ProjectsEventsReport'
{ _perXgafv = Nothing
, _perUploadProtocol = Nothing
, _perAccessToken = Nothing
, _perUploadType = Nothing
, _perPayload = pPerPayload_
, _perProjectName = pPerProjectName_
, _perCallback = Nothing
}
-- | V1 error format.
perXgafv :: Lens' ProjectsEventsReport (Maybe Xgafv)
perXgafv = lens _perXgafv (\ s a -> s{_perXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
perUploadProtocol :: Lens' ProjectsEventsReport (Maybe Text)
perUploadProtocol
= lens _perUploadProtocol
(\ s a -> s{_perUploadProtocol = a})
-- | OAuth access token.
perAccessToken :: Lens' ProjectsEventsReport (Maybe Text)
perAccessToken
= lens _perAccessToken
(\ s a -> s{_perAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
perUploadType :: Lens' ProjectsEventsReport (Maybe Text)
perUploadType
= lens _perUploadType
(\ s a -> s{_perUploadType = a})
-- | Multipart request metadata.
perPayload :: Lens' ProjectsEventsReport ReportedErrorEvent
perPayload
= lens _perPayload (\ s a -> s{_perPayload = a})
-- | Required. The resource name of the Google Cloud Platform project.
-- Written as \`projects\/{projectId}\`, where \`{projectId}\` is the
-- [Google Cloud Platform project
-- ID](https:\/\/support.google.com\/cloud\/answer\/6158840). Example: \/\/
-- \`projects\/my-project-123\`.
perProjectName :: Lens' ProjectsEventsReport Text
perProjectName
= lens _perProjectName
(\ s a -> s{_perProjectName = a})
-- | JSONP
perCallback :: Lens' ProjectsEventsReport (Maybe Text)
perCallback
= lens _perCallback (\ s a -> s{_perCallback = a})
instance GoogleRequest ProjectsEventsReport where
type Rs ProjectsEventsReport =
ReportErrorEventResponse
type Scopes ProjectsEventsReport =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsEventsReport'{..}
= go _perProjectName _perXgafv _perUploadProtocol
_perAccessToken
_perUploadType
_perCallback
(Just AltJSON)
_perPayload
cloudErrorReportingService
where go
= buildClient
(Proxy :: Proxy ProjectsEventsReportResource)
mempty
| brendanhay/gogol | gogol-clouderrorreporting/gen/Network/Google/Resource/CloudErrorReporting/Projects/Events/Report.hs | mpl-2.0 | 6,962 | 0 | 17 | 1,400 | 805 | 480 | 325 | 116 | 1 |
{-# OPTIONS_GHC -Wall -O2 #-}
import System.Console.CmdArgs (cmdArgsRun)
import System.Environment (getArgs, withArgs)
import System.IO
import NGramCrackers.Parsers.Args
main :: IO ()
main = getArgs >>= \args ->
(if null args then withArgs ["--help"] else id) $ cmdArgsRun myModes >>= optionHandler
| R-Morgan/NGramCrackers | src/Main.hs | agpl-3.0 | 312 | 0 | 12 | 52 | 92 | 52 | 40 | 8 | 2 |
module Main where
import Network.Socket hiding (recvFrom)
import Control.Monad
import Codec.Picture
import System.IO (hPutStr, stderr)
import Network.Socket.ByteString
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import Telepulssi
import ImageTools
udpServer :: Integral a => a -> (BS.ByteString -> IO ()) -> IO ()
udpServer udpPort handler = do
withSocketsDo $ do
sock <- socket AF_INET Datagram 0
bind sock (SockAddrInet (fromIntegral udpPort) iNADDR_ANY)
forever $ do
(msg, _) <- recvFrom sock 65507
handler msg
-- FIXME use my serial handling code instead of `stty -F /dev/ttyACM0 19200 raw`
main = udpServer 1337 pngToTelepulssi
pngToTelepulssi bs = case decodeImage bs of
Left _ -> hPutStr stderr "Invalid image format received\n"
Right img -> case telepulssify (dynToGrayscale img) of
Left e -> hPutStr stderr $ e ++ "\n"
Right a -> BL.putStr a
| HacklabJKL/telepulssi-arduino | tools/UdpServer.hs | agpl-3.0 | 936 | 0 | 14 | 179 | 286 | 146 | 140 | 24 | 3 |
module AST where
import Text.Parsec.Error
import Data.IORef
import Control.Monad.Error
import System.IO
type IOThrowsError = ErrorT LispError IO
type Env = IORef [(String, IORef LispVal)]
data LispError = NumArgs Integer [LispVal]
| TypeMismatch String LispVal
| Parser ParseError
| BadSpecialForm String LispVal
| NotFunction String String
| UnboundVar String String
| Default String
data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal
| Number Integer
| String String
| Bool Bool
| Float Float
| PrimitiveFunc ([LispVal] -> ThrowsError LispVal)
| Func {params :: [String], vararg :: (Maybe String),
body :: [LispVal], closure :: Env}
| IOFunc ([LispVal] -> IOThrowsError LispVal)
| Port Handle
showVal :: LispVal -> String
showVal (String contents) = "\"" ++ contents ++ "\""
showVal (Atom name) = name
showVal (Number contents) = show contents
showVal (Float contents) = show contents
showVal (Bool True) = "#t"
showVal (Bool False) = "#f"
showVal (List contents) = "(" ++ unwordList contents ++ ")"
showVal (DottedList hd tl) = "(" ++ unwordList hd ++ " . " ++ showVal tl ++ ")"
showVal (PrimitiveFunc _) = "<primitive>"
showVal (Func {params = args, vararg = varargs, body = _, closure = _}) =
"(lambda (" ++ unwords (map show args) ++
(case varargs of
Nothing -> ""
Just arg -> " . " ++ arg) ++ ") ...)"
showVal (Port _) = "<IO port>"
showVal (IOFunc _) = "<IO primitive>"
instance Show LispVal where
show = showVal
unwordList :: [LispVal] -> String
unwordList = unwords . map showVal
type ThrowsError = Either LispError
| kkspeed/SICP-Practise | Interpreter/code/AST.hs | lgpl-3.0 | 1,862 | 0 | 11 | 567 | 584 | 318 | 266 | 48 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Network.Haskoin.Wallet.Server
( runSPVServer
, stopSPVServer
) where
import System.Posix.Daemon (runDetached, Redirection (ToFile), killAndWait)
import System.ZMQ4
( Rep(..), bind, receive, send
, withContext, withSocket
)
import Control.Monad (when, unless, forever, liftM)
import Control.Monad.Trans (MonadIO, lift, liftIO)
import Control.Monad.Trans.Control (MonadBaseControl, liftBaseOpDiscard)
import Control.Monad.Base (MonadBase)
import Control.Monad.Catch (MonadThrow)
import Control.Monad.Trans.Resource (MonadResource, runResourceT)
import Control.DeepSeq (NFData(..))
import Control.Concurrent.STM (retry)
import Control.Concurrent.Async.Lifted (async, waitAnyCancel)
import Control.Exception.Lifted (SomeException(..), ErrorCall(..), catches)
import qualified Control.Exception.Lifted as E (Handler(..))
import qualified Control.Concurrent.MSem as Sem (MSem, new)
import Control.Monad.Logger
( MonadLogger
, runStdoutLoggingT
, logDebug
, logWarn
, logInfo
, filterLogger
)
import qualified Data.HashMap.Strict as H (lookup)
import Data.Text (pack)
import Data.Maybe (fromMaybe)
import Data.Aeson (Value, decode, encode)
import Data.Conduit (await, awaitForever, ($$))
import Data.Word (Word32)
import qualified Data.Map.Strict as M
(Map, unionWith, null, empty, fromListWith, assocs, elems)
import Database.Persist.Sql (ConnectionPool, runMigration)
import qualified Database.LevelDB.Base as DB (Options(..), defaultOptions)
import Database.Esqueleto (from, where_, val , (^.), (==.), (&&.), (<=.))
import Network.Haskoin.Crypto
import Network.Haskoin.Constants
import Network.Haskoin.Util
import Network.Haskoin.Block
import Network.Haskoin.Transaction
import Network.Haskoin.Node.Peer
import Network.Haskoin.Node.BlockChain
import Network.Haskoin.Node.STM
import Network.Haskoin.Node.HeaderTree
import Network.Haskoin.Wallet.KeyRing
import Network.Haskoin.Wallet.Transaction
import Network.Haskoin.Wallet.Types
import Network.Haskoin.Wallet.Model
import Network.Haskoin.Wallet.Settings
import Network.Haskoin.Wallet.Server.Handler
import Network.Haskoin.Wallet.Database
data EventSession = EventSession
{ eventBatchSize :: !Int
, eventNewAddrs :: !(M.Map KeyRingAccountId Word32)
}
deriving (Eq, Show, Read)
instance NFData EventSession where
rnf EventSession{..} =
rnf eventBatchSize `seq`
rnf (M.elems eventNewAddrs)
runSPVServer :: Config -> IO ()
runSPVServer cfg = maybeDetach cfg $ do -- start the server process
-- Initialize the database
(sem, pool) <- initDatabase cfg
-- Check the operation mode of the server.
run $ case configMode cfg of
-- In this mode, we do not launch an SPV node. We only accept
-- client requests through the ZMQ API.
SPVOffline -> runWalletApp $ HandlerSession cfg pool Nothing sem
-- In this mode, we launch the client ZMQ API and we sync the
-- wallet database with an SPV node.
SPVOnline -> do
-- Initialize the node state
nodeState <- getNodeState fp opts
-- Spin up the node threads
as <- mapM async
-- Start the SPV node
[ runNodeT nodeState $ do
-- Get our bloom filter
bloom <- liftM fst3 $ runDBPool sem pool getBloomFilter
startSPVNode hosts bloom
-- Merkle block synchronization
, runMerkleSync nodeState sem pool
-- Import solo transactions as they arrive from peers
, runNodeT nodeState $ txSource $$ processTx sem pool
-- Respond to transaction GetData requests
, runNodeT nodeState $
handleGetData $ runDBPool sem pool . getTx
-- Re-broadcast pending transactions
, broadcastPendingTxs nodeState sem pool
-- Run the ZMQ API server
, runWalletApp $ HandlerSession cfg pool (Just nodeState) sem
]
_ <- waitAnyCancel as
return ()
where
-- Setup logging monads
run = runResourceT . runLogging
runLogging = runStdoutLoggingT . filterLogger logFilter
logFilter _ level = level >= configLogLevel cfg
-- Bitcoin nodes to connect to
nodes = fromMaybe
(error $ "BTC nodes for " ++ networkName ++ " not found")
(pack networkName `H.lookup` configBTCNodes cfg)
hosts = map (uncurry PeerHost) nodes
-- LevelDB options
fp = "headertree"
opts = DB.defaultOptions { DB.createIfMissing = True
, DB.cacheSize = 2048
}
-- Run the merkle syncing thread
runMerkleSync nodeState sem pool = runNodeT nodeState $ do
$(logDebug) "Waiting for a valid bloom filter for merkle downloads..."
-- Only download merkles if we have a valid bloom filter
_ <- atomicallyNodeT waitBloomFilter
-- Provide a fast catchup time if we are at height 0
fcM <- liftM (fmap adjustFCTime) $ runDBPool sem pool $ do
(_, h) <- getBestBlock
if h == 0 then firstAddrTime else return Nothing
maybe (return ()) (atomicallyNodeT . rescanTs) fcM
-- Start the merkle sync
merkleSync sem pool 500
-- Run a thread that will re-broadcast pending transactions
broadcastPendingTxs nodeState sem pool = runNodeT nodeState $ forever $ do
-- Wait until we are synced
atomicallyNodeT $ do
synced <- areBlocksSynced
if synced then return () else lift retry
-- Send an INV for those transactions to all peers
broadcastTxs =<< runDBPool sem pool (getPendingTxs 100)
-- Wait until we are not synced
atomicallyNodeT $ do
synced <- areBlocksSynced
if synced then lift retry else return ()
processTx sem pool = awaitForever $ \tx -> lift $ do
(_, newAddrs) <- runDBPool sem pool $ importNetTx tx
unless (null newAddrs) $ do
$(logInfo) $ pack $ unwords
[ "Generated", show $ length newAddrs
, "new addresses while importing the tx."
, "Updating the bloom filter"
]
(bloom, _, _) <- runDBPool sem pool getBloomFilter
atomicallyNodeT $ sendBloomFilter bloom
initDatabase :: Config -> IO (Sem.MSem Int, ConnectionPool)
initDatabase cfg = do
-- Create a semaphore with 1 resource
sem <- Sem.new 1
-- Create a database pool
let dbCfg = fromMaybe
(error $ "DB config settings for " ++ networkName ++ " not found")
(pack networkName `H.lookup` configDatabase cfg)
pool <- getDatabasePool dbCfg
-- Initialize wallet database
runDBPool sem pool $ do
_ <- runMigration migrateWallet
initWallet $ configBloomFP cfg
-- Return the semaphrone and the connection pool
return (sem, pool)
merkleSync
:: ( MonadLogger m
, MonadIO m
, MonadBaseControl IO m
, MonadThrow m
, MonadResource m
)
=> Sem.MSem Int
-> ConnectionPool
-> Int
-> NodeT m ()
merkleSync sem pool bSize = do
-- Get our best block
best <- fst <$> runDBPool sem pool getBestBlock
$(logDebug) "Starting merkle batch download"
-- Wait for a new block or a rescan
(action, source) <- merkleDownload best bSize
$(logDebug) "Received a merkle action and source. Processing the source..."
-- Read and process the data from the source
(lastMerkleM, mTxsAcc, aMap) <- source $$ go Nothing [] M.empty
$(logDebug) "Merkle source processed and closed"
-- Send a new bloom filter to our peers if new addresses were generated
unless (M.null aMap) $ do
$(logInfo) $ pack $ unwords
[ "Generated", show $ sum $ M.elems aMap
, "new addresses while importing the merkle block."
, "Sending our bloom filter."
]
(bloom, _, _) <- runDBPool sem pool getBloomFilter
atomicallyNodeT $ sendBloomFilter bloom
-- Check if we should rescan the current merkle batch
$(logDebug) "Checking if we need to rescan the current batch..."
rescan <- lift $ shouldRescan aMap
when rescan $ $(logDebug) "We need to rescan the current batch"
-- Compute the new batch size
let newBSize | rescan = max 1 $ bSize `div` 2
| otherwise = min 500 $ bSize + max 1 (bSize `div` 20)
when (newBSize /= bSize) $ $(logDebug) $ pack $ unwords
[ "Changing block batch size from", show bSize, "to", show newBSize ]
-- Did we receive all the merkles that we asked for ?
let missing = (headerHash <$> lastMerkleM) /=
Just (nodeBlockHash $ last $ actionNodes action)
when missing $ $(logWarn) $ pack $ unwords
[ "Merkle block stream closed prematurely"
, show lastMerkleM
]
-- TODO: We could still salvage a partially received batch
unless (rescan || missing) $ do
$(logDebug) "Importing merkles into the wallet..."
-- Confirm the transactions
runDBPool sem pool $ importMerkles action mTxsAcc
$(logDebug) "Done importing merkles into the wallet"
logBlockChainAction action
merkleSync sem pool newBSize
where
go lastMerkleM mTxsAcc aMap = await >>= \resM -> case resM of
Just (Right tx) -> do
$(logDebug) $ pack $ unwords
[ "Importing merkle tx", encodeTxHashLE $ txHash tx ]
(_, newAddrs) <- lift $ runDBPool sem pool $ importNetTx tx
$(logDebug) $ pack $ unwords
[ "Generated", show $ length newAddrs
, "new addresses while importing tx"
, encodeTxHashLE $ txHash tx
]
let newMap = M.unionWith (+) aMap $ groupByAcc newAddrs
go lastMerkleM mTxsAcc newMap
Just (Left ((MerkleBlock mHead _ _ _), mTxs)) -> do
$(logDebug) $ pack $ unwords
[ "Buffering merkle block"
, encodeBlockHashLE $ headerHash mHead
]
go (Just mHead) (mTxs:mTxsAcc) aMap
-- Done processing this batch. Reverse mTxsAcc as we have been
-- prepending new values to it.
_ -> return (lastMerkleM, reverse mTxsAcc, aMap)
groupByAcc addrs =
let xs = map (\a -> (keyRingAddrAccount a, 1)) addrs
in M.fromListWith (+) xs
shouldRescan aMap = do
-- Try to find an account whos gap is smaller than the number of new
-- addresses generated in that account.
res <- runDBPool sem pool $ splitSelect (M.assocs aMap) $ \ks ->
from $ \a -> do
let andCond (ai, cnt) =
a ^. KeyRingAccountId ==. val ai &&.
a ^. KeyRingAccountGap <=. val cnt
where_ $ join2 $ map andCond ks
return $ a ^. KeyRingAccountId
return $ not $ null res
-- Some logging of the blocks
logBlockChainAction action = case action of
BestChain nodes -> $(logInfo) $ pack $ unwords
[ "Best chain height"
, show $ nodeHeaderHeight $ last nodes
, "(", encodeBlockHashLE $ nodeBlockHash $ last nodes, ")"
]
ChainReorg _ o n -> $(logInfo) $ pack $ unlines $
[ "Chain reorg."
, "Orphaned blocks:"
]
++ map ((" " ++) . encodeBlockHashLE . nodeBlockHash) o
++ [ "New blocks:" ]
++ map ((" " ++) . encodeBlockHashLE . nodeBlockHash) n
++ [ unwords [ "Best merkle chain height"
, show $ nodeHeaderHeight $ last n
]
]
SideChain n -> $(logWarn) $ pack $ unlines $
"Side chain:" :
map ((" " ++) . encodeBlockHashLE . nodeBlockHash) n
KnownChain n -> $(logWarn) $ pack $ unlines $
"Known chain:" :
map ((" " ++) . encodeBlockHashLE . nodeBlockHash) n
maybeDetach :: Config -> IO () -> IO ()
maybeDetach cfg action =
if configDetach cfg then runDetached pidFile logFile action else action
where
pidFile = Just $ configPidFile cfg
logFile = ToFile $ configLogFile cfg
stopSPVServer :: Config -> IO ()
stopSPVServer cfg =
-- TODO: Should we send a message instead of killing the process ?
killAndWait $ configPidFile cfg
-- Run the main ZeroMQ loop
-- TODO: Support concurrent requests using DEALER socket when we can do
-- concurrent MySQL requests.
runWalletApp :: ( MonadIO m
, MonadLogger m
, MonadBaseControl IO m
, MonadBase IO m
, MonadThrow m
, MonadResource m
)
=> HandlerSession -> m ()
runWalletApp session =
liftBaseOpDiscard withContext $ \ctx ->
liftBaseOpDiscard (withSocket ctx Rep) $ \sock -> do
liftIO $ bind sock $ configBind $ handlerConfig session
forever $ do
bs <- liftIO $ receive sock
res <- case decode $ toLazyBS bs of
Just r -> catchErrors $
runHandler session $ dispatchRequest r
Nothing -> return $ ResponseError "Could not decode request"
liftIO $ send sock [] $ toStrictBS $ encode res
where
catchErrors m = catches m
[ E.Handler $ \(WalletException err) ->
return $ ResponseError $ pack err
, E.Handler $ \(ErrorCall err) ->
return $ ResponseError $ pack err
, E.Handler $ \(SomeException exc) ->
return $ ResponseError $ pack $ show exc
]
dispatchRequest :: ( MonadLogger m
, MonadBaseControl IO m
, MonadBase IO m
, MonadThrow m
, MonadResource m
, MonadIO m
)
=> WalletRequest -> Handler m (WalletResponse Value)
dispatchRequest req = liftM ResponseValid $ case req of
GetKeyRingsR -> getKeyRingsR
GetKeyRingR r -> getKeyRingR r
PostKeyRingsR r -> postKeyRingsR r
GetAccountsR r -> getAccountsR r
PostAccountsR r na -> postAccountsR r na
GetAccountR r n -> getAccountR r n
PostAccountKeysR r n ks -> postAccountKeysR r n ks
PostAccountGapR r n g -> postAccountGapR r n g
GetAddressesR r n t m o p -> getAddressesR r n t m o p
GetAddressesUnusedR r n t -> getAddressesUnusedR r n t
GetAddressR r n i t m o -> getAddressR r n i t m o
PutAddressR r n i t l -> putAddressR r n i t l
PostAddressesR r n i t -> postAddressesR r n i t
GetTxsR r n p -> getTxsR r n p
GetAddrTxsR r n i t p -> getAddrTxsR r n i t p
PostTxsR r n a -> postTxsR r n a
GetTxR r n h -> getTxR r n h
GetOfflineTxR r n h -> getOfflineTxR r n h
PostOfflineTxR r n t cs -> postOfflineTxR r n t cs
GetBalanceR r n mc o -> getBalanceR r n mc o
PostNodeR na -> postNodeR na
| tphyahoo/haskoin-wallet | Network/Haskoin/Wallet/Server.hs | unlicense | 15,473 | 0 | 23 | 4,968 | 3,868 | 1,996 | 1,872 | -1 | -1 |
{- |
Description : Truncation of floating-point significands
Copyright : 2017 Andrew Dawson
License : Apache-2.0
Tools for truncating the number of bits in the significand of floating-point
numbers. The numbers can be represented in decimal, binary or hexadecimal.
You can create additional representations by making instances of the
'Truncatable' typeclass.
-}
--
-- Copyright 2017 Andrew Dawson
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
module Truncate
( Truncatable(..)
, TParser
, WordF(..)
, Binary(..)
, Decimal(..)
, Hexadecimal(..)
, toBin
, toDec
, toHex
, makeBin32
, makeBin64
, makeDec32
, makeDec64
, makeHex32
, makeHex64
) where
------------------------------------------------------------------------
import Data.Binary.IEEE754 ( wordToFloat
, floatToWord
, wordToDouble
, doubleToWord
)
import Text.Read (readMaybe)
------------------------------------------------------------------------
import Truncate.Internal
------------------------------------------------------------------------
-- | A typeclass for things that can be represented as truncatable bits
class Truncatable a where
-- | Convert to a bits representation, either a 'WordF32' or 'WordF64'.
makeBits :: a -> WordF
-- | Convert from a bits representation which will be either a 'WordF32'
-- or a 'WordF64'.
fromBits :: WordF -> a
-- | Truncation operator, truncates an instance to a specified number of
-- bits in its significand. The truncation applies the IEEE round-to-nearest
-- tie-to-even rounding specification.
infixl 5 <#
(<#) :: a -> Int -> a
(<#) = (fromBits .) . truncateWord . makeBits
-- | The same as '(<#)' with the arguments flipped.
infixr 5 #>
(#>) :: Int -> a -> a
(#>)= flip (<#)
-- | Convert from one 'Truncatable' instance to another.
convert :: (Truncatable b) => a -> b
convert = fromBits . makeBits
-----------------------------------------------------------------------
-- | A function type for parsing 'Truncatable' types
type TParser a = String -> Either String a
-----------------------------------------------------------------------
-- | Truncatable floating-point numbers in binary representation.
data Binary = Bin32 String
| Bin64 String
instance Truncatable Binary where
makeBits (Bin32 b) = WordF32 $ binToWord b
makeBits (Bin64 b) = WordF64 $ binToWord b
fromBits (WordF32 b) = Bin32 (wordToBin b)
fromBits (WordF64 b) = Bin64 (wordToBin b)
instance Show Binary where
show (Bin32 s) = zeroPad 32 s
show (Bin64 s) = zeroPad 64 s
instance Eq Binary where
(Bin32 a) == (Bin32 b) = (zeroStrip a) == (zeroStrip b)
(Bin64 a) == (Bin64 b) = (zeroStrip a) == (zeroStrip b)
_ == _ = False
-- | Convert a 'Truncatable' instance to 'Binary'.
toBin :: (Truncatable a) => a -> Binary
toBin = convert
-- | Create a 'Bin32' from a string. The string should be a sequence of the
-- characters @0@ and @1@ no longer than 32 characters in length.
makeBin32 :: TParser Binary
makeBin32 s
| length s > 32 = Left $ tooManyDigits "binary" 32
| (not .validBin) s = Left $ invalidDigits "binary" 32
| otherwise = Right (Bin32 s)
-- | Create a 'Bin64' from a string. The string should be a sequence of the
-- characters @0@ and @1@ no longer than 64 characters in length.
makeBin64 :: TParser Binary
makeBin64 s
| length s > 64 = Left $ tooManyDigits "binary" 64
| (not .validBin) s = Left $ invalidDigits "binary" 64
| otherwise = Right (Bin64 s)
-----------------------------------------------------------------------
-- | Truncatable floating-point numbers in decimal representation.
data Decimal = Dec32 Float
| Dec64 Double
deriving (Eq)
instance Truncatable Decimal where
makeBits (Dec32 f) = WordF32 (floatToWord f)
makeBits (Dec64 f) = WordF64 (doubleToWord f)
fromBits (WordF32 b) = Dec32 (wordToFloat b)
fromBits (WordF64 b) = Dec64 (wordToDouble b)
instance Show Decimal where
show (Dec32 f) = show f
show (Dec64 d) = show d
-- | Convert a 'Truncatable' instance to 'Decimal'.
toDec :: (Truncatable a) => a -> Decimal
toDec = convert
-- | Create a 'Dec32' from a string. The string can be anything that can be
-- interpreted as a 32-bit 'Float' by 'read'.
makeDec32 :: TParser Decimal
makeDec32 s = case readMaybe s :: Maybe Float of
Just f -> Right (Dec32 f)
Nothing -> Left "Error: value is not a 32-bit decimal number"
-- | Create a 'Dec64' from a string. The string can be anything that can be
-- interpreted as a 64-bit 'Double' by 'read'.
makeDec64 :: TParser Decimal
makeDec64 s = case readMaybe s :: Maybe Double of
Just f -> Right (Dec64 f)
Nothing -> Left "Error: value is not a 64-bit decimal number"
-----------------------------------------------------------------------
-- | Truncatable floating-point numbers in hexadecimal representation.
data Hexadecimal = Hex32 String
| Hex64 String
instance Truncatable Hexadecimal where
makeBits (Hex32 s) = WordF32 $ hexToWord s
makeBits (Hex64 s) = WordF64 $ hexToWord s
fromBits (WordF32 b) = Hex32 (wordToHex b)
fromBits (WordF64 b) = Hex64 (wordToHex b)
instance Show Hexadecimal where
show (Hex32 s) = zeroPad 8 s
show (Hex64 s) = zeroPad 16 s
instance Eq Hexadecimal where
(Hex32 a) == (Hex32 b) = (zeroStrip a) == (zeroStrip b)
(Hex64 a) == (Hex64 b) = (zeroStrip a) == (zeroStrip b)
_ == _ = False
-- | Convert a 'Truncatable' instance to 'Hexadecimal'.
toHex :: (Truncatable a) => a -> Hexadecimal
toHex = convert
-- | Create a 'Hex32' from a string. The string should be a sequence of the
-- valid hexadecimal digits @0-9@ and @a-f@ no longer than 8 characters in length.
makeHex32 :: TParser Hexadecimal
makeHex32 s
| length s > 8 = Left $ tooManyDigits "hexadecimal" 32
| (not . validHex) s = Left $ invalidDigits "hexadecimal" 32
| otherwise = Right (Hex32 s)
-- | Create a 'Hex64' from a string. The string should be a sequence of the
-- valid hexadecimal digits @0-9@ and @a-f@ no longer than 16 characters in length.
makeHex64 :: TParser Hexadecimal
makeHex64 s
| length s > 16 = Left $ tooManyDigits "hexadecimal" 64
| (not . validHex) s = Left $ invalidDigits "hexadecimal" 64
| otherwise = Right (Hex64 s)
| aopp-pred/fp-truncate | src/Truncate.hs | apache-2.0 | 7,082 | 2 | 10 | 1,632 | 1,486 | 773 | 713 | 107 | 2 |
compress :: Eq a => [a] -> [a]
compress [] = []
compress (x:xs) = compress' x xs
where
compress' x [] = [x]
compress' y (x:xs)
| y == x = compress' x xs
| otherwise = y:(compress' x xs) | alephnil/h99 | 08.hs | apache-2.0 | 232 | 0 | 10 | 87 | 125 | 62 | 63 | 7 | 2 |
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable, TypeFamilies, TemplateHaskell, OverloadedStrings, InstanceSigs #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Types where
import Control.Applicative ((<$>), pure, (<*>))
import Control.Monad (forM_, mzero)
import Control.Monad.Reader (ask)
import Control.Monad.State (get, put)
import Data.Acid (Query, Update, makeAcidic)
import Data.Aeson ((.:), (.=), object)
import Data.Aeson.TH (deriveJSON, defaultOptions)
import Data.Aeson.Types (FromJSON(..), ToJSON(..), Parser, Value(..))
import Data.Foldable (concat)
import Data.SafeCopy (deriveSafeCopy, base)
import Data.Time (UTCTime)
import Data.Typeable (Typeable)
import Network.URI (URI, URIAuth, parseURI)
import Prelude hiding (concat)
import qualified Data.Map as Map
newtype Tag = Tag String
deriving (Show, Typeable, Eq, Ord)
data Link = Link { uri :: URI
, tags :: [Tag]
}
deriving (Show, Typeable, Eq)
data DateLink = DateLink { link :: Link
, date :: UTCTime
}
deriving (Show, Typeable, Eq)
-- Seems like a horrible hack, but let's make this work first
-- before worrying about space/update efficiency.
newtype Links = Links { getLinkMap :: Map.Map Tag [DateLink] }
deriving (Show, Typeable)
instance FromJSON Link where
parseJSON :: Value -> Parser Link
parseJSON (Object o) = Link
<$> (maybe mzero return . parseURI =<< o .: "link")
<*> o .: "tags"
parseJSON _ = mzero
instance ToJSON Link where
toJSON (Link uri' tags') = object [ "uri" .= show uri'
, "tags" .= tags' ]
-- Orphan safecopy instances for URI-related things
deriveSafeCopy 0 'base ''URI
deriveSafeCopy 0 'base ''URIAuth
deriveSafeCopy 0 'base ''Tag
deriveSafeCopy 0 'base ''DateLink
deriveSafeCopy 0 'base ''Link
deriveSafeCopy 0 'base ''Links
-- Orphan JSON instances for URI-related things
deriveJSON defaultOptions ''URI
deriveJSON defaultOptions ''URIAuth
deriveJSON defaultOptions ''Tag
deriveJSON defaultOptions ''DateLink
getLinksByTag :: Tag -> Query Links [DateLink]
getLinksByTag tag = concat . Map.lookup tag . getLinkMap <$> ask
getLinks :: Query Links [DateLink]
getLinks = concat . Map.elems . getLinkMap <$> ask
postLink :: UTCTime -> Link -> Update Links ()
postLink now link' = forM_ (tags link') $ \t -> do
let dateLink = DateLink link' now
linkMap <- getLinkMap <$> get
let newLinks = maybe (pure dateLink) (dateLink :) (Map.lookup t linkMap)
put . Links $ Map.insert t newLinks linkMap
makeAcidic ''Links ['getLinksByTag, 'getLinks, 'postLink]
| passy/giflib-api | Types.hs | apache-2.0 | 2,657 | 0 | 15 | 548 | 823 | 453 | 370 | 58 | 1 |
module Graphics.GL.Low.Common where
import Graphics.GL
import Graphics.GL.Low.Types
import Graphics.GL.Low.Cube
attachmentPointForImageFormat :: ImageFormat -> GLenum
attachmentPointForImageFormat format = case format of
RGB -> GL_COLOR_ATTACHMENT0
RGBA -> GL_COLOR_ATTACHMENT0
Alpha -> GL_COLOR_ATTACHMENT0
Luminance -> GL_COLOR_ATTACHMENT0
LuminanceAlpha -> GL_COLOR_ATTACHMENT0
Depth24 -> GL_DEPTH_ATTACHMENT
Depth24Stencil8 -> GL_DEPTH_STENCIL_ATTACHMENT
cubeSideCodes :: Cube GLenum
cubeSideCodes = Cube
{ cubeLeft = GL_TEXTURE_CUBE_MAP_NEGATIVE_X
, cubeRight = GL_TEXTURE_CUBE_MAP_POSITIVE_X
, cubeTop = GL_TEXTURE_CUBE_MAP_POSITIVE_Y
, cubeBottom = GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
, cubeFront = GL_TEXTURE_CUBE_MAP_POSITIVE_Z
, cubeBack = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z }
| evanrinehart/lowgl | Graphics/GL/Low/Common.hs | bsd-2-clause | 865 | 0 | 7 | 160 | 141 | 83 | 58 | 21 | 7 |
{-# LANGUAGE TransformListComp #-}
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Backends.Html.Decl
-- Copyright : (c) Simon Marlow 2003-2006,
-- David Waern 2006-2009,
-- Mark Lentczner 2010
-- License : BSD-like
--
-- Maintainer : haddock@projects.haskell.org
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
module Haddock.Backends.Xhtml.Decl (
ppDecl,
ppTyName, ppTyFamHeader, ppTypeApp,
tyvarNames
) where
import Haddock.Backends.Xhtml.DocMarkup
import Haddock.Backends.Xhtml.Layout
import Haddock.Backends.Xhtml.Names
import Haddock.Backends.Xhtml.Types
import Haddock.Backends.Xhtml.Utils
import Haddock.GhcUtils
import Haddock.Types
import Haddock.Doc (combineDocumentation)
import Data.List ( intersperse, sort )
import qualified Data.Map as Map
import Data.Maybe
import Text.XHtml hiding ( name, title, p, quote )
import GHC
import GHC.Exts
import Name
import BooleanFormula
ppDecl :: Bool -> LinksInfo -> LHsDecl DocName
-> DocForDecl DocName -> [DocInstance DocName] -> [(DocName, Fixity)]
-> [(DocName, DocForDecl DocName)] -> Splice -> Unicode -> Qualification -> Html
ppDecl summ links (L loc decl) (mbDoc, fnArgsDoc) instances fixities subdocs splice unicode qual = case decl of
TyClD (FamDecl d) -> ppTyFam summ False links instances fixities loc mbDoc d splice unicode qual
TyClD d@(DataDecl {}) -> ppDataDecl summ links instances fixities subdocs loc mbDoc d splice unicode qual
TyClD d@(SynDecl {}) -> ppTySyn summ links fixities loc (mbDoc, fnArgsDoc) d splice unicode qual
TyClD d@(ClassDecl {}) -> ppClassDecl summ links instances fixities loc mbDoc subdocs d splice unicode qual
SigD (TypeSig lnames lty _) -> ppLFunSig summ links loc (mbDoc, fnArgsDoc) lnames lty fixities splice unicode qual
SigD (PatSynSig lname qtvs prov req ty) ->
ppLPatSig summ links loc (mbDoc, fnArgsDoc) lname qtvs prov req ty fixities splice unicode qual
ForD d -> ppFor summ links loc (mbDoc, fnArgsDoc) d fixities splice unicode qual
InstD _ -> noHtml
_ -> error "declaration not supported by ppDecl"
ppLFunSig :: Bool -> LinksInfo -> SrcSpan -> DocForDecl DocName ->
[Located DocName] -> LHsType DocName -> [(DocName, Fixity)] ->
Splice -> Unicode -> Qualification -> Html
ppLFunSig summary links loc doc lnames lty fixities splice unicode qual =
ppFunSig summary links loc doc (map unLoc lnames) (unLoc lty) fixities
splice unicode qual
ppFunSig :: Bool -> LinksInfo -> SrcSpan -> DocForDecl DocName ->
[DocName] -> HsType DocName -> [(DocName, Fixity)] ->
Splice -> Unicode -> Qualification -> Html
ppFunSig summary links loc doc docnames typ fixities splice unicode qual =
ppSigLike summary links loc mempty doc docnames fixities (typ, pp_typ)
splice unicode qual
where
pp_typ = ppType unicode qual typ
ppLPatSig :: Bool -> LinksInfo -> SrcSpan -> DocForDecl DocName ->
Located DocName ->
(HsExplicitFlag, LHsTyVarBndrs DocName) ->
LHsContext DocName -> LHsContext DocName ->
LHsType DocName ->
[(DocName, Fixity)] ->
Splice -> Unicode -> Qualification -> Html
ppLPatSig summary links loc (doc, _argDocs) (L _ name) (expl, qtvs) lprov lreq typ fixities splice unicode qual
| summary = pref1
| otherwise = topDeclElem links loc splice [name] (pref1 <+> ppFixities fixities qual)
+++ docSection Nothing qual doc
where
pref1 = hsep [ keyword "pattern"
, ppBinder summary occname
, dcolon unicode
, ppLTyVarBndrs expl qtvs unicode qual
, cxt
, ppLType unicode qual typ
]
cxt = case (ppLContextMaybe lprov unicode qual, ppLContextMaybe lreq unicode qual) of
(Nothing, Nothing) -> noHtml
(Nothing, Just req) -> parens noHtml <+> darr <+> req <+> darr
(Just prov, Nothing) -> prov <+> darr
(Just prov, Just req) -> prov <+> darr <+> req <+> darr
darr = darrow unicode
occname = nameOccName . getName $ name
ppSigLike :: Bool -> LinksInfo -> SrcSpan -> Html -> DocForDecl DocName ->
[DocName] -> [(DocName, Fixity)] -> (HsType DocName, Html) ->
Splice -> Unicode -> Qualification -> Html
ppSigLike summary links loc leader doc docnames fixities (typ, pp_typ)
splice unicode qual =
ppTypeOrFunSig summary links loc docnames typ doc
( addFixities $ leader <+> ppTypeSig summary occnames pp_typ unicode
, addFixities . concatHtml . punctuate comma $ map (ppBinder False) occnames
, dcolon unicode
)
splice unicode qual
where
occnames = map (nameOccName . getName) docnames
addFixities html
| summary = html
| otherwise = html <+> ppFixities fixities qual
ppTypeOrFunSig :: Bool -> LinksInfo -> SrcSpan -> [DocName] -> HsType DocName
-> DocForDecl DocName -> (Html, Html, Html)
-> Splice -> Unicode -> Qualification -> Html
ppTypeOrFunSig summary links loc docnames typ (doc, argDocs) (pref1, pref2, sep) splice unicode qual
| summary = pref1
| Map.null argDocs = topDeclElem links loc splice docnames pref1 +++ docSection curName qual doc
| otherwise = topDeclElem links loc splice docnames pref2 +++
subArguments qual (do_args 0 sep typ) +++ docSection curName qual doc
where
curName = getName <$> listToMaybe docnames
argDoc n = Map.lookup n argDocs
do_largs n leader (L _ t) = do_args n leader t
do_args :: Int -> Html -> HsType DocName -> [SubDecl]
do_args n leader (HsForAllTy _ _ tvs lctxt ltype)
= case unLoc lctxt of
[] -> do_largs n leader' ltype
_ -> (leader' <+> ppLContextNoArrow lctxt unicode qual, Nothing, [])
: do_largs n (darrow unicode) ltype
where leader' = leader <+> ppForAll tvs unicode qual
do_args n leader (HsFunTy lt r)
= (leader <+> ppLFunLhType unicode qual lt, argDoc n, [])
: do_largs (n+1) (arrow unicode) r
do_args n leader t
= [(leader <+> ppType unicode qual t, argDoc n, [])]
ppForAll :: LHsTyVarBndrs DocName -> Unicode -> Qualification -> Html
ppForAll tvs unicode qual =
case [ppKTv n k | L _ (KindedTyVar (L _ n) k) <- hsQTvBndrs tvs] of
[] -> noHtml
ts -> forallSymbol unicode <+> hsep ts +++ dot
where ppKTv n k = parens $
ppTyName (getName n) <+> dcolon unicode <+> ppLKind unicode qual k
ppFixities :: [(DocName, Fixity)] -> Qualification -> Html
ppFixities [] _ = noHtml
ppFixities fs qual = foldr1 (+++) (map ppFix uniq_fs) +++ rightEdge
where
ppFix (ns, p, d) = thespan ! [theclass "fixity"] <<
(toHtml d <+> toHtml (show p) <+> ppNames ns)
ppDir InfixR = "infixr"
ppDir InfixL = "infixl"
ppDir InfixN = "infix"
ppNames = case fs of
_:[] -> const noHtml -- Don't display names for fixities on single names
_ -> concatHtml . intersperse (stringToHtml ", ") . map (ppDocName qual Infix False)
uniq_fs = [ (n, the p, the d') | (n, Fixity p d) <- fs
, let d' = ppDir d
, then group by Down (p,d') using groupWith ]
rightEdge = thespan ! [theclass "rightedge"] << noHtml
ppTyVars :: LHsTyVarBndrs DocName -> [Html]
ppTyVars tvs = map ppTyName (tyvarNames tvs)
tyvarNames :: LHsTyVarBndrs DocName -> [Name]
tyvarNames = map getName . hsLTyVarNames
ppFor :: Bool -> LinksInfo -> SrcSpan -> DocForDecl DocName
-> ForeignDecl DocName -> [(DocName, Fixity)]
-> Splice -> Unicode -> Qualification -> Html
ppFor summary links loc doc (ForeignImport (L _ name) (L _ typ) _ _) fixities
splice unicode qual
= ppFunSig summary links loc doc [name] typ fixities splice unicode qual
ppFor _ _ _ _ _ _ _ _ _ = error "ppFor"
-- we skip type patterns for now
ppTySyn :: Bool -> LinksInfo -> [(DocName, Fixity)] -> SrcSpan
-> DocForDecl DocName -> TyClDecl DocName
-> Splice -> Unicode -> Qualification -> Html
ppTySyn summary links fixities loc doc (SynDecl { tcdLName = L _ name, tcdTyVars = ltyvars
, tcdRhs = ltype })
splice unicode qual
= ppTypeOrFunSig summary links loc [name] (unLoc ltype) doc
(full <+> fixs, hdr <+> fixs, spaceHtml +++ equals)
splice unicode qual
where
hdr = hsep ([keyword "type", ppBinder summary occ] ++ ppTyVars ltyvars)
full = hdr <+> equals <+> ppLType unicode qual ltype
occ = nameOccName . getName $ name
fixs
| summary = noHtml
| otherwise = ppFixities fixities qual
ppTySyn _ _ _ _ _ _ _ _ _ = error "declaration not supported by ppTySyn"
ppTypeSig :: Bool -> [OccName] -> Html -> Bool -> Html
ppTypeSig summary nms pp_ty unicode =
concatHtml htmlNames <+> dcolon unicode <+> pp_ty
where
htmlNames = intersperse (stringToHtml ", ") $ map (ppBinder summary) nms
ppTyName :: Name -> Html
ppTyName = ppName Prefix
--------------------------------------------------------------------------------
-- * Type families
--------------------------------------------------------------------------------
ppTyFamHeader :: Bool -> Bool -> FamilyDecl DocName
-> Unicode -> Qualification -> Html
ppTyFamHeader summary associated d@(FamilyDecl { fdInfo = info
, fdKindSig = mkind })
unicode qual =
(case info of
OpenTypeFamily
| associated -> keyword "type"
| otherwise -> keyword "type family"
DataFamily
| associated -> keyword "data"
| otherwise -> keyword "data family"
ClosedTypeFamily _
-> keyword "type family"
) <+>
ppFamDeclBinderWithVars summary d <+>
(case mkind of
Just kind -> dcolon unicode <+> ppLKind unicode qual kind
Nothing -> noHtml
)
ppTyFam :: Bool -> Bool -> LinksInfo -> [DocInstance DocName] ->
[(DocName, Fixity)] -> SrcSpan -> Documentation DocName ->
FamilyDecl DocName -> Splice -> Unicode -> Qualification -> Html
ppTyFam summary associated links instances fixities loc doc decl splice unicode qual
| summary = ppTyFamHeader True associated decl unicode qual
| otherwise = header_ +++ docSection Nothing qual doc +++ instancesBit
where
docname = unLoc $ fdLName decl
header_ = topDeclElem links loc splice [docname] $
ppTyFamHeader summary associated decl unicode qual <+> ppFixities fixities qual
instancesBit
| FamilyDecl { fdInfo = ClosedTypeFamily eqns } <- decl
, not summary
= subEquations qual $ map (ppTyFamEqn . unLoc) eqns
| otherwise
= ppInstances links instances docname unicode qual
-- Individual equation of a closed type family
ppTyFamEqn TyFamEqn { tfe_tycon = n, tfe_rhs = rhs
, tfe_pats = HsWB { hswb_cts = ts }}
= ( ppAppNameTypes (unLoc n) [] (map unLoc ts) unicode qual
<+> equals <+> ppType unicode qual (unLoc rhs)
, Nothing, [] )
--------------------------------------------------------------------------------
-- * Associated Types
--------------------------------------------------------------------------------
ppAssocType :: Bool -> LinksInfo -> DocForDecl DocName -> LFamilyDecl DocName
-> [(DocName, Fixity)] -> Splice -> Unicode -> Qualification -> Html
ppAssocType summ links doc (L loc decl) fixities splice unicode qual =
ppTyFam summ True links [] fixities loc (fst doc) decl splice unicode qual
--------------------------------------------------------------------------------
-- * TyClDecl helpers
--------------------------------------------------------------------------------
-- | Print a type family and its variables
ppFamDeclBinderWithVars :: Bool -> FamilyDecl DocName -> Html
ppFamDeclBinderWithVars summ (FamilyDecl { fdLName = lname, fdTyVars = tvs }) =
ppAppDocNameNames summ (unLoc lname) (tyvarNames tvs)
-- | Print a newtype / data binder and its variables
ppDataBinderWithVars :: Bool -> TyClDecl DocName -> Html
ppDataBinderWithVars summ decl =
ppAppDocNameNames summ (tcdName decl) (tyvarNames $ tcdTyVars decl)
--------------------------------------------------------------------------------
-- * Type applications
--------------------------------------------------------------------------------
-- | Print an application of a DocName and two lists of HsTypes (kinds, types)
ppAppNameTypes :: DocName -> [HsType DocName] -> [HsType DocName]
-> Unicode -> Qualification -> Html
ppAppNameTypes n ks ts unicode qual =
ppTypeApp n ks ts (\p -> ppDocName qual p True) (ppParendType unicode qual)
-- | Print an application of a DocName and a list of Names
ppAppDocNameNames :: Bool -> DocName -> [Name] -> Html
ppAppDocNameNames summ n ns =
ppTypeApp n [] ns ppDN ppTyName
where
ppDN notation = ppBinderFixity notation summ . nameOccName . getName
ppBinderFixity Infix = ppBinderInfix
ppBinderFixity _ = ppBinder
-- | General printing of type applications
ppTypeApp :: DocName -> [a] -> [a] -> (Notation -> DocName -> Html) -> (a -> Html) -> Html
ppTypeApp n [] (t1:t2:rest) ppDN ppT
| operator, not . null $ rest = parens opApp <+> hsep (map ppT rest)
| operator = opApp
where
operator = isNameSym . getName $ n
opApp = ppT t1 <+> ppDN Infix n <+> ppT t2
ppTypeApp n ks ts ppDN ppT = ppDN Prefix n <+> hsep (map ppT $ ks ++ ts)
-------------------------------------------------------------------------------
-- * Contexts
-------------------------------------------------------------------------------
ppLContext, ppLContextNoArrow :: Located (HsContext DocName) -> Unicode
-> Qualification -> Html
ppLContext = ppContext . unLoc
ppLContextNoArrow = ppContextNoArrow . unLoc
ppLContextMaybe :: Located (HsContext DocName) -> Unicode -> Qualification -> Maybe Html
ppLContextMaybe = ppContextNoLocsMaybe . map unLoc . unLoc
ppContextNoArrow :: HsContext DocName -> Unicode -> Qualification -> Html
ppContextNoArrow cxt unicode qual = fromMaybe noHtml $
ppContextNoLocsMaybe (map unLoc cxt) unicode qual
ppContextNoLocs :: [HsType DocName] -> Unicode -> Qualification -> Html
ppContextNoLocs cxt unicode qual = maybe noHtml (<+> darrow unicode) $
ppContextNoLocsMaybe cxt unicode qual
ppContextNoLocsMaybe :: [HsType DocName] -> Unicode -> Qualification -> Maybe Html
ppContextNoLocsMaybe [] _ _ = Nothing
ppContextNoLocsMaybe cxt unicode qual = Just $ ppHsContext cxt unicode qual
ppContext :: HsContext DocName -> Unicode -> Qualification -> Html
ppContext cxt unicode qual = ppContextNoLocs (map unLoc cxt) unicode qual
ppHsContext :: [HsType DocName] -> Unicode -> Qualification-> Html
ppHsContext [] _ _ = noHtml
ppHsContext [p] unicode qual = ppCtxType unicode qual p
ppHsContext cxt unicode qual = parenList (map (ppType unicode qual) cxt)
-------------------------------------------------------------------------------
-- * Class declarations
-------------------------------------------------------------------------------
ppClassHdr :: Bool -> Located [LHsType DocName] -> DocName
-> LHsTyVarBndrs DocName -> [Located ([Located DocName], [Located DocName])]
-> Unicode -> Qualification -> Html
ppClassHdr summ lctxt n tvs fds unicode qual =
keyword "class"
<+> (if not . null . unLoc $ lctxt then ppLContext lctxt unicode qual else noHtml)
<+> ppAppDocNameNames summ n (tyvarNames tvs)
<+> ppFds fds unicode qual
ppFds :: [Located ([Located DocName], [Located DocName])] -> Unicode -> Qualification -> Html
ppFds fds unicode qual =
if null fds then noHtml else
char '|' <+> hsep (punctuate comma (map (fundep . unLoc) fds))
where
fundep (vars1,vars2) = ppVars vars1 <+> arrow unicode <+> ppVars vars2
ppVars = hsep . map ((ppDocName qual Prefix True) . unLoc)
ppShortClassDecl :: Bool -> LinksInfo -> TyClDecl DocName -> SrcSpan
-> [(DocName, DocForDecl DocName)]
-> Splice -> Unicode -> Qualification -> Html
ppShortClassDecl summary links (ClassDecl { tcdCtxt = lctxt, tcdLName = lname, tcdTyVars = tvs
, tcdFDs = fds, tcdSigs = sigs, tcdATs = ats }) loc
subdocs splice unicode qual =
if not (any isVanillaLSig sigs) && null ats
then (if summary then id else topDeclElem links loc splice [nm]) hdr
else (if summary then id else topDeclElem links loc splice [nm]) (hdr <+> keyword "where")
+++ shortSubDecls False
(
[ ppAssocType summary links doc at [] splice unicode qual | at <- ats
, let doc = lookupAnySubdoc (unL $ fdLName $ unL at) subdocs ] ++
-- ToDo: add associated type defaults
[ ppFunSig summary links loc doc names typ [] splice unicode qual
| L _ (TypeSig lnames (L _ typ) _) <- sigs
, let doc = lookupAnySubdoc (head names) subdocs
names = map unLoc lnames ]
-- FIXME: is taking just the first name ok? Is it possible that
-- there are different subdocs for different names in a single
-- type signature?
)
where
hdr = ppClassHdr summary lctxt (unLoc lname) tvs fds unicode qual
nm = unLoc lname
ppShortClassDecl _ _ _ _ _ _ _ _ = error "declaration type not supported by ppShortClassDecl"
ppClassDecl :: Bool -> LinksInfo -> [DocInstance DocName] -> [(DocName, Fixity)]
-> SrcSpan -> Documentation DocName
-> [(DocName, DocForDecl DocName)] -> TyClDecl DocName
-> Splice -> Unicode -> Qualification -> Html
ppClassDecl summary links instances fixities loc d subdocs
decl@(ClassDecl { tcdCtxt = lctxt, tcdLName = lname, tcdTyVars = ltyvars
, tcdFDs = lfds, tcdSigs = lsigs, tcdATs = ats })
splice unicode qual
| summary = ppShortClassDecl summary links decl loc subdocs splice unicode qual
| otherwise = classheader +++ docSection Nothing qual d
+++ minimalBit +++ atBit +++ methodBit +++ instancesBit
where
classheader
| any isVanillaLSig lsigs = topDeclElem links loc splice [nm] (hdr unicode qual <+> keyword "where" <+> fixs)
| otherwise = topDeclElem links loc splice [nm] (hdr unicode qual <+> fixs)
-- Only the fixity relevant to the class header
fixs = ppFixities [ f | f@(n,_) <- fixities, n == unLoc lname ] qual
nm = tcdName decl
hdr = ppClassHdr summary lctxt (unLoc lname) ltyvars lfds
-- ToDo: add assocatied typ defaults
atBit = subAssociatedTypes [ ppAssocType summary links doc at subfixs splice unicode qual
| at <- ats
, let n = unL . fdLName $ unL at
doc = lookupAnySubdoc (unL $ fdLName $ unL at) subdocs
subfixs = [ f | f@(n',_) <- fixities, n == n' ] ]
methodBit = subMethods [ ppFunSig summary links loc doc names typ subfixs splice unicode qual
| L _ (TypeSig lnames (L _ typ) _) <- lsigs
, let doc = lookupAnySubdoc (head names) subdocs
subfixs = [ f | n <- names
, f@(n',_) <- fixities
, n == n' ]
names = map unLoc lnames ]
-- FIXME: is taking just the first name ok? Is it possible that
-- there are different subdocs for different names in a single
-- type signature?
minimalBit = case [ s | L _ (MinimalSig _ s) <- lsigs ] of
-- Miminal complete definition = every shown method
And xs : _ | sort [getName n | Var (L _ n) <- xs] ==
sort [getName n | L _ (TypeSig ns _ _) <- lsigs, L _ n <- ns]
-> noHtml
-- Minimal complete definition = the only shown method
Var (L _ n) : _ | [getName n] ==
[getName n' | L _ (TypeSig ns _ _) <- lsigs, L _ n' <- ns]
-> noHtml
-- Minimal complete definition = nothing
And [] : _ -> subMinimal $ toHtml "Nothing"
m : _ -> subMinimal $ ppMinimal False m
_ -> noHtml
ppMinimal _ (Var (L _ n)) = ppDocName qual Prefix True n
ppMinimal _ (And fs) = foldr1 (\a b -> a+++", "+++b) $ map (ppMinimal True) fs
ppMinimal p (Or fs) = wrap $ foldr1 (\a b -> a+++" | "+++b) $ map (ppMinimal False) fs
where wrap | p = parens | otherwise = id
instancesBit = ppInstances links instances nm unicode qual
ppClassDecl _ _ _ _ _ _ _ _ _ _ _ = error "declaration type not supported by ppShortClassDecl"
ppInstances :: LinksInfo -> [DocInstance DocName] -> DocName -> Unicode -> Qualification -> Html
ppInstances links instances baseName unicode qual
= subInstances qual instName links True baseName (map instDecl instances)
-- force Splice = True to use line URLs
where
instName = getOccString $ getName baseName
instDecl :: DocInstance DocName -> (SubDecl,SrcSpan)
instDecl (L l inst, maybeDoc) = ((instHead inst, maybeDoc, []),l)
instHead (n, ks, ts, ClassInst cs) = ppContextNoLocs cs unicode qual
<+> ppAppNameTypes n ks ts unicode qual
instHead (n, ks, ts, TypeInst rhs) = keyword "type"
<+> ppAppNameTypes n ks ts unicode qual
<+> maybe noHtml (\t -> equals <+> ppType unicode qual t) rhs
instHead (n, ks, ts, DataInst dd) = keyword "data"
<+> ppAppNameTypes n ks ts unicode qual
<+> ppShortDataDecl False True dd unicode qual
lookupAnySubdoc :: Eq id1 => id1 -> [(id1, DocForDecl id2)] -> DocForDecl id2
lookupAnySubdoc n = fromMaybe noDocForDecl . lookup n
-------------------------------------------------------------------------------
-- * Data & newtype declarations
-------------------------------------------------------------------------------
-- TODO: print contexts
ppShortDataDecl :: Bool -> Bool -> TyClDecl DocName -> Unicode -> Qualification -> Html
ppShortDataDecl summary dataInst dataDecl unicode qual
| [] <- cons = dataHeader
| [lcon] <- cons, ResTyH98 <- resTy,
(cHead,cBody,cFoot) <- ppShortConstrParts summary dataInst (unLoc lcon) unicode qual
= (dataHeader <+> equals <+> cHead) +++ cBody +++ cFoot
| ResTyH98 <- resTy = dataHeader
+++ shortSubDecls dataInst (zipWith doConstr ('=':repeat '|') cons)
| otherwise = (dataHeader <+> keyword "where")
+++ shortSubDecls dataInst (map doGADTConstr cons)
where
dataHeader
| dataInst = noHtml
| otherwise = ppDataHeader summary dataDecl unicode qual
doConstr c con = toHtml [c] <+> ppShortConstr summary (unLoc con) unicode qual
doGADTConstr con = ppShortConstr summary (unLoc con) unicode qual
cons = dd_cons (tcdDataDefn dataDecl)
resTy = (con_res . unLoc . head) cons
ppDataDecl :: Bool -> LinksInfo -> [DocInstance DocName] -> [(DocName, Fixity)] ->
[(DocName, DocForDecl DocName)] ->
SrcSpan -> Documentation DocName -> TyClDecl DocName ->
Splice -> Unicode -> Qualification -> Html
ppDataDecl summary links instances fixities subdocs loc doc dataDecl
splice unicode qual
| summary = ppShortDataDecl summary False dataDecl unicode qual
| otherwise = header_ +++ docSection Nothing qual doc +++ constrBit +++ instancesBit
where
docname = tcdName dataDecl
cons = dd_cons (tcdDataDefn dataDecl)
resTy = (con_res . unLoc . head) cons
header_ = topDeclElem links loc splice [docname] $
ppDataHeader summary dataDecl unicode qual <+> whereBit <+> fix
fix = ppFixities (filter (\(n,_) -> n == docname) fixities) qual
whereBit
| null cons = noHtml
| otherwise = case resTy of
ResTyGADT _ _ -> keyword "where"
_ -> noHtml
constrBit = subConstructors qual
[ ppSideBySideConstr subdocs subfixs unicode qual c
| c <- cons
, let subfixs = filter (\(n,_) -> any (\cn -> cn == n)
(map unLoc (con_names (unLoc c)))) fixities
]
instancesBit = ppInstances links instances docname unicode qual
ppShortConstr :: Bool -> ConDecl DocName -> Unicode -> Qualification -> Html
ppShortConstr summary con unicode qual = cHead <+> cBody <+> cFoot
where
(cHead,cBody,cFoot) = ppShortConstrParts summary False con unicode qual
-- returns three pieces: header, body, footer so that header & footer can be
-- incorporated into the declaration
ppShortConstrParts :: Bool -> Bool -> ConDecl DocName -> Unicode -> Qualification -> (Html, Html, Html)
ppShortConstrParts summary dataInst con unicode qual = case con_res con of
ResTyH98 -> case con_details con of
PrefixCon args ->
(header_ unicode qual +++ hsep (ppOcc
: map (ppLParendType unicode qual) args), noHtml, noHtml)
RecCon (L _ fields) ->
(header_ unicode qual +++ ppOcc <+> char '{',
doRecordFields fields,
char '}')
InfixCon arg1 arg2 ->
(header_ unicode qual +++ hsep [ppLParendType unicode qual arg1,
ppOccInfix, ppLParendType unicode qual arg2],
noHtml, noHtml)
ResTyGADT _ resTy -> case con_details con of
-- prefix & infix could use hsConDeclArgTys if it seemed to
-- simplify the code.
PrefixCon args -> (doGADTCon args resTy, noHtml, noHtml)
-- display GADT records with the new syntax,
-- Constr :: (Context) => { field :: a, field2 :: b } -> Ty (a, b)
-- (except each field gets its own line in docs, to match
-- non-GADT records)
RecCon (L _ fields) -> (ppOcc <+> dcolon unicode <+>
ppForAllCon forall_ ltvs lcontext unicode qual <+> char '{',
doRecordFields fields,
char '}' <+> arrow unicode <+> ppLType unicode qual resTy)
InfixCon arg1 arg2 -> (doGADTCon [arg1, arg2] resTy, noHtml, noHtml)
where
doRecordFields fields = shortSubDecls dataInst (map (ppShortField summary unicode qual) (map unLoc fields))
doGADTCon args resTy = ppOcc <+> dcolon unicode <+> hsep [
ppForAllCon forall_ ltvs lcontext unicode qual,
ppLType unicode qual (foldr mkFunTy resTy args) ]
header_ = ppConstrHdr forall_ tyVars context
occ = map (nameOccName . getName . unLoc) $ con_names con
ppOcc = case occ of
[one] -> ppBinder summary one
_ -> hsep (punctuate comma (map (ppBinder summary) occ))
ppOccInfix = case occ of
[one] -> ppBinderInfix summary one
_ -> hsep (punctuate comma (map (ppBinderInfix summary) occ))
ltvs = con_qvars con
tyVars = tyvarNames ltvs
lcontext = con_cxt con
context = unLoc (con_cxt con)
forall_ = con_explicit con
mkFunTy a b = noLoc (HsFunTy a b)
-- ppConstrHdr is for (non-GADT) existentials constructors' syntax
ppConstrHdr :: HsExplicitFlag -> [Name] -> HsContext DocName -> Unicode
-> Qualification -> Html
ppConstrHdr forall_ tvs ctxt unicode qual
= (if null tvs then noHtml else ppForall)
+++
(if null ctxt then noHtml else ppContextNoArrow ctxt unicode qual
<+> darrow unicode +++ toHtml " ")
where
ppForall = case forall_ of
Explicit -> forallSymbol unicode <+> hsep (map (ppName Prefix) tvs) <+> toHtml ". "
Qualified -> noHtml
Implicit -> noHtml
ppSideBySideConstr :: [(DocName, DocForDecl DocName)] -> [(DocName, Fixity)]
-> Unicode -> Qualification -> LConDecl DocName -> SubDecl
ppSideBySideConstr subdocs fixities unicode qual (L _ con) = (decl, mbDoc, fieldPart)
where
decl = case con_res con of
ResTyH98 -> case con_details con of
PrefixCon args ->
hsep ((header_ +++ ppOcc)
: map (ppLParendType unicode qual) args)
<+> fixity
RecCon _ -> header_ +++ ppOcc <+> fixity
InfixCon arg1 arg2 ->
hsep [header_ +++ ppLParendType unicode qual arg1,
ppOccInfix,
ppLParendType unicode qual arg2]
<+> fixity
ResTyGADT _ resTy -> case con_details con of
-- prefix & infix could also use hsConDeclArgTys if it seemed to
-- simplify the code.
PrefixCon args -> doGADTCon args resTy
cd@(RecCon _) -> doGADTCon (hsConDeclArgTys cd) resTy
InfixCon arg1 arg2 -> doGADTCon [arg1, arg2] resTy
fieldPart = case con_details con of
RecCon (L _ fields) -> [doRecordFields fields]
_ -> []
doRecordFields fields = subFields qual
(map (ppSideBySideField subdocs unicode qual) (map unLoc fields))
doGADTCon :: [LHsType DocName] -> Located (HsType DocName) -> Html
doGADTCon args resTy = ppOcc <+> dcolon unicode
<+> hsep [ppForAllCon forall_ ltvs (con_cxt con) unicode qual,
ppLType unicode qual (foldr mkFunTy resTy args) ]
<+> fixity
fixity = ppFixities fixities qual
header_ = ppConstrHdr forall_ tyVars context unicode qual
occ = map (nameOccName . getName . unLoc) $ con_names con
ppOcc = case occ of
[one] -> ppBinder False one
_ -> hsep (punctuate comma (map (ppBinder False) occ))
ppOccInfix = case occ of
[one] -> ppBinderInfix False one
_ -> hsep (punctuate comma (map (ppBinderInfix False) occ))
ltvs = con_qvars con
tyVars = tyvarNames (con_qvars con)
context = unLoc (con_cxt con)
forall_ = con_explicit con
-- don't use "con_doc con", in case it's reconstructed from a .hi file,
-- or also because we want Haddock to do the doc-parsing, not GHC.
mbDoc = lookup (unLoc $ head $ con_names con) subdocs >>=
combineDocumentation . fst
mkFunTy a b = noLoc (HsFunTy a b)
ppSideBySideField :: [(DocName, DocForDecl DocName)] -> Unicode -> Qualification
-> ConDeclField DocName -> SubDecl
ppSideBySideField subdocs unicode qual (ConDeclField names ltype _) =
(hsep (punctuate comma (map ((ppBinder False) . nameOccName . getName . unL) names)) <+> dcolon unicode <+> ppLType unicode qual ltype,
mbDoc,
[])
where
-- don't use cd_fld_doc for same reason we don't use con_doc above
-- Where there is more than one name, they all have the same documentation
mbDoc = lookup (unL $ head names) subdocs >>= combineDocumentation . fst
ppShortField :: Bool -> Unicode -> Qualification -> ConDeclField DocName -> Html
ppShortField summary unicode qual (ConDeclField names ltype _)
= hsep (punctuate comma (map ((ppBinder summary) . nameOccName . getName . unL) names))
<+> dcolon unicode <+> ppLType unicode qual ltype
-- | Print the LHS of a data\/newtype declaration.
-- Currently doesn't handle 'data instance' decls or kind signatures
ppDataHeader :: Bool -> TyClDecl DocName -> Unicode -> Qualification -> Html
ppDataHeader summary decl@(DataDecl { tcdDataDefn =
HsDataDefn { dd_ND = nd
, dd_ctxt = ctxt
, dd_kindSig = ks } })
unicode qual
= -- newtype or data
(case nd of { NewType -> keyword "newtype"; DataType -> keyword "data" })
<+>
-- context
ppLContext ctxt unicode qual <+>
-- T a b c ..., or a :+: b
ppDataBinderWithVars summary decl
<+> case ks of
Nothing -> mempty
Just (L _ x) -> dcolon unicode <+> ppKind unicode qual x
ppDataHeader _ _ _ _ = error "ppDataHeader: illegal argument"
--------------------------------------------------------------------------------
-- * Types and contexts
--------------------------------------------------------------------------------
ppBang :: HsBang -> Html
ppBang HsNoBang = noHtml
ppBang _ = toHtml "!" -- Unpacked args is an implementation detail,
-- so we just show the strictness annotation
tupleParens :: HsTupleSort -> [Html] -> Html
tupleParens HsUnboxedTuple = ubxParenList
tupleParens _ = parenList
--------------------------------------------------------------------------------
-- * Rendering of HsType
--------------------------------------------------------------------------------
pREC_TOP, pREC_CTX, pREC_FUN, pREC_OP, pREC_CON :: Int
pREC_TOP = 0 :: Int -- type in ParseIface.y in GHC
pREC_CTX = 1 :: Int -- Used for single contexts, eg. ctx => type
-- (as opposed to (ctx1, ctx2) => type)
pREC_FUN = 2 :: Int -- btype in ParseIface.y in GHC
-- Used for LH arg of (->)
pREC_OP = 3 :: Int -- Used for arg of any infix operator
-- (we don't keep their fixities around)
pREC_CON = 4 :: Int -- Used for arg of type applicn:
-- always parenthesise unless atomic
maybeParen :: Int -- Precedence of context
-> Int -- Precedence of top-level operator
-> Html -> Html -- Wrap in parens if (ctxt >= op)
maybeParen ctxt_prec op_prec p | ctxt_prec >= op_prec = parens p
| otherwise = p
ppLType, ppLParendType, ppLFunLhType :: Unicode -> Qualification
-> Located (HsType DocName) -> Html
ppLType unicode qual y = ppType unicode qual (unLoc y)
ppLParendType unicode qual y = ppParendType unicode qual (unLoc y)
ppLFunLhType unicode qual y = ppFunLhType unicode qual (unLoc y)
ppType, ppCtxType, ppParendType, ppFunLhType :: Unicode -> Qualification
-> HsType DocName -> Html
ppType unicode qual ty = ppr_mono_ty pREC_TOP ty unicode qual
ppCtxType unicode qual ty = ppr_mono_ty pREC_CTX ty unicode qual
ppParendType unicode qual ty = ppr_mono_ty pREC_CON ty unicode qual
ppFunLhType unicode qual ty = ppr_mono_ty pREC_FUN ty unicode qual
ppLKind :: Unicode -> Qualification -> LHsKind DocName -> Html
ppLKind unicode qual y = ppKind unicode qual (unLoc y)
ppKind :: Unicode -> Qualification -> HsKind DocName -> Html
ppKind unicode qual ki = ppr_mono_ty pREC_TOP ki unicode qual
-- Drop top-level for-all type variables in user style
-- since they are implicit in Haskell
ppForAllCon :: HsExplicitFlag -> LHsTyVarBndrs DocName
-> Located (HsContext DocName) -> Unicode -> Qualification -> Html
ppForAllCon expl tvs cxt unicode qual =
forall_part <+> ppLContext cxt unicode qual
where
forall_part = ppLTyVarBndrs expl tvs unicode qual
ppLTyVarBndrs :: HsExplicitFlag -> LHsTyVarBndrs DocName
-> Unicode -> Qualification
-> Html
ppLTyVarBndrs expl tvs unicode _qual
| show_forall = hsep (forallSymbol unicode : ppTyVars tvs) +++ dot
| otherwise = noHtml
where
show_forall = not (null (hsQTvBndrs tvs)) && is_explicit
is_explicit = case expl of {Explicit -> True; Implicit -> False; Qualified -> False}
ppr_mono_lty :: Int -> LHsType DocName -> Unicode -> Qualification -> Html
ppr_mono_lty ctxt_prec ty = ppr_mono_ty ctxt_prec (unLoc ty)
ppr_mono_ty :: Int -> HsType DocName -> Unicode -> Qualification -> Html
ppr_mono_ty ctxt_prec (HsForAllTy expl extra tvs ctxt ty) unicode qual
= maybeParen ctxt_prec pREC_FUN $ ppForAllCon expl tvs ctxt' unicode qual
<+> ppr_mono_lty pREC_TOP ty unicode qual
where ctxt' = case extra of
Just loc -> (++ [L loc HsWildcardTy]) `fmap` ctxt
Nothing -> ctxt
-- UnicodeSyntax alternatives
ppr_mono_ty _ (HsTyVar name) True _
| getOccString (getName name) == "*" = toHtml "★"
| getOccString (getName name) == "(->)" = toHtml "(→)"
ppr_mono_ty _ (HsBangTy b ty) u q = ppBang b +++ ppLParendType u q ty
ppr_mono_ty _ (HsTyVar name) _ q = ppDocName q Prefix True name
ppr_mono_ty ctxt_prec (HsFunTy ty1 ty2) u q = ppr_fun_ty ctxt_prec ty1 ty2 u q
ppr_mono_ty _ (HsTupleTy con tys) u q = tupleParens con (map (ppLType u q) tys)
ppr_mono_ty _ (HsKindSig ty kind) u q =
parens (ppr_mono_lty pREC_TOP ty u q <+> dcolon u <+> ppLKind u q kind)
ppr_mono_ty _ (HsListTy ty) u q = brackets (ppr_mono_lty pREC_TOP ty u q)
ppr_mono_ty _ (HsPArrTy ty) u q = pabrackets (ppr_mono_lty pREC_TOP ty u q)
ppr_mono_ty ctxt_prec (HsIParamTy n ty) u q =
maybeParen ctxt_prec pREC_CTX $ ppIPName n <+> dcolon u <+> ppr_mono_lty pREC_TOP ty u q
ppr_mono_ty _ (HsSpliceTy {}) _ _ = error "ppr_mono_ty HsSpliceTy"
ppr_mono_ty _ (HsQuasiQuoteTy {}) _ _ = error "ppr_mono_ty HsQuasiQuoteTy"
ppr_mono_ty _ (HsRecTy {}) _ _ = error "ppr_mono_ty HsRecTy"
ppr_mono_ty _ (HsCoreTy {}) _ _ = error "ppr_mono_ty HsCoreTy"
ppr_mono_ty _ (HsExplicitListTy _ tys) u q = quote $ brackets $ hsep $ punctuate comma $ map (ppLType u q) tys
ppr_mono_ty _ (HsExplicitTupleTy _ tys) u q = quote $ parenList $ map (ppLType u q) tys
ppr_mono_ty _ (HsWrapTy {}) _ _ = error "ppr_mono_ty HsWrapTy"
ppr_mono_ty ctxt_prec (HsEqTy ty1 ty2) unicode qual
= maybeParen ctxt_prec pREC_CTX $
ppr_mono_lty pREC_OP ty1 unicode qual <+> char '~' <+> ppr_mono_lty pREC_OP ty2 unicode qual
ppr_mono_ty ctxt_prec (HsAppTy fun_ty arg_ty) unicode qual
= maybeParen ctxt_prec pREC_CON $
hsep [ppr_mono_lty pREC_FUN fun_ty unicode qual, ppr_mono_lty pREC_CON arg_ty unicode qual]
ppr_mono_ty ctxt_prec (HsOpTy ty1 (_, op) ty2) unicode qual
= maybeParen ctxt_prec pREC_FUN $
ppr_mono_lty pREC_OP ty1 unicode qual <+> ppr_op <+> ppr_mono_lty pREC_OP ty2 unicode qual
where
ppr_op = ppLDocName qual Infix op
ppr_mono_ty ctxt_prec (HsParTy ty) unicode qual
-- = parens (ppr_mono_lty pREC_TOP ty)
= ppr_mono_lty ctxt_prec ty unicode qual
ppr_mono_ty ctxt_prec (HsDocTy ty _) unicode qual
= ppr_mono_lty ctxt_prec ty unicode qual
ppr_mono_ty _ HsWildcardTy _ _ = char '_'
ppr_mono_ty _ (HsNamedWildcardTy name) _ q = ppDocName q Prefix True name
ppr_mono_ty _ (HsTyLit n) _ _ = ppr_tylit n
ppr_tylit :: HsTyLit -> Html
ppr_tylit (HsNumTy _ n) = toHtml (show n)
ppr_tylit (HsStrTy _ s) = toHtml (show s)
ppr_fun_ty :: Int -> LHsType DocName -> LHsType DocName -> Unicode -> Qualification -> Html
ppr_fun_ty ctxt_prec ty1 ty2 unicode qual
= let p1 = ppr_mono_lty pREC_FUN ty1 unicode qual
p2 = ppr_mono_lty pREC_TOP ty2 unicode qual
in
maybeParen ctxt_prec pREC_FUN $
hsep [p1, arrow unicode <+> p2]
| JPMoresmau/haddock | haddock-api/src/Haddock/Backends/Xhtml/Decl.hs | bsd-2-clause | 39,178 | 0 | 22 | 10,315 | 11,659 | 5,907 | 5,752 | 612 | 9 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QTcpServer_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:31
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Network.QTcpServer_h (
QhasPendingConnections_h(..)
,QnextPendingConnection_h(..)
) where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Network_h
import Qtc.ClassTypes.Network
import Foreign.Marshal.Array
instance QunSetUserMethod (QTcpServer ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTcpServer_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QTcpServer_unSetUserMethod" qtc_QTcpServer_unSetUserMethod :: Ptr (TQTcpServer a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QTcpServerSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTcpServer_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QTcpServer ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTcpServer_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QTcpServerSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTcpServer_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QTcpServer ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTcpServer_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QTcpServerSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTcpServer_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QTcpServer ()) (QTcpServer x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QTcpServer setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QTcpServer_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTcpServer_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTcpServer x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTcpServer_setUserMethod" qtc_QTcpServer_setUserMethod :: Ptr (TQTcpServer a) -> CInt -> Ptr (Ptr (TQTcpServer x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QTcpServer :: (Ptr (TQTcpServer x0) -> IO ()) -> IO (FunPtr (Ptr (TQTcpServer x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QTcpServer_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QTcpServerSc a) (QTcpServer x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QTcpServer setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QTcpServer_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTcpServer_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTcpServer x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QTcpServer ()) (QTcpServer x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QTcpServer setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QTcpServer_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTcpServer_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTcpServer x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTcpServer_setUserMethodVariant" qtc_QTcpServer_setUserMethodVariant :: Ptr (TQTcpServer a) -> CInt -> Ptr (Ptr (TQTcpServer x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QTcpServer :: (Ptr (TQTcpServer x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQTcpServer x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QTcpServer_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QTcpServerSc a) (QTcpServer x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QTcpServer setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QTcpServer_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTcpServer_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTcpServer x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QTcpServer ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QTcpServer_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QTcpServer_unSetHandler" qtc_QTcpServer_unSetHandler :: Ptr (TQTcpServer a) -> CWString -> IO (CBool)
instance QunSetHandler (QTcpServerSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QTcpServer_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QTcpServer ()) (QTcpServer x0 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTcpServer1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTcpServer1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTcpServer_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTcpServer x0) -> IO (CBool)
setHandlerWrapper x0
= do x0obj <- qTcpServerFromPtr x0
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTcpServer_setHandler1" qtc_QTcpServer_setHandler1 :: Ptr (TQTcpServer a) -> CWString -> Ptr (Ptr (TQTcpServer x0) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTcpServer1 :: (Ptr (TQTcpServer x0) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTcpServer x0) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QTcpServer1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTcpServerSc a) (QTcpServer x0 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTcpServer1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTcpServer1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTcpServer_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTcpServer x0) -> IO (CBool)
setHandlerWrapper x0
= do x0obj <- qTcpServerFromPtr x0
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
class QhasPendingConnections_h x0 x1 where
hasPendingConnections_h :: x0 -> x1 -> IO (Bool)
instance QhasPendingConnections_h (QTcpServer ()) (()) where
hasPendingConnections_h x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTcpServer_hasPendingConnections cobj_x0
foreign import ccall "qtc_QTcpServer_hasPendingConnections" qtc_QTcpServer_hasPendingConnections :: Ptr (TQTcpServer a) -> IO CBool
instance QhasPendingConnections_h (QTcpServerSc a) (()) where
hasPendingConnections_h x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTcpServer_hasPendingConnections cobj_x0
instance QsetHandler (QTcpServer ()) (QTcpServer x0 -> IO (QObject t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTcpServer2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTcpServer2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTcpServer_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTcpServer x0) -> IO (Ptr (TQObject t0))
setHandlerWrapper x0
= do x0obj <- qTcpServerFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTcpServer_setHandler2" qtc_QTcpServer_setHandler2 :: Ptr (TQTcpServer a) -> CWString -> Ptr (Ptr (TQTcpServer x0) -> IO (Ptr (TQObject t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTcpServer2 :: (Ptr (TQTcpServer x0) -> IO (Ptr (TQObject t0))) -> IO (FunPtr (Ptr (TQTcpServer x0) -> IO (Ptr (TQObject t0))))
foreign import ccall "wrapper" wrapSetHandler_QTcpServer2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTcpServerSc a) (QTcpServer x0 -> IO (QObject t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTcpServer2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTcpServer2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTcpServer_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTcpServer x0) -> IO (Ptr (TQObject t0))
setHandlerWrapper x0
= do x0obj <- qTcpServerFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
class QnextPendingConnection_h x0 x1 where
nextPendingConnection_h :: x0 -> x1 -> IO (QTcpSocket ())
instance QnextPendingConnection_h (QTcpServer ()) (()) where
nextPendingConnection_h x0 ()
= withQTcpSocketResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTcpServer_nextPendingConnection cobj_x0
foreign import ccall "qtc_QTcpServer_nextPendingConnection" qtc_QTcpServer_nextPendingConnection :: Ptr (TQTcpServer a) -> IO (Ptr (TQTcpSocket ()))
instance QnextPendingConnection_h (QTcpServerSc a) (()) where
nextPendingConnection_h x0 ()
= withQTcpSocketResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTcpServer_nextPendingConnection cobj_x0
instance QsetHandler (QTcpServer ()) (QTcpServer x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTcpServer3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTcpServer3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTcpServer_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTcpServer x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qTcpServerFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTcpServer_setHandler3" qtc_QTcpServer_setHandler3 :: Ptr (TQTcpServer a) -> CWString -> Ptr (Ptr (TQTcpServer x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTcpServer3 :: (Ptr (TQTcpServer x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTcpServer x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QTcpServer3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTcpServerSc a) (QTcpServer x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTcpServer3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTcpServer3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTcpServer_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTcpServer x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qTcpServerFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QTcpServer ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTcpServer_event cobj_x0 cobj_x1
foreign import ccall "qtc_QTcpServer_event" qtc_QTcpServer_event :: Ptr (TQTcpServer a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QTcpServerSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTcpServer_event cobj_x0 cobj_x1
instance QsetHandler (QTcpServer ()) (QTcpServer x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTcpServer4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTcpServer4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTcpServer_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTcpServer x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qTcpServerFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTcpServer_setHandler4" qtc_QTcpServer_setHandler4 :: Ptr (TQTcpServer a) -> CWString -> Ptr (Ptr (TQTcpServer x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTcpServer4 :: (Ptr (TQTcpServer x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTcpServer x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QTcpServer4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTcpServerSc a) (QTcpServer x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTcpServer4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTcpServer4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTcpServer_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTcpServer x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qTcpServerFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QeventFilter_h (QTcpServer ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTcpServer_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTcpServer_eventFilter" qtc_QTcpServer_eventFilter :: Ptr (TQTcpServer a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QTcpServerSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTcpServer_eventFilter cobj_x0 cobj_x1 cobj_x2
| keera-studios/hsQt | Qtc/Network/QTcpServer_h.hs | bsd-2-clause | 24,198 | 0 | 18 | 5,581 | 7,934 | 3,780 | 4,154 | -1 | -1 |
-- | Parser for ECMAScript 3.
{-# LANGUAGE FlexibleContexts #-}
module Language.ECMAScript3.Parser
(parse
, Parser
, expression
, statement
, program
, parseFromString
, parseFromFile
-- old and deprecated
, parseScriptFromString
, parseJavaScriptFromFile
, parseScript
, parseExpression
, parseString
, ParsedStatement
, ParsedExpression
, parseSimpleExpr'
, parseBlockStmt
, parseStatement
, StatementParser
, ExpressionParser
, assignExpr
, parseObjectLit
) where
import Language.ECMAScript3.Lexer hiding (identifier)
import qualified Language.ECMAScript3.Lexer as Lexer
import Language.ECMAScript3.Parser.State
import Language.ECMAScript3.Parser.Type
import Language.ECMAScript3.Syntax hiding (pushLabel)
import Language.ECMAScript3.Syntax.Annotations
import Data.Default.Class
import Text.Parsec hiding (parse)
import Text.Parsec.Expr
import Control.Monad(liftM,liftM2)
import Control.Monad.Trans (MonadIO,liftIO)
import Numeric(readDec,readOct,readHex, readFloat)
import Data.Char
import Control.Monad.Identity
import Data.Maybe (isJust, isNothing, fromMaybe)
import Control.Monad.Error.Class
import Control.Applicative ((<$>), (<*>))
{-# DEPRECATED ParsedStatement, ParsedExpression, StatementParser,
ExpressionParser
"These type aliases will be hidden in the next version" #-}
{-# DEPRECATED parseSimpleExpr', parseBlockStmt, parseObjectLit
"These parsers will be hidden in the next version" #-}
{-# DEPRECATED assignExpr, parseExpression "Use 'expression' instead" #-}
{-# DEPRECATED parseStatement "Use 'statement' instead" #-}
{-# DEPRECATED parseScript "Use 'program' instead" #-}
{-# DEPRECATED parseScriptFromString, parseString "Use 'parseFromString' instead" #-}
{-# DEPRECATED parseJavaScriptFromFile "Use 'parseFromFile' instead" #-}
-- We parameterize the parse tree over source-locations.
type ParsedStatement = Statement SourcePos
type ParsedExpression = Expression SourcePos
-- These parsers can store some arbitrary state
type StatementParser s = Parser s ParsedStatement
type ExpressionParser s = Parser s ParsedExpression
initialParserState :: ParserState
initialParserState = []
-- | checks if the label is not yet on the stack, if it is -- throws
-- an error; otherwise it pushes it onto the stack
pushLabel :: String -> Parser s ()
pushLabel lab = do labs <- getState
pos <- getPosition
if lab `elem` labs
then fail $ "Duplicate label at " ++ show pos
else putState (lab:labs)
popLabel :: Parser s ()
popLabel = modifyState safeTail
where safeTail [] = []
safeTail (_:xs) = xs
clearLabels :: ParserState -> ParserState
clearLabels _ = []
withFreshLabelStack :: Parser s a -> Parser s a
withFreshLabelStack p = do oldState <- getState
putState $ clearLabels oldState
a <- p
putState oldState
return a
identifier :: Stream s Identity Char => Parser s (Id SourcePos)
identifier =
liftM2 Id getPosition Lexer.identifier
--{{{ Statements
-- Keep in mind that Token.reserved parsers (exported from the lexer) do not
-- consume any input on failure. Note that all statements (expect for labelled
-- and expression statements) begin with a reserved-word. If we fail to parse
-- this reserved-word, no input is consumed. Hence, we can have the massive or
-- block that is parseExpression. Note that if the reserved-word is parsed, it
-- must be whatever statement the reserved-word indicates. If we fail after the
-- reserved-word, we truly have a syntax error. Since input has been consumed,
-- <|> will not try its alternate in parseExpression, and we will fail.
parseIfStmt:: Stream s Identity Char => StatementParser s
parseIfStmt = do
pos <- getPosition
reserved "if"
test <- parseParenExpr <?> "parenthesized test-expression in if statement"
consequent <- parseStatement <?> "true-branch of if statement"
optional semi -- TODO: in spec?
((do reserved "else"
alternate <- parseStatement
return $ IfStmt pos test consequent alternate)
<|> return (IfSingleStmt pos test consequent))
parseSwitchStmt :: Stream s Identity Char => StatementParser s
parseSwitchStmt =
let parseDefault = do
pos <- getPosition
reserved "default"
colon
statements <- many parseStatement
return (CaseDefault pos statements)
parseCase = do
pos <- getPosition
reserved "case"
condition <- parseListExpr
colon
actions <- many parseStatement
return (CaseClause pos condition actions)
isCaseDefault (CaseDefault _ _) = True
isCaseDefault _ = False
checkClauses cs = case filter isCaseDefault cs of
(_:c:_) -> fail $ "duplicate default clause in switch statement at " ++
show (getAnnotation c)
_ -> return ()
in do pos <- getPosition
reserved "switch"
test <- parseParenExpr
clauses <- braces $ many $ parseDefault <|> parseCase
checkClauses clauses
return (SwitchStmt pos test clauses)
parseWhileStmt:: Stream s Identity Char => StatementParser s
parseWhileStmt = do
pos <- getPosition
reserved "while"
test <- parseParenExpr <?> "parenthesized test-expression in while loop"
body <- parseStatement
return (WhileStmt pos test body)
parseDoWhileStmt:: Stream s Identity Char => StatementParser s
parseDoWhileStmt = do
pos <- getPosition
reserved "do"
body <- parseStatement
reserved "while" <?> "while at the end of a do block"
test <- parseParenExpr <?> "parenthesized test-expression in do loop"
optional semi
return (DoWhileStmt pos body test)
parseContinueStmt:: Stream s Identity Char => StatementParser s
parseContinueStmt = do
pos <- getPosition
reserved "continue"
pos' <- getPosition
-- Ensure that the identifier is on the same line as 'continue.'
id <- if sourceLine pos == sourceLine pos'
then liftM Just identifier <|> return Nothing
else return Nothing
optional semi
return $ ContinueStmt pos id
parseBreakStmt:: Stream s Identity Char => StatementParser s
parseBreakStmt = do
pos <- getPosition
reserved "break"
pos' <- getPosition
-- Ensure that the identifier is on the same line as 'break.'
id <- if sourceLine pos == sourceLine pos'
then liftM Just identifier <|> return Nothing
else return Nothing
optional semi
return $ BreakStmt pos id
parseBlockStmt:: Stream s Identity Char => StatementParser s
parseBlockStmt = do
pos <- getPosition
statements <- braces (many parseStatement)
return (BlockStmt pos statements)
parseEmptyStmt:: Stream s Identity Char => StatementParser s
parseEmptyStmt = do
pos <- getPosition
semi
return (EmptyStmt pos)
parseLabelledStmt:: Stream s Identity Char => StatementParser s
parseLabelledStmt = do
pos <- getPosition
-- Lookahead for the colon. If we don't see it, we are parsing an identifier
-- for an expression statement.
label <- try (do label <- identifier
colon
return label)
pushLabel $ unId label
statement <- parseStatement
popLabel
return (LabelledStmt pos label statement)
parseExpressionStmt:: Stream s Identity Char => StatementParser s
parseExpressionStmt = do
pos <- getPosition
expr <- parseExpression -- TODO: spec 12.4?
optional semi
return $ ExprStmt pos expr
parseForInStmt:: Stream s Identity Char => StatementParser s
parseForInStmt =
let parseInit = (reserved "var" >> liftM ForInVar identifier)
<|> liftM ForInLVal lvalue
in do pos <- getPosition
-- Lookahead, so that we don't clash with parseForStmt
(init,expr) <- try $ do reserved "for"
parens $ do init <- parseInit
reserved "in"
expr <- parseExpression
return (init,expr)
body <- parseStatement
return $ ForInStmt pos init expr body
parseForStmt:: Stream s Identity Char => StatementParser s
parseForStmt =
let parseInit = (reserved "var" >> liftM VarInit (parseVarDecl `sepBy` comma))
<|> liftM ExprInit parseListExpr
<|> return NoInit
in do pos <- getPosition
reserved "for"
reservedOp "("
init <- parseInit
semi
test <- optionMaybe parseExpression
semi
iter <- optionMaybe parseExpression
reservedOp ")" <?> "closing paren"
stmt <- parseStatement
return $ ForStmt pos init test iter stmt
parseTryStmt:: Stream s Identity Char => StatementParser s
parseTryStmt =
let parseCatchClause = do pos <- getPosition
reserved "catch"
id <- parens identifier
stmt <- parseStatement
return $ CatchClause pos id stmt
in do reserved "try"
pos <- getPosition
guarded <- parseStatement
mCatch <- optionMaybe parseCatchClause
mFinally <- optionMaybe $ reserved "finally" >> parseStatement
-- the spec requires at least a catch or a finally block to
-- be present
if isJust mCatch || isJust mFinally
then return $ TryStmt pos guarded mCatch mFinally
else fail $ "A try statement should have at least a catch\
\ or a finally block, at " ++ show pos
parseThrowStmt:: Stream s Identity Char => StatementParser s
parseThrowStmt = do
pos <- getPosition
reserved "throw"
expr <- parseExpression
optional semi
return (ThrowStmt pos expr)
parseReturnStmt:: Stream s Identity Char => StatementParser s
parseReturnStmt = do
pos <- getPosition
reserved "return"
expr <- optionMaybe parseListExpr
optional semi
return (ReturnStmt pos expr)
parseWithStmt:: Stream s Identity Char => StatementParser s
parseWithStmt = do
pos <- getPosition
reserved "with"
context <- parseParenExpr
stmt <- parseStatement
return (WithStmt pos context stmt)
parseVarDecl :: Stream s Identity Char => Parser s (VarDecl SourcePos)
parseVarDecl = do
pos <- getPosition
id <- identifier
init <- (reservedOp "=" >> liftM Just assignExpr) <|> return Nothing
return (VarDecl pos id init)
parseVarDeclStmt:: Stream s Identity Char => StatementParser s
parseVarDeclStmt = do
pos <- getPosition
reserved "var"
decls <- parseVarDecl `sepBy` comma
optional semi
return (VarDeclStmt pos decls)
parseFunctionStmt:: Stream s Identity Char => StatementParser s
parseFunctionStmt = do
pos <- getPosition
name <- try (reserved "function" >> identifier) -- ambiguity with FuncExpr
args <- parens (identifier `sepBy` comma)
-- label sets don't cross function boundaries
BlockStmt _ body <- withFreshLabelStack parseBlockStmt <?>
"function body in { ... }"
return (FunctionStmt pos name args body)
parseStatement :: Stream s Identity Char => StatementParser s
parseStatement = parseIfStmt <|> parseSwitchStmt <|> parseWhileStmt
<|> parseDoWhileStmt <|> parseContinueStmt <|> parseBreakStmt
<|> parseBlockStmt <|> parseEmptyStmt <|> parseForInStmt <|> parseForStmt
<|> parseTryStmt <|> parseThrowStmt <|> parseReturnStmt <|> parseWithStmt
<|> parseVarDeclStmt <|> parseFunctionStmt
-- labelled, expression and the error message always go last, in this order
<|> parseLabelledStmt <|> parseExpressionStmt <?> "statement"
-- | The parser that parses a single ECMAScript statement
statement :: Stream s Identity Char => Parser s (Statement SourcePos)
statement = parseStatement
--}}}
--{{{ Expressions
-- References used to construct this stuff:
-- + http://developer.mozilla.org/en/docs/
-- Core_JavaScript_1.5_Reference:Operators:Operator_Precedence
-- + http://www.mozilla.org/js/language/grammar14.html
--
-- Aren't expression tables nice? Well, we can't quite use them, because of
-- JavaScript's ternary (?:) operator. We have to use two expression tables.
-- We use one expression table for the assignment operators that bind looser
-- than ?: (assignTable). The terms of assignTable are ternary expressions
-- (parseTernaryExpr). parseTernaryExpr left-factors the left-recursive
-- production for ?:, and is defined over the second expression table,
-- exprTable, which consists of operators that bind tighter than ?:. The terms
-- of exprTable are atomic expressions, parenthesized expressions, functions and
-- array references.
--{{{ Primary expressions
parseThisRef:: Stream s Identity Char => ExpressionParser s
parseThisRef = do
pos <- getPosition
reserved "this"
return (ThisRef pos)
parseNullLit:: Stream s Identity Char => ExpressionParser s
parseNullLit = do
pos <- getPosition
reserved "null"
return (NullLit pos)
parseBoolLit:: Stream s Identity Char => ExpressionParser s
parseBoolLit = do
pos <- getPosition
let parseTrueLit = reserved "true" >> return (BoolLit pos True)
parseFalseLit = reserved "false" >> return (BoolLit pos False)
parseTrueLit <|> parseFalseLit
parseVarRef:: Stream s Identity Char => ExpressionParser s
parseVarRef = liftM2 VarRef getPosition identifier
parseArrayLit:: Stream s Identity Char => ExpressionParser s
parseArrayLit = liftM2 ArrayLit getPosition (squares (assignExpr `sepEndBy` comma))
parseFuncExpr :: Stream s Identity Char => ExpressionParser s
parseFuncExpr = do
pos <- getPosition
reserved "function"
name <- optionMaybe identifier
args <- parens (identifier `sepBy` comma)
-- labels don't cross function boundaries
BlockStmt _ body <- withFreshLabelStack parseBlockStmt
return $ FuncExpr pos name args body
--{{{ parsing strings
escapeChars =
[('\'','\''),('\"','\"'),('\\','\\'),('b','\b'),('f','\f'),('n','\n'),
('r','\r'),('t','\t'),('v','\v'),('/','/'),(' ',' '),('0','\0')]
allEscapes:: String
allEscapes = map fst escapeChars
parseEscapeChar :: Stream s Identity Char => Parser s Char
parseEscapeChar = do
c <- oneOf allEscapes
let (Just c') = lookup c escapeChars -- will succeed due to line above
return c'
parseAsciiHexChar :: Stream s Identity Char => Parser s Char
parseAsciiHexChar = do
char 'x'
d1 <- hexDigit
d2 <- hexDigit
return ((chr.fst.head.readHex) (d1:d2:""))
parseUnicodeHexChar :: Stream s Identity Char => Parser s Char
parseUnicodeHexChar = do
char 'u'
liftM (chr.fst.head.readHex)
(sequence [hexDigit,hexDigit,hexDigit,hexDigit])
isWhitespace ch = ch `elem` " \t"
-- The endWith argument is either single-quote or double-quote, depending on how
-- we opened the string.
parseStringLit' endWith =
(char endWith >> return "") <|>
(do try (string "\\'")
cs <- parseStringLit' endWith
return $ "'" ++ cs) <|>
(do char '\\'
c <- parseEscapeChar <|> parseAsciiHexChar <|> parseUnicodeHexChar <|>
char '\r' <|> char '\n'
cs <- parseStringLit' endWith
if c == '\r' || c == '\n'
then return (c:dropWhile isWhitespace cs)
else return (c:cs)) <|>
liftM2 (:) anyChar (parseStringLit' endWith)
parseStringLit:: Stream s Identity Char => ExpressionParser s
parseStringLit = do
pos <- getPosition
-- parseStringLit' takes as an argument the quote-character that opened the
-- string.
str <- lexeme $ (char '\'' >>= parseStringLit') <|> (char '\"' >>= parseStringLit')
-- CRUCIAL: Parsec.Token parsers expect to find their token on the first
-- character, and read whitespaces beyond their tokens. Without 'lexeme'
-- above, expressions like:
-- var s = "string" ;
-- do not parse.
return $ StringLit pos str
--}}}
parseRegexpLit:: Stream s Identity Char => ExpressionParser s
parseRegexpLit = do
let parseFlags = do
flags <- many (oneOf "mgi")
return $ \f -> f ('g' `elem` flags) ('i' `elem` flags)
let parseEscape :: Stream s Identity Char => Parser s Char
parseEscape = char '\\' >> anyChar
let parseChar :: Stream s Identity Char => Parser s Char
parseChar = noneOf "/"
let parseRe = (char '/' >> return "") <|>
(do char '\\'
ch <- anyChar -- TODO: too lenient
rest <- parseRe
return ('\\':ch:rest)) <|>
liftM2 (:) anyChar parseRe
pos <- getPosition
char '/'
notFollowedBy $ char '/'
pat <- parseRe --many1 parseChar
flags <- parseFlags
spaces -- crucial for Parsec.Token parsers
return $ flags (RegexpLit pos pat)
parseObjectLit:: Stream s Identity Char => ExpressionParser s
parseObjectLit =
let parseProp = do
-- Parses a string, identifier or integer as the property name. I
-- apologize for the abstruse style, but it really does make the code
-- much shorter.
name <- liftM (\(StringLit p s) -> PropString p s) parseStringLit
<|> liftM2 PropId getPosition identifier
<|> liftM2 PropNum getPosition (parseNumber >>= toInt)
colon
val <- assignExpr
return (name,val)
toInt eid = case eid of
Left i -> return $ fromIntegral i
-- Note, the spec actually allows floats in property names.
-- This is left for legacy reasons and will be fixed in 1.0
Right d-> unexpected "Floating point number in property name"
in do pos <- getPosition
props <- braces (parseProp `sepEndBy` comma) <?> "object literal"
return $ ObjectLit pos props
--{{{ Parsing numbers. From pg. 17-18 of ECMA-262.
hex :: Stream s Identity Char => Parser s (Either Int Double)
hex = do s <- hexIntLit
Left <$> wrapReadS Numeric.readHex s
decimal :: Stream s Identity Char => Parser s (Either Int Double)
decimal = do (s, i) <- decLit
if i then Left <$> wrapReadS readDec s
else Right <$> wrapReadS readFloat s
wrapReadS :: ReadS a -> String -> Parser s a
wrapReadS r s = case r s of
[(a, "")] -> return a
_ -> fail "Bad parse: could not convert a string to a Haskell value"
parseNumber:: Stream s Identity Char => Parser s (Either Int Double)
parseNumber = hex <|> decimal
parseNumLit:: Stream s Identity Char => ExpressionParser s
parseNumLit = do pos <- getPosition
eid <- lexeme $ parseNumber
notFollowedBy identifierStart <?> "whitespace"
return $ case eid of
Left i -> IntLit pos i
Right d-> NumLit pos d
------------------------------------------------------------------------------
-- Position Helper
------------------------------------------------------------------------------
withPos cstr p = do { pos <- getPosition; e <- p; return $ cstr pos e }
-------------------------------------------------------------------------------
-- Compound Expression Parsers
-------------------------------------------------------------------------------
dotRef e = (reservedOp "." >> withPos cstr identifier) <?> "property.ref"
where cstr pos = DotRef pos e
funcApp e = parens (withPos cstr (assignExpr `sepBy` comma))
<?>"(function application)"
where cstr pos = CallExpr pos e
bracketRef e = brackets (withPos cstr parseExpression) <?> "[property-ref]"
where cstr pos = BracketRef pos e
-------------------------------------------------------------------------------
-- Expression Parsers
-------------------------------------------------------------------------------
parseParenExpr:: Stream s Identity Char => ExpressionParser s
parseParenExpr = parens parseListExpr
-- everything above expect functions
parseExprForNew :: Stream s Identity Char => ExpressionParser s
parseExprForNew = parseThisRef <|> parseNullLit <|> parseBoolLit <|> parseStringLit
<|> parseArrayLit <|> parseParenExpr <|> parseNewExpr <|> parseNumLit
<|> parseRegexpLit <|> parseObjectLit <|> parseVarRef
-- all the expression parsers defined above
parseSimpleExpr' :: Stream s Identity Char => ExpressionParser s
parseSimpleExpr' = parseThisRef <|> parseNullLit <|> parseBoolLit
<|> parseStringLit <|> parseArrayLit <|> parseParenExpr
<|> parseFuncExpr <|> parseNumLit <|> parseRegexpLit <|> parseObjectLit
<|> parseVarRef
parseNewExpr :: Stream s Identity Char => ExpressionParser s
parseNewExpr =
(do pos <- getPosition
reserved "new"
constructor <- parseSimpleExprForNew Nothing -- right-associativity
arguments <- try (parens (assignExpr `sepBy` comma)) <|> return []
return (NewExpr pos constructor arguments)) <|>
parseSimpleExpr'
parseSimpleExpr (Just e) = ((dotRef e <|> funcApp e <|> bracketRef e) >>=
parseSimpleExpr . Just)
<|> return e
parseSimpleExpr Nothing = do
e <- parseNewExpr <?> "expression (3)"
parseSimpleExpr (Just e)
parseSimpleExprForNew :: Stream s Identity Char
=>(Maybe ParsedExpression) -> ExpressionParser s
parseSimpleExprForNew (Just e) = ((dotRef e <|> bracketRef e) >>=
parseSimpleExprForNew . Just)
<|> return e
parseSimpleExprForNew Nothing = do
e <- parseNewExpr <?> "expression (3)"
parseSimpleExprForNew (Just e)
--}}}
makeInfixExpr str constr = Infix parser AssocLeft where
parser:: Stream s Identity Char
=> Parser s (Expression SourcePos -> Expression SourcePos -> Expression SourcePos)
parser = do
pos <- getPosition
reservedOp str
return (InfixExpr pos constr) -- points-free, returns a function
-- apparently, expression tables can't handle immediately-nested prefixes
parsePrefixedExpr :: Stream s Identity Char => ExpressionParser s
parsePrefixedExpr = do
pos <- getPosition
op <- optionMaybe $ (reservedOp "!" >> return PrefixLNot) <|>
(reservedOp "~" >> return PrefixBNot) <|>
(try (lexeme $ char '-' >> notFollowedBy (char '-')) >>
return PrefixMinus) <|>
(try (lexeme $ char '+' >> notFollowedBy (char '+')) >>
return PrefixPlus) <|>
(reserved "typeof" >> return PrefixTypeof) <|>
(reserved "void" >> return PrefixVoid) <|>
(reserved "delete" >> return PrefixDelete)
case op of
Nothing -> unaryAssignExpr
Just op -> do
innerExpr <- parsePrefixedExpr
return (PrefixExpr pos op innerExpr)
exprTable:: Stream s Identity Char => [[Operator s ParserState Identity ParsedExpression]]
exprTable =
[ [ makeInfixExpr "*" OpMul
, makeInfixExpr "/" OpDiv
, makeInfixExpr "%" OpMod
]
, [ makeInfixExpr "+" OpAdd
, makeInfixExpr "-" OpSub
]
, [ makeInfixExpr "<<" OpLShift
, makeInfixExpr ">>" OpSpRShift
, makeInfixExpr ">>>" OpZfRShift
]
, [ makeInfixExpr "<" OpLT
, makeInfixExpr "<=" OpLEq
, makeInfixExpr ">" OpGT
, makeInfixExpr ">=" OpGEq
, makeInfixExpr "instanceof" OpInstanceof
, makeInfixExpr "in" OpIn
]
, [ makeInfixExpr "==" OpEq
, makeInfixExpr "!=" OpNEq
, makeInfixExpr "===" OpStrictEq
, makeInfixExpr "!==" OpStrictNEq
]
, [ makeInfixExpr "&" OpBAnd ]
, [ makeInfixExpr "^" OpBXor ]
, [ makeInfixExpr "|" OpBOr ]
, [ makeInfixExpr "&&" OpLAnd ]
, [ makeInfixExpr "||" OpLOr ]
]
parseExpression' :: Stream s Identity Char => ExpressionParser s
parseExpression' =
buildExpressionParser exprTable parsePrefixedExpr <?> "simple expression"
asLValue :: Stream s Identity Char
=> SourcePos
-> Expression SourcePos
-> Parser s (LValue SourcePos)
asLValue p' e = case e of
VarRef p (Id _ x) -> return (LVar p x)
DotRef p e (Id _ x) -> return (LDot p e x)
BracketRef p e1 e2 -> return (LBracket p e1 e2)
otherwise -> fail $ "expected a left-value at " ++ show p'
lvalue :: Stream s Identity Char => Parser s (LValue SourcePos)
lvalue = do
p <- getPosition
e <- parseSimpleExpr Nothing
asLValue p e
unaryAssignExpr :: Stream s Identity Char => ExpressionParser s
unaryAssignExpr = do
p <- getPosition
let prefixInc = do
reservedOp "++"
liftM (UnaryAssignExpr p PrefixInc) lvalue
let prefixDec = do
reservedOp "--"
liftM (UnaryAssignExpr p PrefixDec) lvalue
let postfixInc e = do
reservedOp "++"
liftM (UnaryAssignExpr p PostfixInc) (asLValue p e)
let postfixDec e = do
reservedOp "--"
liftM (UnaryAssignExpr p PostfixDec) (asLValue p e)
let other = do
e <- parseSimpleExpr Nothing
postfixInc e <|> postfixDec e <|> return e
prefixInc <|> prefixDec <|> other
parseTernaryExpr':: Stream s Identity Char
=> Parser s (ParsedExpression,ParsedExpression)
parseTernaryExpr' = do
reservedOp "?"
l <- assignExpr
colon
r <- assignExpr
return (l,r)
parseTernaryExpr:: Stream s Identity Char => ExpressionParser s
parseTernaryExpr = do
e <- parseExpression'
e' <- optionMaybe parseTernaryExpr'
case e' of
Nothing -> return e
Just (l,r) -> do p <- getPosition
return $ CondExpr p e l r
assignOp :: Stream s Identity Char => Parser s AssignOp
assignOp = (reservedOp "=" >> return OpAssign)
<|>(reservedOp "+=" >> return OpAssignAdd)
<|>(reservedOp "-=" >> return OpAssignSub)
<|>(reservedOp "*=" >> return OpAssignMul)
<|>(reservedOp "/=" >> return OpAssignDiv)
<|>(reservedOp "%=" >> return OpAssignMod)
<|>(reservedOp "<<=" >> return OpAssignLShift)
<|>(reservedOp ">>=" >> return OpAssignSpRShift)
<|>(reservedOp ">>>=" >> return OpAssignZfRShift)
<|>(reservedOp "&=" >> return OpAssignBAnd)
<|>(reservedOp "^=" >> return OpAssignBXor)
<|>(reservedOp "|=" >> return OpAssignBOr)
assignExpr :: Stream s Identity Char => ExpressionParser s
assignExpr = do
p <- getPosition
lhs <- parseTernaryExpr
let assign = do
op <- assignOp
lhs <- asLValue p lhs
rhs <- assignExpr
return (AssignExpr p op lhs rhs)
assign <|> return lhs
parseExpression:: Stream s Identity Char => ExpressionParser s
parseExpression = parseListExpr
-- | A parser that parses ECMAScript expressions
expression :: Stream s Identity Char => Parser s (Expression SourcePos)
expression = parseExpression
parseListExpr :: Stream s Identity Char => ExpressionParser s
parseListExpr = assignExpr `sepBy1` comma >>= \exprs ->
case exprs of
[expr] -> return expr
es -> liftM2 ListExpr getPosition (return es)
parseScript:: Stream s Identity Char => Parser s (JavaScript SourcePos)
parseScript = do
whiteSpace
liftM2 Script getPosition (parseStatement `sepBy` whiteSpace)
-- | A parser that parses an ECMAScript program.
program :: Stream s Identity Char => Parser s (JavaScript SourcePos)
program = parseScript
-- | Parse from a stream given a parser, same as 'Text.Parsec.parse'
-- in Parsec. We can use this to parse expressions or statements alone,
-- not just whole programs.
parse :: Stream s Identity Char
=> Parser s a -- ^ The parser to use
-> SourceName -- ^ Name of the source file
-> s -- ^ the stream to parse, usually a 'String'
-> Either ParseError a
parse p = runParser p initialParserState
-- | A convenience function that takes a 'String' and tries to parse
-- it as an ECMAScript program:
--
-- > parseFromString = parse program ""
parseFromString :: String -- ^ JavaScript source to parse
-> Either ParseError (JavaScript SourcePos)
parseFromString = parse program ""
-- | A convenience function that takes a filename and tries to parse
-- the file contents an ECMAScript program, it fails with an error
-- message if it can't.
parseFromFile :: (Error e, MonadIO m, MonadError e m) => String -- ^ file name
-> m (JavaScript SourcePos)
parseFromFile fname =
liftIO (readFile fname) >>= \source ->
case parse program fname source of
Left err -> throwError $ strMsg $ show err
Right js -> return js
-- | Read a JavaScript program from file an parse it into a list of
-- statements
parseJavaScriptFromFile :: MonadIO m => String -- ^ file name
-> m [Statement SourcePos]
parseJavaScriptFromFile filename = do
chars <- liftIO $ readFile filename
case parse parseScript filename chars of
Left err -> fail (show err)
Right (Script _ stmts) -> return stmts
-- | Parse a JavaScript program from a string
parseScriptFromString :: String -- ^ source file name
-> String -- ^ JavaScript source to parse
-> Either ParseError (JavaScript SourcePos)
parseScriptFromString = parse parseScript
-- | Parse a JavaScript source string into a list of statements
parseString :: String -- ^ JavaScript source
-> [Statement SourcePos]
parseString str = case parse parseScript "" str of
Left err -> error (show err)
Right (Script _ stmts) -> stmts
| sinelaw/language-ecmascript | src/Language/ECMAScript3/Parser.hs | bsd-3-clause | 29,230 | 578 | 20 | 7,010 | 7,122 | 3,753 | 3,369 | 607 | 4 |
{-|
Module : Idris.Error
Description : Utilities to deal with error reporting.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.Error where
import Prelude hiding (catch)
import Idris.AbsSyntax
import Idris.Delaborate
import Idris.Core.Evaluate (ctxtAlist)
import Idris.Core.TT
import Idris.Core.Typecheck
import Idris.Core.Constraints
import Idris.Output
import System.Console.Haskeline
import System.Console.Haskeline.MonadException
import Control.Monad (when)
import Control.Monad.State.Strict
import System.IO.Error(isUserError, ioeGetErrorString)
import Data.Char
import Data.List (intercalate, isPrefixOf)
import qualified Data.Text as T
import qualified Data.Set as S
import Data.Typeable
import qualified Data.Traversable as Traversable
import qualified Data.Foldable as Foldable
iucheck :: Idris ()
iucheck = do tit <- typeInType
ist <- getIState
let cs = idris_constraints ist
logLvl 7 $ "ALL CONSTRAINTS: " ++ show (length (S.toList cs))
when (not tit) $
(tclift $ ucheck (idris_constraints ist)) `idrisCatch`
(\e -> do let fc = getErrSpan e
setErrSpan fc
iWarn fc $ pprintErr ist e)
showErr :: Err -> Idris String
showErr e = getIState >>= return . flip pshow e
report :: IOError -> String
report e
| isUserError e = ioeGetErrorString e
| otherwise = show e
idrisCatch :: Idris a -> (Err -> Idris a) -> Idris a
idrisCatch = catchError
setAndReport :: Err -> Idris ()
setAndReport e = do ist <- getIState
case (unwrap e) of
At fc e -> do setErrSpan fc
iWarn fc $ pprintErr ist e
_ -> do setErrSpan (getErrSpan e)
iWarn emptyFC $ pprintErr ist e
where unwrap (ProofSearchFail e) = e -- remove bookkeeping constructor
unwrap e = e
ifail :: String -> Idris a
ifail = throwError . Msg
ierror :: Err -> Idris a
ierror = throwError
tclift :: TC a -> Idris a
tclift (OK v) = return v
tclift (Error err@(At fc e)) = do setErrSpan fc; throwError err
tclift (Error err@(UniverseError fc _ _ _ _)) = do setErrSpan fc; throwError err
tclift (Error err) = throwError err
tctry :: TC a -> TC a -> Idris a
tctry tc1 tc2
= case tc1 of
OK v -> return v
Error err -> tclift tc2
getErrSpan :: Err -> FC
getErrSpan (At fc _) = fc
getErrSpan (UniverseError fc _ _ _ _) = fc
getErrSpan _ = emptyFC
--------------------------------------------------------------------
-- Specific warnings not included in elaborator
--------------------------------------------------------------------
-- | Issue a warning on "with"-terms whose namespace is empty or nonexistent
warnDisamb :: IState -> PTerm -> Idris ()
warnDisamb ist (PQuote _) = return ()
warnDisamb ist (PRef _ _ _) = return ()
warnDisamb ist (PInferRef _ _ _) = return ()
warnDisamb ist (PPatvar _ _) = return ()
warnDisamb ist (PLam _ _ _ t b) = warnDisamb ist t >> warnDisamb ist b
warnDisamb ist (PPi _ _ _ t b) = warnDisamb ist t >> warnDisamb ist b
warnDisamb ist (PLet _ _ _ x t b) = warnDisamb ist x >> warnDisamb ist t >> warnDisamb ist b
warnDisamb ist (PTyped x t) = warnDisamb ist x >> warnDisamb ist t
warnDisamb ist (PApp _ t args) = warnDisamb ist t >>
mapM_ (warnDisamb ist . getTm) args
warnDisamb ist (PWithApp _ t a) = warnDisamb ist t >> warnDisamb ist a
warnDisamb ist (PAppBind _ f args) = warnDisamb ist f >>
mapM_ (warnDisamb ist . getTm) args
warnDisamb ist (PMatchApp _ _) = return ()
warnDisamb ist (PCase _ tm cases) = warnDisamb ist tm >>
mapM_ (\(x,y)-> warnDisamb ist x >> warnDisamb ist y) cases
warnDisamb ist (PIfThenElse _ c t f) = mapM_ (warnDisamb ist) [c, t, f]
warnDisamb ist (PTrue _ _) = return ()
warnDisamb ist (PResolveTC _) = return ()
warnDisamb ist (PRewrite _ _ x y z) = warnDisamb ist x >> warnDisamb ist y >>
Foldable.mapM_ (warnDisamb ist) z
warnDisamb ist (PPair _ _ _ x y) = warnDisamb ist x >> warnDisamb ist y
warnDisamb ist (PDPair _ _ _ x y z) = warnDisamb ist x >> warnDisamb ist y >> warnDisamb ist z
warnDisamb ist (PAlternative _ _ tms) = mapM_ (warnDisamb ist) tms
warnDisamb ist (PHidden tm) = warnDisamb ist tm
warnDisamb ist (PType _) = return ()
warnDisamb ist (PUniverse _ _) = return ()
warnDisamb ist (PGoal _ x _ y) = warnDisamb ist x >> warnDisamb ist y
warnDisamb ist (PConstant _ _) = return ()
warnDisamb ist Placeholder = return ()
warnDisamb ist (PDoBlock steps) = mapM_ wStep steps
where wStep (DoExp _ x) = warnDisamb ist x
wStep (DoBind _ _ _ x) = warnDisamb ist x
wStep (DoBindP _ x y cs) = warnDisamb ist x >> warnDisamb ist y >>
mapM_ (\(x,y) -> warnDisamb ist x >> warnDisamb ist y) cs
wStep (DoLet _ _ _ x y) = warnDisamb ist x >> warnDisamb ist y
wStep (DoLetP _ x y) = warnDisamb ist x >> warnDisamb ist y
warnDisamb ist (PIdiom _ x) = warnDisamb ist x
warnDisamb ist (PMetavar _ _) = return ()
warnDisamb ist (PProof tacs) = mapM_ (Foldable.mapM_ (warnDisamb ist)) tacs
warnDisamb ist (PTactics tacs) = mapM_ (Foldable.mapM_ (warnDisamb ist)) tacs
warnDisamb ist (PElabError _) = return ()
warnDisamb ist PImpossible = return ()
warnDisamb ist (PCoerced tm) = warnDisamb ist tm
warnDisamb ist (PDisamb ds tm) = warnDisamb ist tm >>
mapM_ warnEmpty ds
where warnEmpty d =
when (not (any (isIn d . fst) (ctxtAlist (tt_ctxt ist)))) $
ierror . Msg $
"Nothing found in namespace \"" ++
intercalate "." (map T.unpack . reverse $ d) ++
"\"."
isIn d (NS _ ns) = isPrefixOf d ns
isIn d _ = False
warnDisamb ist (PUnifyLog tm) = warnDisamb ist tm
warnDisamb ist (PNoImplicits tm) = warnDisamb ist tm
warnDisamb ist (PQuasiquote tm goal) = warnDisamb ist tm >>
Foldable.mapM_ (warnDisamb ist) goal
warnDisamb ist (PUnquote tm) = warnDisamb ist tm
warnDisamb ist (PQuoteName _ _ _) = return ()
warnDisamb ist (PAs _ _ tm) = warnDisamb ist tm
warnDisamb ist (PAppImpl tm _) = warnDisamb ist tm
warnDisamb ist (PRunElab _ tm _) = warnDisamb ist tm
warnDisamb ist (PConstSugar _ tm) = warnDisamb ist tm
| enolan/Idris-dev | src/Idris/Error.hs | bsd-3-clause | 6,583 | 0 | 20 | 1,766 | 2,474 | 1,214 | 1,260 | 133 | 6 |
{-# LANGUAGE GeneralizedNewtypeDeriving, TemplateHaskell,
DeriveDataTypeable, PatternGuards,
DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
-- Those extensions are required by the Uniplate instances.
--{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
module Language.LaTeX.Types where
import Prelude hiding (and, foldr, foldl, foldr1, foldl1, elem, concatMap, concat)
import Data.Monoid (Monoid(..))
import Data.List (intercalate)
import Data.Ratio ((%))
import Data.Foldable
import Data.String (IsString(..))
-- import Data.Generics.PlateTypeable
import Data.Data
import Control.Applicative
import Control.Arrow (second)
import Control.Monad.Writer (Writer)
import Control.Monad.Trans ()
import Control.Monad.Error
data Document = Document { documentClass :: DocumentClss
, documentPreamble :: PreambleItm
, documentBody :: ParItm }
deriving (Show, Eq, Typeable, Data)
type LineNumber = Int
type CharNumber = Int
data Loc = Loc { locFile :: FilePath
, locLine :: LineNumber
, locChar :: CharNumber
}
deriving (Show, Eq, Typeable, Data)
data Note = TextNote String
| IntNote Int
| LocNote Loc
deriving (Show, Eq, Typeable, Data)
data DocumentClassKind = Article
| Book
| Report
| Letter
| OtherDocumentClassKind String
deriving (Show, Eq, Typeable, Data)
data DocumentClss
= DocClass { docClassKind :: DocumentClassKind
, docClassOptions :: [AnyItm]
}
deriving (Show, Eq, Typeable, Data)
data AnyItm = PreambleItm PreambleItm
| LatexItm LatexItm
| MathItm MathItm
| ParItm ParItm
| LocSpecs [LocSpec]
| Key Key
| PackageName PackageName
| Coord Coord
| Length LatexLength
| SaveBin SaveBin
deriving (Show, Eq, Typeable, Data)
data PreambleItm = PreambleCmdArgs String [Arg AnyItm]
| PreambleEnv String [Arg AnyItm] AnyItm
| PreambleCast AnyItm
| PreambleConcat [PreambleItm]
| RawPreamble String
| PreambleNote Key Note PreambleItm
deriving (Show, Eq, Typeable, Data)
instance Semigroup PreambleItm where
PreambleConcat xs <> PreambleConcat ys = PreambleConcat (xs ++ ys)
PreambleConcat xs <> y = PreambleConcat (xs ++ [y])
x <> PreambleConcat ys = PreambleConcat (x : ys)
x <> y = PreambleConcat [x, y]
instance Monoid PreambleItm where
mempty = PreambleConcat []
data TexDcl = TexDcl { texDeclName :: String
, texDeclArgs :: [Arg AnyItm]
}
deriving (Show, Eq, Typeable, Data)
-- This is the subset of tex strings that fits in the LR mode.
-- The distinction between the paragraph and the LR mode is always
-- made explicit using the Para constructor.
--
-- Modes: http://www.personal.ceu.hu/tex/modes.htm
data LatexItm
= LatexCmdArgs String [Arg LatexItm]
| LatexCmdAnyArgs String [Arg AnyItm]
| TexDecls [TexDcl]
| TexCmdNoArg String
| TexCmdArg String LatexItm
| Environment String [Arg AnyItm] AnyItm
| RawTex String
| LatexCast AnyItm -- a cast from math induce $...$
| TexGroup LatexItm
| LatexEmpty
| LatexAppend LatexItm LatexItm
| LatexNote Key Note LatexItm
deriving (Show, Eq, Typeable, Data)
appendAny :: AnyItm -> AnyItm -> Maybe AnyItm
appendAny (PreambleItm x) (PreambleItm y) = Just $ PreambleItm (x `mappend` y)
appendAny (LatexItm x) (LatexItm y) = Just $ LatexItm (x `mappend` y)
appendAny (MathItm x) (MathItm y) = Just $ MathItm (x `mappend` y)
appendAny (ParItm x) (ParItm y) = Just $ ParItm (x `mappend` y)
appendAny (LocSpecs x) (LocSpecs y) = Just $ LocSpecs (x `mappend` y)
-- this lengthy matching is to get a warning when we extend the AnyItm type
appendAny PreambleItm{} _ = Nothing
appendAny LatexItm{} _ = Nothing
appendAny MathItm{} _ = Nothing
appendAny ParItm{} _ = Nothing
appendAny LocSpecs{} _ = Nothing
appendAny Key{} _ = Nothing
appendAny PackageName{} _ = Nothing
appendAny Coord{} _ = Nothing
appendAny Length{} _ = Nothing
appendAny SaveBin{} _ = Nothing
instance Semigroup LatexItm where
RawTex xs <> RawTex ys = RawTex (xs ++ ys)
LatexCast x <> LatexCast y | Just z <- appendAny x y = LatexCast z
LatexEmpty <> x = x
x <> LatexEmpty = x
LatexAppend x y <> z = x <> (y <> z) -- TODO complexity issue?
x <> LatexAppend y z =
case x <> y of
LatexAppend x' y' -> x' `LatexAppend` (y' <> z) -- TODO complexity issue?
xy -> xy <> z
x <> y = x `LatexAppend` y
instance Monoid LatexItm where
mempty = LatexEmpty -- LatexConcat []
{-
LatexConcat xs `mappend` LatexConcat ys = LatexConcat (xs ++ ys)
LatexConcat xs `mappend` y = LatexConcat (xs ++ [y])
x `mappend` LatexConcat ys = LatexConcat (x : ys)
x `mappend` y = LatexConcat [x, y]
-}
instance IsString LatexItm where
fromString s
| null s = mempty
| otherwise = f s
where f = RawTex . concatMap rawhchar . intercalate "\n" . filter (not . null) . lines
data Named a = Named String a
deriving (Show, Eq, Typeable, Data, Functor, Foldable, Traversable)
data PackageAction = PackageDependency PackageName
| ProvidePackage PackageName
deriving (Show, Eq, Typeable, Data)
data Arg a = NoArg
| StarArg -- `*'
| Mandatory [a] -- surrounded by `{' `}', separated by `,'
| Optional [a] -- surrounded by `[' `]', separated by `,' or empty if null
| NamedArgs [Named a] -- surrounded by `{' `}', separated by `=` and `,'
| NamedOpts [Named a] -- surrounded by `[' `]', separated by `=' and `,' or empty if null
| Coordinates a a -- surrounded by `(' `)', separated by ` '
| RawArg String
| LiftArg a
| PackageAction PackageAction
deriving (Show, Eq, Typeable, Data, Functor, Foldable, Traversable)
data Star = Star | NoStar
deriving (Show, Eq, Typeable, Data)
instance Semigroup Star where
NoStar <> x = x
x <> _ = x
instance Monoid Star where
mempty = NoStar
data Coord = MkCoord LatexLength LatexLength
deriving (Show, Eq, Typeable, Data)
newtype Percentage = Percentage { percentage :: Int } deriving (Eq,Show,Ord,Num)
data ParItm = ParCmdArgs String [Arg AnyItm]
| ParEnv String [Arg AnyItm] AnyItm
| Tabular [RowSpec LatexItm] [Row LatexItm]
| RawParMode String
| ParCast AnyItm -- a cast from Math induce \[...\]
| ParGroup ParItm -- check validity of this
| ParConcat [ParItm]
| ParNote Key Note ParItm
deriving (Show, Eq, Typeable, Data)
instance Semigroup ParItm where
ParConcat xs <> ParConcat ys = ParConcat (xs ++ ys)
ParConcat xs <> y = ParConcat (xs ++ [y])
x <> ParConcat ys = ParConcat (x : ys)
x <> y = ParConcat [x, y]
instance Monoid ParItm where
mempty = ParConcat []
unParNote :: ParItm -> Maybe (Key, Note, ParItm)
unParNote (ParNote k n p) = Just (k, n, p)
unParNote _ = Nothing
uncatParItm :: ParItm -> [ParItm]
uncatParItm (ParConcat pars) = pars
uncatParItm par = [par]
newtype MathDcl = MathDcl String
deriving (Show, Eq, Typeable, Data)
data MathItm = MathDecls [MathDcl]
| MathCmdArgs String [Arg AnyItm]
| MathArray [RowSpec MathItm] [Row MathItm]
| RawMath String
| MathCast AnyItm
| MathRat Rational
| MathGroup MathItm
| MathConcat [MathItm]
| MathBinOp String MathItm MathItm
| MathUnOp String MathItm
| MathNote Key Note MathItm
deriving (Show, Eq, Typeable, Data)
instance Semigroup MathItm where
MathConcat xs <> MathConcat ys = MathConcat (xs ++ ys)
MathConcat xs <> y = MathConcat (xs ++ [y])
x <> MathConcat ys = MathConcat (x : ys)
x <> y = MathConcat [x, y]
instance Monoid MathItm where
mempty = MathConcat []
instance Num MathItm where
(+) = MathBinOp "+"
(*) = MathBinOp "*"
(-) = MathBinOp "-"
negate = MathUnOp "-"
abs x = MathCmdArgs "abs" [Mandatory [MathItm x]] -- TODO check
signum = error "MathItm.signum is undefined"
fromInteger = MathRat . (%1)
instance Fractional MathItm where
(/) = MathBinOp "/"
fromRational = MathRat
{-
instance Real MathItm where
toRational = error "MathItm.toRational is undefined"
instance Integral MathItm where
mod = MathBinOp "bmod"
-- TODO quot, rem
-}
data TexUnit
= Sp -- ^ Scalled point (1pt = 65536sp)
| Pt -- ^ Point unit size (1pt = 0.351mm)
| Bp -- ^ Big point (1in = 72bp), also PostScript point
| Dd -- ^ Didôt point (1dd = 0.376mm)
| Em -- ^ One em is about the width of the letter M in the current font
| Ex -- ^ One ex is about the hoigh of the letter x in the current font
| Cm -- ^ Centimeter unit size
| Mm -- ^ Milimeter unit size (1mm = 2.845pt)
| In -- ^ Inch unit size (1in = 72.27pt)
| Pc -- ^ Picas (1pc = 12pt)
| Cc -- ^ Cicero (1dd = 12dd = 4.531mm)
| Mu -- ^ Math unit (18mu = 1em)
deriving (Eq, Ord, Enum, Show, Typeable, Data)
data LatexLength = LengthScaledBy Rational LatexLength
| LengthCmdRatArg String Rational
| LengthCmd String
| LengthCst (Maybe TexUnit) Rational
deriving (Show, Eq, Typeable, Data)
lengthCst :: LatexLength -> Maybe (Maybe TexUnit, Rational)
lengthCst (LengthScaledBy rat len) = second (rat *) <$> lengthCst len
lengthCst (LengthCmdRatArg _ _) = Nothing
lengthCst (LengthCmd _) = Nothing
lengthCst (LengthCst mtu rat) = Just (mtu, rat)
safeLengthOp :: String -> (Rational -> Rational -> Rational) -> LatexLength -> LatexLength -> LatexLength
safeLengthOp _ op (LengthCst Nothing rx) (LengthCst munit ry)
= LengthCst munit (op rx ry)
safeLengthOp _ op (LengthCst (Just unit) rx) (LengthCst Nothing ry)
= LengthCst (Just unit) (op rx ry)
safeLengthOp op _ x y
= error $ "LatexLength." ++ op
++ ": undefined on non constants terms (" ++ show x ++ op ++ show y ++ ")"
scaleBy :: Rational -> LatexLength -> LatexLength
scaleBy rx (LengthScaledBy ry l) = LengthScaledBy (rx * ry) l
scaleBy rx (LengthCst munit ry) = LengthCst munit (rx * ry)
scaleBy rx (LengthCmd cmd) = LengthScaledBy rx (LengthCmd cmd)
scaleBy rx (LengthCmdRatArg cmd r) = LengthScaledBy rx (LengthCmdRatArg cmd r)
instance Num LatexLength where
LengthCst Nothing x * y = scaleBy x y
x * LengthCst Nothing y = scaleBy y x
x * y = safeLengthOp "*" (*) x y
(+) = safeLengthOp "+" (+)
(-) = safeLengthOp "-" (-)
negate x = LengthCst Nothing (-1) * x
abs = error "LatexLength.abs is undefined"
signum = error "LatexLength.signum is undefined"
fromInteger = LengthCst Nothing . (%1)
instance Semigroup LatexLength where
(<>) = (+)
instance Monoid LatexLength where
mempty = 0
instance Fractional LatexLength where
x / LengthCst Nothing ry = scaleBy (1/ry) x
x / y = safeLengthOp "/" (/) x y
fromRational = LengthCst Nothing
-- p{wd}, and *{num}{cols} are explicitly
-- not supported, it seems much more natural and
-- simple to obtain the same goals using standard
-- programming uppon the rows and cells.
data RowSpec a = Rc --- ^ Centered
| Rl --- ^ Left
| Rr --- ^ Right
| Rvline --- ^ A vertical line
| Rtext a --- ^ A fixed text column (@-expression in LaTeX parlance)
deriving (Show, Eq, Typeable, Data, Functor, Foldable, Traversable)
{-
instance Functor RowSpec where
_ `fmap` Rc = Rc
_ `fmap` Rl = Rl
_ `fmap` Rr = Rr
_ `fmap` Rvline = Rvline
f `fmap` (Rtext x) = Rtext $ f x
instance Foldable RowSpec where
foldr _ z Rc = z
foldr _ z Rl = z
foldr _ z Rr = z
foldr _ z Rvline = z
foldr f z (Rtext x) = f x z
instance Traversable RowSpec where
sequenceA Rc = pure Rc
sequenceA Rl = pure Rl
sequenceA Rr = pure Rr
sequenceA Rvline = pure Rvline
sequenceA (Rtext x) = Rtext <$> x
-}
data LocSpec = Lh --- ^ Here
| Lt --- ^ Top
| Lb --- ^ Bottom
| Lp --- ^ Page of floats: on a sperate page containing no text,
--- only figures and tables.
deriving (Show, Eq, Typeable, Data)
locSpecChar :: LocSpec -> Char
locSpecChar Lh = 'h'
locSpecChar Lt = 't'
locSpecChar Lb = 'b'
locSpecChar Lp = 'p'
data Pos = Centered -- ^ Centered (default).
| FlushLeft -- ^ Flush left
| FlushRight -- ^ Flush right
| Stretch -- ^ Stretch (justify) across entire width; text must contain
-- stretchable space for this to work.
charPos :: Pos -> Char
charPos Centered = 'c'
charPos FlushLeft = 'l'
charPos FlushRight = 'r'
charPos Stretch = 's'
-- TODO: add more paper sizes
data LatexPaperSize = A4paper | OtherPaperSize String
deriving (Show, Eq, Typeable, Data)
{- NOTE: their is no handling of the \multicolumn command at the moment -}
data Row cell = Cells [cell]
| Hline
| Cline Int Int
deriving (Show, Eq, Typeable, Data, Functor, Foldable, Traversable)
{-
instance Functor Row where
f `fmap` Cells cs = Cells (fmap f cs)
_ `fmap` Hline = Hline
_ `fmap` Cline i j = Cline i j
instance Foldable Row where
foldr f z (Cells cs) = foldr f z cs
foldr _ z Hline = z
foldr _ z (Cline _ _) = z
instance Traversable Row where
sequenceA (Cells cs) = Cells <$> sequenceA cs
sequenceA Hline = pure Hline
sequenceA (Cline i j) = pure $ Cline i j
-}
data ListItm = ListItm { itemOptions :: [Arg LatexItm], itemContents :: ParItm }
newtype PackageName = PkgName { getPkgName :: String }
deriving (Ord, Eq, Show, Typeable, Data)
newtype Key = MkKey { getKey :: String }
deriving (Eq, Show, Typeable, Data)
newtype SaveBin = UnsafeMakeSaveBin { unsafeGetSaveBin :: Int }
deriving (Eq, Show, Typeable, Data)
data LatexState = LS { freshSaveBin :: SaveBin }
instance (Error a, Eq a, Show a, Num b) => Num (Either a b) where
fromInteger = pure . fromInteger
(+) = liftM2 (+)
(-) = liftM2 (-)
(*) = liftM2 (*)
negate = liftM negate
abs = liftM abs
signum = liftM signum
instance (Error a, Eq a, Show a, Fractional b) => Fractional (Either a b) where
(/) = liftM2 (/)
fromRational = pure . fromRational
type ErrorMessage = String
newtype LatexM a = LatexM { runLatexM :: Either ErrorMessage a }
deriving (Functor, Applicative, Alternative, Monad, MonadPlus,
MonadError ErrorMessage, Show, Eq, Num, Fractional,
Typeable, Data)
instance Semigroup a => Semigroup (LatexM a) where
(<>) = liftM2 (<>)
-- sconcat = liftM sconcat . sequenceA
instance Monoid a => Monoid (LatexM a) where
mempty = pure mempty
instance IsString a => IsString (LatexM a) where fromString = pure . fromString
type TexDecl = LatexM TexDcl
type LatexItem = LatexM LatexItm
type ParItem = LatexM ParItm
type MathDecl = LatexM MathDcl
newtype AnyItem = AnyItem { anyItmM :: LatexM AnyItm }
deriving (Eq, Show, Typeable, Data)
newtype MathItem = MathItem { mathItmM :: LatexM MathItm }
deriving (Semigroup, Monoid, Eq, Show, Num, Fractional, Typeable, Data)
type ListItem = LatexM ListItm
type PreambleItem = LatexM PreambleItm
type DocumentClass = LatexM DocumentClss
type TexDeclW = Writer TexDecl ()
type LatexItemW = Writer LatexItem ()
type ParItemW = Writer ParItem ()
type MathDeclW = Writer MathDecl ()
type MathItemW = Writer MathItem ()
type PreambleItemW = Writer PreambleItem ()
-- TODO: Maybe one should handle quotes in a less LaTeX
-- way: provide a replacement for ``...'' and escape `'"
--
-- NOTE: Don't confuse this function with ttchar
-- NOTE: this raw Tex is ugly
rawhchar :: Char -> String
rawhchar '\\' = "\\textbackslash{}"
rawhchar '<' = "\\textless{}"
rawhchar '>' = "\\textgreater{}"
rawhchar '|' = "\\textbar{}"
rawhchar x
| x `elem` "~^_#&{}$%" = ['\\',x,'{','}']
| x `elem` ":][" = ['{', x, '}'] -- '[' and ']' are escaped to avoid mess up optional args
| otherwise = [x]
-- | Type for encodings used in commands like.
-- @\usepackage[utf8]{inputenc}@, that we can
-- express as 'useInputenc' 'utf8'.
newtype Encoding = Encoding { fromEncoding :: String }
deriving (Eq,Ord,Show)
-- instance (Integral a, Typeable a, Typeable b, PlateAll a b) => PlateAll (Ratio a) b where
-- plateAll r = plate (%) |+ numerator r |+ denominator r
{-
$(derive makeUniplateTypeable ''SaveBin)
$(derive makeUniplateTypeable ''PackageName)
$(derive makeUniplateTypeable ''Loc)
$(derive makeUniplateTypeable ''Note)
$(derive makeUniplateTypeable ''Arg)
$(derive makeUniplateTypeable ''Key)
$(derive makeUniplateTypeable ''Row)
$(derive makeUniplateTypeable ''RowSpec)
$(derive makeUniplateTypeable ''LocSpec)
$(derive makeUniplateTypeable ''LatexLength)
$(derive makeUniplateTypeable ''Coord)
$(derive makeUniplateTypeable ''DocumentClassKind)
$(derive makeUniplateTypeable ''TexDcl)
$(derive makeUniplateTypeable ''MathItm)
$(derive makeUniplateTypeable ''MathDcl)
$(derive makeUniplateTypeable ''ParItm)
$(derive makeUniplateTypeable ''TexUnit)
$(derive makeUniplateTypeable ''LatexItm)
$(derive makeUniplateTypeable ''DocumentClass)
$(derive makeUniplateTypeable ''PreambleItm)
$(derive makeUniplateTypeable ''Document)
-}
| np/hlatex | Language/LaTeX/Types.hs | bsd-3-clause | 18,172 | 0 | 12 | 5,015 | 4,427 | 2,405 | 2,022 | 339 | 1 |
{-# LANGUAGE TypeFamilies, CPP, FlexibleInstances, FlexibleContexts, NamedFieldPuns, RecordWildCards, UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses, UnboxedTuples, StandaloneDeriving, TypeSynonymInstances #-}
{-# OPTIONS -funbox-strict-fields #-}
module Data.TrieMap.Key () where
import Data.TrieMap.Class
import Data.TrieMap.TrieKey
import Data.TrieMap.Representation.Class
import Data.TrieMap.Modifiers
import Prelude hiding (foldr, foldl, foldr1, foldl1, lookup)
type RepMap k = TrieMap (Rep k)
keyMap :: (Repr k, TrieKey (Rep k), Sized a) => TrieMap (Rep k) a -> TrieMap (Key k) a
keyMap m = KeyMap (sizeM m) m
#define KMAP(m) KeyMap{tMap = m}
#define CONTEXT(cl) (Repr k, TrieKey (Rep k), cl (RepMap k))
instance CONTEXT(Foldable) => Foldable (TrieMap (Key k)) where
foldMap f KMAP(m) = foldMap f m
foldr f z KMAP(m) = foldr f z m
foldl f z KMAP(m) = foldl f z m
instance CONTEXT(Functor) => Functor (TrieMap (Key k)) where
fmap f KeyMap{..} = KeyMap{sz, tMap = f <$> tMap}
instance CONTEXT(Traversable) => Traversable (TrieMap (Key k)) where
traverse f KeyMap{..} = KeyMap sz <$> traverse f tMap
instance CONTEXT(Subset) => Subset (TrieMap (Key k)) where
KMAP(m1) <=? KMAP(m2) = m1 <=? m2
instance (Repr k, TrieKey (Rep k), Buildable (RepMap k) (Rep k)) => Buildable (TrieMap (Key k)) (Key k) where
type UStack (TrieMap (Key k)) = UMStack (Rep k)
uFold = fmap keyMap . mapFoldlKeys keyRep . uFold
type AStack (TrieMap (Key k)) = AMStack (Rep k)
aFold = fmap keyMap . mapFoldlKeys keyRep . aFold
type DAStack (TrieMap (Key k)) = DAMStack (Rep k)
daFold = keyMap <$> mapFoldlKeys keyRep daFold
#define SETOP(op) op f KMAP(m1) KMAP(m2) = keyMap (op f m1 m2)
instance CONTEXT(SetOp) => SetOp (TrieMap (Key k)) where
SETOP(union)
SETOP(isect)
SETOP(diff)
instance CONTEXT(Project) => Project (TrieMap (Key k)) where
mapMaybe f KMAP(m) = keyMap $ mapMaybe f m
mapEither f KMAP(m) = both keyMap (mapEither f) m
instance CONTEXT(Zippable) => Zippable (TrieMap (Key k)) where
empty = KeyMap 0 empty
clear (KeyHole hole) = keyMap (clear hole)
assign a (KeyHole hole) = keyMap (assign a hole)
#define SPLITOP(op) op (KeyHole hole) = keyMap (op hole)
instance CONTEXT(Splittable) => Splittable (TrieMap (Key k)) where
SPLITOP(before)
SPLITOP(beforeWith a)
SPLITOP(after)
SPLITOP(afterWith a)
instance CONTEXT(Indexable) => Indexable (TrieMap (Key k)) where
index i KMAP(m) = case index i m of
(# i', a, hole #) -> (# i', a, KeyHole hole #)
instance TKey k => Searchable (TrieMap (Key k)) (Key k) where
search k KMAP(m) = mapHole KeyHole (search (keyRep k) m)
singleZip k = KeyHole (singleZip (keyRep k))
lookup k KMAP(m) = lookup (keyRep k) m
insertWith f k a KMAP(m) = keyMap (insertWith f (keyRep k) a m)
alter f k KMAP(m) = keyMap (alter f (keyRep k) m)
instance CONTEXT(Alternatable) => Alternatable (TrieMap (Key k)) where
alternate KMAP(m) = do
(a, hole) <- alternate m
return (a, KeyHole hole)
data instance TrieMap (Key k) a = KeyMap {sz :: !Int, tMap :: !(TrieMap (Rep k) a)}
newtype instance Zipper (TrieMap (Key k)) a = KeyHole (Hole (Rep k) a)
-- | @'TrieMap' ('Key' k) a@ is a wrapper around a @TrieMap (Rep k) a@.
instance TKey k => TrieKey (Key k) where
getSimpleM KMAP(m) = getSimpleM m
sizeM = sz
unifierM (Key k1) (Key k2) a = KeyHole <$> unifierM (toRep k1) (toRep k2) a
unifyM (Key k1) a1 (Key k2) a2 = keyMap <$> unifyM (toRep k1) a1 (toRep k2) a2
keyRep :: (Repr k, TrieKey (Rep k)) => Key k -> Rep k
keyRep (Key k) = toRep k | lowasser/TrieMap | Data/TrieMap/Key.hs | bsd-3-clause | 3,563 | 7 | 13 | 674 | 1,528 | 787 | 741 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Cauterize.Common.ParserUtils
( pSexp
, parseBuiltInName
, parseSchemaVersion
, parseFormHash
) where
import Text.Parsec
import Text.Parsec.Text.Lazy
import Cauterize.FormHash
import Cauterize.Lexer
import Control.Monad
import Data.Word
import qualified Data.Text.Lazy as T
import Numeric
import qualified Data.ByteString as BS
import Cauterize.Common.Types
parseManyStartingWith :: String -> String -> Parser T.Text
parseManyStartingWith s r = lexeme $ do
s' <- oneOf s
r' <- many . oneOf $ r
return $ s' `T.cons` T.pack r'
parseSchemaVersion :: Parser T.Text
parseSchemaVersion = parseManyStartingWith start rest
where
start = ['a'..'z'] ++ ['0'..'9']
rest = start ++ "_.-"
parseFormHash :: Parser FormHash
parseFormHash = pSexp "sha1" $
lexeme $ liftM (FormHash . BS.pack . hexStrToWord8s) $ count 40 $ oneOf (['a'..'f'] ++ ['0'..'9'])
pSexp :: String -> Parser a -> Parser a
pSexp n p = lexeme (parens $ reserved n >> p)
hexStrToWord8s :: String -> [Word8]
hexStrToWord8s (a:b:rs) = let w = (fst . head) $ readHex [a,b]
rs' = hexStrToWord8s rs
in w:rs'
hexStrToWord8s [] = []
hexStrToWord8s _ = error "Must have even number of characters"
parseBuiltInName :: Parser BuiltIn
parseBuiltInName = lexeme $ liftM read $ choice names
where
names = map (try . string . show) bis
bis = [minBound .. maxBound] :: [BuiltIn]
| reiddraper/cauterize | src/Cauterize/Common/ParserUtils.hs | bsd-3-clause | 1,465 | 0 | 12 | 312 | 488 | 262 | 226 | 40 | 1 |
module Euler.E60
( concatInts
, remarkable
, remarkableSet
, addToRemarkableSet
, solve
, s
)
where
import Data.Monoid
import Data.Maybe
import Data.Numbers.Primes
solve :: Int -> Int
solve n = sum $ head $ dropWhile (\xs -> length xs < n) s
s :: [[Int]]
s = [] : concatMap (\p -> mapMaybe (addToRemarkableSet p) (takeWhile (f p) s)) primes
where
f _ [] = True
f y (x:_) = x < y
addToRemarkableSet :: Int -> [Int] -> Maybe [Int]
addToRemarkableSet y [] = Just [y]
addToRemarkableSet y (x:xs)
| remarkableSet (x:xs) y = Just (y:x:xs)
| otherwise = Nothing
remarkableSet :: [Int] -> Int -> Bool
remarkableSet xs y = all (== True) $ map (remarkable y) xs
remarkable :: Int -> Int -> Bool
remarkable x y = {-# SCC remarkable #-} isPrime (concatInts x y) && isPrime (concatInts y x)
concatInts :: Int -> Int -> Int
concatInts x y
| x <= 0 || y <= 0 = error "Invalid arguments"
| otherwise = read $ show x <> show y
| lslah/euler | src/Euler/E60.hs | bsd-3-clause | 985 | 0 | 13 | 251 | 445 | 230 | 215 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ViewPatterns #-}
-- | Build-specific types.
module Stack.Types.Build
(StackBuildException(..)
,FlagSource(..)
,UnusedFlags(..)
,InstallLocation(..)
,ModTime
,modTime
,Installed(..)
,PackageInstallInfo(..)
,Task(..)
,taskLocation
,LocalPackage(..)
,BaseConfigOpts(..)
,Plan(..)
,TestOpts(..)
,BenchmarkOpts(..)
,FileWatchOpts(..)
,BuildOpts(..)
,BuildSubset(..)
,defaultBuildOpts
,TaskType(..)
,TaskConfigOpts(..)
,ConfigCache(..)
,ConstructPlanException(..)
,configureOpts
,BadDependency(..)
,wantedLocalPackages
,FileCacheInfo (..)
,ConfigureOpts (..)
,PrecompiledCache (..))
where
import Control.DeepSeq
import Control.Exception
import Data.Binary (getWord8, putWord8, gput, gget)
import Data.Binary.VersionTagged
import qualified Data.ByteString as S
import Data.Char (isSpace)
import Data.Data
import Data.Hashable
import Data.List (dropWhileEnd, nub, intercalate)
import qualified Data.Map as Map
import Data.Map.Strict (Map)
import Data.Maybe
import Data.Monoid
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import Data.Time.Calendar
import Data.Time.Clock
import Distribution.System (Arch)
import Distribution.Text (display)
import GHC.Generics
import Path (Path, Abs, File, Dir, mkRelDir, toFilePath, parseRelDir, (</>))
import Prelude
import Stack.Types.FlagName
import Stack.Types.GhcPkgId
import Stack.Types.Compiler
import Stack.Types.Config
import Stack.Types.Package
import Stack.Types.PackageIdentifier
import Stack.Types.PackageName
import Stack.Types.Version
import System.Exit (ExitCode (ExitFailure))
import System.FilePath (dropTrailingPathSeparator, pathSeparator)
----------------------------------------------
-- Exceptions
data StackBuildException
= Couldn'tFindPkgId PackageName
| CompilerVersionMismatch
(Maybe (CompilerVersion, Arch))
(CompilerVersion, Arch)
GHCVariant
VersionCheck
(Maybe (Path Abs File))
Text -- recommended resolution
-- ^ Path to the stack.yaml file
| Couldn'tParseTargets [Text]
| UnknownTargets
(Set PackageName) -- no known version
(Map PackageName Version) -- not in snapshot, here's the most recent version in the index
(Path Abs File) -- stack.yaml
| TestSuiteFailure PackageIdentifier (Map Text (Maybe ExitCode)) (Maybe (Path Abs File)) S.ByteString
| ConstructPlanExceptions
[ConstructPlanException]
(Path Abs File) -- stack.yaml
| CabalExitedUnsuccessfully
ExitCode
PackageIdentifier
(Path Abs File) -- cabal Executable
[String] -- cabal arguments
(Maybe (Path Abs File)) -- logfiles location
S.ByteString -- log contents
| ExecutionFailure [SomeException]
| LocalPackageDoesn'tMatchTarget
PackageName
Version -- local version
Version -- version specified on command line
| NoSetupHsFound (Path Abs Dir)
| InvalidFlagSpecification (Set UnusedFlags)
| TargetParseException [Text]
| DuplicateLocalPackageNames [(PackageName, [Path Abs Dir])]
deriving Typeable
data FlagSource = FSCommandLine | FSStackYaml
deriving (Show, Eq, Ord)
data UnusedFlags = UFNoPackage FlagSource PackageName
| UFFlagsNotDefined FlagSource Package (Set FlagName)
| UFSnapshot PackageName
deriving (Show, Eq, Ord)
instance Show StackBuildException where
show (Couldn'tFindPkgId name) =
("After installing " <> packageNameString name <>
", the package id couldn't be found " <> "(via ghc-pkg describe " <>
packageNameString name <> "). This shouldn't happen, " <>
"please report as a bug")
show (CompilerVersionMismatch mactual (expected, earch) ghcVariant check mstack resolution) = concat
[ case mactual of
Nothing -> "No compiler found, expected "
Just (actual, arch) -> concat
[ "Compiler version mismatched, found "
, compilerVersionString actual
, " ("
, display arch
, ")"
, ", but expected "
]
, case check of
MatchMinor -> "minor version match with "
MatchExact -> "exact version "
NewerMinor -> "minor version match or newer with "
, compilerVersionString expected
, " ("
, display earch
, ghcVariantSuffix ghcVariant
, ") (based on "
, case mstack of
Nothing -> "command line arguments"
Just stack -> "resolver setting in " ++ toFilePath stack
, ").\n"
, T.unpack resolution
]
show (Couldn'tParseTargets targets) = unlines
$ "The following targets could not be parsed as package names or directories:"
: map T.unpack targets
show (UnknownTargets noKnown notInSnapshot stackYaml) =
unlines $ noKnown' ++ notInSnapshot'
where
noKnown'
| Set.null noKnown = []
| otherwise = return $
"The following target packages were not found: " ++
intercalate ", " (map packageNameString $ Set.toList noKnown)
notInSnapshot'
| Map.null notInSnapshot = []
| otherwise =
"The following packages are not in your snapshot, but exist"
: "in your package index. Recommended action: add them to your"
: ("extra-deps in " ++ toFilePath stackYaml)
: "(Note: these are the most recent versions,"
: "but there's no guarantee that they'll build together)."
: ""
: map
(\(name, version) -> "- " ++ packageIdentifierString
(PackageIdentifier name version))
(Map.toList notInSnapshot)
show (TestSuiteFailure ident codes mlogFile bs) = unlines $ concat
[ ["Test suite failure for package " ++ packageIdentifierString ident]
, flip map (Map.toList codes) $ \(name, mcode) -> concat
[ " "
, T.unpack name
, ": "
, case mcode of
Nothing -> " executable not found"
Just ec -> " exited with: " ++ show ec
]
, return $ case mlogFile of
Nothing -> "Logs printed to console"
-- TODO Should we load up the full error output and print it here?
Just logFile -> "Full log available at " ++ toFilePath logFile
, if S.null bs
then []
else ["", "", doubleIndent $ T.unpack $ decodeUtf8With lenientDecode bs]
]
where
indent = dropWhileEnd isSpace . unlines . fmap (\line -> " " ++ line) . lines
doubleIndent = indent . indent
show (ConstructPlanExceptions exceptions stackYaml) =
"While constructing the BuildPlan the following exceptions were encountered:" ++
appendExceptions exceptions' ++
if Map.null extras then "" else (unlines
$ ("\n\nRecommended action: try adding the following to your extra-deps in "
++ toFilePath stackYaml)
: map (\(name, version) -> concat
[ "- "
, packageNameString name
, "-"
, versionString version
]) (Map.toList extras)
++ ["", "You may also want to try the 'stack solver' command"]
)
where
exceptions' = removeDuplicates exceptions
appendExceptions = foldr (\e -> (++) ("\n\n--" ++ show e)) ""
removeDuplicates = nub
extras = Map.unions $ map getExtras exceptions'
getExtras (DependencyCycleDetected _) = Map.empty
getExtras (UnknownPackage _) = Map.empty
getExtras (DependencyPlanFailures _ m) =
Map.unions $ map go $ Map.toList m
where
go (name, (_range, Just version, NotInBuildPlan)) =
Map.singleton name version
go _ = Map.empty
-- Supressing duplicate output
show (CabalExitedUnsuccessfully exitCode taskProvides' execName fullArgs logFiles bs) =
let fullCmd = (dropQuotes (toFilePath execName) ++ " " ++ (unwords fullArgs))
logLocations = maybe "" (\fp -> "\n Logs have been written to: " ++ toFilePath fp) logFiles
in "\n-- While building package " ++ dropQuotes (show taskProvides') ++ " using:\n" ++
" " ++ fullCmd ++ "\n" ++
" Process exited with code: " ++ show exitCode ++
(if exitCode == ExitFailure (-9)
then " (THIS MAY INDICATE OUT OF MEMORY)"
else "") ++
logLocations ++
(if S.null bs
then ""
else "\n\n" ++ doubleIndent (T.unpack $ decodeUtf8With lenientDecode bs))
where
-- appendLines = foldr (\pName-> (++) ("\n" ++ show pName)) ""
indent = dropWhileEnd isSpace . unlines . fmap (\line -> " " ++ line) . lines
dropQuotes = filter ('\"' /=)
doubleIndent = indent . indent
show (ExecutionFailure es) = intercalate "\n\n" $ map show es
show (LocalPackageDoesn'tMatchTarget name localV requestedV) = concat
[ "Version for local package "
, packageNameString name
, " is "
, versionString localV
, ", but you asked for "
, versionString requestedV
, " on the command line"
]
show (NoSetupHsFound dir) =
"No Setup.hs or Setup.lhs file found in " ++ toFilePath dir
show (InvalidFlagSpecification unused) = unlines
$ "Invalid flag specification:"
: map go (Set.toList unused)
where
showFlagSrc :: FlagSource -> String
showFlagSrc FSCommandLine = " (specified on command line)"
showFlagSrc FSStackYaml = " (specified in stack.yaml)"
go :: UnusedFlags -> String
go (UFNoPackage src name) = concat
[ "- Package '"
, packageNameString name
, "' not found"
, showFlagSrc src
]
go (UFFlagsNotDefined src pkg flags) = concat
[ "- Package '"
, name
, "' does not define the following flags"
, showFlagSrc src
, ":\n"
, intercalate "\n"
(map (\flag -> " " ++ flagNameString flag)
(Set.toList flags))
, "\n- Flags defined by package '" ++ name ++ "':\n"
, intercalate "\n"
(map (\flag -> " " ++ name ++ ":" ++ flagNameString flag)
(Set.toList pkgFlags))
]
where name = packageNameString (packageName pkg)
pkgFlags = packageDefinedFlags pkg
go (UFSnapshot name) = concat
[ "- Attempted to set flag on snapshot package "
, packageNameString name
, ", please add to extra-deps"
]
show (TargetParseException [err]) = "Error parsing targets: " ++ T.unpack err
show (TargetParseException errs) = unlines
$ "The following errors occurred while parsing the build targets:"
: map (("- " ++) . T.unpack) errs
show (DuplicateLocalPackageNames pairs) = concat
$ "The same package name is used in multiple local packages\n"
: map go pairs
where
go (name, dirs) = unlines
$ ""
: (packageNameString name ++ " used in:")
: map goDir dirs
goDir dir = "- " ++ toFilePath dir
instance Exception StackBuildException
data ConstructPlanException
= DependencyCycleDetected [PackageName]
| DependencyPlanFailures PackageIdentifier (Map PackageName (VersionRange, LatestVersion, BadDependency))
| UnknownPackage PackageName -- TODO perhaps this constructor will be removed, and BadDependency will handle it all
-- ^ Recommend adding to extra-deps, give a helpful version number?
deriving (Typeable, Eq)
-- | For display purposes only, Nothing if package not found
type LatestVersion = Maybe Version
-- | Reason why a dependency was not used
data BadDependency
= NotInBuildPlan
| Couldn'tResolveItsDependencies
| DependencyMismatch Version
deriving (Typeable, Eq)
instance Show ConstructPlanException where
show e =
let details = case e of
(DependencyCycleDetected pNames) ->
"While checking call stack,\n" ++
" dependency cycle detected in packages:" ++ indent (appendLines pNames)
(DependencyPlanFailures pIdent (Map.toList -> pDeps)) ->
"Failure when adding dependencies:" ++ doubleIndent (appendDeps pDeps) ++ "\n" ++
" needed for package: " ++ packageIdentifierString pIdent
(UnknownPackage pName) ->
"While attempting to add dependency,\n" ++
" Could not find package " ++ show pName ++ " in known packages"
in indent details
where
appendLines = foldr (\pName-> (++) ("\n" ++ show pName)) ""
indent = dropWhileEnd isSpace . unlines . fmap (\line -> " " ++ line) . lines
doubleIndent = indent . indent
appendDeps = foldr (\dep-> (++) ("\n" ++ showDep dep)) ""
showDep (name, (range, mlatest, badDep)) = concat
[ show name
, ": needed ("
, display range
, ")"
, ", "
, let latestStr =
case mlatest of
Nothing -> ""
Just latest -> " (latest is " ++ versionString latest ++ ")"
in case badDep of
NotInBuildPlan -> "not present in build plan" ++ latestStr
Couldn'tResolveItsDependencies -> "couldn't resolve its dependencies"
DependencyMismatch version ->
case mlatest of
Just latest
| latest == version ->
versionString version ++
" found (latest version available)"
_ -> versionString version ++ " found" ++ latestStr
]
{- TODO Perhaps change the showDep function to look more like this:
dropQuotes = filter ((/=) '\"')
(VersionOutsideRange pName pIdentifier versionRange) ->
"Exception: Stack.Build.VersionOutsideRange\n" ++
" While adding dependency for package " ++ show pName ++ ",\n" ++
" " ++ dropQuotes (show pIdentifier) ++ " was found to be outside its allowed version range.\n" ++
" Allowed version range is " ++ display versionRange ++ ",\n" ++
" should you correct the version range for " ++ dropQuotes (show pIdentifier) ++ ", found in [extra-deps] in the project's stack.yaml?"
-}
----------------------------------------------
-- | Which subset of packages to build
data BuildSubset
= BSAll
| BSOnlySnapshot
-- ^ Only install packages in the snapshot database, skipping
-- packages intended for the local database.
| BSOnlyDependencies
deriving Show
-- | Configuration for building.
data BuildOpts =
BuildOpts {boptsTargets :: ![Text]
,boptsLibProfile :: !Bool
,boptsExeProfile :: !Bool
,boptsHaddock :: !Bool
-- ^ Build haddocks?
,boptsHaddockDeps :: !(Maybe Bool)
-- ^ Build haddocks for dependencies?
,boptsDryrun :: !Bool
,boptsGhcOptions :: ![Text]
,boptsFlags :: !(Map (Maybe PackageName) (Map FlagName Bool))
,boptsInstallExes :: !Bool
-- ^ Install executables to user path after building?
,boptsPreFetch :: !Bool
-- ^ Fetch all packages immediately
,boptsBuildSubset :: !BuildSubset
,boptsFileWatch :: !FileWatchOpts
-- ^ Watch files for changes and automatically rebuild
,boptsKeepGoing :: !(Maybe Bool)
-- ^ Keep building/running after failure
,boptsForceDirty :: !Bool
-- ^ Force treating all local packages as having dirty files
,boptsTests :: !Bool
-- ^ Turn on tests for local targets
,boptsTestOpts :: !TestOpts
-- ^ Additional test arguments
,boptsBenchmarks :: !Bool
-- ^ Turn on benchmarks for local targets
,boptsBenchmarkOpts :: !BenchmarkOpts
-- ^ Additional test arguments
,boptsExec :: ![(String, [String])]
-- ^ Commands (with arguments) to run after a successful build
,boptsOnlyConfigure :: !Bool
-- ^ Only perform the configure step when building
,boptsReconfigure :: !Bool
-- ^ Perform the configure step even if already configured
,boptsCabalVerbose :: !Bool
-- ^ Ask Cabal to be verbose in its builds
}
deriving (Show)
defaultBuildOpts :: BuildOpts
defaultBuildOpts = BuildOpts
{ boptsTargets = []
, boptsLibProfile = False
, boptsExeProfile = False
, boptsHaddock = False
, boptsHaddockDeps = Nothing
, boptsDryrun = False
, boptsGhcOptions = []
, boptsFlags = Map.empty
, boptsInstallExes = False
, boptsPreFetch = False
, boptsBuildSubset = BSAll
, boptsFileWatch = NoFileWatch
, boptsKeepGoing = Nothing
, boptsForceDirty = False
, boptsTests = False
, boptsTestOpts = defaultTestOpts
, boptsBenchmarks = False
, boptsBenchmarkOpts = defaultBenchmarkOpts
, boptsExec = []
, boptsOnlyConfigure = False
, boptsReconfigure = False
, boptsCabalVerbose = False
}
-- | Options for the 'FinalAction' 'DoTests'
data TestOpts =
TestOpts {toRerunTests :: !Bool -- ^ Whether successful tests will be run gain
,toAdditionalArgs :: ![String] -- ^ Arguments passed to the test program
,toCoverage :: !Bool -- ^ Generate a code coverage report
,toDisableRun :: !Bool -- ^ Disable running of tests
} deriving (Eq,Show)
defaultTestOpts :: TestOpts
defaultTestOpts = TestOpts
{ toRerunTests = True
, toAdditionalArgs = []
, toCoverage = False
, toDisableRun = False
}
-- | Options for the 'FinalAction' 'DoBenchmarks'
data BenchmarkOpts =
BenchmarkOpts {beoAdditionalArgs :: !(Maybe String) -- ^ Arguments passed to the benchmark program
,beoDisableRun :: !Bool -- ^ Disable running of benchmarks
} deriving (Eq,Show)
defaultBenchmarkOpts :: BenchmarkOpts
defaultBenchmarkOpts = BenchmarkOpts
{ beoAdditionalArgs = Nothing
, beoDisableRun = False
}
data FileWatchOpts
= NoFileWatch
| FileWatch
| FileWatchPoll
deriving (Show,Eq)
-- | Package dependency oracle.
newtype PkgDepsOracle =
PkgDeps PackageName
deriving (Show,Typeable,Eq,Hashable,Binary,NFData)
-- | Stored on disk to know whether the flags have changed or any
-- files have changed.
data ConfigCache = ConfigCache
{ configCacheOpts :: !ConfigureOpts
-- ^ All options used for this package.
, configCacheDeps :: !(Set GhcPkgId)
-- ^ The GhcPkgIds of all of the dependencies. Since Cabal doesn't take
-- the complete GhcPkgId (only a PackageIdentifier) in the configure
-- options, just using the previous value is insufficient to know if
-- dependencies have changed.
, configCacheComponents :: !(Set S.ByteString)
-- ^ The components to be built. It's a bit of a hack to include this in
-- here, as it's not a configure option (just a build option), but this
-- is a convenient way to force compilation when the components change.
, configCacheHaddock :: !Bool
-- ^ Are haddocks to be built?
}
deriving (Generic,Eq,Show)
instance Binary ConfigCache where
put x = do
-- magic string
putWord8 1
putWord8 3
putWord8 4
putWord8 8
gput $ from x
get = do
1 <- getWord8
3 <- getWord8
4 <- getWord8
8 <- getWord8
fmap to gget
instance NFData ConfigCache
instance HasStructuralInfo ConfigCache
instance HasSemanticVersion ConfigCache
-- | A task to perform when building
data Task = Task
{ taskProvides :: !PackageIdentifier -- ^ the package/version to be built
, taskType :: !TaskType -- ^ the task type, telling us how to build this
, taskConfigOpts :: !TaskConfigOpts
, taskPresent :: !(Map PackageIdentifier GhcPkgId) -- ^ GhcPkgIds of already-installed dependencies
}
deriving Show
-- | Given the IDs of any missing packages, produce the configure options
data TaskConfigOpts = TaskConfigOpts
{ tcoMissing :: !(Set PackageIdentifier)
-- ^ Dependencies for which we don't yet have an GhcPkgId
, tcoOpts :: !(Map PackageIdentifier GhcPkgId -> ConfigureOpts)
-- ^ Produce the list of options given the missing @GhcPkgId@s
}
instance Show TaskConfigOpts where
show (TaskConfigOpts missing f) = concat
[ "Missing: "
, show missing
, ". Without those: "
, show $ f Map.empty
]
-- | The type of a task, either building local code or something from the
-- package index (upstream)
data TaskType = TTLocal LocalPackage
| TTUpstream Package InstallLocation
deriving Show
taskLocation :: Task -> InstallLocation
taskLocation task =
case taskType task of
TTLocal _ -> Local
TTUpstream _ loc -> loc
-- | A complete plan of what needs to be built and how to do it
data Plan = Plan
{ planTasks :: !(Map PackageName Task)
, planFinals :: !(Map PackageName (Task, LocalPackageTB))
-- ^ Final actions to be taken (test, benchmark, etc)
, planUnregisterLocal :: !(Map GhcPkgId (PackageIdentifier, Maybe Text))
-- ^ Text is reason we're unregistering, for display only
, planInstallExes :: !(Map Text InstallLocation)
-- ^ Executables that should be installed after successful building
}
deriving Show
-- | Basic information used to calculate what the configure options are
data BaseConfigOpts = BaseConfigOpts
{ bcoSnapDB :: !(Path Abs Dir)
, bcoLocalDB :: !(Path Abs Dir)
, bcoSnapInstallRoot :: !(Path Abs Dir)
, bcoLocalInstallRoot :: !(Path Abs Dir)
, bcoBuildOpts :: !BuildOpts
}
-- | Render a @BaseConfigOpts@ to an actual list of options
configureOpts :: EnvConfig
-> BaseConfigOpts
-> Map PackageIdentifier GhcPkgId -- ^ dependencies
-> Bool -- ^ wanted?
-> InstallLocation
-> Package
-> ConfigureOpts
configureOpts econfig bco deps wanted loc package = ConfigureOpts
{ coDirs = configureOptsDirs bco loc package
, coNoDirs = configureOptsNoDir econfig bco deps wanted package
}
configureOptsDirs :: BaseConfigOpts
-> InstallLocation
-> Package
-> [String]
configureOptsDirs bco loc package = concat
[ ["--user", "--package-db=clear", "--package-db=global"]
, map (("--package-db=" ++) . toFilePath) $ case loc of
Snap -> [bcoSnapDB bco]
Local -> [bcoSnapDB bco, bcoLocalDB bco]
, [ "--libdir=" ++ toFilePathNoTrailingSlash (installRoot </> $(mkRelDir "lib"))
, "--bindir=" ++ toFilePathNoTrailingSlash (installRoot </> bindirSuffix)
, "--datadir=" ++ toFilePathNoTrailingSlash (installRoot </> $(mkRelDir "share"))
, "--libexecdir=" ++ toFilePathNoTrailingSlash (installRoot </> $(mkRelDir "libexec"))
, "--sysconfdir=" ++ toFilePathNoTrailingSlash (installRoot </> $(mkRelDir "etc"))
, "--docdir=" ++ toFilePathNoTrailingSlash docDir
, "--htmldir=" ++ toFilePathNoTrailingSlash docDir
, "--haddockdir=" ++ toFilePathNoTrailingSlash docDir]
]
where
toFilePathNoTrailingSlash = dropTrailingPathSeparator . toFilePath
installRoot =
case loc of
Snap -> bcoSnapInstallRoot bco
Local -> bcoLocalInstallRoot bco
docDir =
case pkgVerDir of
Nothing -> installRoot </> docDirSuffix
Just dir -> installRoot </> docDirSuffix </> dir
pkgVerDir =
parseRelDir (packageIdentifierString (PackageIdentifier (packageName package)
(packageVersion package)) ++
[pathSeparator])
-- | Same as 'configureOpts', but does not include directory path options
configureOptsNoDir :: EnvConfig
-> BaseConfigOpts
-> Map PackageIdentifier GhcPkgId -- ^ dependencies
-> Bool -- ^ wanted?
-> Package
-> [String]
configureOptsNoDir econfig bco deps wanted package = concat
[ depOptions
, ["--enable-library-profiling" | boptsLibProfile bopts || boptsExeProfile bopts]
, ["--enable-executable-profiling" | boptsExeProfile bopts]
, map (\(name,enabled) ->
"-f" <>
(if enabled
then ""
else "-") <>
flagNameString name)
(Map.toList (packageFlags package))
, concatMap (\x -> ["--ghc-options", T.unpack x]) allGhcOptions
, map (("--extra-include-dirs=" ++) . T.unpack) (Set.toList (configExtraIncludeDirs config))
, map (("--extra-lib-dirs=" ++) . T.unpack) (Set.toList (configExtraLibDirs config))
, if whichCompiler (envConfigCompilerVersion econfig) == Ghcjs
then ["--ghcjs"]
else []
]
where
config = getConfig econfig
bopts = bcoBuildOpts bco
depOptions = map (uncurry toDepOption) $ Map.toList deps
where
toDepOption =
if envConfigCabalVersion econfig >= $(mkVersion "1.22")
then toDepOption1_22
else toDepOption1_18
toDepOption1_22 ident gid = concat
[ "--dependency="
, packageNameString $ packageIdentifierName ident
, "="
, ghcPkgIdString gid
]
toDepOption1_18 ident _gid = concat
[ "--constraint="
, packageNameString name
, "=="
, versionString version
]
where
PackageIdentifier name version = ident
ghcOptionsMap = configGhcOptions $ getConfig econfig
allGhcOptions = concat
[ fromMaybe [] $ Map.lookup Nothing ghcOptionsMap
, fromMaybe [] $ Map.lookup (Just $ packageName package) ghcOptionsMap
, if wanted
then boptsGhcOptions bopts
else []
]
-- | Get set of wanted package names from locals.
wantedLocalPackages :: [LocalPackage] -> Set PackageName
wantedLocalPackages = Set.fromList . map (packageName . lpPackage) . filter lpWanted
-- | One-way conversion to serialized time.
modTime :: UTCTime -> ModTime
modTime x =
ModTime
( toModifiedJulianDay
(utctDay x)
, toRational
(utctDayTime x))
data Installed = Library PackageIdentifier GhcPkgId | Executable PackageIdentifier
deriving (Show, Eq, Ord)
-- | Configure options to be sent to Setup.hs configure
data ConfigureOpts = ConfigureOpts
{ coDirs :: ![String]
-- ^ Options related to various paths. We separate these out since they do
-- not have an impact on the contents of the compiled binary for checking
-- if we can use an existing precompiled cache.
, coNoDirs :: ![String]
}
deriving (Show, Eq, Generic)
instance Binary ConfigureOpts
instance HasStructuralInfo ConfigureOpts
instance NFData ConfigureOpts
-- | Information on a compiled package: the library conf file (if relevant),
-- and all of the executable paths.
data PrecompiledCache = PrecompiledCache
-- Use FilePath instead of Path Abs File for Binary instances
{ pcLibrary :: !(Maybe FilePath)
-- ^ .conf file inside the package database
, pcExes :: ![FilePath]
-- ^ Full paths to executables
}
deriving (Show, Eq, Generic)
instance Binary PrecompiledCache
instance HasSemanticVersion PrecompiledCache
instance HasStructuralInfo PrecompiledCache
instance NFData PrecompiledCache
| robstewart57/stack | src/Stack/Types/Build.hs | bsd-3-clause | 29,426 | 0 | 21 | 9,239 | 5,598 | 3,063 | 2,535 | 682 | 5 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.PixelRectangles.Histogram
-- Copyright : (c) Sven Panne 2002-2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- This module corresponds to a part of section 3.6.1 (Pixel Storage Modes) of
-- the OpenGL 2.1 specs.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.PixelRectangles.Histogram (
Sink(..), histogram, Reset(..), getHistogram, resetHistogram,
histogramRGBASizes, histogramLuminanceSize
) where
import Foreign.Marshal.Utils
import Graphics.Rendering.OpenGL.GL.Capability
import Graphics.Rendering.OpenGL.GL.PeekPoke
import Graphics.Rendering.OpenGL.GL.PixelData
import Graphics.Rendering.OpenGL.GL.PixelRectangles.ColorTable
import Graphics.Rendering.OpenGL.GL.PixelRectangles.Reset
import Graphics.Rendering.OpenGL.GL.PixelRectangles.Sink
import Graphics.Rendering.OpenGL.GL.StateVar
import Graphics.Rendering.OpenGL.GL.Texturing.PixelInternalFormat
import Graphics.Rendering.OpenGL.GL.VertexSpec
import Graphics.Rendering.OpenGL.Raw
--------------------------------------------------------------------------------
data HistogramTarget =
Histogram
| ProxyHistogram
marshalHistogramTarget :: HistogramTarget -> GLenum
marshalHistogramTarget x = case x of
Histogram -> gl_HISTOGRAM
ProxyHistogram -> gl_PROXY_HISTOGRAM
proxyToHistogramTarget :: Proxy -> HistogramTarget
proxyToHistogramTarget x = case x of
NoProxy -> Histogram
Proxy -> ProxyHistogram
--------------------------------------------------------------------------------
histogram :: Proxy -> StateVar (Maybe (GLsizei, PixelInternalFormat, Sink))
histogram proxy =
makeStateVarMaybe
(return CapHistogram) (getHistogram' proxy) (setHistogram proxy)
getHistogram' :: Proxy -> IO (GLsizei, PixelInternalFormat, Sink)
getHistogram' proxy = do
w <- getHistogramParameteri fromIntegral proxy HistogramWidth
f <- getHistogramParameteri unmarshalPixelInternalFormat proxy HistogramFormat
s <- getHistogramParameteri unmarshalSink proxy HistogramSink
return (w, f, s)
getHistogramParameteri ::
(GLint -> a) -> Proxy -> GetHistogramParameterPName -> IO a
getHistogramParameteri f proxy p =
with 0 $ \buf -> do
glGetHistogramParameteriv
(marshalHistogramTarget (proxyToHistogramTarget proxy))
(marshalGetHistogramParameterPName p)
buf
peek1 f buf
setHistogram :: Proxy -> (GLsizei, PixelInternalFormat, Sink) -> IO ()
setHistogram proxy (w, int, sink) =
glHistogram
(marshalHistogramTarget (proxyToHistogramTarget proxy))
w
(marshalPixelInternalFormat' int)
(marshalSink sink)
--------------------------------------------------------------------------------
getHistogram :: Reset -> PixelData a -> IO ()
getHistogram reset pd =
withPixelData pd $
glGetHistogram
(marshalHistogramTarget Histogram)
(marshalReset reset)
--------------------------------------------------------------------------------
resetHistogram :: IO ()
resetHistogram = glResetHistogram (marshalHistogramTarget Histogram)
--------------------------------------------------------------------------------
data GetHistogramParameterPName =
HistogramWidth
| HistogramFormat
| HistogramRedSize
| HistogramGreenSize
| HistogramBlueSize
| HistogramAlphaSize
| HistogramLuminanceSize
| HistogramSink
marshalGetHistogramParameterPName :: GetHistogramParameterPName -> GLenum
marshalGetHistogramParameterPName x = case x of
HistogramWidth -> gl_HISTOGRAM_WIDTH
HistogramFormat -> gl_HISTOGRAM_FORMAT
HistogramRedSize -> gl_HISTOGRAM_RED_SIZE
HistogramGreenSize -> gl_HISTOGRAM_GREEN_SIZE
HistogramBlueSize -> gl_HISTOGRAM_BLUE_SIZE
HistogramAlphaSize -> gl_HISTOGRAM_ALPHA_SIZE
HistogramLuminanceSize -> gl_HISTOGRAM_LUMINANCE_SIZE
HistogramSink -> gl_HISTOGRAM_SINK
--------------------------------------------------------------------------------
histogramRGBASizes :: Proxy -> GettableStateVar (Color4 GLsizei)
histogramRGBASizes proxy =
makeGettableStateVar $ do
r <- getHistogramParameteri fromIntegral proxy HistogramRedSize
g <- getHistogramParameteri fromIntegral proxy HistogramGreenSize
b <- getHistogramParameteri fromIntegral proxy HistogramBlueSize
a <- getHistogramParameteri fromIntegral proxy HistogramAlphaSize
return $ Color4 r g b a
histogramLuminanceSize :: Proxy -> GettableStateVar GLsizei
histogramLuminanceSize proxy =
makeGettableStateVar $
getHistogramParameteri fromIntegral proxy HistogramLuminanceSize
| hesiod/OpenGL | src/Graphics/Rendering/OpenGL/GL/PixelRectangles/Histogram.hs | bsd-3-clause | 4,803 | 0 | 13 | 667 | 847 | 465 | 382 | 90 | 8 |
-- | Module: Acme.LOLCAT
-- Copyright: (c) 2013 Antonio Nikishaev
-- License: BSD
-- Maintainer: me@lelf.lu
--
-- >>> (OH HAI I CAN HAZ ЙO? THXBYE <*> putStrLn) "LOL" == ()
-- LOL
-- True
{-# LANGUAGE Unsafe #-}
module Acme.LOLCAT.IO (OH(..),HAI(..),I(..),CAN(..),HAZ(..),
IO(..),ÏO(..),ЙО(..),ЙO(..),YO(..),
(?),THXBYE(..)) where
import Prelude hiding (IO)
import System.IO.Unsafe (unsafePerformIO)
data HAI a b c d e = HAI a b c d e
data OH a b c d e = OH a b c d e
data I = I
data IO = IO
data ÏO = ÏO
data ЙО = ЙО
data ЙO = ЙO
data YO = YO
data CAN = CAN
data HAZ = HAZ
data THXBYE = THXBYE
_?_ = return unsafePerformIO
| llelf/acme-lolcat | Acme/LOLCAT/IO.hs | bsd-3-clause | 711 | 9 | 7 | 194 | 248 | 159 | 89 | 18 | 1 |
module MaybeHero.World
( World
, mkWorld
, moveRoom
, currentRoom
, lookupRoom
, lookupRoomStrict
, rooms
, roomDestinations
, showCurrentInventory
) where
import qualified Data.Map as Map
import qualified Data.Maybe as Maybe
import qualified Data.List as List
import qualified MaybeHero.Room as Room
import qualified MaybeHero.Inventory as I
import qualified MaybeHero.GameObject as GO
type RoomName = String
type Inventory = [I.MoveableItem]
data World = World (Map.Map RoomName Room.Room) RoomName Inventory
mkWorld :: (Map.Map RoomName Room.Room) -> RoomName -> Inventory -> World
mkWorld roomMap roomName inventory = World roomMap roomName inventory
lookupRoomStrict :: String -> World -> Maybe Room.Room
lookupRoomStrict s (World roomMap _ _) = Map.lookup s roomMap
lookupRoom :: String -> World -> Room.Room
lookupRoom s world = Maybe.maybe message id (lookupRoomStrict s world)
where message = (error $ "Room does not exist for name " ++ s)
moveRoom :: String -> World -> Maybe World
moveRoom direction world@(World roomMap _ inventory) = do
newRoomName <- Map.lookup direction $ Room.roomOrientation $ currentRoom world
return $ World roomMap newRoomName inventory
currentRoom :: World -> Room.Room
currentRoom world@(World roomMap currentRoomName _) = lookupRoom currentRoomName world
currentInventory :: World -> Inventory
currentInventory (World _ _ inventory) = inventory
showCurrentInventory :: World -> String
showCurrentInventory = concat . List.intersperse ", " . map GO.objectName . currentInventory
rooms :: World -> [Room.Room]
rooms (World roomMap _ _) = Map.elems roomMap
roomDestinations :: World -> [String]
roomDestinations w = do
room <- rooms w
orientation <- Map.elems $ Room.roomOrientation room
return orientation
| gtrogers/maybe-hero | src/MaybeHero/World.hs | bsd-3-clause | 1,768 | 0 | 11 | 270 | 547 | 292 | 255 | 43 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE PolyKinds #-}
{-# OPTIONS_HADDOCK not-home #-}
module Servant.API.QueryParam (QueryFlag, QueryParam, QueryParams) where
import Data.Typeable (Typeable)
import GHC.TypeLits (Symbol)
-- | Lookup the value associated to the @sym@ query string parameter
-- and try to extract it as a value of type @a@.
--
-- Example:
--
-- >>> -- /books?author=<author name>
-- >>> type MyApi = "books" :> QueryParam "author" Text :> Get '[JSON] [Book]
data QueryParam (sym :: Symbol) a
deriving Typeable
-- | Lookup the values associated to the @sym@ query string parameter
-- and try to extract it as a value of type @[a]@. This is typically
-- meant to support query string parameters of the form
-- @param[]=val1¶m[]=val2@ and so on. Note that servant doesn't actually
-- require the @[]@s and will fetch the values just fine with
-- @param=val1¶m=val2@, too.
--
-- Example:
--
-- >>> -- /books?authors[]=<author1>&authors[]=<author2>&...
-- >>> type MyApi = "books" :> QueryParams "authors" Text :> Get '[JSON] [Book]
data QueryParams (sym :: Symbol) a
deriving Typeable
-- | Lookup a potentially value-less query string parameter
-- with boolean semantics. If the param @sym@ is there without any value,
-- or if it's there with value "true" or "1", it's interpreted as 'True'.
-- Otherwise, it's interpreted as 'False'.
--
-- Example:
--
-- >>> -- /books?published
-- >>> type MyApi = "books" :> QueryFlag "published" :> Get '[JSON] [Book]
data QueryFlag (sym :: Symbol)
-- $setup
-- >>> import Servant.API
-- >>> import Data.Aeson
-- >>> import Data.Text
-- >>> data Book
-- >>> instance ToJSON Book where { toJSON = undefined }
| zerobuzz/servant | servant/src/Servant/API/QueryParam.hs | bsd-3-clause | 1,790 | 0 | 5 | 334 | 114 | 89 | 25 | -1 | -1 |
{-# LANGUAGE RecursiveDo #-}
module Main where
import Reflex
import Reflex.Gloss.Scene
import Reflex.Monad.Time
import Reflex.Animation
import Data.Foldable
import Data.Traversable
import Reflex.Monad
import Graphics.Gloss
import Widgets
foldMerge :: MonadReflex t m => a -> [Event t (a -> a)] -> m (Dynamic t a)
foldMerge initial events = foldDyn ($) initial (mergeWith (.) events)
renderCanvas :: Vector -> [Picture] -> Picture
renderCanvas (sx, sy) drawings = mconcat
[ color black $ rectangleWire sx sy
, mconcat drawings
]
pen :: Reflex t => Vector -> Behavior t Color -> Scene t (Event t Picture)
pen size currentCol = mdo
start <- mouseDown LeftButton <$> targetRect (constant size)
stop <- mouseUp LeftButton <$> targetWindow
drawing <- widgetHold (return never) $ leftmost
[ scrible stop <$ start
, return never <$ stop
]
return (switch (current drawing))
where
scrible stop = do
updates <- observe =<< localMouse
points <- current <$> foldDyn (:) [] (clampSize <$> updates)
let drawing = drawPath <$> points <*> currentCol
render $ drawing
return (tag drawing stop)
clampSize (x, y) = (clamp (-w/2, w/2) x, clamp (-h/2, h/2) y)
where (w, h) = size
drawPath points c = color c $ line points
palette :: Reflex t => [Color] -> Scene t (Behavior t Color)
palette colors = do
clicks <- forM indexed $ \(i, c) -> ith i $ do
target <- targetRect (pure (30, 30))
render $ pure (drawColor c)
(click, _) <- clicked LeftButton target
return (c <$ click)
currentCol <- hold (head colors) (leftmost clicks)
render (drawSelected <$> currentCol)
return currentCol
where
height = fromIntegral (length colors) * 40 + 50
ith i = translation (0, i * 40 - height/2)
indexed = zip [1..] colors
drawColor c = color c $ rectangleSolid 30 30
drawSelected c = translate 0 (-(height/2) - 25) $ color c $ rectangleSolid 40 40
canvas :: Reflex t => Vector -> Scene t ()
canvas size = do
currentCol <- translation (200, 0)
$ palette [black, red, green, blue]
scribble <- pen size currentCol
drawings <- current <$> foldDyn (:) [] scribble
render $ renderCanvas <$> pure size <*> drawings
widget :: Reflex t => Scene t ()
widget = canvas (300, 300)
main = playSceneGraph display background frequency widget
where
display = InWindow "Scribble3" (600, 600) (0, 0)
background = white
frequency = 30 | Saulzar/scribble | src/Scribble3.hs | bsd-3-clause | 2,557 | 0 | 17 | 668 | 1,027 | 516 | 511 | 62 | 1 |
-- | Multipart names.
module Text.MultipartNames.MultipartName(
MultipartName,
mkMultipartName,
mkMultipartNameFromWords,
isLegalSegment,
toSegments
) where
-- import Control.Lens
import Data.CaseInsensitive(CI)
import qualified Data.CaseInsensitive as CI
import Data.Char(isAscii, isLetter)
-- | An opaque type that represents a multipart name. The initial
-- character of each segment must be a cased letter. Currently, only
-- ASCII letters are allowed as first characters of segments.
newtype MultipartName = MultipartName [CI String]
deriving (Eq, Ord, Show)
-- | Returns the segments of the name
toSegments :: MultipartName -> [CI String]
toSegments (MultipartName ss) = ss
-- | Creates a multipart name from its segments.
mkMultipartName :: [String] -> MultipartName
mkMultipartName ss
| null ss = error "mkMultipartName []: argument cannot be null"
| all isLegalSegment ss
= MultipartName $ map CI.mk ss
| otherwise = error msg
where
msg = "mkMultipartName " ++ show ss
++ ": all segments must start with a cased letter"
-- | Creates a multipart name from words. Equivalent to
-- @mkMultipartName . words@.
mkMultipartNameFromWords :: String -> MultipartName
mkMultipartNameFromWords = mkMultipartName . words
-- | Is this string a legal segment for a 'MultipartName'?
isLegalSegment :: String -> Bool
isLegalSegment seg = case seg of
[] -> False
c : _ -> isAscii c && isLetter c
| nedervold/multipart-names | src/Text/MultipartNames/MultipartName.hs | bsd-3-clause | 1,466 | 6 | 9 | 285 | 283 | 154 | 129 | 27 | 2 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.ES3Compatibility
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- All raw functions, tokens and types from the ARB_ES3_compatibility extension,
-- see <http://www.opengl.org/registry/specs/ARB/ES3_compatibility.txt>.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.ES3Compatibility (
-- * Tokens
gl_COMPRESSED_RGB8_ETC2,
gl_COMPRESSED_SRGB8_ETC2,
gl_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,
gl_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,
gl_COMPRESSED_RGBA8_ETC2_EAC,
gl_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,
gl_COMPRESSED_R11_EAC,
gl_COMPRESSED_SIGNED_R11_EAC,
gl_COMPRESSED_RG11_EAC,
gl_COMPRESSED_SIGNED_RG11_EAC,
gl_PRIMITIVE_RESTART_FIXED_INDEX,
gl_ANY_SAMPLES_PASSED_CONSERVATIVE,
gl_MAX_ELEMENT_INDEX
) where
import Graphics.Rendering.OpenGL.Raw.Core31.Types
gl_COMPRESSED_RGB8_ETC2 :: GLenum
gl_COMPRESSED_RGB8_ETC2 = 0x9274
gl_COMPRESSED_SRGB8_ETC2 :: GLenum
gl_COMPRESSED_SRGB8_ETC2 = 0x9275
gl_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 :: GLenum
gl_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276
gl_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 :: GLenum
gl_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9277
gl_COMPRESSED_RGBA8_ETC2_EAC :: GLenum
gl_COMPRESSED_RGBA8_ETC2_EAC = 0x9278
gl_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC :: GLenum
gl_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279
gl_COMPRESSED_R11_EAC :: GLenum
gl_COMPRESSED_R11_EAC = 0x9270
gl_COMPRESSED_SIGNED_R11_EAC :: GLenum
gl_COMPRESSED_SIGNED_R11_EAC = 0x9271
gl_COMPRESSED_RG11_EAC :: GLenum
gl_COMPRESSED_RG11_EAC = 0x9272
gl_COMPRESSED_SIGNED_RG11_EAC :: GLenum
gl_COMPRESSED_SIGNED_RG11_EAC = 0x9273
gl_PRIMITIVE_RESTART_FIXED_INDEX :: GLenum
gl_PRIMITIVE_RESTART_FIXED_INDEX = 0x8D69
gl_ANY_SAMPLES_PASSED_CONSERVATIVE :: GLenum
gl_ANY_SAMPLES_PASSED_CONSERVATIVE = 0x8D6A
gl_MAX_ELEMENT_INDEX :: GLenum
gl_MAX_ELEMENT_INDEX = 0x8D6B
| mfpi/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/ARB/ES3Compatibility.hs | bsd-3-clause | 2,197 | 0 | 4 | 228 | 205 | 135 | 70 | 41 | 1 |
module Language.Xi.Base.Parser where
| fizruk/xi-base | src/Language/Xi/Base/Parser.hs | bsd-3-clause | 37 | 0 | 3 | 3 | 8 | 6 | 2 | 1 | 0 |
module Parser.Internal where
import Control.Applicative
( (<|>)
)
import ASTree
( Number(..)
, Expr(..)
, LatCalError(..)
)
import Text.ParserCombinators.ReadP
( ReadP
, readP_to_S
, optional
, eof
, char
, munch
, (<++)
, chainl1
, string
, between
, skipSpaces
, option
, satisfy
)
import Data.Char
( isDigit
)
{- | Parse a latex expression string to either a parseerror or a latex
- expression. -}
parseString :: String
-- ^ String to parse.
-> Either LatCalError Expr
parseString str = case readP_to_S parseExpr str of
[(program, "")] -> Right program
_ -> Left $ ParserError "Parse error"
parseExpr :: ReadP Expr
parseExpr = do
expr <- token parseExpr0
eof
return expr
parseExpr0 :: ReadP Expr
parseExpr0 = parseExpr1 `chainl1` plusminus
where
plusminus = plus <|> minus
plus = infixOp "+" Sum
minus = infixOp "-" Minus
parseExpr1 :: ReadP Expr
parseExpr1 = parseExpr2 `chainl1` mult
where
mult = mult1 <|> mult2 <|> mult3
mult1 = token (optional $ char '*') >> return Product
mult2 = infixOp "\\cdot" Product
mult3 = infixOp "\\times" Product
parseExpr2 :: ReadP Expr
parseExpr2 = parseExpr3 `chainl1` pow
where
pow = infixOp "^" Power
parseExpr3 :: ReadP Expr
parseExpr3 = fact <|> parseExpr4 <|> divi <|> binom <|> expo
where
divi = do
_ <- string "\\frac"
expr1 <- between (token $ char '{') (token $ char '}') parseExpr0
expr2 <- between (token $ char '{') (token $ char '}') parseExpr0
return $ Fraction expr1 expr2
fact = do
expr <- token parseExpr4
_ <- char '!'
return $ Factorial expr
binom = do
_ <- token $ string "\\binom"
expr1 <- between (token $ char '{') (token $ char '}') parseExpr0
expr2 <- between (token $ char '{') (token $ char '}') parseExpr0
return $ Binomial expr1 expr2
expo = do
_ <- token $ string "exp"
expr <- between (token $ char '(') (token $ char ')') parseExpr0
return $ Power (Literal $ Real (exp 1)) expr
parseExpr4 :: ReadP Expr
parseExpr4 = real <++ whole <++ constant <++ bracket
where
real = token $ do
skipSpaces
minus <- option ' ' (char '-')
first <- satisfy (`elem` ['0'..'9'])
digits1 <- munch isDigit
_ <- char '.'
digits2 <- munch isDigit
let int = Whole $ read (minus:first:digits1)
frac = Real $ read ((minus:"0.") ++ digits2)
return $ Literal (int + frac)
whole = do
skipSpaces
minus <- option ' ' (char '-')
first <- satisfy (`elem` ['0'..'9'])
digits <- munch isDigit
return $ Literal (Whole $ read (minus:first:digits))
bracket = bracket1 <|> bracket2 <|> bracket3
bracket1 = parseBracket (char '(') (char ')')
bracket2 = parseBracket (string "\\left(") (string "\\right)")
bracket3 = parseBracket (char '{') (char '}')
parseBracket s e = between (token s) (token e) parseExpr0
constant = pi' <|> euler
pi' = token (string "\\pi") >> return (Literal $ Real pi)
euler = token (char 'e') >> return (Literal $ Real (exp 1))
infixOp :: String -> (a -> a -> a) -> ReadP (a -> a -> a)
infixOp x f = token (string x) >> return f
token :: ReadP a -> ReadP a
token f = skipSpaces >> f >>= \v -> skipSpaces >> return v
| bus000/latex-calculator | src/Parser/Internal.hs | bsd-3-clause | 3,436 | 0 | 18 | 996 | 1,258 | 635 | 623 | 97 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Main where
import qualified System.Exit as Exit
import qualified TsParse as T
main :: IO ()
main = T.runAllTests >>= \b ->
if b then Exit.exitSuccess else Exit.exitFailure
| massysett/tsparse | test-tsp.hs | bsd-3-clause | 217 | 0 | 8 | 38 | 57 | 36 | 21 | 7 | 2 |
-- | This module re-exports everything from 'Pos.Chain.Block.Logic.*'.
module Pos.Chain.Block.Logic
( module Pos.Chain.Block.Logic.Integrity
) where
import Pos.Chain.Block.Logic.Integrity
| input-output-hk/pos-haskell-prototype | chain/src/Pos/Chain/Block/Logic.hs | mit | 213 | 0 | 5 | 42 | 28 | 21 | 7 | 3 | 0 |
module Interaction where
import Logic
import Browser
-- | number of sentences
type Window = Int
type
data DB = DB {
retrieve :: Int -> Maybe Conversation,
update :: Int -> Conversation -> DB,
data Browsing = Browsing
{ browser :: Browser
data State = State
{ conversations :: [(Int,Browsing)]
}
data Modify
= Up Int
| Down Int
| Append String
| Keep Int Bool
| Refresh
| Taint Int Int
data Request
= SetUser String
| GetPage
| GetConversation Int
data Interaction a
= Modification (Modify -> State -> State)
| Interface (Request -> a
| paolino/qrmaniacs | Interaction.hs | mit | 577 | 44 | 6 | 141 | 205 | 126 | 79 | -1 | -1 |
{-
SockeyeSymbolTable.hs: Symbol Table for Sockeye
Part of Sockeye
Copyright (c) 2017, ETH Zurich.
All rights reserved.
This file is distributed under the terms in the attached LICENSE file.
If you do not find this file, copies can be found by writing to:
ETH Zurich D-INFK, CAB F.78, Universitaetstrasse 6, CH-8092 Zurich,
Attn: Systems Group.
-}
module SockeyeSymbolTable
( module SockeyeSymbolTable
, module SockeyeAST
) where
import Data.Set (Set)
import Data.Map (Map)
import SockeyeASTMeta
import SockeyeAST
( NaturalSet(NaturalSet)
, NaturalRange(SingletonRange, LimitRange, BitsRange)
, natRangeMeta, base, limit, bits
, NaturalExpr(Addition, Subtraction, Multiplication, Slice, Concat, Variable, Literal)
, natExprMeta, natExprOp1, natExprOp2, bitRange, varName, natural
)
data Sockeye = Sockeye
{ entryPoint :: FilePath
, files :: Map FilePath SockeyeFile
}
deriving (Show)
data SockeyeFile = SockeyeFile
{ sockeyeFileMeta :: ASTMeta
, modules :: Map String Module
, types :: Map String NamedType
}
deriving (Show)
instance MetaAST SockeyeFile where
meta = sockeyeFileMeta
data Module
= Module
{ moduleMeta :: ASTMeta
, parameters :: Map String ModuleParameter
, parameterOrder :: [String]
, constants :: Map String NamedConstant
, inputPorts :: Set String
, outputPorts :: Map String Node
, instances :: Map String Instance
, nodes :: Map String Node
}
| ImportedModule
{ moduleMeta :: ASTMeta
, moduleFile :: !FilePath
, origModName :: !String
}
deriving (Show)
instance MetaAST Module where
meta = moduleMeta
data ModuleParameter = ModuleParameter
{ paramMeta :: ASTMeta
, paramRange :: NaturalSet
}
deriving (Show)
instance MetaAST ModuleParameter where
meta = paramMeta
data Instance = Instance
{ instMeta :: ASTMeta
, instModule :: !String
, instArrSize :: Maybe ArraySize
}
deriving (Show)
instance MetaAST Instance where
meta = instMeta
data Node = Node
{ nodeMeta :: ASTMeta
, nodeType :: NodeType
, nodeArrSize :: Maybe ArraySize
}
deriving (Show)
instance MetaAST Node where
meta = nodeMeta
data NodeType = NodeType
{ nodeTypeMeta :: ASTMeta
, originDomain :: !Domain
, originType :: EdgeType
, targetDomain :: !Domain
, targetType :: Maybe EdgeType
}
deriving (Show)
instance MetaAST NodeType where
meta = nodeTypeMeta
data Domain
= Memory
| Interrupt
| Power
| Clock
deriving (Eq, Show)
data EdgeType
= TypeLiteral
{ edgeTypeMeta :: ASTMeta
, typeLiteral :: AddressType
}
| TypeName
{ edgeTypeMeta :: ASTMeta
, typeRef :: !String
}
deriving (Show)
instance MetaAST EdgeType where
meta = edgeTypeMeta
data NamedType
= NamedType
{ namedTypeMeta :: ASTMeta
, namedType :: AddressType
}
| ImportedType
{ namedTypeMeta :: ASTMeta
, typeFile :: !FilePath
, origTypeName :: !String
}
deriving (Show)
instance MetaAST NamedType where
meta = namedTypeMeta
data NamedConstant = NamedConstant
{ namedConstMeta :: ASTMeta
, namedConst :: !Integer
}
deriving (Show)
instance MetaAST NamedConstant where
meta = namedConstMeta
data ArraySize = ArraySize ASTMeta [NaturalSet]
deriving (Show)
instance MetaAST ArraySize where
meta (ArraySize m _) = m
data AddressType = AddressType ASTMeta [NaturalSet]
deriving (Show)
instance MetaAST AddressType where
meta (AddressType m _) = m
| kishoredbn/barrelfish | tools/sockeye/SockeyeSymbolTable.hs | mit | 4,001 | 0 | 9 | 1,288 | 823 | 487 | 336 | 128 | 0 |
--
--
--
-----------------
-- Exercise 5.17.
-----------------
--
--
--
module E'5'17 where
-- GHCi> [2 .. 2]
-- [2]
-- [n .. n] results in the list [n].
-- GHCi> [2, 7 .. 4]
-- [2]
-- [2, 7 .. 4] results in the list [2].
-- GHCi> [2, 2 .. 2]
-- [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
-- ,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
-- ,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
-- ,2,2,2,2,2,2,2,2,2,2,2,2,2Interrupted.
-- [n, n .. n] (ao.) results in an infinite calculation that has to be interrupted.
| pascal-knodel/haskell-craft | _/links/E'5'17.hs | mit | 509 | 0 | 2 | 92 | 25 | 24 | 1 | 1 | 0 |
module XML.GGXParseOut
( parseCPGraph
, parseCSGraph
, serializeGraph
, XML.GGXParseOut.getLHS
, XML.GGXParseOut.getRHS
, getNacs
, getMappings
) where
import Data.Maybe (fromMaybe, isJust)
import Abstract.Category as FC
import Abstract.Rewriting.DPO
import qualified Analysis.CriticalPairs as CP
import qualified Analysis.CriticalSequence as CS
import qualified Data.Graphs as G
import Data.TypedGraph
import Data.TypedGraph.Morphism
import qualified Rewriting.DPO.TypedGraph as GR
import XML.ParsedTypes
parseCPGraph :: (String,String,[CP.CriticalPair (TypedGraphMorphism a b)]) -> Overlappings
parseCPGraph (name1,name2,cps) = (name1,name2,overlaps)
where
overlaps = map (overlapsCP name2) cps
overlapsCP :: String -> CP.CriticalPair (TypedGraphMorphism a b) -> (ParsedTypedGraph, [Mapping], [Mapping], String, String)
overlapsCP name2 cs = (graph, mapM1, mapM2 ++ mapM2WithNac, nacName cs, csType cs)
where
(m1,m2) = case CP.getCriticalPairType cs of
CP.ProduceForbid -> fromMaybe (error "Error when exporting ProduceForbid") (CP.getCriticalPairComatches cs)
_ -> CP.getCriticalPairMatches cs
(graph, mapM1, mapM2) = serializePair m1 m2
mapM2WithNac = case CP.getCriticalPairType cs of
CP.ProduceForbid -> addNacMap
_ -> []
nacMatch = fromMaybe (error "Error when exporting ProduceForbid") (CP.getNacMatchOfCriticalPair cs)
addNacMap = getTgmMappings (Just (nacName cs)) nacMatch
nacName = parseNacName name2 CP.getNacIndexOfCriticalPair
csType = show . CP.getCriticalPairType
parseCSGraph :: (String,String,[CS.CriticalSequence (TypedGraphMorphism a b)]) -> Overlappings
parseCSGraph (name1,name2,cps) = (name1,name2,overlaps)
where
overlaps = map (overlapsCS name2) cps
overlapsCS :: String -> CS.CriticalSequence (TypedGraphMorphism a b)
-> (ParsedTypedGraph, [Mapping], [Mapping], String, String)
overlapsCS name2 cs = (graph, mapM1, mapM2 ++ mapM2WithNac, nacName cs, csType cs)
where
(m1,m2) = case CS.getCriticalSequenceType cs of
CS.DeleteForbid -> fromMaybe (error "Error when exporting DeleteForbid") (CS.getCriticalSequenceMatches cs)
CS.ForbidProduce -> fromMaybe (error "Error when exporting ForbidProduce") (CS.getCriticalSequenceMatches cs)
_ -> CS.getCriticalSequenceComatches cs
(graph, mapM1, mapM2) = serializePair m1 m2
mapM2WithNac = case CS.getCriticalSequenceType cs of
CS.DeleteForbid -> addNacMap
CS.ForbidProduce -> addNacMap
_ -> []
nacMatch = fromMaybe (error "Error when exporting DeleteForbid or ForbidProduce") (CS.getNacMatchOfCriticalSequence cs)
addNacMap = getTgmMappings (Just (nacName cs)) nacMatch
nacName = parseNacName name2 CS.getNacIndexOfCriticalSequence
csType = show . CS.getCriticalSequenceType
getTgmMappings :: Maybe String -> TypedGraphMorphism a b -> [Mapping]
getTgmMappings prefix tgm = nodesMorph ++ edgesMorph
where
nodeMap = applyNodeIdUnsafe tgm
edgeMap = applyEdgeIdUnsafe tgm
nodesMorph = map (\n -> ("N" ++ show (nodeMap n), prefix, "N" ++ show n)) (nodeIds $ domain tgm)
edgesMorph = map (\e -> ("E" ++ show (edgeMap e), prefix, "E" ++ show e)) (edgeIds $ domain tgm)
getLHS :: [Mapping] -> [Mapping] -> GR.TypedGraphRule a b -> ParsedTypedGraph
getLHS objNameN objNameE rule = serializeGraph objNameN objNameE $ GR.leftMorphism rule
getRHS :: [Mapping] -> [Mapping] -> GR.TypedGraphRule a b -> ParsedTypedGraph
getRHS objNameN objNameE rule = serializeGraph objNameN objNameE $ GR.rightMorphism rule
getNacs :: String -> GR.TypedGraphRule a b -> [(ParsedTypedGraph,[Mapping])]
getNacs ruleName rule = map getNac nacsWithIds
where
zipIds = zip ([0..]::[Int]) (nacs rule)
nacsWithIds = map (\(x,y) -> ("NAC_" ++ ruleName ++ "_" ++ show x, y)) zipIds
getNac :: (String, TypedGraphMorphism a b) -> (ParsedTypedGraph, [Mapping])
getNac (nacId,nac) = (graph, mappings)
where
(_,n,e) = serializeGraph [] [] nac
graph = (nacId, n, e)
mappings = getTgmMappings Nothing nac
getMappings :: GR.TypedGraphRule a b -> [Mapping]
getMappings rule = nodesMorph ++ edgesMorph
where
no = Nothing
invL = invert (GR.leftMorphism rule)
lr = GR.rightMorphism rule <&> invL
nodeMap = applyNodeIdUnsafe lr
nodes = filter (isJust . applyNodeId lr) (nodeIds $ domain lr)
nodesMorph = map (\n -> ("N" ++ show (nodeMap n), no, "N" ++ show n)) nodes
edgeMap = applyEdgeIdUnsafe lr
edges = filter (isJust . applyEdgeId lr) (edgeIds $ domain lr)
edgesMorph = map (\e -> ("E" ++ show (edgeMap e), no, "E" ++ show e)) edges
parseNacName :: String -> (t -> Maybe Int) -> t -> String
parseNacName ruleName f x = case f x of
Just n -> "NAC_" ++ ruleName ++ "_" ++ show n
Nothing -> ""
serializePair :: TypedGraphMorphism a b -> TypedGraphMorphism a b -> (ParsedTypedGraph, [Mapping], [Mapping])
serializePair m1 m2 = (serializeGraph [] [] m1, getTgmMappings Nothing m1, getTgmMappings Nothing m2)
serializeGraph :: [Mapping] -> [Mapping] -> TypedGraphMorphism a b -> ParsedTypedGraph
serializeGraph objNameNodes objNameEdges morphism = ("", nodes, edges)
where
graph = FC.codomain morphism
nodes = map (serializeNode (map (\(x,_,y) -> (x,y)) objNameNodes) graph) (G.nodeIds $ FC.domain graph)
edges = map (serializeEdge (map (\(x,_,y) -> (x,y)) objNameEdges) graph) (G.edges $ FC.domain graph)
serializeNode :: [(String,String)] -> TypedGraph a b -> G.NodeId -> ParsedTypedNode
serializeNode objName graph n = ("N" ++ show n,
lookup (show n) objName,
"N" ++ show (extractNodeType graph n))
serializeEdge :: [(String,String)] -> TypedGraph a b -> G.Edge (Maybe b) -> ParsedTypedEdge
serializeEdge objName graph e = ("E" ++ show (G.edgeId e),
lookup (show (G.edgeId e)) objName,
"E" ++ show (extractEdgeType graph (G.edgeId e)),
"N" ++ show (G.sourceId e),
"N" ++ show (G.targetId e))
| rodrigo-machado/verigraph | src/library/XML/GGXParseOut.hs | gpl-3.0 | 6,318 | 0 | 14 | 1,458 | 2,152 | 1,151 | 1,001 | 104 | 5 |
-----------------------------------------------------------------------------
-- |
-- Module : Control.Functor.Indexed
-- Copyright : (C) 2008 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : portable
--
----------------------------------------------------------------------------
module Control.Functor.Indexed
( IxFunctor(..)
, IxCopointed(..)
, IxPointed(..)
, IxApplicative(..)
) where
class IxFunctor f where
imap :: (a -> b) -> f j k a -> f j k b
class IxPointed m => IxApplicative m where
iap :: m i j (a -> b) -> m j k a -> m i k b
class IxFunctor m => IxPointed m where
ireturn :: a -> m i i a
class IxFunctor w => IxCopointed w where
iextract :: w i i a -> a
{-# RULES
"iextract/ireturn" iextract . ireturn = id
#-}
| urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav | Control/Functor/Indexed.hs | apache-2.0 | 875 | 4 | 10 | 177 | 217 | 118 | 99 | 15 | 0 |
<?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="it-IT">
<title>Code Dx | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/codedx/src/main/javahelp/org/zaproxy/zap/extension/codedx/resources/help_it_IT/helpset_it_IT.hs | apache-2.0 | 969 | 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="tr-TR">
<title>Pasif Tarama Kuralları - Beta | ZAP Uzantıları</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>İçindekiler</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>İçerik</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Arama</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favoriler</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/pscanrulesBeta/src/main/javahelp/org/zaproxy/zap/extension/pscanrulesBeta/resources/help_tr_TR/helpset_tr_TR.hs | apache-2.0 | 1,002 | 80 | 67 | 163 | 434 | 218 | 216 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Text.XmlHtml.TestCommon where
import Control.Exception as E
import System.IO.Unsafe
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit hiding (Test, Node)
------------------------------------------------------------------------------
-- | Tests a simple Bool property.
testIt :: TestName -> Bool -> Test
testIt name b = testCase name $ assertBool name b
------------------------------------------------------------------------------
-- Code adapted from ChasingBottoms.
--
-- Adding an actual dependency isn't possible because Cabal refuses to build
-- the package due to version conflicts.
--
-- isBottom is impossible to write, but very useful! So we defy the
-- impossible, and write it anyway.
isBottom :: a -> Bool
isBottom a = unsafePerformIO $
(E.evaluate a >> return False) `E.catches` [
E.Handler $ \ (_ :: PatternMatchFail) -> return True,
E.Handler $ \ (_ :: ErrorCall) -> return True,
E.Handler $ \ (_ :: NoMethodError) -> return True,
E.Handler $ \ (_ :: RecConError) -> return True,
E.Handler $ \ (_ :: RecUpdError) -> return True,
E.Handler $ \ (_ :: RecSelError) -> return True
]
------------------------------------------------------------------------------
isLeft :: Either a b -> Bool
isLeft = either (const True) (const False)
| 23Skidoo/xmlhtml | test/suite/Text/XmlHtml/TestCommon.hs | bsd-3-clause | 1,466 | 0 | 10 | 328 | 317 | 179 | 138 | 20 | 1 |
--
-- Data vault for metrics
--
--
-- Copyright © 2013-2014 Anchor Systems, Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
-- the 3-clause BSD licence.
--
{-# LANGUAGE OverloadedStrings #-}
module Vaultaire.Types.ContentsResponse
(
ContentsResponse(..),
) where
import Control.Applicative ((<$>), (<*>))
import Control.Exception (SomeException (..))
import qualified Data.ByteString as S
import Data.Packer (getBytes, getWord64LE, putBytes, putWord64LE, putWord8,
runPacking, runUnpacking)
import Test.QuickCheck
import Vaultaire.Classes.WireFormat
import Vaultaire.Types.Address
import Vaultaire.Types.SourceDict
data ContentsResponse = RandomAddress Address
| InvalidContentsOrigin
| ContentsListEntry Address SourceDict
| EndOfContentsList
| UpdateSuccess
| RemoveSuccess
deriving (Show, Eq)
instance WireFormat ContentsResponse where
fromWire bs
| bs == "\x00" = Right InvalidContentsOrigin
| bs == "\x03" = Right EndOfContentsList
| bs == "\x04" = Right UpdateSuccess
| bs == "\x05" = Right RemoveSuccess
| S.take 1 bs == "\x01" = RandomAddress <$> fromWire (S.drop 1 bs)
-- This relies on address being fixed-length when encoded
| S.take 1 bs == "\x02" = do
let body = S.drop 1 bs
let unpacker = (,) <$> getBytes 8 <*> (getWord64LE >>= getBytes . fromIntegral)
let (addr_bytes, dict_bytes ) = runUnpacking unpacker body
ContentsListEntry <$> fromWire addr_bytes <*> fromWire dict_bytes
| otherwise = Left $ SomeException $
userError "Invalid ContentsResponse packet"
toWire InvalidContentsOrigin = "\x00"
toWire (RandomAddress addr) = "\x01" `S.append` toWire addr
toWire (ContentsListEntry addr dict) =
let addr_bytes = toWire addr
dict_bytes = toWire dict
dict_len = S.length dict_bytes
in runPacking (dict_len + 17) $ do
putWord8 0x2
putBytes addr_bytes
putWord64LE $ fromIntegral dict_len
putBytes dict_bytes
-- Be aware there is also case such that:
-- toWire (ContentsListBypass addr b) =
-- "\x02" ...
-- so that raw encoded bytes stored on disk can be tunnelled through. See
-- Vaultaire.Types.ContentsListBypass for details
toWire EndOfContentsList = "\x03"
toWire UpdateSuccess = "\x04"
toWire RemoveSuccess = "\x05"
instance Arbitrary ContentsResponse where
arbitrary = oneof [ RandomAddress <$> arbitrary
, ContentsListEntry <$> arbitrary <*> arbitrary
, return EndOfContentsList
, return UpdateSuccess
, return RemoveSuccess ]
| afcowie/vaultaire-common | lib/Vaultaire/Types/ContentsResponse.hs | bsd-3-clause | 3,024 | 0 | 15 | 867 | 605 | 319 | 286 | 54 | 0 |
{- |
Module : $Header$
Description : some utilities for the abstract syntax
Copyright : (c) Christian Maeder and Uni Bremen 2003-2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : experimental
Portability : portable
utility functions and computations of meaningful positions for
various data types of the abstract syntax
-}
module HasCASL.AsUtils where
import HasCASL.As
import HasCASL.FoldType
import HasCASL.HToken
import Common.DocUtils
import Common.Id
import Common.Keywords
import Common.Parsec
import qualified Data.Set as Set
import qualified Text.ParserCombinators.Parsec as P
-- | the string for the universe type
typeUniverseS :: String
typeUniverseS = "Type"
-- | the id of the universe type
universeId :: Id
universeId = stringToId typeUniverseS
-- | the type universe
universe :: Kind
universe = ClassKind universeId
-- | the type universe
universeWithRange :: Range -> Kind
universeWithRange = ClassKind . simpleIdToId . Token typeUniverseS
-- | the name for the Unit type
unitTypeS :: String
unitTypeS = "Unit"
-- | the identifier for the Unit type
unitTypeId :: Id
unitTypeId = stringToId unitTypeS
-- | single step beta reduce type abstractions
redStep :: Type -> Maybe Type
redStep ty = case ty of
TypeAppl t1 t2 -> case t1 of
TypeAbs (TypeArg _ _ _ _ c _ _) b _ -> return $
foldType mapTypeRec
{ foldTypeName = \ t _ _ n -> if n == c then t2 else t
, foldTypeAbs = \ t v1@(TypeArg _ _ _ _ n _ _) tb p ->
if n == c then t else TypeAbs v1 tb p } b
ExpandedType _ t -> redStep $ TypeAppl t t2
KindedType t _ _ -> redStep $ TypeAppl t t2
_ -> do
r1 <- redStep t1
redStep $ TypeAppl r1 t2
ExpandedType e t -> fmap (ExpandedType e) $ redStep t
KindedType t k ps -> do
r <- redStep t
return $ KindedType r k ps
_ -> fail "unreducible"
strippedType :: Type -> Type
strippedType = foldType mapTypeRec
{ foldTypeAppl = \ trm f a -> let t = TypeAppl f a in
case redStep trm of
Nothing -> case f of
TypeName i _ 0
| i == lazyTypeId -> a
| isArrow i -> TypeAppl (toFunType PFunArr) a
_ -> t
Just r -> strippedType r
, foldTypeName = \ _ i k v -> TypeName (if v >= 0 then i else typeId) k v
, foldKindedType = \ _ t _ _ -> t
, foldExpandedType = \ _ _ t -> t }
eqStrippedType :: Type -> Type -> Bool
eqStrippedType t1 t2 = strippedType t1 == strippedType t2
-- | get top-level type constructor and its arguments and beta reduce
getTypeAppl :: Type -> (Type, [Type])
getTypeAppl = getTypeApplAux True
-- | get top-level type constructor and its arguments and beta reduce if True
getTypeApplAux :: Bool -> Type -> (Type, [Type])
getTypeApplAux b ty = let (t, args) = getTyAppl ty in (t, reverse args) where
getTyAppl typ =
case typ of
TypeAppl t1 t2 -> case redStep typ of
Just r | b -> getTyAppl r
_ -> let (t, args) = getTyAppl t1 in (t, t2 : args)
ExpandedType _ te -> let (t, args) = getTyAppl te in case t of
TypeName {} -> (t, args)
_ -> if null args then (typ, []) else (t, args)
KindedType t _ _ -> getTyAppl t
_ -> (typ, [])
-- | the builtin function arrows
data Arrow = FunArr | PFunArr | ContFunArr | PContFunArr deriving (Eq, Ord)
instance Show Arrow where
show a = case a of
FunArr -> funS
PFunArr -> pFun
ContFunArr -> contFun
PContFunArr -> pContFun
arrowIdRange :: Range -> Arrow -> Id
arrowIdRange r a = mkId $ map (`Token` r) [place, show a, place]
-- | construct an infix identifier for a function arrow
arrowId :: Arrow -> Id
arrowId = arrowIdRange nullRange
-- | test for a function identifier
isArrow :: Id -> Bool
isArrow i = isPartialArrow i || elem i (map arrowId [FunArr, ContFunArr])
-- | test for a partial function identifier
isPartialArrow :: Id -> Bool
isPartialArrow i = elem i $ map arrowId [PFunArr, PContFunArr]
-- | construct a mixfix product identifier with n places
productId :: Int -> Range -> Id
productId n r = if n > 1 then
mkId $ placeTok : concat (replicate (n - 1) [Token prodS r, placeTok])
else error "productId"
-- | test for a product identifier
isProductId :: Id -> Bool
isProductId i = isProductIdWithArgs i 0
-- | test for a product identifier
isProductIdWithArgs :: Id -> Int -> Bool
isProductIdWithArgs (Id ts cs _) m = let n = length ts in
null cs && (if m > 1 then m == div (n + 1) 2 else n > 2) && altPlaceProd ts
where altPlaceProd l = case l of
[] -> False
t : r -> isPlace t && altProdPlace r
altProdPlace l = case l of
[] -> True
t : r -> tokStr t == prodS && altPlaceProd r
-- | map a kind and its variance
mapKindV :: (Variance -> Variance) -> (a -> b) -> AnyKind a -> AnyKind b
mapKindV g f k = case k of
ClassKind a -> ClassKind $ f a
FunKind v a b r -> FunKind (g v) (mapKindV g f a) (mapKindV g f b) r
-- | map a kind and keep variance the same
mapKind :: (a -> b) -> AnyKind a -> AnyKind b
mapKind = mapKindV id
-- | ignore variances of raw kinds
nonVarRawKind :: RawKind -> RawKind
nonVarRawKind = mapKindV (const NonVar) id
-- | compute raw kind (if class ids or no higher kinds)
toRaw :: Kind -> RawKind
toRaw = mapKind $ const ()
-- | the type universe as raw kind
rStar :: RawKind
rStar = ClassKind ()
-- | the Unit type (name)
unitType :: Type
unitType = toType unitTypeId
-- | the Unit type (name)
unitTypeWithRange :: Range -> Type
unitTypeWithRange = toType . simpleIdToId . Token unitTypeS
-- | the prefix name for lazy types
lazyTypeId :: Id
lazyTypeId = mkId [mkSimpleId "?"]
-- | the kind of the lazy type constructor
coKind :: Kind
coKind = FunKind CoVar universe universe nullRange
-- | the lazy type constructor
lazyTypeConstr :: Type
lazyTypeConstr = TypeName lazyTypeId (toRaw coKind) 0
-- | make a type lazy
mkLazyType :: Type -> Type
mkLazyType = TypeAppl lazyTypeConstr
-- | function type
mkFunArrType :: Type -> Arrow -> Type -> Type
mkFunArrType = mkFunArrTypeWithRange nullRange
mkFunArrTypeWithRange :: Range -> Type -> Arrow -> Type -> Type
mkFunArrTypeWithRange r t1 a t2 = mkTypeAppl (toFunTypeRange r a) [t1, t2]
-- | construct a product type
mkProductType :: [Type] -> Type
mkProductType ts = mkProductTypeWithRange ts nullRange
-- | construct a product type
mkProductTypeWithRange :: [Type] -> Range -> Type
mkProductTypeWithRange ts r = case ts of
[] -> unitType
[t] -> t
_ -> let n = length ts in
mkTypeAppl (toProdType n r) ts
-- | convert a type with unbound variables to a scheme
simpleTypeScheme :: Type -> TypeScheme
simpleTypeScheme t = TypeScheme [] t nullRange
{- | add the unit type as result type or convert a parsed empty tuple
to the unit type -}
predType :: Range -> Type -> Type
predType r t = case t of
BracketType Parens [] _ -> mkLazyType $ unitTypeWithRange r
_ -> mkFunArrTypeWithRange r t PFunArr $ unitTypeWithRange r
-- | change the type of the scheme to a 'predType'
predTypeScheme :: Range -> TypeScheme -> TypeScheme
predTypeScheme = mapTypeOfScheme . predType
-- | check for and remove predicate arrow
unPredType :: Type -> (Bool, Type)
unPredType t = case getTypeAppl t of
(TypeName at _ 0, [ty, TypeName ut (ClassKind _) 0])
| ut == unitTypeId && at == arrowId PFunArr -> (True, ty)
(TypeName lt _ 0, [TypeName ut (ClassKind _) 0])
| ut == unitTypeId && lt == lazyTypeId ->
(True, BracketType Parens [] nullRange) -- for printing only
_ -> (False, t)
-- | test if type is a predicate type
isPredType :: Type -> Bool
isPredType = fst . unPredType
-- | remove predicate arrow in a type scheme
unPredTypeScheme :: TypeScheme -> TypeScheme
unPredTypeScheme = mapTypeOfScheme (snd . unPredType)
funKindWithRange3 :: Range -> Kind -> Kind -> Kind -> Kind
funKindWithRange3 r a b c = FunKind ContraVar a (FunKind CoVar b c r) r
funKind3 :: Kind -> Kind -> Kind -> Kind
funKind3 = funKindWithRange3 nullRange
funKindWithRange :: Range -> Kind
funKindWithRange r = let c = universeWithRange r in funKindWithRange3 r c c c
-- | the kind of the function type
funKind :: Kind
funKind = funKindWithRange nullRange
-- | construct higher order kind from arguments and result kind
mkFunKind :: Range -> [(Variance, AnyKind a)] -> AnyKind a -> AnyKind a
mkFunKind r args res = foldr ( \ (v, a) k -> FunKind v a k r) res args
-- | the 'Kind' of the product type
prodKind1 :: Int -> Range -> Kind -> Kind
prodKind1 n r c =
if n > 1 then mkFunKind r (replicate n (CoVar, c)) c
else error "prodKind"
prodKind :: Int -> Range -> Kind
prodKind n r = prodKind1 n r universe
-- | a type name with a universe kind
toType :: Id -> Type
toType i = TypeName i rStar 0
toFunTypeRange :: Range -> Arrow -> Type
toFunTypeRange r a = TypeName (arrowIdRange r a) (toRaw $ funKindWithRange r) 0
-- | the type name for a function arrow
toFunType :: Arrow -> Type
toFunType = toFunTypeRange nullRange
-- | the type name for a function arrow
toProdType :: Int -> Range -> Type
toProdType n r = TypeName (productId n r) (toRaw $ prodKind n r) 0
-- | the brackets as tokens with positions
mkBracketToken :: BracketKind -> Range -> [Token]
mkBracketToken k ps =
map (flip Token ps) $ (\ (o, c) -> [o, c]) $ getBrackets k
-- | construct a tuple from non-singleton lists
mkTupleTerm :: [Term] -> Range -> Term
mkTupleTerm ts ps = if isSingle ts then head ts else TupleTerm ts ps
-- | try to extract tuple arguments
getTupleArgs :: Term -> Maybe [Term]
getTupleArgs t = case t of
TypedTerm trm qt _ _ -> case qt of
InType -> Nothing
_ -> getTupleArgs trm
TupleTerm ts _ -> Just ts
_ -> Nothing
{- | decompose an 'ApplTerm' into an application of an operation and a
list of arguments -}
getAppl :: Term -> Maybe (Id, TypeScheme, [Term])
getAppl = thrdM reverse . getRevAppl where
thrdM :: (c -> c) -> Maybe (a, b, c) -> Maybe (a, b, c)
thrdM f = fmap ( \ (a, b, c) -> (a, b, f c))
getRevAppl :: Term -> Maybe (Id, TypeScheme, [Term])
getRevAppl t = case t of
TypedTerm trm q _ _ -> case q of
InType -> Nothing
_ -> getRevAppl trm
QualOp _ (PolyId i _ _) sc _ _ _ -> Just (i, sc, [])
QualVar (VarDecl v ty _ _) -> Just (v, simpleTypeScheme ty, [])
ApplTerm t1 t2 _ -> thrdM (t2 :) $ getRevAppl t1
_ -> Nothing
-- | split the list of generic variables into values and type variables
splitVars :: [GenVarDecl] -> ([VarDecl], [TypeArg])
splitVars l = let f x (vs, tvs) =
case x of
GenVarDecl vd -> (vd : vs, tvs)
GenTypeVarDecl tv -> (vs, tv : tvs)
in foldr f ([], []) l
-- | extract bindings from an analysed pattern
extractVars :: Term -> [VarDecl]
extractVars pat = case pat of
QualVar vd -> getVd vd
ApplTerm p1 p2 _ ->
extractVars p1 ++ extractVars p2
TupleTerm pats _ -> concatMap extractVars pats
TypedTerm p _ _ _ -> extractVars p
AsPattern v p2 _ -> getVd v ++ extractVars p2
ResolvedMixTerm _ _ pats _ -> concatMap extractVars pats
_ -> []
where getVd vd@(VarDecl v _ _ _) = if showId v "" == "_" then [] else [vd]
-- | construct term from id
mkOpTerm :: Id -> TypeScheme -> Term
mkOpTerm i sc = QualOp Op (PolyId i [] nullRange) sc [] Infer nullRange
-- | bind a term
mkForall :: [GenVarDecl] -> Term -> Term
mkForall vl f = if null vl then f else QuantifiedTerm Universal vl f nullRange
-- | construct application with curried arguments
mkApplTerm :: Term -> [Term] -> Term
mkApplTerm = foldl ( \ t a -> ApplTerm t a nullRange)
-- | make function arrow partial after some arguments
addPartiality :: [a] -> Type -> Type
addPartiality args t = case args of
[] -> mkLazyType t
_ : rs -> case getTypeAppl t of
(TypeName a _ _, [t1, t2]) | a == arrowId FunArr ->
if null rs then case getTypeAppl t2 of
(TypeName l _ _, [t3]) | l == lazyTypeId
-> mkFunArrType t1 PFunArr t3
_ -> mkFunArrType t1 PFunArr t2
else mkFunArrType t1 FunArr $ addPartiality rs t2
_ -> error "addPartiality"
-- | convert a type argument to a type
typeArgToType :: TypeArg -> Type
typeArgToType (TypeArg i _ _ rk c _ _) = TypeName i rk c
{- | convert a parameterized type identifier with a result raw kind
to a type application -}
patToType :: Id -> [TypeArg] -> RawKind -> Type
patToType i args rk =
mkTypeAppl (TypeName i (typeArgsListToRawKind args rk) 0)
$ map typeArgToType args
-- | create the (raw if True) kind from type arguments
typeArgsListToRawKind :: [TypeArg] -> RawKind -> RawKind
typeArgsListToRawKind tArgs = mkFunKind (getRange tArgs) $
map (\ (TypeArg _ v _ rk _ _ _) -> (v, rk)) tArgs
-- | create the kind from type arguments
typeArgsListToKind :: [TypeArg] -> Kind -> Kind
typeArgsListToKind tArgs = mkFunKind (getRange tArgs) $
map ( \ (TypeArg _ v ak _ _ _ _) -> (v, toKind ak)) tArgs
-- | get the type of a constructor with given curried argument types
getFunType :: Type -> Partiality -> [Type] -> Type
getFunType rty p ts = (case p of
Total -> id
Partial -> addPartiality ts)
$ foldr (`mkFunArrType` FunArr) rty ts
-- | get the type of a selector given the data type as first arguemnt
getSelType :: Type -> Partiality -> Type -> Type
getSelType dt p = (case p of
Partial -> addPartiality [dt]
Total -> id) . mkFunArrType dt FunArr
-- | make type argument non-variant
nonVarTypeArg :: TypeArg -> TypeArg
nonVarTypeArg (TypeArg i _ vk rk c o p) = TypeArg i NonVar vk rk c o p
-- | get the type variable
getTypeVar :: TypeArg -> Id
getTypeVar (TypeArg v _ _ _ _ _ _) = v
-- | construct application left-associative
mkTypeAppl :: Type -> [Type] -> Type
mkTypeAppl = foldl TypeAppl
-- | get the kind of an analyzed type variable
toKind :: VarKind -> Kind
toKind vk = case vk of
VarKind k -> k
Downset t -> case t of
KindedType _ k _ | Set.size k == 1 -> Set.findMin k
_ -> error "toKind: Downset"
MissingKind -> error "toKind: Missing"
-- | try to reparse the pretty printed input as an identifier
reparseAsId :: Pretty a => a -> Maybe Id
reparseAsId t = case P.parse (opId << P.eof) "" $ showDoc t "" of
Right x -> Just x
_ -> Nothing
-- | generate a comparison string
expected :: Pretty a => a -> a -> String
expected a b =
"\n expected: " ++ showDoc a
"\n found: " ++ showDoc b "\n"
| keithodulaigh/Hets | HasCASL/AsUtils.hs | gpl-2.0 | 14,692 | 0 | 20 | 3,689 | 4,675 | 2,415 | 2,260 | 280 | 9 |
module Spielbaum.Wort where
-- this file is copied only (source: /autotool/autobahn/Wort.hs)
-- reason for copying: autotool/util contains another Wort.hs
import Spielbaum.Next
import ToDoc
import Data.List (inits, tails)
import Control.Monad (guard)
data Regel a =
Regel { from :: [a]
, to :: [a]
}
data Wort a = Wort { inhalt :: [a]
, regeln :: [ Regel a ]
}
instance ToDoc [a] => ToDoc (Wort a) where
toDoc = toDoc . inhalt
instance ToDoc (Wort a) => Show (Wort a) where
show = render . toDoc
instance Eq [a] => Eq (Wort a) where
x == y = inhalt x == inhalt y
instance Ord [a] => Ord (Wort a) where
x `compare` y = inhalt x `compare` inhalt y
instance Eq a => Next (Wort a) where
next w = do
let i = inhalt w
( pre, midpost ) <- zip ( inits i ) ( tails i )
r <- regeln w
let ( mid, post ) = splitAt (length $ from r) midpost
guard $ mid == from r
return $ w { inhalt = pre ++ to r ++ post }
| Erdwolf/autotool-bonn | src/Spielbaum/Wort.hs | gpl-2.0 | 966 | 7 | 14 | 260 | 417 | 218 | 199 | -1 | -1 |
module Main where
import Graphics.X11.Turtle
import Data.IORef
import Control.Concurrent
import Control.Monad
import System.Environment
import Text.XML.YJSVG
import Data.Word
main :: IO ()
main = do
[fn, save] <- getArgs
clr <- newIORef 0
bgclr <- newIORef 0
f <- openField
t <- newTurtle f
threadDelay 100000
height <- windowHeight t
width <- windowWidth t
clrT <- newTurtle f
pensize clrT 10
hideturtle clrT
penup clrT
goto clrT (width / 2 - 10) (height / 2 - 10)
pendown clrT
shape t "turtle"
shapesize t 2 2
pensize t 10
hideturtle t
penup t
readFile fn >>= runInputs t . read
onclick f $ \b x y -> do
case b of
1 -> goto t x y >> pendown t >> forward t 0 >> return True
3 -> clear t >> return True
2 -> modifyIORef bgclr (+ 1) >> readIORef bgclr >>=
(\c -> bgcolor t c) . (colors !!) >> return True
4 -> goto t x y >> modifyIORef clr (+ 6) >> readIORef clr >>=
(\c -> pencolor t c >> pencolor clrT c) . (colors !!) >>
forward clrT 0 >> return True
5 -> goto t x y >> modifyIORef clr (+ 1) >> readIORef clr >>=
(\c -> pencolor t c >> pencolor clrT c) . (colors !!) >>
forward clrT 0 >> return True
onrelease f $ \_ _ _ -> penup t>> return True
onkeypress f $ \_ -> do
{-
print "hello"
print $ head inputs
print inputs
print $ length inputs
-}
w <- windowWidth t
h <- windowHeight t
getSVG t >>= putStrLn . showSVG w h
inputs <- inputs t
when (read save) $ writeFile fn $ show $ drop 5 inputs
return False
ondrag f $ \bn x y -> case bn of
1 -> goto t x y
_ -> return ()
waitField f
colors :: [(Word8, Word8, Word8)]
colors = cycle [
(255, 0, 0), (0, 255, 0), (255, 255, 0), (0, 0, 255),
(128, 76, 0), (255, 255, 255), (0, 0, 0)]
| YoshikuniJujo/wxturtle | tests/draw.hs | bsd-3-clause | 1,723 | 14 | 21 | 430 | 861 | 420 | 441 | 58 | 6 |
{-| Template Haskell code for Haskell to Python constants.
-}
{-
Copyright (C) 2013 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
{-# LANGUAGE TemplateHaskell #-}
module Ganeti.Hs2Py.GenConstants (genPyConstants) where
import Language.Haskell.TH
import Ganeti.THH
fileFromModule :: Maybe String -> String
fileFromModule Nothing = ""
fileFromModule (Just name) = "src/" ++ map dotToSlash name ++ ".hs"
where dotToSlash '.' = '/'
dotToSlash c = c
comment :: Name -> String
comment name =
"# Generated automatically from Haskell constant '" ++ nameBase name ++
"' in file '" ++ fileFromModule (nameModule name) ++ "'"
genList :: Name -> [Name] -> Q [Dec]
genList name consNames = do
let cons = listE $ map (\n -> tupE [mkString n, mkPyValueEx n]) consNames
sig <- sigD name [t| [(String, String)] |]
fun <- funD name [clause [] (normalB cons) []]
return [sig, fun]
where mkString n = stringE (comment n ++ "\n" ++ deCamelCase (nameBase n))
mkPyValueEx n = [| showValue $(varE n) |]
genPyConstants :: String -> [Name] -> Q [Dec]
genPyConstants name = genList (mkName name)
| vladimir-ipatov/ganeti | src/Ganeti/Hs2Py/GenConstants.hs | gpl-2.0 | 1,762 | 0 | 16 | 329 | 355 | 183 | 172 | 23 | 2 |
-- %************************************************************************
-- %* *
-- The known-key names for Template Haskell
-- %* *
-- %************************************************************************
module THNames where
import PrelNames( mk_known_key_name )
import Module( Module, mkModuleNameFS, mkModule, thUnitId )
import Name( Name )
import OccName( tcName, clsName, dataName, varName )
import RdrName( RdrName, nameRdrName )
import Unique
import FastString
-- To add a name, do three things
--
-- 1) Allocate a key
-- 2) Make a "Name"
-- 3) Add the name to templateHaskellNames
templateHaskellNames :: [Name]
-- The names that are implicitly mentioned by ``bracket''
-- Should stay in sync with the import list of DsMeta
templateHaskellNames = [
returnQName, bindQName, sequenceQName, newNameName, liftName,
mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName,
mkNameSName,
liftStringName,
unTypeName,
unTypeQName,
unsafeTExpCoerceName,
-- Lit
charLName, stringLName, integerLName, intPrimLName, wordPrimLName,
floatPrimLName, doublePrimLName, rationalLName, stringPrimLName,
charPrimLName,
-- Pat
litPName, varPName, tupPName, unboxedTupPName,
conPName, tildePName, bangPName, infixPName,
asPName, wildPName, recPName, listPName, sigPName, viewPName,
-- FieldPat
fieldPatName,
-- Match
matchName,
-- Clause
clauseName,
-- Exp
varEName, conEName, litEName, appEName, infixEName,
infixAppName, sectionLName, sectionRName, lamEName, lamCaseEName,
tupEName, unboxedTupEName,
condEName, multiIfEName, letEName, caseEName, doEName, compEName,
fromEName, fromThenEName, fromToEName, fromThenToEName,
listEName, sigEName, recConEName, recUpdEName, staticEName, unboundVarEName,
-- FieldExp
fieldExpName,
-- Body
guardedBName, normalBName,
-- Guard
normalGEName, patGEName,
-- Stmt
bindSName, letSName, noBindSName, parSName,
-- Dec
funDName, valDName, dataDName, newtypeDName, tySynDName,
classDName, instanceDName, standaloneDerivDName, sigDName, forImpDName,
pragInlDName, pragSpecDName, pragSpecInlDName, pragSpecInstDName,
pragRuleDName, pragAnnDName, defaultSigDName,
dataFamilyDName, openTypeFamilyDName, closedTypeFamilyDName,
dataInstDName, newtypeInstDName, tySynInstDName,
infixLDName, infixRDName, infixNDName,
roleAnnotDName,
-- Cxt
cxtName,
-- Strict
isStrictName, notStrictName, unpackedName,
-- Con
normalCName, recCName, infixCName, forallCName,
-- StrictType
strictTypeName,
-- VarStrictType
varStrictTypeName,
-- Type
forallTName, varTName, conTName, appTName, equalityTName,
tupleTName, unboxedTupleTName, arrowTName, listTName, sigTName, litTName,
promotedTName, promotedTupleTName, promotedNilTName, promotedConsTName,
wildCardTName, namedWildCardTName,
-- TyLit
numTyLitName, strTyLitName,
-- TyVarBndr
plainTVName, kindedTVName,
-- Role
nominalRName, representationalRName, phantomRName, inferRName,
-- Kind
varKName, conKName, tupleKName, arrowKName, listKName, appKName,
starKName, constraintKName,
-- FamilyResultSig
noSigName, kindSigName, tyVarSigName,
-- InjectivityAnn
injectivityAnnName,
-- Callconv
cCallName, stdCallName, cApiCallName, primCallName, javaScriptCallName,
-- Safety
unsafeName,
safeName,
interruptibleName,
-- Inline
noInlineDataConName, inlineDataConName, inlinableDataConName,
-- RuleMatch
conLikeDataConName, funLikeDataConName,
-- Phases
allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName,
-- TExp
tExpDataConName,
-- RuleBndr
ruleVarName, typedRuleVarName,
-- FunDep
funDepName,
-- FamFlavour
typeFamName, dataFamName,
-- TySynEqn
tySynEqnName,
-- AnnTarget
valueAnnotationName, typeAnnotationName, moduleAnnotationName,
-- The type classes
liftClassName,
-- And the tycons
qTyConName, nameTyConName, patTyConName, fieldPatTyConName, matchQTyConName,
clauseQTyConName, expQTyConName, fieldExpTyConName, predTyConName,
stmtQTyConName, decQTyConName, conQTyConName, strictTypeQTyConName,
varStrictTypeQTyConName, typeQTyConName, expTyConName, decTyConName,
typeTyConName, tyVarBndrTyConName, matchTyConName, clauseTyConName,
patQTyConName, fieldPatQTyConName, fieldExpQTyConName, funDepTyConName,
predQTyConName, decsQTyConName, ruleBndrQTyConName, tySynEqnQTyConName,
roleTyConName, tExpTyConName, injAnnTyConName, kindTyConName,
-- Quasiquoting
quoteDecName, quoteTypeName, quoteExpName, quotePatName]
thSyn, thLib, qqLib :: Module
thSyn = mkTHModule (fsLit "Language.Haskell.TH.Syntax")
thLib = mkTHModule (fsLit "Language.Haskell.TH.Lib")
qqLib = mkTHModule (fsLit "Language.Haskell.TH.Quote")
mkTHModule :: FastString -> Module
mkTHModule m = mkModule thUnitId (mkModuleNameFS m)
libFun, libTc, thFun, thTc, thCls, thCon, qqFun :: FastString -> Unique -> Name
libFun = mk_known_key_name OccName.varName thLib
libTc = mk_known_key_name OccName.tcName thLib
thFun = mk_known_key_name OccName.varName thSyn
thTc = mk_known_key_name OccName.tcName thSyn
thCls = mk_known_key_name OccName.clsName thSyn
thCon = mk_known_key_name OccName.dataName thSyn
qqFun = mk_known_key_name OccName.varName qqLib
-------------------- TH.Syntax -----------------------
liftClassName :: Name
liftClassName = thCls (fsLit "Lift") liftClassKey
qTyConName, nameTyConName, fieldExpTyConName, patTyConName,
fieldPatTyConName, expTyConName, decTyConName, typeTyConName,
tyVarBndrTyConName, matchTyConName, clauseTyConName, funDepTyConName,
predTyConName, tExpTyConName, injAnnTyConName, kindTyConName :: Name
qTyConName = thTc (fsLit "Q") qTyConKey
nameTyConName = thTc (fsLit "Name") nameTyConKey
fieldExpTyConName = thTc (fsLit "FieldExp") fieldExpTyConKey
patTyConName = thTc (fsLit "Pat") patTyConKey
fieldPatTyConName = thTc (fsLit "FieldPat") fieldPatTyConKey
expTyConName = thTc (fsLit "Exp") expTyConKey
decTyConName = thTc (fsLit "Dec") decTyConKey
typeTyConName = thTc (fsLit "Type") typeTyConKey
tyVarBndrTyConName= thTc (fsLit "TyVarBndr") tyVarBndrTyConKey
matchTyConName = thTc (fsLit "Match") matchTyConKey
clauseTyConName = thTc (fsLit "Clause") clauseTyConKey
funDepTyConName = thTc (fsLit "FunDep") funDepTyConKey
predTyConName = thTc (fsLit "Pred") predTyConKey
tExpTyConName = thTc (fsLit "TExp") tExpTyConKey
injAnnTyConName = thTc (fsLit "InjectivityAnn") injAnnTyConKey
kindTyConName = thTc (fsLit "Kind") kindTyConKey
returnQName, bindQName, sequenceQName, newNameName, liftName,
mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName,
mkNameLName, mkNameSName, liftStringName, unTypeName, unTypeQName,
unsafeTExpCoerceName :: Name
returnQName = thFun (fsLit "returnQ") returnQIdKey
bindQName = thFun (fsLit "bindQ") bindQIdKey
sequenceQName = thFun (fsLit "sequenceQ") sequenceQIdKey
newNameName = thFun (fsLit "newName") newNameIdKey
liftName = thFun (fsLit "lift") liftIdKey
liftStringName = thFun (fsLit "liftString") liftStringIdKey
mkNameName = thFun (fsLit "mkName") mkNameIdKey
mkNameG_vName = thFun (fsLit "mkNameG_v") mkNameG_vIdKey
mkNameG_dName = thFun (fsLit "mkNameG_d") mkNameG_dIdKey
mkNameG_tcName = thFun (fsLit "mkNameG_tc") mkNameG_tcIdKey
mkNameLName = thFun (fsLit "mkNameL") mkNameLIdKey
mkNameSName = thFun (fsLit "mkNameS") mkNameSIdKey
unTypeName = thFun (fsLit "unType") unTypeIdKey
unTypeQName = thFun (fsLit "unTypeQ") unTypeQIdKey
unsafeTExpCoerceName = thFun (fsLit "unsafeTExpCoerce") unsafeTExpCoerceIdKey
-------------------- TH.Lib -----------------------
-- data Lit = ...
charLName, stringLName, integerLName, intPrimLName, wordPrimLName,
floatPrimLName, doublePrimLName, rationalLName, stringPrimLName,
charPrimLName :: Name
charLName = libFun (fsLit "charL") charLIdKey
stringLName = libFun (fsLit "stringL") stringLIdKey
integerLName = libFun (fsLit "integerL") integerLIdKey
intPrimLName = libFun (fsLit "intPrimL") intPrimLIdKey
wordPrimLName = libFun (fsLit "wordPrimL") wordPrimLIdKey
floatPrimLName = libFun (fsLit "floatPrimL") floatPrimLIdKey
doublePrimLName = libFun (fsLit "doublePrimL") doublePrimLIdKey
rationalLName = libFun (fsLit "rationalL") rationalLIdKey
stringPrimLName = libFun (fsLit "stringPrimL") stringPrimLIdKey
charPrimLName = libFun (fsLit "charPrimL") charPrimLIdKey
-- data Pat = ...
litPName, varPName, tupPName, unboxedTupPName, conPName, infixPName, tildePName, bangPName,
asPName, wildPName, recPName, listPName, sigPName, viewPName :: Name
litPName = libFun (fsLit "litP") litPIdKey
varPName = libFun (fsLit "varP") varPIdKey
tupPName = libFun (fsLit "tupP") tupPIdKey
unboxedTupPName = libFun (fsLit "unboxedTupP") unboxedTupPIdKey
conPName = libFun (fsLit "conP") conPIdKey
infixPName = libFun (fsLit "infixP") infixPIdKey
tildePName = libFun (fsLit "tildeP") tildePIdKey
bangPName = libFun (fsLit "bangP") bangPIdKey
asPName = libFun (fsLit "asP") asPIdKey
wildPName = libFun (fsLit "wildP") wildPIdKey
recPName = libFun (fsLit "recP") recPIdKey
listPName = libFun (fsLit "listP") listPIdKey
sigPName = libFun (fsLit "sigP") sigPIdKey
viewPName = libFun (fsLit "viewP") viewPIdKey
-- type FieldPat = ...
fieldPatName :: Name
fieldPatName = libFun (fsLit "fieldPat") fieldPatIdKey
-- data Match = ...
matchName :: Name
matchName = libFun (fsLit "match") matchIdKey
-- data Clause = ...
clauseName :: Name
clauseName = libFun (fsLit "clause") clauseIdKey
-- data Exp = ...
varEName, conEName, litEName, appEName, infixEName, infixAppName,
sectionLName, sectionRName, lamEName, lamCaseEName, tupEName,
unboxedTupEName, condEName, multiIfEName, letEName, caseEName,
doEName, compEName, staticEName, unboundVarEName :: Name
varEName = libFun (fsLit "varE") varEIdKey
conEName = libFun (fsLit "conE") conEIdKey
litEName = libFun (fsLit "litE") litEIdKey
appEName = libFun (fsLit "appE") appEIdKey
infixEName = libFun (fsLit "infixE") infixEIdKey
infixAppName = libFun (fsLit "infixApp") infixAppIdKey
sectionLName = libFun (fsLit "sectionL") sectionLIdKey
sectionRName = libFun (fsLit "sectionR") sectionRIdKey
lamEName = libFun (fsLit "lamE") lamEIdKey
lamCaseEName = libFun (fsLit "lamCaseE") lamCaseEIdKey
tupEName = libFun (fsLit "tupE") tupEIdKey
unboxedTupEName = libFun (fsLit "unboxedTupE") unboxedTupEIdKey
condEName = libFun (fsLit "condE") condEIdKey
multiIfEName = libFun (fsLit "multiIfE") multiIfEIdKey
letEName = libFun (fsLit "letE") letEIdKey
caseEName = libFun (fsLit "caseE") caseEIdKey
doEName = libFun (fsLit "doE") doEIdKey
compEName = libFun (fsLit "compE") compEIdKey
-- ArithSeq skips a level
fromEName, fromThenEName, fromToEName, fromThenToEName :: Name
fromEName = libFun (fsLit "fromE") fromEIdKey
fromThenEName = libFun (fsLit "fromThenE") fromThenEIdKey
fromToEName = libFun (fsLit "fromToE") fromToEIdKey
fromThenToEName = libFun (fsLit "fromThenToE") fromThenToEIdKey
-- end ArithSeq
listEName, sigEName, recConEName, recUpdEName :: Name
listEName = libFun (fsLit "listE") listEIdKey
sigEName = libFun (fsLit "sigE") sigEIdKey
recConEName = libFun (fsLit "recConE") recConEIdKey
recUpdEName = libFun (fsLit "recUpdE") recUpdEIdKey
staticEName = libFun (fsLit "staticE") staticEIdKey
unboundVarEName = libFun (fsLit "unboundVarE") unboundVarEIdKey
-- type FieldExp = ...
fieldExpName :: Name
fieldExpName = libFun (fsLit "fieldExp") fieldExpIdKey
-- data Body = ...
guardedBName, normalBName :: Name
guardedBName = libFun (fsLit "guardedB") guardedBIdKey
normalBName = libFun (fsLit "normalB") normalBIdKey
-- data Guard = ...
normalGEName, patGEName :: Name
normalGEName = libFun (fsLit "normalGE") normalGEIdKey
patGEName = libFun (fsLit "patGE") patGEIdKey
-- data Stmt = ...
bindSName, letSName, noBindSName, parSName :: Name
bindSName = libFun (fsLit "bindS") bindSIdKey
letSName = libFun (fsLit "letS") letSIdKey
noBindSName = libFun (fsLit "noBindS") noBindSIdKey
parSName = libFun (fsLit "parS") parSIdKey
-- data Dec = ...
funDName, valDName, dataDName, newtypeDName, tySynDName, classDName,
instanceDName, sigDName, forImpDName, pragInlDName, pragSpecDName,
pragSpecInlDName, pragSpecInstDName, pragRuleDName, pragAnnDName,
standaloneDerivDName, defaultSigDName,
dataInstDName, newtypeInstDName, tySynInstDName,
dataFamilyDName, openTypeFamilyDName, closedTypeFamilyDName,
infixLDName, infixRDName, infixNDName, roleAnnotDName :: Name
funDName = libFun (fsLit "funD") funDIdKey
valDName = libFun (fsLit "valD") valDIdKey
dataDName = libFun (fsLit "dataD") dataDIdKey
newtypeDName = libFun (fsLit "newtypeD") newtypeDIdKey
tySynDName = libFun (fsLit "tySynD") tySynDIdKey
classDName = libFun (fsLit "classD") classDIdKey
instanceDName = libFun (fsLit "instanceD") instanceDIdKey
standaloneDerivDName = libFun (fsLit "standaloneDerivD") standaloneDerivDIdKey
sigDName = libFun (fsLit "sigD") sigDIdKey
defaultSigDName = libFun (fsLit "defaultSigD") defaultSigDIdKey
forImpDName = libFun (fsLit "forImpD") forImpDIdKey
pragInlDName = libFun (fsLit "pragInlD") pragInlDIdKey
pragSpecDName = libFun (fsLit "pragSpecD") pragSpecDIdKey
pragSpecInlDName = libFun (fsLit "pragSpecInlD") pragSpecInlDIdKey
pragSpecInstDName = libFun (fsLit "pragSpecInstD") pragSpecInstDIdKey
pragRuleDName = libFun (fsLit "pragRuleD") pragRuleDIdKey
pragAnnDName = libFun (fsLit "pragAnnD") pragAnnDIdKey
dataInstDName = libFun (fsLit "dataInstD") dataInstDIdKey
newtypeInstDName = libFun (fsLit "newtypeInstD") newtypeInstDIdKey
tySynInstDName = libFun (fsLit "tySynInstD") tySynInstDIdKey
openTypeFamilyDName = libFun (fsLit "openTypeFamilyD") openTypeFamilyDIdKey
closedTypeFamilyDName= libFun (fsLit "closedTypeFamilyD") closedTypeFamilyDIdKey
dataFamilyDName = libFun (fsLit "dataFamilyD") dataFamilyDIdKey
infixLDName = libFun (fsLit "infixLD") infixLDIdKey
infixRDName = libFun (fsLit "infixRD") infixRDIdKey
infixNDName = libFun (fsLit "infixND") infixNDIdKey
roleAnnotDName = libFun (fsLit "roleAnnotD") roleAnnotDIdKey
-- type Ctxt = ...
cxtName :: Name
cxtName = libFun (fsLit "cxt") cxtIdKey
-- data Strict = ...
isStrictName, notStrictName, unpackedName :: Name
isStrictName = libFun (fsLit "isStrict") isStrictKey
notStrictName = libFun (fsLit "notStrict") notStrictKey
unpackedName = libFun (fsLit "unpacked") unpackedKey
-- data Con = ...
normalCName, recCName, infixCName, forallCName :: Name
normalCName = libFun (fsLit "normalC") normalCIdKey
recCName = libFun (fsLit "recC") recCIdKey
infixCName = libFun (fsLit "infixC") infixCIdKey
forallCName = libFun (fsLit "forallC") forallCIdKey
-- type StrictType = ...
strictTypeName :: Name
strictTypeName = libFun (fsLit "strictType") strictTKey
-- type VarStrictType = ...
varStrictTypeName :: Name
varStrictTypeName = libFun (fsLit "varStrictType") varStrictTKey
-- data Type = ...
forallTName, varTName, conTName, tupleTName, unboxedTupleTName, arrowTName,
listTName, appTName, sigTName, equalityTName, litTName,
promotedTName, promotedTupleTName,
promotedNilTName, promotedConsTName,
wildCardTName, namedWildCardTName :: Name
forallTName = libFun (fsLit "forallT") forallTIdKey
varTName = libFun (fsLit "varT") varTIdKey
conTName = libFun (fsLit "conT") conTIdKey
tupleTName = libFun (fsLit "tupleT") tupleTIdKey
unboxedTupleTName = libFun (fsLit "unboxedTupleT") unboxedTupleTIdKey
arrowTName = libFun (fsLit "arrowT") arrowTIdKey
listTName = libFun (fsLit "listT") listTIdKey
appTName = libFun (fsLit "appT") appTIdKey
sigTName = libFun (fsLit "sigT") sigTIdKey
equalityTName = libFun (fsLit "equalityT") equalityTIdKey
litTName = libFun (fsLit "litT") litTIdKey
promotedTName = libFun (fsLit "promotedT") promotedTIdKey
promotedTupleTName = libFun (fsLit "promotedTupleT") promotedTupleTIdKey
promotedNilTName = libFun (fsLit "promotedNilT") promotedNilTIdKey
promotedConsTName = libFun (fsLit "promotedConsT") promotedConsTIdKey
wildCardTName = libFun (fsLit "wildCardT") wildCardTIdKey
namedWildCardTName = libFun (fsLit "namedWildCardT") namedWildCardTIdKey
-- data TyLit = ...
numTyLitName, strTyLitName :: Name
numTyLitName = libFun (fsLit "numTyLit") numTyLitIdKey
strTyLitName = libFun (fsLit "strTyLit") strTyLitIdKey
-- data TyVarBndr = ...
plainTVName, kindedTVName :: Name
plainTVName = libFun (fsLit "plainTV") plainTVIdKey
kindedTVName = libFun (fsLit "kindedTV") kindedTVIdKey
-- data Role = ...
nominalRName, representationalRName, phantomRName, inferRName :: Name
nominalRName = libFun (fsLit "nominalR") nominalRIdKey
representationalRName = libFun (fsLit "representationalR") representationalRIdKey
phantomRName = libFun (fsLit "phantomR") phantomRIdKey
inferRName = libFun (fsLit "inferR") inferRIdKey
-- data Kind = ...
varKName, conKName, tupleKName, arrowKName, listKName, appKName,
starKName, constraintKName :: Name
varKName = libFun (fsLit "varK") varKIdKey
conKName = libFun (fsLit "conK") conKIdKey
tupleKName = libFun (fsLit "tupleK") tupleKIdKey
arrowKName = libFun (fsLit "arrowK") arrowKIdKey
listKName = libFun (fsLit "listK") listKIdKey
appKName = libFun (fsLit "appK") appKIdKey
starKName = libFun (fsLit "starK") starKIdKey
constraintKName = libFun (fsLit "constraintK") constraintKIdKey
-- data FamilyResultSig = ...
noSigName, kindSigName, tyVarSigName :: Name
noSigName = libFun (fsLit "noSig") noSigIdKey
kindSigName = libFun (fsLit "kindSig") kindSigIdKey
tyVarSigName = libFun (fsLit "tyVarSig") tyVarSigIdKey
-- data InjectivityAnn = ...
injectivityAnnName :: Name
injectivityAnnName = libFun (fsLit "injectivityAnn") injectivityAnnIdKey
-- data Callconv = ...
cCallName, stdCallName, cApiCallName, primCallName, javaScriptCallName :: Name
cCallName = libFun (fsLit "cCall") cCallIdKey
stdCallName = libFun (fsLit "stdCall") stdCallIdKey
cApiCallName = libFun (fsLit "cApi") cApiCallIdKey
primCallName = libFun (fsLit "prim") primCallIdKey
javaScriptCallName = libFun (fsLit "javaScript") javaScriptCallIdKey
-- data Safety = ...
unsafeName, safeName, interruptibleName :: Name
unsafeName = libFun (fsLit "unsafe") unsafeIdKey
safeName = libFun (fsLit "safe") safeIdKey
interruptibleName = libFun (fsLit "interruptible") interruptibleIdKey
-- newtype TExp a = ...
tExpDataConName :: Name
tExpDataConName = thCon (fsLit "TExp") tExpDataConKey
-- data RuleBndr = ...
ruleVarName, typedRuleVarName :: Name
ruleVarName = libFun (fsLit ("ruleVar")) ruleVarIdKey
typedRuleVarName = libFun (fsLit ("typedRuleVar")) typedRuleVarIdKey
-- data FunDep = ...
funDepName :: Name
funDepName = libFun (fsLit "funDep") funDepIdKey
-- data FamFlavour = ...
typeFamName, dataFamName :: Name
typeFamName = libFun (fsLit "typeFam") typeFamIdKey
dataFamName = libFun (fsLit "dataFam") dataFamIdKey
-- data TySynEqn = ...
tySynEqnName :: Name
tySynEqnName = libFun (fsLit "tySynEqn") tySynEqnIdKey
-- data AnnTarget = ...
valueAnnotationName, typeAnnotationName, moduleAnnotationName :: Name
valueAnnotationName = libFun (fsLit "valueAnnotation") valueAnnotationIdKey
typeAnnotationName = libFun (fsLit "typeAnnotation") typeAnnotationIdKey
moduleAnnotationName = libFun (fsLit "moduleAnnotation") moduleAnnotationIdKey
matchQTyConName, clauseQTyConName, expQTyConName, stmtQTyConName,
decQTyConName, conQTyConName, strictTypeQTyConName,
varStrictTypeQTyConName, typeQTyConName, fieldExpQTyConName,
patQTyConName, fieldPatQTyConName, predQTyConName, decsQTyConName,
ruleBndrQTyConName, tySynEqnQTyConName, roleTyConName :: Name
matchQTyConName = libTc (fsLit "MatchQ") matchQTyConKey
clauseQTyConName = libTc (fsLit "ClauseQ") clauseQTyConKey
expQTyConName = libTc (fsLit "ExpQ") expQTyConKey
stmtQTyConName = libTc (fsLit "StmtQ") stmtQTyConKey
decQTyConName = libTc (fsLit "DecQ") decQTyConKey
decsQTyConName = libTc (fsLit "DecsQ") decsQTyConKey -- Q [Dec]
conQTyConName = libTc (fsLit "ConQ") conQTyConKey
strictTypeQTyConName = libTc (fsLit "StrictTypeQ") strictTypeQTyConKey
varStrictTypeQTyConName = libTc (fsLit "VarStrictTypeQ") varStrictTypeQTyConKey
typeQTyConName = libTc (fsLit "TypeQ") typeQTyConKey
fieldExpQTyConName = libTc (fsLit "FieldExpQ") fieldExpQTyConKey
patQTyConName = libTc (fsLit "PatQ") patQTyConKey
fieldPatQTyConName = libTc (fsLit "FieldPatQ") fieldPatQTyConKey
predQTyConName = libTc (fsLit "PredQ") predQTyConKey
ruleBndrQTyConName = libTc (fsLit "RuleBndrQ") ruleBndrQTyConKey
tySynEqnQTyConName = libTc (fsLit "TySynEqnQ") tySynEqnQTyConKey
roleTyConName = libTc (fsLit "Role") roleTyConKey
-- quasiquoting
quoteExpName, quotePatName, quoteDecName, quoteTypeName :: Name
quoteExpName = qqFun (fsLit "quoteExp") quoteExpKey
quotePatName = qqFun (fsLit "quotePat") quotePatKey
quoteDecName = qqFun (fsLit "quoteDec") quoteDecKey
quoteTypeName = qqFun (fsLit "quoteType") quoteTypeKey
-- data Inline = ...
noInlineDataConName, inlineDataConName, inlinableDataConName :: Name
noInlineDataConName = thCon (fsLit "NoInline") noInlineDataConKey
inlineDataConName = thCon (fsLit "Inline") inlineDataConKey
inlinableDataConName = thCon (fsLit "Inlinable") inlinableDataConKey
-- data RuleMatch = ...
conLikeDataConName, funLikeDataConName :: Name
conLikeDataConName = thCon (fsLit "ConLike") conLikeDataConKey
funLikeDataConName = thCon (fsLit "FunLike") funLikeDataConKey
-- data Phases = ...
allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName :: Name
allPhasesDataConName = thCon (fsLit "AllPhases") allPhasesDataConKey
fromPhaseDataConName = thCon (fsLit "FromPhase") fromPhaseDataConKey
beforePhaseDataConName = thCon (fsLit "BeforePhase") beforePhaseDataConKey
{- *********************************************************************
* *
Class keys
* *
********************************************************************* -}
-- ClassUniques available: 200-299
-- Check in PrelNames if you want to change this
liftClassKey :: Unique
liftClassKey = mkPreludeClassUnique 200
{- *********************************************************************
* *
TyCon keys
* *
********************************************************************* -}
-- TyConUniques available: 200-299
-- Check in PrelNames if you want to change this
expTyConKey, matchTyConKey, clauseTyConKey, qTyConKey, expQTyConKey,
decQTyConKey, patTyConKey, matchQTyConKey, clauseQTyConKey,
stmtQTyConKey, conQTyConKey, typeQTyConKey, typeTyConKey, tyVarBndrTyConKey,
decTyConKey, varStrictTypeQTyConKey, strictTypeQTyConKey,
fieldExpTyConKey, fieldPatTyConKey, nameTyConKey, patQTyConKey,
fieldPatQTyConKey, fieldExpQTyConKey, funDepTyConKey, predTyConKey,
predQTyConKey, decsQTyConKey, ruleBndrQTyConKey, tySynEqnQTyConKey,
roleTyConKey, tExpTyConKey, injAnnTyConKey, kindTyConKey :: Unique
expTyConKey = mkPreludeTyConUnique 200
matchTyConKey = mkPreludeTyConUnique 201
clauseTyConKey = mkPreludeTyConUnique 202
qTyConKey = mkPreludeTyConUnique 203
expQTyConKey = mkPreludeTyConUnique 204
decQTyConKey = mkPreludeTyConUnique 205
patTyConKey = mkPreludeTyConUnique 206
matchQTyConKey = mkPreludeTyConUnique 207
clauseQTyConKey = mkPreludeTyConUnique 208
stmtQTyConKey = mkPreludeTyConUnique 209
conQTyConKey = mkPreludeTyConUnique 210
typeQTyConKey = mkPreludeTyConUnique 211
typeTyConKey = mkPreludeTyConUnique 212
decTyConKey = mkPreludeTyConUnique 213
varStrictTypeQTyConKey = mkPreludeTyConUnique 214
strictTypeQTyConKey = mkPreludeTyConUnique 215
fieldExpTyConKey = mkPreludeTyConUnique 216
fieldPatTyConKey = mkPreludeTyConUnique 217
nameTyConKey = mkPreludeTyConUnique 218
patQTyConKey = mkPreludeTyConUnique 219
fieldPatQTyConKey = mkPreludeTyConUnique 220
fieldExpQTyConKey = mkPreludeTyConUnique 221
funDepTyConKey = mkPreludeTyConUnique 222
predTyConKey = mkPreludeTyConUnique 223
predQTyConKey = mkPreludeTyConUnique 224
tyVarBndrTyConKey = mkPreludeTyConUnique 225
decsQTyConKey = mkPreludeTyConUnique 226
ruleBndrQTyConKey = mkPreludeTyConUnique 227
tySynEqnQTyConKey = mkPreludeTyConUnique 228
roleTyConKey = mkPreludeTyConUnique 229
tExpTyConKey = mkPreludeTyConUnique 230
injAnnTyConKey = mkPreludeTyConUnique 231
kindTyConKey = mkPreludeTyConUnique 232
{- *********************************************************************
* *
DataCon keys
* *
********************************************************************* -}
-- DataConUniques available: 100-150
-- If you want to change this, make sure you check in PrelNames
-- data Inline = ...
noInlineDataConKey, inlineDataConKey, inlinableDataConKey :: Unique
noInlineDataConKey = mkPreludeDataConUnique 100
inlineDataConKey = mkPreludeDataConUnique 101
inlinableDataConKey = mkPreludeDataConUnique 102
-- data RuleMatch = ...
conLikeDataConKey, funLikeDataConKey :: Unique
conLikeDataConKey = mkPreludeDataConUnique 103
funLikeDataConKey = mkPreludeDataConUnique 104
-- data Phases = ...
allPhasesDataConKey, fromPhaseDataConKey, beforePhaseDataConKey :: Unique
allPhasesDataConKey = mkPreludeDataConUnique 105
fromPhaseDataConKey = mkPreludeDataConUnique 106
beforePhaseDataConKey = mkPreludeDataConUnique 107
-- newtype TExp a = ...
tExpDataConKey :: Unique
tExpDataConKey = mkPreludeDataConUnique 108
{- *********************************************************************
* *
Id keys
* *
********************************************************************* -}
-- IdUniques available: 200-499
-- If you want to change this, make sure you check in PrelNames
returnQIdKey, bindQIdKey, sequenceQIdKey, liftIdKey, newNameIdKey,
mkNameIdKey, mkNameG_vIdKey, mkNameG_dIdKey, mkNameG_tcIdKey,
mkNameLIdKey, mkNameSIdKey, unTypeIdKey, unTypeQIdKey,
unsafeTExpCoerceIdKey :: Unique
returnQIdKey = mkPreludeMiscIdUnique 200
bindQIdKey = mkPreludeMiscIdUnique 201
sequenceQIdKey = mkPreludeMiscIdUnique 202
liftIdKey = mkPreludeMiscIdUnique 203
newNameIdKey = mkPreludeMiscIdUnique 204
mkNameIdKey = mkPreludeMiscIdUnique 205
mkNameG_vIdKey = mkPreludeMiscIdUnique 206
mkNameG_dIdKey = mkPreludeMiscIdUnique 207
mkNameG_tcIdKey = mkPreludeMiscIdUnique 208
mkNameLIdKey = mkPreludeMiscIdUnique 209
mkNameSIdKey = mkPreludeMiscIdUnique 210
unTypeIdKey = mkPreludeMiscIdUnique 211
unTypeQIdKey = mkPreludeMiscIdUnique 212
unsafeTExpCoerceIdKey = mkPreludeMiscIdUnique 213
-- data Lit = ...
charLIdKey, stringLIdKey, integerLIdKey, intPrimLIdKey, wordPrimLIdKey,
floatPrimLIdKey, doublePrimLIdKey, rationalLIdKey, stringPrimLIdKey,
charPrimLIdKey:: Unique
charLIdKey = mkPreludeMiscIdUnique 220
stringLIdKey = mkPreludeMiscIdUnique 221
integerLIdKey = mkPreludeMiscIdUnique 222
intPrimLIdKey = mkPreludeMiscIdUnique 223
wordPrimLIdKey = mkPreludeMiscIdUnique 224
floatPrimLIdKey = mkPreludeMiscIdUnique 225
doublePrimLIdKey = mkPreludeMiscIdUnique 226
rationalLIdKey = mkPreludeMiscIdUnique 227
stringPrimLIdKey = mkPreludeMiscIdUnique 228
charPrimLIdKey = mkPreludeMiscIdUnique 229
liftStringIdKey :: Unique
liftStringIdKey = mkPreludeMiscIdUnique 230
-- data Pat = ...
litPIdKey, varPIdKey, tupPIdKey, unboxedTupPIdKey, conPIdKey, infixPIdKey, tildePIdKey, bangPIdKey,
asPIdKey, wildPIdKey, recPIdKey, listPIdKey, sigPIdKey, viewPIdKey :: Unique
litPIdKey = mkPreludeMiscIdUnique 240
varPIdKey = mkPreludeMiscIdUnique 241
tupPIdKey = mkPreludeMiscIdUnique 242
unboxedTupPIdKey = mkPreludeMiscIdUnique 243
conPIdKey = mkPreludeMiscIdUnique 244
infixPIdKey = mkPreludeMiscIdUnique 245
tildePIdKey = mkPreludeMiscIdUnique 246
bangPIdKey = mkPreludeMiscIdUnique 247
asPIdKey = mkPreludeMiscIdUnique 248
wildPIdKey = mkPreludeMiscIdUnique 249
recPIdKey = mkPreludeMiscIdUnique 250
listPIdKey = mkPreludeMiscIdUnique 251
sigPIdKey = mkPreludeMiscIdUnique 252
viewPIdKey = mkPreludeMiscIdUnique 253
-- type FieldPat = ...
fieldPatIdKey :: Unique
fieldPatIdKey = mkPreludeMiscIdUnique 260
-- data Match = ...
matchIdKey :: Unique
matchIdKey = mkPreludeMiscIdUnique 261
-- data Clause = ...
clauseIdKey :: Unique
clauseIdKey = mkPreludeMiscIdUnique 262
-- data Exp = ...
varEIdKey, conEIdKey, litEIdKey, appEIdKey, infixEIdKey, infixAppIdKey,
sectionLIdKey, sectionRIdKey, lamEIdKey, lamCaseEIdKey, tupEIdKey,
unboxedTupEIdKey, condEIdKey, multiIfEIdKey,
letEIdKey, caseEIdKey, doEIdKey, compEIdKey,
fromEIdKey, fromThenEIdKey, fromToEIdKey, fromThenToEIdKey,
listEIdKey, sigEIdKey, recConEIdKey, recUpdEIdKey, staticEIdKey,
unboundVarEIdKey :: Unique
varEIdKey = mkPreludeMiscIdUnique 270
conEIdKey = mkPreludeMiscIdUnique 271
litEIdKey = mkPreludeMiscIdUnique 272
appEIdKey = mkPreludeMiscIdUnique 273
infixEIdKey = mkPreludeMiscIdUnique 274
infixAppIdKey = mkPreludeMiscIdUnique 275
sectionLIdKey = mkPreludeMiscIdUnique 276
sectionRIdKey = mkPreludeMiscIdUnique 277
lamEIdKey = mkPreludeMiscIdUnique 278
lamCaseEIdKey = mkPreludeMiscIdUnique 279
tupEIdKey = mkPreludeMiscIdUnique 280
unboxedTupEIdKey = mkPreludeMiscIdUnique 281
condEIdKey = mkPreludeMiscIdUnique 282
multiIfEIdKey = mkPreludeMiscIdUnique 283
letEIdKey = mkPreludeMiscIdUnique 284
caseEIdKey = mkPreludeMiscIdUnique 285
doEIdKey = mkPreludeMiscIdUnique 286
compEIdKey = mkPreludeMiscIdUnique 287
fromEIdKey = mkPreludeMiscIdUnique 288
fromThenEIdKey = mkPreludeMiscIdUnique 289
fromToEIdKey = mkPreludeMiscIdUnique 290
fromThenToEIdKey = mkPreludeMiscIdUnique 291
listEIdKey = mkPreludeMiscIdUnique 292
sigEIdKey = mkPreludeMiscIdUnique 293
recConEIdKey = mkPreludeMiscIdUnique 294
recUpdEIdKey = mkPreludeMiscIdUnique 295
staticEIdKey = mkPreludeMiscIdUnique 296
unboundVarEIdKey = mkPreludeMiscIdUnique 297
-- type FieldExp = ...
fieldExpIdKey :: Unique
fieldExpIdKey = mkPreludeMiscIdUnique 310
-- data Body = ...
guardedBIdKey, normalBIdKey :: Unique
guardedBIdKey = mkPreludeMiscIdUnique 311
normalBIdKey = mkPreludeMiscIdUnique 312
-- data Guard = ...
normalGEIdKey, patGEIdKey :: Unique
normalGEIdKey = mkPreludeMiscIdUnique 313
patGEIdKey = mkPreludeMiscIdUnique 314
-- data Stmt = ...
bindSIdKey, letSIdKey, noBindSIdKey, parSIdKey :: Unique
bindSIdKey = mkPreludeMiscIdUnique 320
letSIdKey = mkPreludeMiscIdUnique 321
noBindSIdKey = mkPreludeMiscIdUnique 322
parSIdKey = mkPreludeMiscIdUnique 323
-- data Dec = ...
funDIdKey, valDIdKey, dataDIdKey, newtypeDIdKey, tySynDIdKey,
classDIdKey, instanceDIdKey, sigDIdKey, forImpDIdKey, pragInlDIdKey,
pragSpecDIdKey, pragSpecInlDIdKey, pragSpecInstDIdKey, pragRuleDIdKey,
pragAnnDIdKey, defaultSigDIdKey, dataFamilyDIdKey, openTypeFamilyDIdKey,
closedTypeFamilyDIdKey, dataInstDIdKey, newtypeInstDIdKey, tySynInstDIdKey,
standaloneDerivDIdKey, infixLDIdKey, infixRDIdKey, infixNDIdKey,
roleAnnotDIdKey :: Unique
funDIdKey = mkPreludeMiscIdUnique 330
valDIdKey = mkPreludeMiscIdUnique 331
dataDIdKey = mkPreludeMiscIdUnique 332
newtypeDIdKey = mkPreludeMiscIdUnique 333
tySynDIdKey = mkPreludeMiscIdUnique 334
classDIdKey = mkPreludeMiscIdUnique 335
instanceDIdKey = mkPreludeMiscIdUnique 336
sigDIdKey = mkPreludeMiscIdUnique 337
forImpDIdKey = mkPreludeMiscIdUnique 338
pragInlDIdKey = mkPreludeMiscIdUnique 339
pragSpecDIdKey = mkPreludeMiscIdUnique 340
pragSpecInlDIdKey = mkPreludeMiscIdUnique 341
pragSpecInstDIdKey = mkPreludeMiscIdUnique 342
pragRuleDIdKey = mkPreludeMiscIdUnique 343
pragAnnDIdKey = mkPreludeMiscIdUnique 344
dataFamilyDIdKey = mkPreludeMiscIdUnique 345
openTypeFamilyDIdKey = mkPreludeMiscIdUnique 346
dataInstDIdKey = mkPreludeMiscIdUnique 347
newtypeInstDIdKey = mkPreludeMiscIdUnique 348
tySynInstDIdKey = mkPreludeMiscIdUnique 349
closedTypeFamilyDIdKey = mkPreludeMiscIdUnique 350
infixLDIdKey = mkPreludeMiscIdUnique 352
infixRDIdKey = mkPreludeMiscIdUnique 353
infixNDIdKey = mkPreludeMiscIdUnique 354
roleAnnotDIdKey = mkPreludeMiscIdUnique 355
standaloneDerivDIdKey = mkPreludeMiscIdUnique 356
defaultSigDIdKey = mkPreludeMiscIdUnique 357
-- type Cxt = ...
cxtIdKey :: Unique
cxtIdKey = mkPreludeMiscIdUnique 360
-- data Strict = ...
isStrictKey, notStrictKey, unpackedKey :: Unique
isStrictKey = mkPreludeMiscIdUnique 363
notStrictKey = mkPreludeMiscIdUnique 364
unpackedKey = mkPreludeMiscIdUnique 365
-- data Con = ...
normalCIdKey, recCIdKey, infixCIdKey, forallCIdKey :: Unique
normalCIdKey = mkPreludeMiscIdUnique 370
recCIdKey = mkPreludeMiscIdUnique 371
infixCIdKey = mkPreludeMiscIdUnique 372
forallCIdKey = mkPreludeMiscIdUnique 373
-- type StrictType = ...
strictTKey :: Unique
strictTKey = mkPreludeMiscIdUnique 374
-- type VarStrictType = ...
varStrictTKey :: Unique
varStrictTKey = mkPreludeMiscIdUnique 375
-- data Type = ...
forallTIdKey, varTIdKey, conTIdKey, tupleTIdKey, unboxedTupleTIdKey, arrowTIdKey,
listTIdKey, appTIdKey, sigTIdKey, equalityTIdKey, litTIdKey,
promotedTIdKey, promotedTupleTIdKey,
promotedNilTIdKey, promotedConsTIdKey,
wildCardTIdKey, namedWildCardTIdKey :: Unique
forallTIdKey = mkPreludeMiscIdUnique 380
varTIdKey = mkPreludeMiscIdUnique 381
conTIdKey = mkPreludeMiscIdUnique 382
tupleTIdKey = mkPreludeMiscIdUnique 383
unboxedTupleTIdKey = mkPreludeMiscIdUnique 384
arrowTIdKey = mkPreludeMiscIdUnique 385
listTIdKey = mkPreludeMiscIdUnique 386
appTIdKey = mkPreludeMiscIdUnique 387
sigTIdKey = mkPreludeMiscIdUnique 388
equalityTIdKey = mkPreludeMiscIdUnique 389
litTIdKey = mkPreludeMiscIdUnique 390
promotedTIdKey = mkPreludeMiscIdUnique 391
promotedTupleTIdKey = mkPreludeMiscIdUnique 392
promotedNilTIdKey = mkPreludeMiscIdUnique 393
promotedConsTIdKey = mkPreludeMiscIdUnique 394
wildCardTIdKey = mkPreludeMiscIdUnique 395
namedWildCardTIdKey = mkPreludeMiscIdUnique 396
-- data TyLit = ...
numTyLitIdKey, strTyLitIdKey :: Unique
numTyLitIdKey = mkPreludeMiscIdUnique 400
strTyLitIdKey = mkPreludeMiscIdUnique 401
-- data TyVarBndr = ...
plainTVIdKey, kindedTVIdKey :: Unique
plainTVIdKey = mkPreludeMiscIdUnique 402
kindedTVIdKey = mkPreludeMiscIdUnique 403
-- data Role = ...
nominalRIdKey, representationalRIdKey, phantomRIdKey, inferRIdKey :: Unique
nominalRIdKey = mkPreludeMiscIdUnique 404
representationalRIdKey = mkPreludeMiscIdUnique 405
phantomRIdKey = mkPreludeMiscIdUnique 406
inferRIdKey = mkPreludeMiscIdUnique 407
-- data Kind = ...
varKIdKey, conKIdKey, tupleKIdKey, arrowKIdKey, listKIdKey, appKIdKey,
starKIdKey, constraintKIdKey :: Unique
varKIdKey = mkPreludeMiscIdUnique 408
conKIdKey = mkPreludeMiscIdUnique 409
tupleKIdKey = mkPreludeMiscIdUnique 410
arrowKIdKey = mkPreludeMiscIdUnique 411
listKIdKey = mkPreludeMiscIdUnique 412
appKIdKey = mkPreludeMiscIdUnique 413
starKIdKey = mkPreludeMiscIdUnique 414
constraintKIdKey = mkPreludeMiscIdUnique 415
-- data FamilyResultSig = ...
noSigIdKey, kindSigIdKey, tyVarSigIdKey :: Unique
noSigIdKey = mkPreludeMiscIdUnique 416
kindSigIdKey = mkPreludeMiscIdUnique 417
tyVarSigIdKey = mkPreludeMiscIdUnique 418
-- data InjectivityAnn = ...
injectivityAnnIdKey :: Unique
injectivityAnnIdKey = mkPreludeMiscIdUnique 419
-- data Callconv = ...
cCallIdKey, stdCallIdKey, cApiCallIdKey, primCallIdKey,
javaScriptCallIdKey :: Unique
cCallIdKey = mkPreludeMiscIdUnique 420
stdCallIdKey = mkPreludeMiscIdUnique 421
cApiCallIdKey = mkPreludeMiscIdUnique 422
primCallIdKey = mkPreludeMiscIdUnique 423
javaScriptCallIdKey = mkPreludeMiscIdUnique 424
-- data Safety = ...
unsafeIdKey, safeIdKey, interruptibleIdKey :: Unique
unsafeIdKey = mkPreludeMiscIdUnique 430
safeIdKey = mkPreludeMiscIdUnique 431
interruptibleIdKey = mkPreludeMiscIdUnique 432
-- data FunDep = ...
funDepIdKey :: Unique
funDepIdKey = mkPreludeMiscIdUnique 440
-- data FamFlavour = ...
typeFamIdKey, dataFamIdKey :: Unique
typeFamIdKey = mkPreludeMiscIdUnique 450
dataFamIdKey = mkPreludeMiscIdUnique 451
-- data TySynEqn = ...
tySynEqnIdKey :: Unique
tySynEqnIdKey = mkPreludeMiscIdUnique 460
-- quasiquoting
quoteExpKey, quotePatKey, quoteDecKey, quoteTypeKey :: Unique
quoteExpKey = mkPreludeMiscIdUnique 470
quotePatKey = mkPreludeMiscIdUnique 471
quoteDecKey = mkPreludeMiscIdUnique 472
quoteTypeKey = mkPreludeMiscIdUnique 473
-- data RuleBndr = ...
ruleVarIdKey, typedRuleVarIdKey :: Unique
ruleVarIdKey = mkPreludeMiscIdUnique 480
typedRuleVarIdKey = mkPreludeMiscIdUnique 481
-- data AnnTarget = ...
valueAnnotationIdKey, typeAnnotationIdKey, moduleAnnotationIdKey :: Unique
valueAnnotationIdKey = mkPreludeMiscIdUnique 490
typeAnnotationIdKey = mkPreludeMiscIdUnique 491
moduleAnnotationIdKey = mkPreludeMiscIdUnique 492
{-
************************************************************************
* *
RdrNames
* *
************************************************************************
-}
lift_RDR, mkNameG_dRDR, mkNameG_vRDR :: RdrName
lift_RDR = nameRdrName liftName
mkNameG_dRDR = nameRdrName mkNameG_dName
mkNameG_vRDR = nameRdrName mkNameG_vName
-- data Exp = ...
conE_RDR, litE_RDR, appE_RDR, infixApp_RDR :: RdrName
conE_RDR = nameRdrName conEName
litE_RDR = nameRdrName litEName
appE_RDR = nameRdrName appEName
infixApp_RDR = nameRdrName infixAppName
-- data Lit = ...
stringL_RDR, intPrimL_RDR, wordPrimL_RDR, floatPrimL_RDR,
doublePrimL_RDR, stringPrimL_RDR, charPrimL_RDR :: RdrName
stringL_RDR = nameRdrName stringLName
intPrimL_RDR = nameRdrName intPrimLName
wordPrimL_RDR = nameRdrName wordPrimLName
floatPrimL_RDR = nameRdrName floatPrimLName
doublePrimL_RDR = nameRdrName doublePrimLName
stringPrimL_RDR = nameRdrName stringPrimLName
charPrimL_RDR = nameRdrName charPrimLName
| AlexanderPankiv/ghc | compiler/prelude/THNames.hs | bsd-3-clause | 41,406 | 0 | 8 | 8,724 | 7,533 | 4,373 | 3,160 | 687 | 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="ur-PK">
<title>Call Home Add-On</title>
<maps>
<homeID>callhome</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/callhome/src/main/javahelp/org/zaproxy/addon/callhome/resources/help_ur_PK/helpset_ur_PK.hs | apache-2.0 | 966 | 77 | 67 | 157 | 413 | 209 | 204 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
--
-- Module : IDE.Command.VCS.GIT
-- Copyright : 2007-2011 Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GPL Nothing
--
-- Maintainer : maintainer@leksah.org
-- Stability : provisional
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module IDE.Command.VCS.GIT (
commitAction
,viewLogAction
,pushAction
,pullAction
,mkGITActions
) where
import IDE.Core.Types
import IDE.Core.State
import qualified IDE.Command.VCS.Common.Helper as Helper
import qualified IDE.Command.VCS.Types as Types
import qualified VCSGui.Git as GitGUI
import qualified VCSWrapper.Git as Git
import Data.Text (Text)
commitAction :: Types.VCSAction ()
commitAction = Helper.createActionFromContext GitGUI.showCommitGUI
viewLogAction :: Types.VCSAction ()
viewLogAction = Helper.createActionFromContext GitGUI.showLogGUI
pushAction :: Types.VCSAction ()
pushAction = Helper.createActionFromContext $ GitGUI.askPassWrapper Git.push
pullAction :: Types.VCSAction ()
pullAction = Helper.createActionFromContext $ GitGUI.askPassWrapper GitGUI.pull
mkGITActions :: [(Text, Types.VCSAction ())]
mkGITActions = [
("_Commit", commitAction)
,("_View Log", viewLogAction)
,("_Push", pushAction)
,("_Pull", pullAction)
]
| 573/leksah | src/IDE/Command/VCS/GIT.hs | gpl-2.0 | 1,489 | 0 | 8 | 259 | 268 | 167 | 101 | 28 | 1 |
module Foo () where
{-@ measure getfst :: (a, b) -> a
getfst (x, y) = x
@-}
{-@ type Pair a b = {v0 : ({v:a | v = (getfst v0)}, b) | true } @-}
{-@ type OPList a b = [(Pair a b)]<\h -> {v: (a, b) | (getfst v) >= (getfst h)}> @-}
{-@ type OList a = [a]<\h -> {v: a | (v >= h)}> @-}
{-@ getFsts :: OPList a b -> OList a @-}
getFsts [] = []
getFsts ((x,_) : xs) = x : getFsts xs
| ssaavedra/liquidhaskell | tests/pos/PairMeasure.hs | bsd-3-clause | 413 | 0 | 8 | 131 | 52 | 31 | 21 | 3 | 1 |
module Util.Http (
Links(..),
httpGet,
httpGetLink,
httpPost,
httpPostStatus,
httpPut,
httpDelete
) where
import Import.NoFoundation hiding (responseBody, responseStatus, statusCode, checkStatus)
import Data.Text (append)
import qualified Data.ByteString.Lazy as L
import Network.Wreq
import Control.Lens
data Links = Links {
relNext :: Maybe Text,
relPrev :: Maybe Text,
relFirst :: Maybe Text,
relLast :: Maybe Text
} deriving (Show)
toLinks :: Response body -> Links
toLinks r =
Links{
relNext=decodeUtf8 <$> (r ^? responseLink "rel" "next" . linkURL),
relPrev=decodeUtf8 <$> (r ^? responseLink "rel" "prev" . linkURL),
relFirst=decodeUtf8 <$> (r ^? responseLink "rel" "first" . linkURL),
relLast=decodeUtf8 <$> (r ^? responseLink "rel" "last" . linkURL)
}
httpGet :: String -> Maybe Text -> IO L.ByteString
httpGet url authToken = do
r <- getWith (reqOptions authToken) url
return $ r ^. responseBody
httpGetLink :: String -> Maybe Text -> IO (L.ByteString, Links)
httpGetLink url authToken = do
r <- getWith (reqOptions authToken) url
return $ (r ^. responseBody, toLinks r)
httpPost :: String -> Maybe Text -> L.ByteString -> IO L.ByteString
httpPost url authToken payload = do
r <- postWith (reqOptions authToken) url payload
return $ r ^. responseBody
httpPostStatus :: String -> Maybe Text -> L.ByteString -> IO (Int, L.ByteString)
httpPostStatus url authToken payload = do
r <- postWith (reqOptionsNoCheck authToken) url payload
return (r ^. responseStatus . statusCode, r ^. responseBody)
httpPut :: String -> Maybe Text -> L.ByteString -> IO L.ByteString
httpPut url authToken payload = do
r <- putWith (reqOptions authToken) url payload
return $ r ^. responseBody
httpDelete :: String -> Maybe Text -> IO Int
httpDelete url authToken = do
r <- deleteWith (reqOptions authToken) url
return $ r ^. responseStatus . statusCode
reqOptionsNoCheck :: Maybe Text -> Options
reqOptionsNoCheck authToken =
(reqOptions authToken) & checkStatus .~ Just (\_ _ _ -> Nothing)
reqOptions :: Maybe Text -> Options
reqOptions Nothing = defaults & header "Content-type" .~ ["application/json"]
reqOptions (Just authToken) =
defaults &
header "Authorization" .~ [authHeader authToken] &
header "Content-type" .~ ["application/json"]
authHeader :: Text -> ByteString
authHeader = encodeUtf8 . append "Token "
| vinnymac/glot-www | Util/Http.hs | mit | 2,470 | 0 | 11 | 505 | 835 | 429 | 406 | -1 | -1 |
module OpcodeTypes
( Bytecode(..)
, oneOperandBytecodes
, zeroOperandBytecodes
, twoOperandBytecodes
, varOperandBytecodes
, extBytecodes
, opcodeName
) where
import qualified Story as S
data Bytecode = OP2_1 | OP2_2 | OP2_3 | OP2_4 | OP2_5 | OP2_6 | OP2_7
| OP2_8 | OP2_9 | OP2_10 | OP2_11 | OP2_12 | OP2_13 | OP2_14 | OP2_15
| OP2_16 | OP2_17 | OP2_18 | OP2_19 | OP2_20 | OP2_21 | OP2_22 | OP2_23
| OP2_24 | OP2_25 | OP2_26 | OP2_27 | OP2_28
| OP1_128 | OP1_129 | OP1_130 | OP1_131 | OP1_132 | OP1_133 | OP1_134 | OP1_135
| OP1_136 | OP1_137 | OP1_138 | OP1_139 | OP1_140 | OP1_141 | OP1_142 | OP1_143
| OP0_176 | OP0_177 | OP0_178 | OP0_179 | OP0_180 | OP0_181 | OP0_182 | OP0_183
| OP0_184 | OP0_185 | OP0_186 | OP0_187 | OP0_188 | OP0_189 | OP0_190 | OP0_191
| VAR_224 | VAR_225 | VAR_226 | VAR_227 | VAR_228 | VAR_229 | VAR_230 | VAR_231
| VAR_232 | VAR_233 | VAR_234 | VAR_235 | VAR_236 | VAR_237 | VAR_238 | VAR_239
| VAR_240 | VAR_241 | VAR_242 | VAR_243 | VAR_244 | VAR_245 | VAR_246 | VAR_247
| VAR_248 | VAR_249 | VAR_250 | VAR_251 | VAR_252 | VAR_253 | VAR_254 | VAR_255
| EXT_0 | EXT_1 | EXT_2 | EXT_3 | EXT_4 | EXT_5 | EXT_6 | EXT_7
| EXT_8 | EXT_9 | EXT_10 | EXT_11 | EXT_12 | EXT_13 | EXT_14
| EXT_16 | EXT_17 | EXT_18 | EXT_19 | EXT_20 | EXT_21 | EXT_22 | EXT_23
| EXT_24 | EXT_25 | EXT_26 | EXT_27 | EXT_28 | EXT_29
| ILLEGAL
deriving (Eq)
--these lists are used to map from the opcode number to the opcode type
oneOperandBytecodes :: [Bytecode]
oneOperandBytecodes = [
OP1_128, OP1_129, OP1_130, OP1_131, OP1_132, OP1_133, OP1_134, OP1_135,
OP1_136, OP1_137, OP1_138, OP1_139, OP1_140, OP1_141, OP1_142, OP1_143 ]
zeroOperandBytecodes :: [Bytecode]
zeroOperandBytecodes = [
OP0_176, OP0_177, OP0_178, OP0_179, OP0_180, OP0_181, OP0_182, OP0_183,
OP0_184, OP0_185, OP0_186, OP0_187, OP0_188, OP0_189, OP0_190, OP0_191 ]
twoOperandBytecodes :: [Bytecode]
twoOperandBytecodes =[
ILLEGAL, OP2_1, OP2_2, OP2_3, OP2_4, OP2_5, OP2_6, OP2_7,
OP2_8, OP2_9, OP2_10, OP2_11, OP2_12, OP2_13, OP2_14, OP2_15,
OP2_16, OP2_17, OP2_18, OP2_19, OP2_20, OP2_21, OP2_22, OP2_23,
OP2_24, OP2_25, OP2_26, OP2_27, OP2_28, ILLEGAL, ILLEGAL, ILLEGAL ]
varOperandBytecodes :: [Bytecode]
varOperandBytecodes = [
VAR_224, VAR_225, VAR_226, VAR_227, VAR_228, VAR_229, VAR_230, VAR_231,
VAR_232, VAR_233, VAR_234, VAR_235, VAR_236, VAR_237, VAR_238, VAR_239,
VAR_240, VAR_241, VAR_242, VAR_243, VAR_244, VAR_245, VAR_246, VAR_247,
VAR_248, VAR_249, VAR_250, VAR_251, VAR_252, VAR_253, VAR_254, VAR_255 ]
extBytecodes :: [Bytecode]
extBytecodes = [
EXT_0, EXT_1, EXT_2, EXT_3, EXT_4, EXT_5, EXT_6, EXT_7,
EXT_8, EXT_9, EXT_10, EXT_11, EXT_12, EXT_13, EXT_14, ILLEGAL,
EXT_16, EXT_17, EXT_18, EXT_19, EXT_20, EXT_21, EXT_22, EXT_23,
EXT_24, EXT_25, EXT_26, EXT_27, EXT_28, EXT_29, ILLEGAL, ILLEGAL ]
opcodeName :: S.Story -> Bytecode -> String
opcodeName story opcode = case opcode of
ILLEGAL -> "ILLEGAL"
OP2_1 -> "je"
OP2_2 -> "jl"
OP2_3 -> "jg"
OP2_4 -> "dec_chk"
OP2_5 -> "inc_chk"
OP2_6 -> "jin"
OP2_7 -> "test"
OP2_8 -> "or"
OP2_9 -> "and"
OP2_10 -> "test_attr"
OP2_11 -> "set_attr"
OP2_12 -> "clear_attr"
OP2_13 -> "store"
OP2_14 -> "insert_obj"
OP2_15 -> "loadw"
OP2_16 -> "loadb"
OP2_17 -> "get_prop"
OP2_18 -> "get_prop_addr"
OP2_19 -> "get_next_prop"
OP2_20 -> "add"
OP2_21 -> "sub"
OP2_22 -> "mul"
OP2_23 -> "div"
OP2_24 -> "mod"
OP2_25 -> "call_2s"
OP2_26 -> "call_2n"
OP2_27 -> "set_colour"
OP2_28 -> "throw"
OP1_128 -> "jz"
OP1_129 -> "get_sibling"
OP1_130 -> "get_child"
OP1_131 -> "get_parent"
OP1_132 -> "get_prop_len"
OP1_133 -> "inc"
OP1_134 -> "dec"
OP1_135 -> "print_addr"
OP1_136 -> "call_1s"
OP1_137 -> "remove_obj"
OP1_138 -> "print_obj"
OP1_139 -> "ret"
OP1_140 -> "jump"
OP1_141 -> "print_paddr"
OP1_142 -> "load"
OP1_143 -> if S.isV4OrLower story then "not" else "call_1n"
OP0_176 -> "rtrue"
OP0_177 -> "rfalse"
OP0_178 -> "print"
OP0_179 -> "print_ret"
OP0_180 -> "nop"
OP0_181 -> "save"
OP0_182 -> "restore"
OP0_183 -> "restart"
OP0_184 -> "ret_popped"
OP0_185 -> if S.isV4OrLower story then "pop" else "catch"
OP0_186 -> "quit"
OP0_187 -> "new_line"
OP0_188 -> "show_status"
OP0_189 -> "verify"
OP0_190 -> "EXTENDED"
OP0_191 -> "piracy"
VAR_224 -> if S.isV3OrLower story then "call" else "call_vs"
VAR_225 -> "storew"
VAR_226 -> "storeb"
VAR_227 -> "put_prop"
VAR_228 -> if S.isV4OrLower story then "sread" else "aread"
VAR_229 -> "print_char"
VAR_230 -> "print_num"
VAR_231 -> "random"
VAR_232 -> "push"
VAR_233 -> "pull"
VAR_234 -> "split_window"
VAR_235 -> "set_window"
VAR_236 -> "call_vs2"
VAR_237 -> "erase_window"
VAR_238 -> "erase_line"
VAR_239 -> "set_cursor"
VAR_240 -> "get_cursor"
VAR_241 -> "set_text_style"
VAR_242 -> "buffer_mode"
VAR_243 -> "output_stream"
VAR_244 -> "input_stream"
VAR_245 -> "sound_effect"
VAR_246 -> "read_char"
VAR_247 -> "scan_table"
VAR_248 -> "not"
VAR_249 -> "call_vn"
VAR_250 -> "call_vn2"
VAR_251 -> "tokenise"
VAR_252 -> "encode_text"
VAR_253 -> "copy_table"
VAR_254 -> "print_table"
VAR_255 -> "check_arg_count"
EXT_0 -> "save"
EXT_1 -> "restore"
EXT_2 -> "log_shift"
EXT_3 -> "art_shift"
EXT_4 -> "set_font"
EXT_5 -> "draw_picture"
EXT_6 -> "picture_data"
EXT_7 -> "erase_picture"
EXT_8 -> "set_margins"
EXT_9 -> "save_undo"
EXT_10 -> "restore_undo"
EXT_11 -> "print_unicode"
EXT_12 -> "check_unicode"
EXT_13 -> "set_true_colour"
EXT_14 -> "sound_data"
EXT_16 -> "move_window"
EXT_17 -> "window_size"
EXT_18 -> "window_style"
EXT_19 -> "get_wind_prop"
EXT_20 -> "scroll_window"
EXT_21 -> "pop_stack"
EXT_22 -> "read_mouse"
EXT_23 -> "mouse_window"
EXT_24 -> "push_stack"
EXT_25 -> "put_wind_prop"
EXT_26 -> "print_form"
EXT_27 -> "make_menu"
EXT_28 -> "picture_table"
EXT_29 -> "buffer_screen"
| DylanSp/zmachine-interpreter | src/OpcodeTypes.hs | mit | 6,699 | 0 | 10 | 1,890 | 1,677 | 982 | 695 | 177 | 126 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
module Unison.Codebase.SqliteCodebase
( Unison.Codebase.SqliteCodebase.init,
unsafeGetConnection,
shutdownConnection,
)
where
import qualified Control.Concurrent
import qualified Control.Exception
import Control.Monad (filterM, unless, when, (>=>))
import Control.Monad.Except (ExceptT(ExceptT), MonadError (throwError), runExceptT)
import qualified Control.Monad.Except as Except
import Control.Monad.Extra (ifM, unlessM)
import qualified Control.Monad.Extra as Monad
import Control.Monad.Reader (ReaderT (runReaderT))
import Control.Monad.State (MonadState)
import qualified Control.Monad.State as State
import Control.Monad.Trans (MonadTrans (lift))
import Control.Monad.Trans.Maybe (MaybeT (MaybeT))
import Data.Bifunctor (Bifunctor (bimap, first), second)
import qualified Data.Either.Combinators as Either
import qualified Data.Char as Char
import Data.Foldable (Foldable (toList), for_, traverse_)
import Data.Functor (void, (<&>), ($>))
import qualified Data.List as List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (fromJust)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.IO as TextIO
import Data.Traversable (for)
import Data.Word (Word64)
import qualified Database.SQLite.Simple as Sqlite
import GHC.Stack (HasCallStack)
import qualified System.Console.ANSI as ANSI
import System.FilePath ((</>))
import qualified System.FilePath as FilePath
import U.Codebase.HashTags (CausalHash (CausalHash, unCausalHash))
import U.Codebase.Sqlite.Operations (EDB)
import qualified U.Codebase.Reference as C.Reference
import U.Codebase.Sqlite.Connection (Connection (Connection))
import qualified U.Codebase.Sqlite.Connection as Connection
import qualified U.Codebase.Sqlite.JournalMode as JournalMode
import qualified U.Codebase.Sqlite.ObjectType as OT
import qualified U.Codebase.Sqlite.Operations as Ops
import qualified U.Codebase.Sqlite.Queries as Q
import qualified U.Codebase.Sqlite.Sync22 as Sync22
import qualified U.Codebase.Sync as Sync
import qualified U.Codebase.WatchKind as WK
import qualified U.Util.Cache as Cache
import qualified U.Util.Hash as H2
import qualified U.Util.Monoid as Monoid
import qualified U.Util.Set as Set
import qualified Unison.Builtin as Builtins
import Unison.Codebase (Codebase, CodebasePath)
import qualified Unison.Codebase as Codebase1
import Unison.Codebase.Branch (Branch (..))
import qualified Unison.Codebase.Branch as Branch
import qualified Unison.Codebase.Causal as Causal
import Unison.Codebase.Editor.Git (gitIn, gitTextIn, pullBranch)
import Unison.Codebase.Editor.RemoteRepo (ReadRemoteNamespace, WriteRepo (WriteGitRepo), writeToRead, printWriteRepo)
import Unison.Codebase.GitError (GitError)
import qualified Unison.Codebase.GitError as GitError
import qualified Unison.Codebase.Init as Codebase
import qualified Unison.Codebase.Init as Codebase1
import Unison.Codebase.Patch (Patch)
import qualified Unison.Codebase.Reflog as Reflog
import Unison.Codebase.ShortBranchHash (ShortBranchHash)
import qualified Unison.Codebase.SqliteCodebase.Branch.Dependencies as BD
import qualified Unison.Codebase.SqliteCodebase.Conversions as Cv
import qualified Unison.Codebase.SqliteCodebase.SyncEphemeral as SyncEphemeral
import Unison.Codebase.SyncMode (SyncMode)
import qualified Unison.ConstructorType as CT
import Unison.DataDeclaration (Decl)
import qualified Unison.DataDeclaration as Decl
import Unison.Hash (Hash)
import Unison.Parser (Ann)
import Unison.Prelude (MaybeT (runMaybeT), fromMaybe, isJust, trace, traceM)
import Unison.Reference (Reference)
import qualified Unison.Reference as Reference
import qualified Unison.Referent as Referent
import Unison.ShortHash (ShortHash)
import qualified Unison.ShortHash as SH
import qualified Unison.ShortHash as ShortHash
import Unison.Symbol (Symbol)
import Unison.Term (Term)
import qualified Unison.Term as Term
import Unison.Type (Type)
import qualified Unison.Type as Type
import qualified Unison.UnisonFile as UF
import qualified Unison.Util.Pretty as P
import U.Util.Timing (time)
import UnliftIO (MonadIO, catchIO, finally, liftIO)
import UnliftIO.Directory (canonicalizePath, createDirectoryIfMissing, doesDirectoryExist, doesFileExist)
import UnliftIO.STM
import U.Codebase.Sqlite.DbId (SchemaVersion(SchemaVersion))
import Control.Exception.Safe (MonadCatch)
debug, debugProcessBranches, debugCommitFailedTransaction :: Bool
debug = False
debugProcessBranches = False
debugCommitFailedTransaction = False
codebasePath :: FilePath
codebasePath = ".unison" </> "v2" </> "unison.sqlite3"
v2dir :: FilePath -> FilePath
v2dir root = root </> ".unison" </> "v2"
init :: HasCallStack => (MonadIO m, MonadCatch m) => Codebase.Init m Symbol Ann
init = Codebase.Init getCodebaseOrError createCodebaseOrError v2dir
createCodebaseOrError ::
(MonadIO m, MonadCatch m) =>
Codebase.DebugName ->
CodebasePath ->
m (Either Codebase1.CreateCodebaseError (m (), Codebase m Symbol Ann))
createCodebaseOrError debugName dir = do
prettyDir <- P.string <$> canonicalizePath dir
let convertError = \case
CreateCodebaseAlreadyExists -> Codebase1.CreateCodebaseAlreadyExists
CreateCodebaseUnknownSchemaVersion v -> Codebase1.CreateCodebaseOther $ prettyError v
prettyError :: SchemaVersion -> Codebase1.Pretty
prettyError v = P.wrap $
"I don't know how to handle " <> P.shown v <> "in" <> P.backticked' prettyDir "."
Either.mapLeft convertError <$> createCodebaseOrError' debugName dir
data CreateCodebaseError
= CreateCodebaseAlreadyExists
| CreateCodebaseUnknownSchemaVersion SchemaVersion
deriving (Show)
createCodebaseOrError' ::
(MonadIO m, MonadCatch m) =>
Codebase.DebugName ->
CodebasePath ->
m (Either CreateCodebaseError (m (), Codebase m Symbol Ann))
createCodebaseOrError' debugName path = do
ifM
(doesFileExist $ path </> codebasePath)
(pure $ Left CreateCodebaseAlreadyExists)
do
createDirectoryIfMissing True (path </> FilePath.takeDirectory codebasePath)
liftIO $
Control.Exception.bracket
(unsafeGetConnection (debugName ++ ".createSchema") path)
shutdownConnection
(runReaderT do
Q.createSchema
runExceptT (void . Ops.saveRootBranch $ Cv.causalbranch1to2 Branch.empty) >>= \case
Left e -> error $ show e
Right () -> pure ()
)
fmap (Either.mapLeft CreateCodebaseUnknownSchemaVersion) (sqliteCodebase debugName path)
openOrCreateCodebaseConnection :: MonadIO m => Codebase.DebugName -> FilePath -> m Connection
openOrCreateCodebaseConnection debugName path = do
unlessM
(doesFileExist $ path </> codebasePath)
(initSchemaIfNotExist path)
unsafeGetConnection debugName path
-- get the codebase in dir
getCodebaseOrError :: forall m. (MonadIO m, MonadCatch m) => Codebase.DebugName -> CodebasePath -> m (Either Codebase1.Pretty (m (), Codebase m Symbol Ann))
getCodebaseOrError debugName dir = do
prettyDir <- liftIO $ P.string <$> canonicalizePath dir
let prettyError v = P.wrap $ "I don't know how to handle " <> P.shown v <> "in" <> P.backticked' prettyDir "."
doesFileExist (dir </> codebasePath) >>= \case
-- If the codebase file doesn't exist, just return any string. The string is currently ignored (see
-- Unison.Codebase.Init.getCodebaseOrExit).
False -> pure (Left "codebase doesn't exist")
True -> fmap (Either.mapLeft prettyError) (sqliteCodebase debugName dir)
initSchemaIfNotExist :: MonadIO m => FilePath -> m ()
initSchemaIfNotExist path = liftIO do
unlessM (doesDirectoryExist $ path </> FilePath.takeDirectory codebasePath) $
createDirectoryIfMissing True (path </> FilePath.takeDirectory codebasePath)
unlessM (doesFileExist $ path </> codebasePath) $
Control.Exception.bracket
(unsafeGetConnection "initSchemaIfNotExist" path)
shutdownConnection
(runReaderT Q.createSchema)
-- checks if a db exists at `path` with the minimum schema
codebaseExists :: MonadIO m => CodebasePath -> m Bool
codebaseExists root = liftIO do
Monad.when debug $ traceM $ "codebaseExists " ++ root
Control.Exception.catch @Sqlite.SQLError
( sqliteCodebase "codebaseExists" root >>= \case
Left _ -> pure False
Right (close, _codebase) -> close $> True
)
(const $ pure False)
-- 1) buffer up the component
-- 2) in the event that the component is complete, then what?
-- * can write component provided all of its dependency components are complete.
-- if dependency not complete,
-- register yourself to be written when that dependency is complete
-- an entry for a single hash
data BufferEntry a = BufferEntry
{ -- First, you are waiting for the cycle to fill up with all elements
-- Then, you check: are all dependencies of the cycle in the db?
-- If yes: write yourself to database and trigger check of dependents
-- If no: just wait, do nothing
beComponentTargetSize :: Maybe Word64,
beComponent :: Map Reference.Pos a,
beMissingDependencies :: Set Hash,
beWaitingDependents :: Set Hash
}
deriving (Eq, Show)
prettyBufferEntry :: Show a => Hash -> BufferEntry a -> String
prettyBufferEntry (h :: Hash) BufferEntry {..} =
"BufferEntry " ++ show h ++ "\n"
++ " { beComponentTargetSize = "
++ show beComponentTargetSize
++ "\n"
++ " , beComponent = "
++ if Map.size beComponent < 2
then show $ Map.toList beComponent
else
mkString (Map.toList beComponent) (Just "\n [ ") " , " (Just "]\n")
++ " , beMissingDependencies ="
++ if Set.size beMissingDependencies < 2
then show $ Set.toList beMissingDependencies
else
mkString (Set.toList beMissingDependencies) (Just "\n [ ") " , " (Just "]\n")
++ " , beWaitingDependents ="
++ if Set.size beWaitingDependents < 2
then show $ Set.toList beWaitingDependents
else
mkString (Set.toList beWaitingDependents) (Just "\n [ ") " , " (Just "]\n")
++ " }"
where
mkString :: (Foldable f, Show a) => f a -> Maybe String -> String -> Maybe String -> String
mkString as start middle end = fromMaybe "" start ++ List.intercalate middle (show <$> toList as) ++ fromMaybe "" end
type TermBufferEntry = BufferEntry (Term Symbol Ann, Type Symbol Ann)
type DeclBufferEntry = BufferEntry (Decl Symbol Ann)
unsafeGetConnection :: MonadIO m => Codebase.DebugName -> CodebasePath -> m Connection
unsafeGetConnection name root = do
let path = root </> codebasePath
Monad.when debug $ traceM $ "unsafeGetconnection " ++ name ++ " " ++ root ++ " -> " ++ path
(Connection name path -> conn) <- liftIO $ Sqlite.open path
runReaderT Q.setFlags conn
pure conn
shutdownConnection :: MonadIO m => Connection -> m ()
shutdownConnection conn = do
Monad.when debug $ traceM $ "shutdown connection " ++ show conn
liftIO $ Sqlite.close (Connection.underlying conn)
sqliteCodebase :: (MonadIO m, MonadCatch m) => Codebase.DebugName -> CodebasePath -> m (Either SchemaVersion (m (), Codebase m Symbol Ann))
sqliteCodebase debugName root = do
Monad.when debug $ traceM $ "sqliteCodebase " ++ debugName ++ " " ++ root
conn <- unsafeGetConnection debugName root
termCache <- Cache.semispaceCache 8192 -- pure Cache.nullCache -- to disable
typeOfTermCache <- Cache.semispaceCache 8192
declCache <- Cache.semispaceCache 1024
runReaderT Q.schemaVersion conn >>= \case
SchemaVersion 1 -> do
rootBranchCache <- newTVarIO Nothing
-- The v1 codebase interface has operations to read and write individual definitions
-- whereas the v2 codebase writes them as complete components. These two fields buffer
-- the individual definitions until a complete component has been written.
termBuffer :: TVar (Map Hash TermBufferEntry) <- newTVarIO Map.empty
declBuffer :: TVar (Map Hash DeclBufferEntry) <- newTVarIO Map.empty
cycleLengthCache <- Cache.semispaceCache 8192
declTypeCache <- Cache.semispaceCache 2048
let getTerm :: MonadIO m => Reference.Id -> m (Maybe (Term Symbol Ann))
getTerm (Reference.Id h1@(Cv.hash1to2 -> h2) i _n) =
runDB' conn do
term2 <- Ops.loadTermByReference (C.Reference.Id h2 i)
Cv.term2to1 h1 (getCycleLen "getTerm") getDeclType term2
getCycleLen :: EDB m => String -> Hash -> m Reference.Size
getCycleLen source = Cache.apply cycleLengthCache \h ->
(Ops.getCycleLen . Cv.hash1to2) h `Except.catchError` \case
e@(Ops.DatabaseIntegrityError (Q.NoObjectForPrimaryHashId {})) -> pure . error $ show e ++ " in " ++ source
e -> Except.throwError e
getDeclType :: EDB m => C.Reference.Reference -> m CT.ConstructorType
getDeclType = Cache.apply declTypeCache \case
C.Reference.ReferenceBuiltin t ->
let err =
error $
"I don't know about the builtin type ##"
++ show t
++ ", but I've been asked for it's ConstructorType."
in pure . fromMaybe err $
Map.lookup (Reference.Builtin t) Builtins.builtinConstructorType
C.Reference.ReferenceDerived i -> getDeclTypeById i
getDeclTypeById :: EDB m => C.Reference.Id -> m CT.ConstructorType
getDeclTypeById = fmap Cv.decltype2to1 . Ops.getDeclTypeByReference
getTypeOfTermImpl :: MonadIO m => Reference.Id -> m (Maybe (Type Symbol Ann))
getTypeOfTermImpl id | debug && trace ("getTypeOfTermImpl " ++ show id) False = undefined
getTypeOfTermImpl (Reference.Id (Cv.hash1to2 -> h2) i _n) =
runDB' conn do
type2 <- Ops.loadTypeOfTermByTermReference (C.Reference.Id h2 i)
Cv.ttype2to1 (getCycleLen "getTypeOfTermImpl") type2
getTypeDeclaration :: MonadIO m => Reference.Id -> m (Maybe (Decl Symbol Ann))
getTypeDeclaration (Reference.Id h1@(Cv.hash1to2 -> h2) i _n) =
runDB' conn do
decl2 <- Ops.loadDeclByReference (C.Reference.Id h2 i)
Cv.decl2to1 h1 (getCycleLen "getTypeDeclaration") decl2
putTerm :: MonadIO m => Reference.Id -> Term Symbol Ann -> Type Symbol Ann -> m ()
putTerm id tm tp | debug && trace (show "SqliteCodebase.putTerm " ++ show id ++ " " ++ show tm ++ " " ++ show tp) False = undefined
putTerm (Reference.Id h@(Cv.hash1to2 -> h2) i n') tm tp =
runDB conn $
unlessM
(Ops.objectExistsForHash h2 >>= if debug then \b -> do traceM $ "objectExistsForHash " ++ show h2 ++ " = " ++ show b; pure b else pure)
( withBuffer termBuffer h \be@(BufferEntry size comp missing waiting) -> do
Monad.when debug $ traceM $ "adding to BufferEntry" ++ show be
let size' = Just n'
-- if size was previously set, it's expected to match size'.
case size of
Just n
| n /= n' ->
error $ "targetSize for term " ++ show h ++ " was " ++ show size ++ ", but now " ++ show size'
_ -> pure ()
let comp' = Map.insert i (tm, tp) comp
-- for the component element that's been passed in, add its dependencies to missing'
missingTerms' <-
filterM
(fmap not . Ops.objectExistsForHash . Cv.hash1to2)
[h | Reference.Derived h _i _n <- Set.toList $ Term.termDependencies tm]
missingTypes' <-
filterM (fmap not . Ops.objectExistsForHash . Cv.hash1to2) $
[h | Reference.Derived h _i _n <- Set.toList $ Term.typeDependencies tm]
++ [h | Reference.Derived h _i _n <- Set.toList $ Type.dependencies tp]
let missing' = missing <> Set.fromList (missingTerms' <> missingTypes')
-- notify each of the dependencies that h depends on them.
traverse (addBufferDependent h termBuffer) missingTerms'
traverse (addBufferDependent h declBuffer) missingTypes'
putBuffer termBuffer h (BufferEntry size' comp' missing' waiting)
tryFlushTermBuffer h
)
putBuffer :: (MonadIO m, Show a) => TVar (Map Hash (BufferEntry a)) -> Hash -> BufferEntry a -> m ()
putBuffer tv h e = do
Monad.when debug $ traceM $ "putBuffer " ++ prettyBufferEntry h e
atomically $ modifyTVar tv (Map.insert h e)
withBuffer :: (MonadIO m, Show a) => TVar (Map Hash (BufferEntry a)) -> Hash -> (BufferEntry a -> m b) -> m b
withBuffer tv h f = do
Monad.when debug $ readTVarIO tv >>= \tv -> traceM $ "tv = " ++ show tv
Map.lookup h <$> readTVarIO tv >>= \case
Just e -> do
Monad.when debug $ traceM $ "SqliteCodebase.withBuffer " ++ prettyBufferEntry h e
f e
Nothing -> do
Monad.when debug $ traceM $ "SqliteCodebase.with(new)Buffer " ++ show h
f (BufferEntry Nothing Map.empty Set.empty Set.empty)
removeBuffer :: (MonadIO m, Show a) => TVar (Map Hash (BufferEntry a)) -> Hash -> m ()
removeBuffer _tv h | debug && trace ("removeBuffer " ++ show h) False = undefined
removeBuffer tv h = do
Monad.when debug $ readTVarIO tv >>= \tv -> traceM $ "before delete: " ++ show tv
atomically $ modifyTVar tv (Map.delete h)
Monad.when debug $ readTVarIO tv >>= \tv -> traceM $ "after delete: " ++ show tv
addBufferDependent :: (MonadIO m, Show a) => Hash -> TVar (Map Hash (BufferEntry a)) -> Hash -> m ()
addBufferDependent dependent tv dependency = withBuffer tv dependency \be -> do
putBuffer tv dependency be {beWaitingDependents = Set.insert dependent $ beWaitingDependents be}
tryFlushBuffer ::
(EDB m, Show a) =>
TVar (Map Hash (BufferEntry a)) ->
(H2.Hash -> [a] -> m ()) ->
(Hash -> m ()) ->
Hash ->
m ()
tryFlushBuffer _ _ _ h | debug && trace ("tryFlushBuffer " ++ show h) False = undefined
tryFlushBuffer buf saveComponent tryWaiting h@(Cv.hash1to2 -> h2) =
-- skip if it has already been flushed
unlessM (Ops.objectExistsForHash h2) $ withBuffer buf h try
where
try (BufferEntry size comp (Set.delete h -> missing) waiting) = case size of
Just size -> do
missing' <-
filterM
(fmap not . Ops.objectExistsForHash . Cv.hash1to2)
(toList missing)
Monad.when debug do
traceM $ "tryFlushBuffer.missing' = " ++ show missing'
traceM $ "tryFlushBuffer.size = " ++ show size
traceM $ "tryFlushBuffer.length comp = " ++ show (length comp)
if null missing' && size == fromIntegral (length comp)
then do
saveComponent h2 (toList comp)
removeBuffer buf h
Monad.when debug $ traceM $ "tryFlushBuffer.notify waiting " ++ show waiting
traverse_ tryWaiting waiting
else -- update
putBuffer buf h $
BufferEntry (Just size) comp (Set.fromList missing') waiting
Nothing ->
-- it's never even been added, so there's nothing to do.
pure ()
tryFlushTermBuffer :: EDB m => Hash -> m ()
tryFlushTermBuffer h | debug && trace ("tryFlushTermBuffer " ++ show h) False = undefined
tryFlushTermBuffer h =
tryFlushBuffer
termBuffer
( \h2 ->
void . Ops.saveTermComponent h2
. fmap (first (Cv.term1to2 h) . second Cv.ttype1to2)
)
tryFlushTermBuffer
h
tryFlushDeclBuffer :: EDB m => Hash -> m ()
tryFlushDeclBuffer h | debug && trace ("tryFlushDeclBuffer " ++ show h) False = undefined
tryFlushDeclBuffer h =
tryFlushBuffer
declBuffer
(\h2 -> void . Ops.saveDeclComponent h2 . fmap (Cv.decl1to2 h))
(\h -> tryFlushTermBuffer h >> tryFlushDeclBuffer h)
h
putTypeDeclaration :: MonadIO m => Reference.Id -> Decl Symbol Ann -> m ()
putTypeDeclaration (Reference.Id h@(Cv.hash1to2 -> h2) i n') decl =
runDB conn $
unlessM
(Ops.objectExistsForHash h2)
( withBuffer declBuffer h \(BufferEntry size comp missing waiting) -> do
let size' = Just n'
case size of
Just n
| n /= n' ->
error $ "targetSize for type " ++ show h ++ " was " ++ show size ++ ", but now " ++ show size'
_ -> pure ()
let comp' = Map.insert i decl comp
moreMissing <-
filterM (fmap not . Ops.objectExistsForHash . Cv.hash1to2) $
[h | Reference.Derived h _i _n <- Set.toList $ Decl.declDependencies decl]
let missing' = missing <> Set.fromList moreMissing
traverse (addBufferDependent h declBuffer) moreMissing
putBuffer declBuffer h (BufferEntry size' comp' missing' waiting)
tryFlushDeclBuffer h
)
getRootBranch :: MonadIO m => TVar (Maybe (Q.DataVersion, Branch m)) -> m (Either Codebase1.GetRootBranchError (Branch m))
getRootBranch rootBranchCache =
readTVarIO rootBranchCache >>= \case
Nothing -> forceReload
Just (v, b) -> do
-- check to see if root namespace hash has been externally modified
-- and reload it if necessary
v' <- runDB conn Ops.dataVersion
if v == v' then pure (Right b) else do
newRootHash <- runDB conn Ops.loadRootCausalHash
if Branch.headHash b == Cv.branchHash2to1 newRootHash
then pure (Right b)
else do
traceM $ "database was externally modified (" ++ show v ++ " -> " ++ show v' ++ ")"
forceReload
where
forceReload = time "Get root branch" do
b <- fmap (Either.mapLeft err)
. runExceptT
. flip runReaderT conn
. fmap (Branch.transform (runDB conn))
$ Cv.causalbranch2to1 getCycleLen getDeclType =<< Ops.loadRootCausal
v <- runDB conn Ops.dataVersion
for_ b (atomically . writeTVar rootBranchCache . Just . (v,))
pure b
err :: Ops.Error -> Codebase1.GetRootBranchError
err = \case
Ops.DatabaseIntegrityError Q.NoNamespaceRoot ->
Codebase1.NoRootBranch
Ops.DecodeError (Ops.ErrBranch oId) _bytes _msg ->
Codebase1.CouldntParseRootBranch $
"Couldn't decode " ++ show oId ++ ": " ++ _msg
Ops.ExpectedBranch ch _bh ->
Codebase1.CouldntLoadRootBranch $ Cv.causalHash2to1 ch
e -> error $ show e
putRootBranch :: MonadIO m => TVar (Maybe (Q.DataVersion, Branch m)) -> Branch m -> m ()
putRootBranch rootBranchCache branch1 = do
-- todo: check to see if root namespace hash has been externally modified
-- and do something (merge?) it if necessary. But for now, we just overwrite it.
runDB conn
. void
. Ops.saveRootBranch
. Cv.causalbranch1to2
$ Branch.transform (lift . lift) branch1
atomically $ modifyTVar rootBranchCache (fmap . second $ const branch1)
rootBranchUpdates :: MonadIO m => TVar (Maybe (Q.DataVersion, a)) -> m (IO (), IO (Set Branch.Hash))
rootBranchUpdates _rootBranchCache = do
-- branchHeadChanges <- TQueue.newIO
-- (cancelWatch, watcher) <- Watch.watchDirectory' (v2dir root)
-- watcher1 <-
-- liftIO . forkIO
-- $ forever
-- $ do
-- -- void ignores the name and time of the changed file,
-- -- and assume 'unison.sqlite3' has changed
-- (filename, time) <- watcher
-- traceM $ "SqliteCodebase.watcher " ++ show (filename, time)
-- readTVarIO rootBranchCache >>= \case
-- Nothing -> pure ()
-- Just (v, _) -> do
-- -- this use of `conn` in a separate thread may be problematic.
-- -- hopefully sqlite will produce an obvious error message if it is.
-- v' <- runDB conn Ops.dataVersion
-- if v /= v' then
-- atomically
-- . TQueue.enqueue branchHeadChanges =<< runDB conn Ops.loadRootCausalHash
-- else pure ()
-- -- case hashFromFilePath filePath of
-- -- Nothing -> failWith $ CantParseBranchHead filePath
-- -- Just h ->
-- -- atomically . TQueue.enqueue branchHeadChanges $ Branch.Hash h
-- -- smooth out intermediate queue
-- pure
-- ( cancelWatch >> killThread watcher1
-- , Set.fromList <$> Watch.collectUntilPause branchHeadChanges 400000
-- )
pure (cleanup, liftIO newRootsDiscovered)
where
newRootsDiscovered = do
Control.Concurrent.threadDelay maxBound -- hold off on returning
pure mempty -- returning nothing
cleanup = pure ()
-- if this blows up on cromulent hashes, then switch from `hashToHashId`
-- to one that returns Maybe.
getBranchForHash :: MonadIO m => Branch.Hash -> m (Maybe (Branch m))
getBranchForHash h = runDB conn do
Ops.loadCausalBranchByCausalHash (Cv.branchHash1to2 h) >>= \case
Just b ->
pure . Just . Branch.transform (runDB conn)
=<< Cv.causalbranch2to1 getCycleLen getDeclType b
Nothing -> pure Nothing
putBranch :: MonadIO m => Branch m -> m ()
putBranch = runDB conn . putBranch'
isCausalHash :: MonadIO m => Branch.Hash -> m Bool
isCausalHash = runDB conn . isCausalHash'
getPatch :: MonadIO m => Branch.EditHash -> m (Maybe Patch)
getPatch h =
runDB conn . runMaybeT $
MaybeT (Ops.primaryHashToMaybePatchObjectId (Cv.patchHash1to2 h))
>>= Ops.loadPatchById
>>= Cv.patch2to1 getCycleLen
putPatch :: MonadIO m => Branch.EditHash -> Patch -> m ()
putPatch h p =
runDB conn . void $
Ops.savePatch (Cv.patchHash1to2 h) (Cv.patch1to2 p)
patchExists :: MonadIO m => Branch.EditHash -> m Bool
patchExists = runDB conn . patchExists'
dependentsImpl :: MonadIO m => Reference -> m (Set Reference.Id)
dependentsImpl r =
runDB conn $
Set.traverse (Cv.referenceid2to1 (getCycleLen "dependentsImpl"))
=<< Ops.dependents (Cv.reference1to2 r)
syncFromDirectory :: MonadIO m => Codebase1.CodebasePath -> SyncMode -> Branch m -> m ()
syncFromDirectory srcRoot _syncMode b =
flip State.evalStateT emptySyncProgressState $ do
srcConn <- unsafeGetConnection (debugName ++ ".sync.src") srcRoot
syncInternal syncProgress srcConn conn $ Branch.transform lift b
syncToDirectory :: MonadIO m => Codebase1.CodebasePath -> SyncMode -> Branch m -> m ()
syncToDirectory destRoot _syncMode b =
flip State.evalStateT emptySyncProgressState $ do
initSchemaIfNotExist destRoot
destConn <- unsafeGetConnection (debugName ++ ".sync.dest") destRoot
syncInternal syncProgress conn destConn $ Branch.transform lift b
watches :: MonadIO m => UF.WatchKind -> m [Reference.Id]
watches w =
runDB conn $
Ops.listWatches (Cv.watchKind1to2 w)
>>= traverse (Cv.referenceid2to1 (getCycleLen "watches"))
getWatch :: MonadIO m => UF.WatchKind -> Reference.Id -> m (Maybe (Term Symbol Ann))
getWatch k r@(Reference.Id h _i _n)
| elem k standardWatchKinds =
runDB' conn $
Ops.loadWatch (Cv.watchKind1to2 k) (Cv.referenceid1to2 r)
>>= Cv.term2to1 h (getCycleLen "getWatch") getDeclType
getWatch _unknownKind _ = pure Nothing
standardWatchKinds = [UF.RegularWatch, UF.TestWatch]
putWatch :: MonadIO m => UF.WatchKind -> Reference.Id -> Term Symbol Ann -> m ()
putWatch k r@(Reference.Id h _i _n) tm
| elem k standardWatchKinds =
runDB conn $
Ops.saveWatch
(Cv.watchKind1to2 k)
(Cv.referenceid1to2 r)
(Cv.term1to2 h tm)
putWatch _unknownKind _ _ = pure ()
clearWatches :: MonadIO m => m ()
clearWatches = runDB conn Ops.clearWatches
getReflog :: MonadIO m => m [Reflog.Entry]
getReflog =
liftIO $
( do
contents <- TextIO.readFile (reflogPath root)
let lines = Text.lines contents
let entries = parseEntry <$> lines
pure entries
)
`catchIO` const (pure [])
where
parseEntry t = fromMaybe (err t) (Reflog.fromText t)
err t =
error $
"I couldn't understand this line in " ++ reflogPath root ++ "\n\n"
++ Text.unpack t
appendReflog :: MonadIO m => Text -> Branch m -> Branch m -> m ()
appendReflog reason old new =
liftIO $ TextIO.appendFile (reflogPath root) (t <> "\n")
where
t = Reflog.toText $ Reflog.Entry (Branch.headHash old) (Branch.headHash new) reason
reflogPath :: CodebasePath -> FilePath
reflogPath root = root </> "reflog"
termsOfTypeImpl :: MonadIO m => Reference -> m (Set Referent.Id)
termsOfTypeImpl r =
runDB conn $
Ops.termsHavingType (Cv.reference1to2 r)
>>= Set.traverse (Cv.referentid2to1 (getCycleLen "termsOfTypeImpl") getDeclType)
termsMentioningTypeImpl :: MonadIO m => Reference -> m (Set Referent.Id)
termsMentioningTypeImpl r =
runDB conn $
Ops.termsMentioningType (Cv.reference1to2 r)
>>= Set.traverse (Cv.referentid2to1 (getCycleLen "termsMentioningTypeImpl") getDeclType)
hashLength :: Applicative m => m Int
hashLength = pure 10
branchHashLength :: Applicative m => m Int
branchHashLength = pure 10
defnReferencesByPrefix :: MonadIO m => OT.ObjectType -> ShortHash -> m (Set Reference.Id)
defnReferencesByPrefix _ (ShortHash.Builtin _) = pure mempty
defnReferencesByPrefix ot (ShortHash.ShortHash prefix (fmap Cv.shortHashSuffix1to2 -> cycle) _cid) =
Monoid.fromMaybe <$> runDB' conn do
refs <- do
Ops.componentReferencesByPrefix ot prefix cycle
>>= traverse (C.Reference.idH Ops.loadHashByObjectId)
>>= pure . Set.fromList
Set.fromList <$> traverse (Cv.referenceid2to1 (getCycleLen "defnReferencesByPrefix")) (Set.toList refs)
termReferencesByPrefix :: MonadIO m => ShortHash -> m (Set Reference.Id)
termReferencesByPrefix = defnReferencesByPrefix OT.TermComponent
declReferencesByPrefix :: MonadIO m => ShortHash -> m (Set Reference.Id)
declReferencesByPrefix = defnReferencesByPrefix OT.DeclComponent
referentsByPrefix :: MonadIO m => ShortHash -> m (Set Referent.Id)
referentsByPrefix SH.Builtin {} = pure mempty
referentsByPrefix (SH.ShortHash prefix (fmap Cv.shortHashSuffix1to2 -> cycle) cid) = runDB conn do
termReferents <-
Ops.termReferentsByPrefix prefix cycle
>>= traverse (Cv.referentid2to1 (getCycleLen "referentsByPrefix") getDeclType)
declReferents' <- Ops.declReferentsByPrefix prefix cycle (read . Text.unpack <$> cid)
let declReferents =
[ Referent.Con' (Reference.Id (Cv.hash2to1 h) pos len) (fromIntegral cid) (Cv.decltype2to1 ct)
| (h, pos, len, ct, cids) <- declReferents',
cid <- cids
]
pure . Set.fromList $ termReferents <> declReferents
branchHashesByPrefix :: MonadIO m => ShortBranchHash -> m (Set Branch.Hash)
branchHashesByPrefix sh = runDB conn do
-- given that a Branch is shallow, it's really `CausalHash` that you'd
-- refer to to specify a full namespace w/ history.
-- but do we want to be able to refer to a namespace without its history?
cs <- Ops.causalHashesByPrefix (Cv.sbh1to2 sh)
pure $ Set.map (Causal.RawHash . Cv.hash2to1 . unCausalHash) cs
sqlLca :: MonadIO m => Branch.Hash -> Branch.Hash -> m (Maybe Branch.Hash)
sqlLca h1 h2 = liftIO $ Control.Exception.bracket open close \(c1, c2) ->
runDB conn
. (fmap . fmap) Cv.causalHash2to1
$ Ops.lca (Cv.causalHash1to2 h1) (Cv.causalHash1to2 h2) c1 c2
where
open = (,) <$> unsafeGetConnection (debugName ++ ".lca.left") root
<*> unsafeGetConnection (debugName ++ ".lca.left") root
close (c1, c2) = shutdownConnection c1 *> shutdownConnection c2
let finalizer :: MonadIO m => m ()
finalizer = do
shutdownConnection conn
decls <- readTVarIO declBuffer
terms <- readTVarIO termBuffer
let printBuffer header b =
liftIO
if b /= mempty
then putStrLn header >> putStrLn "" >> print b
else pure ()
printBuffer "Decls:" decls
printBuffer "Terms:" terms
pure . Right $
( finalizer,
let
code = Codebase1.Codebase
(Cache.applyDefined termCache getTerm)
(Cache.applyDefined typeOfTermCache getTypeOfTermImpl)
(Cache.applyDefined declCache getTypeDeclaration)
putTerm
putTypeDeclaration
(getRootBranch rootBranchCache)
(putRootBranch rootBranchCache)
(rootBranchUpdates rootBranchCache)
getBranchForHash
putBranch
isCausalHash
getPatch
putPatch
patchExists
dependentsImpl
syncFromDirectory
syncToDirectory
viewRemoteBranch'
(\b r _s -> pushGitRootBranch conn b r)
watches
getWatch
putWatch
clearWatches
getReflog
appendReflog
termsOfTypeImpl
termsMentioningTypeImpl
hashLength
termReferencesByPrefix
declReferencesByPrefix
referentsByPrefix
branchHashLength
branchHashesByPrefix
(Just sqlLca)
(Just \l r -> runDB conn $ fromJust <$> before l r)
in code
)
v -> shutdownConnection conn $> Left v
-- well one or the other. :zany_face: the thinking being that they wouldn't hash-collide
termExists', declExists' :: MonadIO m => Hash -> ReaderT Connection (ExceptT Ops.Error m) Bool
termExists' = fmap isJust . Ops.primaryHashToMaybeObjectId . Cv.hash1to2
declExists' = termExists'
patchExists' :: MonadIO m => Branch.EditHash -> ReaderT Connection (ExceptT Ops.Error m) Bool
patchExists' h = fmap isJust $ Ops.primaryHashToMaybePatchObjectId (Cv.patchHash1to2 h)
putBranch' :: MonadIO m => Branch m -> ReaderT Connection (ExceptT Ops.Error m) ()
putBranch' branch1 =
void . Ops.saveBranch . Cv.causalbranch1to2 $
Branch.transform (lift . lift) branch1
isCausalHash' :: MonadIO m => Branch.Hash -> ReaderT Connection (ExceptT Ops.Error m) Bool
isCausalHash' (Causal.RawHash h) =
Q.loadHashIdByHash (Cv.hash1to2 h) >>= \case
Nothing -> pure False
Just hId -> Q.isCausalHash hId
before :: MonadIO m => Branch.Hash -> Branch.Hash -> ReaderT Connection m (Maybe Bool)
before h1 h2 =
Ops.before (Cv.causalHash1to2 h1) (Cv.causalHash1to2 h2)
syncInternal ::
forall m.
MonadIO m =>
Sync.Progress m Sync22.Entity ->
Connection ->
Connection ->
Branch m ->
m ()
syncInternal progress srcConn destConn b = time "syncInternal" do
runDB srcConn $ Q.savepoint "sync"
runDB destConn $ Q.savepoint "sync"
result <- runExceptT do
let syncEnv = Sync22.Env srcConn destConn (16 * 1024 * 1024)
-- we want to use sync22 wherever possible
-- so for each branch, we'll check if it exists in the destination branch
-- or if it exists in the source branch, then we can sync22 it
-- oh god but we have to figure out the dbid
-- if it doesn't exist in the dest or source branch,
-- then just use putBranch to the dest
let se :: forall m a. Functor m => (ExceptT Sync22.Error m a -> ExceptT SyncEphemeral.Error m a)
se = Except.withExceptT SyncEphemeral.Sync22Error
let r :: forall m a. (ReaderT Sync22.Env m a -> m a)
r = flip runReaderT syncEnv
processBranches ::
forall m.
MonadIO m =>
Sync.Sync (ReaderT Sync22.Env (ExceptT Sync22.Error m)) Sync22.Entity ->
Sync.Progress (ReaderT Sync22.Env (ExceptT Sync22.Error m)) Sync22.Entity ->
[Entity m] ->
ExceptT Sync22.Error m ()
processBranches _ _ [] = pure ()
processBranches sync progress (b0@(B h mb) : rest) = do
when debugProcessBranches do
traceM $ "processBranches " ++ show b0
traceM $ " queue: " ++ show rest
ifM @(ExceptT Sync22.Error m)
(lift . runDB destConn $ isCausalHash' h)
do
when debugProcessBranches $ traceM $ " " ++ show b0 ++ " already exists in dest db"
processBranches sync progress rest
do
when debugProcessBranches $ traceM $ " " ++ show b0 ++ " doesn't exist in dest db"
let h2 = CausalHash . Cv.hash1to2 $ Causal.unRawHash h
lift (flip runReaderT srcConn (Q.loadCausalHashIdByCausalHash h2)) >>= \case
Just chId -> do
when debugProcessBranches $ traceM $ " " ++ show b0 ++ " exists in source db, so delegating to direct sync"
r $ Sync.sync' sync progress [Sync22.C chId]
processBranches sync progress rest
Nothing ->
lift mb >>= \b -> do
when debugProcessBranches $ traceM $ " " ++ show b0 ++ " doesn't exist in either db, so delegating to Codebase.putBranch"
let (branchDeps, BD.to' -> BD.Dependencies' es ts ds) = BD.fromBranch b
when debugProcessBranches do
traceM $ " branchDeps: " ++ show (fst <$> branchDeps)
traceM $ " terms: " ++ show ts
traceM $ " decls: " ++ show ds
traceM $ " edits: " ++ show es
(cs, es, ts, ds) <- lift $ runDB destConn do
cs <- filterM (fmap not . isCausalHash' . fst) branchDeps
es <- filterM (fmap not . patchExists') es
ts <- filterM (fmap not . termExists') ts
ds <- filterM (fmap not . declExists') ds
pure (cs, es, ts, ds)
if null cs && null es && null ts && null ds
then do
lift . runDB destConn $ putBranch' b
processBranches @m sync progress rest
else do
let bs = map (uncurry B) cs
os = map O (es <> ts <> ds)
processBranches @m sync progress (os ++ bs ++ b0 : rest)
processBranches sync progress (O h : rest) = do
when debugProcessBranches $ traceM $ "processBranches O " ++ take 10 (show h)
(runExceptT $ flip runReaderT srcConn (Q.expectHashIdByHash (Cv.hash1to2 h) >>= Q.expectObjectIdForAnyHashId)) >>= \case
Left e -> error $ show e
Right oId -> do
r $ Sync.sync' sync progress [Sync22.O oId]
processBranches sync progress rest
sync <- se . r $ Sync22.sync22
let progress' = Sync.transformProgress (lift . lift) progress
bHash = Branch.headHash b
se $ time "SyncInternal.processBranches" $ processBranches sync progress' [B bHash (pure b)]
testWatchRefs <- time "SyncInternal enumerate testWatches" $
lift . fmap concat $ for [WK.TestWatch] \wk ->
fmap (Sync22.W wk) <$> flip runReaderT srcConn (Q.loadWatchesByWatchKind wk)
se . r $ Sync.sync sync progress' testWatchRefs
let onSuccess a = runDB destConn (Q.release "sync") *> pure a
onFailure e = do
if debugCommitFailedTransaction
then runDB destConn (Q.release "sync")
else runDB destConn (Q.rollbackRelease "sync")
error (show e)
runDB srcConn $ Q.rollbackRelease "sync" -- (we don't write to the src anyway)
either onFailure onSuccess result
runDB' :: MonadIO m => Connection -> MaybeT (ReaderT Connection (ExceptT Ops.Error m)) a -> m (Maybe a)
runDB' conn = runDB conn . runMaybeT
runDB :: MonadIO m => Connection -> ReaderT Connection (ExceptT Ops.Error m) a -> m a
runDB conn = (runExceptT >=> err) . flip runReaderT conn
where
err = \case Left err -> error $ show err; Right a -> pure a
data Entity m
= B Branch.Hash (m (Branch m))
| O Hash
instance Show (Entity m) where
show (B h _) = "B " ++ take 10 (show h)
show (O h) = "O " ++ take 10 (show h)
data SyncProgressState = SyncProgressState
{ _needEntities :: Maybe (Set Sync22.Entity),
_doneEntities :: Either Int (Set Sync22.Entity),
_warnEntities :: Either Int (Set Sync22.Entity)
}
emptySyncProgressState :: SyncProgressState
emptySyncProgressState = SyncProgressState (Just mempty) (Right mempty) (Right mempty)
syncProgress :: MonadState SyncProgressState m => MonadIO m => Sync.Progress m Sync22.Entity
syncProgress = Sync.Progress need done warn allDone
where
quiet = False
maxTrackedHashCount = 1024 * 1024
size :: SyncProgressState -> Int
size = \case
SyncProgressState Nothing (Left i) (Left j) -> i + j
SyncProgressState (Just need) (Right done) (Right warn) -> Set.size need + Set.size done + Set.size warn
SyncProgressState _ _ _ -> undefined
need, done, warn :: (MonadState SyncProgressState m, MonadIO m) => Sync22.Entity -> m ()
need h = do
unless quiet $ Monad.whenM (State.gets size <&> (== 0)) $ liftIO $ putStr "\n"
State.get >>= \case
SyncProgressState Nothing Left {} Left {} -> pure ()
SyncProgressState (Just need) (Right done) (Right warn) ->
if Set.size need + Set.size done + Set.size warn > maxTrackedHashCount
then State.put $ SyncProgressState Nothing (Left $ Set.size done) (Left $ Set.size warn)
else
if Set.member h done || Set.member h warn
then pure ()
else State.put $ SyncProgressState (Just $ Set.insert h need) (Right done) (Right warn)
SyncProgressState _ _ _ -> undefined
unless quiet printSynced
done h = do
unless quiet $ Monad.whenM (State.gets size <&> (== 0)) $ liftIO $ putStr "\n"
State.get >>= \case
SyncProgressState Nothing (Left done) warn ->
State.put $ SyncProgressState Nothing (Left (done + 1)) warn
SyncProgressState (Just need) (Right done) warn ->
State.put $ SyncProgressState (Just $ Set.delete h need) (Right $ Set.insert h done) warn
SyncProgressState _ _ _ -> undefined
unless quiet printSynced
warn h = do
unless quiet $ Monad.whenM (State.gets size <&> (== 0)) $ liftIO $ putStr "\n"
State.get >>= \case
SyncProgressState Nothing done (Left warn) ->
State.put $ SyncProgressState Nothing done (Left $ warn + 1)
SyncProgressState (Just need) done (Right warn) ->
State.put $ SyncProgressState (Just $ Set.delete h need) done (Right $ Set.insert h warn)
SyncProgressState _ _ _ -> undefined
unless quiet printSynced
allDone = do
State.get >>= liftIO . putStrLn . renderState (" " ++ "Done syncing ")
printSynced :: (MonadState SyncProgressState m, MonadIO m) => m ()
printSynced = State.get >>= \s -> liftIO $
finally
do ANSI.hideCursor; putStr . renderState (" " ++ "Synced ") $ s
ANSI.showCursor
renderState :: String -> SyncProgressState -> String
renderState prefix = \case
SyncProgressState Nothing (Left done) (Left warn) ->
"\r" ++ prefix ++ show done ++ " entities" ++ if warn > 0 then " with " ++ show warn ++ " warnings." else "."
SyncProgressState (Just _need) (Right done) (Right warn) ->
"\r" ++ prefix ++ show (Set.size done + Set.size warn)
++ " entities"
++ if Set.size warn > 0
then " with " ++ show (Set.size warn) ++ " warnings."
else "."
SyncProgressState need done warn ->
"invalid SyncProgressState "
++ show (fmap v need, bimap id v done, bimap id v warn)
where
v = const ()
viewRemoteBranch' ::
forall m.
(MonadIO m, MonadCatch m) =>
ReadRemoteNamespace ->
m (Either GitError (m (), Branch m, CodebasePath))
viewRemoteBranch' (repo, sbh, path) = runExceptT do
-- set up the cache dir
remotePath <- time "Git fetch" $ pullBranch repo
ifM
(codebaseExists remotePath)
do
lift (sqliteCodebase "viewRemoteBranch.gitCache" remotePath) >>= \case
Left sv -> ExceptT . pure . Left $ GitError.UnrecognizedSchemaVersion repo remotePath sv
Right (closeCodebase, codebase) -> do
-- try to load the requested branch from it
branch <- time "Git fetch (sbh)" $ case sbh of
-- no sub-branch was specified, so use the root.
Nothing ->
lift (time "Get remote root branch" $ Codebase1.getRootBranch codebase) >>= \case
-- this NoRootBranch case should probably be an error too.
Left Codebase1.NoRootBranch -> pure Branch.empty
Left (Codebase1.CouldntLoadRootBranch h) ->
throwError $ GitError.CouldntLoadRootBranch repo h
Left (Codebase1.CouldntParseRootBranch s) ->
throwError $ GitError.CouldntParseRootBranch repo s
Right b -> pure b
-- load from a specific `ShortBranchHash`
Just sbh -> do
branchCompletions <- lift $ Codebase1.branchHashesByPrefix codebase sbh
case toList branchCompletions of
[] -> throwError $ GitError.NoRemoteNamespaceWithHash repo sbh
[h] ->
lift (Codebase1.getBranchForHash codebase h) >>= \case
Just b -> pure b
Nothing -> throwError $ GitError.NoRemoteNamespaceWithHash repo sbh
_ -> throwError $ GitError.RemoteNamespaceHashAmbiguous repo sbh branchCompletions
pure (closeCodebase, Branch.getAt' path branch, remotePath)
-- else there's no initialized codebase at this repo; we pretend there's an empty one.
-- I'm thinking we should probably return an error value instead.
(pure (pure (), Branch.empty, remotePath))
-- Given a branch that is "after" the existing root of a given git repo,
-- stage and push the branch (as the new root) + dependencies to the repo.
pushGitRootBranch ::
(MonadIO m, MonadCatch m) =>
Connection ->
Branch m ->
WriteRepo ->
m (Either GitError ())
pushGitRootBranch srcConn branch repo = runExceptT @GitError do
-- pull the remote repo to the staging directory
-- open a connection to the staging codebase
-- create a savepoint on the staging codebase
-- sync the branch to the staging codebase using `syncInternal`, which probably needs to be passed in instead of `syncToDirectory`
-- do a `before` check on the staging codebase
-- if it passes, then release the savepoint (commit it), clean up, and git-push the result
-- if it fails, rollback to the savepoint and clean up.
-- set up the cache dir
remotePath <- time "Git fetch" $ pullBranch (writeToRead repo)
destConn <- openOrCreateCodebaseConnection "push.dest" remotePath
flip runReaderT destConn $ Q.savepoint "push"
lift . flip State.execStateT emptySyncProgressState $
syncInternal syncProgress srcConn destConn (Branch.transform lift branch)
flip runReaderT destConn do
let newRootHash = Branch.headHash branch
-- the call to runDB "handles" the possible DB error by bombing
(fmap . fmap) Cv.branchHash2to1 (runDB destConn Ops.loadMaybeRootCausalHash) >>= \case
Nothing -> do
setRepoRoot newRootHash
Q.release "push"
Just oldRootHash -> do
before oldRootHash newRootHash >>= \case
Nothing ->
error $
"I couldn't find the hash " ++ show newRootHash
++ " that I just synced to the cached copy of "
++ repoString
++ " in "
++ show remotePath
++ "."
Just False -> do
Q.rollbackRelease "push"
throwError $ GitError.PushDestinationHasNewStuff repo
Just True -> do
setRepoRoot newRootHash
Q.release "push"
Q.setJournalMode JournalMode.DELETE
liftIO do
shutdownConnection destConn
void $ push remotePath repo
where
repoString = Text.unpack $ printWriteRepo repo
setRepoRoot :: Q.DB m => Branch.Hash -> m ()
setRepoRoot h = do
let h2 = Cv.causalHash1to2 h
err = error $ "Called SqliteCodebase.setNamespaceRoot on unknown causal hash " ++ show h2
chId <- fromMaybe err <$> Q.loadCausalHashIdByCausalHash h2
Q.setNamespaceRoot chId
-- This function makes sure that the result of git status is valid.
-- Valid lines are any of:
--
-- ?? .unison/v2/unison.sqlite3 (initial commit to an empty repo)
-- M .unison/v2/unison.sqlite3 (updating an existing repo)
-- D .unison/v2/unison.sqlite3-wal (cleaning up the WAL from before bugfix)
-- D .unison/v2/unison.sqlite3-shm (ditto)
--
-- Invalid lines are like:
--
-- ?? .unison/v2/unison.sqlite3-wal
--
-- Which will only happen if the write-ahead log hasn't been
-- fully folded into the unison.sqlite3 file.
--
-- Returns `Just (hasDeleteWal, hasDeleteShm)` on success,
-- `Nothing` otherwise. hasDeleteWal means there's the line:
-- D .unison/v2/unison.sqlite3-wal
-- and hasDeleteShm is `True` if there's the line:
-- D .unison/v2/unison.sqlite3-shm
--
parseStatus :: Text -> Maybe (Bool, Bool)
parseStatus status =
if all okLine statusLines then Just (hasDeleteWal, hasDeleteShm)
else Nothing
where
statusLines = Text.unpack <$> Text.lines status
t = dropWhile Char.isSpace
okLine (t -> '?' : '?' : (t -> p)) | p == codebasePath = True
okLine (t -> 'M' : (t -> p)) | p == codebasePath = True
okLine line = isWalDelete line || isShmDelete line
isWalDelete (t -> 'D' : (t -> p)) | p == codebasePath ++ "-wal" = True
isWalDelete _ = False
isShmDelete (t -> 'D' : (t -> p)) | p == codebasePath ++ "-wal" = True
isShmDelete _ = False
hasDeleteWal = any isWalDelete statusLines
hasDeleteShm = any isShmDelete statusLines
-- Commit our changes
push :: CodebasePath -> WriteRepo -> IO Bool -- withIOError needs IO
push remotePath (WriteGitRepo url) = time "SqliteCodebase.pushGitRootBranch.push" $ do
-- has anything changed?
-- note: -uall recursively shows status for all files in untracked directories
-- we want this so that we see
-- `?? .unison/v2/unison.sqlite3` and not
-- `?? .unison/`
status <- gitTextIn remotePath ["status", "--short", "-uall"]
if Text.null status
then pure False
else case parseStatus status of
Nothing ->
error $ "An error occurred during push.\n"
<> "I was expecting only to see .unison/v2/unison.sqlite3 modified, but saw:\n\n"
<> Text.unpack status <> "\n\n"
<> "Please visit https://github.com/unisonweb/unison/issues/2063\n"
<> "and add any more details about how you encountered this!\n"
Just (hasDeleteWal, hasDeleteShm) -> do
-- Only stage files we're expecting; don't `git add --all .`
-- which could accidentally commit some garbage
gitIn remotePath ["add", ".unison/v2/unison.sqlite3"]
when hasDeleteWal $ gitIn remotePath ["rm", ".unison/v2/unison.sqlite3-wal"]
when hasDeleteShm $ gitIn remotePath ["rm", ".unison/v2/unison.sqlite3-shm"]
gitIn
remotePath
["commit", "-q", "-m", "Sync branch " <> Text.pack (show $ Branch.headHash branch)]
-- Push our changes to the repo
gitIn remotePath ["push", "--quiet", url]
pure True
| unisonweb/platform | parser-typechecker/src/Unison/Codebase/SqliteCodebase.hs | mit | 55,182 | 0 | 38 | 16,518 | 14,482 | 7,218 | 7,264 | -1 | -1 |
-- | Commit version.
-- Adapted from Apia.Utils.CommitVersion.hs
-- http://github.com/asr/apia.
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UnicodeSyntax #-}
-- The constructor @versionTagsq (see GHC ticket #2496) is deprecated
-- (at least in GHC 8.0.1). See Issue #83.
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
module Athena.Utils.CommitVersion ( getVersion ) where
------------------------------------------------------------------------------
import Control.Exception ( IOException, try )
import Data.Version ( Version ( versionTags ) )
import System.Exit ( ExitCode ( ExitSuccess ) )
import System.Process ( readProcessWithExitCode )
------------------------------------------------------------------------------
-- | If inside a `git` repository, then @'getVersion' x@ will return
-- @x@ plus the hash of the top commit used for
-- compilation. Otherwise, only @x@ will be returned.
getVersion ∷ Version → IO Version
getVersion version = do
commit ∷ Maybe String ← commitInfo
case commit of
Nothing → return version
Just rev → return $ gitVersion version rev
tryIO ∷ IO a → IO (Either IOException a)
tryIO = try
commitInfo ∷ IO (Maybe String)
commitInfo = do
res ← tryIO $
readProcessWithExitCode "git" ["log", "--format=%h", "-n", "1"] ""
case res of
Right (ExitSuccess, hash, _) → do
(_, _, _) ← readProcessWithExitCode "git" ["diff", "--quiet"] ""
return $ Just (init hash)
_ → return Nothing
gitVersion ∷ Version → String → Version
gitVersion version hash = version { versionTags = [take 7 hash] }
| jonaprieto/athena | src/Athena/Utils/CommitVersion.hs | mit | 1,626 | 0 | 15 | 285 | 339 | 185 | 154 | 27 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Describes Rowling values, i.e., the entities which are produced by
-- evaluating expressions, and passed as input to the evaluator.
module Language.Rowling.Definitions.Values where
import Data.Aeson (FromJSON(..), ToJSON(..), (.=), object)
import qualified Data.Aeson as Aeson
import Data.ContextStack
import qualified Data.HashMap.Strict as H
import Data.Scientific (isInteger, toRealFloat, fromFloatDigits)
import qualified GHC.Exts as GHC
import Language.Rowling.Common
import Language.Rowling.Definitions.Expressions
-- | The evaluated form of an `Expr`.
data Value = VInt !Integer -- ^ An integer.
| VFloat !Double -- ^ A floating-point number.
| VString !Text -- ^ A string.
| VBool !Bool -- ^ A boolean.
| VArray !(Vector Value) -- ^ An array of values.
| VTagged !Name !(Vector Value)
-- ^ A tagged union, like `Either` or `List`.
| VMaybe !(Maybe Value)
-- ^ A maybe (using the Haskell type for efficiency)
| VBuiltin !Builtin -- ^ A builtin function.
| VRecord !(Record Value) -- ^ An instantiated Record.
| VClosure !(Record Value) !Pattern !Expr -- ^ A closure.
deriving (Show, Eq)
-- | Looks up a field in a record. If the field doesn't exist, or the value
-- isn't a record, an IO exception will be thrown.
deref :: Name -> Value -> Value
deref name (VRecord fields) = case H.lookup name fields of
Nothing -> error $ "No field " <> show name
Just val -> val
deref _ _ = error "Not a record value"
instance Render Value
-- | The default value is an empty record, akin to @()@.
instance Default Value where
def = VRecord mempty
-- | Makes creating string values more convenient.
instance IsString Value where
fromString = VString . fromString
-- | Array values are lists, that contain values.
instance IsList Value where
type Item Value = Value
fromList = VArray . GHC.fromList
toList (VArray vs) = GHC.toList vs
toList _ = error "Not a list value"
-- | Values can be read out of JSON. Of course, closures and builtins
-- can't be represented.
instance FromJSON Value where
parseJSON (Aeson.Object v) = VRecord <$> mapM parseJSON v
parseJSON (Aeson.Array arr) = VArray <$> mapM parseJSON arr
parseJSON (Aeson.String s) = return $ VString s
parseJSON (Aeson.Bool b) = return $ VBool b
parseJSON (Aeson.Number n)
| isInteger n = return $ VInt (floor n)
| otherwise = return $ VFloat $ toRealFloat n
parseJSON _ = mzero
-- | Most values have JSON representations. Where they don't, it's an error
-- to try to serialize them to JSON.
instance ToJSON Value where
toJSON (VInt i) = Aeson.Number $ fromIntegral i
toJSON (VFloat f) = Aeson.Number $ fromFloatDigits f
toJSON (VString txt) = Aeson.String txt
toJSON (VBool b) = Aeson.Bool b
toJSON (VArray arr) = Aeson.Array $ map toJSON arr
toJSON (VMaybe Nothing) = object ["@constructor" .= Aeson.String "None"]
toJSON (VMaybe (Just v)) = object [
"@constructor" .= Aeson.String "Some",
"@values" .= Aeson.Array [toJSON v]
]
toJSON (VTagged name vals) = object ["@constructor" .= name,
"@values" .= map toJSON vals]
toJSON (VRecord rec) = Aeson.Object $ map toJSON rec
toJSON v = errorC ["Can't serialize '", render v, "' to JSON"]
-- | Matches a pattern against a value and either fails, or returns a map of
-- name bindings. For example, matching the pattern @Just x@ against the value
-- @VTagged "Just" (VInt 1)@ would return @[("x", VInt 1)]@. Matching the
-- same pattern against @VFloat 2.3@ would return @Nothing@.
patternMatch :: Pattern -> Value -> Maybe (Record Value)
patternMatch p v = case (p, v) of
-- Primitive literals just match if equal. (Constructors are literals).
(Int n, VInt vn) | n == vn -> Just mempty
(Float n, VFloat vn) | n == vn -> Just mempty
(String (Plain s), VString vs) | s == vs -> Just mempty
-- True and false are constructors, but use Haskell bools
(Constructor "True", VBool True) -> Just mempty
(Constructor "False", VBool False) -> Just mempty
(Constructor "None", VMaybe Nothing) -> Just mempty
(Apply (Constructor "Some") p, VMaybe (Just v)) -> patternMatch p v
-- A variable can match with anything.
(Variable name, v) -> Just [(name, v)]
-- With a list expression, it matches if and only if all of them match.
(List ps, VArray vs) -> matchVector ps vs
(Record precord, VRecord vrecord) -> matchRecord precord vrecord
-- For a compound expression, dive into it (see below).
(compoundExpr, VTagged n' vs) -> case dive compoundExpr of
Just (n, ps) | n == n' -> matchVector (fromList ps) vs
otherwise -> Nothing
-- Anything else is not a match.
otherwise -> Nothing
where
matchRecord precord vrecord = loop mempty $ H.toList precord where
loop bindings [] = Just bindings
loop bindings ((key, pattern):rest) = case lookup key vrecord of
-- Key doesn't exist, pattern match fails.
Nothing -> Nothing
Just val -> case patternMatch pattern val of
-- Value doesn't pattern match with pattern, no match.
Nothing -> Nothing
Just bindings' -> loop (bindings' <> bindings) rest
matchVector ps vs = case length ps == length vs of
True -> concat <$> mapM (uncurry patternMatch) (zip ps vs)
False -> Nothing
-- "Dives" into a pattern and grabs the constructor name and patterns.
-- Note that it's only going to return a @Just@ value if the "left most"
-- expression in the pattern is a constructor. This prevents an pattern
-- like @a b@ from matching against @Just 1@.
dive = map (map reverse) . dive' where
dive' (Constructor n) = Just (n, [])
dive' (Apply p1 p2) = for (dive' p1) (\(name, ps) -> (name, p2:ps))
dive' _ = Nothing
------------------------------------------------------------------------------
-- * The Evaluator Monad
-- Note: we have to put these definitions here because `Value`s need to be
-- aware of the `Eval` type.
------------------------------------------------------------------------------
-- | An evaluation frame. It consists of the argument passed into the
-- function currently being evaluated, and all of the variables in the
-- current scope.
data EvalFrame = EvalFrame {
_fArgument :: Value,
_fEnvironment :: Record Value
} deriving (Show)
-- | A frame is a key-value store where the internal dictionary is the
-- environment.
instance KeyValueStore EvalFrame where
type LookupKey EvalFrame = Name
type StoredValue EvalFrame = Value
empty = def
loadBindings bs f = f {_fEnvironment = bs <> _fEnvironment f}
getValue name = lookup name . _fEnvironment
putValue name val frame = frame {_fEnvironment = insertMap name val env}
where env = _fEnvironment frame
-- | The evaluator's state is a stack of evaluation frames.
data EvalState = EvalState {_esStack :: [EvalFrame]} deriving (Show)
-- | The evaluator state is a stack of `EvalFrame`s.
instance Stack EvalState where
type Frame EvalState = EvalFrame
push frame state = state {_esStack = push frame $ _esStack state}
pop state = (top, state {_esStack=rest}) where
top:rest = _esStack state
asList = _esStack
modifyTop func state = state {_esStack=func top : rest} where
top:rest = _esStack state
-- | The default evaluation state is a stack with a single evaluation frame.
instance Default EvalState where
def = EvalState {_esStack = [def]}
-- | The default evaluation frame just takes default arguments and
-- environment.
instance Default EvalFrame where
def = EvalFrame {_fArgument = def, _fEnvironment = mempty}
-- | The evaluator monad.
type Eval = ReaderT () (StateT EvalState IO)
-- | A built-in function. Allows us to write functions in Haskell and
-- make them callable from inside the Rowling evaluator.
data Builtin = Builtin Name (Value -> Eval Value)
-- | All we show is the function's name, which is assumed to be unique.
instance Show Builtin where
show (Builtin n _) = "<BUILTIN " <> show n <> ">"
-- | Builtins are considered equal if they have the same name.
instance Eq Builtin where
Builtin n1 _ == Builtin n2 _ = n1 == n2
| thinkpad20/rowling | src/Language/Rowling/Definitions/Values.hs | mit | 8,495 | 0 | 17 | 1,884 | 2,031 | 1,062 | 969 | 151 | 19 |
module FrontEnd.TypeSynonyms (
removeSynonymsFromType,
declsToTypeSynonyms,
TypeSynonyms,
restrictTypeSynonyms,
expandTypeSyns,
showSynonyms,
showSynonym
) where
import Control.Applicative(Applicative)
import Control.Monad.Writer
import Data.Binary
import Data.List
import qualified Data.Map as Map
import qualified Data.Set as Set
import Doc.DocLike
import FrontEnd.HsSyn
import FrontEnd.SrcLoc
import FrontEnd.Syn.Traverse
import FrontEnd.Warning
import GenUtil
import Name.Name
import Support.FreeVars
import Support.MapBinaryInstance
import Util.HasSize
import Util.UniqueMonad
import qualified Util.Graph as G
newtype TypeSynonyms = TypeSynonyms (Map.Map Name ([HsName], HsType, SrcLoc))
deriving(Monoid,HasSize)
instance Binary TypeSynonyms where
put (TypeSynonyms ts) = putMap ts
get = fmap TypeSynonyms getMap
restrictTypeSynonyms :: (Name -> Bool) -> TypeSynonyms -> TypeSynonyms
restrictTypeSynonyms f (TypeSynonyms fm) = TypeSynonyms (Map.filterWithKey (\k _ -> f k) fm)
showSynonym :: (DocLike d,Monad m) => (HsType -> d) -> Name -> TypeSynonyms -> m d
showSynonym pprint n (TypeSynonyms m) =
case Map.lookup n m of
Just (ns, t, _) -> return $ hsep (tshow n:map tshow ns) <+> text "=" <+> pprint t
Nothing -> fail "key not found"
showSynonyms :: DocLike d => (HsType -> d) -> TypeSynonyms -> d
showSynonyms pprint (TypeSynonyms m) = vcat (map f (Map.toList m)) where
f (n,(ns,t,_)) = hsep (tshow n:map tshow ns) <+> text "=" <+> pprint t
-- | convert a set of type synonym declarations to a synonym map used for efficient synonym
-- expansion
--declsToTypeSynonyms :: [HsDecl] -> TypeSynonyms
--declsToTypeSynonyms ts = TypeSynonyms $ Map.fromList $
-- [ (toName TypeConstructor name,( args , quantifyHsType args (HsQualType [] t) , sl)) | (HsTypeDecl sl name args' t) <- ts, let args = [ n | ~(HsTyVar n) <- args'] ]
-- ++ [ (toName TypeConstructor name,( args , HsTyAssoc, sl)) | (HsClassDecl _ _ ds) <- ts,(HsTypeDecl sl name args' _) <- ds, let args = [ n | ~(HsTyVar n) <- args'] ]
-- | convert a set of type synonym declarations to a synonym map used for efficient synonym
-- expansion, expanding out the body of synonyms along the way.
declsToTypeSynonyms :: (Applicative m,MonadWarn m) => TypeSynonyms -> [HsDecl] -> m TypeSynonyms
declsToTypeSynonyms tsin ds = f tsin gr [] where
gr = G.scc $ G.newGraph [ (toName TypeConstructor name,( args , quantifyHsType args (HsQualType [] t) , sl)) | (HsTypeDecl sl name args' t) <- ds, let args = [ n | ~(HsTyVar n) <- args'] ] fst (Set.toList . freeVars . (\ (_,(_,t,_)) -> t))
f tsin (Right ns:xs) rs = do
warn (head [ sl | (_,(_,_,sl)) <- ns]) TypeSynonymRecursive ("Recursive type synonyms:" <+> show (fsts ns))
f tsin xs rs
f tsin (Left (n,(as,body,sl)):xs) rs = do
body' <- evalTypeSyms sl tsin body
f (tsInsert n (as,body',sl) tsin) xs ((n,(as,body',sl)):rs)
f _ [] rs = return $ TypeSynonyms (Map.fromList rs)
tsInsert x y (TypeSynonyms xs) = TypeSynonyms (Map.insert x y xs)
removeSynonymsFromType :: (Applicative m,MonadSrcLoc m, MonadWarn m) => TypeSynonyms -> HsType -> m HsType
removeSynonymsFromType syns t = do
sl <- getSrcLoc
evalTypeSyms sl syns t
expandTypeSyns :: (TraverseHsOps a,MonadWarn m) => TypeSynonyms -> a -> m a
expandTypeSyns syns m = runSLM (applyHsOps ops m) where
ops = (hsOpsDefault ops) { opHsDecl, opHsType = removeSynonymsFromType syns } where
opHsDecl td@HsTypeDecl {} = return td
opHsDecl d = traverseHsOps ops d
quantifyHsType :: [HsName] -> HsQualType -> HsType
quantifyHsType inscope t
| null vs, null (hsQualTypeContext t) = hsQualTypeType t
| otherwise = HsTyForall vs t where
vs = map g $ snub (execWriter (fv (hsQualTypeType t))) \\ inscope
g n = hsTyVarBind { hsTyVarBindName = n }
fv (HsTyVar v) = tell [v]
fv (HsTyForall vs qt) = tell $ snub (execWriter (fv $ hsQualTypeType qt)) \\ map hsTyVarBindName vs
fv (HsTyExists vs qt) = tell $ snub (execWriter (fv $ hsQualTypeType qt)) \\ map hsTyVarBindName vs
fv x = traverseHsType (\x -> fv x >> return x) x >> return ()
evalTypeSyms :: (Applicative m,Monad m,MonadWarn m) => SrcLoc -> TypeSynonyms -> HsType -> m HsType
evalTypeSyms sl (TypeSynonyms tmap) ot = execUniqT 1 (eval [] ot) where
eval stack x@(HsTyCon n) | Just (args, t, sldef) <- Map.lookup (toName TypeConstructor n) tmap = do
let excess = length stack - length args
if (excess < 0) then do
lift $ warn sl TypeSynonymPartialAp ("Partially applied typesym:" <+> show n <+> "need" <+> show (- excess) <+> "more arguments.")
unwind x stack
else case t of
HsTyAssoc -> unwind x stack
_ -> do
st <- subst (Map.fromList [(a,s) | a <- args | s <- stack]) t
eval (drop (length args) stack) st
eval stack (HsTyApp t1 t2) = eval (t2:stack) t1
eval stack x = do
t <- traverseHsType (eval []) x
unwind t stack
unwind t [] = return t
unwind t (t1:rest) = do
t1' <- eval [] t1
unwind (HsTyApp t t1') rest
subst sm (HsTyForall vs t) = do
ns <- mapM (const newUniq) vs
let nvs = [ (hsTyVarBindName v,v { hsTyVarBindName = hsNameIdent_u ((show n ++ "00") ++) (hsTyVarBindName v)})| (n,v) <- zip ns vs ]
nsm = Map.fromList [ (v,HsTyVar $ hsTyVarBindName t)| (v,t) <- nvs] `Map.union` sm
t' <- substqt nsm t
return $ HsTyForall (snds nvs) t'
subst sm (HsTyExists vs t) = do
ns <- mapM (const newUniq) vs
let nvs = [ (hsTyVarBindName v,v { hsTyVarBindName = hsNameIdent_u ((show n ++ "00") ++) (hsTyVarBindName v)})| (n,v) <- zip ns vs ]
nsm = Map.fromList [ (v,HsTyVar $ hsTyVarBindName t)| (v,t) <- nvs] `Map.union` sm
t' <- substqt nsm t
return $ HsTyExists (snds nvs) t'
subst (sm::(Map.Map HsName HsType)) (HsTyVar n) | Just v <- Map.lookup n sm = return v
subst sm t = traverseHsType (subst sm) t
substqt sm qt@HsQualType { hsQualTypeContext = ps, hsQualTypeType = t } = do
t' <- subst sm t
let f (HsAsst c xs) = return (HsAsst c (map g xs))
f (HsAsstEq a b) = do
a' <- subst sm a
b' <- subst sm b
return (HsAsstEq a' b')
g n = case Map.lookup n sm of Just (HsTyVar n') -> n' ; _ -> n
ps' <- mapM f ps -- = [ case Map.lookup n sm of Just (HsTyVar n') -> (c,n') ; _ -> (c,n) | (c,n) <- ps ]
return qt { hsQualTypeType = t', hsQualTypeContext = ps' }
| m-alvarez/jhc | src/FrontEnd/TypeSynonyms.hs | mit | 6,646 | 1 | 22 | 1,618 | 2,532 | 1,291 | 1,241 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module AI.Funn.CL.Batched.Param (
Param(..),
reshape,
split,
appendD
) where
import Control.Applicative
import Control.Exception
import Control.Monad
import Control.Monad.IO.Class
import Data.Foldable
import Data.Monoid
import Data.Proxy
import Data.Traversable
import GHC.TypeLits
import System.IO.Unsafe
import AI.Funn.CL.Blob (Blob, BlobT(Blob))
import qualified AI.Funn.CL.Blob as Blob
import AI.Funn.CL.MonadCL
import AI.Funn.CL.Tensor (Tensor)
import qualified AI.Funn.CL.Tensor as T
import qualified AI.Funn.CL.TensorLazy as TL
import qualified AI.Funn.CL.LazyMem as LM
import AI.Funn.Diff.Diff (Derivable(..))
import AI.Funn.Space
newtype Param (ω :: Nat) (n :: Nat) = Param { getParam :: Tensor '[n] }
instance Derivable (Param ω n) where
type D (Param ω n) = TL.Tensor '[ω, n]
instance (MonadIO m, KnownNat n) => Zero m (Param ω n) where
zero = Param <$> zero
instance (MonadIO m, KnownNat n) => Semi m (Param ω n) where
plus (Param x) (Param y) = Param <$> plus x y
instance (MonadIO m, KnownNat n) => Additive m (Param ω n) where
plusm xs = Param <$> plusm (map getParam xs)
instance (MonadIO m, KnownNat n) => Scale m Double (Param ω n) where
scale x (Param xs) = Param <$> scale x xs
instance (MonadIO m, KnownNat n) => VectorSpace m Double (Param ω n) where
{}
instance (MonadIO m, KnownNat n) => Inner m Double (Param ω n) where
inner (Param x) (Param y) = inner x y
instance (MonadIO m, KnownNat n) => Finite m Double (Param ω n) where
getBasis (Param x) = getBasis x
-- O(1)
reshape :: (Prod ds ~ n) => Param ω n -> Tensor ds
reshape (Param xs) = T.reshape xs
-- O(1)
split :: (KnownNat a, KnownNat b) => Param ω (a+b) -> (Param ω a, Param ω b)
split (Param xs) = case T.split xs of
(a, b) -> (Param a, Param b)
-- O(ω)
appendD :: forall ω a b. (KnownDimsF [ω, a, b]) => TL.Tensor [ω, a] -> TL.Tensor [ω, b] -> TL.Tensor [ω, a+b]
appendD = TL.appendW
| nshepperd/funn | AI/Funn/CL/Batched/Param.hs | mit | 2,439 | 0 | 11 | 567 | 878 | 496 | 382 | 57 | 1 |
import Data.List.Split (splitOn)
import Data.List (sort)
import Prelude hiding (readList)
import Control.Applicative
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Trans.Maybe
import Data.Maybe
part1 input = sum (map (\x -> part1helper $sort x) input)
where
part1helper [a,b,c] = 2*(a*b + a*c + b*c) + a*b
part2 input = sum (map (\x -> part2helper $sort x) input)
where
part2helper [a,b,c] = 2*(a+b) + a*b*c
readList :: IO [String]
readList = fmap (fromMaybe []) $ runMaybeT $ many $ do
l <- lift getLine
guard $ not $ null l
return l
make_int dat = map (\x -> read x ::Int) (splitOn "x" dat)
main = do
input <- readList
let split_data = map make_int input
print split_data
print $ part1 split_data
print $ part2 split_data | jO-Osko/adventofcode2015 | 2015/problems/haskell/day2.hs | mit | 804 | 4 | 13 | 179 | 392 | 193 | 199 | 24 | 1 |
module CSPMTypeChecker.TCDependencies
(Dependencies, dependencies, namesBoundByDecl, namesBoundByDecl',
FreeVars, freeVars, prebindDataType) where
import Data.List (nub, (\\))
import CSPMDataStructures
import CSPMTypeChecker.TCMonad
import Util
-- This method heavily affects the DataType clause of typeCheckDecl.
-- If any changes are made here changes will need to be made to typeCheckDecl
-- too
prebindDataType :: Decl -> TypeCheckMonad ()
prebindDataType (DataType n cs) =
let
prebindDataTypeClause (DataTypeClause n' es) =
do
fvs <- replicateM (length es) freshTypeVar
setType n' (ForAll [] (TDatatypeClause n fvs))
clauseNames = [n' | DataTypeClause n' es <- map removeAnnotation cs]
in do
errorIfFalse (noDups clauseNames) (DuplicatedDefinitions clauseNames)
mapM_ (prebindDataTypeClause . removeAnnotation) cs
-- n is the set of all TDatatypeClause
setType n (ForAll [] (TSet (TDatatypeClause n [])))
class Dependencies a where
dependencies :: a -> TypeCheckMonad [Name]
dependencies xs = liftM nub (dependencies' xs)
dependencies' :: a -> TypeCheckMonad [Name]
instance Dependencies a => Dependencies [a] where
dependencies' xs = concatMapM dependencies xs
instance Dependencies a => Dependencies (Maybe a) where
dependencies' (Just x) = dependencies' x
dependencies' Nothing = return []
instance Dependencies a => Dependencies (Annotated b a) where
dependencies' (Annotated _ _ inner) = dependencies inner
instance Dependencies Pat where
dependencies' (PVar n) =
do
res <- safeGetType n
case res of
Just (ForAll _ t) ->
case t of
-- See typeCheck (PVar) for a discussion of why
-- we only do this
TDatatypeClause n ts -> return [n]
_ -> return []
Nothing -> return [] -- var is not bound
dependencies' (PConcat p1 p2) =
do
fvs1 <- dependencies' p1
fvs2 <- dependencies' p2
return $ fvs1++fvs2
dependencies' (PDotApp p1 p2) = dependencies' [p1,p2]
dependencies' (PList ps) = dependencies' ps
dependencies' (PWildCard) = return []
dependencies' (PTuple ps) = dependencies' ps
dependencies' (PSet ps) = dependencies' ps
dependencies' (PParen p) = dependencies' p
dependencies' (PLit l) = return []
dependencies' (PDoublePattern p1 p2) =
do
fvs1 <- dependencies' p1
fvs2 <- dependencies' p2
return $ fvs1++fvs2
instance Dependencies Exp where
dependencies' (App e es) = dependencies' (e:es)
dependencies' (BooleanBinaryOp _ e1 e2) = dependencies' [e1,e2]
dependencies' (BooleanUnaryOp _ e) = dependencies' e
dependencies' (Concat e1 e2) = dependencies' [e1,e2]
dependencies' (DotApp e1 e2) = dependencies' [e1,e2]
dependencies' (If e1 e2 e3) = dependencies' [e1,e2, e3]
dependencies' (Lambda p e) =
do
fvsp <- freeVars p
depsp <- dependencies p
fvse <- dependencies e
return $ (fvse \\ fvsp)++depsp
dependencies' (Let ds e) =
do
fvsd <- dependencies ds
newBoundVars <- liftM nub (concatMapM namesBoundByDecl ds)
fvse <- dependencies e
return $ nub (fvse++fvsd) \\ newBoundVars
dependencies' (Lit _) = return []
dependencies' (List es) = dependencies es
dependencies' (ListComp es stmts) =
do
fvStmts <- freeVars stmts
depsStmts <- dependencies stmts
fvses' <- dependencies es
let fvse = nub (fvses'++depsStmts)
return $ fvse \\ fvStmts
dependencies' (ListEnumFrom e1) = dependencies' e1
dependencies' (ListEnumFromTo e1 e2) = dependencies' [e1,e2]
dependencies' (ListLength e) = dependencies' e
dependencies' (MathsBinaryOp _ e1 e2) = dependencies' [e1,e2]
dependencies' (NegApp e) = dependencies' e
dependencies' (Paren e) = dependencies' e
dependencies' (Set es) = dependencies es
dependencies' (SetComp es stmts) =
do
fvStmts <- freeVars stmts
depsStmts <- dependencies stmts
fvses' <- dependencies es
let fvse = nub (fvses'++depsStmts)
return $ fvse \\ fvStmts
dependencies' (SetEnumComp es stmts) =
do
fvStmts <- freeVars stmts
depsStmts <- dependencies stmts
fvses' <- dependencies es
let fvse = nub (fvses'++depsStmts)
return $ fvse \\ fvStmts
dependencies' (SetEnumFrom e1) = dependencies' e1
dependencies' (SetEnumFromTo e1 e2) = dependencies' [e1,e2]
dependencies' (SetEnum es) = dependencies' es
dependencies' (Tuple es) = dependencies' es
dependencies' (Var (UnQual n)) = return [n]
dependencies' (UserOperator n es) = dependencies' es
dependencies' (ReplicatedUserOperator n es stmts) =
do
fvStmts <- freeVars stmts
depsStmts <- dependencies stmts
fvses' <- dependencies es
let fvse = nub (fvses'++depsStmts)
return $ fvse \\ fvStmts
instance Dependencies Stmt where
dependencies' (Generator p e) =
do
ds1 <- dependencies p
ds2 <- dependencies e
return $ ds1++ds2
dependencies' (Qualifier e) = dependencies e
instance Dependencies Decl where
dependencies' (FunBind n ms t) =
do
fvsms <- dependencies ms
fvst <- dependencies t
return $ fvsms++fvst
dependencies' (PatBind p e) =
do
depsp <- dependencies p
fvsp <- freeVars p
depse <- dependencies e
return $ depsp++depse
dependencies' (Channel ns es) = dependencies es
dependencies' (Assert e1 e2 m) = dependencies [e1, e2]
dependencies' (DataType n cs) = dependencies [cs]
dependencies' (External ns) = return []
dependencies' (Transparent ns) = return []
instance Dependencies Match where
dependencies' (Match ps e) =
do
fvs1 <- freeVars ps
depsPs <- dependencies ps
fvs2 <- dependencies e
return $ (fvs2 \\ fvs1) ++ depsPs
instance Dependencies DataTypeClause where
dependencies' (DataTypeClause n es) = dependencies es
namesBoundByDecl :: AnDecl -> TypeCheckMonad [Name]
namesBoundByDecl = namesBoundByDecl' . removeAnnotation
namesBoundByDecl' (FunBind n ms t) = return [n]
namesBoundByDecl' (PatBind p ms) = freeVars p
namesBoundByDecl' (Channel ns es) = return ns
namesBoundByDecl' (Assert e1 e2 m) = return []
namesBoundByDecl' (DataType n dcs) =
let
namesBoundByDtClause (DataTypeClause n _) = [n]
in
return $ n:concatMap (namesBoundByDtClause . removeAnnotation) dcs
namesBoundByDecl' (External ns) = return ns
namesBoundByDecl' (Transparent ns) = return ns
class FreeVars a where
freeVars :: a -> TypeCheckMonad [Name]
freeVars = liftM nub . freeVars'
freeVars' :: a -> TypeCheckMonad [Name]
instance FreeVars a => FreeVars [a] where
freeVars' xs = concatMapM freeVars' xs
instance FreeVars a => FreeVars (Annotated b a) where
freeVars' (Annotated _ _ inner) = freeVars inner
instance FreeVars Pat where
freeVars' (PVar n) =
do
res <- safeGetType n
case res of
Just (ForAll _ t) ->
case t of
-- See typeCheck (PVar) for a discussion of why
-- we only do this
TDatatypeClause n ts -> return []
_ -> return [n]
Nothing -> return [n] -- var is not bound
freeVars' (PConcat p1 p2) =
do
fvs1 <- freeVars' p1
fvs2 <- freeVars' p2
return $ fvs1++fvs2
freeVars' (PDotApp p1 p2) = freeVars' [p1,p2]
freeVars' (PList ps) = freeVars' ps
freeVars' (PWildCard) = return []
freeVars' (PTuple ps) = freeVars' ps
freeVars' (PSet ps) = freeVars' ps
freeVars' (PParen p) = freeVars' p
freeVars' (PLit l) = return []
freeVars' (PDoublePattern p1 p2) =
do
fvs1 <- freeVars' p1
fvs2 <- freeVars' p2
return $ fvs1++fvs2
instance FreeVars Stmt where
freeVars' (Qualifier e) = return []
freeVars' (Generator p e) = freeVars p
| tomgr/tyger | src/CSPMTypeChecker/TCDependencies.hs | mit | 7,419 | 76 | 16 | 1,488 | 2,827 | 1,357 | 1,470 | 202 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module Errors
( AppError (..)
, authenticationRequired
, raiseAppError
, resourceNotFound
, serverError
, badRequest
) where
import Control.Monad.Except
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TLE
import Servant
data AppError = ResourceNotFound
| BadRequest T.Text
| AuthenticationRequired
| ServerError
deriving (Show, Eq, Read)
raiseAppError :: MonadError ServantErr m => AppError -> m a
raiseAppError ResourceNotFound = throwError resourceNotFound
raiseAppError (BadRequest errMsg) = throwError $ badRequest errMsg
raiseAppError AuthenticationRequired = throwError authenticationRequired
raiseAppError ServerError = throwError serverError
authenticationRequired :: ServantErr
authenticationRequired = err401 { errBody = "Authentication required" }
resourceNotFound :: ServantErr
resourceNotFound = err404 { errBody = "The request resource could not be found" }
serverError :: ServantErr
serverError = err500 { errBody = "Internal server error" }
badRequest :: T.Text -> ServantErr
badRequest msg = err400 { errBody = encode msg }
encode :: T.Text -> BL.ByteString
encode = TLE.encodeUtf8 . TL.fromStrict
| gust/feature-creature | marketing-site/app/Errors.hs | mit | 1,337 | 0 | 7 | 238 | 294 | 172 | 122 | 34 | 1 |
{-# LANGUAGE Arrows #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TemplateHaskell #-}
module Db.Transaction
( Transaction'(Transaction)
, NewTransaction
, Transaction
, transactionQuery
, allTransactions
, getTransaction
, insertTransaction
, transactionId
, transactionDate
, transactionAmount
, transactionBalance
, transactionType
, transactionPlaceId
, transactionAccountId
) where
import BasePrelude hiding (optional)
import Control.Lens
import Data.Profunctor.Product.TH (makeAdaptorAndInstance)
import Data.Text (Text)
import Data.Time (Day)
import Opaleye
import Db.Internal
data Transaction' a b c d e f g = Transaction
{ _transactionId :: a
, _transactionDate :: b
, _transactionAmount :: c
, _transactionBalance :: d
, _transactionType :: e
, _transactionPlaceId :: f
, _transactionAccountId :: g
} deriving (Eq,Show)
makeLenses ''Transaction'
type Transaction = Transaction' Int Day Double Double Text (Maybe Int) Int
type TransactionColumn = Transaction'
(Column PGInt4)
(Column PGDate)
(Column PGFloat8) -- These should be non-floating point numbers
(Column PGFloat8) -- but Opaleye doesn't support these yet. :(
(Column PGText)
(Column (Nullable PGInt4))
(Column PGInt4)
makeAdaptorAndInstance "pTransaction" ''Transaction'
type NewTransaction = Transaction' (Maybe Int) Day Double Double Text (Maybe Int) Int
type NewTransactionColumn = Transaction'
(Maybe (Column PGInt4))
(Column PGDate)
(Column PGFloat8)
(Column PGFloat8)
(Column PGText)
(Column (Nullable PGInt4))
(Column PGInt4)
transactionTable :: Table NewTransactionColumn TransactionColumn
transactionTable = Table "transaction" $ pTransaction Transaction
{ _transactionId = optional "id"
, _transactionDate = required "date"
, _transactionAmount = required "amount"
, _transactionBalance = required "balance"
, _transactionType = required "type"
, _transactionPlaceId = required "place_id"
, _transactionAccountId = required "account_id"
}
transactionQuery :: Query TransactionColumn
transactionQuery = queryTable transactionTable
allTransactions :: CanDb c e m => m [Transaction]
allTransactions = liftQuery transactionQuery
insertTransaction :: CanDb c e m => NewTransaction -> m Int
insertTransaction =
liftInsertReturningFirst transactionTable (view transactionId) . packNew
getTransaction :: CanDb c e m => Int -> m (Maybe Transaction)
getTransaction i = liftQueryFirst $ proc () -> do
t <- transactionQuery -< ()
restrict -< t^.transactionId .== pgInt4 i
returnA -< t
packNew :: NewTransaction -> NewTransactionColumn
packNew = pTransaction Transaction
{ _transactionId = fmap pgInt4
, _transactionDate = pgDay
, _transactionAmount = pgDouble
, _transactionBalance = pgDouble
, _transactionType = pgStrictText
, _transactionPlaceId = maybeToNullable . fmap pgInt4
, _transactionAccountId = pgInt4
}
| benkolera/talk-stacking-your-monads | code-classy/src/Db/Transaction.hs | mit | 3,165 | 1 | 11 | 635 | 745 | 410 | 335 | 90 | 1 |
module Y2016.M12.D20.Exercise where
-- below import available from 1HaskellADay git repository
import Data.SymbolTable
import Data.SymbolTable.Compiler
import Data.SAIPE.USStates
{--
So, yesterday, as you see from the import above, we enumerated the US States!
YAY! *throws confetti
NOW! Using the same data-set, stored at:
Y2016/M12/D15/SAIPESNC_15DEC16_11_35_13_00.csv.gz
let's enumerate the US Counties.
A slight problem: the SymbolTable-type works with strings, SO you can enumerate
the strings, sure.
(I think any Ord-type should work, but hey.)
('but hey' is a perfect counter-argument to anything. Try it sometime.)
Well you can do that. No problem. But how do you associate an atomic County
symbol with its State?
Today's Haskell problem.
1) create a complied symbol table of Data.SAIPE.USCounties, enumerated and
indexible.
--}
usCountySymbols :: FilePath -> FilePath -> IO ()
usCountySymbols gzipSAIPEdata modul = undefined
data USCounty = PlaceholderForCompiledUSCountyType
-- see yesterday's exercise for guidance
{--
Now, USState and USCounty and their associations are all deterministic (as we'd
say in Prolog-parlance), so how do we do a lookup for the USState of a USCounty
in a deterministic fashion?
--}
usStateFor :: USCounty -> USState
usStateFor county = undefined
-- 2) define usStateFor as above that guarantees to return a USState value
-- (the correct one, at that) for the input USCounty value.
-- hint: A USCounty's USState is a fact. No doubt.
| geophf/1HaskellADay | exercises/HAD/Y2016/M12/D20/Exercise.hs | mit | 1,493 | 0 | 8 | 237 | 84 | 51 | 33 | 9 | 1 |
f x = if x < 10
then x
else x*2
| Bolt64/my_code | haskell/hello_haskell.hs | mit | 49 | 1 | 6 | 28 | 28 | 13 | 15 | 3 | 2 |
revList :: [a] -> [a]
revList [] = []
revList (h:t) = revList t ++ [h]
dropList :: Int -> [a] -> [a]
dropList 0 list = list
dropList _ [] = []
dropList n (h:t) = dropList (n-1) t
fizzbuzz :: Int -> String
fizzbuzz a
| a `mod` 15 == 0 = "FizzBuzz"
| a `mod` 3 == 0 = "Fizz"
| a `mod` 5 == 0 = "Buzz"
| otherwise = show a
(|>) :: a -> (a -> b) -> b
(|>) val func = func val
quicksort :: (Ord a) => [a] -> [a]
quicksort (x:xs) = [v | v <- xs, v <= x] ++ [x] ++ [v | v <- xs, v > x]
zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' _ [] _ = []
zipWith' _ _ [] = []
zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys
partition' :: (a -> Bool) -> [a] -> ([a],[a])
partition' f l = partition_' f ([],[]) l
partition_' :: (a -> Bool) -> ([a],[a]) -> [a] -> ([a],[a])
partition_' f (h,t) [] = (h,t)
partition_' f (h,t) (x:xs)
| f(x) = partition_' f (h, x:t) xs
| otherwise = partition_' f (x:h, t) xs
--
-- Types
-- Int
-- Integer makes use unbounded list
-- Char
-- Bool
-- Float
-- Double
-- Here Shape is the type and Circle and Rectange are the value constructors
-- like Circle :: Float -> Float -> Float -> Shape
-- Value Constructors are functions
data Shape = Circle Float Float Float
| Rectangle Float Float Float Float deriving (Show, Eq)
area :: Shape -> Float
area (Circle _ _ r) = 3.1415 * r * r
area (Rectangle x1 y1 x2 y2) = abs (x1 - x2) * abs(y1 - y2)
data Vector2D = Vector2D Float Float deriving (Show, Eq)
add :: Vector2D -> Vector2D -> Vector2D
add (Vector2D x1 y1) (Vector2D x2 y2) = Vector2D (x1+x2) (y1+y2)
data MyBool = MyFalse | MyTrue deriving (Ord, Eq, Show)
class YesNo a where
yesno :: a -> MyBool
instance YesNo Int where
yesno 0 = MyFalse
yesno _ = MyTrue
instance YesNo [a] where
yesno [] = MyFalse
yesno _ = MyTrue
instance YesNo MyBool where
yesno = id
data Optional a = Empty | Some a deriving (Show, Eq)
instance Functor Optional where
fmap f Empty = Empty
fmap f (Some a) = Some $ f a
rpn :: (Num a, Read a) => String -> a
rpn exp = exp |> words |> foldl f [] |> head
where f (x:y:ys) "*" = (x * y):ys
f (x:y:ys) "+" = (x + y):ys
f (x:y:ys) "-" = (y - x):ys
f x num = (read num):x
main = do
print (revList [1,2,3,4,5])
print (dropList (-100) [1,2,3,4,5,6])
print (fizzbuzz 10)
print (fizzbuzz 3)
print (fizzbuzz 75)
print (fizzbuzz 101)
print (quicksort [23,5,34,78,9,10,20])
print (zipWith' (+) [1,2,3] [5,6,7])
print ( 3 |> (*3) |> (+10) |> \x -> x * x)
print (partition' (>3) [1,2,3,4,5,6])
print $ area $ Rectangle 1 2 11 12
print $ yesno MyTrue
print $ yesno (0::Int)
print $ rpn "90 34 12 33 55 66 + * - + -"
| anujjamwal/learning | Haskell/first.hs | mit | 2,734 | 13 | 12 | 725 | 1,601 | 823 | 778 | 72 | 4 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module Text.Html.Nice.Internal where
import Control.DeepSeq (NFData (..))
import Control.Monad
import Control.Monad.Trans.Reader (ReaderT (..))
import Data.Bifunctor.TH
import Data.Functor.Foldable.TH
import Data.Functor.Identity
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TLB
import qualified Data.Text.Lazy.Builder.Int as TLB
import qualified Data.Text.Lazy.Builder.RealFloat as TLB
import Data.Vector (Vector)
import qualified Data.Vector as V
import Data.Void
import GHC.Generics (Generic)
import qualified Text.Blaze as Blaze
import qualified Text.Blaze.Internal as Blaze (textBuilder)
import qualified Text.Blaze.Renderer.Text as Blaze
type AttrName = Text
data Attr a = (:=)
{ attrKey :: !AttrName
, attrVal :: !Text
} | (:-)
{ attrKey :: !AttrName
, attrValHole :: a
} deriving (Show, Eq, Functor, Foldable, Traversable)
data IsEscaped = DoEscape | Don'tEscape
deriving (Show, Eq)
data SomeText
= LazyT TL.Text
| BuilderT TLB.Builder
| StrictT !T.Text
deriving (Show, Eq)
-- | A very simple HTML DSL
data Markup' a
= Doctype
| Node !Text !(Vector (Attr a)) (Markup' a)
| VoidNode !Text !(Vector (Attr a))
| List [Markup' a]
| Stream (Stream a)
| Text !IsEscaped !SomeText
| Hole !IsEscaped a
| Precompiled !(FastMarkup a)
| Empty
deriving (Show, Eq, Functor, Foldable) {- , Traversable) -}
data Stream a = forall s. ListS [s] !(FastMarkup (s -> a))
instance Show a => Show (Stream a) where
show (ListS s f) = "(Stream (" ++ show (map (\a -> fmap ($ a) f) s) ++ "))"
-- | Don't use this! It's a lie!
instance Eq (Stream a) where
_ == _ = True
instance Functor Stream where
fmap f (ListS l g) = ListS l (fmap (fmap f) g)
instance Foldable Stream where
foldMap f s = unstream (foldMap f) s mappend mempty
instance NFData a => NFData (Stream a) where
rnf (ListS !_ !s) = rnf s
{-# INLINE unstream #-}
unstream :: (FastMarkup a -> b) -> Stream a -> (b -> c -> c) -> c -> c
unstream f (ListS l fm) cons nil =
foldr (\x -> cons (f (fmap ($ x) fm))) nil l
--------------------------------------------------------------------------------
-- Compiling
data a :$ b = (:$) (FastMarkup (a -> b)) a
deriving (Functor)
infixl 0 :$
instance Show a => Show (a :$ b) where
show (a :$ b) = '(':showsPrec 11 b (' ':':':'$':' ':showsPrec 11 (b <$ a) ")")
data FastMarkup a
= Bunch {-# UNPACK #-} !(Vector (FastMarkup a))
-- could unpack this manually but would then have to also write
-- Show/Eq/Functor/Foldable manually
| FStream !(Stream a)
| FHole !IsEscaped !a
| FLText TL.Text
| FSText {-# UNPACK #-} !Text
| FBuilder !TLB.Builder
| FEmpty
| FDeep (FastMarkup (FastMarkup a))
deriving (Show, Eq, Functor, Foldable, Generic)
instance Monoid (FastMarkup a) where
mempty = FBuilder mempty
mappend a b = Bunch [a, b]
instance NFData a => NFData (FastMarkup a) where
rnf f = case f of
Bunch v -> rnf v
FStream s -> rnf s
FLText t -> rnf t
FSText t -> rnf t
FHole !_ a -> rnf a
_ -> ()
makeBaseFunctor ''Markup'
deriveBifunctor ''Markup'F
{-# INLINE plateFM #-}
-- | Unlike 'plate', this uses 'Monad'. That's because 'traverse' over 'Vector'
-- is really quite slow.
plateFM :: Monad m
=> (FastMarkup a -> m (FastMarkup a))
-> FastMarkup a
-> m (FastMarkup a)
plateFM f x = case x of
Bunch v -> Bunch <$> V.mapM f v
_ -> pure x
compileAttrs :: forall a. Vector (Attr a) -> (TLB.Builder, Vector (Attr a))
compileAttrs v = (static, dynAttrs)
where
isHoly :: Foldable f => f a -> Bool
isHoly = foldr (\_ _ -> True) False
staticAttrs :: Vector (Attr a)
dynAttrs :: Vector (Attr a)
(dynAttrs, staticAttrs) = case V.unstablePartition isHoly v of
(dyn, stat) -> (dyn, stat)
static :: TLB.Builder
static =
V.foldr
(\((:=) key val) xs ->
" " <> TLB.fromText key <> "=\"" <> escapeText val <> "\"" <> xs)
mempty
staticAttrs
escapeText :: Text -> TLB.Builder
escapeText = Blaze.renderMarkupBuilder . Blaze.text
{-# INLINE escape #-}
escape :: SomeText -> TLB.Builder
escape st = case st of
StrictT t -> Blaze.renderMarkupBuilder (Blaze.text t)
LazyT t -> Blaze.renderMarkupBuilder (Blaze.lazyText t)
BuilderT t -> Blaze.renderMarkupBuilder (Blaze.textBuilder t)
toText :: TLB.Builder -> Text
toText = TL.toStrict . TLB.toLazyText
fastAttr :: Attr a -> FastMarkup a
fastAttr ((:-) k v) =
Bunch [FSText (" " <> k <> "=\""), FHole DoEscape v, FSText "\""]
fastAttr _ =
error "very bad"
fast :: Markup' a -> FastMarkup a
fast m = case m of
Doctype -> FSText "<!DOCTYPE html>\n"
Node t attrs m' -> case compileAttrs attrs of
(staticAttrs, dynAttrs) -> case V.length dynAttrs of
0 -> Bunch
[ FSText (T.concat ["<", t, toText staticAttrs, ">"])
, fast m'
, FSText (T.concat ["</", t, ">"])
]
_ -> Bunch
[ FBuilder ("<" <> TLB.fromText t <> staticAttrs)
, Bunch (V.map fastAttr dynAttrs)
, FSText ">"
, fast m'
, FSText ("</" <> t <> ">")
]
VoidNode t attrs -> case compileAttrs attrs of
(staticAttrs, dynAttrs) -> case V.length dynAttrs of
0 -> FSText (T.concat ["<", t, toText staticAttrs, " />"])
_ -> Bunch
[ FBuilder ("<" <> TLB.fromText t <> staticAttrs)
, Bunch (V.map fastAttr dynAttrs)
, FSText " />"
]
Text DoEscape t -> FBuilder (escape t)
Text Don'tEscape t -> case t of
StrictT a -> FSText a
LazyT a -> FLText a
BuilderT a -> FBuilder a
List v -> Bunch (V.map fast (V.fromList v))
Hole e v -> FHole e v
Stream a -> FStream a
Empty -> FEmpty
Precompiled fm -> fm
-- | Look for an immediate string-like term and render that
immediateRender :: FastMarkup a -> Maybe TLB.Builder
immediateRender fm = case fm of
FBuilder t -> Just t
FSText t -> Just (TLB.fromText t)
FLText t -> Just (TLB.fromLazyText t)
FEmpty -> Just mempty
_ -> Nothing
-- | Flatten a vector of 'FastMarkup. String-like terms that are next to
-- eachother should be combined
munch :: Vector (FastMarkup a) -> Vector (FastMarkup a)
munch v = V.fromList (go mempty 0)
where
len = V.length v
go acc i
| i < len =
let e = V.unsafeIndex v i
in case immediateRender e of
Just b -> go (acc <> b) (i + 1)
Nothing -> FBuilder acc : e : go mempty (i + 1)
| otherwise = [FBuilder acc]
-- | Recursively flatten 'FastMarkup' until doing so does nothing
flatten :: FastMarkup a -> FastMarkup a
flatten fm = case fm of
FStream t -> FStream t -- ignore streams
_ -> go
where
go = again $ case fm of
Bunch v -> case V.length v of
0 -> FEmpty
1 -> V.head v
_ -> Bunch
(munch
(V.concatMap
(\x -> case x of
Bunch v' -> v'
FEmpty -> V.empty
_ -> V.singleton (flatten x))
v))
_ -> runIdentity (plateFM (Identity . flatten) fm)
again a
-- Eq but ignore holes
| (() <$ a) == (() <$ fm) = fm
| otherwise = flatten a
-- | Run all Text builders
strictify :: FastMarkup a -> FastMarkup a
strictify fm = case fm of
FBuilder t -> FLText (TLB.toLazyText t)
FLText t -> FLText t
_ -> runIdentity (plateFM (Identity . strictify) fm)
-- | Compile 'Markup'''
compile_ :: Markup' a -> FastMarkup a
compile_ = strictify . flatten . fast
recompile :: FastMarkup a -> FastMarkup a
recompile = strictify . flatten
unlayer :: FastMarkup (FastMarkup a) -> FastMarkup a
unlayer = FDeep
--------------------------------------------------------------------------------
-- Rendering
{-#
SPECIALISE renderM :: (a -> Identity TLB.Builder)
-> FastMarkup a
-> Identity TLB.Builder
#-}
{-# INLINE renderM #-}
-- | Render 'FastMarkup'
renderM :: Monad m => (a -> m TLB.Builder) -> FastMarkup a -> m TLB.Builder
renderM f = go
where
go fm = case fm of
Bunch v -> V.foldM (\acc x -> mappend acc <$> go x) mempty v
FBuilder t -> return t
FSText t -> return (TLB.fromText t)
FLText t -> return (TLB.fromLazyText t)
FHole esc a -> case esc of
DoEscape -> Blaze.renderMarkupBuilder . Blaze.textBuilder <$> f a
Don'tEscape -> f a
FStream str -> unstream go str (liftM2 mappend) (return mempty)
FDeep a -> renderM go a
_ -> return mempty
{-# INLINE renderMs #-}
-- | Render 'FastMarkup' by recursively rendering any sub-markup.
renderMs :: Monad m => (a -> m (FastMarkup Void)) -> FastMarkup a -> m TLB.Builder
renderMs f = renderM (f >=> renderMs (f . absurd))
{-# INLINE render #-}
-- | Render 'FastMarkup' that has no holes.
render :: FastMarkup Void -> TLB.Builder
render = runIdentity . renderM absurd
{-# INLINE r_ #-}
r_ :: Render a Identity => a -> TLB.Builder
r_ = runIdentity . r
class Render a m where
r :: a -> m TLB.Builder
-- needs undecidableinstances ...
instance (Render b m, m' ~ ReaderT a m) => Render (a -> b) m' where
{-# INLINE r #-}
r f = ReaderT (r . f)
-- | Defer application of an argument to rendering
instance (Monad m, Render b m) => Render (a :$ b) m where
{-# INLINE r #-}
r (b :$ a) = renderM (\f -> r (f a)) b
instance Monad m => Render Void m where
{-# INLINE r #-}
r = return . absurd
instance Monad m => Render TLB.Builder m where
{-# INLINE r #-}
r = return
instance Monad m => Render T.Text m where
{-# INLINE r #-}
r = return . TLB.fromText
instance Monad m => Render TL.Text m where
{-# INLINE r #-}
r = return . TLB.fromLazyText
instance {-# OVERLAPPABLE #-} (Render a m, Monad m) => Render (FastMarkup a) m where
{-# INLINE r #-}
r = renderM r
newtype RenderToFastMarkup a = RenderToFastMarkup { unToFastMarkup :: a }
instance (ToFastMarkup a, Monad m) => Render (RenderToFastMarkup a) m where
{-# INLINE r #-}
r = r . (toFastMarkup :: a -> FastMarkup Void) . unToFastMarkup
--------------------------------------------------------------------------------
class ToFastMarkup a where
toFastMarkup :: a -> FastMarkup b
instance ToFastMarkup (FastMarkup Void) where
toFastMarkup = vacuous
instance ToFastMarkup Text where
{-# INLINE toFastMarkup #-}
toFastMarkup = FSText
instance ToFastMarkup TL.Text where
{-# INLINE toFastMarkup #-}
toFastMarkup = FLText
instance ToFastMarkup TLB.Builder where
{-# INLINE toFastMarkup #-}
toFastMarkup = FBuilder
newtype AsDecimal a = AsDecimal { asDecimal :: a }
instance Integral a => ToFastMarkup (AsDecimal a) where
{-# INLINE toFastMarkup #-}
toFastMarkup = toFastMarkup . TLB.decimal . asDecimal
newtype AsHex a = AsHex { asHex :: a }
instance Integral a => ToFastMarkup (AsHex a) where
{-# INLINE toFastMarkup #-}
toFastMarkup = toFastMarkup . TLB.hexadecimal . asHex
newtype AsRealFloat a = AsRealFloat { asRealFloat :: a }
instance RealFloat a => ToFastMarkup (AsRealFloat a) where
{-# INLINE toFastMarkup #-}
toFastMarkup = toFastMarkup . TLB.realFloat . asRealFloat
| TransportEngineering/nice-html | src/Text/Html/Nice/Internal.hs | mit | 12,438 | 297 | 17 | 3,367 | 3,795 | 2,054 | 1,741 | 341 | 14 |
{-
Game of Life Core - provides the basic funtions used in the SDL version
Copyright (C) 2012 Josh Chase
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
module GameOfLife (Cell, glider, advanceGrid, alive) where
import Data.List
import System.Process as S
type Cell = (Int, Int)
xDim = 20
yDim = 20
glider :: Cell -> [Cell]
glider (x,y) = [(x+1,y),(x+2,y+1),(x,y+2),(x+1,y+2),(x+2,y+2)]
grid :: Int -> Int -> [[Cell]]
grid x y | y > 0 = map (\z -> (z,y)) [0..xDim] : (let y' = y - 1 in grid x y')
| otherwise = [map (\z -> (z,y)) [0..xDim]]
-- List of points that may be livig next turn
interestingCells ps = concat . map neighbors $ ps
-- List of living points next turn
livingCells ps = nub . filter (\p -> testCell p ps) $ (interestingCells ps)
-- Probably a better way of doing this, but eh, whatever
neighbors :: Cell -> [Cell]
neighbors (x,y) = [(x+1,y+1),(x+1,y),(x,y+1),(x-1,y-1),(x-1,y),(x,y-1),(x-1,y+1),(x+1,y-1)]
-- Check if a point is 'alive'
alive :: Cell -> [Cell] -> Bool
alive p ps | intersect [p] ps == [] = False
| otherwise = True
-- Populates the grid with a list of Cells. Any Cells that are repeated or outside of the grid area are ignored.
populateGrid :: [Cell] -> [Cell]
populateGrid points = points
-- Advance the grid one turn
advanceGrid :: [Cell] -> [Cell]
advanceGrid ps = livingCells ps
-- Advance the grid n turns
advanceGridN :: Int -> [Cell] -> [Cell]
advanceGridN 0 ps = ps
advanceGridN n ps | n > 0 = advanceGridN (n-1) (advanceGrid ps)
| n < 0 = ps
-- Check the status of a point for the next iteration
testCell :: Cell -> [Cell] -> Bool
testCell p ps | alive p ps && (checkNeighbors p ps == 2 || checkNeighbors p ps == 3) = True
| not (alive p ps) && (checkNeighbors p ps == 3) = True
| otherwise = False
-- Check how many living neighbors a point has
checkNeighbors :: Cell -> [Cell] -> Int
checkNeighbors p ps = length . intersect ps $ (neighbors p)
-- Utility function to divide a list into even intervals
splitEvery :: Int -> [a] -> [[a]]
splitEvery _ [] = []
splitEvery a lst = l1 : splitEvery a l2
where (l1,l2) = splitAt a lst
-- Because I screwed up the rows/columns :P
rotateMatrix :: [[a]] -> [[a]]
rotateMatrix [] = []
rotateMatrix m = (map head m) : (rotateMatrix . filter (not . null) $ (map tail m))
-- Generates a string for a list of points based on whether they're alive
genString :: [Cell] -> [Cell] -> String
genString live pts = foldr (\x acc -> if alive x live then '#' : acc else ' ':acc) "" pts
-- Display the grid
showGrid :: [Cell] -> IO [()]
showGrid ps = sequence . map putStrLn $ stringList
where stringList = map (genString ps) (grid xDim yDim)
-- Reads a Int from the user's input String. If none is found, it defaults to 1
parseInput :: String -> Int
parseInput s = case reads s of
[(x,_)] -> x
_ -> 1
| Pursuit92/GameOfLife | src/GameOfLife.hs | gpl-3.0 | 3,498 | 0 | 13 | 786 | 1,170 | 637 | 533 | 48 | 2 |
import Control.Monad as M
import Control.Monad.Trans.Resource
import Data.Array.Repa as R
import Data.Conduit
import Data.Conduit.List as CL
import Data.List as L
import Data.Maybe as Maybe
import PetaVision.Data.Weight
import PetaVision.Image.ImageIO
import PetaVision.PVPFile.IO
import Prelude as P
import System.Directory
import System.Environment
main = do
(reconFilePath:idxStr:reconName:_) <- getArgs
let idx = read idxStr :: Int
recons <-
runConduitRes $
pvpFileSource reconFilePath .| (CL.drop idx >> CL.map id) .| CL.head
case recons of
Nothing -> error "idx is out of boundary."
Just recon ->
let arr = pvpOutputData2Array recon
(Z :. _ :. _ :. nf) = extent arr
in do createDirectoryIfMissing True "Recon"
M.mapM_
(\i ->
let x =
Image 8 .
computeUnboxedS .
extend (Z :. (1 :: Int) :. All :. All) . R.slice arr $
(Z :. All :. All :. i)
in plotImageRepa
("Recon/" L.++ reconName L.++ "_" L.++ show i L.++ ".png")
x)
[0 .. nf - 1]
| XinhuaZhang/PetaVisionHaskell | Application/Amoeba/PlotRecon.hs | gpl-3.0 | 1,422 | 0 | 29 | 633 | 374 | 198 | 176 | 36 | 2 |
module Lab6 where
import Control.Monad
import Lecture6
import Data.List
import Data.Bits
import Control.Exception
import Data.Time
import System.Random
import Formatting
import Formatting.Clock
import System.Clock
import Control.Monad
-- Define Main --
main = do
putStrLn "===================="
putStrLn "Assignment 6 / Lab 6"
putStrLn "===================="
putStrLn "> Exercise 1"
exercise1
putStrLn "> Exercise 2"
exercise2
putStrLn "> Exercise 3"
exercise3
putStrLn "> Exercise 4"
exercise4
putStrLn "> Exercise 5"
exercise5
putStrLn "> Exercise 6 (1)"
exercise6
putStrLn "> Exercise 6 (2)"
exercise62
putStrLn "> Exercise 7 (BONUS)"
exercise7
-- =============================================================================
-- Exercise 1 :: Time spent: +- 5 hours
-- While implementing multiple versions of the exM function I came acros a package
-- that implemented the function if the squaring method.
-- =============================================================================
exercise1 = do
print()
-- This the implimentation found in the crypto-numbers package -- Using exponentiation by squaring
exM' :: Integer -> Integer -> Integer -> Integer
exM' 0 0 m = 1 `mod` m
exM' b e m = loop e b 1
where sq x = (x * x) `mod` m
loop 0 _ a = a `mod` m
loop i s a = loop (i `shiftR` 1) (sq s) (if odd i then a * s else a)
exM'' 0 _ m = 1 `mod` m
exM'' b e m = f e b 1
where
f e' b' r | e' <= 0 = r
| ((e' `mod` 2) == 1) = f (e' `shiftR` 1) ((b' * b') `mod` m) ((r * b') `mod` m)
| otherwise = f (e' `shiftR` 1) ((b' * b') `mod` m) (r)
-- =============================================================================
-- Exercise 2 :: Time spent: +- 2 hours
-- A fair test should apply the same inputs to each function
-- It first generate 3 list of input and use them with both functions
-- =============================================================================
exercise2 = do
bs <- runRepl
es <- runRepl
ms <- runRepl
package <- doRun (doCalculation' exM'' bs es ms)
ownImplementation <- doRun (doCalculation' exM' bs es ms)
standardImplementation <- doRun (doCalculation' exM bs es ms)
reportTime "package variant" package
reportTime "optimized variant" ownImplementation
reportTime "standard implementation" standardImplementation
reportTime str (start,end) = do
fprint (timeSpecs) start end
putStrLn $ " when using the " ++ str
doRun f = do
start <- getTime Monotonic
print f
end <- getTime Monotonic
return (start,end)
doCalculation' :: (Integer -> Integer -> Integer -> Integer) -> [Integer] -> [Integer] -> [ Integer] ->[[Integer]]
doCalculation' fn bs es ms = do
let z = zip3 bs es ms
let ys = map (runFn) z
return ys
where
runFn (b, e , m) = fn b e m
runRepl = replicateM 10 randomInt
randomInt = do
x <- randomRIO (400, 10000 :: Integer)
return x
-- =============================================================================
-- Exercise 3 :: Time spent: +- 20 minutes
-- Since every whole number over 1 is either a composite number or a prime number
-- I can check if the number is not a prime number
-- =============================================================================
exercise3 = do
print $ take 100 composites'
composites' :: [Integer]
composites' = filter (not.prime) [4..]
-- =============================================================================
-- Exercise 4 :: Time spent: +- 1 hour
-- The smallest composite number that passes the test is 9
-- If k = 1 it runs fast if k = 2 then takes a little longer but comes to the same conclusion. Running k = 3
-- takes a lot longer and got as low as 15 in one test.
-- =============================================================================
exercise4 = do
k1 <- testFer (testFermatKn 1)
k2 <- testFer (testFermatKn 2)
k3 <- testFer (testFermatKn 3)
putStrLn " Exercise 4: Smallest composite number that passes Fermat test"
putStrLn " K = 1 "
print k1
putStrLn " K = 2 "
print k2
putStrLn " K = 3 "
print k3
testFer x = do
avg <- testFerAvg x
small <- testFerSmall x
return (small , avg)
testFerAvg :: IO Integer -> IO Integer
testFerAvg tk = do
x <- replicateM 100 tk
let avg = (sum x) `div` 100
return avg
testFerSmall tk = do
x <- replicateM 100 tk
let sorted = sort x
return $ head sorted
testFermatKn n = foolFermat' n composites
foolFermat' :: Int -> [Integer] -> IO Integer
foolFermat' k (x:xs) = do
z <- primeTestsF k x
if z then
return x
else
foolFermat' k xs
-- =============================================================================
-- Exercise 5 :: Time spent: +- 2 hours
-- This function uses J. Chernick's theorem to construct a subset of carmichael numbers.
-- The fermat test is easily by the first 2 numbers produced by the carmichael function
-- =============================================================================
exercise5 = do
k1 <- testFer (testFermatCarmichaelKn 1)
k2 <- testFer (testFermatCarmichaelKn 2)
k3 <- testFer (testFermatCarmichaelKn 3)
putStrLn " Exercise 5: Smallest number in J. Chernick's subset of carmichael numbers that passes Fermat test"
putStrLn " K = 1 "
print k1
putStrLn " K = 2 "
print k2
putStrLn " K = 3 "
print k3
testFermatCarmichaelKn n= foolFermat' n carmichael
carmichael :: [Integer]
carmichael = [ (6*k+1)*(12*k+1)*(18*k+1) |
k <- [2..],
prime (6*k+1),
prime (12*k+1),
prime (18*k+1) ]
-- =============================================================================
-- Exercise 6 (1) :: Time spent: +- 30 min
-- The numbers are much larger but the Miller-Rabin primality check does get fooled.
-- =============================================================================
exercise6 = do
k1 <- testFer (testMRKn 1)
k2 <- testFer (testMRKn 2)
k3 <- testFer (testMRKn 3)
putStrLn " Exercise 6: Smallest number in J. Chernick's subset of carmichael numbers that passes Miller-Rabin"
putStrLn " K = 1 "
print k1
putStrLn " K = 2 "
print k2
putStrLn " K = 3 "
print k3
testMRKn n = testMR n carmichael
testMR :: Int -> [Integer] -> IO Integer
testMR k (x:xs) = do
z <- primeMR k x
if z then
return x
else
testMR k xs
-- =============================================================================
-- Exercise 6 (2) :: Time spent: +- 15 minutes
-- I manage to get to 607 easily but then the program hangs.
-- =============================================================================
exercise62 = do
print ()
filterM ((primeMR 1).(\x -> ((2^x) - 1 ))) $ take 150 primes
-- =============================================================================
-- Exercise 7 :: Time spent: +-
-- =============================================================================
exercise7 = do
print()
| vdweegen/UvA-Software_Testing | Lab6/Jordan/Exercises.hs | gpl-3.0 | 6,993 | 1 | 16 | 1,456 | 1,742 | 856 | 886 | 149 | 3 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
module Types where
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Logger (runNoLoggingT, NoLoggingT)
import Control.Monad.Trans.Resource (runResourceT, ResourceT)
import Database.Persist.Sqlite (runSqlConn, SqlBackend, SqlPersistT)
import Web.Spock.Safe (SpockCtxT)
import Web.Spock.Shared ( runQuery, SpockConn, HasSpock
, ActionCtxT, WebStateM)
type OM a = SpockCtxT () (WebStateM SqlBackend (Maybe a) OMState) ()
type OMRoute ctx m b = (MonadIO m) => OMSqlResult (ActionCtxT ctx m) b
data OMState = OMState { }
type OMSQL a = SqlPersistT (NoLoggingT (ResourceT IO)) a
type OMSqlResult m a = (HasSpock m, SpockConn m ~ SqlBackend) => m a
runSQL :: OMSQL a -> OMSqlResult m a
runSQL action = runQuery $ \conn -> runResourceT $ runNoLoggingT $ runSqlConn action conn
| Southern-Exposure-Seed-Exchange/Order-Manager-Prototypes | spock/src/Types.hs | gpl-3.0 | 987 | 2 | 10 | 234 | 274 | 160 | 114 | 18 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DataKinds #-}
module RollMyOwnLiterals where
import Language.Haskell.TH
data Nat = Z | S Nat
nat :: Integer -> Q Type
nat 0 = [t|Z|]
nat n = [t|S $(nat (n-1))|]
| ntc2/haskell-call-trace | experiments/composition/RollMyOwnLiterals.hs | mpl-2.0 | 211 | 0 | 6 | 40 | 60 | 38 | 22 | 8 | 1 |
module Main where
main :: IO ()
main = mapM_ putStrLn c_yes
c_yes :: [String]
c_yes = repeat "y"
{-
main2 :: IO ()
main2 = do putStrLn "y"
main2
-}
| tyoko-dev/coreutils-haskell | src/Yes.hs | agpl-3.0 | 162 | 0 | 6 | 45 | 41 | 23 | 18 | 5 | 1 |
{-# LANGUAGE RankNTypes #-}
foo :: (forall a. a -> a) -> Char
foo f = f 'c'
type IdFunc = forall a. a -> a
someInt :: IdFunc -> Integer
someInt id' = id' 1
main = print "hello world"
----
-- runST :: forall s,a. ST s a -> a
-- newVar :: a -> ST s (MutVar s a)
-- readVar :: MutVar s a -> ST s a
-- writeVar :: MutVar s a -> a -> ST s ()
-- newVar True :: ST s (MutVar s Bool)
-- runST (newVar True) :: ST s Bool
-- readVar s :: ST s Bool
-- runST (readVar s) :: Bool
----
runST :: forall a. (forall s. ST s a) -> a
newVar :: a -> ST s (MutVar s a)
readVar :: MutVar s a -> ST s a
writeVar :: MutVar s a -> a -> ST s ()
newVar True :: ST s (MutVar s Bool)
runST (newVar True) ::
let v = runST (newVar True)
in runST (readVar v)
| seckcoder/lang-learn | haskell/samples/src/RankN.hs | unlicense | 744 | 4 | 9 | 194 | 238 | 128 | 110 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module BarthPar.Data where
import Conduit
import Control.Error
import Control.Lens
import qualified Data.Aeson as A
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as L8
import Data.Csv
import qualified Data.Csv as Csv
import qualified Data.Vector as V
import BarthPar.Lens
import BarthPar.Parallel
import BarthPar.Types
splitTabs :: FromRecord a => L8.ByteString -> Either String (V.Vector a)
splitTabs = traverse (Csv.runParser . parseRecord . V.fromList . fmap L8.toStrict . L8.split '\t')
. V.fromList
. L8.lines
lazyWriteNetwork :: Int -> FilePath -> Network -> Script ()
lazyWriteNetwork chunkSize output n = runResourceT $ doc n $$ sinkFile output
where
doc Network{..} = do
yield "{\"nodes\":"
injectJsonArray $ smartMap chunkSize A.encode nodes
yield ",\"links\":"
injectJsonArray $ smartMap chunkSize A.encode links
yield "}"
injectJsonArray :: Monad m => [BL.ByteString] -> Source m BL.ByteString
injectJsonArray [] = yield "[]"
injectJsonArray (x:xs) = do
yield "["
yield x
mapM_ item xs
yield "]"
where
item y = yield "," >> yield y
{-# INLINE item #-}
getWord :: InputRow -> Token
getWord = view inputWord
| erochest/barth-scrape | src/BarthPar/Data.hs | apache-2.0 | 1,497 | 0 | 13 | 443 | 402 | 207 | 195 | 38 | 1 |
module Palindromes.A249642Spec (main, spec) where
import Test.Hspec
import Palindromes.A249642 (a249642)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A249642" $
it "correctly computes the first 10 elements" $
take 10 (map a249642 [0..]) `shouldBe` expectedValue where
expectedValue = [0,0,9,153,1449,13617,123129,1113273,10024569,90266553]
| peterokagey/haskellOEIS | test/Palindromes/A249642Spec.hs | apache-2.0 | 371 | 0 | 10 | 59 | 130 | 75 | 55 | 10 | 1 |
{-|
Module : Text.ABNF.Document
Description : Documents according to an ABNF definition
Copyright : (c) Martin Zeller, 2016
License : BSD2
Maintainer : Martin Zeller <mz.bremerhaven@gmail.com>
Stability : experimental
Portability : non-portable
-}
module Text.ABNF.Document
(
-- * Document types
-- | Re-exported from "Text.ABNF.Document.Types"
Document(..)
-- * Reducing documents
-- | Re-exported from "Text.ABNF.Document.Operations"
--
-- In most cases, you don't want to work with the full tree of a 'Document'.
-- You can use these cases to 'filterDocument' away any branches you do not
-- need and 'squashDocumentOn' those, where you don't need it as
-- fine-grained.
--
-- This is incredibly useful if you have rules that parse single characters.
, filterDocument
, squashDocument
, squashDocumentOn
, lookupDocument
, lookupDocument'
, getContent
-- * Parsing documents
-- | Re-exported from "Text.ABNF.Document.Parser"
, generateParser
, parseDocument
) where
import Text.ABNF.Document.Types ( Document(..)
)
import Text.ABNF.Document.Operations ( filterDocument
, squashDocument
, squashDocumentOn
, getContent
, lookupDocument
, lookupDocument'
)
import Text.ABNF.Document.Parser ( generateParser
, parseDocument
)
| Xandaros/abnf | src/Text/ABNF/Document.hs | bsd-2-clause | 1,662 | 0 | 6 | 603 | 112 | 80 | 32 | 20 | 0 |
module Main where
import Criterion
import Criterion.Main
main :: IO ()
main = defaultMain
[ env (return ()) $
\ ~() -> bgroup "\"oops\"" [bench "dummy" $ nf id ()]
, env (return ()) $
\ ~() -> bgroup "'oops'" [bench "dummy" $ nf id ()]
]
| bos/criterion | examples/Quotes.hs | bsd-2-clause | 266 | 0 | 13 | 75 | 126 | 63 | 63 | 9 | 1 |
module Database.Narc.Rewrite where
import Data.Maybe (fromMaybe)
import Database.Narc.AST
import Database.Narc.Type
import Database.Narc.Util (alistmap)
-- | In @perhaps f x@, use @f@ to transform @x@, unless it declines by
-- returning @Nothing@, in which case return @x@ unchanged.
perhaps :: (a -> Maybe a) -> a -> a
perhaps f x = fromMaybe x (f x)
-- | Apply @f@ to each subterm of a given term, in a bottom-up fashion.
bu :: (Term a -> Maybe (Term a)) -> Term a -> Term a
bu f (Unit, d) = perhaps f (Unit, d)
bu f (Bool b, d) = perhaps f (Bool b, d)
bu f (Num n, d) = perhaps f (Num n, d)
bu f (Var x, d) = perhaps f (Var x, d)
bu f (Abs x n, d) = perhaps f (Abs x (bu f n), d)
bu f (App l m, d) = perhaps f (App (bu f l) (bu f m), d)
bu f (If c a b, d) =
perhaps f (If (bu f c)
(bu f a)
(bu f b), d)
bu f (Table tab fields, d) = perhaps f (Table tab fields, d)
bu f (Singleton m, d) = perhaps f (Singleton (bu f m), d)
bu f (Record fields, d) = perhaps f (Record (alistmap (bu f) fields), d)
bu f (Project m a, d) = perhaps f (Project (bu f m) a, d)
bu f (Comp x src body, d) = perhaps f (Comp x (bu f src) (bu f body), d)
bu f (PrimApp fun args, d) = perhaps f (PrimApp fun args, d)
bu f (Nil, d) = perhaps f (Nil, d)
bu f (Union a b, d) = perhaps f (Union a b, d)
-- | Small-step version of compilation: local rewrite rules applied
-- willy-nilly. (Incomplete?)
rw (Comp x (Singleton m, _) n, t) = Just (substTerm x m n)
rw (App (Abs x n, st) m, t) = Just (substTerm x m n)
rw (Project (Record fields, rect) fld, t) = lookup fld fields
rw (Singleton (Var x, xT), t) = Nothing -- for now
rw (Comp x (Nil, _) n, t) = Just (Nil, t)
rw (Comp x m (Nil, _), t) = Just (Nil, t)
rw (Comp x (Comp y l m, s) n, t) =
if y `notElem` fvs n then
Just (Comp y l (Comp x m n, t), t)
else Nothing
rw (Comp x (m1 `Union` m2, s) n, t) =
Just ((Comp x m1 n, t) `Union` (Comp x m2 n, t), t)
rw (Comp x m (n1 `Union` n2, _), t) =
Just ((Comp x m n1, t) `Union` (Comp x m n2, t), t)
rw (Comp x (If b m (Nil, _), _) n, t) =
Just (Comp x m (If b n (Nil, t), t), t)
rw (If (b, bTy) m n, t@(TList _, _)) | fst n /= Nil =
Just((If (b,bTy) m (Nil, t), t) `Union`
(If (PrimApp "not" [(b, bTy)], bTy) n (Nil, t), t), t)
rw (If b (Nil, _) (Nil, _), t) = Just (Nil, t)
rw (If b (Comp x m n, _) (Nil, _), t) = Just (Comp x m (If b n (Nil, t), t), t)
rw (If b (m1 `Union` m2, _) (Nil, _), t) =
Just ((If b m1 (Nil, t), t) `Union` (If b m2 (Nil, t), t), t)
-- push App inside If
-- push Project inside If
-- push If inside Record
-- rw (IsEmpty m, t)
-- | lorob t = Nothing
-- | otherwise =
-- IsEmpty (Comp "x" m (Singleton (Unit, TUnit), TList Tunit), TList TUnit)
rw _ = Nothing
| ezrakilty/narc | Database/Narc/Rewrite.hs | bsd-2-clause | 2,786 | 0 | 14 | 743 | 1,620 | 877 | 743 | 50 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.