code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE Trustworthy #-}
{-# OPTIONS_HADDOCK hide #-}
-- we hide this module from haddock to enforce GHC.Stack as the main
-- access point.
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Stack.Types
-- Copyright : (c) The University of Glasgow 2015
-- License : see libraries/ghc-prim/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- type definitions for implicit call-stacks.
-- Use "GHC.Stack" from the base package instead of importing this
-- module directly.
--
-----------------------------------------------------------------------------
module GHC.Stack.Types (
-- * Implicit call stacks
CallStack(..), HasCallStack,
emptyCallStack, freezeCallStack, fromCallSiteList,
getCallStack, pushCallStack,
-- * Source locations
SrcLoc(..)
) where
{-
Ideally these would live in GHC.Stack but sadly they can't due to this
import cycle,
Module imports form a cycle:
module ‘Data.Maybe’ (libraries/base/Data/Maybe.hs)
imports ‘GHC.Base’ (libraries/base/GHC/Base.hs)
which imports ‘GHC.Err’ (libraries/base/GHC/Err.hs)
which imports ‘GHC.Stack’ (libraries/base/dist-install/build/GHC/Stack.hs)
which imports ‘GHC.Foreign’ (libraries/base/GHC/Foreign.hs)
which imports ‘Data.Maybe’ (libraries/base/Data/Maybe.hs)
-}
import GHC.Classes (Eq)
import GHC.Types (Char, Int)
-- Make implicit dependency known to build system
import GHC.Tuple ()
import GHC.Integer ()
----------------------------------------------------------------------
-- Explicit call-stacks built via ImplicitParams
----------------------------------------------------------------------
-- | Request a CallStack.
--
-- NOTE: The implicit parameter @?callStack :: CallStack@ is an
-- implementation detail and __should not__ be considered part of the
-- 'CallStack' API, we may decide to change the implementation in the
-- future.
--
-- @since 4.9.0.0
type HasCallStack = (?callStack :: CallStack)
-- | 'CallStack's are a lightweight method of obtaining a
-- partial call-stack at any point in the program.
--
-- A function can request its call-site with the 'HasCallStack' constraint.
-- For example, we can define
--
-- @
-- errorWithCallStack :: HasCallStack => String -> a
-- @
--
-- as a variant of @error@ that will get its call-site. We can access the
-- call-stack inside @errorWithCallStack@ with 'GHC.Stack.callStack'.
--
-- @
-- errorWithCallStack :: HasCallStack => String -> a
-- errorWithCallStack msg = error (msg ++ "\n" ++ prettyCallStack callStack)
-- @
--
-- Thus, if we call @errorWithCallStack@ we will get a formatted call-stack
-- alongside our error message.
--
--
-- >>> errorWithCallStack "die"
-- *** Exception: die
-- CallStack (from HasCallStack):
-- errorWithCallStack, called at <interactive>:2:1 in interactive:Ghci1
--
--
-- GHC solves 'HasCallStack' constraints in three steps:
--
-- 1. If there is a 'CallStack' in scope -- i.e. the enclosing function
-- has a 'HasCallStack' constraint -- GHC will append the new
-- call-site to the existing 'CallStack'.
--
-- 2. If there is no 'CallStack' in scope -- e.g. in the GHCi session
-- above -- and the enclosing definition does not have an explicit
-- type signature, GHC will infer a 'HasCallStack' constraint for the
-- enclosing definition (subject to the monomorphism restriction).
--
-- 3. If there is no 'CallStack' in scope and the enclosing definition
-- has an explicit type signature, GHC will solve the 'HasCallStack'
-- constraint for the singleton 'CallStack' containing just the
-- current call-site.
--
-- 'CallStack's do not interact with the RTS and do not require compilation
-- with @-prof@. On the other hand, as they are built up explicitly via the
-- 'HasCallStack' constraints, they will generally not contain as much
-- information as the simulated call-stacks maintained by the RTS.
--
-- A 'CallStack' is a @[(String, SrcLoc)]@. The @String@ is the name of
-- function that was called, the 'SrcLoc' is the call-site. The list is
-- ordered with the most recently called function at the head.
--
-- NOTE: The intrepid user may notice that 'HasCallStack' is just an
-- alias for an implicit parameter @?callStack :: CallStack@. This is an
-- implementation detail and __should not__ be considered part of the
-- 'CallStack' API, we may decide to change the implementation in the
-- future.
--
-- @since 4.8.1.0
data CallStack
= EmptyCallStack
| PushCallStack [Char] SrcLoc CallStack
| FreezeCallStack CallStack
-- ^ Freeze the stack at the given @CallStack@, preventing any further
-- call-sites from being pushed onto it.
-- See Note [Overview of implicit CallStacks]
-- | Extract a list of call-sites from the 'CallStack'.
--
-- The list is ordered by most recent call.
--
-- @since 4.8.1.0
getCallStack :: CallStack -> [([Char], SrcLoc)]
getCallStack stk = case stk of
EmptyCallStack -> []
PushCallStack fn loc stk' -> (fn,loc) : getCallStack stk'
FreezeCallStack stk' -> getCallStack stk'
-- | Convert a list of call-sites to a 'CallStack'.
--
-- @since 4.9.0.0
fromCallSiteList :: [([Char], SrcLoc)] -> CallStack
fromCallSiteList ((fn,loc):cs) = PushCallStack fn loc (fromCallSiteList cs)
fromCallSiteList [] = EmptyCallStack
-- Note [Definition of CallStack]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- CallStack is defined very early in base because it is
-- used by error and undefined. At this point in the dependency graph,
-- we do not have enough functionality to (conveniently) write a nice
-- pretty-printer for CallStack. The sensible place to define the
-- pretty-printer would be GHC.Stack, which is the main access point,
-- but unfortunately GHC.Stack imports GHC.Exception, which *needs*
-- the pretty-printer. So the CallStack type and functions are split
-- between three modules:
--
-- 1. GHC.Stack.Types: defines the type and *simple* functions
-- 2. GHC.Exception: defines the pretty-printer
-- 3. GHC.Stack: exports everything and acts as the main access point
-- | Push a call-site onto the stack.
--
-- This function has no effect on a frozen 'CallStack'.
--
-- @since 4.9.0.0
pushCallStack :: ([Char], SrcLoc) -> CallStack -> CallStack
pushCallStack (fn, loc) stk = case stk of
FreezeCallStack _ -> stk
_ -> PushCallStack fn loc stk
{-# INLINE pushCallStack #-}
-- | The empty 'CallStack'.
--
-- @since 4.9.0.0
emptyCallStack :: CallStack
emptyCallStack = EmptyCallStack
{-# INLINE emptyCallStack #-}
-- | Freeze a call-stack, preventing any further call-sites from being appended.
--
-- prop> pushCallStack callSite (freezeCallStack callStack) = freezeCallStack callStack
--
-- @since 4.9.0.0
freezeCallStack :: CallStack -> CallStack
freezeCallStack stk = FreezeCallStack stk
{-# INLINE freezeCallStack #-}
-- | A single location in the source code.
--
-- @since 4.8.1.0
data SrcLoc = SrcLoc
{ srcLocPackage :: [Char]
, srcLocModule :: [Char]
, srcLocFile :: [Char]
, srcLocStartLine :: Int
, srcLocStartCol :: Int
, srcLocEndLine :: Int
, srcLocEndCol :: Int
} deriving Eq
|
tolysz/prepare-ghcjs
|
spec-lts8/base/GHC/Stack/Types.hs
|
bsd-3-clause
| 7,471 | 0 | 9 | 1,319 | 561 | 386 | 175 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, PatternGuards #-}
{- | Implements a proof state, some primitive tactics for manipulating
proofs, and some high level commands for introducing new theorems,
evaluation/checking inside the proof system, etc.
-}
module Idris.Core.ProofTerm(ProofTerm, Goal(..), mkProofTerm, getProofTerm,
resetProofTerm,
updateSolved, updateSolvedTerm, updateSolvedTerm',
bound_in, bound_in_term, refocus, updsubst,
Hole, RunTactic',
goal, atHole) where
import Idris.Core.Typecheck
import Idris.Core.Evaluate
import Idris.Core.TT
import Control.Monad.State.Strict
import Data.List
import Debug.Trace
-- | A zipper over terms, in order to efficiently update proof terms.
data TermPath = Top
| AppL (AppStatus Name) TermPath Term
| AppR (AppStatus Name) Term TermPath
| InBind Name BinderPath Term
| InScope Name (Binder Term) TermPath
deriving Show
-- | A zipper over binders, because terms and binders are mutually defined.
data BinderPath = Binder (Binder TermPath)
| LetT TermPath Term
| LetV Term TermPath
| GuessT TermPath Term
| GuessV Term TermPath
deriving Show
-- | Replace the top of a term path with another term path. In other
-- words, "graft" one term path into another.
replaceTop :: TermPath -> TermPath -> TermPath
replaceTop p Top = p
replaceTop p (AppL s l t) = AppL s (replaceTop p l) t
replaceTop p (AppR s t r) = AppR s t (replaceTop p r)
replaceTop p (InBind n bp sc) = InBind n (replaceTopB p bp) sc
where
replaceTopB p (Binder b) = Binder (fmap (replaceTop p) b)
replaceTopB p (LetT t v) = LetT (replaceTop p t) v
replaceTopB p (LetV t v) = LetV t (replaceTop p v)
replaceTopB p (GuessT t v) = GuessT (replaceTop p t) v
replaceTopB p (GuessV t v) = GuessV t (replaceTop p v)
replaceTop p (InScope n b sc) = InScope n b (replaceTop p sc)
-- | Build a term from a zipper, given something to put in the hole.
rebuildTerm :: Term -> TermPath -> Term
rebuildTerm tm Top = tm
rebuildTerm tm (AppL s p a) = App s (rebuildTerm tm p) a
rebuildTerm tm (AppR s f p) = App s f (rebuildTerm tm p)
rebuildTerm tm (InScope n b p) = Bind n b (rebuildTerm tm p)
rebuildTerm tm (InBind n bp sc) = Bind n (rebuildBinder tm bp) sc
-- | Build a binder from a zipper, given something to put in the hole.
rebuildBinder :: Term -> BinderPath -> Binder Term
rebuildBinder tm (Binder p) = fmap (rebuildTerm tm) p
rebuildBinder tm (LetT p t) = Let (rebuildTerm tm p) t
rebuildBinder tm (LetV v p) = Let v (rebuildTerm tm p)
rebuildBinder tm (GuessT p t) = Guess (rebuildTerm tm p) t
rebuildBinder tm (GuessV v p) = Guess v (rebuildTerm tm p)
-- | Find the binding of a hole in a term. If present, return the path
-- to the hole's binding, the environment extended by the binders that
-- are crossed, and the actual binding term.
findHole :: Name -> Env -> Term -> Maybe (TermPath, Env, Term)
findHole n env t = fh' env Top t where
fh' env path tm@(Bind x h sc)
| hole h && n == x = Just (path, env, tm)
fh' env path (App Complete _ _) = Nothing
fh' env path (App s f a)
| Just (p, env', tm) <- fh' env path a = Just (AppR s f p, env', tm)
| Just (p, env', tm) <- fh' env path f = Just (AppL s p a, env', tm)
fh' env path (Bind x b sc)
| Just (bp, env', tm) <- fhB env path b = Just (InBind x bp sc, env', tm)
| Just (p, env', tm) <- fh' ((x,b):env) path sc = Just (InScope x b p, env', tm)
fh' _ _ _ = Nothing
fhB env path (Let t v)
| Just (p, env', tm) <- fh' env path t = Just (LetT p v, env', tm)
| Just (p, env', tm) <- fh' env path v = Just (LetV t p, env', tm)
fhB env path (Guess t v)
| Just (p, env', tm) <- fh' env path t = Just (GuessT p v, env', tm)
| Just (p, env', tm) <- fh' env path v = Just (GuessV t p, env', tm)
fhB env path b
| Just (p, env', tm) <- fh' env path (binderTy b)
= Just (Binder (fmap (\_ -> p) b), env', tm)
fhB _ _ _ = Nothing
data ProofTerm = PT { -- wholeterm :: Term,
path :: TermPath,
subterm_env :: Env,
subterm :: Term,
updates :: [(Name, Term)] }
deriving Show
type RunTactic' a = Context -> Env -> Term -> StateT a TC Term
type Hole = Maybe Name -- Nothing = default hole, first in list in proof state
-- | Refocus the proof term zipper on a particular hole, if it
-- exists. If not, return the original proof term.
refocus :: Hole -> ProofTerm -> ProofTerm
refocus h t = let res = refocus' h t in res
-- trace ("OLD: " ++ show t ++ "\n" ++
-- "REFOCUSSED " ++ show h ++ ": " ++ show res) res
refocus' (Just n) pt@(PT path env tm ups)
-- First look for the hole in the proof term as-is
| Just (p', env', tm') <- findHole n env tm
= PT (replaceTop p' path) env' tm' ups
-- If it's not there, rebuild and look from the top
| Just (p', env', tm') <- findHole n [] (rebuildTerm tm (updateSolvedPath ups path))
= PT p' env' tm' []
| otherwise = pt
refocus' _ pt = pt
data Goal = GD { premises :: Env,
goalType :: Binder Term
}
mkProofTerm :: Term -> ProofTerm
mkProofTerm tm = PT Top [] tm []
getProofTerm :: ProofTerm -> Term
getProofTerm (PT path _ sub ups) = rebuildTerm sub (updateSolvedPath ups path)
resetProofTerm :: ProofTerm -> ProofTerm
resetProofTerm = mkProofTerm . getProofTerm
same :: Eq a => Maybe a -> a -> Bool
same Nothing n = True
same (Just x) n = x == n
-- | Is a particular binder a hole or a guess?
hole :: Binder b -> Bool
hole (Hole _) = True
hole (Guess _ _) = True
hole _ = False
-- | Given a list of solved holes, fill out the solutions in a term
updateSolvedTerm :: [(Name, Term)] -> Term -> Term
updateSolvedTerm xs x = fst $ updateSolvedTerm' xs x
-- | Given a list of solved holes, fill out the solutions in a
-- term. Return whether updates were performed, to facilitate sharing
-- when there are no updates.
updateSolvedTerm' :: [(Name, Term)] -> Term -> (Term, Bool)
updateSolvedTerm' [] x = (x, False)
updateSolvedTerm' xs x = updateSolved' xs x where
-- This version below saves allocations, because it doesn't need to reallocate
-- the term if there are no updates to do.
-- The Bool is ugly, and probably 'Maybe' would be less ugly, but >>= is
-- the wrong combinator. Feel free to tidy up as long as it's still as cheap :).
updateSolved' [] x = (x, False)
updateSolved' xs (Bind n (Hole ty) t)
| Just v <- lookup n xs
= case xs of
[_] -> (updsubst n v t, True) -- some may be Vs! Can't assume
-- explicit names
_ -> let (t', _) = updateSolved' xs t in
(updsubst n v t', True)
updateSolved' xs tm@(Bind n b t)
| otherwise = let (t', ut) = updateSolved' xs t
(b', ub) = updateSolvedB' xs b in
if ut || ub then (Bind n b' t', True)
else (tm, False)
updateSolved' xs t@(App Complete f a) = (t, False)
updateSolved' xs t@(App s f a)
= let (f', uf) = updateSolved' xs f
(a', ua) = updateSolved' xs a in
if uf || ua then (App s f' a', True)
else (t, False)
updateSolved' xs t@(P _ n@(MN _ _) _)
| Just v <- lookup n xs = (v, True)
updateSolved' xs t@(P nt n ty)
= let (ty', ut) = updateSolved' xs ty in
if ut then (P nt n ty', True) else (t, False)
updateSolved' xs t = (t, False)
updateSolvedB' xs b@(Let t v) = let (t', ut) = updateSolved' xs t
(v', uv) = updateSolved' xs v in
if ut || uv then (Let t' v', True)
else (b, False)
updateSolvedB' xs b@(Guess t v) = let (t', ut) = updateSolved' xs t
(v', uv) = updateSolved' xs v in
if ut || uv then (Guess t' v', True)
else (b, False)
updateSolvedB' xs b = let (ty', u) = updateSolved' xs (binderTy b) in
if u then (b { binderTy = ty' }, u) else (b, False)
noneOf ns (P _ n _) | n `elem` ns = False
noneOf ns (App s f a) = noneOf ns a && noneOf ns f
noneOf ns (Bind n (Hole ty) t) = n `notElem` ns && noneOf ns ty && noneOf ns t
noneOf ns (Bind n b t) = noneOf ns t && noneOfB ns b
where
noneOfB ns (Let t v) = noneOf ns t && noneOf ns v
noneOfB ns (Guess t v) = noneOf ns t && noneOf ns v
noneOfB ns b = noneOf ns (binderTy b)
noneOf ns _ = True
-- | As 'subst', in TT, but takes advantage of knowing not to substitute
-- under Complete applications.
updsubst :: Eq n => n {-^ The id to replace -} ->
TT n {-^ The replacement term -} ->
TT n {-^ The term to replace in -} ->
TT n
-- subst n v tm = instantiate v (pToV n tm)
updsubst n v tm = fst $ subst' 0 tm
where
-- keep track of updates to save allocations - this is a big win on
-- large terms in particular
-- ('Maybe' would be neater here, but >>= is not the right combinator.
-- Feel free to tidy up, as long as it still saves allocating when no
-- substitution happens...)
subst' i (V x) | i == x = (v, True)
subst' i (P _ x _) | n == x = (v, True)
subst' i t@(P nt x ty)
= let (ty', ut) = subst' i ty in
if ut then (P nt x ty', True) else (t, False)
subst' i t@(Bind x b sc) | x /= n
= let (b', ub) = substB' i b
(sc', usc) = subst' (i+1) sc in
if ub || usc then (Bind x b' sc', True) else (t, False)
subst' i t@(App Complete f a) = (t, False)
subst' i t@(App s f a) = let (f', uf) = subst' i f
(a', ua) = subst' i a in
if uf || ua then (App s f' a', True) else (t, False)
subst' i t@(Proj x idx) = let (x', u) = subst' i x in
if u then (Proj x' idx, u) else (t, False)
subst' i t = (t, False)
substB' i b@(Let t v) = let (t', ut) = subst' i t
(v', uv) = subst' i v in
if ut || uv then (Let t' v', True)
else (b, False)
substB' i b@(Guess t v) = let (t', ut) = subst' i t
(v', uv) = subst' i v in
if ut || uv then (Guess t' v', True)
else (b, False)
substB' i b = let (ty', u) = subst' i (binderTy b) in
if u then (b { binderTy = ty' }, u) else (b, False)
-- | Apply solutions to an environment.
updateEnv :: [(Name, Term)] -> Env -> Env
updateEnv [] e = e
updateEnv ns [] = []
updateEnv ns ((n, b) : env) = (n, fmap (updateSolvedTerm ns) b) : updateEnv ns env
-- | Fill out solved holes in a term zipper.
updateSolvedPath :: [(Name, Term)] -> TermPath -> TermPath
updateSolvedPath [] t = t
updateSolvedPath ns Top = Top
updateSolvedPath ns t@(AppL Complete _ _) = t
updateSolvedPath ns t@(AppR Complete _ _) = t
updateSolvedPath ns (AppL s p r) = AppL s (updateSolvedPath ns p) (updateSolvedTerm ns r)
updateSolvedPath ns (AppR s l p) = AppR s (updateSolvedTerm ns l) (updateSolvedPath ns p)
updateSolvedPath ns (InBind n b sc)
= InBind n (updateSolvedPathB b) (updateSolvedTerm ns sc)
where
updateSolvedPathB (Binder b) = Binder (fmap (updateSolvedPath ns) b)
updateSolvedPathB (LetT p v) = LetT (updateSolvedPath ns p) (updateSolvedTerm ns v)
updateSolvedPathB (LetV v p) = LetV (updateSolvedTerm ns v) (updateSolvedPath ns p)
updateSolvedPathB (GuessT p v) = GuessT (updateSolvedPath ns p) (updateSolvedTerm ns v)
updateSolvedPathB (GuessV v p) = GuessV (updateSolvedTerm ns v) (updateSolvedPath ns p)
updateSolvedPath ns (InScope n (Hole ty) t)
| Just v <- lookup n ns = case ns of
[_] -> updateSolvedPath [(n,v)] t
_ -> updateSolvedPath ns $
updateSolvedPath [(n,v)] t
updateSolvedPath ns (InScope n b sc)
= InScope n (fmap (updateSolvedTerm ns) b) (updateSolvedPath ns sc)
updateSolved :: [(Name, Term)] -> ProofTerm -> ProofTerm
updateSolved xs pt@(PT path env sub ups)
= PT path -- (updateSolvedPath xs path)
(updateEnv xs (filter (\(n, t) -> n `notElem` map fst xs) env))
(updateSolvedTerm xs sub)
(ups ++ xs)
goal :: Hole -> ProofTerm -> TC Goal
goal h pt@(PT path env sub ups)
-- | OK ginf <- g env sub = return ginf
| otherwise = g [] (rebuildTerm sub (updateSolvedPath ups path))
where
g :: Env -> Term -> TC Goal
g env (Bind n b@(Guess _ _) sc)
| same h n = return $ GD env b
| otherwise
= gb env b `mplus` g ((n, b):env) sc
g env (Bind n b sc) | hole b && same h n = return $ GD env b
| otherwise
= g ((n, b):env) sc `mplus` gb env b
g env (App Complete f a) = fail "Can't find hole"
g env (App _ f a) = g env a `mplus` g env f
g env t = fail "Can't find hole"
gb env (Let t v) = g env v `mplus` g env t
gb env (Guess t v) = g env v `mplus` g env t
gb env t = g env (binderTy t)
atHole :: Hole -> RunTactic' a -> Context -> Env -> ProofTerm ->
StateT a TC (ProofTerm, Bool)
atHole h f c e pt -- @(PT path env sub)
= do let PT path env sub ups = refocus h pt
(tm, u) <- atH f c env sub
return (PT path env tm ups, u)
-- if u then return (PT path env tm ups, u)
-- else do let PT path env sub ups = refocus h pt
-- (tm, u) <- atH f c env sub
-- return (PT path env tm ups, u)
where
updated o = do o' <- o
return (o', True)
ulift2 f c env op a b
= do (b', u) <- atH f c env b
if u then return (op a b', True)
else do (a', u) <- atH f c env a
return (op a' b', u)
-- Search the things most likely to contain the binding first!
atH :: RunTactic' a -> Context -> Env -> Term -> StateT a TC (Term, Bool)
atH f c env binder@(Bind n b@(Guess t v) sc)
| same h n = updated (f c env binder)
| otherwise
= do -- binder first
(b', u) <- ulift2 f c env Guess t v
if u then return (Bind n b' sc, True)
else do (sc', u) <- atH f c ((n, b) : env) sc
return (Bind n b' sc', u)
atH f c env binder@(Bind n b sc)
| hole b && same h n = updated (f c env binder)
| otherwise -- scope first
= do (sc', u) <- atH f c ((n, b) : env) sc
if u then return (Bind n b sc', True)
else do (b', u) <- atHb f c env b
return (Bind n b' sc', u)
atH tac c env (App s f a) = ulift2 tac c env (App s) f a
atH tac c env t = return (t, False)
atHb f c env (Let t v) = ulift2 f c env Let t v
atHb f c env (Guess t v) = ulift2 f c env Guess t v
atHb f c env t = do (ty', u) <- atH f c env (binderTy t)
return (t { binderTy = ty' }, u)
bound_in :: ProofTerm -> [Name]
bound_in (PT path _ tm ups) = bound_in_term (rebuildTerm tm (updateSolvedPath ups path))
bound_in_term :: Term -> [Name]
bound_in_term (Bind n b sc) = n : bi b ++ bound_in_term sc
where
bi (Let t v) = bound_in_term t ++ bound_in_term v
bi (Guess t v) = bound_in_term t ++ bound_in_term v
bi b = bound_in_term (binderTy b)
bound_in_term (App _ f a) = bound_in_term f ++ bound_in_term a
bound_in_term _ = []
|
mrmonday/Idris-dev
|
src/Idris/Core/ProofTerm.hs
|
bsd-3-clause
| 16,383 | 5 | 17 | 5,655 | 6,196 | 3,191 | 3,005 | 272 | 23 |
{-# LANGUAGE TypeFamilies #-}
module T3990 where
data family Complex a
data instance Complex Double = CD {-# UNPACK #-} !Double
{-# UNPACK #-} !Double
data T = T {-# UNPACK #-} !(Complex Double)
-- This shouuld actually get unpacked!
test_case :: T
test_case = T (CD 1 1)
|
ezyang/ghc
|
testsuite/tests/simplCore/should_compile/T3990.hs
|
bsd-3-clause
| 309 | 0 | 9 | 86 | 69 | 39 | 30 | 8 | 1 |
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Control.Exception
import qualified Data.ByteString.Lazy as DBL
import qualified Data.HashMap.Strict as Map
import qualified Data.HashSet as Set
import qualified Data.Vector as Vector
import qualified Network
import Thrift.Protocol.Binary
import Thrift.Server
import Thrift.Transport.Handle
import qualified ThriftTestUtils
import qualified DebugProtoTest_Types as Types
import qualified Inherited
import qualified Inherited_Client as IClient
import qualified Inherited_Iface as IIface
import qualified Srv_Client as SClient
import qualified Srv_Iface as SIface
-- we don't actually need this import, but force it to check the code generator exports proper Haskell syntax
import qualified Srv()
data InheritedHandler = InheritedHandler
instance SIface.Srv_Iface InheritedHandler where
janky _ arg = do
ThriftTestUtils.serverLog $ "Got janky method call: " ++ show arg
return $ 31
voidMethod _ = do
ThriftTestUtils.serverLog "Got voidMethod method call"
return ()
primitiveMethod _ = do
ThriftTestUtils.serverLog "Got primitiveMethod call"
return $ 42
structMethod _ = do
ThriftTestUtils.serverLog "Got structMethod call"
return $ Types.CompactProtoTestStruct {
Types.compactProtoTestStruct_a_byte = 0x01,
Types.compactProtoTestStruct_a_i16 = 0x02,
Types.compactProtoTestStruct_a_i32 = 0x03,
Types.compactProtoTestStruct_a_i64 = 0x04,
Types.compactProtoTestStruct_a_double = 0.1,
Types.compactProtoTestStruct_a_string = "abcdef",
Types.compactProtoTestStruct_a_binary = DBL.empty,
Types.compactProtoTestStruct_true_field = True,
Types.compactProtoTestStruct_false_field = False,
Types.compactProtoTestStruct_empty_struct_field = Types.Empty,
Types.compactProtoTestStruct_byte_list = Vector.empty,
Types.compactProtoTestStruct_i16_list = Vector.empty,
Types.compactProtoTestStruct_i32_list = Vector.empty,
Types.compactProtoTestStruct_i64_list = Vector.empty,
Types.compactProtoTestStruct_double_list = Vector.empty,
Types.compactProtoTestStruct_string_list = Vector.empty,
Types.compactProtoTestStruct_binary_list = Vector.empty,
Types.compactProtoTestStruct_boolean_list = Vector.empty,
Types.compactProtoTestStruct_struct_list = Vector.empty,
Types.compactProtoTestStruct_byte_set = Set.empty,
Types.compactProtoTestStruct_i16_set = Set.empty,
Types.compactProtoTestStruct_i32_set = Set.empty,
Types.compactProtoTestStruct_i64_set = Set.empty,
Types.compactProtoTestStruct_double_set = Set.empty,
Types.compactProtoTestStruct_string_set = Set.empty,
Types.compactProtoTestStruct_binary_set = Set.empty,
Types.compactProtoTestStruct_boolean_set = Set.empty,
Types.compactProtoTestStruct_struct_set = Set.empty,
Types.compactProtoTestStruct_byte_byte_map = Map.empty,
Types.compactProtoTestStruct_i16_byte_map = Map.empty,
Types.compactProtoTestStruct_i32_byte_map = Map.empty,
Types.compactProtoTestStruct_i64_byte_map = Map.empty,
Types.compactProtoTestStruct_double_byte_map = Map.empty,
Types.compactProtoTestStruct_string_byte_map = Map.empty,
Types.compactProtoTestStruct_binary_byte_map = Map.empty,
Types.compactProtoTestStruct_boolean_byte_map = Map.empty,
Types.compactProtoTestStruct_byte_i16_map = Map.empty,
Types.compactProtoTestStruct_byte_i32_map = Map.empty,
Types.compactProtoTestStruct_byte_i64_map = Map.empty,
Types.compactProtoTestStruct_byte_double_map = Map.empty,
Types.compactProtoTestStruct_byte_string_map = Map.empty,
Types.compactProtoTestStruct_byte_binary_map = Map.empty,
Types.compactProtoTestStruct_byte_boolean_map = Map.empty,
Types.compactProtoTestStruct_list_byte_map = Map.empty,
Types.compactProtoTestStruct_set_byte_map = Map.empty,
Types.compactProtoTestStruct_map_byte_map = Map.empty,
Types.compactProtoTestStruct_byte_map_map = Map.empty,
Types.compactProtoTestStruct_byte_set_map = Map.empty,
Types.compactProtoTestStruct_byte_list_map = Map.empty }
methodWithDefaultArgs _ arg = do
ThriftTestUtils.serverLog $ "Got methodWithDefaultArgs: " ++ show arg
return ()
onewayMethod _ = do
ThriftTestUtils.serverLog "Got onewayMethod"
instance IIface.Inherited_Iface InheritedHandler where
identity _ arg = do
ThriftTestUtils.serverLog $ "Got identity method: " ++ show arg
return arg
client :: (String, Network.PortID) -> IO ()
client addr = do
to <- hOpen addr
let p = BinaryProtocol to
let ps = (p,p)
v1 <- SClient.janky ps 42
ThriftTestUtils.clientLog $ show v1
SClient.voidMethod ps
v2 <- SClient.primitiveMethod ps
ThriftTestUtils.clientLog $ show v2
v3 <- SClient.structMethod ps
ThriftTestUtils.clientLog $ show v3
SClient.methodWithDefaultArgs ps 42
SClient.onewayMethod ps
v4 <- IClient.identity ps 42
ThriftTestUtils.clientLog $ show v4
return ()
server :: Network.PortNumber -> IO ()
server port = do
ThriftTestUtils.serverLog "Ready..."
(runBasicServer InheritedHandler Inherited.process port)
`Control.Exception.catch`
(\(TransportExn s _) -> error $ "FAILURE: " ++ show s)
main :: IO ()
main = ThriftTestUtils.runTest server client
|
jcgruenhage/dendrite
|
vendor/src/github.com/apache/thrift/test/hs/DebugProtoTest_Main.hs
|
apache-2.0
| 6,601 | 0 | 11 | 1,421 | 1,126 | 627 | 499 | 116 | 1 |
module Main where
import Control.Monad (when, (>=>))
import System.Environment (getArgs, getProgName)
data HelpKeyword = CheckKeyword
deriving Show
-- Available/possible sub-commands
data Command = Help { keyword :: Maybe HelpKeyword }
| Check { inputData :: String }
deriving Show
-- This is the verbosity level in general for the application,
-- including sub-commands like help, add, remove and check
data VerboseLevel = Quiet | Verbose | Debug deriving Show
-- These are general options that apply to the top-level of the
-- application and to sub-commands as well
data Opts = Opts { verbose :: VerboseLevel
, command :: Command
} deriving Show
-- A command line parser is a function that takes a list of arguments
-- (strings) and returns either a) an error or b) a result and the
-- remainder of the arguments
newtype CLParser a = CLParser ([String] -> Either String (a, [String]))
runCLParser :: CLParser a -> [String] -> Either String (a, [String])
runCLParser (CLParser p) = p
instance Monad CLParser where
return v = CLParser $ \i -> Right (v, i)
fail msg = CLParser $ \_ -> Left msg
p >>= f = CLParser $ runCLParser p >=> (\(x, r) -> runCLParser (f x) r)
(<++) :: Show a => CLParser a -> CLParser a -> CLParser a
CLParser p1 <++ CLParser p2 =
CLParser $ \i -> case p1 i of Left _ -> p2 i
Right x -> Right x
peek, item :: CLParser String
peek = CLParser $ \i@(x:_) -> Right (x, i)
item = CLParser $ \(x:xs) -> Right (x, xs)
isEnd :: CLParser Bool
isEnd = CLParser $ \i -> return (null i, i)
failEnd :: String -> CLParser ()
failEnd msg = isEnd >>= \e -> when e $ fail $ "Unexpected end of input: " ++ msg
defaultOpts :: Opts
defaultOpts = Opts { verbose = Quiet
, command = Help { keyword = Nothing }
}
main :: IO ()
main = do args <- getArgs
prog <- getProgName
putStrLn $ "hello" ++ unwords (map show args) ++ "foo" ++ prog
|
fredmorcos/attic
|
projects/pet/archive/pet_haskell_EitherIO/Main.hs
|
isc
| 2,058 | 0 | 12 | 568 | 635 | 347 | 288 | 37 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Pladen.App.Tar
(
tarResponse
, Archive
) where
import Control.Applicative
import Data.Maybe
import Data.Monoid
import Data.Char (ord, isDigit)
import Data.Text.Encoding (decodeUtf8)
import Blaze.ByteString.Builder (Builder, fromByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Conduit
import qualified Data.Conduit.List as CL
import Text.Parsec.Text (Parser)
import Text.Parsec.Char
import Text.Parsec (parse)
import Network.Wai
import Network.HTTP.Types.Status
import Network.HTTP.Types.Header
import Network.HTTP.Types.Method
import Pladen.Tar
tarResponse :: ResponseHeaders
-- ^ Additional headers for the reponse
-> Archive
-> Request
-> IO Response
tarResponse h a req =
responseSourceBracket (openEntries a)
teardown
(respond defFallback h req)
defFallback :: BracketResponse
defFallback = (status404, [], mempty)
-- | Close all handles
teardown :: Maybe [FileEntryHandle] -> IO ()
teardown = maybe (return ()) (mapM_ closeEntry)
type BracketResponse = (Status, ResponseHeaders, Source IO (Flush Builder))
respond :: BracketResponse
-- ^ Fallback response if file entries
-- could not be opened
-> ResponseHeaders
-- ^ Additional headers for tar response
-> Request
-> Maybe [FileEntryHandle]
-> IO BracketResponse
respond fb h req = maybe (return fb) (fmap modify . respond' req)
where modify (st, h', src) = (st, h' ++ h, src)
respond' :: Request
-> [FileEntryHandle]
-> IO BracketResponse
respond' req hs = do
size <- sum <$> mapM entrySize hs
let headers' = headers start size
let okStatus | start == 0 = ok200
| otherwise = partialContent206
let method = requestMethod req
let res | method == methodGet = (okStatus, headers', source hs)
| method == methodHead = (okStatus, headers', mempty)
| otherwise = (status405, [], mempty)
return res
where
start = fromMaybe 0 $ do
range <- lookup hRange (requestHeaders req)
parseMaybe rangeParser range
source :: [FileEntryHandle] -> Source IO (Flush Builder)
source hs' = (mconcat $ map entrySource hs')
=$ consume (fromIntegral start)
headers :: Integer -> Integer -> ResponseHeaders
headers from full =
[ (hContentType, "application/x-tar")
, (hContentLength, BS.pack $ show (full - from) )
] ++ if from == 0
then [(hContentRange, contentRange from full)]
else []
contentRange from full = BS.pack $ "bytes " ++ show from
++ "-" ++ show (full-1)
++ "/" ++ show full
hContentRange = "Content-Range"
-- | Drop the first /n/ bytes and converts the rest to builders.
consume :: Int -> Conduit (Flush BS.ByteString) IO (Flush Builder)
consume n =
awaitForever $ \input ->
case input of
Chunk input' ->
let remaining = BS.drop n input' in
if BS.length remaining > 0
then do yield (Chunk $ fromByteString remaining)
CL.map (fmap fromByteString)
else consume (n - BS.length input')
_ -> yield Flush >> consume n
-- | Parse the content of the /Range/ header per
-- <http://tools.ietf.org/html/rfc2616#section-14.35 RFC 2616>.
rangeParser :: Parser Integer
rangeParser = string "bytes=" >> takePosDigit >>= add
where
add :: Integer -> Parser Integer
add x = (takeAddDigit x >>= add) <|> return x
takeAddDigit :: Integer -> Parser Integer
takeAddDigit x = (10*x +) <$> takeDigit
takeDigit :: Parser Integer
takeDigit = toInt <$> satisfy isDigit
takePosDigit :: Parser Integer
takePosDigit = toInt <$> satisfy isPosDigit
isPosDigit a = isDigit a && a /= '0'
toInt :: Char -> Integer
toInt a = toInteger $ ord a - ord '0'
parseMaybe :: Parser a -> BS.ByteString -> Maybe a
parseMaybe p s = either (const Nothing) Just $ parse p "" (decodeUtf8 s)
|
geigerzaehler/pladen
|
Pladen/App/Tar.hs
|
mit
| 4,341 | 0 | 18 | 1,333 | 1,222 | 638 | 584 | 98 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE CPP #-}
module Hpack.Run (
run
, renderPackage
, RenderSettings(..)
, Alignment(..)
, CommaStyle(..)
, defaultRenderSettings
#ifdef TEST
, renderConditional
, renderFlag
, renderSourceRepository
, renderDirectories
, formatDescription
#endif
) where
import Prelude ()
import Prelude.Compat
import Control.Monad
import Data.Char
import Data.Maybe
import Data.List.Compat
import System.Exit.Compat
import System.FilePath
import Hpack.Util
import Hpack.Config
import Hpack.Render
import Hpack.FormattingHints
run :: Maybe FilePath -> FilePath -> IO ([String], FilePath, String)
run mDir c = do
let dir = fromMaybe "" mDir
mPackage <- readPackageConfig (dir </> c)
case mPackage of
Right (warnings, pkg) -> do
let cabalFile = dir </> (packageName pkg ++ ".cabal")
old <- tryReadFile cabalFile
let
FormattingHints{..} = sniffFormattingHints (fromMaybe "" old)
alignment = fromMaybe 16 formattingHintsAlignment
settings = formattingHintsRenderSettings
output = renderPackage settings alignment formattingHintsFieldOrder formattingHintsSectionsFieldOrder pkg
return (warnings, cabalFile, output)
Left err -> die err
renderPackage :: RenderSettings -> Alignment -> [String] -> [(String, [String])] -> Package -> String
renderPackage settings alignment existingFieldOrder sectionsFieldOrder Package{..} = intercalate "\n" (unlines header : chunks)
where
chunks :: [String]
chunks = map unlines . filter (not . null) . map (render settings 0) $ sortSectionFields sectionsFieldOrder stanzas
header :: [String]
header = concatMap (render settings {renderSettingsFieldAlignment = alignment} 0) fields
extraSourceFiles :: Element
extraSourceFiles = Field "extra-source-files" (LineSeparatedList packageExtraSourceFiles)
dataFiles :: Element
dataFiles = Field "data-files" (LineSeparatedList packageDataFiles)
sourceRepository :: [Element]
sourceRepository = maybe [] (return . renderSourceRepository) packageSourceRepository
customSetup :: [Element]
customSetup = maybe [] (return . renderCustomSetup) packageCustomSetup
library :: [Element]
library = maybe [] (return . renderLibrary) packageLibrary
stanzas :: [Element]
stanzas =
extraSourceFiles
: dataFiles
: sourceRepository
++ concat [
customSetup
, map renderFlag packageFlags
, library
, renderExecutables packageExecutables
, renderTests packageTests
, renderBenchmarks packageBenchmarks
]
fields :: [Element]
fields = sortFieldsBy existingFieldOrder . mapMaybe (\(name, value) -> Field name . Literal <$> value) $ [
("name", Just packageName)
, ("version", Just packageVersion)
, ("synopsis", packageSynopsis)
, ("description", (formatDescription alignment <$> packageDescription))
, ("category", packageCategory)
, ("stability", packageStability)
, ("homepage", packageHomepage)
, ("bug-reports", packageBugReports)
, ("author", formatList packageAuthor)
, ("maintainer", formatList packageMaintainer)
, ("copyright", formatList packageCopyright)
, ("license", packageLicense)
, case packageLicenseFile of
[file] -> ("license-file", Just file)
files -> ("license-files", formatList files)
, ("tested-with", packageTestedWith)
, ("build-type", Just (show packageBuildType))
, ("cabal-version", cabalVersion)
]
formatList :: [String] -> Maybe String
formatList xs = guard (not $ null xs) >> (Just $ intercalate separator xs)
where
separator = let Alignment n = alignment in ",\n" ++ replicate n ' '
cabalVersion :: Maybe String
cabalVersion = maximum [
Just ">= 1.10"
, packageLibrary >>= libCabalVersion
]
where
libCabalVersion :: Section Library -> Maybe String
libCabalVersion sect = ">= 1.21" <$ guard (hasReexportedModules sect)
hasReexportedModules :: Section Library -> Bool
hasReexportedModules = not . null . libraryReexportedModules . sectionData
sortSectionFields :: [(String, [String])] -> [Element] -> [Element]
sortSectionFields sectionsFieldOrder = go
where
go sections = case sections of
[] -> []
Stanza name fields : xs | Just fieldOrder <- lookup name sectionsFieldOrder -> Stanza name (sortFieldsBy fieldOrder fields) : go xs
x : xs -> x : go xs
formatDescription :: Alignment -> String -> String
formatDescription (Alignment alignment) description = case map emptyLineToDot $ lines description of
x : xs -> intercalate "\n" (x : map (indentation ++) xs)
[] -> ""
where
n = max alignment (length ("description: " :: String))
indentation = replicate n ' '
emptyLineToDot xs
| isEmptyLine xs = "."
| otherwise = xs
isEmptyLine = all isSpace
renderSourceRepository :: SourceRepository -> Element
renderSourceRepository SourceRepository{..} = Stanza "source-repository head" [
Field "type" "git"
, Field "location" (Literal sourceRepositoryUrl)
, Field "subdir" (maybe "" Literal sourceRepositorySubdir)
]
renderFlag :: Flag -> Element
renderFlag Flag {..} = Stanza ("flag " ++ flagName) $ description ++ [
Field "manual" (Literal $ show flagManual)
, Field "default" (Literal $ show flagDefault)
]
where
description = maybe [] (return . Field "description" . Literal) flagDescription
renderExecutables :: [Section Executable] -> [Element]
renderExecutables = map renderExecutable
renderExecutable :: Section Executable -> Element
renderExecutable sect@(sectionData -> Executable{..}) =
Stanza ("executable " ++ executableName) (renderExecutableSection sect)
renderTests :: [Section Executable] -> [Element]
renderTests = map renderTest
renderTest :: Section Executable -> Element
renderTest sect@(sectionData -> Executable{..}) =
Stanza ("test-suite " ++ executableName)
(Field "type" "exitcode-stdio-1.0" : renderExecutableSection sect)
renderBenchmarks :: [Section Executable] -> [Element]
renderBenchmarks = map renderBenchmark
renderBenchmark :: Section Executable -> Element
renderBenchmark sect@(sectionData -> Executable{..}) =
Stanza ("benchmark " ++ executableName)
(Field "type" "exitcode-stdio-1.0" : renderExecutableSection sect)
renderExecutableSection :: Section Executable -> [Element]
renderExecutableSection sect@(sectionData -> Executable{..}) =
mainIs : renderSection sect ++ [otherModules, defaultLanguage]
where
mainIs = Field "main-is" (Literal executableMain)
otherModules = renderOtherModules executableOtherModules
renderCustomSetup :: CustomSetup -> Element
renderCustomSetup CustomSetup{..} =
Stanza "custom-setup" [renderSetupDepends customSetupDependencies]
renderLibrary :: Section Library -> Element
renderLibrary sect@(sectionData -> Library{..}) = Stanza "library" $
renderSection sect ++
maybe [] (return . renderExposed) libraryExposed ++ [
renderExposedModules libraryExposedModules
, renderOtherModules libraryOtherModules
, renderReexportedModules libraryReexportedModules
, defaultLanguage
]
renderExposed :: Bool -> Element
renderExposed = Field "exposed" . Literal . show
renderSection :: Section a -> [Element]
renderSection Section{..} = [
renderDirectories "hs-source-dirs" sectionSourceDirs
, renderDefaultExtensions sectionDefaultExtensions
, renderOtherExtensions sectionOtherExtensions
, renderGhcOptions sectionGhcOptions
, renderGhcProfOptions sectionGhcProfOptions
, renderGhcjsOptions sectionGhcjsOptions
, renderCppOptions sectionCppOptions
, renderCcOptions sectionCcOptions
, renderDirectories "include-dirs" sectionIncludeDirs
, Field "install-includes" (LineSeparatedList sectionInstallIncludes)
, Field "c-sources" (LineSeparatedList sectionCSources)
, Field "js-sources" (LineSeparatedList sectionJsSources)
, renderDirectories "extra-lib-dirs" sectionExtraLibDirs
, Field "extra-libraries" (LineSeparatedList sectionExtraLibraries)
, renderLdOptions sectionLdOptions
, renderDependencies sectionDependencies
, renderBuildTools sectionBuildTools
]
++ maybe [] (return . renderBuildable) sectionBuildable
++ map renderConditional sectionConditionals
renderConditional :: Conditional -> Element
renderConditional (Conditional condition sect mElse) = case mElse of
Nothing -> if_
Just else_ -> Group if_ (Stanza "else" $ renderSection else_)
where
if_ = Stanza ("if " ++ condition) (renderSection sect)
defaultLanguage :: Element
defaultLanguage = Field "default-language" "Haskell2010"
renderDirectories :: String -> [String] -> Element
renderDirectories name = Field name . LineSeparatedList . replaceDots
where
replaceDots = map replaceDot
replaceDot xs = case xs of
"." -> "./."
_ -> xs
renderExposedModules :: [String] -> Element
renderExposedModules = Field "exposed-modules" . LineSeparatedList
renderOtherModules :: [String] -> Element
renderOtherModules = Field "other-modules" . LineSeparatedList
renderReexportedModules :: [String] -> Element
renderReexportedModules = Field "reexported-modules" . LineSeparatedList
renderDependencies :: [Dependency] -> Element
renderDependencies = Field "build-depends" . CommaSeparatedList . map dependencyName
renderGhcOptions :: [GhcOption] -> Element
renderGhcOptions = Field "ghc-options" . WordList
renderGhcProfOptions :: [GhcProfOption] -> Element
renderGhcProfOptions = Field "ghc-prof-options" . WordList
renderGhcjsOptions :: [GhcjsOption] -> Element
renderGhcjsOptions = Field "ghcjs-options" . WordList
renderCppOptions :: [CppOption] -> Element
renderCppOptions = Field "cpp-options" . WordList
renderCcOptions :: [CcOption] -> Element
renderCcOptions = Field "cc-options" . WordList
renderLdOptions :: [LdOption] -> Element
renderLdOptions = Field "ld-options" . WordList
renderBuildable :: Bool -> Element
renderBuildable = Field "buildable" . Literal . show
renderDefaultExtensions :: [String] -> Element
renderDefaultExtensions = Field "default-extensions" . WordList
renderOtherExtensions :: [String] -> Element
renderOtherExtensions = Field "other-extensions" . WordList
renderBuildTools :: [Dependency] -> Element
renderBuildTools = Field "build-tools" . CommaSeparatedList . map dependencyName
renderSetupDepends :: [Dependency] -> Element
renderSetupDepends = Field "setup-depends" . CommaSeparatedList . map dependencyName
|
mitchellwrosen/hpack
|
src/Hpack/Run.hs
|
mit
| 10,743 | 0 | 18 | 1,970 | 2,832 | 1,488 | 1,344 | 223 | 3 |
{-# htermination insert :: Ord a => a -> [a] -> [a] #-}
import List
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/List_insert_1.hs
|
mit
| 68 | 0 | 3 | 15 | 5 | 3 | 2 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Server.User where
import API.User
import API.Pagination
import User
import Util.JWT
import Util.Neo
import Util.Crypto
import Util.Server
import Server.Config
import Control.Applicative
import Control.Monad
import Control.Monad.Reader
import Control.Monad.Trans.Maybe
import Data.Aeson
import qualified Data.ByteString.Char8 as BSC
import Data.Int
import Data.Maybe
import Data.Text hiding (map)
import Database.Neo4j
import qualified Database.Neo4j.Transactional.Cypher as C
import qualified Data.HashMap.Lazy as HM
import Servant
import Servant.Server
import Web.JWT hiding (decode)
userServer :: ServerT UserAPI ConfigM
userServer = getAll
:<|> register
-- :<|> getSingle
:<|> updateUser
:<|> deleteUser
:<|> signIn
register :: Registration -> ConfigM (Encoded Authorization)
register (Registration email pw) = do
mHashed <- hashPassword pw
case mHashed of
Nothing -> errorOf err500
Just (HashedPW hashedPW) -> do
created <- runNeo $ do
existing <- getNodesByLabelAndProperty "User" $ Just ("email" |: fromEmail email)
case existing of
[] -> do
user <- createNode $ HM.fromList [ "email" |: fromEmail email
, "password" |: hashedPW
]
addLabels ["User"] user
return True
_ -> return False
unless created $ errorOf err409
secret <- asks jwtSecret
return $ Encoded (Authorization email) secret
signIn :: Email -> Maybe (Password Unhashed) -> ConfigM (Encoded Authorization)
signIn _ Nothing = errorOf err401
signIn email (Just unhashed) = do
mHash <- runNeo $ do
users <- getNodesByLabelAndProperty "User" $ Just ("email" |: fromEmail email)
let mUser = listToMaybe users
mPasswordProp <- runMaybeT $ MaybeT (return mUser) >>= (MaybeT . (flip getProperty) "password")
case mPasswordProp of
Just (ValueProperty (TextVal pwHash)) ->
return . Just $ HashedPW pwHash
_ -> return Nothing
case mHash of
Nothing -> errorOf err403
Just hashed -> do unless (verifyPassword hashed unhashed) $ errorOf err403
secret <- asks jwtSecret
return $ Encoded (Authorization email) secret
updateUser :: Email -> Maybe (Token Authorization) -> User -> ConfigM ()
updateUser email token user = do
Authorization authEmail <- requireToken token
unless (authEmail == email) $ errorOf err403
let Just userProps = HM.delete "id" <$> (decode $ encode user)
updated <- runNeo $ do
userNodes <- getNodesByLabelAndProperty "User" $ Just ("email" |: fromEmail email)
case userNodes of
[userNode] -> do
forM_ (HM.toList userProps) $ \(key, val) ->
setProperty userNode key val
return True
[] -> return False
unless updated $ errorOf err404
getAll :: Maybe Int64 -> ConfigM (Headers '[Header "Link" Pagination] [User])
getAll Nothing = getAll (Just 1)
getAll (Just offset) = runTransaction $ do
[Only countVal] <- query "MATCH (u:User) RETURN COUNT(u)" HM.empty
users <- query "MATCH (u:User) RETURN ID(u), u SKIP {offset} LIMIT 50" $ HM.fromList [("offset", C.newparam . (50 *) $ offset - 1)]
let Success count = fromJSON countVal
maxOffset = (count `div` 50) + 1
return . addHeader (mkPagination offset maxOffset (Proxy :: Proxy GetAll) (Proxy :: Proxy UserAPI)) $ users
{-
getSingle :: Email -> ConfigM User
getSingle email = do
user <- runNeo $ do
userNodes <- getNodesByLabelAndProperty "User" $ Just ("email" |: fromEmail email)
userProperties <- forM userNodes getProperties
case userProperties of
[user] -> return . decode $ encode user
_ -> return Nothing
case user of
Just x -> return x
Nothing -> errorOf err404
-}
deleteUser :: Email -> Maybe (Token Authorization) -> ConfigM ()
deleteUser email token = do
Authorization authEmail <- requireToken token
unless (authEmail == email) $ errorOf err403
deleted <- runNeo $ do
userNodes <- getNodesByLabelAndProperty "User" $ Just ("email" |: fromEmail email)
case userNodes of
[userNode] -> deleteNode userNode >> return True
_ -> return False
unless deleted $ errorOf err404
|
benweitzman/PhoBuddies-Servant
|
src/Server/User.hs
|
mit
| 4,736 | 0 | 26 | 1,385 | 1,281 | 625 | 656 | 100 | 3 |
{-# LANGUAGE ForeignFunctionInterface, CPP #-}
module VideoCore.Raw where
#include "HsVideoCoreRaw.h"
import Foreign
import Foreign.C
FFI_FUNC(bcm_host_init, IO ())
FFI_FUNC(bcm_host_deinit, IO())
FFI_FUNC(graphics_get_display_size, CUShort -> Ptr CUInt -> Ptr CUInt -> IO CInt)
|
Wollw/VideoCore-Haskell
|
src/VideoCore/Raw.hs
|
mit
| 282 | 1 | 10 | 33 | 83 | 42 | 41 | -1 | -1 |
module Yage.Rendering.Resources.GL
( module Base
, module Buffer
, module Framebuffer
, module Renderbuffer
, module Shader
, module Texture
) where
import Yage.Rendering.Resources.GL.Base as Base
import Yage.Rendering.Resources.GL.Buffer as Buffer
import Yage.Rendering.Resources.GL.Framebuffer as Framebuffer
import Yage.Rendering.Resources.GL.Renderbuffer as Renderbuffer
import Yage.Rendering.Resources.GL.Shader as Shader
import Yage.Rendering.Resources.GL.Texture as Texture
import Yage.Rendering.Resources.GL.TextureFormat as Texture
-- import Yage.Resources.Texture
|
MaxDaten/yage
|
src/Yage/Rendering/Resources/GL.hs
|
mit
| 691 | 0 | 4 | 170 | 105 | 82 | 23 | 14 | 0 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module Text.Greek.Sublist where
import Text.Greek.Utility
data Error b e
= ErrorOnlyBegin b
| ErrorOnlyEnd e
| ErrorNestedEnd e e
deriving (Show)
data TopLevel b e t
= TopLevelBegin b
| TopLevelEnd e
| TopLevelPass t
foldrSublist :: (s -> TopLevel b e t) -> [s] -> Error b e + [t + (b, e, [t])]
foldrSublist f xs = case foldr buildSublistR (StateROutside []) . fmap f $ xs of
StateRError e -> Left e
StateRInside e _ _ -> Left (ErrorOnlyEnd e)
StateROutside os -> Right os
data StateR b e t
= StateRError (Error b e)
| StateROutside [t + (b, e, [t])]
| StateRInside e [t] [t + (b, e, [t])]
buildSublistR
:: TopLevel b e t
-> StateR b e t
-> StateR b e t
buildSublistR _ e@(StateRError _) = e
buildSublistR (TopLevelBegin b) (StateRInside e cs os) = StateROutside (Right (b, e, cs) : os)
buildSublistR (TopLevelEnd e') (StateRInside e _ _) = StateRError (ErrorNestedEnd e' e)
buildSublistR (TopLevelPass t) (StateRInside e cs os) = StateRInside e (t : cs) os
buildSublistR (TopLevelBegin b) (StateROutside _) = StateRError (ErrorOnlyBegin b)
buildSublistR (TopLevelEnd e) (StateROutside os) = StateRInside e [] os
buildSublistR (TopLevelPass t) (StateROutside os) = StateROutside (Left t : os)
|
scott-fleischman/greek-grammar
|
haskell/greek-grammar/src/Text/Greek/Sublist.hs
|
mit
| 1,396 | 0 | 11 | 298 | 561 | 297 | 264 | 35 | 3 |
module Main where
backwards :: [a] -> [a]
backwards [] = []
backwards (h:t) = backwards t ++ [h]
|
mtraina/seven-languages-seven-weeks
|
week-7-haskell/day3/backwards.hs
|
mit
| 103 | 0 | 7 | 25 | 56 | 31 | 25 | 4 | 1 |
module Lambency.GameLoop (
GameLoopState, mkLoopState,
GameLoopConfig, mkLoopConfig,
runGameLoop
) where
--------------------------------------------------------------------------------
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.RWS.Strict
import qualified Control.Wire as W
import qualified Graphics.UI.GLFW as GLFW
import qualified Graphics.Rendering.OpenGL as GL
import Data.Time
import FRP.Netwire.Input.GLFW
import Lambency.ResourceLoader
import Lambency.Sound
import Lambency.Sprite
import Lambency.Texture
import Lambency.Types
import Lambency.GameSession
import System.CPUTime
import Linear
--------------------------------------------------------------------------------
maximumFramerate :: NominalDiffTime
maximumFramerate = fromRational . toRational $ (1.0 / 10.0 :: Double)
-- When we handle actions, only really print logs and play any sounds
-- that may need to start or stop.
handleAction :: OutputAction -> IO ()
handleAction (SoundAction sound cmd) = handleCommand sound cmd
handleAction (LogAction s) = putStrLn s
handleAction (WireframeAction True) = GL.polygonMode GL.$= (GL.Line, GL.Line)
handleAction (WireframeAction False) = GL.polygonMode GL.$= (GL.Fill, GL.Fill)
step :: a -> Game a -> TimeStep ->
GameMonad (Maybe a, Camera, [Light], Game a)
step go game t = do
(Right cam, nCamWire) <-
W.stepWire (getContinuousWire $ mainCamera game) t (Right ())
(lights, lwires) <-
collect <$>
mapM (\w -> W.stepWire w t $ Right ()) (getContinuousWire <$> dynamicLights game)
(Right result, gameWire) <-
W.stepWire (getContinuousWire $ gameLogic game) t (Right go)
case result of
Nothing -> return (result, cam, lights, newGame nCamWire lwires W.mkEmpty)
Just x -> return (x `seq` result, cam, lights, newGame nCamWire lwires gameWire)
where
collect :: [(Either e b, GameWire a b)] -> ([b], [GameWire a b])
collect [] = ([], [])
collect ((Left _, _) : _) = error "Internal -- Light wire inhibited?"
collect ((Right obj, wire) : rest) = (obj : objs, wire : wires)
where
(objs, wires) = collect rest
newGame cam lights logic =
Game { mainCamera = CW cam
, dynamicLights = CW <$> lights
, gameLogic = CW logic
}
data GameLoopConfig = GameLoopConfig {
gameRenderer :: Renderer,
simpleQuadSprite :: Sprite,
glfwInputControl :: Maybe GLFWInputControl,
windowDimensions :: V2 Int
}
mkLoopConfig :: Renderer -> Maybe GLFW.Window -> IO (GameLoopConfig, IO ())
mkLoopConfig r win' = do
-- !FIXME! Use fully opaque 'mask' texture that we can change the color and
-- size for dynamically. This isn't the best way to do this, but it'll work.
(sprite, unloadSprite) <-
runResourceLoader r $ createSolidTexture (pure 255)
>>= loadStaticSpriteWithMask
-- Collect the window dimensions. TODO: This should be done every frame so
-- that we can properly update our UI on state changes. For now, we just tell
-- GLFW to prevent the user from resizing the window, but that need not be a
-- restriction.
(winDims, ictl) <- case win' of
Just win -> do
winDims <- uncurry V2 <$> liftIO (GLFW.getWindowSize win)
ictl <- Just <$> mkInputControl win
return (winDims, ictl)
Nothing -> return (V2 0 0, Nothing)
return (GameLoopConfig r sprite ictl winDims, unloadSprite)
data GameLoopState a = GameLoopState {
currentGameValue :: a,
currentGameLogic :: Game a,
currentGameSession :: GameSession,
currentPhysicsAccum :: NominalDiffTime,
lastFramePicoseconds :: Integer
}
mkLoopState :: a -> Game a -> GameLoopState a
mkLoopState initialVal initGame = GameLoopState
{ currentGameValue = initialVal
, currentGameLogic = initGame
, currentGameSession = mkGameSession
, currentPhysicsAccum = toEnum 0
, lastFramePicoseconds = 0
}
type GameLoopM a = ReaderT GameLoopConfig (StateT (GameLoopState a) IO)
runLoop :: UTCTime -> GameLoopM a ()
runLoop prevFrameTime = do
(GameLoopState _ _ _ accumulator _) <- get
-- Step
thisFrameTime <- liftIO getCurrentTime
let newAccum = accumulator + (diffUTCTime thisFrameTime prevFrameTime)
modify $ \ls -> ls { currentPhysicsAccum = min newAccum maximumFramerate }
(go, (nextsession, accum), nextGame) <- stepGame
case go of
Just gobj -> do
ls <- get
put $ GameLoopState gobj nextGame nextsession accum (lastFramePicoseconds ls)
runLoop thisFrameTime
Nothing -> return ()
runGameLoop :: GameLoopState a -> GameLoopConfig -> IO ()
runGameLoop st config = do
curTime <- getCurrentTime
evalStateT (runReaderT (runLoop curTime) config) st
type TimeStepper = (GameSession, NominalDiffTime)
stepGame :: GameLoopM a (Maybe a, TimeStepper, Game a)
stepGame = do
(GameLoopState go game session accum _) <- get
if (accum < physicsDeltaUTC)
then return (Just go, (session, accum), game)
else runGame
runGame :: GameLoopM a (Maybe a, TimeStepper, Game a)
runGame = do
gameLoopConfig <- ask
gls <- get
(hasInput, ipt) <- liftIO $ case glfwInputControl gameLoopConfig of
Just glfwIpt -> getInput glfwIpt >>= (\x -> return (True, x))
Nothing -> return (False, emptyGLFWState)
-- Retreive the next time step from our game session
(ts, nextSess) <- liftIO $ W.stepSession (currentGameSession gls)
let
-- The game step is the complete GameMonad computation that
-- produces four values: Either inhibition or a new game value
-- A new camera, a list of dynamic lights, and the next simulation
-- wire
gameStep = step (currentGameValue gls) (currentGameLogic gls) ts
-- We need to render if we're going to fall below the physics threshold
-- on the next frame. This simulates a while loop. If we don't fall
-- through this threshold, we will perform another physics step before
-- we finally decide to render.
accum = currentPhysicsAccum gls
winDims = windowDimensions gameLoopConfig
renderTime = lastFramePicoseconds gls
sprite = simpleQuadSprite gameLoopConfig
frameConfig = GameConfig (gameRenderer gameLoopConfig) renderTime winDims sprite
-- This is the meat of the step routine. This calls runRWS on the
-- main game wire, and uses the results to figure out what needs
-- to be done.
((result, cam, lights, nextGame), newIpt, (actions, renderActs)) <-
liftIO $ runRWST (nextFrame gameStep) frameConfig ipt
-- The ReaderT RenderConfig IO program that will do the actual rendering
let accumRemainder = accum - physicsDeltaUTC
needsRender = case result of
Nothing -> False
Just _ -> accumRemainder < physicsDeltaUTC
frameTime <-
if needsRender
then liftIO $ do
t <- getCPUTime
render (gameRenderer gameLoopConfig) lights cam renderActs
t' <- getCPUTime
return (t' - t)
else return renderTime
_ <- liftIO $ do
-- Actually do the associated actions
mapM_ handleAction actions
-- Poll the input
when hasInput $ case glfwInputControl gameLoopConfig of
Just glfwIpt -> pollGLFW newIpt glfwIpt >> return ()
Nothing -> return ()
-- If our main wire inhibited, return immediately.
case result of
Just obj -> do
put $ GameLoopState obj nextGame nextSess accumRemainder frameTime
stepGame
Nothing -> return (result, (nextSess, accum), nextGame)
|
Mokosha/Lambency
|
lib/Lambency/GameLoop.hs
|
mit
| 7,401 | 0 | 18 | 1,540 | 1,978 | 1,041 | 937 | 143 | 6 |
import Control.Monad
import Data.List.Extra
import Data.Maybe
import qualified Data.Char as C
import qualified Data.Map as Map
import qualified Data.Set as Set
------
iread :: String -> Int
iread = read
answer :: (Show a) => (String -> a) -> IO ()
answer f = interact $ (++"\n") . show . f
ord0 c = C.ord c - C.ord 'a'
chr0 i = C.chr (i + C.ord 'a')
incletter c i = chr0 ((ord0 c + i) `mod` 26)
splitOn1 a b = fromJust $ stripInfix a b
rsplitOn1 a b = fromJust $ stripInfixEnd a b
-- pull out every part of a String that can be read in
-- for some Read a and ignore the rest
readOut :: Read a => String -> [a]
readOut "" = []
readOut s = case reads s of
[] -> readOut $ tail s
[(x, s')] -> x : readOut s'
_ -> error "ambiguous parse"
ireadOut :: String -> [Int]
ireadOut = readOut
--------
ckfilter (x:xs) (y:ys) = if x == y then x : rest else rest
where rest = ckfilter xs ys
ckfilter _ _ = []
cksum l = (sum $ ckfilter l (tail (l ++ [head l])),
sum $ ckfilter l (drop (length l `div` 2) (cycle l)))
main = answer $ cksum . map (read . (:[])) . head . lines
|
msullivan/advent-of-code
|
2017/A1.hs
|
mit
| 1,087 | 0 | 13 | 254 | 515 | 275 | 240 | 29 | 3 |
module Draw.Style
( LineStyle (..),
FrameStyle (..),
VertexStyle (..),
GridStyle (..),
gDefault,
gDefaultIrreg,
gDashed,
gDashedThick,
gPlain,
gPlainDashed,
gSlither,
)
where
import Diagrams.Prelude
import Draw.Widths
data LineStyle
= LineNone
| LineThin
| LineDashed
| LineThick
data FrameStyle
= FrameStyle
{ _fWidthFactor :: Double,
_fColour :: Colour Double
}
data VertexStyle
= VertexNone
| VertexDot
data GridStyle
= GridStyle
{ _line :: LineStyle,
_border :: LineStyle,
_frame :: Maybe FrameStyle,
_vertex :: VertexStyle
}
gDefault,
gDefaultIrreg,
gSlither,
gDashed,
gDashedThick,
gPlain,
gPlainDashed ::
GridStyle
gDefault =
GridStyle
LineThin
LineThin
(Just (FrameStyle framewidthfactor black))
VertexNone
gDefaultIrreg = GridStyle LineThin LineThick Nothing VertexNone
gSlither = GridStyle LineNone LineNone Nothing VertexDot
gDashed =
GridStyle
LineDashed
LineThin
(Just (FrameStyle framewidthfactor black))
VertexNone
gDashedThick = GridStyle LineDashed LineThick Nothing VertexNone
gPlain = GridStyle LineThin LineThin Nothing VertexNone
gPlainDashed = GridStyle LineDashed LineDashed Nothing VertexNone
|
robx/puzzle-draw
|
src/Draw/Style.hs
|
mit
| 1,291 | 0 | 9 | 310 | 297 | 176 | 121 | 57 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Workaround(encodeWithWorkaround) where
import Data.Aeson as A
import Data.Vector as V
import Data.Maybe
import Data.ByteString.Lazy
import Data.HashMap.Strict as HMS
-- Working around Aeson bug #454
-- See https://github.com/bos/aeson/issues/454
-- This should be fixed in Aeson 1.x.y.z but
-- In the meantime the function below is a drop-in replacement for encode
-- Won't show null values in objects
encodeWithWorkaround :: ToJSON a => a -> ByteString
encodeWithWorkaround s =
A.encode . cleanUp . fromJust . A.decode $ A.encode s
cleanUp (Object m) =
let m' = HMS.filter (/= Null) m in Object $ HMS.map cleanUp m'
cleanUp (Array a) = Array $ V.map cleanUp a
cleanUp val = val
|
gip/cinq-cloches-ledger
|
src/Workaround.hs
|
mit
| 738 | 0 | 10 | 129 | 177 | 98 | 79 | 14 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
-- | Unification Grammars with no CFG backbone
-- Following http://cs.haifa.ac.il/~shuly/teaching/06/nlp/ug3.pdf
module NLP.UG.Grammar where
import Common
import NLP.AVM
------------------------------------------------------------------------------
-- Types
-- | Grammar
data Grammar = Grammar {
start :: Cat, -- ^ Start category
rules :: [Rule] -- ^ Rules
}
deriving (Eq, Ord, Show)
-- | Category
type Cat = String
-- | Rule is essentially a multi-avm, where first item is LHS
data Rule = Rule MultiAVM -- ^ Non-terminal rule
| Terminal Token AVM -- ^ Terminal rule
deriving (Eq, Ord, Show)
-- | Token
type Token = String
-- | A derivation tree
-- Use only the dictionary in root AVM; all others should be empty
data DerivationTree = Leaf Token -- ^ A leaf
| Node AVM [DerivationTree] -- ^ An intermediate node
deriving (Eq, Ord, Show)
------------------------------------------------------------------------------
-- Helpers
-- | Is a tree complete?
-- Useful for filtering
isComplete :: DerivationTree -> Bool
isComplete (Leaf _) = True
isComplete (Node _ []) = False
isComplete (Node _ kids) = all isComplete kids
-- | Get linearisation from derivation tree
-- May include holes if tree is incomplete
lin :: DerivationTree -> [Token]
lin (Leaf tok) = [tok]
lin (Node _ []) = ["?"]
lin (Node _ kids) = concatMap lin kids
------------------------------------------------------------------------------
-- Pretty printing
pp :: DerivationTree -> IO ()
pp = putStrLn . ppTree
-- | Pretty print a derivation tree
ppTree :: DerivationTree -> String
ppTree = go 0
where
go :: Int -> DerivationTree -> String
go l d = concat (replicate l " ") ++ case d of
Leaf tok -> show tok ++ "\n"
Node avm kids -> inlineAVM avm ++ "\n" ++ concatMap (go (l+1)) kids
------------------------------------------------------------------------------
-- Examples
g1 :: Grammar
g1 = Grammar "s"
[ Rule $ mkMultiAVM [ cat "s" nullAVM
, cat "np" numX
, cat "vp" numX
]
, Rule $ mkMultiAVM [ cat "np" numX
, cat "d" numX
, cat "n" numX
]
, Rule $ mkMultiAVM [ cat "vp" numX
, cat "v" numX
]
, Rule $ mkMultiAVM [ cat "vp" numX
, cat "v" numX
, cat "np" numY
]
-- Terminals
, Terminal "lamb" $ term "n" ⊔ numSG
, Terminal "lambs" $ term "n" ⊔ numPL
, Terminal "sheep" $ term "n" ⊔ numSG
, Terminal "sheep" $ term "n" ⊔ numPL
, Terminal "sleeps" $ term "v" ⊔ numSG
, Terminal "sleep" $ term "v" ⊔ numPL
, Terminal "a" $ term "d" ⊔ numSG
, Terminal "two" $ term "d" ⊔ numPL
]
where
cat c avm = ValAVM $ mkAVM1 "CAT" (ValAtom c) ⊔ avm
term c = mkAVM1 "CAT" (ValAtom c)
numX = mkAVM1 "NUM" (ValIndex 1)
numY = mkAVM1 "NUM" (ValIndex 2)
numSG = mkAVM [("NUM",ValIndex 1)] `addDict` [(1,ValAtom "sg")]
numPL = mkAVM [("NUM",ValIndex 1)] `addDict` [(1,ValAtom "pl")]
-- Adds case to g1
g2 :: Grammar
g2 = Grammar "s"
[ Rule $ mkMultiAVM [ cat "s" nullAVM
, cat "np" $ numX ⊔ mkAVM1 "CASE" (ValAtom "nom")
, cat "vp" numX
]
, Rule $ mkMultiAVM [ cat "np" $ numX ⊔ caseY
, cat "d" numX
, cat "n" $ numX ⊔ caseY
]
, Rule $ mkMultiAVM [ cat "np" $ numX ⊔ caseY
, cat "pron" $ numX ⊔ caseY
]
, Rule $ mkMultiAVM [ cat "np" $ numX ⊔ caseY
, cat "propn" $ numX ⊔ caseY
]
, Rule $ mkMultiAVM [ cat "vp" numX
, cat "v" $ numX ⊔ scIntrans
]
, Rule $ mkMultiAVM [ cat "vp" numX
, cat "v" $ numX ⊔ scTrans
, cat "np" $ numY ⊔ mkAVM1 "CASE" (ValAtom "acc")
]
-- Terminals
, Terminal "sleeps" $ term "v" ⊔ numSG ⊔ scIntrans
, Terminal "sleep" $ term "v" ⊔ numPL ⊔ scIntrans
, Terminal "feeds" $ term "v" ⊔ numSG ⊔ scTrans
, Terminal "feed" $ term "v" ⊔ numPL ⊔ scTrans
, Terminal "lamb" $ term "n" ⊔ numSG ⊔ caseY
, Terminal "lambs" $ term "n" ⊔ numPL ⊔ caseY
, Terminal "she" $ term "pron" ⊔ numSG ⊔ mkAVM1 "CASE" (ValIndex 2) `addDict` [(2,ValAtom "nom")]
, Terminal "her" $ term "pron" ⊔ numSG ⊔ mkAVM1 "CASE" (ValIndex 2) `addDict` [(2,ValAtom "acc")]
, Terminal "John" $ term "propn" ⊔ numSG ⊔ caseY
, Terminal "a" $ term "d" ⊔ numSG
, Terminal "two" $ term "d" ⊔ numPL
]
where
cat c avm = ValAVM $ mkAVM1 "CAT" (ValAtom c) ⊔ avm
term c = mkAVM1 "CAT" (ValAtom c)
numX = mkAVM1 "NUM" (ValIndex 1)
numY = mkAVM1 "NUM" (ValIndex 2)
caseY = mkAVM1 "CASE" (ValIndex 2)
scIntrans = mkAVM1 "SUBCAT" (ValAtom "intrans")
scTrans = mkAVM1 "SUBCAT" (ValAtom "trans")
numSG = mkAVM [("NUM",ValIndex 1)] `addDict` [(1,ValAtom "sg")]
numPL = mkAVM [("NUM",ValIndex 1)] `addDict` [(1,ValAtom "pl")]
-- Subcategorisation lists, with number removed
g3a :: Grammar
g3a = Grammar "s"
[ Rule $ mkMultiAVM [ ValAVM $ cat "s"
, ValAVM $ cat "np"
, ValAVM $ cat "v" ⊔ mkAVM1 "SUBCAT" (unlist [])
]
, Rule $ mkMultiAVM [ ValAVM $ cat "v" ⊔ mkAVM1 "SUBCAT" (ValIndex 2)
, ValAVM $ cat "v" ⊔ mkAVM1 "SUBCAT" (vmkAVM [ ("FIRST", vmkAVM1 "CAT" (ValIndex 1))
, ("REST", ValIndex 2)
])
, ValAVM $ mkAVM1 "CAT" (ValIndex 1)
]
, Terminal "John" $ term "np"
, Terminal "Mary" $ term "np"
-- , Terminal "Rachel" $ term "np"
, Terminal "sleeps" $ term "v" ⊔ mkAVM1 "SUBCAT" (unlist [])
, Terminal "loves" $ term "v" ⊔ mkAVM1 "SUBCAT" (unlist [ vmkAVM1 "CAT" (ValAtom "np") ])
, Terminal "gives" $ term "v" ⊔ mkAVM1 "SUBCAT" (unlist [ vmkAVM1 "CAT" (ValAtom "np")
, vmkAVM1 "CAT" (ValAtom "np")
])
, Terminal "tells" $ term "v" ⊔ mkAVM1 "SUBCAT" (unlist [ vmkAVM1 "CAT" (ValAtom "np")
, vmkAVM1 "CAT" (ValAtom "s")
])
]
where
cat c = mkAVM1 "CAT" (ValAtom c)
term c = mkAVM1 "CAT" (ValAtom c)
-- As in slides
g3 :: Grammar
g3 = Grammar "s"
[ Rule $ mkMultiAVM [ cat "s" $ nullAVM
, cat "np" $ numX ⊔ (mkAVM1 "CASE" (ValAtom "nom"))
, cat "v" $ numX ⊔ (mkAVM1 "SUBCAT" (unlist []))
]
, Rule $ mkMultiAVM [ cat "v" $ numX ⊔ (mkAVM1 "SUBCAT" (ValIndex 2))
, cat "v" $ numX ⊔ (mkAVM1 "SUBCAT" (vmkAVM [("FIRST",ValIndex 3), ("REST",ValIndex 2)]))
, ValIndex 3
] `maddDict` [(3,vnullAVM)]
, Rule $ mkMultiAVM [ cat "np" $ numX ⊔ caseY
, cat "d" $ numX
, cat "n" $ numX ⊔ caseY
]
, Rule $ mkMultiAVM [ cat "np" $ numX ⊔ caseY -- ⊔ queQ
, cat "pron" $ numX ⊔ caseY -- ⊔ queQ
]
, Rule $ mkMultiAVM [ cat "np" $ numX ⊔ caseY
, cat "propn" $ numX ⊔ caseY
]
, Terminal "sleep" $ term "v" ⊔ (mkAVM1 "SUBCAT" (unlist [])) ⊔ numPL
, Terminal "love" $ term "v" ⊔ (mkAVM1 "SUBCAT" (unlist [vmkAVM [("CAT",ValAtom "np"),("CASE",ValAtom "acc")]])) ⊔ numPL
, Terminal "give" $ term "v" ⊔ (mkAVM1 "SUBCAT" (unlist [vmkAVM [("CAT",ValAtom "np"),("CASE",ValAtom "acc")], vmkAVM1 "CAT" (ValAtom "np")])) ⊔ numPL
, Terminal "lamb" $ term "n" ⊔ numSG ⊔ caseY
, Terminal "lambs" $ term "n" ⊔ numPL ⊔ caseY
, Terminal "she" $ term "pron" ⊔ numSG ⊔ mkAVM1 "CASE" (ValAtom "nom")
, Terminal "her" $ term "pron" ⊔ numSG ⊔ mkAVM1 "CASE" (ValAtom "acc")
, Terminal "whom" $ term "pron" ⊔ mkAVM [("CASE",ValAtom "acc"){-,("QUE",ValAtom "+")-}]
, Terminal "Rachel" $ term "propn" ⊔ numSG
, Terminal "Jacob" $ term "propn" ⊔ numSG
, Terminal "a" $ term "d" ⊔ numSG
, Terminal "two" $ term "d" ⊔ numPL
]
where
cat c avm = ValAVM $ mkAVM1 "CAT" (ValAtom c) ⊔ avm
term c = mkAVM1 "CAT" (ValAtom c)
numX = mkAVM1 "NUM" (ValIndex 1)
numY = mkAVM1 "NUM" (ValIndex 2)
numSG = mkAVM1 "NUM" (ValAtom "sg")
numPL = mkAVM1 "NUM" (ValAtom "pl")
caseY = mkAVM1 "CASE" (ValIndex 2)
queQ = mkAVM1 "QUE" (ValIndex 4)
|
johnjcamilleri/hpsg
|
NLP/UG/Grammar.hs
|
mit
| 9,434 | 0 | 18 | 3,474 | 2,935 | 1,498 | 1,437 | 151 | 2 |
module Tests.ConnectionTest (main) where
import Web.Slack
import System.Environment (lookupEnv)
import System.Exit
import System.IO.Unsafe
myConfig :: String -> SlackConfig
myConfig apiToken = SlackConfig
{ _slackApiToken = apiToken -- Specify your API token here
}
connectBot :: SlackBot ()
connectBot Hello = unsafePerformIO exitSuccess
connectBot _ = return ()
main :: IO ()
main = do
apiToken <- lookupEnv "SLACK_API_TOKEN"
case apiToken of
Nothing -> exitFailure
Just token -> runBot (myConfig token) connectBot ()
|
madjar/slack-api
|
tests/Tests/ConnectionTest.hs
|
mit
| 559 | 0 | 12 | 111 | 159 | 83 | 76 | 17 | 2 |
import System.Environment
import qualified Data.ByteString.Lazy as B
main = do
(fileName1:fileName2:_) <- getArgs
copyFile fileName1 fileName2
copyFile :: FilePath -> FilePath -> IO ()
copyFile source dest = do
contents <- B.readFile source
B.writeFile dest contents
|
softwaremechanic/Miscellaneous
|
Haskell/bytestring.hs
|
gpl-2.0
| 287 | 0 | 10 | 56 | 96 | 48 | 48 | 9 | 1 |
module WXMaxima where
import Bugs
import Control.Monad.State
import Data.List
import Utils
import System.Directory
-- Zipper On lists
data LstZipPlus a = LZP { lzp'left :: [a] ,
lzp'elem :: a ,
lzp'right :: [a]
}
deriving (Eq,Ord,Show,Read)
type LstZip a = Maybe (LstZipPlus a)
data WXMT a = WXMT { unWXMT :: State (LstZip Entry, String) a}
instance Monad WXMT where
return = WXMT . return
(WXMT m) >>= f = WXMT $ m >>= unWXMT . f
-- wxMaxima Printing
print_input_cell :: String -> [String]
print_input_cell s =
[ "/* [wxMaxima: input start ] */"
, s ++ ";"
, "/* [wxMaxima: input end ] */"
, ""
]
print_comment_cell :: String -> [String]
print_comment_cell s =
[ "/* [wxMaxima: comment start ]"
, s
, " [wxMaxima: comment end ] */"
, ""
]
print_pair :: (Show a, Show b) => (a, b) -> String
print_pair (i,j) = "[ " ++ (show i) ++ " , " ++ (show j) ++ " ]"
print_table :: (Show a, Show b) => [(a, b)] -> String
print_table l = "[" ++ (aux l)
where
aux [] = " ]"
aux [x] = "\n " ++ (print_pair x) ++ "\n ]"
aux (x : l) = "\n " ++ (print_pair x) ++ "," ++ (aux l)
print_entry :: Entry -> [String]
print_entry (Entry c sql n t) =
(print_comment_cell $ "Computation for kernel " ++ c ++ "\n" ++ sql)
++ (print_input_cell $ table ++ " : " ++ (print_table t))
++ (print_input_cell $ theta ++ " : log_param_of_table(" ++ table ++ ")")
++ (print_input_cell $ chi_square ++ " : chi_square_of_table(" ++ theta ++ "[1] , " ++ table ++ ")")
++ (print_input_cell $ pblog_expected ++ " : pblog_expected_table(" ++ theta ++ "[1]," ++ table ++ ")")
++ (print_input_cell $ df ++ " : degree_of_freedom(" ++ table ++ ")")
++ (print_input_cell $ pvalue ++ " : p_value_chi_square(" ++ chi_square ++ "," ++ df ++ ")")
where
table = "table_" ++ n
theta = "theta_" ++ n
chi_square = "chi_square_" ++ n
pblog_expected = "pblog_expected_" ++ n
df = "degree_of_freedom_" ++ n
pvalue = "p_value_chi_square_" ++ n
print_entries :: [Entry] -> [String]
print_entries = concatMap print_entry
extract_version :: String -> String
extract_version name =
(sepPred (== '_') ((sepPred (== '-') name) !! 1)) !! 0
print_tex_entry :: Entry -> String
print_tex_entry (Entry c sql n t) =
"if "++theta++"[1] = und\n"
++ "then printf (stream, \""++ version ++" & "
++ "\\\\textcolor{Red}{NA} & \\\\textcolor{Red}{NA} & "
++ "\\\\textcolor{Red}{$~4d$} & \\\\textcolor{Red}{NA} \\\\\\\\~%\", "++ df ++")\n"
++ "elseif "++ pvalue ++ " > 0.05\n"
++ "then printf (stream, \""++ version ++" & $~{~,3,,,'0f~}$ & $~,3,,,'0f$ & $~4d$ & $~5,3,,,'0f$ \\\\\\\\~%\", "
++ theta ++ ", "
++ chi_square ++ ", "
-- ++ pblog_expected ++ ", "
++ df ++ ", "
++ pvalue ++")"
++ "else printf (stream, \""++ version ++" & "
++ "\\\\textcolor{Red}{$~{~,3,,,'0f~}$} & "
++ "\\\\textcolor{Red}{$~,3,,,'0f$} & "
++ "\\\\textcolor{Red}{$~4d$} & "
++ "\\\\textcolor{Red}{$~5,3,,,'0f$} \\\\\\\\~%\", "
++ theta ++ ", "
++ chi_square ++ ", "
-- ++ pblog_expected ++ ", "
++ df ++ ", "
++ pvalue ++")"
where
version = extract_version c
theta = "theta_" ++ n
chi_square = "chi_square_" ++ n
-- pblog_expected = "pblog_expected_" ++ n
df = "degree_of_freedom_" ++ n
pvalue = "p_value_chi_square_" ++ n
print_tex :: String -> [Entry] -> [String]
print_tex output entries =
print_input_cell $ concat $ intersperse ";\n"
( ["stream : openw(\"" ++ output ++ "\")"]
++ ["printf (stream, \"% Version & $\\\\theta$ & $\\\\chi^2$ & Degree of freedom & $\\\\chi^2$ p-value \\\\\\\\~%\")"]
++ (map print_tex_entry entries)
++ ["close(stream)"]
)
-- Maxima Batch file manipulation
wxmaxima_begining = [ "/* [wxMaxima batch file version 1] [ DO NOT EDIT BY HAND! ]*/"
, "/* [ Created with wxMaxima version 0.8.5 ] */"
, ""
]
wxmaxima_ending = [ "/* Maxima can't load/batch files which end with a comment! */"
, "\"Created with wxMaxima\"$"
]
wxmaximize s = wxmaxima_begining ++ s ++ wxmaxima_ending
wxunmaximize :: [String] -> [String]
wxunmaximize s = aux $ drop 2 $ s
where
aux l = if length l <= 2
then []
else (head l) : (aux $ tail l)
getLibrary :: [Char] -> IO [String]
getLibrary libdir = do l <- getDirectoryContents libdir
ls <- mapM doone $ sort $ filter (isSuffixOf ".wxm") l
return $ concat $ ls
where
doone filename = do s <- readFile $ libdir ++ "/" ++ filename
return $ wxunmaximize $ normalizeWXMlines $ lines s
output_tables :: String -> Maybe String -> [Entry] -> IO String
output_tables output lib entries =
do plib <- case lib of
Nothing -> return []
Just fp -> getLibrary fp
return $ concat $
intersperse "\n" $
normalizeWXMlines $
wxmaximize $
(plib
++ (print_entries entries)
++ (print_tex (output++".tex") entries))
-- Summery
-- Utils
normalizeWXMlines :: [String] -> [String]
normalizeWXMlines = check . (dropWhile p)
where
pc c = c == ' ' || c == '\t'
p = all pc
check [] = []
check l = map snd $ filter perase $ zip toeraise l
where
mask = map p l
toeraise = map (uncurry (&&)) $ zip mask (tail mask ++ [True])
perase (b,_) = not b
normalizeWXMstr :: String -> String
normalizeWXMstr = concat . (intersperse "\n") . normalizeWXMlines . lines
|
coccinelle/herodotos
|
hBugs/src/WXMaxima.hs
|
gpl-2.0
| 6,116 | 11 | 42 | 2,019 | 1,683 | 892 | 791 | 127 | 3 |
{-|
A module for converting Pepa models to hydra models
-}
module Language.Pepa.Compile.Dizzy
( pepaToDizzy )
where
{- Imported Standard Libraries -}
import qualified Data.Map as Map
{- External Library Modules Imported -}
{- Imported Local Libraries -}
import Language.Pepa.Syntax
( ParsedModel )
import Language.Pepa.Compile.TimedSystemEquation
( pepaToRateEquations )
import Language.Dizzy.Syntax
( DizzyModel ( .. ) )
import Language.Pepa.Analysis.Analysis
( getInitialConcentrations )
import Language.Pepa.MainControl
( MainControl )
{- End of Imports -}
{-|
Convert a pepa model into a dizzy model
-}
pepaToDizzy :: ParsedModel -> MainControl DizzyModel
pepaToDizzy model =
do rateEqns <- pepaToRateEquations model
return $ DizzyModel initConcentrations rateEqns
where
initConcentrations = Map.toList $ getInitialConcentrations model
|
allanderek/ipclib
|
Language/Pepa/Compile/Dizzy.hs
|
gpl-2.0
| 879 | 0 | 8 | 146 | 146 | 88 | 58 | 18 | 1 |
module Language.BioPepa.Print
( hprintBioPepaModel
, pprintBioPepaModel
)
where
{- Standard Library Modules Imported -}
import qualified Text.PrettyPrint.HughesPJ as Pretty
import Text.PrettyPrint.HughesPJ
( Doc )
{- External Library Modules Imported -}
{- Local Modules Imported -}
import Language.BioPepa.Syntax
( Model ( .. )
, RateDef
, RateExpr ( .. )
, Component ( .. )
, ComponentDef
, PrefixOp ( .. )
)
import qualified Language.Pepa.Print as PepaPrint
import Language.Pepa.Print
( pprintActionList
, actionToDoc
, pprintAngles
)
import Language.Pepa.QualifiedName
( pprintQualifiedName )
import qualified Language.Pepa.Utils as Utils
{- End of Module Imports -}
hprintBioPepaModel :: Model -> String
hprintBioPepaModel = Pretty.render . pprintBioPepaModel
pprintBioPepaModel :: Model -> Doc
pprintBioPepaModel pModel =
Pretty.vcat [ Pretty.vcat $ map rateDefToDoc (modelRateDefs pModel)
, Pretty.text ""
, Pretty.vcat $ map compDefToDoc (modelCompDefs pModel)
, Pretty.text ""
, compToDoc $ modelSystemEqn pModel
]
rateDefToDoc :: RateDef -> Doc
rateDefToDoc (ident, rateExpr) =
Pretty.hsep [ pprintQualifiedName ident
, Pretty.text "="
, Pretty.brackets $ rateExprToDoc rateExpr
, Pretty.text ";"
]
rateExprToDoc :: RateExpr -> Doc
rateExprToDoc (RateName ident) = pprintQualifiedName ident
rateExprToDoc (RateConstant d) = Utils.pprintDouble d
rateExprToDoc (RateMult left right) = Pretty.sep [ rateExprToDoc left
, Pretty.text "*"
, rateExprToDoc right
]
rateExprToDoc (RateDiv left right) = Pretty.sep [ rateExprToDoc left
, Pretty.text "/"
, rateExprToDoc right
]
rateExprToDoc (RateAdd left right) = Pretty.sep [ rateExprToDoc left
, Pretty.text "+"
, rateExprToDoc right
]
rateExprToDoc (RateSub left right) = Pretty.sep [ rateExprToDoc left
, Pretty.text "-"
, rateExprToDoc right
]
compDefToDoc :: ComponentDef -> Doc
compDefToDoc (ident, comp) =
Pretty.hsep [ pprintQualifiedName ident
, Pretty.text "="
, compToDoc comp
, Pretty.text ";"
]
compToDoc :: Component -> Doc
compToDoc (Named ident) =
pprintQualifiedName ident
compToDoc (PrefixComp action sto oper comp) =
Pretty.hsep [ Pretty.parens prefix
, prefixOpToDoc oper
, pprintQualifiedName comp
]
where
prefix = Pretty.sep [ actionToDoc action
, Pretty.comma
, Pretty.text sto
]
compToDoc (Choice left right) =
Pretty.sep [ compToDoc left
, compToDoc right
]
compToDoc (Cooperation left actions right) =
Pretty.sep [ compToDoc left
, pprintAngles $ pprintActionList actions
, compToDoc right
]
compToDoc (CompConcent ident conc) =
Pretty.hcat [ pprintQualifiedName ident
, Pretty.parens $ Pretty.text (show conc)
]
prefixOpToDoc :: PrefixOp -> Doc
prefixOpToDoc Reactant = Pretty.text "<<"
prefixOpToDoc Product = Pretty.text ">>"
prefixOpToDoc Activator = Pretty.text "act"
prefixOpToDoc Inhibitor = Pretty.text "inh"
prefixOpToDoc GenModifier = Pretty.text "gen"
|
allanderek/ipclib
|
Language/BioPepa/Print.hs
|
gpl-2.0
| 3,957 | 0 | 10 | 1,502 | 863 | 454 | 409 | 83 | 1 |
{-# LANGUAGE PackageImports #-}
import "wordify-webapp" Application (develMain)
import Prelude (IO)
main :: IO ()
main = develMain
|
Happy0/liscrabble
|
app/devel.hs
|
gpl-2.0
| 132 | 0 | 6 | 19 | 34 | 20 | 14 | 5 | 1 |
module Resolver
( satisfiable
) where
import Data.List
import Data.Maybe
-- Type declarations
data Formula = Atom String | Or Formula Formula | And Formula Formula | Not Formula deriving (Eq, Show, Read)
data Literal = NegativeLiteral String | PositiveLiteral String deriving (Eq, Ord, Show, Read)
type Clause = [Literal]
type ClauseSet = [Clause]
-- Helpers
-- | Converts positive to negative and negative to positive literal.
negatedLiteral :: Literal -> Literal
negatedLiteral (NegativeLiteral name) = PositiveLiteral name
negatedLiteral (PositiveLiteral name) = NegativeLiteral name
-- Any formula to CNF formula
-- !(a & b) === (!a | !B) !(a | b) === (!a & !b) !!a === a
-- | Moves negations inwards using deMorgan and eliminates duplicate negations
shiftNegations :: Formula -> Formula
shiftNegations (Not (And left right)) = Or (shiftNegations (Not left)) (shiftNegations (Not right))
shiftNegations (Not (Or left right)) = And (shiftNegations (Not left)) (shiftNegations (Not right))
shiftNegations (Not (Not f)) = shiftNegations f
shiftNegations (Not (Atom name)) = Not $ Atom name
shiftNegations (And left right) = And (shiftNegations left) (shiftNegations right)
shiftNegations (Or left right) = Or (shiftNegations left) (shiftNegations right)
shiftNegations (Atom name) = (Atom name)
-- a | (b & c) === (a | b) & (a | c)
-- | Moves 'and's outwards using the distributive law
shiftAndOr :: Formula -> Formula
shiftAndOr (Or l r) =
let args = (shiftAndOr l, shiftAndOr r)
in case args of ((And left right), other) -> And (shiftAndOr (Or left other)) (shiftAndOr (Or right other))
(other, (And left right)) -> And (shiftAndOr (Or other left)) (shiftAndOr (Or other right))
(left, right) -> Or left right
shiftAndOr (And left right) = (And (shiftAndOr left) (shiftAndOr right))
shiftAndOr f = f
-- | Converts a formula to Conjunctive Normal Form
formulaToCNF :: Formula -> Formula
formulaToCNF = shiftAndOr . shiftNegations
-- CNF formula to clause set
-- | Converts an atomic formula or a negation of an atomic formula to a literal
cnfToLiteral :: Formula -> Literal
cnfToLiteral (Atom name) = PositiveLiteral name
cnfToLiteral (Not (Atom name)) = NegativeLiteral name
-- | Converts a disjunction of atomic formulas / negations thereof to a set of literals
cnfToClause :: Formula -> Clause
cnfToClause (Or left right) = (cnfToClause left) ++ (cnfToClause right)
cnfToClause formula = [cnfToLiteral formula]
-- | Converts a conjunction of disjunction of atomic formulas / negations thereof to a set
-- | of set of literals
cnfToClauseSet :: Formula -> ClauseSet
cnfToClauseSet (And left right) = (cnfToClauseSet left) ++ (cnfToClauseSet right)
cnfToClauseSet formula = [cnfToClause formula]
-- Normalize clause sets
-- | Removes duplicate literals, sorts literals and makes tautologies Nothing
normalizeClause :: Clause -> Maybe Clause
normalizeClause literals
| overlaps = Nothing
| otherwise = Just $ [PositiveLiteral a | a <- positive] ++ [NegativeLiteral a | a <- negative]
where positive = sort . nub $ [ a | PositiveLiteral a <- literals]
negative = sort . nub $ [a | NegativeLiteral a <- literals]
overlaps = not . null $ intersect positive negative
-- | Removes duplicate and clauses, sorts clauses and removes tautologies
normalizeClauseSet :: ClauseSet -> ClauseSet
normalizeClauseSet clauses = sort . nub $ mapMaybe normalizeClause clauses
-- Resolution
-- | Resolves a new clause of two old clauses
resolveClause :: Clause -> Clause -> Maybe Clause
resolveClause leftClause rightClause =
case leftLiteral of Just lit -> Just . nub $ (delete lit leftClause) ++ (delete (negatedLiteral lit) rightClause)
Nothing -> Nothing
where leftLiteral = find (\lit -> (negatedLiteral lit) `elem` rightClause) leftClause
-- | Gets all possible resolvents of a clause set
resolveClauseSet :: ClauseSet -> ClauseSet
resolveClauseSet clauses = normalizeClauseSet $ clauses ++ [a | Just a <- resolvents]
where resolvents = [resolveClause left right | left <- clauses, right <- clauses, left /= right]
-- | Resolves until no new clauses can be resolved
resolve :: ClauseSet -> ClauseSet
resolve clauses =
if changed then resolve resolution else resolution
where resolution = resolveClauseSet clauses
changed = (length resolution) /= (length clauses)
-- Lexer
data Symbol = OpenParenthesis | ClosingParenthesis | AndOperator | OrOperator | NotOperator | Identifier String | EndOfFile deriving (Eq, Show, Read)
-- | Gets the next symbol and the remaining string
scan :: String -> (Symbol, String)
scan ('(':tail) = (OpenParenthesis, tail)
scan (')':tail) = (ClosingParenthesis, tail)
scan ('&':tail) = (AndOperator, tail)
scan ('|':tail) = (OrOperator, tail)
scan ('!':tail) = (NotOperator, tail)
scan (' ':tail) = scan tail
scan "" = (EndOfFile, "")
scan all
| not $ null ident = (Identifier ident, tail)
| otherwise = error $ "invalid char at " ++ tail
where ident = takeWhile isLetter all
tail = dropWhile isLetter all
isLetter a = (a `elem` ['a'..'z']) || (a `elem` ['A'..'Z'])
-- Parser
-- | Parses the string as an atomic formula or as a grouped formula
parseAtomic :: String -> (Formula, String)
parseAtomic all =
case symbol of (Identifier name) -> (Atom name, tail)
OpenParenthesis -> let (formula, tail2) = parseOr tail;
(nextSymbol, realTail) = scan tail2 in case nextSymbol of ClosingParenthesis -> (formula, realTail)
_ -> error ("')' expected, but " ++ (show nextSymbol) ++ " found")
s -> error("Identifier or '(' expected, but " ++ (show s) ++ " found")
where (symbol, tail) = scan all
-- | Parses the string as a possibly negated atomic formula
parseNot :: String -> (Formula, String)
parseNot all =
case symbol of NotOperator -> let (formula, realTail) = parseNot tail in (Not formula, realTail)
_ -> parseAtomic all
where (symbol, tail) = scan all
-- | Parses the string as a conjunction of formulas
parseAnd :: String -> (Formula, String)
parseAnd all = case middleSymbol of AndOperator -> (And first second, realTail)
_ -> (first, firstTail)
where (first, firstTail) = parseNot(all)
(middleSymbol, secondTail) = scan(firstTail)
(second, realTail) = parseAnd(secondTail)
-- | Parses the string as a disjunction of formulas
parseOr :: String -> (Formula, String)
parseOr all = case middleSymbol of OrOperator -> (Or first second, realTail)
_ -> (first, firstTail)
where (first, firstTail) = parseAnd(all)
(middleSymbol, secondTail) = scan(firstTail)
(second, realTail) = parseOr(secondTail)
-- | Parses the string as a formula
parse :: String -> Formula
parse str = case nextSymbol of EndOfFile -> formula
_ -> error $ "End of input expected, but " ++ (show nextSymbol) ++ " found"
where (formula, tail) = parseOr str
(nextSymbol, _) = scan tail
-- High-level functions
-- | Converts any formula to a normalized clause set that can be resolved
formulaToClauseSet :: Formula -> ClauseSet
formulaToClauseSet = normalizeClauseSet . cnfToClauseSet . formulaToCNF
-- | Checks whether the formula given as string is satisfiable
satisfiable :: String -> Bool
satisfiable str = not $ [] `elem` resolution
where resolution = resolve . formulaToClauseSet . parse $ str
|
Yogu/haskell-resolve
|
Resolver.hs
|
gpl-2.0
| 7,627 | 0 | 18 | 1,668 | 2,199 | 1,167 | 1,032 | 110 | 4 |
{-# LANGUAGE Arrows #-}
{-# LANGUAGE MultiWayIf #-}
-- | This module defines the game enemies, or balls.
--
-- Objects are represented as Signal Functions as well ('ObjectSF'). In this
-- game we are introducing a novel construct, named 'AliveObject' in this
-- a particular instance of a 'ListSF'. A 'ListSF' is a signal function that
-- can die, or can produce more signal functions of the same type.
--
-- Each object is responsible for itself, but it cannot affect others:
-- objects can watch others, depend on others and react to them, but they
-- cannot /send a message/ or eliminate other objects.
--
-- You may want to read the basic definition of 'Controller' and 'ObjectSF'
-- before you attempt to go through this module.
--
module Game.Objects.Balls where
-- External imports
import Prelude hiding ((.))
import Control.Category ((.))
import FRP.Yampa
import FRP.Yampa.Extra
import FRP.Yampa.Switches
-- General-purpose internal imports
import Data.Extra.VectorSpace
import Physics.CollisionEngine
import Physics.TwoDimensions.Dimensions
import Physics.TwoDimensions.PhysicalObjects
-- Internal iports
import Game.Constants
import Game.Input
import Game.Objects
import Game.ObjectSF
import Game.Time
-- ** Balls
-- | A ball that splits in two when hit unless it is too small.
splittingBall :: ObjectName -> Double -> Pos2D -> Vel2D -> AliveObject
splittingBall bid size p0 v0 = ListSF $ timeTransformSF timeProgressionHalt $ proc i -> do
-- Default, just bouncing behaviour
bo <- bouncingBall bid size p0 v0 -< i
-- Hit fire? If so, it should split
click <- edge <<^ ballIsHit bid -< collisions i
let shouldSplit = isEvent click
-- We need two unique IDs so that collisions work
t <- localTime -< ()
let offspringIDL = bid ++ show t ++ "L"
offspringIDR = bid ++ show t ++ "R"
let enforceYPositive (x,y) = (x, abs y)
-- Position and velocity of new offspring
let bpos = physObjectPos bo
bvel = enforceYPositive $ physObjectVel bo
ovel = enforceYPositive $ (\(vx,vy) -> (-vx, vy)) bvel
-- Offspring size, unless this ball is too small to split
let tooSmall = size <= (ballWidth / 8)
let offspringSize = size / 2
-- Calculate offspring, if any
let offspringL = splittingBall offspringIDL offspringSize bpos bvel
offspringR = splittingBall offspringIDR offspringSize bpos ovel
offspring = if shouldSplit && not tooSmall
then [ offspringL, offspringR ]
else []
-- If it splits, we just remove this one
let dead = shouldSplit
returnA -< (bo, dead, offspring)
where
-- | Determine if a given fall has been hit by a bullet.
ballIsHit :: ObjectName -> Game.Objects.Collisions -> Bool
ballIsHit bid = not . null . collisionMask (bid, Ball) (collisionObjectKind Projectile)
-- | A bouncing ball that moves freely until there is a collision, then bounces
-- and goes on and on.
--
-- This SF needs an initial position and velocity. Every time there is a
-- bounce, it takes a snapshot of the point of collision and corrected
-- velocity, and starts again.
--
bouncingBall :: ObjectName -> Double -> Pos2D -> Vel2D -> ObjectSF
bouncingBall bid size p0 v0 = repeatRevSF (progressAndBounce bid size) (p0, v0)
-- | Calculate the future tentative position, and bounce if necessary. Pass on
-- snapshot of ball position and velocity if bouncing.
progressAndBounce :: ObjectName -> Double -> (Pos2D, Vel2D)
-> SF ObjectInput (Object, Event (Pos2D, Vel2D))
progressAndBounce bid size (p0, v0) = proc i -> do
-- Position of the ball, starting from p0 with velicity v0, since the
-- time of last switching (or being fired, whatever happened last)
-- provided that no obstacles are encountered.
o <- freeBall bid size p0 v0 -< i
-- The ballBounce needs the ball SF' input (which has knowledge of
-- collisions), so we carry it parallely to the tentative new
-- positions, and then use it to detect when it's time to bounce
b <- ballBounce bid -< (i, o)
returnA -< (o, b)
-- | Detect if the ball must bounce and, if so, take a snapshot of the object's
-- current position and velocity.
--
-- It proceeds by detecting whether any collision affects the ball's velocity,
-- and outputs a snapshot of the object position and the corrected velocity if
-- necessary.
-- NOTE: To avoid infinite loops when switching, the initial input is discarded
-- and never causes a bounce. Careful: this prevents the ball from bouncing
-- immediately after creation, which may or may not be what we want.
ballBounce :: ObjectName -> SF (ObjectInput, Object) (Event (Pos2D, Vel2D))
ballBounce bid = noEvent --> proc (ObjectInput ci cs, o) -> do
-- HN 2014-09-07: With the present strategy, need to be able to
-- detect an event directly after
-- ev <- edgeJust -< changedVelocity "ball" cs
let collisionsWithoutBalls = filter (not . allBalls) cs
allBalls (Collision cdata) = all (collisionObjectKind Ball . fst) cdata
let collisionsWithoutPlayer = filter (not . anyPlayer)
collisionsWithoutBalls
anyPlayer (Collision cdata) = any (collisionObjectKind Player . fst) cdata
let ev = maybeToEvent (changedVelocity (bid, Ball) collisionsWithoutPlayer)
returnA -< fmap (\v -> (objectPos o, v)) ev
-- | Position of the ball, starting from p0 with velicity v0, since the time of
-- last switching (that is, collision, or the beginning of time if never
-- switched before), provided that no obstacles are encountered.
freeBall :: ObjectName -> Double -> Pos2D -> Vel2D -> ObjectSF
freeBall name size p0 v0 = proc (ObjectInput ci cs) -> do
-- Integrate acceleration, add initial velocity and cap speed. Resets both
-- the initial velocity and the current velocity to (0,0) when the user
-- presses the Halt key (hence the dependency on the controller input ci).
vInit <- startAs v0 -< ci
vel <- vdiffSF -< (vInit, (0, -1000.8), ci)
-- Any free moving object behaves like this (but with
-- acceleration. This should be in some FRP.NewtonianPhysics
-- module)
pos <- (p0 ^+^) ^<< integral -< vel
let obj = Object { objectName = name
, objectKind = Ball
, objectProperties = BallProps size
, objectPos = pos
, objectVel = vel
, canCauseCollisions = True
, collisionEnergy = 1
}
returnA -< obj
where
-- Spike every time the user presses the Halt key
restartCond = spikeOn (arr controllerStop)
-- Calculate the velocity, restarting when the user
-- requests it.
vdiffSF = proc (iv, acc, ci) -> do
-- Calculate velocity difference by integrating acceleration
-- Reset calculation when user requests to stop balls
vd <- restartOn (fst ^>> integral)
(snd ^>> restartCond) -< (acc, ci)
-- Add initial velocity, and cap the result
v <- arr (uncurry (^+^)) -< (iv, vd)
let vFinal = limitNorm v (maxVNorm size)
returnA -< vFinal
-- Initial velocity, reset when the user requests it.
startAs v0 = revSwitch (constant v0 &&& restartCond)
(\_ -> startAs (0,0))
|
keera-studios/pang-a-lambda
|
src/Game/Objects/Balls.hs
|
gpl-3.0
| 7,428 | 14 | 19 | 1,844 | 1,307 | 716 | 591 | 79 | 2 |
{-# OPTIONS -cpp #-}
{-# LANGUAGE CPP, ForeignFunctionInterface #-}
------------------------------------------------------------------------
-- Program for converting .hsc files to .hs files, by converting the
-- file into a C program which is run to generate the Haskell source.
-- Certain items known only to the C compiler can then be used in
-- the Haskell module; for example #defined constants, byte offsets
-- within structures, etc.
--
-- See the documentation in the Users' Guide for more details.
#if defined(__GLASGOW_HASKELL__) && !defined(BUILD_NHC)
#include "../../includes/ghcconfig.h"
#endif
import Control.Monad ( liftM, forM_ )
import Data.List ( isSuffixOf )
import System.Console.GetOpt
#if defined(mingw32_HOST_OS)
import Foreign
import Foreign.C.String
#endif
import System.Directory ( doesFileExist, findExecutable )
import System.Environment ( getProgName, getArgs )
import System.Exit ( ExitCode(..), exitWith )
import System.FilePath ( normalise, splitFileName, splitExtension )
import System.IO
#ifdef BUILD_NHC
import System.Directory ( getCurrentDirectory )
#else
import Data.Version ( showVersion )
import Paths_hsc2hs as Main ( getDataFileName, version )
#endif
import Common
import CrossCodegen
import DirectCodegen
import Flags
import HSCParser
#ifdef mingw32_HOST_OS
# if defined(i386_HOST_ARCH)
# define WINDOWS_CCONV stdcall
# elif defined(x86_64_HOST_ARCH)
# define WINDOWS_CCONV ccall
# else
# error Unknown mingw32 arch
# endif
#endif
#ifdef BUILD_NHC
getDataFileName s = do here <- getCurrentDirectory
return (here++"/"++s)
version = "0.67" -- TODO!!!
showVersion = id
#endif
versionString :: String
versionString = "hsc2hs version " ++ showVersion version ++ "\n"
main :: IO ()
main = do
prog <- getProgramName
let header = "Usage: "++prog++" [OPTIONS] INPUT.hsc [...]\n"
usage = usageInfo header options
args <- getArgs
let (fs, files, errs) = getOpt Permute options args
let mode = foldl (.) id fs emptyMode
case mode of
Help -> bye usage
Version -> bye versionString
UseConfig config ->
case (files, errs) of
((_:_), []) -> processFiles config files usage
(_, _ ) -> die (concat errs ++ usage)
getProgramName :: IO String
getProgramName = liftM (`withoutSuffix` "-bin") getProgName
where str `withoutSuffix` suff
| suff `isSuffixOf` str = take (length str - length suff) str
| otherwise = str
bye :: String -> IO a
bye s = putStr s >> exitWith ExitSuccess
processFiles :: ConfigM Maybe -> [FilePath] -> String -> IO ()
processFiles configM files usage = do
mb_libdir <- getLibDir
(template, extraFlags) <- findTemplate usage mb_libdir configM
compiler <- findCompiler mb_libdir configM
let linker = case cmLinker configM of
Nothing -> compiler
Just l -> l
config = Config {
cmTemplate = Id template,
cmCompiler = Id compiler,
cmLinker = Id linker,
cKeepFiles = cKeepFiles configM,
cNoCompile = cNoCompile configM,
cCrossCompile = cCrossCompile configM,
cCrossSafe = cCrossSafe configM,
cVerbose = cVerbose configM,
cFlags = cFlags configM ++ extraFlags
}
let outputter = if cCrossCompile config then outputCross else outputDirect
forM_ files (\name -> do
(outName, outDir, outBase) <- case [f | Output f <- cFlags config] of
[] -> if not (null ext) && last ext == 'c'
then return (dir++base++init ext, dir, base)
else
if ext == ".hs"
then return (dir++base++"_out.hs", dir, base)
else return (dir++base++".hs", dir, base)
where
(dir, file) = splitFileName name
(base, ext) = splitExtension file
[f] -> let
(dir, file) = splitFileName f
(base, _) = splitExtension file
in return (f, dir, base)
_ -> onlyOne "output file"
let file_name = normalise name
toks <- parseFile file_name
outputter config outName outDir outBase file_name toks)
findTemplate :: String -> Maybe FilePath -> ConfigM Maybe
-> IO (FilePath, [Flag])
findTemplate usage mb_libdir config
= -- If there's no template specified on the commandline, try to locate it
case cmTemplate config of
Just t ->
return (t, [])
Nothing -> do
-- If there is no Template flag explicitly specified, try
-- to find one. We first look near the executable. This only
-- works on Win32 or Hugs (getExecDir). If this finds a template
-- file then it's certainly the one we want, even if hsc2hs isn't
-- installed where we told Cabal it would be installed.
--
-- Next we try the location we told Cabal about.
--
-- If neither of the above work, then hopefully we're on Unix and
-- there's a wrapper script which specifies an explicit template flag.
mb_templ1 <-
case mb_libdir of
Nothing -> return Nothing
Just path -> do
-- Euch, this is horrible. Unfortunately
-- Paths_hsc2hs isn't too useful for a
-- relocatable binary, though.
let
templ1 = path ++ "/template-hsc.h"
incl = path ++ "/include/"
exists1 <- doesFileExist templ1
if exists1
then return $ Just (templ1, CompFlag ("-I" ++ incl))
else return Nothing
case mb_templ1 of
Just (templ1, incl) ->
return (templ1, [incl])
Nothing -> do
templ2 <- getDataFileName "template-hsc.h"
exists2 <- doesFileExist templ2
if exists2 then return (templ2, [])
else die ("No template specified, and template-hsc.h not located.\n\n" ++ usage)
findCompiler :: Maybe FilePath -> ConfigM Maybe -> IO FilePath
findCompiler mb_libdir config
= case cmCompiler config of
Just c -> return c
Nothing ->
do let search_path = do
mb_path <- findExecutable default_compiler
case mb_path of
Nothing ->
die ("Can't find "++default_compiler++"\n")
Just path -> return path
-- if this hsc2hs is part of a GHC installation on
-- Windows, then we should use the mingw gcc that
-- comes with GHC (#3929)
inplaceGccs = case mb_libdir of
Nothing -> []
Just d -> [d ++ "/../mingw/bin/gcc.exe"]
search [] = search_path
search (x : xs) = do b <- doesFileExist x
if b then return x else search xs
search inplaceGccs
parseFile :: String -> IO [Token]
parseFile name
= do h <- openBinaryFile name ReadMode
-- use binary mode so we pass through UTF-8, see GHC ticket #3837
-- But then on Windows we end up turning things like
-- #let alignment t = e^M
-- into
-- #define hsc_alignment(t ) printf ( e^M);
-- which gcc doesn't like, so strip out any ^M characters.
s <- hGetContents h
let s' = filter ('\r' /=) s
case runParser parser name s' of
Success _ _ _ toks -> return toks
Failure (SourcePos name' line) msg ->
die (name'++":"++show line++": "++msg++"\n")
getLibDir :: IO (Maybe String)
getLibDir = fmap (fmap (++ "/lib")) $ getExecDir "/bin/hsc2hs.exe"
-- (getExecDir cmd) returns the directory in which the current
-- executable, which should be called 'cmd', is running
-- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
-- you'll get "/a/b/c" back as the result
getExecDir :: String -> IO (Maybe String)
getExecDir cmd =
getExecPath >>= maybe (return Nothing) removeCmdSuffix
where initN n = reverse . drop n . reverse
removeCmdSuffix = return . Just . initN (length cmd) . normalise
getExecPath :: IO (Maybe String)
#if defined(mingw32_HOST_OS)
getExecPath = try_size 2048 -- plenty, PATH_MAX is 512 under Win32.
where
try_size size = allocaArray (fromIntegral size) $ \buf -> do
ret <- c_GetModuleFileName nullPtr buf size
case ret of
0 -> return Nothing
_ | ret < size -> fmap Just $ peekCWString buf
| otherwise -> try_size (size * 2)
foreign import WINDOWS_CCONV unsafe "windows.h GetModuleFileNameW"
c_GetModuleFileName :: Ptr () -> CWString -> Word32 -> IO Word32
#else
getExecPath = return Nothing
#endif
|
jwiegley/ghc-release
|
utils/hsc2hs/Main.hs
|
gpl-3.0
| 9,041 | 1 | 22 | 2,866 | 1,982 | 1,026 | 956 | 140 | 7 |
module FRP.Chimera.Environment.Spatial
(
EnvironmentWrapping (..)
) where
data EnvironmentWrapping = ClipToMax | WrapHorizontal | WrapVertical | WrapBoth deriving (Show, Read)
|
thalerjonathan/phd
|
coding/libraries/chimera/src/FRP/Chimera/Environment/Spatial.hs
|
gpl-3.0
| 185 | 0 | 6 | 29 | 44 | 28 | 16 | 4 | 0 |
-- kata location:
-- https://leetcode.com/problems/two-sum/
--
-- goal: find the 2 indices of integers in a list that sum results in the target
-- ie:
-- list = [2, 7, 9, 11] and target = 9
-- solution is [0,1]
-- because 7 + 2 = 9
--
-- nothing is said about the order of the elements in the list (sorted or not)
-- but only ONE solution is possible
-- also, I suppose that all elements in the list are unique
-- libs
import Data.List
-- Entries
list :: [Int]
list = [2, 7, 11, 15]
target :: Int
target = 9
-- algo
-- I think I need a recursive thing to simply try all combinations
-- and stop when I found the target sum
-- here is a one liner ;)
solution = [(x `elemIndex` list, y `elemIndex` list)
| x <- list, y <- tail list, x+y==target]
-- lets turn that into a function and let's try a bunch of patterns
process :: Int -> [Int] -> Maybe (Maybe Int, Maybe Int)
process t l
| set == [] = Nothing
| set /= [] = Just $ head set
where set = [(x `elemIndex` l, y `elemIndex` l) | x <- l, y <- tail l, x + y == t]
-- preparing a bunch of lists to test
list1 :: [Int]
list1 = [1, 4, 6, 3, 8, 10, 14]
list2 :: [Int]
list2 = [20, 8, 9, 4, 7, 13, 2]
list3 :: [Int]
list3 = [1..30]
-- test a list with no solution
list4 :: [Int]
list4 = [1,2,3,4]
-- let's run that
run = do
print (process target list)
print (process target list1)
print (process target list2)
print (process target list3)
print (process target list4)
|
simonced/haskell-kata
|
training/1_twosum.hs
|
gpl-3.0
| 1,461 | 0 | 10 | 342 | 440 | 252 | 188 | 26 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( getApplicationDev
, appMain
, develMain
, makeFoundation
-- * for DevelMain
, getApplicationRepl
, shutdownApp
-- * for GHCI
, handler
, db
) where
import Control.Monad.Logger (liftLoc, runLoggingT)
import Database.Persist.Postgresql (createPostgresqlPool, pgConnStr,
pgPoolSize, runSqlPool, runMigrationUnsafe)
import Import
import Language.Haskell.TH.Syntax (qLocation)
import Network.Wai.Handler.Warp (Settings, defaultSettings,
defaultShouldDisplayException,
runSettings, setHost,
setOnException, setPort, getPort)
import Network.Wai.Middleware.RequestLogger (Destination (Logger),
IPAddrSource (..),
OutputFormat (..), destination,
mkRequestLogger, outputFormat)
import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet,
toLogStr)
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Common
import Handler.Home
import Handler.Wallet
import Handler.Settings
import Handler.Update
import Handler.Stock
import Handler.ProfitItems
import Handler.Orders
import Handler.Item
import Handler.Problematic
import Handler.LostOrders
-- This line actually creates our YesodDispatch instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
-- comments there for more details.
mkYesodDispatch "App" resourcesApp
-- | This function allocates resources (such as a database connection pool),
-- performs initialization and return a foundation datatype value. This is also
-- the place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeFoundation :: AppSettings -> IO App
makeFoundation appSettings = do
-- Some basic initializations: HTTP connection manager, logger, and static
-- subsite.
appHttpManager <- newManager
appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger
appStatic <-
(if appMutableStatic appSettings then staticDevel else static)
(appStaticDir appSettings)
-- We need a log function to create a connection pool. We need a connection
-- pool to create our foundation. And we need our foundation to get a
-- logging function. To get out of this loop, we initially create a
-- temporary foundation without a real connection pool, get a log function
-- from there, and then create the real foundation.
let mkFoundation appConnPool = App {..}
tempFoundation = mkFoundation $ error "connPool forced in tempFoundation"
logFunc = messageLoggerSource tempFoundation appLogger
-- Create the database connection pool
pool <- flip runLoggingT logFunc $ createPostgresqlPool
(pgConnStr $ appDatabaseConf appSettings)
(pgPoolSize $ appDatabaseConf appSettings)
-- Perform database migration using our application's logging settings.
runLoggingT (runSqlPool (runMigrationUnsafe migrateAll) pool) logFunc
-- Return the foundation
return $ mkFoundation pool
-- | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and
-- applyng some additional middlewares.
makeApplication :: App -> IO Application
makeApplication foundation = do
logWare <- mkRequestLogger def
{ outputFormat =
if appDetailedRequestLogging $ appSettings foundation
then Detailed True
else Apache
(if appIpFromHeader $ appSettings foundation
then FromFallback
else FromSocket)
, destination = Logger $ loggerSet $ appLogger foundation
}
-- Create the WAI application and apply middlewares
appPlain <- toWaiAppPlain foundation
return $ logWare $ defaultMiddlewaresNoLogging appPlain
-- | Warp settings for the given foundation value.
warpSettings :: App -> Settings
warpSettings foundation =
setPort (appPort $ appSettings foundation)
$ setHost (appHost $ appSettings foundation)
$ setOnException (\_req e ->
when (defaultShouldDisplayException e) $ messageLoggerSource
foundation
(appLogger foundation)
$(qLocation >>= liftLoc)
"yesod"
LevelError
(toLogStr $ "Exception from Warp: " ++ show e))
defaultSettings
-- | For yesod devel, return the Warp settings and WAI Application.
getApplicationDev :: IO (Settings, Application)
getApplicationDev = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app <- makeApplication foundation
return (wsettings, app)
getAppSettings :: IO AppSettings
getAppSettings = loadYamlSettings [configSettingsYml] [] useEnv
-- | main function for use by yesod devel
develMain :: IO ()
develMain = develMainHelper getApplicationDev
-- | The @main@ function for an executable running this site.
appMain :: IO ()
appMain = do
-- Get the settings from all relevant sources
settings <- loadYamlSettingsArgs
-- fall back to compile-time values, set to [] to require values at runtime
[configSettingsYmlValue]
-- allow environment variables to override
useEnv
-- Generate the foundation from the settings
foundation <- makeFoundation settings
-- Generate a WAI Application from the foundation
app <- makeApplication foundation
-- Run the application with Warp
runSettings (warpSettings foundation) app
--------------------------------------------------------------
-- Functions for DevelMain.hs (a way to run the app from GHCi)
--------------------------------------------------------------
getApplicationRepl :: IO (Int, App, Application)
getApplicationRepl = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app1 <- makeApplication foundation
return (getPort wsettings, foundation, app1)
shutdownApp :: App -> IO ()
shutdownApp _ = return ()
---------------------------------------------
-- Functions for use in development with GHCi
---------------------------------------------
-- | Run a handler
handler :: Handler a -> IO a
handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h
-- | Run DB queries
db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a
db = handler . runDB
|
Drezil/neat
|
Application.hs
|
gpl-3.0
| 6,852 | 0 | 16 | 1,734 | 1,057 | 568 | 489 | -1 | -1 |
{-# LANGUAGE TemplateHaskell, FlexibleContexts, PatternGuards #-}
module GGen.Geometry.Intersect ( rayLineSeg2Intersect
, lineLineSeg2Intersect
, lineSegLineSeg2Intersect
, lineLine2Intersect
, faceLineIntersect
, planeLineSegIntersect
, planeFaceIntersect
, GGen.Geometry.Intersect.runTests
) where
import Debug.Trace
import Data.VectorSpace
import Data.AffineSpace
import GGen.Geometry.Types
import GGen.Geometry.LineSeg
import Data.Maybe (mapMaybe, isJust, fromJust)
import Control.Monad (when)
import qualified GGen.Pretty as P
import GGen.Pretty (($$), (<+>))
import Test.QuickCheck.All
import Test.QuickCheck.Property
import Test.QuickCheck.Modifiers (NonZero(..))
import Data.VectorSpace.QuickCheck
import Data.Cross
-- | Test whether a point falls on a line
pointOnLine :: (InnerSpace v, RealFloat (Scalar v)) => Point v -> Line v -> Bool
pointOnLine p (Line {lPoint=p'}) | p `coincident` p' = True
pointOnLine (P p) (Line {lPoint=P a, lDir=m}) | magnitude p == 0 =
a `parallel` m
pointOnLine (P r) (Line {lPoint=P a, lDir=m}) =
let t = (magnitudeSq r - r <.> a) / (r <.> m)
in P r `coincident` (P a .+^ t *^ m)
-- | Point of intersection between a ray and a line segment in two dimensions
rayLineSeg2Intersect :: Ray R2 -> LineSeg R2 -> Intersection P2
rayLineSeg2Intersect u v@(LineSeg va vb)
| IIntersect (ut, vt) <- i = if ut >~ 0 && vt >~ 0 && vt <= 1
then IIntersect $ va .+^ lsDispl v ^* vt
else INull
| IDegenerate <- i = IDegenerate
| INull <- i = INull
where i = lineLine2Intersect' (Line {lPoint=rBegin u, lDir=rDir u}) (Line {lPoint=va, lDir=lsDispl v})
-- | Point of intersection between a line and a line segment in two dimensions
lineLineSeg2Intersect :: Line R2 -> LineSeg R2 -> Intersection P2
lineLineSeg2Intersect l v@(LineSeg va vb)
| IIntersect (ut, vt) <- i = if vt >~ 0 && vt <~ 1
then IIntersect $ va .+^ lsDispl v ^* vt
else INull
| IDegenerate <- i = IDegenerate
| INull <- i = INull
where i = lineLine2Intersect' l (Line {lPoint=va, lDir=lsDispl v})
-- | Point of intersection between two line segments in two dimensions
lineSegLineSeg2Intersect :: LineSeg R2 -> LineSeg R2 -> Intersection P2
lineSegLineSeg2Intersect u@(LineSeg ua ub) v@(LineSeg va vb)
| IIntersect (ut, vt) <- i = if ut >~ 0 && ut <~ 1 && vt >~ 0 && vt <~ 1
then IIntersect $ ua .+^ lsDispl u ^* ut
else INull
| IDegenerate <- i = let la = lsDispl u <.> (ua .-. va)
lb = lsDispl u <.> (ua .-. vb)
in case () of
_ | la*lb < 0 -> IDegenerate
_ | otherwise -> INull
| INull <- i = INull
where i = lineLine2Intersect' (Line {lPoint=ua, lDir=lsDispl u}) (Line {lPoint=va, lDir=lsDispl v})
-- | Point of intersection between two lines in two dimensions
lineLine2Intersect :: Line R2 -> Line R2 -> Intersection P2
lineLine2Intersect u@(Line {lPoint=ua, lDir=m}) v
| IIntersect (tu, tv) <- i = IIntersect $ ua .+^ tu *^ m
| IDegenerate <- i = IDegenerate
| INull <- i = INull
where i = lineLine2Intersect' u v
-- | Parameters (tu, tv) of intersection between two lines in two dimensions
lineLine2Intersect' :: Line R2 -> Line R2 -> Intersection (Double,Double)
lineLine2Intersect' u v
| m `parallel` n && ua `pointOnLine` v = IDegenerate
| otherwise = IIntersect (tu, tv)
where Line {lPoint=ua, lDir=m} = u
Line {lPoint=va, lDir=n} = v
mm = magnitudeSq m
nn = magnitudeSq n
-- Length along line u
tu = ((m ^/ mm) <.> (va.-.ua) + ((ua.-.va) <.> (n ^/ nn)) * (n <.> (m ^/ mm)))
/ (1 - (m <.> n)^2 / (mm*nn))
tv = ((tu *^ m + (ua.-.va)) <.> n) / nn -- Length along line v
-- | Point of intersection between a face and a line
-- Using Moeller, Trumbore (1997)
faceLineIntersect :: Face -> Line R3 -> Intersection P3
faceLineIntersect (Face {faceVertices=(P v0,P v1,P v2)}) (Line {lPoint=P p, lDir=d}) =
do let u = v1 - v0
v = v2 - v0
pp = d `cross3` v
det = u <.> pp
when (abs det <~ 0) INull
let tt = p - v0
uu = (tt <.> pp) / det
when (uu <~ 0 || uu >~ 1) INull
let qq = tt `cross3` u
vv = (d <.> qq) / det
when (vv <~ 0 || uu+vv >~ 1) INull
let t = (v <.> qq) / det
return $ P $ p + t *^ d
-- | Check whether a point sits on a plane
pointOnPlane :: Plane R3 -> P3 -> Bool
pointOnPlane (Plane {planePoint=v, planeNormal=n}) p =
abs ((p.-.v) <.> n) =~ 0
-- | Find point of intersection of a plane and line
planeLineIntersect :: Plane R3 -> Line R3 -> Intersection P3
planeLineIntersect plane line@(Line {lPoint=a, lDir=m})
| planeNormal plane `perpendicular` m && pointOnPlane plane a =
IDegenerate
| otherwise =
IIntersect $ a .+^ m ^* planeLineIntersect' plane line
-- | Find value of parameter t of the line $\vec r = \vec A*t + \vec B$ for the
-- intersection with plane
planeLineIntersect' :: Plane R3 -> Line R3 -> Double
planeLineIntersect' (Plane {planeNormal=n, planePoint=v0}) (Line{lPoint=a, lDir=m}) =
(n <.> (v0 .-. a)) / (n <.> m)
-- | Point of intersection between plane and line segment
planeLineSegIntersect :: Plane R3 -> LineSeg R3 -> Intersection P3
planeLineSegIntersect plane (LineSeg a b)
| perpendicular n (b.-.a)
&& pointOnPlane plane a = IDegenerate
| t < 0 = INull
| t > 1 = INull
| otherwise = IIntersect $ alerp a b t
where Plane {planeNormal=n, planePoint=v} = plane
t = (n <.> (v.-.a)) / (n <.> (b.-.a))
-- | Line segment of intersection between plane and face
planeFaceIntersect :: Plane R3 -> Face -> Intersection (LineSeg R3)
planeFaceIntersect plane face@(Face {faceVertices=(a,b,c)})
| aOnPlane && bOnPlane && cOnPlane = IDegenerate
| aOnPlane && bOnPlane = IIntersect (LineSeg a b)
| aOnPlane && cOnPlane = IIntersect (LineSeg a c)
| bOnPlane && cOnPlane = IIntersect (LineSeg b c)
| otherwise =
let lines = map (uncurry LineSeg) [(a,b), (b,c), (c,a)]
f l | IIntersect p <- i = Just p
| otherwise = Nothing
where i = planeLineSegIntersect plane l
lineIntersects = nubPoints $ mapMaybe f lines
in case length lineIntersects of
0 -> INull
1 -> INull -- TODO: Or perhaps IDegenerate?
2 -> IIntersect $ LineSeg (head lineIntersects) (last lineIntersects)
3 -> IDegenerate
otherwise -> error (show $ P.text "Error while finding plane-face intersection:"
$$ P.text "Unexpected number of intersections"
$$ P.nest 2 (P.vcat $ map P.point lineIntersects)
$$ P.text "Face: " $$ P.nest 2 (P.face face)
$$ P.text "Plane: " $$ P.nest 2 (P.plane plane))
where aOnPlane = pointOnPlane plane a
bOnPlane = pointOnPlane plane b
cOnPlane = pointOnPlane plane c
-- QuickCheck properties
-- Properties for rayLineSeg2Intersect
-- | Check that ray-line segment intersections are found
prop_ray_line_seg2_intersection_hit :: NonNull (LineSeg R2) -> P2 -> Normalized Double -> Result
prop_ray_line_seg2_intersection_hit (NonNull l@(LineSeg a b)) rayBegin (Normalized t)
| rayDir `parallel` (lsDispl l) = rejected
| otherwise = case rayLineSeg2Intersect (Ray {rBegin=rayBegin, rDir=rayDir}) l of
IIntersect i -> if coincident i intersect
then succeeded
else failed {reason="Incorrect intersection"}
otherwise -> failed {reason="No intersection"}
where intersect = alerp a b t
rayDir = normalized $ intersect .-. rayBegin
-- Properties for lineSegLineSeg2Intersect
-- | Check that line segment-line segment intersections are found
prop_line_seg_line_seg2_intersection_hit :: NonNull (LineSeg R2) -> P2 -> Normalized Double -> Result
prop_line_seg_line_seg2_intersection_hit (NonNull l@(LineSeg a b)) v (Normalized t)
| parallel (lsDispl l) (lsDispl l') = rejected
| otherwise = case lineSegLineSeg2Intersect l l' of
IIntersect i -> if coincident i intersect
then succeeded
else failed {reason="Incorrect intersection"}
otherwise -> failed {reason="No intersection"}
where intersect = alerp a b t
l' = LineSeg {lsA=v, lsB=v .+^ 2*(intersect .-. v)}
-- Properties for lineLine2Intersect
-- | Check that intersect falls on both lines
prop_line_line2_intersection_on_both :: Line R2 -> Line R2 -> Result
prop_line_line2_intersection_on_both u@(Line {lPoint=up, lDir=ud}) v@(Line {lPoint=vp, lDir=vd})
| vd `parallel` ud = rejected
| otherwise = case lineLine2Intersect u v of
IIntersect i -> let t = ((i .-. up) <.> ud) / magnitudeSq ud
t' = ((i .-. vp) <.> vd) / magnitudeSq vd
in liftBool $ magnitude ((up .+^ ud^*t ) .-. i) < 1e-8
&& magnitude ((vp .+^ vd^*t') .-. i) < 1e-8
-- Properties for faceLineIntersect
-- | Check that face-line intersections are found
prop_face_line_intersection_hit :: Face -> NormalizedV NR3 -> Normalized Double -> Result
prop_face_line_intersection_hit face@(Face {faceVertices=(v0,v1,v2)}) (NormalizedV dir) (Normalized a)
| magnitude ((v1.-.v0) `cross3` (v2.-.v0)) =~ 0 = rejected
| otherwise =
let tol = 1e-8
u = v1 .-. v0
v = v2 .-. v0
a' = (1-tol) * a -- Avoid numerical error near edges
b' = (1-tol) - a'
hitPoint = v0 .+^ a' *^ u + b' *^ v
origin = hitPoint .-^ dir
in case faceLineIntersect face (Line {lPoint=origin, lDir=dir}) of
IIntersect intersect -> liftBool $ magnitude (intersect .-. hitPoint) < 1e-5
INull -> failed {reason="No intersection found"}
-- | Check that only intersections are found
prop_face_line_intersection_miss :: Face -> NormalizedV NR3 -> Normalized Double -> Result
prop_face_line_intersection_miss face@(Face {faceVertices=(v0,v1,v2)}) (NormalizedV dir) (Normalized a) =
let tol = 1e-8
u = v1 .-. v0
v = v2 .-. v0
a' = (1-tol) * a
b' = (1-tol) * a'
hitPoint = v0 .-^ a' *^ u - b' *^ v
origin = hitPoint .-^ dir
in case faceLineIntersect face (Line {lPoint=origin, lDir=dir}) of
IIntersect intersect -> failed {reason="Found non-existent intersection"}
INull -> succeeded
-- Properties for planeLineIntersect
-- | Check that line-plane intersection point falls on plane
prop_plane_line_intersection_on_plane :: Line R3 -> Plane R3 -> Bool
prop_plane_line_intersection_on_plane line plane@(Plane n (P p)) =
abs ((i - p) <.> n) < 1e-8
where IIntersect (P i) = planeLineIntersect plane line
-- | Check that line-plane intersection point falls on line
prop_plane_line_intersection_on_line :: Line R3 -> Plane R3 -> Bool
prop_plane_line_intersection_on_line line@(Line {lPoint=P v, lDir=d}) plane =
magnitude (lambda *^ d + v - p) < 1e-8
where IIntersect (P p) = planeLineIntersect plane line
lambda = (p - v) <.> d ^/ magnitudeSq d
-- | Check that line falling on plane is degenerate
prop_plane_line_intersection_degenerate :: Plane R3 -> R3 -> NonNull R3 -> Bool
prop_plane_line_intersection_degenerate plane@(Plane {planeNormal=n, planePoint=p}) a (NonNull b) =
case planeLineIntersect plane line of
IDegenerate -> True
otherwise -> False
where b' = b - n ^* (n <.> b)
line = Line {lPoint=p .+^ a `cross3` n, lDir=normalized b'}
-- Properties for pointOnPlane
-- | Check that point on plane is recognized
prop_point_on_plane_hit :: Plane R3 -> R3 -> Bool
prop_point_on_plane_hit plane v =
pointOnPlane plane (planePoint plane .+^ v')
where n = planeNormal plane
v' = v - n ^* (v <.> n)
-- | Check that point off plane is recognized
prop_point_on_plane_miss :: Plane R3 -> NonNull R3 -> Result
prop_point_on_plane_miss plane@(Plane {planeNormal=n}) (NonNull v)
| abs (n <.> v) < 1e-8 = rejected
| otherwise = liftBool $ not $ pointOnPlane plane (P v)
-- Properties for planeFaceIntersect
-- | Check that a face sitting in the plane is recognized as degenerate
prop_plane_face_intersect_face_in_plane :: Plane R3 -> NonNull R3 -> NonNull R3 -> NonNull R3 -> Bool
prop_plane_face_intersect_face_in_plane plane (NonNull a) (NonNull b) (NonNull c) =
case planeFaceIntersect plane face of
IDegenerate -> True
otherwise -> False
where Plane {planePoint=p, planeNormal=n} = plane
proj x = x - n ^* (n <.> x) -- Project onto plane
vs = (p .+^ proj a, p .+^ proj b, p .+^ proj c)
face = faceFromVertices vs
-- | Check that a face intersection with a plane gives a line segment
prop_plane_face_intersect_face_intersects_plane :: Plane R3 -> NonZero R3 -> NonZero R3 -> NonZero R3 -> Result
prop_plane_face_intersect_face_intersects_plane plane (NonZero a) (NonZero b) (NonZero c)
| parallel (faceNormal face) (planeNormal plane) = rejected
| otherwise =
case planeFaceIntersect plane face of
IIntersect _ -> succeeded
otherwise -> failed
where d = planePoint plane .-^ (a + b + c) ^/ 3 -- Displacement from center of points to planePoint
face = faceFromVertices (d.+^a, d.+^b, d.+^c)
-- | Check face with one edge sitting on plane
prop_plane_face_intersect_edge_on_plane :: Plane R3 -> NonZero R3 -> NonZero R3 -> NonNull R3 -> Result
prop_plane_face_intersect_edge_on_plane plane (NonZero a) (NonZero b) (NonNull c) =
case planeFaceIntersect plane face of
IIntersect l -> let d = lsDispl l
d' = lsDispl (LineSeg a' b')
in if 1 - abs (d <.> d') > 1e-8
then failed {reason="Line of intersection has incorrect direction"}
else if abs (magnitude d - magnitude d') > 1e-8
then failed {reason="Line of intersection has incorrect magnitude"}
else succeeded
otherwise -> failed {reason="No intersection found"}
where Plane {planePoint=p, planeNormal=n} = plane
a' = p .+^ projInPlane plane a
b' = p .+^ projInPlane plane b
c' = p .+^ c
face = faceFromVertices (a', b', c')
-- Properties for planeLineSegIntersect
-- | Check that line sitting in plane is degenerate
prop_plane_line_seg_intersect_line_in_plane :: Plane R3 -> NonZero R3 -> NonZero R3 -> Bool
prop_plane_line_seg_intersect_line_in_plane plane (NonZero a) (NonZero b) =
case planeLineSegIntersect plane l of
IDegenerate -> True
otherwise -> False
where Plane {planePoint=p, planeNormal=n} = plane
proj = projInPlane plane
l = LineSeg (p .+^ proj a) (p .+^ proj b)
-- | Check that non-degenerate plane-line segment intersections work
prop_plane_line_seg_intersect_hit :: Plane R3 -> NonZero R3 -> Result
prop_plane_line_seg_intersect_hit plane (NonZero a)
| perpendicular (planeNormal plane) a = rejected
| otherwise =
case planeLineSegIntersect plane l of
IIntersect i -> if magnitude (i.-.p) < 1e-8 then succeeded
else failed {reason="Incorrect intersection"}
otherwise -> failed {reason="No intersection found"}
where p = planePoint plane
l = LineSeg (p .+^ a) (p .-^ a)
-- | Check that line parallel to plane sitting out of plane doesn't intersect
prop_plane_line_seg_intersect_parallel_off_plane :: Plane R3 -> NonZero Double -> R3 -> NonZero R3 -> Result
prop_plane_line_seg_intersect_parallel_off_plane plane (NonZero s) a (NonZero b) =
case planeLineSegIntersect plane l of
INull -> succeeded
otherwise -> failed
where Plane {planeNormal=n, planePoint=p} = plane
a' = (p .+^ n ^* s) .+^ projInPlane plane a
b' = a' .+^ projInPlane plane b
l = LineSeg a' b'
runTests = $quickCheckAll
|
bgamari/GGen
|
GGen/Geometry/Intersect.hs
|
gpl-3.0
| 18,474 | 0 | 22 | 6,499 | 5,308 | 2,763 | 2,545 | 277 | 5 |
module Mudblood.Contrib.Lisp
( module Mudblood.Contrib.Lisp.Core
, module Mudblood.Contrib.Lisp.MB
, module Mudblood.Contrib.Lisp.Builtins
) where
import Mudblood.Contrib.Lisp.Core
import Mudblood.Contrib.Lisp.MB
import Mudblood.Contrib.Lisp.Builtins
|
talanis85/mudblood
|
src/Mudblood/Contrib/Lisp.hs
|
gpl-3.0
| 268 | 0 | 5 | 36 | 54 | 39 | 15 | 7 | 0 |
module Geimskell.Render
( HasImage (..)
, renderRectangle
, red
, blue
)
where
import Data.Array
import Enemy
import Geimskell.WorldState
import Geometry
import qualified Linear.V2 as L
import Reactive
import SDL.Compositor
import SDL.Compositor.ResIndependent
import Shoot
import Spaceship
import Stage
import TileSet
red, blue, green :: Color
red = rgba 255 0 0 255
blue = rgba 0 0 255 255
green = rgba 0 255 0 255
renderRectangle :: Color -> Rectangle -> ResIndependentImage
renderRectangle col rect =
translateR offset (filledRectangleR (L.V2 width height) col)
where
width = abs $ (pointX . rectangleA $ rect) - (pointX . rectangleB $ rect)
height = abs $ (pointY . rectangleA $ rect) - (pointY . rectangleB $ rect)
offset =
L.V2
(avg (pointX . rectangleA $ rect) (pointX . rectangleB $ rect))
(avg (pointY . rectangleA $ rect) (pointY . rectangleB $ rect))
avg a b = (a+b)/2
class HasResolutionIndependentImage a where
renderResolutionIndependentImage :: Number -> a -> ResIndependentImage
instance (HasResolutionIndependentImage a) => HasResolutionIndependentImage [a] where
renderResolutionIndependentImage cameraPosition =
mconcat . map (renderResolutionIndependentImage cameraPosition)
class HasImage a where
renderImage :: Number -> a -> Image
instance (HasImage a) => HasImage [a] where
renderImage cameraPosition = mconcat . map (renderImage cameraPosition)
adjustToCameraR :: Number -> ResIndependentImage -> ResIndependentImage
adjustToCameraR cameraPosition =
translateR (L.V2 (-cameraPosition) 0) .
translateR (L.V2 0.5 0.5) .
flipC (L.V2 False True)
fromResolutionIndependent :: (HasResolutionIndependentImage a)
=> Number -> a -> Image
fromResolutionIndependent cameraPosition x =
fromRelativeCompositor
(fromIntegral <$> L.V2 screenWidth screenHeight)
(renderResolutionIndependentImage cameraPosition x)
instance HasImage Stage where
renderImage camPosition stage =
mconcat . fmap makeImage . filter onScreen . assocs $ (stageData stage)
where
camPositionAbsolute = floor $ camPosition * 600
tileWidth = 32 :: Int
tileHeight = 32 :: Int
relativeWidth = 1/fromIntegral tileWidth :: Number
makeImage (_,Nothing) = mempty
makeImage ((x,y), Just tile) =
( translateA
( L.V2
(x * tileWidth - camPositionAbsolute)
(y * tileHeight + tileHeight `div` 2)
)
) $
sizedA (L.V2 tileWidth tileHeight) (tileTexture tile)
onScreen ((gridXPos,_),_) =
-- gridXPos is just the position in the tilegrid and has nothing
-- to do with the actual position on the screen
x * relativeWidth > camPosition - 2 &&
x * relativeWidth < camPosition + 2
where
x = fromIntegral gridXPos
instance HasResolutionIndependentImage PlayerShip where
renderResolutionIndependentImage xPosition playerShip =
adjustToCameraR xPosition .
renderRectangle blue $
playerShipRectangle playerShip
instance HasImage PlayerShip where
renderImage = fromResolutionIndependent
instance HasResolutionIndependentImage Projectile where
renderResolutionIndependentImage cameraPosition =
adjustToCameraR cameraPosition . renderRectangle red . projectileRect
instance HasImage Projectile where
renderImage = fromResolutionIndependent
instance HasResolutionIndependentImage Enemy where
renderResolutionIndependentImage camPosition =
adjustToCameraR camPosition . renderRectangle green . fromEnemy
instance HasImage Enemy where
renderImage = fromResolutionIndependent
instance HasResolutionIndependentImage WorldState where
renderResolutionIndependentImage xPosition worldstate = image
where
image =
(renderResolutionIndependentImage xPosition . wsEnemies $ worldstate) <>
(renderResolutionIndependentImage xPosition . wsProjectiles $ worldstate) <>
(renderResolutionIndependentImage xPosition . wsPlayer $ worldstate)
instance HasImage WorldState where
renderImage = fromResolutionIndependent
|
seppeljordan/geimskell
|
Geimskell/Render.hs
|
gpl-3.0
| 4,219 | 0 | 16 | 938 | 1,074 | 566 | 508 | 95 | 1 |
----------------------------------------------------------------------------
-- |
-- Module : $Header$
-- Copyright : (c) Proyecto Theona, 2012-2013
-- (c) Alejandro Gadea, Emmanuel Gunther, Miguel Pagano
-- License : <license>
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Definimos la noción de módulo de fun.
--
----------------------------------------------------------------------------
{-# Language TemplateHaskell #-}
module Fun.Module where
import Equ.Syntax ( Operator )
import Fun.Verification
import Fun.Declarations
import Fun.Derivation
import Control.Lens
import Data.Text (Text)
import Data.Function
type ModName = Text
data InvalidDeclsAndVerifs =
InvalidDeclsAndVerifs { decls :: InvalidDeclarations
, verifs :: [ErrInVerif Verification]
}
deriving Show
emptyInDeclsVerifs :: InvalidDeclsAndVerifs
emptyInDeclsVerifs = InvalidDeclsAndVerifs emptyInDecls []
data Import = Import ModName
deriving (Eq, Show)
data Module = Module { _pragmas :: [Operator]
, _modName :: ModName
, _imports :: [Import]
, _validDecls :: Declarations
, _invalidDecls :: InvalidDeclsAndVerifs
, _verifications :: [Verification]
, _derivations :: [Derivation]
}
$(makeLenses ''Module)
imName :: Lens' Import ModName
imName = lens (\(Import m) -> m) (\_ -> Import )
instance Eq Module where
(==) = (==) `on` (^. modName)
instance Show Module where
show m = unlines [ ""
, "========LoadModule========="
, "Pragmas: " ++ show (_pragmas m)
, "ModName: " ++ show (_modName m)
, "Imports: " ++ show (_imports m)
, ""
, "Decls: " ++ show (_validDecls m)
, ""
, "Verifications : " ++ show (_verifications m)
, "Derivations : " ++ show (_derivations m)
, "Invalid Decls : " ++ show (_invalidDecls m)
, "=========================="
]
allDeclsValid :: Module -> Bool
allDeclsValid m =
let invd = decls (_invalidDecls m) in
inSpecs invd == [] && inFunctions invd == [] &&
inTheorems invd == [] && inProps invd == [] &&
inVals invd == [] && inVals invd == [] &&
inDerivs invd == [] &&
verifs (_invalidDecls m) == []
|
alexgadea/fun
|
Fun/Module.hs
|
gpl-3.0
| 2,698 | 0 | 22 | 937 | 572 | 317 | 255 | 51 | 1 |
import System.Environment
import System.IO
import System.IO.Error
import Control.Exception
main = toTry `catch` handler
toTry :: IO ()
toTry = do
(fileName:_) <- getArgs
contents <- readFile fileName
putStrLn $ "The file has " ++ show (length (lines contents))++" lines!"
handler :: IOError -> IO ()
handler e
-- | isDoesNotExistError e = putStrLn "The file doesn't exist!"
| isDoesNotExistError e =
case ioeGetFileName e of
Just path -> putStrLn $ "Whoops! File does not exist at: " ++ path
Nothing -> putStrLn "Whoops! File does not exist at unknown location!"
| otherwise = ioError e
|
lamontu/learning_haskell
|
exceptions.hs
|
gpl-3.0
| 646 | 0 | 13 | 154 | 179 | 88 | 91 | 17 | 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.FirebaseRules.Projects.Rulesets.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- List \`Ruleset\` metadata only and optionally filter the results by
-- \`Ruleset\` name. The full \`Source\` contents of a \`Ruleset\` may be
-- retrieved with GetRuleset.
--
-- /See:/ <https://firebase.google.com/docs/storage/security Firebase Rules API Reference> for @firebaserules.projects.rulesets.list@.
module Network.Google.Resource.FirebaseRules.Projects.Rulesets.List
(
-- * REST Resource
ProjectsRulesetsListResource
-- * Creating a Request
, projectsRulesetsList
, ProjectsRulesetsList
-- * Request Lenses
, prlXgafv
, prlUploadProtocol
, prlAccessToken
, prlUploadType
, prlName
, prlFilter
, prlPageToken
, prlPageSize
, prlCallback
) where
import Network.Google.FirebaseRules.Types
import Network.Google.Prelude
-- | A resource alias for @firebaserules.projects.rulesets.list@ method which the
-- 'ProjectsRulesetsList' request conforms to.
type ProjectsRulesetsListResource =
"v1" :>
Capture "name" Text :>
"rulesets" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListRulesetsResponse
-- | List \`Ruleset\` metadata only and optionally filter the results by
-- \`Ruleset\` name. The full \`Source\` contents of a \`Ruleset\` may be
-- retrieved with GetRuleset.
--
-- /See:/ 'projectsRulesetsList' smart constructor.
data ProjectsRulesetsList =
ProjectsRulesetsList'
{ _prlXgafv :: !(Maybe Xgafv)
, _prlUploadProtocol :: !(Maybe Text)
, _prlAccessToken :: !(Maybe Text)
, _prlUploadType :: !(Maybe Text)
, _prlName :: !Text
, _prlFilter :: !(Maybe Text)
, _prlPageToken :: !(Maybe Text)
, _prlPageSize :: !(Maybe (Textual Int32))
, _prlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsRulesetsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'prlXgafv'
--
-- * 'prlUploadProtocol'
--
-- * 'prlAccessToken'
--
-- * 'prlUploadType'
--
-- * 'prlName'
--
-- * 'prlFilter'
--
-- * 'prlPageToken'
--
-- * 'prlPageSize'
--
-- * 'prlCallback'
projectsRulesetsList
:: Text -- ^ 'prlName'
-> ProjectsRulesetsList
projectsRulesetsList pPrlName_ =
ProjectsRulesetsList'
{ _prlXgafv = Nothing
, _prlUploadProtocol = Nothing
, _prlAccessToken = Nothing
, _prlUploadType = Nothing
, _prlName = pPrlName_
, _prlFilter = Nothing
, _prlPageToken = Nothing
, _prlPageSize = Nothing
, _prlCallback = Nothing
}
-- | V1 error format.
prlXgafv :: Lens' ProjectsRulesetsList (Maybe Xgafv)
prlXgafv = lens _prlXgafv (\ s a -> s{_prlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
prlUploadProtocol :: Lens' ProjectsRulesetsList (Maybe Text)
prlUploadProtocol
= lens _prlUploadProtocol
(\ s a -> s{_prlUploadProtocol = a})
-- | OAuth access token.
prlAccessToken :: Lens' ProjectsRulesetsList (Maybe Text)
prlAccessToken
= lens _prlAccessToken
(\ s a -> s{_prlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
prlUploadType :: Lens' ProjectsRulesetsList (Maybe Text)
prlUploadType
= lens _prlUploadType
(\ s a -> s{_prlUploadType = a})
-- | Required. Resource name for the project. Format:
-- \`projects\/{project_id}\`
prlName :: Lens' ProjectsRulesetsList Text
prlName = lens _prlName (\ s a -> s{_prlName = a})
-- | \`Ruleset\` filter. The list method supports filters with restrictions
-- on \`Ruleset.name\`. Filters on \`Ruleset.create_time\` should use the
-- \`date\` function which parses strings that conform to the RFC 3339
-- date\/time specifications. Example: \`create_time >
-- date(\"2017-01-01T00:00:00Z\") AND name=UUID-*\`
prlFilter :: Lens' ProjectsRulesetsList (Maybe Text)
prlFilter
= lens _prlFilter (\ s a -> s{_prlFilter = a})
-- | Next page token for loading the next batch of \`Ruleset\` instances.
prlPageToken :: Lens' ProjectsRulesetsList (Maybe Text)
prlPageToken
= lens _prlPageToken (\ s a -> s{_prlPageToken = a})
-- | Page size to load. Maximum of 100. Defaults to 10. Note: \`page_size\`
-- is just a hint and the service may choose to load less than
-- \`page_size\` due to the size of the output. To traverse all of the
-- releases, caller should iterate until the \`page_token\` is empty.
prlPageSize :: Lens' ProjectsRulesetsList (Maybe Int32)
prlPageSize
= lens _prlPageSize (\ s a -> s{_prlPageSize = a}) .
mapping _Coerce
-- | JSONP
prlCallback :: Lens' ProjectsRulesetsList (Maybe Text)
prlCallback
= lens _prlCallback (\ s a -> s{_prlCallback = a})
instance GoogleRequest ProjectsRulesetsList where
type Rs ProjectsRulesetsList = ListRulesetsResponse
type Scopes ProjectsRulesetsList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/firebase",
"https://www.googleapis.com/auth/firebase.readonly"]
requestClient ProjectsRulesetsList'{..}
= go _prlName _prlXgafv _prlUploadProtocol
_prlAccessToken
_prlUploadType
_prlFilter
_prlPageToken
_prlPageSize
_prlCallback
(Just AltJSON)
firebaseRulesService
where go
= buildClient
(Proxy :: Proxy ProjectsRulesetsListResource)
mempty
|
brendanhay/gogol
|
gogol-firebase-rules/gen/Network/Google/Resource/FirebaseRules/Projects/Rulesets/List.hs
|
mpl-2.0
| 6,706 | 0 | 19 | 1,542 | 976 | 568 | 408 | 135 | 1 |
module Proc.Compiled (compileProc, runCompiled) where
-- import Control.Monad.Except
import Proc.Params
import Proc.CodeBlock
data CompiledProc = CProc CodeBlock ParamList
compileProc params body = do
cb <- toCodeBlock body
return (CProc cb params)
runCompiled (CProc cb _) = runCodeBlock cb
|
tolysz/hiccup
|
Proc/Compiled.hs
|
lgpl-2.1
| 300 | 0 | 9 | 46 | 89 | 46 | 43 | 8 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Main (main) where
import Control.Monad
import Data.List
import Data.Maybe
import Test.HUnit hiding (Test)
import Test.Framework (Test, defaultMain, testGroup)
import Test.Framework.TH
import Test.Framework.Providers.HUnit
import BV
case_test1 = do
eval prog 0 @?= 0x0000000000000000
eval prog 1 @?= 0x0000000000000001
eval prog 2 @?= 0x0000000000000002
eval prog 3 @?= 0x0000000000000003
eval prog 4 @?= 0x0000000000000004
eval prog 5 @?= 0x0000000000000005
eval prog 0x112233 @?= 0x0000000000000033
eval prog 0x1122334455667788 @?= 0x00000000000000FF
eval prog 0xFFFFFFFFFFFFFFFF @?= 0x00000000000000FF
where
-- P = (lambda (x) (fold x 0 (lambda (y z) (or y z))))
prog = Program "x" (fold x b0 "y" "z" (or' y z))
x = var "x"
y = var "y"
z = var "z"
case_test2 = do
eval prog 0 @?= 0x00000000000055D5
eval prog 1 @?= 0x00000000000054D5
eval prog 0x12345 @?= 0x00000000012310D5
where
-- P = (lambda (x_65671) (fold (shr1 (or (not (xor (plus x_65671 (shr1 (if0 (or (plus (shl1 x_65671) x_65671) x_65671) 0 1))) x_65671)) 0)) x_65671 (lambda (x_65672 x_65673) (xor (shl1 x_65673) x_65672))))
prog =
Program "x_65671" $
Fold (shr1 (or' (not' (xor' (plus x_65671 (shr1 (if0 (or' (plus (shl1 x_65671) x_65671) x_65671) b0 b1))) x_65671)) b0))
x_65671
"x_65672" "x_65673" (xor' (shl1 x_65673) x_65672)
x_65671 = var "x_65671"
x_65672 = var "x_65672"
x_65673 = var "x_65673"
case_not = do
eval prog 0 @?= 0xFFFFFFFFFFFFFFFF
eval prog 1 @?= 0xFFFFFFFFFFFFFFFE
eval prog 2 @?= 0xFFFFFFFFFFFFFFFD
eval prog 3 @?= 0xFFFFFFFFFFFFFFFC
eval prog 4 @?= 0xFFFFFFFFFFFFFFFB
eval prog 5 @?= 0xFFFFFFFFFFFFFFFA
eval prog 0x112233 @?= 0xFFFFFFFFFFEEDDCC
eval prog 0x1122334455667788 @?= 0xEEDDCCBBAA998877
eval prog 0xFFFFFFFFFFFFFFFF @?= 0x0000000000000000
where
-- P = (lambda (x) (not x))
prog = Program "x" (not' x)
x = var "x"
case_shl1 = do
forM_ (zip inputs outputs) $ \(x,y) -> do
eval prog x @?= y
where
prog = Program "x" (shl1 x)
x = var "x"
inputs = [0x0,0x1,0x2,0x3,0x4,0x5,0x112233,0x1122334455667788,0xFFFFFFFFFFFFFFFF]
outputs = [0x0000000000000000, 0x0000000000000002, 0x0000000000000004, 0x0000000000000006, 0x0000000000000008, 0x000000000000000A, 0x0000000000224466, 0x22446688AACCEF10, 0xFFFFFFFFFFFFFFFE]
case_shr1 = do
forM_ (zip inputs outputs) $ \(x,y) -> do
eval prog x @?= y
where
prog = Program "x" (shr1 x)
x = var "x"
inputs = [0x0,0x1,0x2,0x3,0x4,0x5,0x112233,0x1122334455667788,0xFFFFFFFFFFFFFFFF]
outputs = [0x0000000000000000, 0x0000000000000000, 0x0000000000000001, 0x0000000000000001, 0x0000000000000002, 0x0000000000000002, 0x0000000000089119, 0x089119A22AB33BC4, 0x7FFFFFFFFFFFFFFF]
case_shr4 = do
forM_ (zip inputs outputs) $ \(x,y) -> do
eval prog x @?= y
where
prog = Program "x" (shr4 x)
x = var "x"
inputs = [0x0,0x1,0x2,0x3,0x4,0x5,0x112233,0x1122334455667788,0xFFFFFFFFFFFFFFFF]
outputs = [0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000011223, 0x0112233445566778, 0x0FFFFFFFFFFFFFFF]
case_shr16 = do
forM_ (zip inputs outputs) $ \(x,y) -> do
eval prog x @?= y
where
prog = Program "x" (shr16 x)
x = var "x"
inputs = [0x0,0x1,0x2,0x3,0x4,0x5,0x112233,0x1122334455667788,0xFFFFFFFFFFFFFFFF]
outputs = [0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000011, 0x0000112233445566, 0x0000FFFFFFFFFFFF]
case_xor = do
forM_ (zip inputs outputs) $ \(x,y) -> do
eval prog x @?= y
where
-- (lambda (x) (xor (shl1 x) x))
prog = Program "x" (xor' (shl1 x) x)
x = var "x"
inputs = [0x0,0x1,0x2,0x3,0x4,0x5,0x12345,0x112233,0x1122334455667788,0xFFFFFFFFFFFFFFFF]
outputs = [0x0000000000000000, 0x0000000000000003, 0x0000000000000006, 0x0000000000000005, 0x000000000000000C, 0x000000000000000F, 0x00000000000365CF, 0x0000000000336655, 0x336655CCFFAA9898, 0x0000000000000001]
case_if0 = do
forM_ (zip inputs outputs) $ \(x,y) -> do
eval prog x @?= y
where
prog = Program "x" (if0 x b1 b0)
x = var "x"
inputs = [0x0,0x1,0x2,0x3,0x4,0x5,0x112233,0x1122334455667788,0xFFFFFFFFFFFFFFFF]
outputs = [0x0000000000000001, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000]
case_fold = do
forM_ (zip inputs outputs) $ \(x,y) -> do
eval prog x @?= y
where
-- (lambda (x) (fold x 1 (lambda (y z) (xor y (shl1 z)))))
prog = Program "x" (fold x b1 "y" "z" (xor' y (shl1 z)))
x = var "x"
y = var "y"
z = var "z"
inputs = [0x0,0x1,0x2,0x3,0x4,0x5,0x112233,0x1122334455667788,0xFFFFFFFFFFFFFFFF]
outputs = [0x0000000000000100, 0x0000000000000180, 0x0000000000000000, 0x0000000000000080, 0x0000000000000300, 0x0000000000000380, 0x0000000000001220, 0x00000000000053E9, 0x0000000000005455]
case_fold_2 = do
forM_ (zip inputs outputs) $ \(x,y) -> do
eval prog x @?= y
where
-- (lambda (x) (fold x 0 (lambda (y z) y)))
prog = Program "x" (fold x b0 "y" "z" y)
x = var "x"
y = var "y"
z = var "z"
inputs = [0x0,0x1,0x2,0x3,0x4,0x5,0x12345,0x112233,0x1122334455667788,0xFFFFFFFFFFFFFFFF]
outputs = [0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000011, 0x00000000000000FF]
case_fold_3 = do
forM_ (zip inputs outputs) $ \(x,y) -> do
eval prog x @?= y
where
-- (lambda (x) (fold x 0 (lambda (y z) z)))
prog = Program "x" (fold x b0 "y" "z" z)
x = var "x"
y = var "y"
z = var "z"
inputs = [0x0,0x1,0x2,0x3,0x4,0x5,0x12345,0x112233,0x1122334455667788,0xFFFFFFFFFFFFFFFF]
outputs = [0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000]
case_parseProgram =
parseProgram "(lambda (x) (fold x 0 (lambda (y z) (or y z))))" @?= Just expected
where
expected = Program "x" (Fold (Var "x") (Const Zero) "y" "z" (Op2 OR (Var "y") (Var "z")))
case_parseExpr =
parseExpr "(fold x 0 (lambda (y z) (or y z)))" @?= Just expected
where
expected = Fold (Var "x") (Const Zero) "y" "z" (Op2 OR (Var "y") (Var "z"))
case_renderProgram = render prog @?= "(lambda (x) (fold x 0 (lambda (y z) (or y z))))"
where
prog = Program "x" (Fold (Var "x") (Const Zero) "y" "z" (Op2 OR (Var "y") (Var "z")))
case_renderExpr = render e @?= "(fold x 0 (lambda (y z) (or y z)))"
where
e = Fold (Var "x") (Const Zero) "y" "z" (Op2 OR (Var "y") (Var "z"))
case_isValidFor_normal = (prog `isValidFor` ops) @?= True
where
prog = program "(lambda (x_9367) (fold x_9367 (xor x_9367 x_9367) (lambda (x_9368 x_9369) (plus (shr16 x_9369) x_9368))))"
ops = [ "fold", "plus", "shr16", "xor" ]
case_isValidFor_tfold = (prog `isValidFor` ops) @?= True
where
prog = program "(lambda (x_1353) (fold x_1353 0 (lambda (x_1353 x_1354) (shr1 (shr4 x_1353)))))"
ops = [ "shr1", "shr4", "tfold" ]
case_isValidFor_bonus = (prog `isValidFor` ops) @?= True
where
prog = program "(lambda (x_9) (if0 (and (plus (shr16 (shr16 (shl1 x_9))) (shr16 x_9)) 1) (plus x_9 (shl1 (and (shr4 x_9) x_9))) (plus 1 (plus x_9 x_9))))"
ops = [ "bonus", "and", "if0", "plus", "shl1", "shr16", "shr4" ]
------------------------------------------------------------------------
-- Test harness
main :: IO ()
main = $(defaultMainGenerator)
|
msakai/icfpc2013
|
test/TestBV.hs
|
bsd-2-clause
| 7,814 | 0 | 28 | 1,466 | 2,343 | 1,273 | 1,070 | 138 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds #-}
-- | Linux input
module Haskus.System.Linux.Input
( getSupportedEvents
)
where
import Haskus.System.Linux.Internals.Input
import Haskus.System.Linux.Handle
import Haskus.System.Linux.ErrorCode
import Haskus.Format.Binary.Buffer
import Haskus.Utils.Flow
-- | Call getDeviceBits until the buffer is large enough to contain all the
-- event codes. Initial buffer size should be sensible size in *bits*.
getDeviceBits :: MonadInIO m => Handle -> Maybe EventType -> Word -> FlowT '[ErrorCode] m Buffer
getDeviceBits hdl ev bitSize = go ((bitSize + 7) `div` 8)
where
go sz = do
(rdsz,b) <- ioctlGetDeviceBits ev (fromIntegral sz) hdl
-- check that the buffer was large enough and splice it, otherwise retry
-- with a larger buffer
if rdsz == fromIntegral sz
then go (2*sz)
else return (bufferTake (fromIntegral rdsz) b)
-- | Return the event types supported by the input device
getSupportedEvents :: MonadInIO m => Handle -> FlowT '[ErrorCode] m Buffer
getSupportedEvents hdl = do
getDeviceBits hdl Nothing 0x20
|
hsyl20/ViperVM
|
haskus-system/src/lib/Haskus/System/Linux/Input.hs
|
bsd-3-clause
| 1,181 | 0 | 14 | 243 | 254 | 141 | 113 | 20 | 2 |
module Main where
import System.Directory
import System.FilePath
import Lang.Php.Ast
assertUnchanged :: String -> IO ()
assertUnchanged s = do
let
astMb :: Either ParseError Ast
astMb = runParser parse () "." s
case astMb of
Left e -> error $ "assertUnchanged:\n" ++ show s ++ "\n ->\n" ++ show e
Right ast -> do
let s' = unparse ast
when (s /= s') . error $
"assertUnchanged:\n" ++ show s ++ "\n ->\n" ++
show ast ++ "\n ->\n" ++ show s'
testDir :: FilePath
testDir = "src/Lang/Php/Ast/Test"
main :: IO ()
main = do
assertUnchanged "<?php ''.'';"
doesDirectoryExist testDir >>= \ e -> when e $
mapM_ ((assertUnchanged =<<) . readFile . (testDir </>)) =<<
filter ((/= '.') . head) <$> getDirectoryContents testDir
putStrLn "all tests passed"
|
facebookarchive/lex-pass
|
src/Lang/Php/Ast/Test.hs
|
bsd-3-clause
| 809 | 0 | 21 | 195 | 287 | 141 | 146 | 25 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-| This modules handles the parsing of .json files written out by our
modified GHC. Here is an example:
{
"definingPackage":"main",
"exportedNames":[
{
"package":"ghc-prim",
"module":"GHC.Classes",
"name":"Eq"
},
{
"package":"base",
"module":"GHC.Base",
"name":"id"
},
{
"package":"bytestring-0.10.7.0",
"module":"Data.ByteString",
"name":"empty"
},
{
"package":"bytestring-0.10.7.0",
"module":"Data.ByteString",
"name":"append"
},
{
"package":"bytestring-0.10.7.0",
"module":"Data.ByteString.Lazy.Internal",
"name":"ByteString"
}
]
}
-}
module HPack.Iface.ExternalSymbols
( ModuleRequirements(..)
, RequiredSymbolName(..)
, PkgOrigin(..)
, parseSymbolsForModule
) where
import Data.Aeson
import Data.Aeson.Types
import qualified Data.ByteString.Lazy as BS
import Data.String.Utils (split)
import HPack.Source ( Pkg(..), ModulePath(..), Version(..)
, mkModulePath, parseVersion)
import HPack.JSON
type Name = String
-- | Module containing a list of exported symbols
data ModuleRequirements
= ModuleRequirements [RequiredSymbolName]
deriving (Show)
data RequiredSymbolName
= RequiredSymbolName PkgOrigin ModulePath Name
deriving (Show)
data PkgOrigin
= BuiltinPkg Name
| ExternalPkg Pkg
deriving (Show)
instance FromJSON ModuleRequirements where
parseJSON (Object mod) = do
symbols <- mod .: "exportedNames"
ModuleRequirements <$> mapM parseJSON symbols
parseJSON val
= typeMismatch "Expected an ModuleRequirements (a JSON Object)" val
instance FromJSON RequiredSymbolName where
parseJSON (Object sym) = do
pkgOrigin <- parsePkgOrigin =<< sym .: "package"
RequiredSymbolName <$> (parsePkgOrigin =<< sym .: "package")
<*> fmap mkModulePath (sym .: "module")
<*> sym .: "name"
-- A non-Object value is of the wrong type, so fail.
parseJSON val
= typeMismatch "Expected an RequiredSymbolName (a JSON Object)" val
parsePkgOrigin :: Value -> Parser PkgOrigin
parsePkgOrigin json@(String txt) = do
let s = textToString txt
case split "-" s of
[pkgName, pkgVersion] ->
case parseVersion pkgVersion of
Just version
-> return $ ExternalPkg $ Pkg pkgName version
Nothing
-> return $ BuiltinPkg s
[pkgName] -> return $ BuiltinPkg pkgName
_
-> typeMismatch ("Expected a pkgName-pkgVersion, got " ++ s) json
parsePkg json =
typeMismatch "Expected a package string name" json
parseSymbolsForModule :: BS.ByteString -> Either String ModuleRequirements
parseSymbolsForModule = eitherDecode
|
markflorisson/hpack
|
src/HPack/Iface/ExternalSymbols.hs
|
bsd-3-clause
| 3,048 | 0 | 14 | 933 | 498 | 269 | 229 | 55 | 4 |
{-# LANGUAGE CPP, DeriveFunctor #-}
--
-- (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
--
--------------------------------------------------------------
-- Converting Core to STG Syntax
--------------------------------------------------------------
-- And, as we have the info in hand, we may convert some lets to
-- let-no-escapes.
module GHC.CoreToStg ( coreToStg ) where
#include "HsVersions.h"
import GhcPrelude
import CoreSyn
import CoreUtils ( exprType, findDefault, isJoinBind
, exprIsTickedString_maybe )
import CoreArity ( manifestArity )
import GHC.Stg.Syntax
import Type
import GHC.Types.RepType
import TyCon
import MkId ( coercionTokenId )
import Id
import IdInfo
import DataCon
import CostCentre
import VarEnv
import Module
import Name ( isExternalName, nameModule_maybe )
import BasicTypes ( Arity )
import TysWiredIn ( unboxedUnitDataCon, unitDataConId )
import Literal
import Outputable
import MonadUtils
import FastString
import Util
import DynFlags
import ForeignCall
import Demand ( isUsedOnce )
import PrimOp ( PrimCall(..), primOpWrapperId )
import SrcLoc ( mkGeneralSrcSpan )
import Data.List.NonEmpty (nonEmpty, toList)
import Data.Maybe (fromMaybe)
import Control.Monad (ap)
-- Note [Live vs free]
-- ~~~~~~~~~~~~~~~~~~~
--
-- The two are not the same. Liveness is an operational property rather
-- than a semantic one. A variable is live at a particular execution
-- point if it can be referred to directly again. In particular, a dead
-- variable's stack slot (if it has one):
--
-- - should be stubbed to avoid space leaks, and
-- - may be reused for something else.
--
-- There ought to be a better way to say this. Here are some examples:
--
-- let v = [q] \[x] -> e
-- in
-- ...v... (but no q's)
--
-- Just after the `in', v is live, but q is dead. If the whole of that
-- let expression was enclosed in a case expression, thus:
--
-- case (let v = [q] \[x] -> e in ...v...) of
-- alts[...q...]
--
-- (ie `alts' mention `q'), then `q' is live even after the `in'; because
-- we'll return later to the `alts' and need it.
--
-- Let-no-escapes make this a bit more interesting:
--
-- let-no-escape v = [q] \ [x] -> e
-- in
-- ...v...
--
-- Here, `q' is still live at the `in', because `v' is represented not by
-- a closure but by the current stack state. In other words, if `v' is
-- live then so is `q'. Furthermore, if `e' mentions an enclosing
-- let-no-escaped variable, then its free variables are also live if `v' is.
-- Note [What are these SRTs all about?]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- Consider the Core program,
--
-- fibs = go 1 1
-- where go a b = let c = a + c
-- in c : go b c
-- add x = map (\y -> x*y) fibs
--
-- In this case we have a CAF, 'fibs', which is quite large after evaluation and
-- has only one possible user, 'add'. Consequently, we want to ensure that when
-- all references to 'add' die we can garbage collect any bit of 'fibs' that we
-- have evaluated.
--
-- However, how do we know whether there are any references to 'fibs' still
-- around? Afterall, the only reference to it is buried in the code generated
-- for 'add'. The answer is that we record the CAFs referred to by a definition
-- in its info table, namely a part of it known as the Static Reference Table
-- (SRT).
--
-- Since SRTs are so common, we use a special compact encoding for them in: we
-- produce one table containing a list of CAFs in a module and then include a
-- bitmap in each info table describing which entries of this table the closure
-- references.
--
-- See also: commentary/rts/storage/gc/CAFs on the GHC Wiki.
-- Note [What is a non-escaping let]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- NB: Nowadays this is recognized by the occurrence analyser by turning a
-- "non-escaping let" into a join point. The following is then an operational
-- account of join points.
--
-- Consider:
--
-- let x = fvs \ args -> e
-- in
-- if ... then x else
-- if ... then x else ...
--
-- `x' is used twice (so we probably can't unfold it), but when it is
-- entered, the stack is deeper than it was when the definition of `x'
-- happened. Specifically, if instead of allocating a closure for `x',
-- we saved all `x's fvs on the stack, and remembered the stack depth at
-- that moment, then whenever we enter `x' we can simply set the stack
-- pointer(s) to these remembered (compile-time-fixed) values, and jump
-- to the code for `x'.
--
-- All of this is provided x is:
-- 1. non-updatable;
-- 2. guaranteed to be entered before the stack retreats -- ie x is not
-- buried in a heap-allocated closure, or passed as an argument to
-- something;
-- 3. all the enters have exactly the right number of arguments,
-- no more no less;
-- 4. all the enters are tail calls; that is, they return to the
-- caller enclosing the definition of `x'.
--
-- Under these circumstances we say that `x' is non-escaping.
--
-- An example of when (4) does not hold:
--
-- let x = ...
-- in case x of ...alts...
--
-- Here, `x' is certainly entered only when the stack is deeper than when
-- `x' is defined, but here it must return to ...alts... So we can't just
-- adjust the stack down to `x''s recalled points, because that would lost
-- alts' context.
--
-- Things can get a little more complicated. Consider:
--
-- let y = ...
-- in let x = fvs \ args -> ...y...
-- in ...x...
--
-- Now, if `x' is used in a non-escaping way in ...x..., and `y' is used in a
-- non-escaping way in ...y..., then `y' is non-escaping.
--
-- `x' can even be recursive! Eg:
--
-- letrec x = [y] \ [v] -> if v then x True else ...
-- in
-- ...(x b)...
-- Note [Cost-centre initialization plan]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- Previously `coreToStg` was initializing cost-centre stack fields as `noCCS`,
-- and the fields were then fixed by a separate pass `stgMassageForProfiling`.
-- We now initialize these correctly. The initialization works like this:
--
-- - For non-top level bindings always use `currentCCS`.
--
-- - For top-level bindings, check if the binding is a CAF
--
-- - CAF: If -fcaf-all is enabled, create a new CAF just for this CAF
-- and use it. Note that these new cost centres need to be
-- collected to be able to generate cost centre initialization
-- code, so `coreToTopStgRhs` now returns `CollectedCCs`.
--
-- If -fcaf-all is not enabled, use "all CAFs" cost centre.
--
-- - Non-CAF: Top-level (static) data is not counted in heap profiles; nor
-- do we set CCCS from it; so we just slam in
-- dontCareCostCentre.
-- --------------------------------------------------------------
-- Setting variable info: top-level, binds, RHSs
-- --------------------------------------------------------------
coreToStg :: DynFlags -> Module -> CoreProgram
-> ([StgTopBinding], CollectedCCs)
coreToStg dflags this_mod pgm
= (pgm', final_ccs)
where
(_, (local_ccs, local_cc_stacks), pgm')
= coreTopBindsToStg dflags this_mod emptyVarEnv emptyCollectedCCs pgm
prof = WayProf `elem` ways dflags
final_ccs
| prof && gopt Opt_AutoSccsOnIndividualCafs dflags
= (local_ccs,local_cc_stacks) -- don't need "all CAFs" CC
| prof
= (all_cafs_cc:local_ccs, all_cafs_ccs:local_cc_stacks)
| otherwise
= emptyCollectedCCs
(all_cafs_cc, all_cafs_ccs) = getAllCAFsCC this_mod
coreTopBindsToStg
:: DynFlags
-> Module
-> IdEnv HowBound -- environment for the bindings
-> CollectedCCs
-> CoreProgram
-> (IdEnv HowBound, CollectedCCs, [StgTopBinding])
coreTopBindsToStg _ _ env ccs []
= (env, ccs, [])
coreTopBindsToStg dflags this_mod env ccs (b:bs)
= (env2, ccs2, b':bs')
where
(env1, ccs1, b' ) =
coreTopBindToStg dflags this_mod env ccs b
(env2, ccs2, bs') =
coreTopBindsToStg dflags this_mod env1 ccs1 bs
coreTopBindToStg
:: DynFlags
-> Module
-> IdEnv HowBound
-> CollectedCCs
-> CoreBind
-> (IdEnv HowBound, CollectedCCs, StgTopBinding)
coreTopBindToStg _ _ env ccs (NonRec id e)
| Just str <- exprIsTickedString_maybe e
-- top-level string literal
-- See Note [CoreSyn top-level string literals] in CoreSyn
= let
env' = extendVarEnv env id how_bound
how_bound = LetBound TopLet 0
in (env', ccs, StgTopStringLit id str)
coreTopBindToStg dflags this_mod env ccs (NonRec id rhs)
= let
env' = extendVarEnv env id how_bound
how_bound = LetBound TopLet $! manifestArity rhs
(stg_rhs, ccs') =
initCts dflags env $
coreToTopStgRhs dflags ccs this_mod (id,rhs)
bind = StgTopLifted $ StgNonRec id stg_rhs
in
-- NB: previously the assertion printed 'rhs' and 'bind'
-- as well as 'id', but that led to a black hole
-- where printing the assertion error tripped the
-- assertion again!
(env', ccs', bind)
coreTopBindToStg dflags this_mod env ccs (Rec pairs)
= ASSERT( not (null pairs) )
let
binders = map fst pairs
extra_env' = [ (b, LetBound TopLet $! manifestArity rhs)
| (b, rhs) <- pairs ]
env' = extendVarEnvList env extra_env'
-- generate StgTopBindings and CAF cost centres created for CAFs
(ccs', stg_rhss)
= initCts dflags env' $ do
mapAccumLM (\ccs rhs -> do
(rhs', ccs') <-
coreToTopStgRhs dflags ccs this_mod rhs
return (ccs', rhs'))
ccs
pairs
bind = StgTopLifted $ StgRec (zip binders stg_rhss)
in
(env', ccs', bind)
coreToTopStgRhs
:: DynFlags
-> CollectedCCs
-> Module
-> (Id,CoreExpr)
-> CtsM (StgRhs, CollectedCCs)
coreToTopStgRhs dflags ccs this_mod (bndr, rhs)
= do { new_rhs <- coreToStgExpr rhs
; let (stg_rhs, ccs') =
mkTopStgRhs dflags this_mod ccs bndr new_rhs
stg_arity =
stgRhsArity stg_rhs
; return (ASSERT2( arity_ok stg_arity, mk_arity_msg stg_arity) stg_rhs,
ccs') }
where
-- It's vital that the arity on a top-level Id matches
-- the arity of the generated STG binding, else an importing
-- module will use the wrong calling convention
-- (#2844 was an example where this happened)
-- NB1: we can't move the assertion further out without
-- blocking the "knot" tied in coreTopBindsToStg
-- NB2: the arity check is only needed for Ids with External
-- Names, because they are externally visible. The CorePrep
-- pass introduces "sat" things with Local Names and does
-- not bother to set their Arity info, so don't fail for those
arity_ok stg_arity
| isExternalName (idName bndr) = id_arity == stg_arity
| otherwise = True
id_arity = idArity bndr
mk_arity_msg stg_arity
= vcat [ppr bndr,
text "Id arity:" <+> ppr id_arity,
text "STG arity:" <+> ppr stg_arity]
-- ---------------------------------------------------------------------------
-- Expressions
-- ---------------------------------------------------------------------------
coreToStgExpr
:: CoreExpr
-> CtsM StgExpr
-- The second and third components can be derived in a simple bottom up pass, not
-- dependent on any decisions about which variables will be let-no-escaped or
-- not. The first component, that is, the decorated expression, may then depend
-- on these components, but it in turn is not scrutinised as the basis for any
-- decisions. Hence no black holes.
-- No LitInteger's or LitNatural's should be left by the time this is called.
-- CorePrep should have converted them all to a real core representation.
coreToStgExpr (Lit (LitNumber LitNumInteger _ _)) = panic "coreToStgExpr: LitInteger"
coreToStgExpr (Lit (LitNumber LitNumNatural _ _)) = panic "coreToStgExpr: LitNatural"
coreToStgExpr (Lit l) = return (StgLit l)
coreToStgExpr (App (Lit LitRubbish) _some_unlifted_type)
-- We lower 'LitRubbish' to @()@ here, which is much easier than doing it in
-- a STG to Cmm pass.
= coreToStgExpr (Var unitDataConId)
coreToStgExpr (Var v) = coreToStgApp v [] []
coreToStgExpr (Coercion _) = coreToStgApp coercionTokenId [] []
coreToStgExpr expr@(App _ _)
= coreToStgApp f args ticks
where
(f, args, ticks) = myCollectArgs expr
coreToStgExpr expr@(Lam _ _)
= let
(args, body) = myCollectBinders expr
args' = filterStgBinders args
in
extendVarEnvCts [ (a, LambdaBound) | a <- args' ] $ do
body' <- coreToStgExpr body
let
result_expr = case nonEmpty args' of
Nothing -> body'
Just args'' -> StgLam args'' body'
return result_expr
coreToStgExpr (Tick tick expr)
= do case tick of
HpcTick{} -> return ()
ProfNote{} -> return ()
SourceNote{} -> return ()
Breakpoint{} -> panic "coreToStgExpr: breakpoint should not happen"
expr2 <- coreToStgExpr expr
return (StgTick tick expr2)
coreToStgExpr (Cast expr _)
= coreToStgExpr expr
-- Cases require a little more real work.
coreToStgExpr (Case scrut _ _ [])
= coreToStgExpr scrut
-- See Note [Empty case alternatives] in CoreSyn If the case
-- alternatives are empty, the scrutinee must diverge or raise an
-- exception, so we can just dive into it.
--
-- Of course this may seg-fault if the scrutinee *does* return. A
-- belt-and-braces approach would be to move this case into the
-- code generator, and put a return point anyway that calls a
-- runtime system error function.
coreToStgExpr (Case scrut bndr _ alts) = do
alts2 <- extendVarEnvCts [(bndr, LambdaBound)] (mapM vars_alt alts)
scrut2 <- coreToStgExpr scrut
return (StgCase scrut2 bndr (mkStgAltType bndr alts) alts2)
where
vars_alt (con, binders, rhs)
| DataAlt c <- con, c == unboxedUnitDataCon
= -- This case is a bit smelly.
-- See Note [Nullary unboxed tuple] in Type.hs
-- where a nullary tuple is mapped to (State# World#)
ASSERT( null binders )
do { rhs2 <- coreToStgExpr rhs
; return (DEFAULT, [], rhs2) }
| otherwise
= let -- Remove type variables
binders' = filterStgBinders binders
in
extendVarEnvCts [(b, LambdaBound) | b <- binders'] $ do
rhs2 <- coreToStgExpr rhs
return (con, binders', rhs2)
coreToStgExpr (Let bind body) = do
coreToStgLet bind body
coreToStgExpr e = pprPanic "coreToStgExpr" (ppr e)
mkStgAltType :: Id -> [CoreAlt] -> AltType
mkStgAltType bndr alts
| isUnboxedTupleType bndr_ty || isUnboxedSumType bndr_ty
= MultiValAlt (length prim_reps) -- always use MultiValAlt for unboxed tuples
| otherwise
= case prim_reps of
[LiftedRep] -> case tyConAppTyCon_maybe (unwrapType bndr_ty) of
Just tc
| isAbstractTyCon tc -> look_for_better_tycon
| isAlgTyCon tc -> AlgAlt tc
| otherwise -> ASSERT2( _is_poly_alt_tycon tc, ppr tc )
PolyAlt
Nothing -> PolyAlt
[unlifted] -> PrimAlt unlifted
not_unary -> MultiValAlt (length not_unary)
where
bndr_ty = idType bndr
prim_reps = typePrimRep bndr_ty
_is_poly_alt_tycon tc
= isFunTyCon tc
|| isPrimTyCon tc -- "Any" is lifted but primitive
|| isFamilyTyCon tc -- Type family; e.g. Any, or arising from strict
-- function application where argument has a
-- type-family type
-- Sometimes, the TyCon is a AbstractTyCon which may not have any
-- constructors inside it. Then we may get a better TyCon by
-- grabbing the one from a constructor alternative
-- if one exists.
look_for_better_tycon
| ((DataAlt con, _, _) : _) <- data_alts =
AlgAlt (dataConTyCon con)
| otherwise =
ASSERT(null data_alts)
PolyAlt
where
(data_alts, _deflt) = findDefault alts
-- ---------------------------------------------------------------------------
-- Applications
-- ---------------------------------------------------------------------------
coreToStgApp :: Id -- Function
-> [CoreArg] -- Arguments
-> [Tickish Id] -- Debug ticks
-> CtsM StgExpr
coreToStgApp f args ticks = do
(args', ticks') <- coreToStgArgs args
how_bound <- lookupVarCts f
let
n_val_args = valArgCount args
-- Mostly, the arity info of a function is in the fn's IdInfo
-- But new bindings introduced by CoreSat may not have no
-- arity info; it would do us no good anyway. For example:
-- let f = \ab -> e in f
-- No point in having correct arity info for f!
-- Hence the hasArity stuff below.
-- NB: f_arity is only consulted for LetBound things
f_arity = stgArity f how_bound
saturated = f_arity <= n_val_args
res_ty = exprType (mkApps (Var f) args)
app = case idDetails f of
DataConWorkId dc
| saturated -> StgConApp dc args'
(dropRuntimeRepArgs (fromMaybe [] (tyConAppArgs_maybe res_ty)))
-- Some primitive operator that might be implemented as a library call.
-- As described in Note [Primop wrappers] in PrimOp.hs, here we
-- turn unsaturated primop applications into applications of
-- the primop's wrapper.
PrimOpId op
| saturated -> StgOpApp (StgPrimOp op) args' res_ty
| otherwise -> StgApp (primOpWrapperId op) args'
-- A call to some primitive Cmm function.
FCallId (CCall (CCallSpec (StaticTarget _ lbl (Just pkgId) True)
PrimCallConv _))
-> ASSERT( saturated )
StgOpApp (StgPrimCallOp (PrimCall lbl pkgId)) args' res_ty
-- A regular foreign call.
FCallId call -> ASSERT( saturated )
StgOpApp (StgFCallOp call (idType f)) args' res_ty
TickBoxOpId {} -> pprPanic "coreToStg TickBox" $ ppr (f,args')
_other -> StgApp f args'
tapp = foldr StgTick app (ticks ++ ticks')
-- Forcing these fixes a leak in the code generator, noticed while
-- profiling for trac #4367
app `seq` return tapp
-- ---------------------------------------------------------------------------
-- Argument lists
-- This is the guy that turns applications into A-normal form
-- ---------------------------------------------------------------------------
coreToStgArgs :: [CoreArg] -> CtsM ([StgArg], [Tickish Id])
coreToStgArgs []
= return ([], [])
coreToStgArgs (Type _ : args) = do -- Type argument
(args', ts) <- coreToStgArgs args
return (args', ts)
coreToStgArgs (Coercion _ : args) -- Coercion argument; replace with place holder
= do { (args', ts) <- coreToStgArgs args
; return (StgVarArg coercionTokenId : args', ts) }
coreToStgArgs (Tick t e : args)
= ASSERT( not (tickishIsCode t) )
do { (args', ts) <- coreToStgArgs (e : args)
; return (args', t:ts) }
coreToStgArgs (arg : args) = do -- Non-type argument
(stg_args, ticks) <- coreToStgArgs args
arg' <- coreToStgExpr arg
let
(aticks, arg'') = stripStgTicksTop tickishFloatable arg'
stg_arg = case arg'' of
StgApp v [] -> StgVarArg v
StgConApp con [] _ -> StgVarArg (dataConWorkId con)
StgLit lit -> StgLitArg lit
_ -> pprPanic "coreToStgArgs" (ppr arg)
-- WARNING: what if we have an argument like (v `cast` co)
-- where 'co' changes the representation type?
-- (This really only happens if co is unsafe.)
-- Then all the getArgAmode stuff in CgBindery will set the
-- cg_rep of the CgIdInfo based on the type of v, rather
-- than the type of 'co'.
-- This matters particularly when the function is a primop
-- or foreign call.
-- Wanted: a better solution than this hacky warning
dflags <- getDynFlags
let
arg_rep = typePrimRep (exprType arg)
stg_arg_rep = typePrimRep (stgArgType stg_arg)
bad_args = not (primRepsCompatible dflags arg_rep stg_arg_rep)
WARN( bad_args, text "Dangerous-looking argument. Probable cause: bad unsafeCoerce#" $$ ppr arg )
return (stg_arg : stg_args, ticks ++ aticks)
-- ---------------------------------------------------------------------------
-- The magic for lets:
-- ---------------------------------------------------------------------------
coreToStgLet
:: CoreBind -- bindings
-> CoreExpr -- body
-> CtsM StgExpr -- new let
coreToStgLet bind body = do
(bind2, body2)
<- do
( bind2, env_ext)
<- vars_bind bind
-- Do the body
extendVarEnvCts env_ext $ do
body2 <- coreToStgExpr body
return (bind2, body2)
-- Compute the new let-expression
let
new_let | isJoinBind bind = StgLetNoEscape noExtFieldSilent bind2 body2
| otherwise = StgLet noExtFieldSilent bind2 body2
return new_let
where
mk_binding binder rhs
= (binder, LetBound NestedLet (manifestArity rhs))
vars_bind :: CoreBind
-> CtsM (StgBinding,
[(Id, HowBound)]) -- extension to environment
vars_bind (NonRec binder rhs) = do
rhs2 <- coreToStgRhs (binder,rhs)
let
env_ext_item = mk_binding binder rhs
return (StgNonRec binder rhs2, [env_ext_item])
vars_bind (Rec pairs)
= let
binders = map fst pairs
env_ext = [ mk_binding b rhs
| (b,rhs) <- pairs ]
in
extendVarEnvCts env_ext $ do
rhss2 <- mapM coreToStgRhs pairs
return (StgRec (binders `zip` rhss2), env_ext)
coreToStgRhs :: (Id,CoreExpr)
-> CtsM StgRhs
coreToStgRhs (bndr, rhs) = do
new_rhs <- coreToStgExpr rhs
return (mkStgRhs bndr new_rhs)
-- Generate a top-level RHS. Any new cost centres generated for CAFs will be
-- appended to `CollectedCCs` argument.
mkTopStgRhs :: DynFlags -> Module -> CollectedCCs
-> Id -> StgExpr -> (StgRhs, CollectedCCs)
mkTopStgRhs dflags this_mod ccs bndr rhs
| StgLam bndrs body <- rhs
= -- StgLam can't have empty arguments, so not CAF
( StgRhsClosure noExtFieldSilent
dontCareCCS
ReEntrant
(toList bndrs) body
, ccs )
| StgConApp con args _ <- unticked_rhs
, -- Dynamic StgConApps are updatable
not (isDllConApp dflags this_mod con args)
= -- CorePrep does this right, but just to make sure
ASSERT2( not (isUnboxedTupleCon con || isUnboxedSumCon con)
, ppr bndr $$ ppr con $$ ppr args)
( StgRhsCon dontCareCCS con args, ccs )
-- Otherwise it's a CAF, see Note [Cost-centre initialization plan].
| gopt Opt_AutoSccsOnIndividualCafs dflags
= ( StgRhsClosure noExtFieldSilent
caf_ccs
upd_flag [] rhs
, collectCC caf_cc caf_ccs ccs )
| otherwise
= ( StgRhsClosure noExtFieldSilent
all_cafs_ccs
upd_flag [] rhs
, ccs )
where
unticked_rhs = stripStgTicksTopE (not . tickishIsCode) rhs
upd_flag | isUsedOnce (idDemandInfo bndr) = SingleEntry
| otherwise = Updatable
-- CAF cost centres generated for -fcaf-all
caf_cc = mkAutoCC bndr modl
caf_ccs = mkSingletonCCS caf_cc
-- careful: the binder might be :Main.main,
-- which doesn't belong to module mod_name.
-- bug #249, tests prof001, prof002
modl | Just m <- nameModule_maybe (idName bndr) = m
| otherwise = this_mod
-- default CAF cost centre
(_, all_cafs_ccs) = getAllCAFsCC this_mod
-- Generate a non-top-level RHS. Cost-centre is always currentCCS,
-- see Note [Cost-centre initialization plan].
mkStgRhs :: Id -> StgExpr -> StgRhs
mkStgRhs bndr rhs
| StgLam bndrs body <- rhs
= StgRhsClosure noExtFieldSilent
currentCCS
ReEntrant
(toList bndrs) body
| isJoinId bndr -- must be a nullary join point
= ASSERT(idJoinArity bndr == 0)
StgRhsClosure noExtFieldSilent
currentCCS
ReEntrant -- ignored for LNE
[] rhs
| StgConApp con args _ <- unticked_rhs
= StgRhsCon currentCCS con args
| otherwise
= StgRhsClosure noExtFieldSilent
currentCCS
upd_flag [] rhs
where
unticked_rhs = stripStgTicksTopE (not . tickishIsCode) rhs
upd_flag | isUsedOnce (idDemandInfo bndr) = SingleEntry
| otherwise = Updatable
{-
SDM: disabled. Eval/Apply can't handle functions with arity zero very
well; and making these into simple non-updatable thunks breaks other
assumptions (namely that they will be entered only once).
upd_flag | isPAP env rhs = ReEntrant
| otherwise = Updatable
-- Detect thunks which will reduce immediately to PAPs, and make them
-- non-updatable. This has several advantages:
--
-- - the non-updatable thunk behaves exactly like the PAP,
--
-- - the thunk is more efficient to enter, because it is
-- specialised to the task.
--
-- - we save one update frame, one stg_update_PAP, one update
-- and lots of PAP_enters.
--
-- - in the case where the thunk is top-level, we save building
-- a black hole and furthermore the thunk isn't considered to
-- be a CAF any more, so it doesn't appear in any SRTs.
--
-- We do it here, because the arity information is accurate, and we need
-- to do it before the SRT pass to save the SRT entries associated with
-- any top-level PAPs.
isPAP env (StgApp f args) = listLengthCmp args arity == LT -- idArity f > length args
where
arity = stgArity f (lookupBinding env f)
isPAP env _ = False
-}
{- ToDo:
upd = if isOnceDem dem
then (if isNotTop toplev
then SingleEntry -- HA! Paydirt for "dem"
else
(if debugIsOn then trace "WARNING: SE CAFs unsupported, forcing UPD instead" else id) $
Updatable)
else Updatable
-- For now we forbid SingleEntry CAFs; they tickle the
-- ASSERT in rts/Storage.c line 215 at newCAF() re mut_link,
-- and I don't understand why. There's only one SE_CAF (well,
-- only one that tickled a great gaping bug in an earlier attempt
-- at ClosureInfo.getEntryConvention) in the whole of nofib,
-- specifically Main.lvl6 in spectral/cryptarithm2.
-- So no great loss. KSW 2000-07.
-}
-- ---------------------------------------------------------------------------
-- A monad for the core-to-STG pass
-- ---------------------------------------------------------------------------
-- There's a lot of stuff to pass around, so we use this CtsM
-- ("core-to-STG monad") monad to help. All the stuff here is only passed
-- *down*.
newtype CtsM a = CtsM
{ unCtsM :: DynFlags -- Needed for checking for bad coercions in coreToStgArgs
-> IdEnv HowBound
-> a
}
deriving (Functor)
data HowBound
= ImportBound -- Used only as a response to lookupBinding; never
-- exists in the range of the (IdEnv HowBound)
| LetBound -- A let(rec) in this module
LetInfo -- Whether top level or nested
Arity -- Its arity (local Ids don't have arity info at this point)
| LambdaBound -- Used for both lambda and case
deriving (Eq)
data LetInfo
= TopLet -- top level things
| NestedLet
deriving (Eq)
-- For a let(rec)-bound variable, x, we record LiveInfo, the set of
-- variables that are live if x is live. This LiveInfo comprises
-- (a) dynamic live variables (ones with a non-top-level binding)
-- (b) static live variables (CAFs or things that refer to CAFs)
--
-- For "normal" variables (a) is just x alone. If x is a let-no-escaped
-- variable then x is represented by a code pointer and a stack pointer
-- (well, one for each stack). So all of the variables needed in the
-- execution of x are live if x is, and are therefore recorded in the
-- LetBound constructor; x itself *is* included.
--
-- The set of dynamic live variables is guaranteed ot have no further
-- let-no-escaped variables in it.
-- The std monad functions:
initCts :: DynFlags -> IdEnv HowBound -> CtsM a -> a
initCts dflags env m = unCtsM m dflags env
{-# INLINE thenCts #-}
{-# INLINE returnCts #-}
returnCts :: a -> CtsM a
returnCts e = CtsM $ \_ _ -> e
thenCts :: CtsM a -> (a -> CtsM b) -> CtsM b
thenCts m k = CtsM $ \dflags env
-> unCtsM (k (unCtsM m dflags env)) dflags env
instance Applicative CtsM where
pure = returnCts
(<*>) = ap
instance Monad CtsM where
(>>=) = thenCts
instance HasDynFlags CtsM where
getDynFlags = CtsM $ \dflags _ -> dflags
-- Functions specific to this monad:
extendVarEnvCts :: [(Id, HowBound)] -> CtsM a -> CtsM a
extendVarEnvCts ids_w_howbound expr
= CtsM $ \dflags env
-> unCtsM expr dflags (extendVarEnvList env ids_w_howbound)
lookupVarCts :: Id -> CtsM HowBound
lookupVarCts v = CtsM $ \_ env -> lookupBinding env v
lookupBinding :: IdEnv HowBound -> Id -> HowBound
lookupBinding env v = case lookupVarEnv env v of
Just xx -> xx
Nothing -> ASSERT2( isGlobalId v, ppr v ) ImportBound
getAllCAFsCC :: Module -> (CostCentre, CostCentreStack)
getAllCAFsCC this_mod =
let
span = mkGeneralSrcSpan (mkFastString "<entire-module>") -- XXX do better
all_cafs_cc = mkAllCafsCC this_mod span
all_cafs_ccs = mkSingletonCCS all_cafs_cc
in
(all_cafs_cc, all_cafs_ccs)
-- Misc.
filterStgBinders :: [Var] -> [Var]
filterStgBinders bndrs = filter isId bndrs
myCollectBinders :: Expr Var -> ([Var], Expr Var)
myCollectBinders expr
= go [] expr
where
go bs (Lam b e) = go (b:bs) e
go bs (Cast e _) = go bs e
go bs e = (reverse bs, e)
-- | Precondition: argument expression is an 'App', and there is a 'Var' at the
-- head of the 'App' chain.
myCollectArgs :: CoreExpr -> (Id, [CoreArg], [Tickish Id])
myCollectArgs expr
= go expr [] []
where
go (Var v) as ts = (v, as, ts)
go (App f a) as ts = go f (a:as) ts
go (Tick t e) as ts = ASSERT( all isTypeArg as )
go e as (t:ts) -- ticks can appear in type apps
go (Cast e _) as ts = go e as ts
go (Lam b e) as ts
| isTyVar b = go e as ts -- Note [Collect args]
go _ _ _ = pprPanic "CoreToStg.myCollectArgs" (ppr expr)
-- Note [Collect args]
-- ~~~~~~~~~~~~~~~~~~~
--
-- This big-lambda case occurred following a rather obscure eta expansion.
-- It all seems a bit yukky to me.
stgArity :: Id -> HowBound -> Arity
stgArity _ (LetBound _ arity) = arity
stgArity f ImportBound = idArity f
stgArity _ LambdaBound = 0
|
sdiehl/ghc
|
compiler/GHC/CoreToStg.hs
|
bsd-3-clause
| 32,578 | 0 | 21 | 9,483 | 5,369 | 2,852 | 2,517 | -1 | -1 |
module Servant.API.HttpVersion
( -- $httpversion
HttpVersion(..)
) where
import Network.HTTP.Types (HttpVersion (..))
-- $httpversion
--
-- | You can directly use the 'HttpVersion' type from @Network.HTTP.Types@
-- if your request handlers need it to compute a response. This would
-- make the request handlers take an argument of type 'HttpVersion'.
--
-- Example:
--
-- >>> type API = HttpVersion :> Get '[JSON] String
-- $setup
-- >>> import Servant.API
|
zerobuzz/servant
|
servant/src/Servant/API/HttpVersion.hs
|
bsd-3-clause
| 482 | 0 | 6 | 95 | 43 | 33 | 10 | 4 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Language.Haskell.Nemnem.ProcessingPlan
( dagOrdered
) where
import Control.Applicative
import Control.Monad
import qualified Data.ByteString as BS
import Data.Graph.Inductive
import qualified Data.IntMap as IM
import Data.List (nub)
import qualified Data.Map as M
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as TE
import Language.Haskell.Nemnem.Internal.Source
data FileData = FileData
{ fdPath :: FilePath
, fdModule :: T.Text
, fdImportedModules :: [T.Text]
}
-- TODO exceptions handling
parseFile :: FilePath -> IO FileData
parseFile path = {-# SCC parseFile #-} do
lines <- T.lines . T.decodeUtf8With TE.lenientDecode
<$> BS.readFile path
let import_lines = filter ("import " `T.isPrefixOf`) lines
imported_modules = nub . map getImportedModule $ import_lines
module_name = fromMaybe "Unknown" (moduleName lines)
return $ FileData path module_name imported_modules
where
getImportedModule line =
let things = case T.words line of
"import":"qualified":things:_ -> things
"import":things:_ -> things
_ -> error . T.unpack $ "unexpected: " <> line
in beforeOpenParen things
importGraph :: [FileData] -> [(FilePath, [FilePath])]
importGraph file_datas = {-# SCC importGraph #-}
let module_paths = M.fromList . map moduleAndPath $ file_datas
in flip map file_datas $ \fd ->
let import_paths = catMaybes
. map (flip M.lookup module_paths)
. fdImportedModules
$ fd
in (fdPath fd, import_paths)
where
moduleAndPath fd = (fdModule fd, fdPath fd)
dagOrdered :: (a -> FilePath) -> [a] -> IO [a]
dagOrdered getPath as = {-# SCC dagOrdered #-} do
let paths = map getPath as
pathmap = M.fromList $ paths `zip` as
datas <- mapM parseFile paths
let adj = importGraph datas
idmap = M.fromList $ paths `zip` [0..]
return
. map (fromJust . flip M.lookup pathmap)
. dagOrdered' (fromJust . flip M.lookup idmap)
$ adj
dagOrdered' :: (a -> Int) -> [(a, [a])] -> [a]
dagOrdered' getId imports = {-# SCC dagOrdered' #-}
let entries = map fst imports
nodes = map getId entries
reversed = IM.fromList $ nodes `zip` entries
edges = [(getId a_imp, getId a) | (a,a_imps) <- imports, a_imp <- a_imps]
g = mkUGraph nodes edges :: UGr
-- TODO what happens in case the input is not a DAG for some evil reason?
in map (fromJust . flip IM.lookup reversed) . topsort $ g
|
robinp/nemnem
|
nemnem-lib/src/Language/Haskell/Nemnem/ProcessingPlan.hs
|
bsd-3-clause
| 2,607 | 0 | 19 | 578 | 819 | 444 | 375 | -1 | -1 |
{-# LANGUAGE RebindableSyntax #-}
-- Copyright : (C) 2009 Corey O'Connor
-- License : BSD-style (see the file LICENSE)
import Bind.Marshal.Prelude
import Bind.Marshal.Verify
import Bind.Marshal.StaticProperties.SerAction
main = run_test $ do
returnM ()
|
coreyoconnor/bind-marshal
|
test/verify_static_properties_seraction.hs
|
bsd-3-clause
| 269 | 0 | 9 | 48 | 40 | 24 | 16 | 6 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE DeriveGeneric #-}
module Nero.Url
(
-- * URL
Url(..)
, defaultUrl
, Scheme(..)
, Host
, Path
, Query
, HasUrl(..)
, Location(..)
, HasHost(..)
, HasPath(..)
, HasQuery(..)
) where
import Prelude hiding (null)
import GHC.Generics (Generic)
import Data.Text.Strict.Lens (utf8)
import Nero.Prelude
import Nero.Param
import Nero.Binary
-- * URL
-- | Composite type of a 'Scheme', 'Host', 'Path', 'Query'.
data Url = Url Scheme Host Path Query deriving (Show,Eq,Generic)
defaultUrl :: Url
defaultUrl = Url Http mempty mempty mempty
instance HasHost Url where
host f (Url s h p q) = (\h' -> Url s h' p q) <$> f h
instance HasQuery Url where
query f (Url s h p q) = Url s h p <$> f q
instance HasPath Url where
path f (Url s h p q) = (\p' -> Url s h p' q) <$> f p
instance Params Url where
params = query . binary
instance Renderable Url where
render (Url s h p q) = render s <> "://" <> h <> utf8 # p <> (
if isn't _Empty q
then "?" <> q
else mempty)
-- | The scheme given in the 'Url', i.e. @http@ or @https@.
data Scheme = Http | Https deriving (Show,Eq,Generic)
instance Renderable Scheme where
render Http = "http"
render Https = "https"
instance Parseable Scheme where
parse "http" = Just Http
parse "https" = Just Https
parse _ = Nothing
-- | The host name of a 'Url'.
type Host = ByteString
-- | Path after the host name in a 'Url'.
type Path = Text
type Query = ByteString
-- | 'Lens'' for types with an 'Url'.
class HasUrl a where
url :: Lens' a Url
-- | 'Traversal'' to obtain the 'Url' of types with @Location@.
class Location a where
location :: Traversal' a Url
-- | 'Lens'' for types with a 'Host'.
class HasHost a where
host :: Lens' a Host
-- | 'Lens'' for types with a 'Path'.
class HasPath a where
path :: Lens' a Path
-- | 'Lens'' for types with a 'Query'.
class HasQuery a where
query :: Lens' a Query
|
plutonbrb/nero
|
src/Nero/Url.hs
|
bsd-3-clause
| 2,041 | 0 | 11 | 512 | 618 | 338 | 280 | 59 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.PackageDb
-- Copyright : (c) The University of Glasgow 2009, Duncan Coutts 2014
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module provides the view of GHC's database of registered packages that
-- is shared between GHC the compiler\/library, and the ghc-pkg program. It
-- defines the database format that is shared between GHC and ghc-pkg.
--
-- The database format, and this library are constructed so that GHC does not
-- have to depend on the Cabal library. The ghc-pkg program acts as the
-- gateway between the external package format (which is defined by Cabal) and
-- the internal package format which is specialised just for GHC.
--
-- GHC the compiler only needs some of the information which is kept about
-- registerd packages, such as module names, various paths etc. On the other
-- hand ghc-pkg has to keep all the information from Cabal packages and be able
-- to regurgitate it for users and other tools.
--
-- The first trick is that we duplicate some of the information in the package
-- database. We essentially keep two versions of the datbase in one file, one
-- version used only by ghc-pkg which keeps the full information (using the
-- serialised form of the 'InstalledPackageInfo' type defined by the Cabal
-- library); and a second version written by ghc-pkg and read by GHC which has
-- just the subset of information that GHC needs.
--
-- The second trick is that this module only defines in detail the format of
-- the second version -- the bit GHC uses -- and the part managed by ghc-pkg
-- is kept in the file but here we treat it as an opaque blob of data. That way
-- this library avoids depending on Cabal.
--
module GHC.PackageDb (
InstalledPackageInfo(..),
ExposedModule(..),
OriginalModule(..),
BinaryStringRep(..),
emptyInstalledPackageInfo,
readPackageDbForGhc,
readPackageDbForGhcPkg,
writePackageDb
) where
import Data.Version (Version(..))
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS.Char8
import qualified Data.ByteString.Lazy as BS.Lazy
import qualified Data.ByteString.Lazy.Internal as BS.Lazy (defaultChunkSize)
import Data.Binary as Bin
import Data.Binary.Put as Bin
import Data.Binary.Get as Bin
import Control.Exception as Exception
import Control.Monad (when)
import System.FilePath
import System.IO
import System.IO.Error
import GHC.IO.Exception (IOErrorType(InappropriateType))
import System.Directory
-- | This is a subset of Cabal's 'InstalledPackageInfo', with just the bits
-- that GHC is interested in.
--
data InstalledPackageInfo srcpkgid srcpkgname unitid modulename
= InstalledPackageInfo {
unitId :: unitid,
sourcePackageId :: srcpkgid,
packageName :: srcpkgname,
packageVersion :: Version,
abiHash :: String,
depends :: [unitid],
importDirs :: [FilePath],
hsLibraries :: [String],
extraLibraries :: [String],
extraGHCiLibraries :: [String],
libraryDirs :: [FilePath],
libraryDynDirs :: [FilePath],
frameworks :: [String],
frameworkDirs :: [FilePath],
ldOptions :: [String],
ccOptions :: [String],
includes :: [String],
includeDirs :: [FilePath],
haddockInterfaces :: [FilePath],
haddockHTMLs :: [FilePath],
exposedModules :: [ExposedModule unitid modulename],
hiddenModules :: [modulename],
exposed :: Bool,
trusted :: Bool
}
deriving (Eq, Show)
-- | A convenience constraint synonym for common constraints over parameters
-- to 'InstalledPackageInfo'.
type RepInstalledPackageInfo srcpkgid srcpkgname unitid modulename =
(BinaryStringRep srcpkgid, BinaryStringRep srcpkgname,
BinaryStringRep unitid, BinaryStringRep modulename)
-- | An original module is a fully-qualified module name (installed package ID
-- plus module name) representing where a module was *originally* defined
-- (i.e., the 'exposedReexport' field of the original ExposedModule entry should
-- be 'Nothing'). Invariant: an OriginalModule never points to a reexport.
data OriginalModule unitid modulename
= OriginalModule {
originalPackageId :: unitid,
originalModuleName :: modulename
}
deriving (Eq, Show)
-- | Represents a module name which is exported by a package, stored in the
-- 'exposedModules' field. A module export may be a reexport (in which case
-- 'exposedReexport' is filled in with the original source of the module).
-- Thus:
--
-- * @ExposedModule n Nothing@ represents an exposed module @n@ which
-- was defined in this package.
--
-- * @ExposedModule n (Just o)@ represents a reexported module @n@
-- which was originally defined in @o@.
--
-- We use a 'Maybe' data types instead of an ADT with two branches because this
-- representation allows us to treat reexports uniformly.
data ExposedModule unitid modulename
= ExposedModule {
exposedName :: modulename,
exposedReexport :: Maybe (OriginalModule unitid modulename)
}
deriving (Eq, Show)
class BinaryStringRep a where
fromStringRep :: BS.ByteString -> a
toStringRep :: a -> BS.ByteString
emptyInstalledPackageInfo :: RepInstalledPackageInfo a b c d
=> InstalledPackageInfo a b c d
emptyInstalledPackageInfo =
InstalledPackageInfo {
unitId = fromStringRep BS.empty,
sourcePackageId = fromStringRep BS.empty,
packageName = fromStringRep BS.empty,
packageVersion = Version [] [],
abiHash = "",
depends = [],
importDirs = [],
hsLibraries = [],
extraLibraries = [],
extraGHCiLibraries = [],
libraryDirs = [],
libraryDynDirs = [],
frameworks = [],
frameworkDirs = [],
ldOptions = [],
ccOptions = [],
includes = [],
includeDirs = [],
haddockInterfaces = [],
haddockHTMLs = [],
exposedModules = [],
hiddenModules = [],
exposed = False,
trusted = False
}
-- | Read the part of the package DB that GHC is interested in.
--
readPackageDbForGhc :: RepInstalledPackageInfo a b c d =>
FilePath -> IO [InstalledPackageInfo a b c d]
readPackageDbForGhc file =
decodeFromFile file getDbForGhc
where
getDbForGhc = do
_version <- getHeader
_ghcPartLen <- get :: Get Word32
ghcPart <- get
-- the next part is for ghc-pkg, but we stop here.
return ghcPart
-- | Read the part of the package DB that ghc-pkg is interested in
--
-- Note that the Binary instance for ghc-pkg's representation of packages
-- is not defined in this package. This is because ghc-pkg uses Cabal types
-- (and Binary instances for these) which this package does not depend on.
--
readPackageDbForGhcPkg :: Binary pkgs => FilePath -> IO pkgs
readPackageDbForGhcPkg file =
decodeFromFile file getDbForGhcPkg
where
getDbForGhcPkg = do
_version <- getHeader
-- skip over the ghc part
ghcPartLen <- get :: Get Word32
_ghcPart <- skip (fromIntegral ghcPartLen)
-- the next part is for ghc-pkg
ghcPkgPart <- get
return ghcPkgPart
-- | Write the whole of the package DB, both parts.
--
writePackageDb :: (Binary pkgs, RepInstalledPackageInfo a b c d) =>
FilePath -> [InstalledPackageInfo a b c d] -> pkgs -> IO ()
writePackageDb file ghcPkgs ghcPkgPart =
writeFileAtomic file (runPut putDbForGhcPkg)
where
putDbForGhcPkg = do
putHeader
put ghcPartLen
putLazyByteString ghcPart
put ghcPkgPart
where
ghcPartLen :: Word32
ghcPartLen = fromIntegral (BS.Lazy.length ghcPart)
ghcPart = encode ghcPkgs
getHeader :: Get (Word32, Word32)
getHeader = do
magic <- getByteString (BS.length headerMagic)
when (magic /= headerMagic) $
fail "not a ghc-pkg db file, wrong file magic number"
majorVersion <- get :: Get Word32
-- The major version is for incompatible changes
minorVersion <- get :: Get Word32
-- The minor version is for compatible extensions
when (majorVersion /= 1) $
fail "unsupported ghc-pkg db format version"
-- If we ever support multiple major versions then we'll have to change
-- this code
-- The header can be extended without incrementing the major version,
-- we ignore fields we don't know about (currently all).
headerExtraLen <- get :: Get Word32
skip (fromIntegral headerExtraLen)
return (majorVersion, minorVersion)
putHeader :: Put
putHeader = do
putByteString headerMagic
put majorVersion
put minorVersion
put headerExtraLen
where
majorVersion = 1 :: Word32
minorVersion = 0 :: Word32
headerExtraLen = 0 :: Word32
headerMagic :: BS.ByteString
headerMagic = BS.Char8.pack "\0ghcpkg\0"
-- TODO: we may be able to replace the following with utils from the binary
-- package in future.
-- | Feed a 'Get' decoder with data chunks from a file.
--
decodeFromFile :: FilePath -> Get a -> IO a
decodeFromFile file decoder =
withBinaryFile file ReadMode $ \hnd ->
feed hnd (runGetIncremental decoder)
where
feed hnd (Partial k) = do chunk <- BS.hGet hnd BS.Lazy.defaultChunkSize
if BS.null chunk
then feed hnd (k Nothing)
else feed hnd (k (Just chunk))
feed _ (Done _ _ res) = return res
feed _ (Fail _ _ msg) = ioError err
where
err = mkIOError InappropriateType loc Nothing (Just file)
`ioeSetErrorString` msg
loc = "GHC.PackageDb.readPackageDb"
-- Copied from Cabal's Distribution.Simple.Utils.
writeFileAtomic :: FilePath -> BS.Lazy.ByteString -> IO ()
writeFileAtomic targetPath content = do
let (targetDir, targetFile) = splitFileName targetPath
Exception.bracketOnError
(openBinaryTempFileWithDefaultPermissions targetDir $ targetFile <.> "tmp")
(\(tmpPath, handle) -> hClose handle >> removeFile tmpPath)
(\(tmpPath, handle) -> do
BS.Lazy.hPut handle content
hClose handle
renameFile tmpPath targetPath)
instance (RepInstalledPackageInfo a b c d) =>
Binary (InstalledPackageInfo a b c d) where
put (InstalledPackageInfo
unitId sourcePackageId
packageName packageVersion
abiHash depends importDirs
hsLibraries extraLibraries extraGHCiLibraries
libraryDirs libraryDynDirs
frameworks frameworkDirs
ldOptions ccOptions
includes includeDirs
haddockInterfaces haddockHTMLs
exposedModules hiddenModules
exposed trusted) = do
put (toStringRep sourcePackageId)
put (toStringRep packageName)
put packageVersion
put (toStringRep unitId)
put abiHash
put (map toStringRep depends)
put importDirs
put hsLibraries
put extraLibraries
put extraGHCiLibraries
put libraryDirs
put libraryDynDirs
put frameworks
put frameworkDirs
put ldOptions
put ccOptions
put includes
put includeDirs
put haddockInterfaces
put haddockHTMLs
put exposedModules
put (map toStringRep hiddenModules)
put exposed
put trusted
get = do
sourcePackageId <- get
packageName <- get
packageVersion <- get
unitId <- get
abiHash <- get
depends <- get
importDirs <- get
hsLibraries <- get
extraLibraries <- get
extraGHCiLibraries <- get
libraryDirs <- get
libraryDynDirs <- get
frameworks <- get
frameworkDirs <- get
ldOptions <- get
ccOptions <- get
includes <- get
includeDirs <- get
haddockInterfaces <- get
haddockHTMLs <- get
exposedModules <- get
hiddenModules <- get
exposed <- get
trusted <- get
return (InstalledPackageInfo
(fromStringRep unitId)
(fromStringRep sourcePackageId)
(fromStringRep packageName) packageVersion
abiHash
(map fromStringRep depends)
importDirs
hsLibraries extraLibraries extraGHCiLibraries
libraryDirs libraryDynDirs
frameworks frameworkDirs
ldOptions ccOptions
includes includeDirs
haddockInterfaces haddockHTMLs
exposedModules
(map fromStringRep hiddenModules)
exposed trusted)
instance (BinaryStringRep a, BinaryStringRep b) =>
Binary (OriginalModule a b) where
put (OriginalModule originalPackageId originalModuleName) = do
put (toStringRep originalPackageId)
put (toStringRep originalModuleName)
get = do
originalPackageId <- get
originalModuleName <- get
return (OriginalModule (fromStringRep originalPackageId)
(fromStringRep originalModuleName))
instance (BinaryStringRep a, BinaryStringRep b) =>
Binary (ExposedModule a b) where
put (ExposedModule exposedName exposedReexport) = do
put (toStringRep exposedName)
put exposedReexport
get = do
exposedName <- get
exposedReexport <- get
return (ExposedModule (fromStringRep exposedName)
exposedReexport)
|
GaloisInc/halvm-ghc
|
libraries/ghc-boot/GHC/PackageDb.hs
|
bsd-3-clause
| 13,994 | 0 | 14 | 3,877 | 2,514 | 1,344 | 1,170 | 272 | 4 |
{-# LANGUAGE NoImplicitPrelude #-}
--
--
--
module Main where
import Control.Monad
import NumericPrelude
import Ray.Algebra
import Ray.Geometry
import Ray.Physics
import Ray.Light
import Ray.Optics
nphoton = 100000 :: Int
lgt = PointLight (Color 0.33 0.33 0.34) 1.0 (Vector3 0 0 0)
pt = Vector3 0 2 2
main :: IO ()
main = do
putStrLn $ show nphoton
putStrLn "2.0e-5"
forM_ [1..nphoton] $ \i -> do
(wl, (p, d)) <- generatePhoton lgt
putStrLn $ show (wl, ((pt + d), p))
|
eijian/raytracer
|
test/TestPhoton.hs
|
bsd-3-clause
| 487 | 0 | 16 | 99 | 195 | 106 | 89 | 19 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Post where
import qualified Data.ByteString.Lazy.Char8 as L
import Data.IterIO.Http.Support.Action
import Data.Maybe
import Database.HSQL
import Database.HSQL.SQLite3
import System.IO
db :: IO Connection
db = connect "blog.sqlite3" ReadWriteMode
data Post = Post { postId :: Maybe Integer
, postTitle :: String
, postBody :: String
}
deriving (Show)
emptyPost :: Post
emptyPost = Post Nothing "" ""
newPost :: [Param] -> Post
newPost prms = Post Nothing (L.unpack title) (L.unpack body)
where lookup' key [] = Nothing
lookup' key (p:ps)
| key == paramKey p = Just p
| otherwise = lookup' key ps
title = paramValue $ fromJust $ lookup' "title" prms
body = paramValue $ fromJust $ lookup' "body" prms
insertPost :: Post -> IO ()
insertPost post = do
conn <- db
stmt <- query conn $ "insert into posts (title, body) values('"
++ postTitle post ++ "','"
++ postBody post ++ "')"
closeStatement stmt
toPost :: Statement -> IO Post
toPost stmt = do
pid <- getFieldValue stmt "id"
title <- getFieldValue stmt "title"
body <- getFieldValue stmt "body"
return $ Post (Just pid) title body
findPosts :: IO [Post]
findPosts = do
conn <- db
stmt <- query conn "select * from posts"
collectRows toPost stmt
findPost :: Integer -> IO Post
findPost pid = do
conn <- db
stmt <- query conn $ "select * from posts where id = " ++ (show pid)
fetch stmt
toPost stmt
|
scslab/iterio-server
|
Examples/Blog/Post.hs
|
bsd-3-clause
| 1,606 | 0 | 13 | 455 | 509 | 253 | 256 | 48 | 2 |
-- Turnir -- a tool for tournament management.
--
-- Author : Ivan N. Veselov
-- Created: 13-Sep-2010
--
-- Copyright (C) 2010 Ivan N. Veselov
--
-- License: BSD3
--
-- | Contains parsers for reading players data from file, etc.
--
module Parser (
parsePlayers -- ^ parse players list from given file
) where
import Types
import Text.ParserCombinators.Parsec
parsePlayers :: String -> IO (Either ParseError [Player])
parsePlayers = parseFromFile players
players :: Parser [Player]
players = sepEndBy player space >>= return
player :: Parser Player
player = do
id' <- number <?> "player ID"
char '.'
many space
name <- many1 (letter <|> char ' ' <|> char '.') <?> "player name"
char ','
many space
r <- number <?> "rating"
return $ Player id' name r Available
number :: Parser Int
number = do
digits <- many1 digit
return (read digits)
|
sphynx/turnir
|
src/Parser.hs
|
bsd-3-clause
| 885 | 0 | 13 | 195 | 227 | 115 | 112 | 22 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Onedrive.Items where
import Control.Monad.Catch (MonadThrow)
import Control.Monad.IO.Class (MonadIO)
import Data.ByteString.Lazy (ByteString)
import Data.Maybe (maybeToList)
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import Onedrive.Internal.Request (initRequest)
import Onedrive.Internal.Response (json, lbs)
import Onedrive.Session (Session)
import Onedrive.Types.FolderChangesBatch (FolderChangesBatch)
import Onedrive.Types.OnedriveItem (OnedriveItem)
item :: (MonadThrow m, MonadIO m) => Session -> Text -> m OnedriveItem
item session itemId = do
initReq <- initRequest ["drive", "items", itemId] []
json session initReq
content :: (MonadThrow m, MonadIO m) => Session -> Text -> m ByteString
content session itemId = do
initReq <- initRequest ["drive", "items", itemId, "content"] []
lbs session initReq
viewDelta :: (MonadThrow m, MonadIO m) => Session -> Text -> Maybe Text -> m FolderChangesBatch
viewDelta session itemId enumerationToken = do
let
tokenParam tok =
("token", Just (encodeUtf8 tok))
qsParams = ("top", Just "100") :
maybeToList (tokenParam <$> enumerationToken)
initReq <- initRequest ["drive", "items", itemId, "view.delta"] qsParams
json session initReq
|
asvyazin/hs-onedrive
|
src/Onedrive/Items.hs
|
bsd-3-clause
| 1,284 | 0 | 13 | 191 | 413 | 225 | 188 | 30 | 1 |
{-# LANGUAGE CPP
, DataKinds
, OverloadedStrings
, FlexibleContexts
#-}
module Language.Hakaru.Command where
import Language.Hakaru.Syntax.ABT
import qualified Language.Hakaru.Syntax.AST as T
import Language.Hakaru.Parser.Import (expandImports)
import Language.Hakaru.Parser.Parser (parseHakaru, parseHakaruWithImports)
import Language.Hakaru.Parser.SymbolResolve (resolveAST)
import Language.Hakaru.Syntax.TypeCheck
import Control.Monad.Trans.Except
import Control.Monad (when)
import qualified Data.Text as Text
import qualified Data.Text.IO as IO
import qualified Data.Text.Utf8 as U
import qualified Options.Applicative as O
import Data.Vector
import System.IO (stderr)
import System.Environment (getArgs)
import Data.Monoid ((<>),mconcat)
import System.FilePath (takeDirectory)
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative (Applicative(..), (<$>))
#endif
type Term a = TrivialABT T.Term '[] a
parseAndInfer :: Text.Text
-> Either Text.Text (TypedAST (TrivialABT T.Term))
parseAndInfer x = parseAndInferWithMode x LaxMode
parseAndInferWithMode
:: ABT T.Term abt
=> Text.Text
-> TypeCheckMode
-> Either Text.Text (TypedAST abt)
parseAndInferWithMode x mode =
case parseHakaru x of
Left err -> Left (Text.pack . show $ err)
Right past ->
let m = inferType (resolveAST past) in
runTCM m (splitLines x) mode
-- The filepath from which the text came and the text itself. If the filepath is
-- Nothing, imports are searched for in the current directory.
data Source = Source { file :: Maybe FilePath, source :: Text.Text }
noFileSource :: Text.Text -> Source
noFileSource = Source Nothing
fileSource :: FilePath -> Text.Text -> Source
fileSource = Source . Just
parseAndInfer' :: Source
-> IO (Either Text.Text (TypedAST (TrivialABT T.Term)))
parseAndInfer' s = parseAndInferWithMode' s LaxMode
parseAndInferWithMode'
:: ABT T.Term abt
=> Source
-> TypeCheckMode
-> IO (Either Text.Text (TypedAST abt))
parseAndInferWithMode' (Source dir x) mode =
case parseHakaruWithImports x of
Left err -> return . Left $ Text.pack . show $ err
Right past -> do
past' <- runExceptT (expandImports (fmap takeDirectory dir) past)
case past' of
Left err -> return . Left $ Text.pack . show $ err
Right past'' -> do
let m = inferType (resolveAST past'')
return (runTCM m (splitLines x) mode)
parseAndInferWithDebug
:: Bool
-> Text.Text
-> IO (Either Text.Text (TypedAST (TrivialABT T.Term)))
parseAndInferWithDebug debug x =
case parseHakaru x of
Left err -> return $ Left (Text.pack . show $ err)
Right past -> do
when debug $ putErrorLn $ hrule "Parsed AST"
when debug $ putErrorLn . Text.pack . show $ past
let resolved = resolveAST past
let inferred = runTCM (inferType resolved) (splitLines x) LaxMode
when debug $ putErrorLn $ hrule "Inferred AST"
when debug $ putErrorLn . Text.pack . show $ inferred
return $ inferred
where hrule s = Text.concat ["\n<=======================| "
,s," |=======================>\n"]
putErrorLn = IO.hPutStrLn stderr
splitLines :: Text.Text -> Maybe (Vector Text.Text)
splitLines = Just . fromList . Text.lines
readFromFile :: String -> IO Text.Text
readFromFile "-" = U.getContents
readFromFile x = U.readFile x
readFromFile' :: String -> IO Source
readFromFile' x = Source (if x=="-" then Nothing else Just x) <$> readFromFile x
simpleCommand :: (Text.Text -> IO ()) -> Text.Text -> IO ()
simpleCommand k fnName =
let parser =
O.info (O.helper <*> opts)
(O.fullDesc <> O.progDesc
(mconcat["Hakaru:", Text.unpack fnName, " command"]))
opts =
O.strArgument
( O.metavar "PROGRAM" <>
O.showDefault <> O.value "-" <>
O.help "Filepath to Hakaru program OR \"-\"" )
in O.execParser parser >>= readFromFile >>= k
writeToFile :: String -> (Text.Text -> IO ())
writeToFile "-" = U.putStrLn
writeToFile x = U.writeFile x
|
zachsully/hakaru
|
haskell/Language/Hakaru/Command.hs
|
bsd-3-clause
| 4,297 | 0 | 20 | 1,084 | 1,302 | 673 | 629 | 101 | 3 |
module Main where
import System.Exit
import System.IO
import System.Environment
import Text.PrettyPrint
import qualified Parsing as P
data Action
= Parse FilePath
| Lex FilePath
parseArgs :: IO Action
parseArgs = getArgs >>= parse
where
parse [ "lex", fnm ] = return $ Lex fnm
parse [ fnm ] = return $ Parse fnm
parse _ = do
hPutStrLn stderr "Usage: "
hPutStrLn stderr " parse-benchmark lex <filename>.fv"
hPutStrLn stderr " parse-benchmark <filename>.fv"
exitFailure
main :: IO ()
main = do
action <- parseArgs
case action of
Lex filename ->
do readResult <- P.lexFoveranFile filename
case readResult of
Left err ->
do hPutStrLn stderr $ render (P.ppInputError err)
exitFailure
Right tokens ->
do exitSuccess
Parse filename ->
do readResult <- P.readFoveranFile3 filename
case readResult of
Left err ->
do hPutStrLn stderr $ render (P.ppInputError err)
exitFailure
Right decls ->
do putStrLn $ render (P.prettyKnot decls)
exitSuccess
|
bobatkey/Forvie
|
benchmarks/parse-foveran/Main.hs
|
bsd-3-clause
| 1,304 | 0 | 26 | 514 | 331 | 156 | 175 | 39 | 4 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Data.Array.Accelerate.Apart.Exp (
expToC, openExpToC, fun1ToC, fun2ToC
) where
-- standard libraries
import Data.Char
-- libraries
import Data.Loc
import qualified Language.C as C
import Language.C.Quote.C as C
import qualified Text.PrettyPrint.Mainland as C
-- accelerate
import Data.Array.Accelerate.Array.Representation (SliceIndex (..))
import Data.Array.Accelerate.Array.Sugar
import Data.Array.Accelerate.AST hiding (Val (..),
prj)
import Data.Array.Accelerate.Pretty
import Data.Array.Accelerate.Tuple
import Data.Array.Accelerate.Type
-- friends
import Data.Array.Accelerate.Analysis.Type
import Data.Array.Accelerate.Apart.Base
import Data.Array.Accelerate.Apart.Type
-- Generating C code from scalar Accelerate expressions
-- ----------------------------------------------------
-- Compile a closed embedded scalar expression into a list of C expression whose length corresponds to the number of tuple
-- components of the embedded type.
--
expToC :: Elt t => Exp () t -> [C.Exp]
expToC = openExpToC EmptyEnv EmptyEnv
-- Compile an open embedded scalar unary function into a list of C expression whose length corresponds to the number of
-- tuple components of the embedded result type. In addition ot the generated C, the types and names of the variables
-- that need to contain the function argument are returned.
--
-- The expression may contain free array variables according to the array variable valuation passed as a first argument.
--
fun1ToC :: forall t t' aenv. (Elt t, Elt t') => Env aenv -> OpenFun () aenv (t -> t') -> ([(C.Type, Name)], [C.Exp])
fun1ToC aenv (Lam (Body f))
= (bnds, openExpToC env aenv f)
where
(bnds, env) = EmptyEnv `pushExpEnv` (undefined::OpenExp () aenv t)
fun1ToC _aenv _ = error "D.A.A.A.Exp.fun1ToC: unreachable"
userFun1 = undefined
-- Compile an open embedded scalar binary function into a list of C expression whose length corresponds to the number of
-- tuple components of the embedded result type. In addition ot the generated C, the types and names of the variables
-- that need to contain the function argument are returned.
--
-- The expression may contain free array variables according to the array variable valuation passed as a first argument.
--
fun2ToC :: forall t1 t2 t3 aenv. (Elt t1, Elt t2, Elt t3)
=> Env aenv -> OpenFun () aenv (t1 -> t2 -> t3) -> ([(C.Type, Name)], [(C.Type, Name)], [C.Exp])
fun2ToC aenv (Lam (Lam (Body f)))
= (bnds1, bnds2, openExpToC env2 aenv f)
where
(bnds1, env1) = EmptyEnv `pushExpEnv` (undefined::OpenExp () aenv t1)
(bnds2, env2) = env1 `pushExpEnv` (undefined::OpenExp ((), t1) aenv t2)
fun2ToC _aenv _ = error "D.A.A.A.Exp.fun2ToC: unreachable"
userFun2 = undefined
-- Compile an open embedded scalar expression into a list of C expression whose length corresponds to the number of tuple
-- components of the embedded type.
--
-- The expression may contain free array variables according to the array variable valuation passed as a first argument.
--
openExpToC :: Elt t => Env env -> Env aenv -> OpenExp env aenv t -> [C.Exp]
openExpToC = expToC'
where
expToC' :: forall t env aenv. Elt t => Env env -> Env aenv -> OpenExp env aenv t -> [C.Exp]
expToC' env aenv (Let bnd body) = elet env aenv bnd body
expToC' env _aenv (Var idx) = [ [cexp| $id:name |] | (_, name) <- prjEnv idx env]
expToC' _env _aenv (PrimConst c) = [primConstToC c]
expToC' _env _aenv (Const c) = constToC (eltType (undefined::t)) c
expToC' env aenv (PrimApp f arg) = [primToC f $ expToC' env aenv arg]
expToC' env aenv (Tuple t) = tupToC env aenv t
expToC' env aenv e@(Prj i t) = prjToC env aenv i t e
expToC' env aenv (Cond p t e) = condToC env aenv p t e
-- expToC' _env _aenv (Iterate _n _f _x) = error "D.A.A.C.Exp: 'Iterate' not supported"
-- Shapes and indices
expToC' _env _aenv IndexNil = []
expToC' _env _aenv IndexAny = []
expToC' env aenv (IndexCons sh sz) = expToC' env aenv sh ++ expToC' env aenv sz
expToC' env aenv (IndexHead ix) = [last $ expToC' env aenv ix]
expToC' env aenv (IndexTail ix) = init $ expToC' env aenv ix
expToC' env aenv (IndexSlice ix slix sh) = indexSlice ix (expToC' env aenv slix) (expToC' env aenv sh)
expToC' env aenv (IndexFull ix slix sl) = indexFull ix (expToC' env aenv slix) (expToC' env aenv sl)
expToC' env aenv (ToIndex sh ix) = toIndexToC (expToC' env aenv sh) (expToC' env aenv ix)
expToC' env aenv (FromIndex sh ix) = fromIndexToC (expToC' env aenv sh) (expToC' env aenv ix)
-- -- Arrays and indexing
expToC' env aenv (Index acc ix) = indexToC aenv acc (expToC' env aenv ix)
expToC' env aenv (LinearIndex acc ix) = linearIndexToC aenv acc (expToC' env aenv ix)
expToC' _env aenv (Shape acc) = shapeToC aenv acc
expToC' env aenv (ShapeSize sh) = shapeSizeToC (expToC' env aenv sh)
expToC' env aenv (Intersect sh1 sh2) = intersectToC (eltType (undefined::t))
(expToC' env aenv sh1)
(expToC' env aenv sh2)
--Foreign function
expToC' _env _aenv (Foreign _ff _ _e) = error "D.A.A.A.Exp: 'Foreign' not supported"
-- Scalar let expressions evaluate their terms and generate new (const) variable bindings to store these results.
-- Variable names are unambiguously based on the de Bruijn indices and the index of the tuple component they
-- represent.
--
-- FIXME: Currently we need to push lets into each binding, as we don't have a statement sequence as the prelude
-- to the list of expressions that this function returns.
--
elet :: (Elt t, Elt t') => Env env -> Env aenv -> OpenExp env aenv t -> OpenExp (env, t) aenv t' -> [C.Exp]
elet env aenv bnd body
= map (\bodyiC -> [cexp| ({ $items:inits $exp:bodyiC; }) |]) (expToC' env_t aenv body)
where
(binders, env_t) = env `pushExpEnv` bnd
inits = zipWith bindOneComponent binders (expToC' env aenv bnd)
bindOneComponent (tyiC, name) bndiC = [citem| $ty:tyiC $id:name = $exp:bndiC; |]
-- Convert an open expression into a sequence of C expressions. We retain snoc-list ordering, so the element at
-- tuple index zero is at the end of the list. Note that nested tuple structures are flattened.
--
tupToC :: Env aenv -> Env env -> Tuple (OpenExp aenv env) t -> [C.Exp]
tupToC _env _eanv NilTup = []
tupToC env aenv (SnocTup t e) = tupToC env aenv t ++ expToC' env aenv e
-- Project out a tuple index. Since the nested tuple structure is flattened, this actually corresponds to slicing
-- out a subset of the list of C expressions, rather than picking out a single element.
--
prjToC :: Elt t
=> Env env
-> Env aenv
-> TupleIdx (TupleRepr t) e
-> OpenExp env aenv t
-> OpenExp env aenv e
-> [C.Exp]
prjToC env aenv ix t e =
let subset = reverse
. take (length $ tupleTypeToC (expType e))
. drop (prjToInt ix $ preExpType accType t)
. reverse
in
subset $ expToC' env aenv t
-- Scalar conditionals. To keep the return type as an expression list we use the ternery C condition operator (?:).
--
-- FIXME: For tuples this is not particularly good, so the least we can do is make sure the predicate result is
-- evaluated only once and bind it to a local variable.
--
condToC :: Elt t
=> Env env
-> Env aenv
-> OpenExp env aenv Bool
-> OpenExp env aenv t
-> OpenExp env aenv t
-> [C.Exp]
condToC env aenv p t e
= zipWith (\tiC eiC -> [cexp| $exp:pC ? $exp:tiC : $exp:eiC |]) (expToC' env aenv t) (expToC' env aenv e)
where
[pC] = expToC' env aenv p -- type guarantees singleton
-- Tuples
-- ------
-- Convert a tuple index into the corresponding integer. Since the internal representation is flat, be sure to walk
-- over all sub components when indexing past nested tuples.
--
prjToInt :: TupleIdx t e -> TupleType a -> Int
prjToInt ZeroTupIdx _ = 0
prjToInt (SuccTupIdx i) (b `PairTuple` a) = prjToInt i b + sizeTupleType a
prjToInt _ t = error $ "D.A.A.A.Exp.prjToInt: inconsistent tuple index: " ++ show t
-- Shapes and indices
-- ------------------
-- Restrict indices based on a slice specification. In the 'SliceAll' case we elide the 'IndexAny' from the head
-- of slx, as this is not represented by any C term (Any ~ []).
--
indexSlice :: SliceIndex slix' sl co sh' -> [C.Exp] -> [C.Exp] -> [C.Exp]
indexSlice sliceIdx slix sh =
let restrict :: SliceIndex slix sl co sh -> [C.Exp] -> [C.Exp] -> [C.Exp]
restrict SliceNil _ _ = []
restrict (SliceAll sliceIdx) slx (sz:sl) = sz : restrict sliceIdx slx sl
restrict (SliceFixed sliceIdx) (_:slx) ( _:sl) = restrict sliceIdx slx sl
restrict _ _ _ = error "D.A.A.A.Exp.indexSlice: unexpected shapes"
in
reverse $ restrict sliceIdx (reverse slix) (reverse sh)
-- Extend indices based on a slice specification. In the SliceAll case we
-- elide the presence of Any from the head of slx.
--
indexFull :: SliceIndex slix' sl' co sh -> [C.Exp] -> [C.Exp] -> [C.Exp]
indexFull sliceIdx slix sl =
let extend :: SliceIndex slix sl co sh -> [C.Exp] -> [C.Exp] -> [C.Exp]
extend SliceNil _ _ = []
extend (SliceAll sliceIdx) slx (sz:sh) = sz : extend sliceIdx slx sh
extend (SliceFixed sliceIdx) (sz:slx) sh = sz : extend sliceIdx slx sh
extend _ _ _ = error "D.A.A.A.Exp.indexFull: unexpected shapes"
in
reverse $ extend sliceIdx (reverse slix) (reverse sl)
-- Convert between linear and multidimensional indices.
--
toIndexToC :: [C.Exp] -> [C.Exp] -> [C.Exp]
toIndexToC sh ix = [ccall "toIndex" [ccall "shape" sh, ccall "shape" ix]]
-- For the multidimensional case, we've inlined the definition of 'fromIndex' because we need to return an expression
-- for each component.
--
fromIndexToC :: [C.Exp] -> [C.Exp] -> [C.Exp]
fromIndexToC sh ix
= reverse $ fromIndex' (reverse sh) (head ix) -- types ensure that 'ix' is a singleton
where
fromIndex' :: [C.Exp] -> C.Exp -> [C.Exp]
fromIndex' [] _ = []
fromIndex' [_] i = [i]
fromIndex' (d:ds) i = [cexp| $exp:i % $exp:d |] : fromIndex' ds [cexp| $exp:i / $exp:d |]
-- Project out a single scalar element from an array. The array expression does not contain any free scalar variables
-- (strictly flat data parallelism) and has been floated out to be replaced by an array variable.
--
-- FIXME: As we have a non-parametric array representation, we should bind the computed linear array index to a variable
-- and share it in the indexing of the various array components.
--
indexToC :: (Shape sh, Elt e) => Env aenv -> OpenAcc aenv (Array sh e) -> [C.Exp] -> [C.Exp]
indexToC aenv (OpenAcc (Avar idx)) ix
= let ((_, shName):arrNames) = prjEnv idx aenv
in
[ [cexp| $id:arr [ $exp:(toIndexWithShape shName ix) ] |] | (_, arr) <- arrNames ]
indexToC _aenv _arr _ix = error "D.A.A.A.Exp.indexToC: array variable expected"
-- Generate linear array indexing code.
--
-- The array argument here can only be a variable, as arrays are lifted out of expressions in an earlier phase.
--
linearIndexToC :: (Shape sh, Elt e) => Env aenv -> OpenAcc aenv (Array sh e) -> [C.Exp] -> [C.Exp]
linearIndexToC aenv (OpenAcc (Avar idx)) ix
= [ [cexp| $id:arr [ $exp:(head ix) ] |] | (_, arr) <- tail $ prjEnv idx aenv]
-- 'head (prjEnv idx aenv)' is the shape variable
linearIndexToC _aenv _arr _ix = error "D.A.A.A.Exp.linearIndexToC: array variable expected"
-- Generate code to compute the shape of an array.
--
-- The array argument here can only be a variable, as arrays are lifted out of expressions in an earlier phase.
--
-- The first element (always present) in an array valuation is the array's shape variable.
--
shapeToC :: forall sh e aenv. (Shape sh, Elt e) => Env aenv -> OpenAcc aenv (Array sh e) -> [C.Exp]
shapeToC aenv (OpenAcc (Avar idx)) = cshape (sizeTupleType . eltType $ (undefined::sh))
[cexp| * $id:(snd . head $ prjEnv idx aenv) |]
shapeToC _aenv _arr = error "D.A.A.A.Exp.shapeToC: array variable expected"
-- The size of a shape, as the product of the extent in each dimension.
--
shapeSizeToC :: [C.Exp] -> [C.Exp]
shapeSizeToC = (:[]) . foldl (\a b -> [cexp| $exp:a * $exp:b |]) [cexp| 1 |]
-- Intersection of two shapes, taken as the minimum in each dimension.
--
intersectToC :: TupleType t -> [C.Exp] -> [C.Exp] -> [C.Exp]
intersectToC ty sh1 sh2 = zipWith (\a b -> ccall "min" [a, b]) (ccastTup ty sh1) (ccastTup ty sh2)
-- Primtive functions
-- ------------------
primToC :: PrimFun p -> [C.Exp] -> C.Exp
primToC (PrimAdd _) [a,b] = [cexp|$exp:a + $exp:b|]
primToC (PrimSub _) [a,b] = [cexp|$exp:a - $exp:b|]
primToC (PrimMul _) [a,b] = [cexp|$exp:a * $exp:b|]
primToC (PrimNeg _) [a] = [cexp| - $exp:a|]
primToC (PrimAbs ty) [a] = absToC ty a
primToC (PrimSig ty) [a] = sigToC ty a
primToC (PrimQuot _) [a,b] = [cexp|$exp:a / $exp:b|]
primToC (PrimRem _) [a,b] = [cexp|$exp:a % $exp:b|]
primToC (PrimIDiv ty) [a,b] | isSignedIntegralType ty
= idiv ty (ccast (NumScalarType $ IntegralNumType ty) a)
(ccast (NumScalarType $ IntegralNumType ty) b)
| otherwise
= uidiv ty (ccast (NumScalarType $ IntegralNumType ty) a)
(ccast (NumScalarType $ IntegralNumType ty) b)
primToC (PrimMod ty) [a,b] | isSignedIntegralType ty
= imod ty (ccast (NumScalarType $ IntegralNumType ty) a)
(ccast (NumScalarType $ IntegralNumType ty) b)
| otherwise
= uimod ty (ccast (NumScalarType $ IntegralNumType ty) a)
(ccast (NumScalarType $ IntegralNumType ty) b)
primToC (PrimBAnd _) [a,b] = [cexp|$exp:a & $exp:b|]
primToC (PrimBOr _) [a,b] = [cexp|$exp:a | $exp:b|]
primToC (PrimBXor _) [a,b] = [cexp|$exp:a ^ $exp:b|]
primToC (PrimBNot _) [a] = [cexp|~ $exp:a|]
primToC (PrimBShiftL _) [a,b] = [cexp|$exp:a << $exp:b|]
primToC (PrimBShiftR _) [a,b] = [cexp|$exp:a >> $exp:b|]
primToC (PrimBRotateL ty) [a,b] = rotateL ty a b
primToC (PrimBRotateR ty) [a,b] = rotateR ty a b
primToC (PrimFDiv _) [a,b] = [cexp|$exp:a / $exp:b|]
primToC (PrimRecip ty) [a] = recipToC ty a
primToC (PrimSin ty) [a] = ccall (FloatingNumType ty `postfix` "sin") [a]
primToC (PrimCos ty) [a] = ccall (FloatingNumType ty `postfix` "cos") [a]
primToC (PrimTan ty) [a] = ccall (FloatingNumType ty `postfix` "tan") [a]
primToC (PrimAsin ty) [a] = ccall (FloatingNumType ty `postfix` "asin") [a]
primToC (PrimAcos ty) [a] = ccall (FloatingNumType ty `postfix` "acos") [a]
primToC (PrimAtan ty) [a] = ccall (FloatingNumType ty `postfix` "atan") [a]
primToC (PrimAsinh ty) [a] = ccall (FloatingNumType ty `postfix` "asinh") [a]
primToC (PrimAcosh ty) [a] = ccall (FloatingNumType ty `postfix` "acosh") [a]
primToC (PrimAtanh ty) [a] = ccall (FloatingNumType ty `postfix` "atanh") [a]
primToC (PrimExpFloating ty) [a] = ccall (FloatingNumType ty `postfix` "exp") [a]
primToC (PrimSqrt ty) [a] = ccall (FloatingNumType ty `postfix` "sqrt") [a]
primToC (PrimLog ty) [a] = ccall (FloatingNumType ty `postfix` "log") [a]
primToC (PrimFPow ty) [a,b] = ccall (FloatingNumType ty `postfix` "pow") [a,b]
primToC (PrimLogBase ty) [a,b] = logBaseToC ty a b
primToC (PrimTruncate ta tb) [a] = truncateToC ta tb a
primToC (PrimRound ta tb) [a] = roundToC ta tb a
primToC (PrimFloor ta tb) [a] = floorToC ta tb a
primToC (PrimCeiling ta tb) [a] = ceilingToC ta tb a
primToC (PrimAtan2 ty) [a,b] = ccall (FloatingNumType ty `postfix` "atan2") [a,b]
primToC (PrimLt _) [a,b] = [cexp|$exp:a < $exp:b|]
primToC (PrimGt _) [a,b] = [cexp|$exp:a > $exp:b|]
primToC (PrimLtEq _) [a,b] = [cexp|$exp:a <= $exp:b|]
primToC (PrimGtEq _) [a,b] = [cexp|$exp:a >= $exp:b|]
primToC (PrimEq _) [a,b] = [cexp|$exp:a == $exp:b|]
primToC (PrimNEq _) [a,b] = [cexp|$exp:a != $exp:b|]
primToC (PrimMax ty) [a,b] = maxToC ty a b
primToC (PrimMin ty) [a,b] = minToC ty a b
primToC PrimLAnd [a,b] = [cexp|$exp:a && $exp:b|]
primToC PrimLOr [a,b] = [cexp|$exp:a || $exp:b|]
primToC PrimLNot [a] = [cexp| ! $exp:a|]
primToC PrimOrd [a] = ordToC a
primToC PrimChr [a] = chrToC a
primToC PrimBoolToInt [a] = boolToIntToC a
primToC (PrimFromIntegral ta tb) [a] = fromIntegralToC ta tb a
primToC p args = -- If the argument lists are not the correct length
error $
"D.A.A.A.Exp.primToC: inconsistent argument count: '" ++ (show . snd . prettyPrim $ p) ++ "' with " ++
show (length args) ++ " argument(s)"
-- Constants and numeric types
-- ---------------------------
constToC :: TupleType a -> a -> [C.Exp]
constToC UnitTuple _ = []
constToC (SingleTuple ty) c = [scalarToC ty c]
constToC (PairTuple ty1 ty0) (cs,c) = constToC ty1 cs ++ constToC ty0 c
scalarToC :: ScalarType a -> a -> C.Exp
scalarToC (NumScalarType ty) = numScalarToC ty
scalarToC (NonNumScalarType ty) = nonNumScalarToC ty
numScalarToC :: NumType a -> a -> C.Exp
numScalarToC (IntegralNumType ty) = integralScalarToC ty
numScalarToC (FloatingNumType ty) = floatingScalarToC ty
integralScalarToC :: IntegralType a -> a -> C.Exp
integralScalarToC ty x | IntegralDict <- integralDict ty = [cexp| ( $ty:(integralTypeToC ty) ) $exp:(cintegral x) |]
floatingScalarToC :: FloatingType a -> a -> C.Exp
floatingScalarToC (TypeFloat _) x = C.Const (C.FloatConst (shows x "f") (toRational x) noLoc) noLoc
floatingScalarToC (TypeCFloat _) x = C.Const (C.FloatConst (shows x "f") (toRational x) noLoc) noLoc
floatingScalarToC (TypeDouble _) x = C.Const (C.DoubleConst (show x) (toRational x) noLoc) noLoc
floatingScalarToC (TypeCDouble _) x = C.Const (C.DoubleConst (show x) (toRational x) noLoc) noLoc
nonNumScalarToC :: NonNumType a -> a -> C.Exp
nonNumScalarToC (TypeBool _) x = cbool x
nonNumScalarToC (TypeChar _) x = [cexp|$char:x|]
nonNumScalarToC (TypeCChar _) x = [cexp|$char:(chr (fromIntegral x))|]
nonNumScalarToC (TypeCUChar _) x = [cexp|$char:(chr (fromIntegral x))|]
nonNumScalarToC (TypeCSChar _) x = [cexp|$char:(chr (fromIntegral x))|]
primConstToC :: PrimConst a -> C.Exp
primConstToC (PrimMinBound ty) = minBoundToC ty
primConstToC (PrimMaxBound ty) = maxBoundToC ty
primConstToC (PrimPi ty) = piToC ty
piToC :: FloatingType a -> C.Exp
piToC ty | FloatingDict <- floatingDict ty = floatingScalarToC ty pi
minBoundToC :: BoundedType a -> C.Exp
minBoundToC (IntegralBoundedType ty) | IntegralDict <- integralDict ty = integralScalarToC ty minBound
minBoundToC (NonNumBoundedType ty) | NonNumDict <- nonNumDict ty = nonNumScalarToC ty minBound
maxBoundToC :: BoundedType a -> C.Exp
maxBoundToC (IntegralBoundedType ty) | IntegralDict <- integralDict ty = integralScalarToC ty maxBound
maxBoundToC (NonNumBoundedType ty) | NonNumDict <- nonNumDict ty = nonNumScalarToC ty maxBound
-- Methods from Num, Floating, Fractional and RealFrac
-- ---------------------------------------------------
absToC :: NumType a -> C.Exp -> C.Exp
absToC (FloatingNumType ty) x = ccall (FloatingNumType ty `postfix` "fabs") [x]
absToC (IntegralNumType ty) x =
case ty of
TypeWord _ -> x
TypeWord8 _ -> x
TypeWord16 _ -> x
TypeWord32 _ -> x
TypeWord64 _ -> x
TypeCUShort _ -> x
TypeCUInt _ -> x
TypeCULong _ -> x
TypeCULLong _ -> x
_ -> ccall "abs" [x]
sigToC :: NumType a -> C.Exp -> C.Exp
sigToC (IntegralNumType ty) = integralSigToC ty
sigToC (FloatingNumType ty) = floatingSigToC ty
integralSigToC :: IntegralType a -> C.Exp -> C.Exp
integralSigToC ty x = [cexp|$exp:x == $exp:zero ? $exp:zero : $exp:(ccall "copysign" [one,x]) |]
where
zero | IntegralDict <- integralDict ty = integralScalarToC ty 0
one | IntegralDict <- integralDict ty = integralScalarToC ty 1
floatingSigToC :: FloatingType a -> C.Exp -> C.Exp
floatingSigToC ty x = [cexp|$exp:x == $exp:zero ? $exp:zero : $exp:(ccall (FloatingNumType ty `postfix` "copysign") [one,x]) |]
where
zero | FloatingDict <- floatingDict ty = floatingScalarToC ty 0
one | FloatingDict <- floatingDict ty = floatingScalarToC ty 1
recipToC :: FloatingType a -> C.Exp -> C.Exp
recipToC ty x | FloatingDict <- floatingDict ty = [cexp|$exp:(floatingScalarToC ty 1) / $exp:x|]
logBaseToC :: FloatingType a -> C.Exp -> C.Exp -> C.Exp
logBaseToC ty x y = let a = ccall (FloatingNumType ty `postfix` "log") [x]
b = ccall (FloatingNumType ty `postfix` "log") [y]
in
[cexp|$exp:b / $exp:a|]
minToC :: ScalarType a -> C.Exp -> C.Exp -> C.Exp
minToC (NumScalarType ty@(IntegralNumType _)) a b = ccall (ty `postfix` "min") [a,b]
minToC (NumScalarType ty@(FloatingNumType _)) a b = ccall (ty `postfix` "fmin") [a,b]
minToC (NonNumScalarType _) a b =
let ty = scalarType :: ScalarType Int32
in minToC ty (ccast ty a) (ccast ty b)
maxToC :: ScalarType a -> C.Exp -> C.Exp -> C.Exp
maxToC (NumScalarType ty@(IntegralNumType _)) a b = ccall (ty `postfix` "max") [a,b]
maxToC (NumScalarType ty@(FloatingNumType _)) a b = ccall (ty `postfix` "fmax") [a,b]
maxToC (NonNumScalarType _) a b =
let ty = scalarType :: ScalarType Int32
in maxToC ty (ccast ty a) (ccast ty b)
-- Type coercions
--
ordToC :: C.Exp -> C.Exp
ordToC = ccast (scalarType :: ScalarType Int)
chrToC :: C.Exp -> C.Exp
chrToC = ccast (scalarType :: ScalarType Char)
boolToIntToC :: C.Exp -> C.Exp
boolToIntToC = ccast (scalarType :: ScalarType Int)
fromIntegralToC :: IntegralType a -> NumType b -> C.Exp -> C.Exp
fromIntegralToC _ ty = ccast (NumScalarType ty)
truncateToC :: FloatingType a -> IntegralType b -> C.Exp -> C.Exp
truncateToC ta tb x
= ccast (NumScalarType (IntegralNumType tb))
$ ccall (FloatingNumType ta `postfix` "trunc") [x]
roundToC :: FloatingType a -> IntegralType b -> C.Exp -> C.Exp
roundToC ta tb x
= ccast (NumScalarType (IntegralNumType tb))
$ ccall (FloatingNumType ta `postfix` "round") [x]
floorToC :: FloatingType a -> IntegralType b -> C.Exp -> C.Exp
floorToC ta tb x
= ccast (NumScalarType (IntegralNumType tb))
$ ccall (FloatingNumType ta `postfix` "floor") [x]
ceilingToC :: FloatingType a -> IntegralType b -> C.Exp -> C.Exp
ceilingToC ta tb x
= ccast (NumScalarType (IntegralNumType tb))
$ ccall (FloatingNumType ta `postfix` "ceil") [x]
-- Auxiliary Functions
-- -------------------
ccast :: ScalarType a -> C.Exp -> C.Exp
ccast ty x = [cexp|($ty:(scalarTypeToC ty)) $exp:x|]
ccastTup :: TupleType e -> [C.Exp] -> [C.Exp]
ccastTup ty = fst . travTup ty
where
travTup :: TupleType e -> [C.Exp] -> ([C.Exp],[C.Exp])
travTup UnitTuple xs = ([], xs)
travTup (SingleTuple ty') (x:xs) = ([ccast ty' x], xs)
travTup (PairTuple l r) xs = let
(ls, xs' ) = travTup l xs
(rs, xs'') = travTup r xs'
in
(ls ++ rs, xs'')
travTup _ _ = error "D.A.A.A.Exp.ccastTup: not enough expressions to match type"
postfix :: NumType a -> String -> String
postfix (FloatingNumType (TypeFloat _)) x = x ++ "f"
postfix (FloatingNumType (TypeCFloat _)) x = x ++ "f"
postfix _ x = x
isSignedIntegralType :: IntegralType a -> Bool
isSignedIntegralType (TypeWord{}) = False
isSignedIntegralType (TypeWord8{}) = False
isSignedIntegralType (TypeWord16{}) = False
isSignedIntegralType (TypeWord32{}) = False
isSignedIntegralType (TypeWord64{}) = False
isSignedIntegralType (TypeCUShort{}) = False
isSignedIntegralType (TypeCUInt{}) = False
isSignedIntegralType (TypeCULong{}) = False
isSignedIntegralType (TypeCULLong{}) = False
isSignedIntegralType _ = True
|
vollmerm/accelerate-apart
|
Data/Array/Accelerate/Apart/Exp.hs
|
bsd-3-clause
| 25,815 | 0 | 19 | 6,979 | 7,917 | 4,198 | 3,719 | 341 | 24 |
module Lab where
-- Exercise 0 --
e0 :: [Bool]
e0 = [False, True, False, True]
-- Exercise 1 --
e1as :: [[Integer]]
e1as = [[1, 2], [3, 4]]
e1bs :: [[Int]]
e1bs = [[1, 2], [3, 4]]
e1cs :: Num a => [[a]]
e1cs = [[1, 2], [3, 4]]
-- Exercise 2 --
e2as :: [[[Integer]]]
e2as = [[[1, 2, 3]], [[3, 4, 5]]]
-- Didn't type out the other lists here since the answer was obvious
-- Exercise 3 --
e3 :: Num a => a -> a
e3 x = x * 2
-- Exercise 4 --
e4 :: (a, b) -> a
e4 (x, y) = x
-- Exercise 5 --
e5 :: (a, b, c) -> c
e5 (x, y, z) = z
-- Exercise 6 --
e6 :: Num a => a -> a -> a
e6 x y = x * y
-- Exercise 7 --
e7 :: (a, b) -> (b, a)
e7 (x, y) = (y, x)
-- Exercise 8 --
e8 :: a -> b -> (b, a)
e8 x y = (y, x)
-- Exercise 9 --
e9 :: [a] -> (a, Bool)
e9 [x, y] = (x, True)
-- Exercise 10 --
e10 :: (a, a) -> [a]
e10 (x, y) = [x, y]
-- Exercise 11 --
e11 :: (Char, Bool)
e11 = ('\a', True)
-- Exercise 12 --
e12 :: [(Char, Int)]
e12 = [('a', 1)]
-- Exercise 13 --
e13 :: Int -> Int -> Int
e13 x y = x + y * y
-- Exercise 14 --
e14 :: ([Char], [Float])
e14 = ("Haskell", [3.1, 3.14, 3.141, 3.1415])
-- Exercise 15 --
e15 :: [a] -> [b] -> (a, b)
e15 xs ys = (head xs, head ys)
|
paulkeene/FP101x
|
chapter03/Lab.hs
|
bsd-3-clause
| 1,197 | 0 | 7 | 330 | 650 | 397 | 253 | 37 | 1 |
-- | This module imports the entire package, except 'Graphics.QML.Debug'.
module Graphics.QML (
-- * Overview
{-|
HsQML layers a low to medium level Haskell API on top of the C++ Qt Quick
framework. It allows you to write graphical applications where the front-end is
written in Qt Quick's QML language (incorporating JavaScript) and the back-end
is written in Haskell. To this end, this library provides two pieces of
functionality:-
The 'Graphics.QML.Engine' module allows you to create windows which host QML
content. You can specify a custom global object to be made available to the
JavaScript running inside the content. In this way, the content can interface
with the Haskell program.
The 'Graphics.QML.Objects' module allows you to define your own custom object
types which can be marshalled between Haskell and JavaScript.
-}
-- * Script-side APIs
{-|
The @window@ object provides the following methods and properties to QML
scripts.
/Properties/
[@source : url@] URL for the Window's QML document.
[@title : string@] Window title.
[@visible : bool@] Window visibility.
/Methods/
[@close()@] Closes the window.
-}
-- * Graphics.QML
module Graphics.QML.Engine,
module Graphics.QML.Marshal,
module Graphics.QML.Objects
) where
import Graphics.QML.Engine
import Graphics.QML.Marshal
import Graphics.QML.Objects
|
drhodes/HsQML
|
src/Graphics/QML.hs
|
bsd-3-clause
| 1,336 | 0 | 5 | 211 | 53 | 38 | 15 | 7 | 0 |
module Options
(
getOptions,
printUsage,
Options(..)
)
where
import System.Console.GetOpt
import Text.Printf
data Options = Options
{
srcDir :: !FilePath,
targetDir :: !FilePath,
onlyView :: !Bool,
targetFileFormat :: !String,
help :: !Bool,
viewVersion :: !Bool
}
deriving(Show)
defaultOptions :: Options
defaultOptions = Options
{
srcDir = ".",
targetDir = ".",
onlyView = False,
targetFileFormat = "%0y%0m%0d_%0H%0M%0S.JPG",
help = False,
viewVersion = False
}
options :: [OptDescr (Options -> Options)]
options =
[
Option "i" ["indir"] (ReqArg (\f opts -> opts { srcDir = f }) "inputDir") (printf "input directory (default %s)" (srcDir defaultOptions)),
Option "o" ["outdir"] (ReqArg (\f opts -> opts { targetDir = f }) "outDir") (printf "output directory (default %s)" (targetDir defaultOptions)),
Option "f" ["fileFormat"] (ReqArg (\f opts -> opts { targetFileFormat = f }) "format") (printf "target file format (default %s)" (targetFileFormat defaultOptions)),
Option "h" ["help"] (NoArg (\opts -> opts { help = True })) "show usage",
Option "a" ["actions"] (NoArg (\opts -> opts { onlyView = True })) "only view actions",
Option "v" ["version"] (NoArg (\opts -> opts { viewVersion = True })) "view version"
]
usageHeader :: String
usageHeader = "Usage: PictureSave [OPTION...]"
getOptions :: [String] -> Options
getOptions argv =
case getOpt Permute options argv of
(o, _, []) -> foldl (flip id) defaultOptions o
(_ ,_, errs) -> error $ concat errs ++ usageInfo usageHeader options
printUsage :: IO ()
printUsage = putStrLn $ usageInfo usageHeader options
|
thomkoehler/PictureSave
|
src/Options.hs
|
bsd-3-clause
| 1,731 | 0 | 12 | 401 | 561 | 316 | 245 | 53 | 2 |
module BachPrelude where
import Haskore.Melody
import Haskore.Music as M
import Haskore.Basic.Duration
import Snippet
import Prelude as P
eight_bar n = n en ()
eight_bars = line . map eight_bar
first_period = eight_bars [c 1, e 1, g 1, c 2, e 2, g 1, c 2, e 2]
prelude_start = line . map (M.replicate 2)
prelude_1 = export_to "prelude" 1 $ prelude_start [first_period]
prelude_2 = export_to "prelude" 2 $ changeTempo 2 $ prelude_start [first_period]
repeat_last_3 xs = xs ++ ( P.reverse $ P.take 3 $ P.reverse xs )
rest_period = map eight_bars $ map repeat_last_3 $ in_group_of 5 [
c 1, d 1, a 1, d 2, f 2,
b 0, d 1, g 1, d 2, f 2,
c 1, e 1, g 1, c 2, e 2,
c 1, e 1, a 1, e 2, a 2,
c 1, d 1, fs 1, a 1, d 2,
b 0, d 1, g 1, d 2, g 2,
b 0, c 1, e 1, g 1, c 2,
a 0, c 1, e 1, g 1, c 2,
d 0, a 0, d 1, fs 1, c 2,
g 0, b 0, d 1, g 1, b 1,
g 0, bf 0, e 1, g 1, cs 2,
f 0, a 0, d 1, a 1, d 2,
f 0, af 0, d 1, f 1, b 1,
e 0, g 0, c 1, g 1, c 2,
e 0, f 0, a 0, c 1, f 1,
d 0, f 0, a 0, c 1, f 1,
g (-1), d 0, g 0, b 0, f 1,
c 0, e 0, g 0, c 1, e 1,
c 0, g 0, bf 0, c 1, e 1,
f (-1), f 0, a 0, c 1, e 1,
fs(-1), c 0, a 0, c 1, ef 1,
af (-1),f 0, b 0, c 1, d 1,
g (-1), f 0, g 0, b 0, d 1,
g (-1), e 0, g 0, c 1, e 1,
g (-1), d 0, g 0, c 1, f 1,
g (-1), d 0, g 0, b 0, f 1,
g (-1), ef 0, a 0, c 1, fs 1,
g (-1), e 0, g 0, c 1, g 1,
g (-1), d 0, g 0, c 1, f 1,
g (-1), d 0, g 0, b 0, f 1,
c (-1), c 0, g 0, bf 0, e 1
]
prelude_end = eight_bars [
c (-1), c 0, f 0, a 0, c 1, f 1, c 1, a 0,
c 1, a 0, f 0, a 0, f 0, d 0, f 0, d 0,
c (-1), b (-1), g 0, b 0, d 1, f 1, d 1, b 0,
d 1, b 0, g 0, b 0, d 0, f 0, e 0, d 0
]
prelude_conclude = chord $ map (\n -> n wn ()) [c (-1), c 0, e 1, g 1, c 2]
prelude_full = line [ prelude_start (first_period : rest_period), prelude_end, prelude_conclude ]
prelude_3 = export_to "prelude" 3 $ changeTempo 2 $ prelude_full
main = do
prelude_1
prelude_2
prelude_3
|
nfjinjing/haskore-guide
|
src/bach_prelude.hs
|
bsd-3-clause
| 2,427 | 0 | 10 | 1,068 | 1,575 | 800 | 775 | 57 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
module Stanag.LOIMap where
import Ivory.Language
[ivory|
struct LOIMap {
uint32_t msg;
uint8_t req;
}
|]
mLOIMap :: MemArea (Array 88 (Struct "LOIMap"))
mLOIMap = area "mLOIMap" (Just (iarray [
istruct [ msg .= ival 1, req .= ival 15 ],
istruct [ msg .= ival 20, req .= ival 15 ],
istruct [ msg .= ival 21, req .= ival 15 ],
istruct [ msg .= ival 40, req .= ival 12 ],
istruct [ msg .= ival 41, req .= ival 12 ],
istruct [ msg .= ival 42, req .= ival 12 ],
istruct [ msg .= ival 43, req .= ival 12 ],
istruct [ msg .= ival 44, req .= ival 12 ],
istruct [ msg .= ival 45, req .= ival 12 ],
istruct [ msg .= ival 46, req .= ival 12 ],
istruct [ msg .= ival 47, req .= ival 12 ],
istruct [ msg .= ival 48, req .= ival 12 ],
istruct [ msg .= ival 100, req .= ival 13 ],
istruct [ msg .= ival 101, req .= ival 13 ],
istruct [ msg .= ival 102, req .= ival 13 ],
istruct [ msg .= ival 103, req .= ival 12 ],
istruct [ msg .= ival 104, req .= ival 13 ],
istruct [ msg .= ival 105, req .= ival 12 ],
istruct [ msg .= ival 106, req .= ival 13 ],
istruct [ msg .= ival 107, req .= ival 12 ],
istruct [ msg .= ival 108, req .= ival 12 ],
istruct [ msg .= ival 109, req .= ival 13 ],
istruct [ msg .= ival 110, req .= ival 13 ],
istruct [ msg .= ival 200, req .= ival 2 ],
istruct [ msg .= ival 201, req .= ival 2 ],
istruct [ msg .= ival 202, req .= ival 2 ],
istruct [ msg .= ival 203, req .= ival 2 ],
istruct [ msg .= ival 204, req .= ival 2 ],
istruct [ msg .= ival 205, req .= ival 2 ],
istruct [ msg .= ival 206, req .= ival 2 ],
istruct [ msg .= ival 207, req .= ival 2 ],
istruct [ msg .= ival 300, req .= ival 3 ],
istruct [ msg .= ival 301, req .= ival 3 ],
istruct [ msg .= ival 302, req .= ival 3 ],
istruct [ msg .= ival 303, req .= ival 3 ],
istruct [ msg .= ival 304, req .= ival 3 ],
istruct [ msg .= ival 305, req .= ival 3 ],
istruct [ msg .= ival 306, req .= ival 3 ],
istruct [ msg .= ival 307, req .= ival 2 ],
istruct [ msg .= ival 308, req .= ival 2 ],
istruct [ msg .= ival 400, req .= ival 15 ],
istruct [ msg .= ival 401, req .= ival 15 ],
istruct [ msg .= ival 402, req .= ival 15 ],
istruct [ msg .= ival 403, req .= ival 15 ],
istruct [ msg .= ival 404, req .= ival 15 ],
istruct [ msg .= ival 500, req .= ival 15 ],
istruct [ msg .= ival 501, req .= ival 15 ],
istruct [ msg .= ival 502, req .= ival 15 ],
istruct [ msg .= ival 503, req .= ival 15 ],
istruct [ msg .= ival 600, req .= ival 14 ],
istruct [ msg .= ival 700, req .= ival 14 ],
istruct [ msg .= ival 800, req .= ival 12 ],
istruct [ msg .= ival 801, req .= ival 12 ],
istruct [ msg .= ival 802, req .= ival 12 ],
istruct [ msg .= ival 803, req .= ival 12 ],
istruct [ msg .= ival 804, req .= ival 12 ],
istruct [ msg .= ival 805, req .= ival 12 ],
istruct [ msg .= ival 806, req .= ival 12 ],
istruct [ msg .= ival 900, req .= ival 12 ],
istruct [ msg .= ival 1000, req .= ival 15 ],
istruct [ msg .= ival 1001, req .= ival 15 ],
istruct [ msg .= ival 1100, req .= ival 15 ],
istruct [ msg .= ival 1101, req .= ival 15 ],
istruct [ msg .= ival 1200, req .= ival 15 ],
istruct [ msg .= ival 1201, req .= ival 15 ],
istruct [ msg .= ival 1202, req .= ival 15 ],
istruct [ msg .= ival 1203, req .= ival 15 ],
istruct [ msg .= ival 1300, req .= ival 15 ],
istruct [ msg .= ival 1301, req .= ival 15 ],
istruct [ msg .= ival 1302, req .= ival 15 ],
istruct [ msg .= ival 1303, req .= ival 15 ],
istruct [ msg .= ival 1304, req .= ival 15 ],
istruct [ msg .= ival 1400, req .= ival 15 ],
istruct [ msg .= ival 1401, req .= ival 15 ],
istruct [ msg .= ival 1402, req .= ival 15 ],
istruct [ msg .= ival 1403, req .= ival 15 ],
istruct [ msg .= ival 1500, req .= ival 12 ],
istruct [ msg .= ival 1501, req .= ival 12 ],
istruct [ msg .= ival 1600, req .= ival 12 ],
istruct [ msg .= ival 2000, req .= ival 12 ],
istruct [ msg .= ival 2001, req .= ival 12 ],
istruct [ msg .= ival 2002, req .= ival 13 ],
istruct [ msg .= ival 2004, req .= ival 13 ],
istruct [ msg .= ival 2005, req .= ival 13 ],
istruct [ msg .= ival 2013, req .= ival 13 ],
istruct [ msg .= ival 2014, req .= ival 13 ],
istruct [ msg .= ival 2244, req .= ival 12 ],
istruct [ msg .= ival 2441, req .= ival 12 ]
]))
loiMapModule :: Module
loiMapModule = package "loiMapModule" $ do
defStruct (Proxy :: Proxy "LOIMap")
defMemArea mLOIMap
|
GaloisInc/loi
|
Stanag/LOIMap.hs
|
bsd-3-clause
| 5,118 | 0 | 14 | 1,750 | 2,392 | 1,200 | 1,192 | 101 | 1 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE OverloadedStrings #-}
module Reporting.Report
( Report(Report)
, simple
, toString
, printError, printWarning
) where
import Control.Applicative ((<|>))
import Control.Monad.Writer (Writer, execWriter, tell)
import qualified Data.List.Split as Split
import System.Console.ANSI
import System.IO (hPutStr, stderr)
import qualified Reporting.Region as R
data Report = Report
{ _title :: String
, _highlight :: Maybe R.Region
, _preHint :: String
, _postHint :: String
}
deriving (Show)
simple :: String -> String -> String -> Report
simple title pre post =
Report title Nothing pre post
toString :: String -> R.Region -> Report -> String -> String
toString location region report source =
execWriter (render plain location region report source)
printError :: String -> R.Region -> Report -> String -> IO ()
printError location region report source =
render (ansi Error) location region report source
printWarning :: String -> R.Region -> Report -> String -> IO ()
printWarning location region report source =
render (ansi Warning) location region report source
render
:: (Monad m)
=> Renderer m
-> String
-> R.Region
-> Report
-> String
-> m ()
render renderer location region (Report title highlight pre post) source =
do messageBar renderer title location
normal renderer (pre ++ "\n\n")
grabRegion renderer highlight region source
normal renderer ("\n" ++ if null post then "\n" else post ++ "\n\n\n")
-- RENDERING
data Renderer m = Renderer
{ normal :: String -> m ()
, header :: String -> m ()
, accent :: String -> m ()
}
plain :: Renderer (Writer String)
plain =
Renderer tell tell tell
data Type = Error | Warning
ansi :: Type -> Renderer IO
ansi tipe =
let
put =
hPutStr stderr
put' intensity color string =
do hSetSGR stderr [SetColor Foreground intensity color]
put string
hSetSGR stderr [Reset]
accentColor =
case tipe of
Error -> Red
Warning -> Yellow
in
Renderer
put
(put' Dull Cyan)
(put' Dull accentColor)
-- REPORT HEADER
messageBar :: Renderer m -> String -> String -> m ()
messageBar renderer tag location =
let
usedSpace = 4 + length tag + 1 + length location
in
header renderer $
"-- " ++ tag ++ " "
++ replicate (max 1 (80 - usedSpace)) '-'
++ " " ++ location ++ "\n\n"
-- REGIONS
grabRegion
:: (Monad m)
=> Renderer m
-> Maybe R.Region
-> R.Region
-> String
-> m ()
grabRegion renderer maybeSubRegion region@(R.Region start end) source =
let
(R.Position startLine startColumn) = start
(R.Position endLine endColumn) = end
(|>) = flip ($)
relevantLines =
-- Using `lines` here will strip the last line.
Split.splitOn "\n" source
|> drop (startLine - 1)
|> take (endLine - startLine + 1)
in
case relevantLines of
[] ->
normal renderer ""
[sourceLine] ->
singleLineRegion renderer startLine sourceLine $
case maybeSubRegion of
Nothing ->
(0, startColumn, endColumn, length sourceLine)
Just (R.Region s e) ->
(startColumn, R.column s, R.column e, endColumn)
firstLine : rest ->
let
filteredFirstLine =
replicate (startColumn - 1) ' '
++ drop (startColumn - 1) firstLine
filteredLastLine =
take (endColumn) (last rest)
focusedRelevantLines =
filteredFirstLine : init rest ++ [filteredLastLine]
lineNumbersWidth =
length (show endLine)
subregion =
maybeSubRegion <|> Just region
numberedLines =
zipWith
(addLineNumber renderer subregion lineNumbersWidth)
[startLine .. endLine]
focusedRelevantLines
in
mapM_ (\line -> line >> normal renderer "\n") numberedLines
addLineNumber
:: (Monad m)
=> Renderer m
-> Maybe R.Region
-> Int
-> Int
-> String
-> m ()
addLineNumber renderer maybeSubRegion width n line =
let
number =
if n < 0 then " " else show n
lineNumber =
replicate (width - length number) ' ' ++ number ++ "│"
spacer (R.Region start end) =
if R.line start <= n && n <= R.line end
then accent renderer ">"
else normal renderer " "
in
do normal renderer lineNumber
maybe (normal renderer " ") spacer maybeSubRegion
normal renderer line
singleLineRegion
:: (Monad m)
=> Renderer m
-> Int
-> String
-> (Int, Int, Int, Int)
-> m ()
singleLineRegion renderer lineNum sourceLine (start, innerStart, innerEnd, end) =
let
width =
length (show lineNum)
underline =
replicate (innerStart + width + 1) ' '
++ replicate (max 1 (innerEnd - innerStart)) '^'
(|>) = flip ($)
trimmedSourceLine =
sourceLine
|> drop (start - 1)
|> take (end - start + 1)
|> (++) (replicate (start - 1) ' ')
in
do addLineNumber renderer Nothing width lineNum trimmedSourceLine
accent renderer $ "\n" ++ underline
|
rgrempel/frelm.org
|
vendor/elm-format/parser/src/Reporting/Report.hs
|
mit
| 5,353 | 0 | 17 | 1,641 | 1,708 | 876 | 832 | 168 | 4 |
{-# LANGUAGE RecursiveDo,ViewPatterns #-}
module E.PrimOpt(performPrimOpt) where
import Control.Monad.Fix()
import C.Prims
import Cmm.OpEval
import Doc.DocLike
import Doc.PPrint
import E.E
import E.Values
import Stats
import StringTable.Atom
import Support.CanType
import qualified Cmm.Op as Op
{-@Extensions
# Foreign Primitives
In addition to foreign imports of external functions as described in the FFI
spec. Jhc supports 'primitive' imports that let you communicate primitives
directly to the compiler. In general, these should not be used other than in the
implementation of the standard libraries. They generally do little error
checking as it is assumed you know what you are doing if you use them. All
haskell visible entities are introduced via foreign declarations in jhc.
They all have the form
foreign import primitive "specification" haskell_name :: type
where "specification" is one of the following
seq
: evaluate first argument to WHNF, then return the second argument
zero,one
: the values zero and one of any primitive type.
const.C_CONSTANT
: the text following const is directly inserted into the resulting C file
peek.TYPE
: the peek primitive for raw value TYPE
poke.TYPE
: the poke primitive for raw value TYPE
sizeOf.TYPE, alignmentOf.TYPE, minBound.TYPE, maxBound.TYPE, umaxBound.TYPE
: various properties of a given internal type.
error.MESSAGE
: results in an error with constant message MESSAGE.
constPeekByte
: peek of a constant value specialized to bytes, used internally by Jhc.String
box
: take an unboxed value and box it, the shape of the box is determined by the type at which this is imported
unbox
: take an boxed value and unbox it, the shape of the box is determined by the type at which this is imported
increment, decrement
: increment or decrement a numerical integral primitive value
fincrement, fdecrement
: increment or decrement a numerical floating point primitive value
exitFailure__
: abort the program immediately
C-- Primitive
: any C-- primitive may be imported in this manner.
-}
-- | this creates a string representing the type of primitive optimization was
-- performed for bookkeeping purposes
primConv cop t1 t2 e rt = EPrim (Op (Op.ConvOp cop t1) t2) [e] rt
performPrimOpt (ELit lc@LitCons { litArgs = xs }) = do
xs' <- mapM performPrimOpt xs
primOpt' (ELit lc { litArgs = xs' })
performPrimOpt (EPrim ap xs t) = do
xs' <- mapM performPrimOpt xs
primOpt' (EPrim ap xs' t)
performPrimOpt e = return e
primOpt' e@(EPrim s xs t) = do
let primopt (Op (Op.BinOp bop t1 t2) tr) [e1,e2] rt =
binOp bop t1 t2 tr e1 e2 rt
primopt (Op (Op.ConvOp cop t1) t2) [ELit (LitInt n t)] rt =
return $ ELit (LitInt (convNumber cop t1 t2 n) rt)
primopt (Op (Op.ConvOp cop t1) t2) [e1] rt = case convOp cop t1 t2 of
Nothing | getType e1 == rt -> return e1
Just cop' | cop' /= cop -> return $ primConv cop' t1 t2 e1 rt
_ -> fail "couldn't apply conversion optimization"
primopt (Op (Op.UnOp bop t1) tr) [e1] rt = unOp bop t1 tr e1 rt
primopt _ _ _ = fail "No Primitive optimization to apply"
case primopt s xs t of
Just n -> do
mtick (toAtom $ "E.PrimOpt." ++ braces (pprint s) ++ cextra s xs )
primOpt' n
Nothing -> return e
primOpt' e = return e
cextra Op {} [] = ""
cextra Op {} xs = '.':map f xs where
f ELit {} = 'c'
f EPrim {} = 'p'
f _ = 'e'
cextra _ _ = ""
instance Expression E E where
toBool True = ELit lTruezh
toBool False = ELit lFalsezh
toConstant (ELit (LitInt n t)) = return (n,t)
toConstant _ = Nothing
equalsExpression e1 e2 = e1 == e2
caseEquals scrut (n,t) e1 e2 = eCase scrut [Alt (LitInt n t) e1 ] e2
toExpression n t = (ELit (LitInt n t))
createBinOp bop t1 t2 tr e1 e2 str =
EPrim Op { primCOp = Op.BinOp bop t1 t2,
primRetTy = tr } [e1, e2] str
createUnOp bop t1 tr e1 str =
EPrim Op { primCOp = Op.UnOp bop t1,
primRetTy = tr } [e1] str
fromBinOp (EPrim Op { primCOp = Op.BinOp bop t1 t2,
primRetTy = tr } [e1, e2] str) =
Just (bop,t1,t2,tr,e1,e2,str)
fromBinOp _ = Nothing
fromUnOp (EPrim Op {
primCOp = Op.UnOp bop t1,
primRetTy = tr } [e1] str) = Just (bop,t1,tr,e1,str)
fromUnOp _ = Nothing
|
dec9ue/jhc_copygc
|
src/E/PrimOpt.hs
|
gpl-2.0
| 4,497 | 0 | 18 | 1,165 | 1,122 | 571 | 551 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
-- |
-- Module : Yi.Frontend.Vty
-- License : GPL-2
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- This module defines a user interface implemented using vty.
--
-- Originally derived from: riot/UI.hs Copyright (c) Tuomo Valkonen 2004.
module Yi.Frontend.Vty
( start
, baseVtyConfig
) where
import Prelude hiding (concatMap, error,
reverse)
import Control.Concurrent (MVar, forkIO, myThreadId, newEmptyMVar,
takeMVar, tryPutMVar, tryTakeMVar)
import Control.Concurrent.STM (atomically, isEmptyTChan, readTChan)
import Control.Exception (IOException, handle)
import Lens.Micro.Platform (makeLenses, view, use, Lens')
import Control.Monad (void, when)
import Data.Char (chr, ord)
import Data.Default (Default)
import qualified Data.DList as D (empty, snoc, toList)
import Data.Foldable (concatMap, toList)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import qualified Data.List.PointedList.Circular as PL (PointedList (_focus), withFocus)
import qualified Data.Map.Strict as M ((!))
import Data.Maybe (fromMaybe, maybeToList)
import Data.Monoid (Endo (appEndo), (<>))
import qualified Data.Text as T (Text, cons, empty,
justifyLeft, length, pack,
singleton, snoc, take,
unpack)
import Data.Typeable (Typeable)
import GHC.Conc (labelThread)
import qualified Graphics.Vty as Vty (Attr, Cursor (Cursor, NoCursor),
Config,
Event (EvResize), Image,
Input (_eventChannel),
Output (displayBounds),
Picture (picCursor), Vty (inputIface, outputIface, refresh, shutdown, update),
bold, char, charFill,
defAttr, emptyImage,
horizCat, mkVty,
picForLayers,
standardIOConfig,
string,
reverseVideo, text',
translate, underline,
vertCat, withBackColor,
withForeColor,
withStyle, (<|>))
import System.Exit (ExitCode, exitWith)
import Yi.Buffer
import Yi.Config
import Yi.Debug (logError, logPutStrLn)
import Yi.Editor
import Yi.Event (Event)
import qualified Yi.Rope as R
import Yi.Style
import Yi.Types (YiConfigVariable)
import qualified Yi.UI.Common as Common
import qualified Yi.UI.SimpleLayout as SL
import Yi.Layout (HasNeighborWest)
import Yi.UI.LineNumbers (getDisplayLineNumbersLocal)
import Yi.UI.TabBar (TabDescr (TabDescr), tabBarDescr)
import Yi.UI.Utils (arrangeItems, attributesPictureAndSelB)
import Yi.Frontend.Vty.Conversions (colorToAttr, fromVtyEvent)
import Yi.Window (Window (bufkey, isMini, wkey, width, height))
data Rendered = Rendered
{ picture :: !Vty.Image
, cursor :: !(Maybe (Int,Int))
}
data FrontendState = FrontendState
{ fsVty :: Vty.Vty
, fsConfig :: Config
, fsEndMain :: MVar ExitCode
, fsEndInputLoop :: MVar ()
, fsEndRenderLoop :: MVar ()
, fsDirty :: MVar ()
, fsEditorRef :: IORef Editor
}
-- | Base vty configuration, named so to distinguish it from any vty
-- frontend configuration.
--
-- If this is set to its default (None) it will be replaced by the default
-- vty configuration from standardIOConfig. However, standardIOConfig
-- runs in the IO monad so we cannot set the real default here.
newtype BaseVtyConfig = BaseVtyConfig { _baseVtyConfig' :: Maybe Vty.Config }
deriving (Typeable, Default)
instance YiConfigVariable BaseVtyConfig
makeLenses ''BaseVtyConfig
baseVtyConfig :: Lens' Config (Maybe Vty.Config)
baseVtyConfig = configVariable . baseVtyConfig'
start :: UIBoot
start config submitEvents submitActions editor = do
let baseConfig = view baseVtyConfig config
vty <- Vty.mkVty =<< case baseConfig of
Nothing -> Vty.standardIOConfig
Just conf -> return conf
let inputChan = Vty._eventChannel (Vty.inputIface vty)
endInput <- newEmptyMVar
endMain <- newEmptyMVar
endRender <- newEmptyMVar
dirty <- newEmptyMVar
editorRef <- newIORef editor
let -- | Action to read characters into a channel
inputLoop :: IO ()
inputLoop = tryTakeMVar endInput >>=
maybe (do
let go evs = do
e <- getEvent
done <- atomically (isEmptyTChan inputChan)
if done
then submitEvents (D.toList (evs `D.snoc` e))
else go (evs `D.snoc` e)
go D.empty
inputLoop)
(const $ return ())
-- | Read a key. UIs need to define a method for getting events.
getEvent :: IO Yi.Event.Event
getEvent = do
event <- atomically (readTChan inputChan)
case event of
(Vty.EvResize _ _) -> do
submitActions []
getEvent
_ -> return (fromVtyEvent event)
renderLoop :: IO ()
renderLoop = do
takeMVar dirty
tryTakeMVar endRender >>=
maybe (handle (\(except :: IOException) -> do
logPutStrLn "refresh crashed with IO Error"
logError (T.pack (show except)))
(readIORef editorRef >>= refresh fs >> renderLoop))
(const $ return ())
fs = FrontendState vty config endMain endInput endRender dirty editorRef
inputThreadId <- forkIO inputLoop
labelThread inputThreadId "VtyInput"
renderThreadId <- forkIO renderLoop
labelThread renderThreadId "VtyRender"
return $! Common.dummyUI
{ Common.main = main fs
, Common.end = end fs
, Common.refresh = requestRefresh fs
, Common.userForceRefresh = Vty.refresh vty
, Common.layout = layout fs
}
main :: FrontendState -> IO ()
main fs = do
tid <- myThreadId
labelThread tid "VtyMain"
exitCode <- takeMVar (fsEndMain fs)
exitWith exitCode
layout :: FrontendState -> Editor -> IO Editor
layout fs e = do
(colCount, rowCount) <- Vty.displayBounds (Vty.outputIface (fsVty fs))
let (e', _layout) = SL.layout colCount rowCount e
return e'
end :: FrontendState -> Maybe ExitCode -> IO ()
end fs mExit = do
-- setTerminalAttributes stdInput (oAttrs ui) Immediately
void $ tryPutMVar (fsEndInputLoop fs) ()
void $ tryPutMVar (fsEndRenderLoop fs) ()
Vty.shutdown (fsVty fs)
case mExit of
Nothing -> pure ()
Just code -> void (tryPutMVar (fsEndMain fs) code)
requestRefresh :: FrontendState -> Editor -> IO ()
requestRefresh fs e = do
writeIORef (fsEditorRef fs) e
void $ tryPutMVar (fsDirty fs) ()
refresh :: FrontendState -> Editor -> IO ()
refresh fs e = do
(colCount, rowCount) <- Vty.displayBounds (Vty.outputIface (fsVty fs))
let (_e, SL.Layout tabbarRect winRects promptRect) = SL.layout colCount rowCount e
ws = windows e
(cmd, cmdSty) = statusLineInfo e
niceCmd = arrangeItems cmd (SL.sizeX promptRect) (maxStatusHeight e)
mkLine = T.justifyLeft colCount ' ' . T.take colCount
formatCmdLine text = withAttributes statusBarStyle (mkLine text)
winImage (win, hasFocus) =
let (rect, nb) = winRects M.! wkey win
in renderWindow (fsConfig fs) e rect nb (win, hasFocus)
windowsAndImages =
fmap (\(w, f) -> (w, winImage (w, f))) (PL.withFocus ws)
bigImages =
map (picture . snd)
(filter (not . isMini . fst) (toList windowsAndImages))
miniImages =
map (picture . snd)
(filter (isMini . fst) (toList windowsAndImages))
statusBarStyle =
((appEndo <$> cmdSty) <*> baseAttributes)
(configStyle (configUI (fsConfig fs)))
tabBarImage =
renderTabBar tabbarRect (configStyle (configUI (fsConfig fs)))
(map (\(TabDescr t f) -> (t, f)) (toList (tabBarDescr e)))
cmdImage = if null cmd
then Vty.emptyImage
else Vty.translate
(SL.offsetX promptRect)
(SL.offsetY promptRect)
(Vty.vertCat (fmap formatCmdLine niceCmd))
cursorPos =
let (w, image) = PL._focus windowsAndImages
in case (isMini w, cursor image) of
(False, Just (y, x)) ->
Vty.Cursor (toEnum x) (toEnum y)
(True, Just (_, x)) -> Vty.Cursor (toEnum x) (toEnum (rowCount - 1))
(_, Nothing) -> Vty.NoCursor
logPutStrLn "refreshing screen."
Vty.update (fsVty fs)
(Vty.picForLayers ([tabBarImage, cmdImage] ++ bigImages ++ miniImages))
{ Vty.picCursor = cursorPos }
renderWindow :: Config -> Editor -> SL.Rect -> HasNeighborWest -> (Window, Bool) -> Rendered
renderWindow cfg' e (SL.Rect x y _ _) nb (win, focused) =
Rendered (Vty.translate x y $ if nb then vertSep Vty.<|> pict else pict)
(fmap (\(i, j) -> (i + y, j + x')) cur)
where
cfg = configUI cfg'
w = Yi.Window.width win
h = Yi.Window.height win
x' = x + if nb then 1 else 0
w' = w - if nb then 1 else 0
b = findBufferWith (bufkey win) e
sty = configStyle cfg
notMini = not (isMini win)
displayLineNumbers =
let local = snd $ runEditor cfg' (withGivenBuffer (bufkey win) getDisplayLineNumbersLocal) e
global = configLineNumbers cfg
in fromMaybe global local
-- Collect some information for displaying line numbers
(lineCount, _) = runBuffer win b lineCountB
(topLine, _) = runBuffer win b screenTopLn
linesInfo = if notMini && displayLineNumbers
then Just (topLine, length (show lineCount) + 1)
else Nothing
wNumbers = maybe 0 snd linesInfo
-- off reserves space for the mode line. The mini window does not have a mode line.
off = if notMini then 1 else 0
h' = h - off
ground = baseAttributes sty
wsty = attributesToAttr ground Vty.defAttr
eofsty = appEndo (eofStyle sty) ground
(point, _) = runBuffer win b pointB
(text, _) = runBuffer win b $
-- Take the window worth of lines; we now know exactly how
-- much text to render, parse and stroke.
fst . R.splitAtLine h' <$> streamB Forward fromMarkPoint
region = mkSizeRegion fromMarkPoint . Size $! R.length text
-- Work around a problem with the mini window never displaying it's contents due to a
-- fromMark that is always equal to the end of the buffer contents.
(Just (MarkSet fromM _ _), _) = runBuffer win b (getMarks win)
fromMarkPoint = if notMini
then fst $ runBuffer win b $ use $ markPointA fromM
else Point 0
(attributes, _) = runBuffer win b $ attributesPictureAndSelB sty (currentRegex e) region
-- TODO: I suspect that this costs quite a lot of CPU in the "dry run" which determines the window size;
-- In that case, since attributes are also useless there, it might help to replace the call by a dummy value.
-- This is also approximately valid of the call to "indexedAnnotatedStreamB".
colors = map (fmap (($ Vty.defAttr) . attributesToAttr)) attributes
bufData = paintChars Vty.defAttr colors $! zip [fromMarkPoint..] (R.toString text)
tabWidth = tabSize . fst $ runBuffer win b indentSettingsB
prompt = if isMini win then miniIdentString b else ""
cur = (fmap (\(SL.Point2D curx cury) -> (cury, T.length prompt + wNumbers + curx)) . fst)
(runBuffer win b
(SL.coordsOfCharacterB
(SL.Size2D (w' - wNumbers) h)
fromMarkPoint
point))
rendered =
drawText wsty h' w'
tabWidth
linesInfo
([(c, wsty) | c <- T.unpack prompt] ++ bufData ++ [(' ', wsty)])
-- we always add one character which can be used to position the cursor at the end of file
commonPref = T.pack <$> commonNamePrefix e
(modeLine0, _) = runBuffer win b $ getModeLine commonPref
modeLine = if notMini then Just modeLine0 else Nothing
prepare = withAttributes modeStyle . T.justifyLeft w' ' ' . T.take w'
modeLines = map prepare $ maybeToList modeLine
modeStyle = (if focused then appEndo (modelineFocusStyle sty) else id) (modelineAttributes sty)
filler :: T.Text
filler = if w' == 0 -- justify would return a single char at w = 0
then T.empty
else T.justifyLeft w' ' ' $ T.singleton (configWindowFill cfg)
pict = Vty.vertCat $ take h' (rendered <> repeat (withAttributes eofsty filler)) <> modeLines
sepStyle = attributesToAttr (modelineAttributes sty) Vty.defAttr
vertSep = Vty.charFill sepStyle ' ' 1 h
withAttributes :: Attributes -> T.Text -> Vty.Image
withAttributes sty = Vty.text' (attributesToAttr sty Vty.defAttr)
attributesToAttr :: Attributes -> Vty.Attr -> Vty.Attr
attributesToAttr (Attributes fg bg reverse bd _itlc underline') =
(if reverse then (`Vty.withStyle` Vty.reverseVideo) else id) .
(if bd then (`Vty.withStyle` Vty.bold) else id) .
(if underline' then (`Vty.withStyle` Vty.underline) else id) .
colorToAttr (flip Vty.withForeColor) fg .
colorToAttr (flip Vty.withBackColor) bg
-- | Apply the attributes in @sty@ and @changes@ to @cs@. If the
-- attributes are not used, @sty@ and @changes@ are not evaluated.
paintChars :: a -> [(Point, a)] -> [(Point, Char)] -> [(Char, a)]
paintChars sty changes cs = zip (fmap snd cs) attrs
where attrs = stys sty changes cs
stys :: a -> [(Point, a)] -> [(Point, Char)] -> [a]
stys sty [] cs = [ sty | _ <- cs ]
stys sty ((endPos, sty') : xs) cs = [ sty | _ <- previous ] <> stys sty' xs later
where (previous, later) = break ((endPos <=) . fst) cs
drawText :: Vty.Attr -- ^ "Ground" attribute.
-> Int -- ^ The height of the part of the window we are in
-> Int -- ^ The width of the part of the window we are in
-> Int -- ^ The number of spaces to represent a tab character with.
-> Maybe (Int, Int) -- ^ The number of the first line and the reserved width
-- for line numbers or Nothing to show no line numbers
-> [(Char, Vty.Attr)] -- ^ The data to draw.
-> [Vty.Image]
drawText wsty h w tabWidth linesInfo bufData
| h == 0 || w == 0 = []
| otherwise = case linesInfo of
Nothing -> renderedLines
Just (firstLine, lineNumberWidth) -> renderedLinesWithNumbers firstLine lineNumberWidth
where
wrapped w' = map (wrapLine w' . addSpace . concatMap expandGraphic) $ take h $ lines' bufData
renderedLinesWithNumbers firstLine lineNumberWidth =
let lns0 = take h $ concatWithNumbers firstLine $ wrapped (w - lineNumberWidth)
renderLineWithNumber (num, ln) = renderLineNumber lineNumberWidth num Vty.<|> fillColorLine (w - lineNumberWidth) ln
in map renderLineWithNumber lns0
renderedLines = map (fillColorLine w) $ take h $ concat $ wrapped w
colorChar (c, a) = Vty.char a c
-- | Like concat, but adds a line number (starting with n) to every first part of a wrapped line
concatWithNumbers :: Int -> [[[(Char, Vty.Attr)]]] -> [(Maybe Int, [(Char, Vty.Attr)])]
concatWithNumbers _ [] = []
concatWithNumbers n ([]:ls) = concatWithNumbers n ls
concatWithNumbers n ((l0:ls0):ls) = (Just n, l0) : map (\l -> (Nothing, l)) ls0 ++ concatWithNumbers (n+1) ls
-- | Render (maybe) a line number padded to a given width
renderLineNumber :: Int -> Maybe Int -> Vty.Image
renderLineNumber w' (Just n) = Vty.charFill wsty ' ' (w' - length (show n) - 1) 1
Vty.<|>
Vty.string wsty (show n)
Vty.<|>
Vty.char wsty ' '
renderLineNumber w' Nothing = Vty.charFill wsty ' ' w' 1
fillColorLine :: Int -> [(Char, Vty.Attr)] -> Vty.Image
fillColorLine w' [] = Vty.charFill Vty.defAttr ' ' w' 1
fillColorLine w' l = Vty.horizCat (map colorChar l)
Vty.<|>
Vty.charFill a ' ' (w' - length l) 1
where (_, a) = last l
addSpace :: [(Char, Vty.Attr)] -> [(Char, Vty.Attr)]
addSpace [] = [(' ', wsty)]
addSpace l = case mod lineLength w of
0 -> l
_ -> l ++ [(' ', wsty)]
where
lineLength = length l
-- | Cut a string in lines separated by a '\n' char. Note
-- that we remove the newline entirely since it is no longer
-- significant for drawing text.
lines' :: [(Char, a)] -> [[(Char, a)]]
lines' [] = []
lines' s = case s' of
[] -> [l]
((_,_):s'') -> l : lines' s''
where
(l, s') = break ((== '\n') . fst) s
wrapLine :: Int -> [x] -> [[x]]
wrapLine _ [] = []
wrapLine n l = let (x,rest) = splitAt n l in x : wrapLine n rest
expandGraphic ('\t', p) = replicate tabWidth (' ', p)
expandGraphic (c, p)
| numeric < 32 = [('^', p), (chr (numeric + 64), p)]
| otherwise = [(c, p)]
where numeric = ord c
renderTabBar :: SL.Rect -> UIStyle -> [(T.Text, Bool)] -> Vty.Image
renderTabBar r uiStyle ts = (Vty.<|> padding) . Vty.horizCat $ fmap render ts
where
render (text, inFocus) = Vty.text' (tabAttr inFocus) (tabTitle text)
tabTitle text = ' ' `T.cons` text `T.snoc` ' '
tabAttr b = baseAttr b $ tabBarAttributes uiStyle
baseAttr True sty =
attributesToAttr (appEndo (tabInFocusStyle uiStyle) sty) Vty.defAttr
baseAttr False sty =
attributesToAttr (appEndo (tabNotFocusedStyle uiStyle) sty) Vty.defAttr
`Vty.withStyle` Vty.underline
padding = Vty.charFill (tabAttr False) ' ' (SL.sizeX r - width') 1
width' = sum . map ((+2) . T.length . fst) $ ts
|
noughtmare/yi
|
yi-frontend-vty/src/Yi/Frontend/Vty.hs
|
gpl-2.0
| 20,413 | 0 | 25 | 7,356 | 5,489 | 2,945 | 2,544 | 353 | 12 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.AutoScaling.DescribeLifecycleHooks
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Describes the lifecycle hooks for the specified Auto Scaling group.
--
-- /See:/ <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeLifecycleHooks.html AWS API Reference> for DescribeLifecycleHooks.
module Network.AWS.AutoScaling.DescribeLifecycleHooks
(
-- * Creating a Request
describeLifecycleHooks
, DescribeLifecycleHooks
-- * Request Lenses
, dlhLifecycleHookNames
, dlhAutoScalingGroupName
-- * Destructuring the Response
, describeLifecycleHooksResponse
, DescribeLifecycleHooksResponse
-- * Response Lenses
, dlhrsLifecycleHooks
, dlhrsResponseStatus
) where
import Network.AWS.AutoScaling.Types
import Network.AWS.AutoScaling.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'describeLifecycleHooks' smart constructor.
data DescribeLifecycleHooks = DescribeLifecycleHooks'
{ _dlhLifecycleHookNames :: !(Maybe [Text])
, _dlhAutoScalingGroupName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeLifecycleHooks' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dlhLifecycleHookNames'
--
-- * 'dlhAutoScalingGroupName'
describeLifecycleHooks
:: Text -- ^ 'dlhAutoScalingGroupName'
-> DescribeLifecycleHooks
describeLifecycleHooks pAutoScalingGroupName_ =
DescribeLifecycleHooks'
{ _dlhLifecycleHookNames = Nothing
, _dlhAutoScalingGroupName = pAutoScalingGroupName_
}
-- | The names of one or more lifecycle hooks.
dlhLifecycleHookNames :: Lens' DescribeLifecycleHooks [Text]
dlhLifecycleHookNames = lens _dlhLifecycleHookNames (\ s a -> s{_dlhLifecycleHookNames = a}) . _Default . _Coerce;
-- | The name of the group.
dlhAutoScalingGroupName :: Lens' DescribeLifecycleHooks Text
dlhAutoScalingGroupName = lens _dlhAutoScalingGroupName (\ s a -> s{_dlhAutoScalingGroupName = a});
instance AWSRequest DescribeLifecycleHooks where
type Rs DescribeLifecycleHooks =
DescribeLifecycleHooksResponse
request = postQuery autoScaling
response
= receiveXMLWrapper "DescribeLifecycleHooksResult"
(\ s h x ->
DescribeLifecycleHooksResponse' <$>
(x .@? "LifecycleHooks" .!@ mempty >>=
may (parseXMLList "member"))
<*> (pure (fromEnum s)))
instance ToHeaders DescribeLifecycleHooks where
toHeaders = const mempty
instance ToPath DescribeLifecycleHooks where
toPath = const "/"
instance ToQuery DescribeLifecycleHooks where
toQuery DescribeLifecycleHooks'{..}
= mconcat
["Action" =:
("DescribeLifecycleHooks" :: ByteString),
"Version" =: ("2011-01-01" :: ByteString),
"LifecycleHookNames" =:
toQuery
(toQueryList "member" <$> _dlhLifecycleHookNames),
"AutoScalingGroupName" =: _dlhAutoScalingGroupName]
-- | /See:/ 'describeLifecycleHooksResponse' smart constructor.
data DescribeLifecycleHooksResponse = DescribeLifecycleHooksResponse'
{ _dlhrsLifecycleHooks :: !(Maybe [LifecycleHook])
, _dlhrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeLifecycleHooksResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dlhrsLifecycleHooks'
--
-- * 'dlhrsResponseStatus'
describeLifecycleHooksResponse
:: Int -- ^ 'dlhrsResponseStatus'
-> DescribeLifecycleHooksResponse
describeLifecycleHooksResponse pResponseStatus_ =
DescribeLifecycleHooksResponse'
{ _dlhrsLifecycleHooks = Nothing
, _dlhrsResponseStatus = pResponseStatus_
}
-- | The lifecycle hooks for the specified group.
dlhrsLifecycleHooks :: Lens' DescribeLifecycleHooksResponse [LifecycleHook]
dlhrsLifecycleHooks = lens _dlhrsLifecycleHooks (\ s a -> s{_dlhrsLifecycleHooks = a}) . _Default . _Coerce;
-- | The response status code.
dlhrsResponseStatus :: Lens' DescribeLifecycleHooksResponse Int
dlhrsResponseStatus = lens _dlhrsResponseStatus (\ s a -> s{_dlhrsResponseStatus = a});
|
fmapfmapfmap/amazonka
|
amazonka-autoscaling/gen/Network/AWS/AutoScaling/DescribeLifecycleHooks.hs
|
mpl-2.0
| 5,052 | 0 | 15 | 1,011 | 672 | 397 | 275 | 86 | 1 |
module Propellor.Property.Group where
import Propellor.Base
import Propellor.Property.User (hasGroup)
type GID = Int
exists :: Group -> Maybe GID -> Property UnixLike
exists (Group group') mgid = check test (cmdProperty "addgroup" (args mgid))
`describe` unwords ["group", group']
where
groupFile = "/etc/group"
test = not . elem group' . words <$> readProcess "cut" ["-d:", "-f1", groupFile]
args Nothing = [group']
args (Just gid) = ["--gid", show gid, group']
hasUser :: Group -> User -> Property DebianLike
hasUser = flip hasGroup
|
ArchiveTeam/glowing-computing-machine
|
src/Propellor/Property/Group.hs
|
bsd-2-clause
| 546 | 2 | 10 | 89 | 202 | 109 | 93 | 13 | 2 |
{-# LANGUAGE CPP #-}
module Ignore.Core
( findIgnoreFiles
, buildChecker
)
where
import Ignore.Builder
import Ignore.Types
import qualified Ignore.VCS.Git as Git
import qualified Ignore.VCS.Mercurial as Hg
import qualified Ignore.VCS.Darcs as Darcs
#if MIN_VERSION_base(4,8,0)
#else
import Control.Applicative
#endif
import Control.Monad.Trans
import Data.Maybe
import Path
import System.Directory (doesFileExist)
import qualified Data.Text as T
import qualified Data.Text.IO as T
-- | Get filename of ignore/boring file for a VCS
getVCSFile :: VCS -> Path Rel File
getVCSFile vcs =
case vcs of
VCSDarcs -> Darcs.file
VCSGit -> Git.file
VCSMercurial -> Hg.file
-- | Search for the ignore/boring files of different VCSes starting a directory
findIgnoreFiles :: [VCS] -> Path Abs Dir -> IO [IgnoreFile]
findIgnoreFiles vcsList rootPath =
catMaybes <$> mapM seekVcs vcsList
where
seekVcs vcs =
seek vcs rootPath (getVCSFile vcs)
seek vcs dir file =
do let full = dir </> file
fp = toFilePath full
isThere <- doesFileExist fp
if isThere
then return $ Just (IgnoreFile vcs (Left full))
else let nextDir = parent dir
in if nextDir == dir
then return Nothing
else seek vcs nextDir file
-- | Build function that checks if a file should be ignored
buildChecker :: [IgnoreFile] -> IO (Either String FileIgnoredChecker)
buildChecker =
runCheckerBuilder . mapM_ go
where
go file =
do contents <-
case if_data file of
Left fp -> liftIO $ T.readFile (toFilePath fp)
Right t -> return t
let lns = T.lines contents
case if_vcs file of
VCSDarcs -> Darcs.makeChecker lns
VCSGit -> Git.makeChecker lns
VCSMercurial -> Hg.makeChecker lns
|
agrafix/ignore
|
src/Ignore/Core.hs
|
bsd-3-clause
| 1,976 | 0 | 16 | 607 | 481 | 253 | 228 | 50 | 4 |
-- | This module defines the interface to points-to analysis in this
-- analysis framework. Each points-to analysis returns a result
-- object that is an instance of the 'PointsToAnalysis' typeclass; the
-- results are intended to be consumed through this interface.
--
-- All of the points-to analysis implementations expose a single function:
--
-- > runPointsToAnalysis :: (PointsToAnalysis a) => Module -> a
--
-- This makes it easy to change the points-to analysis you are using:
-- just modify your imports. If you need multiple points-to analyses
-- in the same module (for example, to support command-line selectable
-- points-to analysis precision), use qualified imports.
module LLVM.Analysis.PointsTo (
-- * Classes
PointsToAnalysis(..),
) where
import LLVM.Analysis
-- | The interface to any points-to analysis.
class PointsToAnalysis a where
mayAlias :: a -> Value -> Value -> Bool
-- ^ Check whether or not two values may alias
pointsTo :: a -> Value -> [Value]
-- ^ Return the list of values that a LoadInst may return. May
-- return targets for other values too (e.g., say that a Function
-- points to itself), but nothing is guaranteed.
--
-- Should also give reasonable answers for globals and arguments
resolveIndirectCall :: a -> Instruction -> [Value]
-- ^ Given a Call instruction, determine its possible callees. The
-- default implementation just delegates the called function value
-- to 'pointsTo' and .
resolveIndirectCall pta i =
case i of
CallInst { callFunction = f } -> pointsTo pta f
InvokeInst { invokeFunction = f } -> pointsTo pta f
_ -> []
|
travitch/llvm-analysis
|
src/LLVM/Analysis/PointsTo.hs
|
bsd-3-clause
| 1,636 | 0 | 12 | 323 | 166 | 101 | 65 | 12 | 0 |
-- {-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies,
FlexibleInstances, UndecidableInstances #-}
-- This tests an aspect of functional dependencies, revealing a bug in GHC 6.0.1
-- discovered by Martin Sulzmann
module ShouldCompile where
data PHI = PHI
data EMPT = EMPT
data LAB l a = LAB l a
data Phi1 = Phi1
data A = A
data A_H = A_H [Char]
class LNFyV r1 r2 h1 h2 | r1 -> r2, r1 r2 -> h1 h2 where
lnfyv :: r1->r2->h1->h2
instance ( REtoHT (LAB l c) h)
=> LNFyV (LAB l c) ((LAB l c),EMPT) h (h,[Phi1]) where -- (L2)
lnfyv = error "urk"
class REtoHT s t | s->t
instance REtoHT (LAB A [Char]) A_H -- (R4)
foo = lnfyv (LAB A "") ((LAB A ""),EMPT) (A_H "1")
{-
ghci 6.0.1
*Test> :t (lnfyv (LAB A "") ((LAB A ""),EMPT) (A_H "1") )
No instance for (LNFyV (LAB A [Char])
(LAB A [Char], EMPT)
A_H
(h, [Phi]))
arising from use of `lnfyv' at <No locn>
hugs November 2002
Test> :t (lnfyv (LAB A "") ((LAB A ""),EMPT) (A_H "1"))
lnfyv (LAB A "") (LAB A "",EMPT) (A_H "1") :: (A_H,[Phi])
hugs is right, here's why
(lnfyv (LAB A "") ((LAB A ""),EMPT) (A_H "1")) yields
LNFyV (LAB A Char) ((LAB A Char),EMPT) (A_H) c
improve by (L2) LNFyV (LAB A Char) ((LAB A Char),EMPT) (A_H) (A_H,[Phi]), c=(A_H,[Phi])
reduce by (L2) REtoHT (LAB A Char) A_H, c=(A_H,[Phi])
reduce by (R4) c=(A_H,[Phi])
-}
|
rahulmutt/ghcvm
|
tests/suite/typecheck/compile/tc180.hs
|
bsd-3-clause
| 1,495 | 0 | 9 | 399 | 256 | 145 | 111 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
module Ros.Sensor_msgs.SetCameraInfoResponse where
import qualified Prelude as P
import Prelude ((.), (+), (*))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import qualified GHC.Generics as G
import qualified Data.Default.Generics as D
import Ros.Internal.Msg.SrvInfo
import qualified Data.Word as Word
import Lens.Family.TH (makeLenses)
import Lens.Family (view, set)
data SetCameraInfoResponse = SetCameraInfoResponse { _success :: P.Bool
, _status_message :: P.String
} deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)
$(makeLenses ''SetCameraInfoResponse)
instance RosBinary SetCameraInfoResponse where
put obj' = put (_success obj') *> put (_status_message obj')
get = SetCameraInfoResponse <$> get <*> get
instance MsgInfo SetCameraInfoResponse where
sourceMD5 _ = "2ec6f3eff0161f4257b808b12bc830c2"
msgTypeName _ = "sensor_msgs/SetCameraInfoResponse"
instance D.Default SetCameraInfoResponse
instance SrvInfo SetCameraInfoResponse where
srvMD5 _ = "bef1df590ed75ed1f393692395e15482"
srvTypeName _ = "sensor_msgs/SetCameraInfo"
|
acowley/roshask
|
msgs/Sensor_msgs/Ros/Sensor_msgs/SetCameraInfoResponse.hs
|
bsd-3-clause
| 1,375 | 1 | 9 | 254 | 297 | 176 | 121 | 31 | 0 |
{-# LANGUAGE Safe #-}
{-# LANGUAGE TypeOperators #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.Zip
-- Copyright : (c) Nils Schweinsberg 2011,
-- (c) George Giorgidze 2011
-- (c) University Tuebingen 2011
-- License : BSD-style (see the file libraries/base/LICENSE)
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Monadic zipping (used for monad comprehensions)
--
-----------------------------------------------------------------------------
module Control.Monad.Zip where
import Control.Monad (liftM, liftM2)
import Data.Functor.Identity
import Data.Monoid
import Data.Ord ( Down(..) )
import Data.Proxy
import qualified Data.List.NonEmpty as NE
import GHC.Generics
-- | Instances should satisfy the laws:
--
-- [Naturality]
--
-- @'liftM' (f 'Control.Arrow.***' g) ('mzip' ma mb)
-- = 'mzip' ('liftM' f ma) ('liftM' g mb)@
--
-- [Information Preservation]
--
-- @'liftM' ('Prelude.const' ()) ma = 'liftM' ('Prelude.const' ()) mb@
-- implies
-- @'munzip' ('mzip' ma mb) = (ma, mb)@
--
class Monad m => MonadZip m where
{-# MINIMAL mzip | mzipWith #-}
mzip :: m a -> m b -> m (a,b)
mzip = mzipWith (,)
mzipWith :: (a -> b -> c) -> m a -> m b -> m c
mzipWith f ma mb = liftM (uncurry f) (mzip ma mb)
munzip :: m (a,b) -> (m a, m b)
munzip mab = (liftM fst mab, liftM snd mab)
-- munzip is a member of the class because sometimes
-- you can implement it more efficiently than the
-- above default code. See #4370 comment by giorgidze
-- | @since 4.3.1.0
instance MonadZip [] where
mzip = zip
mzipWith = zipWith
munzip = unzip
-- | @since 4.9.0.0
instance MonadZip NE.NonEmpty where
mzip = NE.zip
mzipWith = NE.zipWith
munzip = NE.unzip
-- | @since 4.8.0.0
instance MonadZip Identity where
mzipWith = liftM2
munzip (Identity (a, b)) = (Identity a, Identity b)
-- | @since 4.8.0.0
instance MonadZip Dual where
-- Cannot use coerce, it's unsafe
mzipWith = liftM2
-- | @since 4.8.0.0
instance MonadZip Sum where
mzipWith = liftM2
-- | @since 4.8.0.0
instance MonadZip Product where
mzipWith = liftM2
-- | @since 4.8.0.0
instance MonadZip Maybe where
mzipWith = liftM2
-- | @since 4.8.0.0
instance MonadZip First where
mzipWith = liftM2
-- | @since 4.8.0.0
instance MonadZip Last where
mzipWith = liftM2
-- | @since 4.8.0.0
instance MonadZip f => MonadZip (Alt f) where
mzipWith f (Alt ma) (Alt mb) = Alt (mzipWith f ma mb)
-- | @since 4.9.0.0
instance MonadZip Proxy where
mzipWith _ _ _ = Proxy
-- Instances for GHC.Generics
-- | @since 4.9.0.0
instance MonadZip U1 where
mzipWith _ _ _ = U1
-- | @since 4.9.0.0
instance MonadZip Par1 where
mzipWith = liftM2
-- | @since 4.9.0.0
instance MonadZip f => MonadZip (Rec1 f) where
mzipWith f (Rec1 fa) (Rec1 fb) = Rec1 (mzipWith f fa fb)
-- | @since 4.9.0.0
instance MonadZip f => MonadZip (M1 i c f) where
mzipWith f (M1 fa) (M1 fb) = M1 (mzipWith f fa fb)
-- | @since 4.9.0.0
instance (MonadZip f, MonadZip g) => MonadZip (f :*: g) where
mzipWith f (x1 :*: y1) (x2 :*: y2) = mzipWith f x1 x2 :*: mzipWith f y1 y2
-- instances for Data.Ord
-- | @since 4.12.0.0
instance MonadZip Down where
mzipWith = liftM2
|
sdiehl/ghc
|
libraries/base/Control/Monad/Zip.hs
|
bsd-3-clause
| 3,424 | 0 | 10 | 790 | 791 | 438 | 353 | 57 | 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="ko-KR">
<title>Call Graph</title>
<maps>
<homeID>callgraph</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/callgraph/src/main/javahelp/help_ko_KR/helpset_ko_KR.hs
|
apache-2.0
| 961 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
{-# LANGUAGE RankNTypes, GADTs #-}
module Foo where
g :: (Int, Int) -> Int
{-# NOINLINE g #-}
g (p,q) = p+q
f :: Int -> Int -> Int -> Int
f x p q
= g (let j y = (y+p,q)
{-# NOINLINE j #-}
in
case x of
2 -> j 3
_ -> j 4)
|
sdiehl/ghc
|
testsuite/tests/simplCore/should_compile/T13543.hs
|
bsd-3-clause
| 281 | 0 | 12 | 119 | 121 | 65 | 56 | 12 | 2 |
{-# OPTIONS -fglasgow-exts -fforall #-}
-- Make sure for-alls can occur in data types
module Foo where
newtype CPS1 a = CPS1 { unCPS1 :: forall ans . (a -> ans) -> ans }
newtype CPS2 a = CPS2 (forall ans . (a -> ans) -> ans)
-- This one also has an interesting record selector;
-- caused an applyTypeArgs crash in 5.02.1
data CPS3 a = CPS3 { unCPS3 :: forall ans . (a -> ans) -> ans }
data CPS4 a = CPS4 (forall ans . (a -> ans) -> ans)
|
hvr/jhc
|
regress/tests/1_typecheck/2_pass/ghc/tc140.hs
|
mit
| 446 | 4 | 12 | 102 | 131 | 81 | 50 | -1 | -1 |
module LiftOneLevel.C3 where
import LiftOneLevel.D3(pow)
anotherFun (x:xs) = x^pow + anotherFun xs
anotherFun [] = 0
|
RefactoringTools/HaRe
|
test/testdata/LiftOneLevel/C3.hs
|
bsd-3-clause
| 121 | 0 | 7 | 20 | 52 | 28 | 24 | 4 | 1 |
{-@ LIQUID "--no-termination" @-}
module Foo where
import Language.Haskell.Liquid.Prelude
data RBTree a = Leaf
| Node Color a !(RBTree a) !(RBTree a)
deriving (Show)
data Color = B -- ^ Black
| R -- ^ Red
deriving (Eq,Show)
---------------------------------------------------------------------------
-- | Add an element -------------------------------------------------------
---------------------------------------------------------------------------
{-@ add :: (Ord a) => a -> RBT a -> RBT a @-}
add x s = makeBlack (ins x s)
{-@ ins :: (Ord a) => a -> t:RBT a -> {v: ARBTN a {(bh t)} | ((IsB t) => (isRB v))} @-}
ins kx Leaf = Node R kx Leaf Leaf
ins kx s@(Node B x l r) = case compare kx x of
LT -> let zoo = lbal x (ins kx l) r in zoo
GT -> let zoo = rbal x l (ins kx r) in zoo
EQ -> s
ins kx s@(Node R x l r) = case compare kx x of
LT -> Node R x (ins kx l) r
GT -> Node R x l (ins kx r)
EQ -> s
---------------------------------------------------------------------------
-- | Delete an element ----------------------------------------------------
---------------------------------------------------------------------------
{-@ remove :: (Ord a) => a -> RBT a -> RBT a @-}
remove x t = makeBlack (del x t)
{-@ predicate HDel T V = (bh V) = (if (isB T) then (bh T) - 1 else (bh T)) @-}
{-@ del :: (Ord a) => a -> t:RBT a -> {v:ARBT a | ((HDel t v) && ((isB t) || (isRB v)))} @-}
del x Leaf = Leaf
del x (Node _ y a b) = case compare x y of
EQ -> append y a b
LT -> case a of
Leaf -> Node R y Leaf b
Node B _ _ _ -> lbalS y (del x a) b
_ -> let zoo = Node R y (del x a) b in zoo
GT -> case b of
Leaf -> Node R y a Leaf
Node B _ _ _ -> rbalS y a (del x b)
_ -> Node R y a (del x b)
{-@ append :: y:a -> l:RBT {v:a | v < y} -> r:RBTN {v:a | y < v} {(bh l)} -> (ARBT2 a l r) @-}
append :: a -> RBTree a -> RBTree a -> RBTree a
append _ Leaf r = r
append _ l Leaf = l
append piv (Node R lx ll lr) (Node R rx rl rr) = case append piv lr rl of
Node R x lr' rl' -> Node R x (Node R lx ll lr') (Node R rx rl' rr)
lrl -> Node R lx ll (Node R rx lrl rr)
append piv (Node B lx ll lr) (Node B rx rl rr) = case append piv lr rl of
Node R x lr' rl' -> Node R x (Node B lx ll lr') (Node B rx rl' rr)
lrl -> lbalS lx ll (Node B rx lrl rr)
append piv l@(Node B _ _ _) (Node R rx rl rr) = Node R rx (append piv l rl) rr
append piv l@(Node R lx ll lr) r@(Node B _ _ _) = Node R lx ll (append piv lr r)
---------------------------------------------------------------------------
-- | Delete Minimum Element -----------------------------------------------
---------------------------------------------------------------------------
{-@ deleteMin :: RBT a -> RBT a @-}
deleteMin (Leaf) = Leaf
deleteMin (Node _ x l r) = makeBlack t
where
(_, t) = deleteMin' x l r
{-@ deleteMin' :: k:a -> l:RBT {v:a | v < k} -> r:RBTN {v:a | k < v} {(bh l)} -> (a, ARBT2 a l r) @-}
deleteMin' k Leaf r = (k, r)
deleteMin' x (Node R lx ll lr) r = (k, Node R x l' r) where (k, l') = deleteMin' lx ll lr
deleteMin' x (Node B lx ll lr) r = (k, lbalS x l' r ) where (k, l') = deleteMin' lx ll lr
---------------------------------------------------------------------------
-- | Rotations ------------------------------------------------------------
---------------------------------------------------------------------------
{-@ lbalS :: k:a -> l:ARBT {v:a | v < k} -> r:RBTN {v:a | k < v} {1 + (bh l)} -> {v: ARBTN a {1 + (bh l)} | ((IsB r) => (isRB v))} @-}
lbalS k (Node R x a b) r = Node R k (Node B x a b) r
lbalS k l (Node B y a b) = let zoo = rbal k l (Node R y a b) in zoo
lbalS k l (Node R z (Node B y a b) c) = Node R y (Node B k l a) (rbal z b (makeRed c))
lbalS k l r = liquidError "nein" -- Node R l k r
{-@ rbalS :: k:a -> l:RBT {v:a | v < k} -> r:ARBTN {v:a | k < v} {(bh l) - 1} -> {v: ARBTN a {(bh l)} | ((IsB l) => (isRB v))} @-}
rbalS k l (Node R y b c) = Node R k l (Node B y b c)
rbalS k (Node B x a b) r = let zoo = lbal k (Node R x a b) r in zoo
rbalS k (Node R x a (Node B y b c)) r = Node R y (lbal x (makeRed a) b) (Node B k c r)
rbalS k l r = liquidError "nein" -- Node R l k r
{-@ lbal :: k:a -> l:ARBT {v:a | v < k} -> RBTN {v:a | k < v} {(bh l)} -> RBTN a {1 + (bh l)} @-}
lbal k (Node R y (Node R x a b) c) r = Node R y (Node B x a b) (Node B k c r)
lbal k (Node R x a (Node R y b c)) r = Node R y (Node B x a b) (Node B k c r)
lbal k l r = Node B k l r
{-@ rbal :: k:a -> l:RBT {v:a | v < k} -> ARBTN {v:a | k < v} {(bh l)} -> RBTN a {1 + (bh l)} @-}
rbal x a (Node R y b (Node R z c d)) = Node R y (Node B x a b) (Node B z c d)
rbal x a (Node R z (Node R y b c) d) = Node R y (Node B x a b) (Node B z c d)
rbal x l r = Node B x l r
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
{-@ type BlackRBT a = {v: RBT a | ((IsB v) && (bh v) > 0)} @-}
{-@ makeRed :: l:BlackRBT a -> ARBTN a {(bh l) - 1} @-}
makeRed (Node _ x l r) = Node R x l r
makeRed Leaf = liquidError "nein"
{-@ makeBlack :: ARBT a -> RBT a @-}
makeBlack Leaf = Leaf
makeBlack (Node _ x l r) = Node B x l r
---------------------------------------------------------------------------
-- | Specifications -------------------------------------------------------
---------------------------------------------------------------------------
-- | Ordered Red-Black Trees
{-@ type ORBT a = RBTree <{\root v -> v < root }, {\root v -> v > root}> a @-}
-- | Red-Black Trees
{-@ type RBT a = {v: (ORBT a) | ((isRB v) && (isBH v)) } @-}
{-@ type RBTN a N = {v: (RBT a) | (bh v) = N } @-}
{-@ type ORBTL a X = RBT {v:a | v < X} @-}
{-@ type ORBTG a X = RBT {v:a | X < v} @-}
{-@ measure isRB :: RBTree a -> Prop
isRB (Leaf) = true
isRB (Node c x l r) = ((isRB l) && (isRB r) && ((c == R) => ((IsB l) && (IsB r))))
@-}
-- | Almost Red-Black Trees
{-@ type ARBT a = {v: (ORBT a) | ((isARB v) && (isBH v))} @-}
{-@ type ARBTN a N = {v: (ARBT a) | (bh v) = N } @-}
{-@ measure isARB :: (RBTree a) -> Prop
isARB (Leaf) = true
isARB (Node c x l r) = ((isRB l) && (isRB r))
@-}
-- | Conditionally Red-Black Tree
{-@ type ARBT2 a L R = {v:ARBTN a {(bh L)} | (((IsB L) && (IsB R)) => (isRB v))} @-}
-- | Color of a tree
{-@ measure col :: RBTree a -> Color
col (Node c x l r) = c
col (Leaf) = B
@-}
{-@ measure isB :: RBTree a -> Prop
isB (Leaf) = false
isB (Node c x l r) = c == B
@-}
{-@ predicate IsB T = not ((col T) == R) @-}
-- | Black Height
{-@ measure isBH :: RBTree a -> Prop
isBH (Leaf) = true
isBH (Node c x l r) = ((isBH l) && (isBH r) && (bh l) = (bh r))
@-}
{-@ measure bh :: RBTree a -> Int
bh (Leaf) = 0
bh (Node c x l r) = (bh l) + (if (c == R) then 0 else 1)
@-}
-- | Binary Search Ordering
{-@ data RBTree a <l :: a -> a -> Prop, r :: a -> a -> Prop>
= Leaf
| Node (c :: Color)
(key :: a)
(left :: RBTree <l, r> (a <l key>))
(left :: RBTree <l, r> (a <r key>))
@-}
-------------------------------------------------------------------------------
-- Auxiliary Invariants -------------------------------------------------------
-------------------------------------------------------------------------------
{-@ predicate Invs V = ((Inv1 V) && (Inv2 V) && (Inv3 V)) @-}
{-@ predicate Inv1 V = (((isARB V) && (IsB V)) => (isRB V)) @-}
{-@ predicate Inv2 V = ((isRB v) => (isARB v)) @-}
{-@ predicate Inv3 V = 0 <= (bh v) @-}
{-@ invariant {v: Color | (v = R || v = B)} @-}
{-@ invariant {v: RBTree a | (Invs v)} @-}
{-@ inv :: RBTree a -> {v:RBTree a | (Invs v)} @-}
inv Leaf = Leaf
inv (Node c x l r) = Node c x (inv l) (inv r)
|
mightymoose/liquidhaskell
|
benchmarks/llrbtree-0.1.1/Data/Set/RBTree-ord.hs
|
bsd-3-clause
| 8,985 | 0 | 17 | 3,069 | 2,035 | 1,037 | 998 | 71 | 7 |
module HAD.Y2014.M03.D06.Exercise where
-- | takeStrictlyLessThan take elements of a list whils their sum is
-- _strictly_ less than a given number
--
-- Point-free: I didnt' try without parameter, you can easily "hide" the 2nd
-- parameter (ie. takeStrictlyLessThan x = …)
-- Level: MEDIUM
--
-- Examples:
-- >>> takeStrictlyLessThan (10::Int) [1..]
-- [1,2,3]
--
-- >>> takeStrictlyLessThan (3::Integer) $ repeat 1
-- [1,1]
--
-- >>> takeStrictlyLessThan (42::Int) $ []
-- []
--
-- takeStrictlyLessThan :: Choose your poison
takeStrictlyLessThan = undefined
|
weima/1HAD
|
exercises/HAD/Y2014/M03/D06/Exercise.hs
|
mit
| 564 | 0 | 4 | 87 | 32 | 28 | 4 | 2 | 1 |
module Yesod.Core.Internal.Session
( encodeClientSession
, decodeClientSession
, clientSessionDateCacher
, ClientSessionDateCache(..)
, SaveSession
, SessionBackend(..)
) where
import qualified Web.ClientSession as CS
import Data.Serialize
import Data.Time
import Data.ByteString (ByteString)
import Control.Concurrent (forkIO, killThread, threadDelay)
import Control.Monad (forever, guard)
import Yesod.Core.Types
import Yesod.Core.Internal.Util
import qualified Data.IORef as I
encodeClientSession :: CS.Key
-> CS.IV
-> ClientSessionDateCache -- ^ expire time
-> ByteString -- ^ remote host
-> SessionMap -- ^ session
-> ByteString -- ^ cookie value
encodeClientSession key iv date rhost session' =
CS.encrypt key iv $ encode $ SessionCookie expires rhost session'
where expires = Right (csdcExpiresSerialized date)
decodeClientSession :: CS.Key
-> ClientSessionDateCache -- ^ current time
-> ByteString -- ^ remote host field
-> ByteString -- ^ cookie value
-> Maybe SessionMap
decodeClientSession key date rhost encrypted = do
decrypted <- CS.decrypt key encrypted
SessionCookie (Left expire) rhost' session' <-
either (const Nothing) Just $ decode decrypted
guard $ expire > csdcNow date
guard $ rhost' == rhost
return session'
----------------------------------------------------------------------
-- Mostly copied from Kazu's date-cache, but with modifications
-- that better suit our needs.
--
-- The cached date is updated every 10s, we don't need second
-- resolution for session expiration times.
clientSessionDateCacher ::
NominalDiffTime -- ^ Inactive session valitity.
-> IO (IO ClientSessionDateCache, IO ())
clientSessionDateCacher validity = do
ref <- getUpdated >>= I.newIORef
tid <- forkIO $ forever (doUpdate ref)
return $! (I.readIORef ref, killThread tid)
where
getUpdated = do
now <- getCurrentTime
let expires = validity `addUTCTime` now
expiresS = runPut (putTime expires)
return $! ClientSessionDateCache now expires expiresS
doUpdate ref = do
threadDelay 10000000 -- 10s
I.writeIORef ref =<< getUpdated
|
ygale/yesod
|
yesod-core/Yesod/Core/Internal/Session.hs
|
mit
| 2,356 | 0 | 14 | 593 | 506 | 269 | 237 | 52 | 1 |
{-# LANGUAGE TypeFamilies, FlexibleContexts, FlexibleInstances #-}
module T6161 where
data family Fam a
data instance Fam Float = FamFloat Float
class Super a where
testSup :: a -> Float
class Super a => Duper a where
testDup :: a -> Float
--class ( Super (Fam a) ) => Foo a where
class Duper (Fam a) => Foo a where
testFoo :: Fam a -> Float
instance Foo a => Duper (Fam a) where
testDup x = testFoo x + testSup x
--instance Super (Fam Float) where
-- testSup (FamFloat x) = x
instance Foo Float where
testFoo (FamFloat _) = 5.0
testProg :: Float
testProg = testDup (FamFloat 3.0)
|
forked-upstream-packages-for-ghcjs/ghc
|
testsuite/tests/typecheck/should_fail/T6161.hs
|
bsd-3-clause
| 603 | 0 | 8 | 131 | 184 | 94 | 90 | 16 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
-- | Get a mapping from statement patterns to statement expression for all
-- statements.
module Futhark.Optimise.MemoryBlockMerging.Coalescing.Exps
( Exp'(..)
, findExpsFunDef
) where
import qualified Data.Map.Strict as M
import Control.Monad
import Control.Monad.Writer
import Futhark.Representation.AST
import Futhark.Representation.ExplicitMemory (ExplicitMemorish)
import Futhark.Representation.Kernels.Kernel
import Futhark.Optimise.MemoryBlockMerging.Miscellaneous
-- | Describes the nth pattern and the statement expression.
data Exp' = forall lore. Annotations lore => Exp Int (Exp lore)
instance Show Exp' where
show (Exp _npattern e) = show e
type Exps = M.Map VName Exp'
newtype FindM lore a = FindM { unFindM :: Writer Exps a }
deriving (Monad, Functor, Applicative,
MonadWriter Exps)
type LoreConstraints lore = (ExplicitMemorish lore,
FullWalk lore)
coerce :: (ExplicitMemorish flore, ExplicitMemorish tlore) =>
FindM flore a -> FindM tlore a
coerce = FindM . unFindM
findExpsFunDef :: LoreConstraints lore =>
FunDef lore -> Exps
findExpsFunDef fundef =
let m = unFindM $ lookInBody $ funDefBody fundef
res = execWriter m
in res
lookInBody :: LoreConstraints lore =>
Body lore -> FindM lore ()
lookInBody (Body _ bnds _res) =
mapM_ lookInStm bnds
lookInKernelBody :: LoreConstraints lore =>
KernelBody lore -> FindM lore ()
lookInKernelBody (KernelBody _ bnds _res) =
mapM_ lookInStm bnds
lookInStm :: LoreConstraints lore =>
Stm lore -> FindM lore ()
lookInStm (Let (Pattern _patctxelems patvalelems) _ e) = do
forM_ (zip patvalelems [0..]) $ \(PatElem var _ _, i) ->
tell $ M.singleton var $ Exp i e
-- Recursive body walk.
fullWalkExpM walker walker_kernel e
where walker = identityWalker
{ walkOnBody = lookInBody }
walker_kernel = identityKernelWalker
{ walkOnKernelBody = coerce . lookInBody
, walkOnKernelKernelBody = coerce . lookInKernelBody
}
|
ihc/futhark
|
src/Futhark/Optimise/MemoryBlockMerging/Coalescing/Exps.hs
|
isc
| 2,265 | 0 | 12 | 498 | 569 | 306 | 263 | 52 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Network.HTTP.Toolkit.RequestSpec (main, spec) where
import Helper
import qualified Data.ByteString.Char8 as B
import Network.HTTP.Toolkit.Body
import Network.HTTP.Toolkit.Request
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "determineRequestBodyType" $ do
it "returns None" $ do
determineRequestBodyType [] `shouldBe` None
context "when Transfer-Encoding is specified" $ do
it "returns Chunked" $ do
determineRequestBodyType [("Transfer-Encoding", "foo")] `shouldBe` Chunked
it "gives Transfer-Encoding precedence over Content-Length" $ do
determineRequestBodyType [("Transfer-Encoding", "foo"), ("Content-Length", "5")] `shouldBe` Chunked
it "ignores Transfer-Encoding when set to identity" $ do
determineRequestBodyType [("Transfer-Encoding", "identity"), ("Content-Length", "5")] `shouldBe` Length 5
context "when Content-Length is specified" $ do
it "returns Length" $ do
property $ \(NonNegative n) -> do
determineRequestBodyType [("Content-Length", B.pack $ show n)] `shouldBe` Length n
describe "parseRequestLine" $ do
it "parses HTTP request line" $ do
parseRequestLine "GET /index.html HTTP/1.1" `shouldBe` Just ("GET", "/index.html")
it "returns Nothing on parse error" $ do
parseRequestLine "foo" `shouldBe` Nothing
|
zalora/http-kit
|
test/Network/HTTP/Toolkit/RequestSpec.hs
|
mit
| 1,437 | 0 | 25 | 303 | 363 | 189 | 174 | 29 | 1 |
parenToNum c = if c == '(' then 1 else -1
parenStrToNums = map parenToNum
basementPos _ (-1) pos = pos
basementPos (x:xs) sum pos = basementPos xs (sum + x) (pos + 1)
main = do
input <- readFile "input.txt"
let oneszeros = parenStrToNums input
putStrLn (show (basementPos oneszeros 0 0))
|
RatanRSur/advent-of-haskell
|
day1/part2.hs
|
mit
| 302 | 0 | 11 | 66 | 137 | 68 | 69 | 8 | 2 |
-- https://www.reddit.com/r/dailyprogrammer/comments/pm7g7/2122012_challange_4_difficult/
module Main where
import Control.Monad
import Data.List
import Data.Tuple
import Language.Arithmetic
-- The ability to select a given number of values
-- from a list. All in the non-determinism monad
select :: [a] -> [(a, [a])]
select [] = []
select (x : xs) = (x, xs) : fmap (fmap (x:)) (select xs)
selects :: Int -> [a] -> [[a]]
selects 0 xs = return []
selects k xs = do
(a , ys) <- select xs
fmap (a :) $ selects (k - 1) ys
-- The ability to grow an arithmetic expression
-- at any leaf using arbitrary operations.
grow :: Int -> Arith -> [Arith]
grow l = go where
andComm :: BinOp -> [(a,a)] -> [(a,a)]
andComm op as =
if op `elem` [Add, Mul] then as
else as ++ fmap swap as
go a@(Lift k) = do
op <- [minBound..maxBound]
(e, f) <- andComm op [(a, Lift l)]
return $ Op op e f
go (Op op a b) = do
fmap (\ a' -> Op op a' b) (go a)
++ fmap (\ b' -> Op op a b') (go b)
-- Growing multiple times
grows :: [Int] -> Arith -> [Arith]
grows ks a = foldr (concatMap . grow) [a] ks
-- Selecting interesting equations by growing
-- one k times and keeping it only if it is
-- equal to a given value
ariths :: Int -> [Int] -> [(Arith, Int)]
ariths k ks = do
(e : f : gs) <- selects k ks
a <- grows gs (Lift e)
guard (evalArith a == Just f)
return (a, f)
displayEquation :: Arith -> Int -> String
displayEquation a b = show a ++ " = " ++ show b
main :: IO ()
main = do
xs <- fmap read . words . filter (/= ',') <$> getLine
let threes = nub $ ariths 3 xs
let fours = nub $ ariths 4 xs
let allvals = nub $ ariths (length xs) xs
mapM_ (uncurry $ \ name equations -> do
putStrLn ("*** " ++ name)
mapM_ (putStrLn . uncurry displayEquation) equations)
[ ("threes", threes)
, ("fours", fours)
, ("allvals", allvals)
]
|
gallais/dailyprogrammer
|
difficult/004/Main.hs
|
mit
| 1,934 | 0 | 16 | 506 | 824 | 434 | 390 | 48 | 3 |
nww :: Integer -> Integer -> Integer
nww x y = head $ filter (\xx -> xx `mod` y == 0 && xx `mod` x == 0) $ if x > y then [x..x*y] else [y..y*x]
|
RAFIRAF/HASKELL
|
nww3.hs
|
mit
| 144 | 0 | 14 | 36 | 97 | 53 | 44 | 2 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
import Data.Foldable (for_)
import Data.String (fromString)
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import Acronym (abbreviate)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = describe "abbreviate" $ for_ cases test
where
test Case {..} = it description $
abbreviate (fromString input) `shouldBe` fromString expected
data Case = Case { description :: String
, input :: String
, expected :: String
}
cases :: [Case]
cases = [ Case { description = "basic"
, input = "Portable Network Graphics"
, expected = "PNG"
}
, Case { description = "lowercase words"
, input = "Ruby on Rails"
, expected = "ROR"
}
-- Although this case was removed in specification 1.1.0,
-- the Haskell track has chosen to keep it,
-- since it makes the problem more interesting.
, Case { description = "camelcase"
, input = "HyperText Markup Language"
, expected = "HTML"
}
, Case { description = "punctuation"
, input = "First In, First Out"
, expected = "FIFO"
}
, Case { description = "all caps word"
, input = "GNU Image Manipulation Program"
, expected = "GIMP"
}
, Case { description = "punctuation without whitespace"
, input = "Complementary metal-oxide semiconductor"
, expected = "CMOS"
}
, Case { description = "very long abbreviation"
, input = "Rolling On The Floor Laughing So Hard That My Dogs Came Over And Licked Me"
, expected = "ROTFLSHTMDCOALM"
}
, Case { description = "consecutive delimiters"
, input = "Something - I made up from thin air"
, expected = "SIMUFTA"
}
, Case { description = "apostrophes"
, input = "Halley's Comet"
, expected = "HC"
}
, Case { description = "underscore emphasis"
, input = "The Road _Not_ Taken"
, expected = "TRNT"
}
]
-- ad42f2da40183e017f9c52fd00efe33c6bfe7037
|
exercism/xhaskell
|
exercises/practice/acronym/test/Tests.hs
|
mit
| 2,624 | 0 | 11 | 1,054 | 432 | 267 | 165 | 47 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module LLVM.Codegen.Logic (
def,
arg,
var,
avar,
constant,
ife,
for,
while,
range,
loopnest,
seqn,
proj,
assign,
initrec,
(^.),
(.=),
ucast,
scast,
imin,
imax,
printf,
debugInt,
debugFloat,
true,
false,
one,
zero
) where
import Control.Monad (forM, zipWithM_ )
import Control.Monad.Error
import LLVM.Codegen.Builder
import LLVM.Codegen.Module
import LLVM.Codegen.Types
import LLVM.Codegen.Constant
import LLVM.Codegen.Instructions
import LLVM.Codegen.Structure
import qualified LLVM.General.AST.IntegerPredicate as IP
import qualified LLVM.General.AST.Global as G
import LLVM.General.AST (Name(..), Type, Operand, Definition(..))
-------------------------------------------------------------------------------
-- Constants
-------------------------------------------------------------------------------
-- | Constant false value
false :: Codegen Operand
false = return $ constant i1 0
-- | Constant true value
true :: Codegen Operand
true = return $ constant i1 1
-- | Constant integer zero
zero :: Operand
zero = constant i32 0
-- | Constant integer one
one :: Operand
one = constant i32 1
-------------------------------------------------------------------------------
-- Function
-------------------------------------------------------------------------------
-- | Construct a toplevel function.
def :: String -> Type -> [(Type, String)] -> Codegen Operand -> LLVM ()
def name retty argtys body = do
-- XXX cleanup
case makeEntry of
Left err -> throwError err
Right (blocks, globals) -> do
mapM addDefn globals
define retty name argtys blocks
where
makeEntry = evalCodegen $ do
entryBlock
-- Map arguments into values in the symbol table
forM argtys $ \(ty, a) -> do
avar <- (a ++ ".addr") `named` alloca ty
store avar (local (Name a))
setvar a avar
body >>= ret
-- | Retrieve the value of a locally named variable.
arg :: String -> Codegen Operand
arg s = getvar s >>= load
-- | Construct a named variable
var :: Type -> Operand -> String -> Codegen Operand
var ty val name = do
ref <- alloca ty
store ref val
setvar name ref
return ref
-- | Construct an unnamed variable
avar :: Type -> Operand -> Codegen Operand
avar ty val = do
name <- freshName
ref <- alloca ty
store ref val
return ref
constant ty val
| ty == i1 = cons $ ci1 $ val
| ty == i8 = cons $ ci8 $ val
| ty == i16 = cons $ ci16 $ val
| ty == i32 = cons $ ci32 $ val
| ty == i64 = cons $ ci64 $ val
| ty == f32 = cons $ cf32 $ realToFrac val
| ty == f64 = cons $ cf64 $ realToFrac val
| otherwise = error "Constant not supported"
-- Unsigned cast
ucast :: Type -> Type -> Operand -> Codegen Operand
ucast from to val
| isInt from && isInt to = zext to val
| isFloat from && isInt to = fptoui to val
| isFloat from && isInt to = fptoui to val
| isFloat from && isFloat to = fpext to val
-- Signed cast
scast :: Type -> Type -> Operand -> Codegen Operand
scast from to val
| isInt from && isInt to = sext to val
| isFloat from && isInt to = fptosi to val
| isFloat from && isInt to = fptosi to val
| isFloat from && isFloat to = fpext to val
-- | Construction a if/then/else statement
ife :: Type -> Operand -> Codegen Operand -> Codegen Operand -> Codegen Operand
ife ty cond tr fl = do
ifthen <- addBlock "if.then"
ifelse <- addBlock "if.else"
ifexit <- addBlock "if.exit"
cbr cond ifthen ifelse
setBlock ifthen
trval <- tr
br ifexit
ifthen' <- getBlock
setBlock ifelse
flval <- fl
br ifexit
ifelse' <- getBlock
setBlock ifexit
phi ty [(trval, ifthen'), (flval, ifelse')]
-- | Construction a for statement
for :: Codegen Operand -- ^ Iteration variable
-> (Operand -> Codegen Operand) -- ^ Iteration action
-> (Operand -> Codegen Operand) -- ^ Loop exit condition
-> (Operand -> Codegen a) -- ^ Loop body
-> Codegen ()
for ivar inc cond body = do
forcond <- addBlock "for.cond"
forloop <- addBlock "for.loop"
forinc <- addBlock "for.inc"
forexit <- addBlock "for.exit"
i <- ivar
br forcond
setBlock forcond
ival <- load i
test <- cond ival
cbr test forloop forexit
setBlock forloop
ival <- load i
body ival
br forinc
setBlock forinc
iinc <- inc ival
store i iinc
br forcond
setBlock forexit
return ()
-- | Construction for range statement
range :: String -- ^ Name of the iteration variable
-> Operand -- ^ Lower bound
-> Operand -- ^ Upper bound
-> (Operand -> Codegen a) -- ^ Loop body
-> Codegen ()
range ivar start stop body = do
forcond <- addBlock "for.cond"
forloop <- addBlock "for.loop"
forinc <- addBlock "for.inc"
forexit <- addBlock "for.exit"
let lower = start
let upper = stop
i <- var i32 lower ivar
br forcond
setBlock forcond
ival <- load i
test <- icmp IP.ULT ival upper
cbr test forloop forexit
setBlock forloop
ival <- load i
body ival
br forinc
setBlock forinc
iinc <- add ival one
store i iinc
br forcond
setBlock forexit
return ()
-- | Construction a while statement
while :: Codegen Operand -> Codegen a -> Codegen ()
while cond body = do
forcond <- addBlock "while.cond"
forloop <- addBlock "while.loop"
forexit <- addBlock "while.exit"
br forcond
setBlock forcond
test <- cond
cbr test forloop forexit
setBlock forloop
body
br forcond
setBlock forexit
return ()
-- | Construct a multidimensional loop nest. The equivelant in C would be like the following:
--
-- @
-- int i, j;
-- for ( j = 0; j < 100; ++j ) {
-- for ( i = 0; i < 100; ++i ) {
-- .. loop body ..
-- }
-- }
-- @
loopnest :: [Int] -- ^ Start bounds
-> [Int] -- ^ End bounds
-> [Int] -- ^ loop steps
-> ([Operand] -> Codegen a) -- ^ Loop body
-> Codegen ()
loopnest begins ends steps body = do
-- Create the iteration variables
ivars <- mapM makeIVar begins
-- Build up the loops up recursively
go ivars begins ends steps
where
makeIVar _ = avar i32 zero >>= load
go ivars [] [] [] = (body ivars) >> return ()
go ivars (b:bs) (e:es) (s:ss) = do
let start = constant i32 b
let stop = constant i32 e
range "i" start stop $ \_ ->
go ivars bs es ss
go _ _ _ _ = error "loop nest bounds are not equaly sized"
(^.) :: Record -> RecField -> Codegen Operand
(^.) = proj
-- | Construction a record projection statement
proj :: Record -> RecField -> Codegen Operand
proj rec field =
case idxOf field rec of
Nothing -> error $ "No such field name: " ++ show field
Just ix -> gep (recValue rec) [constant i32 0, constant i32 ix]
(.=) :: RecField -> Operand -> Record -> Codegen ()
field .= val = \struct -> assign struct field val
assign :: Record -> RecField -> Operand -> Codegen ()
assign struct fld val = do
ptr <- proj struct fld
store ptr val
-- | Construction a record assignment statement
initrec :: RecordType -> [Operand] -> Codegen Record
initrec rty vals = do
struct <- allocaRecord rty
zipWithM_ (assign struct) (fieldsOf rty) vals
return struct
-- | Construction of a sequence statement
seqn :: Codegen a -> Codegen b -> Codegen b
seqn = (>>)
-------------------------------------------------------------------------------
-- Comparison
-------------------------------------------------------------------------------
-- | min(a,b)
imin :: Operand -> Operand -> Codegen Operand
imin a b = do
test <- icmp IP.ULT a b
ife i32 test (return a) (return b)
-- | max(a,b)
imax :: Operand -> Operand -> Codegen Operand
imax a b = do
test <- icmp IP.ULT a b
ife i32 test (return a) (return b)
-------------------------------------------------------------------------------
-- Debug
-------------------------------------------------------------------------------
-- | Wrapper for debugging with printf
printf :: String -> [Operand] -> Codegen Operand
printf str vals = do
addGlobal defn
addGlobal cprintf
fmt <- gep (global strnm) [zero, zero]
call (fn "printf") (fmt : vals)
where
ty = (array (len + 1) i8)
cstr = cstringz str
len = fromIntegral $ length str
strnm = Name $ take 10 str
defn = GlobalDefinition $ G.globalVariableDefaults {
G.name = strnm
, G.type' = ty
, G.initializer = (Just cstr)
}
-- In C all float arguments to printf are automatically promoted to doubles.
debugInt :: String -> Operand -> Codegen Operand
debugInt fmt val = do
cval <- zext i64 val
printf fmt [cval]
debugFloat :: String -> Operand -> Codegen Operand
debugFloat fmt val = do
cval <- fpext double val
printf fmt [cval]
|
sdiehl/llvm-codegen
|
src/LLVM/Codegen/Logic.hs
|
mit
| 8,970 | 0 | 18 | 2,225 | 2,843 | 1,382 | 1,461 | 249 | 3 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.AudioStreamTrack (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.AudioStreamTrack
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.AudioStreamTrack
#else
#endif
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/AudioStreamTrack.hs
|
mit
| 361 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |
module Main where
import qualified Cenary.Main
main :: IO ()
main = Cenary.Main.main
|
yigitozkavci/ivy
|
src/Main.hs
|
mit
| 87 | 0 | 6 | 15 | 28 | 17 | 11 | 4 | 1 |
myLast :: [a] -> a
myLast [x] = x
myLast (_:xs) = myLast xs
|
curiousily/haskell-99problems
|
1.hs
|
mit
| 60 | 0 | 7 | 14 | 42 | 22 | 20 | 3 | 1 |
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.Async (wait)
import Control.Monad (unless)
import System.Console.AsciiProgress
main :: IO ()
main = displayConsoleRegions $ do
pg1 <- newProgressBar def { pgWidth = 100
, pgOnCompletion = Just "pg 1 is Done!"
}
_ <- forkIO $ loop pg1 (100 * 1000)
pg2 <- newProgressBar def { pgWidth = 100
, pgOnCompletion = Just "pg 2 is Done!"
}
_ <- forkIO $ loop pg2 (400 * 1000)
pg3 <- newProgressBar def { pgWidth = 100
, pgOnCompletion = Just "pg 3 is Done!"
}
_ <- forkIO $ loop pg3 (200 * 1000)
wait $ pgFuture pg1
wait $ pgFuture pg2
wait $ pgFuture pg3
where
loop pg ts = do
b <- isComplete pg
unless b $ do
threadDelay ts
tick pg
loop pg ts
|
yamadapc/haskell-ascii-progress
|
bin/MultiExample.hs
|
mit
| 1,057 | 0 | 12 | 479 | 292 | 143 | 149 | 24 | 1 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Data.Tensor.Scheme.DenseGD
(DenseGD(..)
,mkDenseGD
,mkDefaultDenseGD)
where
import Prelude hiding (foldr1)
import Data.Foldable (foldl', foldr1)
import Data.Monoid (mempty, (<>))
import Data.Sequence (Seq)
import qualified Data.Sequence as SQ
import qualified Data.Vector.Generic as GV
import Data.Permutation (Permutation, permute, invert)
import Data.Tensor.Shape (ShapeGD,rank)
import Data.Tensor.Scheme (Scheme(..),VectorScheme(..),DenseScheme(..))
data DenseGD = DenseGD { _sgdShape :: ShapeGD
, _sgdStorageOrder :: Permutation
, _sgdMTable :: Seq Int
, _sgdOffset :: Int }
mkDenseGD :: Permutation -> Int -> ShapeGD -> DenseGD
mkDenseGD so off s = DenseGD s so mtable off
where mtable = permute (invert so) . SQ.scanr (*) 1 . SQ.drop 1 . permute so $ s
mkDefaultDenseGD :: ShapeGD -> DenseGD
mkDefaultDenseGD = mkDenseGD mempty 0
sgdRank :: DenseGD -> Int
sgdRank = rank . _sgdShape
instance Scheme DenseGD where
type SchemeSelector DenseGD = Seq Int
type SchemeShape DenseGD = ShapeGD
unsafeSelectorToInx sc = foldr1 (+) . SQ.zipWith (*) (_sgdMTable sc)
selectorToInx sc sel = if diffLength || inxOutOfRange
then Nothing
else Just us
where diffLength = SQ.length (_sgdMTable sc) /= SQ.length sel
inxOutOfRange = (us < 0) || (us >= rnk)
us = unsafeSelectorToInx sc sel
rnk = sgdRank sc
inxToSelector sc i = if (i < 0) || (i >= sgdRank sc)
then Nothing
else Just . permute (invert $ _sgdStorageOrder sc) $ soSel
where soSel = fst . foldl' selStep (SQ.empty, i) $ soMTable
selStep (tsel,i') c = let (s,i'') = i' `quotRem` c
in (tsel SQ.|> s, i'')
soMTable = permute (_sgdStorageOrder sc) (_sgdMTable sc)
shape = _sgdShape
storageSize = rank . shape
permuteInxs p sc = mkDenseGD (p <> _sgdStorageOrder sc) 0 (_sgdShape sc)
instance (GV.Vector v e) => VectorScheme DenseGD v e where
getElt = getElt . DenseScheme
unsafeGetElt = unsafeGetElt . DenseScheme
|
lensky/hs-tensor
|
lib/Data/Tensor/Scheme/DenseGD.hs
|
mit
| 2,296 | 0 | 13 | 624 | 715 | 399 | 316 | 51 | 1 |
module Example2 ( main ) where
import Data.List (intercalate)
import Control.Arrow ((&&&))
import LogicProblem
{- Ships Puzzle
from https://www.mathsisfun.com/puzzles/ships.html
There are 5 ships in a port:
1. The Greek ship leaves at six and carries coffee.
2. The Ship in the middle has a black chimney.
3. The English ship leaves at nine.
4. The French ship with blue chimney is to the left of a ship that carries coffee.
5. To the right of the ship carrying cocoa is a ship going to Marseille.
6. The Brazilian ship is heading for Manila.
7. Next to the ship carrying rice is a ship with a green chimney.
8. A ship going to Genoa leaves at five.
9. The Spanish ship leaves at seven and is to the right of the ship going to Marseille.
10. The ship with a red chimney goes to Hamburg.
11. Next to the ship leaving at seven is a ship with a white chimney.
12. The ship on the border carries corn.
13. The ship with a black chimney leaves at eight.
14. The ship carrying corn is anchored next to the ship carrying rice.
15. The ship to Hamburg leaves at six.
Which ship goes to Port Said? Which ship carries tea?
-}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
data Position = Position Int deriving (Show, Eq, Ord)
instance Bounded Position where maxBound = Position 5
minBound = Position 1
instance Enum Position where toEnum i | i >= min && i <= max = Position i
| otherwise = error $ "Position out of range: "
++ show i
where (Position min) = minBound
(Position max) = maxBound
fromEnum (Position i) = i
data Country = Greek | English | French | Brazilian | Spanish deriving (Show, Eq)
data Destination = Marseille | Manila | Genoa | Hamburg | PortSaid deriving (Show, Eq)
data Cargo = Coffee | Cocoa | Rice | Corn | Tea deriving (Show, Eq)
data Color = Black | Blue | Green | Red | White deriving (Show, Eq)
data Leaves = At Int deriving (Show, Eq) -- At5 | At6 | At7 | At8 | At9
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
facts :: KnownFacts AnEntry
facts = rules [
"1a" -: Greek <==> At 6 |:: "The Greek ship leaves at six ..."
, "1b" -: Greek <==> Coffee |:: "... and carries coffee."
, "1c" -: At 6 <==> Coffee
, "2" -: Position 3 <==> Black |:: "The Ship in the middle has a black chimney."
, "3" -: English <==> At 9 |:: "The English ship leaves at nine."
, "4a" -: French <==> Blue |:: "The French ship with blue chimney..."
, "4b" -: French <==> Coffee <?| toTheRight |:: "... is to the left of a ship that carries coffee."
, "4c" -: Blue <==> Coffee <?| toTheRight
, "5" -: Cocoa <==> Marseille <?| toTheRight |:: "To the right of the ship carrying cocoa" ++
" is a ship going to Marseille."
, "6" -: Brazilian <==> Manila |:: "The Brazilian ship is heading for Manila."
, "7" -: Rice <==> Green |?> nextTo |:: "Next to the ship carrying rice is a ship with a green chimney."
, "8" -: Genoa <==> At 5 |:: "A ship going to Genoa leaves at five."
, "9a" -: Spanish <==> At 7 |:: "The Spanish ship leaves at seven ..."
, "9b" -: Spanish <==> Marseille |?> toTheRight |:: "... and is to the right of the ship going to Marseille."
, "9c" -: At 7 <==> Marseille |?> toTheRight
, "10" -: Red <==> Hamburg |:: "The ship with a red chimney goes to Hamburg."
, "11" -: At 7 <==> White |?> nextTo |:: "Next to the ship leaving at seven is a ship with a white chimney."
, "12" -: Corn !? onTheBorder |:: "The ship on the border carries corn."
, "13" -: Black <==> At 8 |:: "The ship with a black chimney leaves at eight."
, "14" -: Corn <==> Rice |?> nextTo |:: "The ship carrying corn is anchored next to the ship carrying rice."
, "15" -: Hamburg <==> At 6 |:: "The ship to Hamburg leaves at six."
]
Just x `toTheRight` Just y = x /= y && (maxBound :: Position) /= y && succ y == x
Just x `nextTo` Just y = x /= y &&
( (maxBound :: Position) /= x && succ x == y || minBound /= x && pred x == y )
onTheBorder (Just pos) = pos == (maxBound :: Position) || pos == minBound
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
instance Accessible Position where modifiable _ = False
varDescriptor _ = AccessibleDescriptor "Position"
instance Accessible Country where modifiable _ = True
varDescriptor _ = AccessibleDescriptor "Country"
instance Accessible Leaves where modifiable _ = True
varDescriptor _ = AccessibleDescriptor "Leaves"
instance Accessible Destination where modifiable _ = True
varDescriptor _ = AccessibleDescriptor "Destination"
instance Accessible Cargo where modifiable _ = True
varDescriptor _ = AccessibleDescriptor "Cargo"
instance Accessible Color where modifiable _ = True
varDescriptor _ = AccessibleDescriptor "Color"
instance IdRepr Position where getOrd (Position i) = i
getRepr = show . getOrd
data AnEntry = AnEntry { position :: Position
, country :: Maybe Country
, destination :: Maybe Destination
, cargo :: Maybe Cargo
, color :: Maybe Color
, leavesAt :: Maybe Leaves
}
deriving Show
instance Entry AnEntry where getId (AnEntry i _ _ _ _ _) = Id i
instance AccessibleEntry AnEntry Position where getV _ = Just . position
setV _ = const Nothing
clearV _ = const Nothing
instance AccessibleEntry AnEntry Country where getV _ = country
setV e x = Just $ e {country = Just x}
clearV _ e = Just $ e {country = Nothing}
instance AccessibleEntry AnEntry Leaves where getV _ = leavesAt
setV e x = Just $ e {leavesAt = Just x}
clearV _ e = Just $ e {leavesAt = Nothing}
instance AccessibleEntry AnEntry Destination where getV _ = destination
setV e x = Just $ e {destination = Just x}
clearV _ e = Just $ e {destination = Nothing}
instance AccessibleEntry AnEntry Cargo where getV _ = cargo
setV e x = Just $ e {cargo = Just x}
clearV _ e = Just $ e {cargo = Nothing}
instance AccessibleEntry AnEntry Color where getV _ = color
setV e x = Just $ e {color = Just x}
clearV _ e = Just $ e {color = Nothing}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
newEntry pos = AnEntry pos Nothing Nothing Nothing Nothing Nothing
table = newETable (Id &&& newEntry) (enumFromTo minBound maxBound)
ctx :: ExecContext AtomicRule AnEntry
ctx = newExecContext table
res = solveProblem ctx facts Nothing --(Just 100)
main :: IO()
main = do putStrLn "facts:"
putStrLn $ intercalate "\n" (map show facts)
putStrLn "== run solveProblem =="
let (c', r', a') = res
putStrLn "-- history:"
putStrLn $ showHistory a'
putStrLn "-- context:"
print c'
putStrLn "-- result:"
print r'
|
fehu/h-logic-einstein
|
example-2/Example2.hs
|
mit
| 8,501 | 0 | 14 | 3,300 | 1,703 | 878 | 825 | -1 | -1 |
-- Dictionary sequence
-- http://www.codewars.com/kata/55c24ce1fb411bbdd1000009/
module Haskell.Codewars.Solution where
import Data.Maybe (fromJust)
alphaDict :: [String]
alphaDict = map f [0..]
where alpha = zip [0..] . map (:[]) $ ['a'..'z']++['A'..'Z']
f x | x < 52 = fromJust . lookup x $ alpha
| otherwise = (++r') . f . pred $ x'
where (x', r) = x `divMod` 52
r' = fromJust . lookup r $ alpha
|
gafiatulin/codewars
|
src/6 kyu/Solution.hs
|
mit
| 464 | 0 | 12 | 132 | 174 | 95 | 79 | 9 | 1 |
module Queue ( Queue
, emptyQ
, isEmptyQ
, addQ
, remQ ) where
data Queue a = Queue [a] [a]
emptyQ :: Queue a
emptyQ = Queue [] []
isEmptyQ :: Queue a -> Bool
isEmptyQ (Queue [] []) = True
isEmptyQ _ = False
addQ :: a -> Queue a -> Queue a
addQ x (Queue xs ys) = Queue xs (x : ys)
remQ :: Queue a -> (a, Queue a)
remQ (Queue [] []) = error "empty queue"
remQ (Queue [] ys) = remQ (Queue (reverse ys) [])
remQ (Queue (x : xs) ys) = (x, Queue xs ys)
|
tonyfloatersu/solution-haskell-craft-of-FP
|
Queue.hs
|
mit
| 550 | 0 | 9 | 205 | 265 | 138 | 127 | 17 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable, StandaloneDeriving #-}
module Yi.GHC where
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Monad.Error ()
import Control.Monad.Reader (asks)
import Control.Monad.State
import Control.Monad.Writer
import Data.Maybe
import ErrUtils
import GHC
import Outputable
import Prelude ()
import Shim.Hsinfo
import Shim.SHM hiding (io)
import Yi.Dynamic
import Yi.Editor
import Yi.Keymap
import Yi.Prelude hiding ((<>))
import qualified Data.List.PointedList.Circular as PL
import qualified Data.Map as M
import qualified Yi.Editor as Editor
newShim :: YiM (MVar ShimState)
newShim = do
session <- io $ ghcInit
r <- asks yiVar
cfg <- asks yiConfig
let logMsg msgSeverity msgSrcSpan style msg =
unsafeWithEditor cfg r $ do
let note = CompileNote msgSeverity msgSrcSpan style msg
modA notesA (Just . maybe (PL.singleton note) (PL.insertRight note))
printMsg ('\n':show ((mkLocMessage msgSrcSpan msg) style))
io $ newMVar ShimState
{ tempSession = session,
sessionMap = M.empty,
compBuffer = M.empty,
compLogAction = logMsg }
getShim :: YiM (MVar ShimState)
getShim = do
r <- withEditor $ getA maybeShimA
case r of
Just x -> return x
Nothing -> do x <- newShim
withEditor $ putA maybeShimA (Just x)
return x
withShim :: SHM a -> YiM a
withShim f = do
r <- getShim
liftIO $ do e <- takeMVar r
(a,e') <- runStateT f e
putMVar r e'
return a
runShimThread :: SHM () -> YiM ThreadId
runShimThread f = do
r <- getShim
(liftIO . forkOS) $
do e <- takeMVar r
(a,e') <- runStateT f e
putMVar r e'
return a
maybeShimA :: Accessor Editor (Maybe (MVar ShimState))
maybeShimA = dynamicValueA . dynamicA
-- ---------------------------------------------------------------------
-- CompileNote
-- TODO: Perhaps this CompileNote should be replaced with something
-- more general not necessary GHC specific.
--
-- It is moved here from Yi.Mode.Shim because it has to be accessible
-- from Yi.Core. The CompileNote type itself comes from SHIM
data CompileNote = CompileNote {severity :: Severity,
srcSpan :: SrcSpan,
pprStyle :: PprStyle,
message :: Message}
instance Show CompileNote where
show n = show $
(hang (ppr (srcSpan n) <> colon) 4 (message n)) (pprStyle n)
type T = (Maybe (PL.PointedList CompileNote))
newtype ShimNotes = ShimNotes { fromShimNotes :: T }
deriving Typeable
instance Initializable ShimNotes where
initial = ShimNotes Nothing
notesA :: Accessor Editor T
notesA = (accessor fromShimNotes (\x (ShimNotes _) -> ShimNotes x))
. dynamicValueA . dynamicA
|
codemac/yi-editor
|
src/Yi/GHC.hs
|
gpl-2.0
| 3,004 | 0 | 20 | 854 | 831 | 436 | 395 | 77 | 2 |
{- |
Module : $Header$
Copyright : DFKI GmbH 2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
-}
module ExtModal.AS_ExtModal where
import Common.Id
import Common.AS_Annotation
import CASL.AS_Basic_CASL
-- DrIFT command
{-! global: GetRange !-}
type EM_BASIC_SPEC = BASIC_SPEC EM_BASIC_ITEM EM_SIG_ITEM EM_FORMULA
type AnEModForm = Annoted (FORMULA EM_FORMULA)
data ModDefn = ModDefn Bool Bool [Annoted Id] [AnEModForm] Range
-- Booleans: time (True) or not and term (True) or simple modality
deriving (Show, Eq, Ord)
data EM_BASIC_ITEM =
ModItem ModDefn
| Nominal_decl [Annoted SIMPLE_ID] Range
deriving Show
data ModOp = Composition | Intersection | Union deriving (Eq, Ord)
instance Show ModOp where
show o = case o of
Composition -> ";"
Intersection -> "&"
Union -> "|"
data MODALITY =
SimpleMod SIMPLE_ID
| TermMod (TERM EM_FORMULA)
| ModOp ModOp MODALITY MODALITY
| TransClos MODALITY
| Guard (FORMULA EM_FORMULA)
deriving (Eq, Ord, Show)
-- True booleans for rigid items, False for flexible ones
data EM_SIG_ITEM =
Rigid_op_items Bool [Annoted (OP_ITEM EM_FORMULA)] Range
-- pos: op, semi colons
| Rigid_pred_items Bool [Annoted (PRED_ITEM EM_FORMULA)] Range
-- pos: pred, semi colons
deriving Show
data EM_FORMULA
= BoxOrDiamond Bool MODALITY Bool Int (FORMULA EM_FORMULA) Range
{- The first identifier and the term specify the kind of the modality
pos: "[]" or "<>", True if Box, False if Diamond;
The second identifier is used for grading:
pos: "<=" or ">=", True if Leq (less than/equal),
False if Geq (greater than/equal), positive integers -}
| Hybrid Bool SIMPLE_ID (FORMULA EM_FORMULA) Range
{- True if @, False if Here
pos: "@", "Here" -}
| UntilSince Bool (FORMULA EM_FORMULA) (FORMULA EM_FORMULA) Range
-- pos: "Until", "Since", True if Until, False if Since
| PathQuantification Bool (FORMULA EM_FORMULA) Range
-- pos: "A", "E", True if Universal (A), False if Existential (E)
| NextY Bool (FORMULA EM_FORMULA) Range
-- pos: "X", "Y", True if Next (X), False if Yesterday (Y)
| StateQuantification Bool Bool (FORMULA EM_FORMULA) Range
{- The time direction (past vs future) and
quantification type must be given, as follows:
(True, True) if (Future, Universal), i.e. Generally (G);
(True, False) if (Future, Existential), i.e. Eventually (F);
(False, True) if (Past, Universal), i.e. Hitherto (H);
(False, False) if (Past, Existential), i.e. Previously (P);
pos: "G", "H", "F", "P" -}
| FixedPoint Bool VAR (FORMULA EM_FORMULA) Range
-- pos: "mu", "nu", True if "mu", False if "nu"
| ModForm ModDefn
deriving (Eq, Ord, Show)
-- Generated by DrIFT, look but don't touch!
instance GetRange ModDefn where
getRange x = case x of
ModDefn _ _ _ _ p -> p
rangeSpan x = case x of
ModDefn a b c d e -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c, rangeSpan d, rangeSpan e]
instance GetRange EM_BASIC_ITEM where
getRange x = case x of
ModItem _ -> nullRange
Nominal_decl _ p -> p
rangeSpan x = case x of
ModItem a -> joinRanges [rangeSpan a]
Nominal_decl a b -> joinRanges [rangeSpan a, rangeSpan b]
instance GetRange ModOp where
getRange = const nullRange
rangeSpan x = case x of
Composition -> []
Intersection -> []
Union -> []
instance GetRange MODALITY where
getRange = const nullRange
rangeSpan x = case x of
SimpleMod a -> joinRanges [rangeSpan a]
TermMod a -> joinRanges [rangeSpan a]
ModOp a b c -> joinRanges [rangeSpan a, rangeSpan b, rangeSpan c]
TransClos a -> joinRanges [rangeSpan a]
Guard a -> joinRanges [rangeSpan a]
instance GetRange EM_SIG_ITEM where
getRange x = case x of
Rigid_op_items _ _ p -> p
Rigid_pred_items _ _ p -> p
rangeSpan x = case x of
Rigid_op_items a b c -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c]
Rigid_pred_items a b c -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c]
instance GetRange EM_FORMULA where
getRange x = case x of
BoxOrDiamond _ _ _ _ _ p -> p
Hybrid _ _ _ p -> p
UntilSince _ _ _ p -> p
PathQuantification _ _ p -> p
NextY _ _ p -> p
StateQuantification _ _ _ p -> p
FixedPoint _ _ _ p -> p
ModForm _ -> nullRange
rangeSpan x = case x of
BoxOrDiamond a b c d e f -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c, rangeSpan d, rangeSpan e, rangeSpan f]
Hybrid a b c d -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c, rangeSpan d]
UntilSince a b c d -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c, rangeSpan d]
PathQuantification a b c -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c]
NextY a b c -> joinRanges [rangeSpan a, rangeSpan b, rangeSpan c]
StateQuantification a b c d -> joinRanges [rangeSpan a,
rangeSpan b, rangeSpan c, rangeSpan d]
FixedPoint a b c d -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c, rangeSpan d]
ModForm a -> joinRanges [rangeSpan a]
|
nevrenato/Hets_Fork
|
ExtModal/AS_ExtModal.hs
|
gpl-2.0
| 5,671 | 0 | 11 | 1,711 | 1,415 | 708 | 707 | 100 | 0 |
------------------------------------------------------------------------
-- |
-- Module : Haskal.Path
-- License : GPL
--
------------------------------------------------------------------------
-- 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.
module Haskal.Path
( Path
, expand
, (</>)
) where
import System.Directory
import Haskal.Util
type Path = String
expand :: Path -> IO Path
expand ('~':p) = liftM (++p) getHomeDirectory
expand p@('/':_) = return p
expand p = liftM (</>p) getCurrentDirectory
(</>) :: Path -> Path -> Path
[] </> p = p
p </> [] = p
p </> q
| head q == '/' || last p == '/' = p ++ q
| otherwise = p ++ "/" ++ q
|
juhp/haskal
|
src/Haskal/Path.hs
|
gpl-2.0
| 1,368 | 0 | 11 | 285 | 226 | 128 | 98 | 17 | 1 |
import Distribution.Simple
import Distribution.PackageDescription
import Data.Monoid (Monoid(mempty, mappend))
main = defaultMainWithHooks (simpleUserHooks { preInst = myPreInst })
myPreInst a f = return (Nothing, [("Test", mempty { buildable = False})])
|
VictorDenisov/jdi
|
Setup.hs
|
gpl-2.0
| 257 | 0 | 10 | 31 | 82 | 49 | 33 | 5 | 1 |
module Elf where
import Data.Binary
import Data.Bits
import Data.Char
import Data.Int
import Data.List
import qualified Data.ByteString.Lazy as B
import Debug.Trace (trace)
import Shared
import qualified Definitions as D
import qualified Encoder as E
-- The size of the ELF header in bytes (e_ehsize)
elfHeaderSize = 64
-- The size of each section header table entry (e_shentsize)
sectionHeaderSize = 64
-- Each section header's offset should be aligned to this value
sectionHeaderAlignment = 16
-- Section header type
data ShType = SHT_NULL
| SHT_PROGBITS
| SHT_SYMTAB
| SHT_STRTAB
| SHT_RELA
deriving Show
renderShType :: ShType -> Word32
renderShType SHT_NULL = 0
renderShType SHT_PROGBITS = 1
renderShType SHT_SYMTAB = 2
renderShType SHT_STRTAB = 3
renderShType SHT_RELA = 4
-- Section header flag field
data ShFlags = SHF_NONE
| SHF_ALLOC_WRITE
| SHF_ALLOC_EXEC
deriving Show
renderShFlags :: ShFlags -> Word64
renderShFlags SHF_NONE = 0
renderShFlags SHF_ALLOC_EXEC = 6
renderShFlags SHF_ALLOC_WRITE = 3
-- Symbol table entry visibility field (st_other)
data SymbolVisibility = STV_DEFAULT
deriving Show
renderSymbolVisibility :: SymbolVisibility -> Word8
renderSymbolVisibility STV_DEFAULT = 0
-- Symbol table entry binding field (part of st_info)
data SymbolBinding = STB_LOCAL
| STB_WEAK
| STB_GLOBAL
deriving (Show, Eq, Ord)
renderSymbolBinding :: SymbolBinding -> Word8
renderSymbolBinding STB_LOCAL = 0
renderSymbolBinding STB_GLOBAL = 1
renderSymbolBinding STB_WEAK = 2
-- Defines what section (if any) the symbol refers to (st_shndx)
data SymbolRelation = RelationUndefined
| RelationAbsolute
| RelatedSection String
-- An entry in the symtab
data Symbol = Symbol {
symbolName :: String,
symbolType :: D.SymbolType,
binding :: SymbolBinding,
visibility :: SymbolVisibility,
relation :: SymbolRelation,
value :: [Word8],
size :: Word64
}
-- The contents of a section
data Contents = NoContents
| ProgBitsContents E.EncodedSection
| RelaContents RelocationSection
| StrTabContents [String]
| SymTabContents [Symbol]
-- An ELF section
data Section = Section {
sectionName :: String,
contents :: Contents
}
-- An entry in the section header table, describing a section
data SectionHeader = SectionHeader {
sh_name :: Word32,
sh_type :: ShType,
sh_flags :: ShFlags,
sh_addr :: Word64,
sh_offset :: Word64,
sh_size :: Word64,
sh_link :: Word32,
sh_info :: Word32,
sh_addralign :: Word64,
sh_entsize :: Word64
}
-- The type of a relocation table entry
data RelocationType = R_X86_64_64
| R_X86_64_PC32
| R_X86_64_32S
-- The contents of a relocation table
data RelocationSection = RelocationSection {
sourceSection :: E.EncodedSection,
relocations :: [Relocation]
}
-- An entry in a relocation table
data Relocation
= LocalRelocation {
sourceOffset :: E.NamedOffset,
targetSection :: E.EncodedSection,
targetLabel :: E.Label,
relocationType :: RelocationType
}
| ExternRelocation {
sourceOffset :: E.NamedOffset,
externName :: String
}
-- Convert a RelocationType into a 4-byte format for a rela tab
renderRelocationType :: RelocationType -> [Word8]
renderRelocationType R_X86_64_64 = [0x01, 0x00, 0x00, 0x00]
renderRelocationType R_X86_64_PC32 = [0x02, 0x00, 0x00, 0x00]
renderRelocationType R_X86_64_32S = [0x0b, 0x00, 0x00, 0x00]
-- Find a label and its section by label name
findLabel :: [E.EncodedSection] -> String -> Maybe (E.EncodedSection, E.Label)
findLabel [] _ = Nothing
findLabel (section:rest) name =
case find (\l -> (E.label l) == name) (E.labels section) of
Just l -> Just (section, l)
Nothing -> findLabel rest name
-- Generate relocations from sections
generateRelocations :: [String] -> [E.EncodedSection] -> [Section]
generateRelocations externs sections = do
let makeRelo offset = do
let (ts, l) = case findLabel sections (E.name offset) of
Just (ts, l) -> (ts, l)
Nothing -> error ("Label " ++ (E.name offset) ++
" not found")
let reloType = if E.offsetType offset == E.OffsetImmediate
then R_X86_64_64
else R_X86_64_32S
let localRelo = LocalRelocation {
sourceOffset = offset,
targetSection = ts,
targetLabel = l,
relocationType = reloType
}
let externRelo = ExternRelocation {
sourceOffset = offset,
externName = E.name offset
}
let isExtern = elem (E.name offset) externs
if isExtern then externRelo else localRelo
let handleSection section = do
let relos = map makeRelo (E.symbols section)
case length relos of
0 -> []
_ -> [Section {
sectionName = ".rela" ++ D.sectionName (E.section section),
contents = RelaContents (RelocationSection {
sourceSection = section,
relocations = relos
})}]
concat (map handleSection sections)
-- Find the index of an element in a list by predicate
indexOf :: (a -> Bool) -> [a] -> Maybe Int
indexOf p all = do
let broken = break p all
case (length (snd broken)) of
0 -> Nothing
_ -> Just (length (fst broken))
-- Look up the index of a section by name
sectionIndex :: String -> [Section] -> Int
sectionIndex section all = do
case indexOf (\s -> section == sectionName s) all of
Nothing -> error("Section " ++ section ++ " not found")
Just i -> i
-- Get the index of the symbol representing a section by section name
sectionSymbolIndex :: [Symbol] -> String -> Int
sectionSymbolIndex symbols sectionName = do
let test sym = case relation sym of
RelatedSection s -> s == sectionName
_ -> False
case indexOf test symbols of
Nothing -> error("Section symbol " ++ sectionName ++ " not found")
Just i -> i
-- Get the index of a symbol by its name
symbolIndex :: [Symbol] -> String -> Int
symbolIndex symbols name = do
let test sym = (symbolName sym) == name
case indexOf test symbols of
Nothing -> error("Symbol " ++ name ++ " not found")
Just i -> i
-- Check if a directive is a global with the given name.
matchGlobalDirective :: String -> D.Directive -> Bool
matchGlobalDirective search (D.Global _ name) = name == search
matchGlobalDirective _ _ = False
-- Generate a symtab including a null symbol, filename symbol, symbols for
-- each PROGBITS section, and symbols for each label
generateSymTab :: [E.EncodedSection] -> String -> [D.Directive] -> Section
generateSymTab sections filename directives = do
-- The null symbol at index 0 in every file's symtab
let nullSymbol = Symbol {
symbolName = "",
symbolType = D.STT_NOTYPE,
binding = STB_LOCAL,
visibility = STV_DEFAULT,
relation = RelationUndefined,
value = [0, 0, 0, 0, 0, 0, 0, 0],
size = 0
}
-- This symbol represents the object file itself
let fileSymbol = Symbol {
symbolName = filename,
symbolType = D.STT_FILE,
binding = STB_LOCAL,
visibility = STV_DEFAULT,
relation = RelationAbsolute,
value = [0, 0, 0, 0, 0, 0, 0, 0],
size = 0
}
-- Each PROGBITS section should have a symbol for it
let sectionSymbol sec = Symbol {
symbolName = "",
symbolType = D.STT_SECTION,
binding = STB_LOCAL,
visibility = STV_DEFAULT,
relation = RelatedSection (D.sectionName (E.section sec)),
value = [0, 0, 0, 0, 0, 0, 0, 0],
size = 0
}
let sectionSymbols = map sectionSymbol sections
-- Each label across all PROGBITS sections should have a symbol for it
let labelSection sec = do
let labelSymbol label = do
let directive = find (matchGlobalDirective (E.label label))
directives
let symType = case directive of
Just (D.Global t _) -> t
otherwise -> D.STT_NOTYPE
let symBinding = case directive of
Just _ -> STB_GLOBAL
otherwise -> STB_LOCAL
Symbol {
symbolName = E.label label,
symbolType = symType,
binding = symBinding,
visibility = STV_DEFAULT,
relation = RelatedSection (D.sectionName (E.section sec)),
value = toBytes (E.labelOffset label),
size = 0
}
map labelSymbol (E.labels sec)
let labels = concat (map labelSection sections)
-- Extern directives should have symbols for them
let externSymbol d = do
case d of
D.Extern name -> [Symbol {
symbolName = name,
symbolType = D.STT_NOTYPE,
binding = STB_GLOBAL,
visibility = STV_DEFAULT,
relation = RelationUndefined,
value = [0, 0, 0, 0, 0, 0, 0, 0],
size = 0
}]
_ -> []
let externs = concat (map externSymbol directives)
let sortable = labels ++ externs
let sorted = sortBy (\l r -> compare (binding l) (binding r)) sortable
Section {
sectionName = ".symtab",
contents = SymTabContents ([nullSymbol, fileSymbol] ++
sectionSymbols ++
sorted)
}
-- Convert a relocation entry into bytes
renderRelocation :: [Section] -> [Symbol] -> Relocation -> [Word8]
renderRelocation all symbols relo@(LocalRelocation _ _ _ _) = do
let targetName = D.sectionName (E.section (targetSection relo))
let targetIndex = sectionSymbolIndex symbols targetName
let labelOffset = E.labelOffset (targetLabel relo)
toBytes (E.offset (sourceOffset relo)) ++
renderRelocationType (relocationType relo) ++
toBytes (fromIntegral targetIndex :: Word32) ++
toBytes (fromIntegral labelOffset :: Int64)
renderRelocation all symbols relo@(ExternRelocation _ _) = do
let targetName = externName relo
let targetIndex = symbolIndex symbols targetName
toBytes (E.offset (sourceOffset relo)) ++
renderRelocationType R_X86_64_PC32 ++
toBytes (fromIntegral targetIndex :: Word32) ++
toBytes (fromIntegral (-4) :: Int64) -- TODO: why -4?
-- Convert a list of relocation table entries into bytes
renderRelocations :: [Section] -> [Relocation] -> [Word8]
renderRelocations all relos = do
let symtab = getSection all ".symtab"
let symbols = case contents symtab of
SymTabContents c -> c
_ -> error("No symtab present when " ++
"rendering symtabs")
concat (map (renderRelocation all symbols) relos)
-- Get a list of all extern names
getExternNames :: [D.Directive] -> [String]
getExternNames [] = []
getExternNames (D.Extern name:xs) = [name] ++ getExternNames xs
getExternNames (_ :xs) = getExternNames xs
-- Generate a strtab from a list of code sections and a filename
generateStrTab :: [D.Directive] -> [E.EncodedSection] -> String -> Section
generateStrTab directives sections filename = do
let allExterns = getExternNames directives
let allLabels = map E.label (concat (map E.labels sections))
Section {
sectionName = ".strtab",
contents = StrTabContents (["", filename] ++ allLabels ++
allExterns)
}
-- Generate a section header strtab containing the names of all existing
-- sections except the null section
generateShStrTab :: [Section] -> Section
generateShStrTab sections =
Section {
sectionName = ".shstrtab",
contents = StrTabContents ((map sectionName sections) ++
[".shstrtab"])
}
-- Look up a section by name; fails if it can't be found
getSection :: [Section] -> String -> Section
getSection sections search =
case find (\s -> sectionName s == search) sections of
Nothing -> error("Section " ++ search ++ " not found.")
Just s -> s
-- Calculate the combined lengths of an array of strings from a string table,
-- assuming ASCII and counting null-termination characters
stringLengths :: [String] -> Int
stringLengths strings = foldl (+) 0 (map succ (map length strings))
-- Look up the index of a string within a specific strtab
stringIndex :: [Section] -> String -> String -> Word32
stringIndex sections secName search = do
let c = case contents (getSection sections secName) of
StrTabContents c -> c
_ -> error("Wrong section type")
let broken = break (\s -> s == search) c
case (length (snd broken)) of
0 -> error("String " ++ search ++ " not found in " ++ secName)
_ -> fromIntegral (stringLengths (fst broken)) :: Word32
shNameIndex :: [Section] -> Section -> Word32
shNameIndex all sec = stringIndex all ".shstrtab" (sectionName sec)
relaEntSize = 24
symbolEntSize = 24
-- Generate a section header for a given section
sh :: [Section] -> Section -> Contents -> Word64 -> SectionHeader
-- The null section header (index 0)
sh _ _ NoContents _ = SectionHeader {
sh_name = 0,
sh_type = SHT_NULL,
sh_flags = SHF_NONE,
sh_addr = 0,
sh_offset = 0,
sh_size = 0,
sh_link = 0,
sh_info = 0,
sh_addralign = 0,
sh_entsize = 0
}
sh all sec (ProgBitsContents enc) offset = SectionHeader {
sh_name = shNameIndex all sec,
sh_type = SHT_PROGBITS,
-- TODO: set flags correctly
sh_flags = if (sectionName sec) == ".data" then SHF_ALLOC_WRITE
else SHF_ALLOC_EXEC,
sh_addr = 0,
sh_offset = offset,
sh_size = fromIntegral (length (E.bytes enc)) :: Word64,
sh_link = 0,
sh_info = 0,
sh_addralign = if (sectionName sec) == ".data" then 4 else 16,
sh_entsize = 0
}
sh all sec (StrTabContents c) offset = SectionHeader {
sh_name = shNameIndex all sec,
sh_type = SHT_STRTAB,
sh_flags = SHF_NONE,
sh_addr = 0,
sh_offset = offset,
sh_size = fromIntegral (stringLengths c) :: Word64,
sh_link = 0,
sh_info = 0,
sh_addralign = 1,
sh_entsize = 0
}
sh all sec (SymTabContents symbols) offset = SectionHeader {
sh_name = shNameIndex all sec,
sh_type = SHT_SYMTAB,
sh_flags = SHF_NONE,
sh_addr = 0,
sh_offset = offset,
sh_size = fromIntegral (symbolEntSize * (length symbols)) :: Word64,
sh_link = fromIntegral (sectionIndex ".strtab" all) :: Word32,
sh_info = fromIntegral (length (fst (break
(\s -> binding s == STB_GLOBAL) symbols))) :: Word32,
sh_addralign = 8,
sh_entsize = fromIntegral symbolEntSize :: Word64
}
sh all sec (RelaContents r) offset = SectionHeader {
sh_name = shNameIndex all sec,
sh_type = SHT_RELA,
sh_flags = SHF_NONE,
sh_addr = 0,
sh_offset = offset,
sh_size = fromIntegral (relaEntSize * (length (relocations r)))
:: Word64,
sh_link = fromIntegral (sectionIndex ".symtab" all) :: Word32,
sh_info = fromIntegral (sectionIndex
(D.sectionName (E.section (sourceSection r))) all)
:: Word32,
sh_addralign = 8,
sh_entsize = fromIntegral relaEntSize :: Word64
}
-- Align value to the nearest alignment by rounding up
align :: Int -> Int -> Int
align value alignment
| r == 0 = value
| otherwise = value + (alignment - r)
where r = mod value alignment
-- Generate a list of section headers for a list of sections
sectionHeaders :: [Section] -> [Section] -> Int -> [SectionHeader]
sectionHeaders _ [] _ = []
sectionHeaders all (current:rest) offset = do
let currentSh = sh all current (contents current)
(fromIntegral offset :: Word64)
let nextOffset = align (offset + fromIntegral (sh_size currentSh) :: Int)
sectionHeaderAlignment
[currentSh] ++ sectionHeaders all rest nextOffset
-- Render a section header into bytes
renderSectionHeader :: SectionHeader -> [Word8]
renderSectionHeader sh = toBytes (sh_name sh) ++
toBytes (renderShType (sh_type sh)) ++
toBytes (renderShFlags (sh_flags sh)) ++
toBytes (sh_addr sh) ++
toBytes (sh_offset sh) ++
toBytes (sh_size sh) ++
toBytes (sh_link sh) ++
toBytes (sh_info sh) ++
toBytes (sh_addralign sh) ++
toBytes (sh_entsize sh)
renderSymbolType :: D.SymbolType -> Word8
renderSymbolType D.STT_NOTYPE = 0
renderSymbolType D.STT_FUNC = 2
renderSymbolType D.STT_SECTION = 3
renderSymbolType D.STT_FILE = 4
-- Combine symbol binding and type into the sh_info field
renderSymTabInfo :: SymbolBinding -> D.SymbolType -> Word8
renderSymTabInfo b t = (shiftL (renderSymbolBinding b) 4) +
(renderSymbolType t)
-- Render a symbol relation
renderRelation :: [Section] -> SymbolRelation -> Word16
renderRelation _ RelationUndefined = 0
renderRelation _ RelationAbsolute = 65521
renderRelation all (RelatedSection sec) = fromIntegral (sectionIndex sec all)
-- Render a symtab entry
renderSymbol :: [Section] -> Symbol -> [Word8]
renderSymbol sections sym =
toBytes (stringIndex sections ".strtab" (symbolName sym)) ++
[renderSymTabInfo (binding sym) (symbolType sym),
renderSymbolVisibility (visibility sym)] ++
toBytes (renderRelation sections (relation sym)) ++
value sym ++
toBytes (size sym)
-- Render a section's contents
renderContents :: [Section] -> Contents -> [Word8]
renderContents _ NoContents = []
renderContents _ (ProgBitsContents enc) = (E.bytes enc)
renderContents sections (RelaContents rel) =
renderRelocations sections (relocations rel)
renderContents _ (StrTabContents strings) = do
let renderString s = map fromIntegral (map ord s ++ [0]) :: [Word8]
concat (map renderString strings)
renderContents sections (SymTabContents symbols) =
concat (map (renderSymbol sections) symbols)
-- Combine section contents, inserting padding as necessary to match the
-- sh_offset fields in each section's header
combineContents :: [(SectionHeader, [Word8])] -> Int -> [Word8]
combineContents [] _ = []
combineContents ((sh, bytes):remaining) offset = do
let targetAlignment = fromIntegral (sh_offset sh) :: Int
let paddingBytes = targetAlignment - offset
let padding = replicate paddingBytes 0 :: [Word8]
let paddedBytes = padding ++ bytes
let nextOffset = offset + length paddedBytes
paddedBytes ++ combineContents remaining nextOffset
-- Encode and assemble an ELF file.
assemble :: [D.Section] -> [D.Directive] -> (B.ByteString, String)
assemble codeSections directives = do
-- Encode instructions
let progBitsEncoded = map E.encodeSection codeSections
-- Generate strtab
let filename = "file.asm"
let strTab = generateStrTab directives progBitsEncoded filename
-- Generate null section
let nullSection = Section {
sectionName = "",
contents = NoContents
}
-- Generate progbits sections
let progBitsSection c = Section {
sectionName = D.sectionName (E.section c),
contents = ProgBitsContents c
}
let progBitsSections = map progBitsSection progBitsEncoded
-- Generate symtab
let symTab = generateSymTab progBitsEncoded filename directives
let symbols = case contents symTab of
SymTabContents c -> c
_ -> error("Not a symtab")
-- Generate relocations
let externNames = getExternNames directives
let relocationSections = generateRelocations externNames progBitsEncoded
let sectionsProgReloSymStr = [nullSection] ++ progBitsSections ++
relocationSections ++ [symTab, strTab]
-- Generate shstrtab
let shStrTab = generateShStrTab sectionsProgReloSymStr
let sections = sectionsProgReloSymStr ++ [shStrTab]
-- Generate section headers
let sectionsOffset = elfHeaderSize + sectionHeaderSize * length sections
let shs = sectionHeaders sections sections sectionsOffset
-- Generate ELF header
let e_shnum = fromIntegral (length shs) :: Word16
let e_shstrndx = fromIntegral (sectionIndex ".shstrtab" sections) :: Word16
let header = [0x7f, 0x45, 0x4c, 0x46, -- magic
0x02, -- 64-bit
0x01, -- little endian
0x01, -- ELF version
0x00, -- System V ABI
0x00, -- ABI version
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, -- padding
0x01, 0x00, -- relocatable
0x3e, 0x00, -- e_machine
0x01, 0x00, 0x00, 0x00, -- e_version
0x00, 0x00, 0x00, 0x00, -- entry point?
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, -- e_phoff
0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, -- e_shoff
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, -- e_flags
0x40, 0x00, -- e_ehsize
0x00, 0x00, -- e_phentsize?
0x00, 0x00, -- e_phnum
0x40, 0x00] ++ -- e_shentsize
toBytes e_shnum ++ -- e_shnum
toBytes e_shstrndx -- e_shstrndx
-- Render sections
let allContents = map (renderContents sections) (map contents sections)
-- Construct object file
let out = header ++
concat (map renderSectionHeader shs) ++
combineContents (zip shs allContents) sectionsOffset
let debug = "strtab: " ++ showStrTab strTab ++ "\n" ++
show (length symbols) ++ "\n" ++
intercalate "\n" (map showSymbol symbols) ++ "\n" ++
intercalate "\n" (map showRelocationSection
relocationSections) ++ "\n" ++
"shstrtab: " ++ showStrTab shStrTab ++ "\n" ++
intercalate "\n" (map showSectionHeader shs) ++ "\n" ++
intercalate " " (map show out) ++ "\n"
(B.pack out, debug)
showSymbolRelation :: SymbolRelation -> String
showSymbolRelation RelationUndefined = "Undefined"
showSymbolRelation RelationAbsolute = "Absolute"
showSymbolRelation (RelatedSection s) = "Section " ++ s
showSymbol :: Symbol -> String
showSymbol symbol = "symbol:\n" ++
" symbolName = " ++ symbolName symbol ++ "\n" ++
" symbolType = " ++ show (symbolType symbol) ++ "\n" ++
" binding = " ++ show (binding symbol) ++ "\n" ++
" visibility = " ++ show (visibility symbol) ++ "\n" ++
" relation = " ++ showSymbolRelation (relation symbol) ++ "\n" ++
" value = " ++ intercalate ", " (map show (value symbol)) ++ "\n" ++
" size = " ++ show (size symbol) ++ "\n"
showSectionHeader :: SectionHeader -> String
showSectionHeader sh = "SectionHeader:\n" ++
" sh_name = " ++ (show (sh_name sh)) ++ "\n" ++
" sh_type = " ++ (show (sh_type sh)) ++ "\n" ++
" sh_flags = " ++ (show (sh_flags sh)) ++ "\n" ++
" sh_addr = " ++ (show (sh_addr sh)) ++ "\n" ++
" sh_offset = " ++ (show (sh_offset sh)) ++ "\n" ++
" sh_size = " ++ (show (sh_size sh)) ++ "\n" ++
" sh_link = " ++ (show (sh_link sh)) ++ "\n" ++
" sh_info = " ++ (show (sh_info sh)) ++ "\n" ++
" sh_addralign = " ++ (show (sh_addralign sh)) ++ "\n" ++
" sh_entsize = " ++ (show (sh_entsize sh)) ++ "\n"
showRelocationSection :: Section -> String
showRelocationSection sec = do
let reloSec = case contents sec of
RelaContents r -> r
_ -> error("Expected RelaContents")
D.sectionName (E.section (sourceSection reloSec)) ++ ":\n " ++
intercalate "\n " (map showRelocation (relocations reloSec))
showRelocation :: Relocation -> String
showRelocation relo =
E.name (sourceOffset relo) ++ ":" ++
show (E.offset (sourceOffset relo)) ++ " -> " ++
D.sectionName (E.section (targetSection relo)) ++ ":" ++
E.label (targetLabel relo) ++ ":" ++
show (E.labelOffset (targetLabel relo))
showStrTab tab = case contents tab of
StrTabContents s -> intercalate " " s
_ -> error("not a strtab")
showOffset (E.NamedOffset n o s _) = n ++ "=(" ++ show s ++ ") " ++ show o
showLabel (E.Label n o) = n ++ "=" ++ (show o)
showEnc e = show (E.bytes e) ++ "\n" ++
(intercalate ", " (map showOffset (E.symbols e))) ++ "\n"++
(intercalate ", " (map showLabel (E.labels e)))
|
briansteffens/basm
|
src/Elf.hs
|
gpl-2.0
| 26,814 | 0 | 37 | 8,838 | 6,800 | 3,612 | 3,188 | 521 | 5 |
module Prompts where
data Prompt = Prompt
{ message :: String
, alert :: String
}
unlockPrompt, tryAgainPrompt, newPasswordPrompt, confirmPasswordPrompt
:: Prompt
unlockPrompt = Prompt
{ message = "Unlock keychain"
, alert = "Please enter the password used to encrypt the keychain."
}
tryAgainPrompt = Prompt
{ message = "Unlock keychain"
, alert = "Incorrect password. Please try again."
}
newPasswordPrompt = Prompt
{ message = "New password"
, alert = "Please enter the a new password to encrypt the keychain."
}
confirmPasswordPrompt = Prompt
{ message = "Confirm password"
, alert = "Please re-enter the new password."
}
focusFail, focusRetry, selectUser, selectService :: String
focusFail = "Couldn't grab focus; proceeding anyway!"
focusRetry = "Retrying focus grab..."
selectUser = "Please select a username from the above:"
selectService = "Please select a service from the above:"
|
frozencemetery/haskey
|
src/Prompts.hs
|
gpl-3.0
| 929 | 0 | 8 | 173 | 143 | 94 | 49 | 23 | 1 |
module Main where
import Control.Monad
import Control.Monad.List
import System.Environment (getArgs)
import System.FilePath
--
import HEP.Parser.XSec
import HEP.Util.Format
import HEP.Util.Table
-- testdir = "/Users/iankim/repo/workspace/montecarlo/mc/Test28_20130227_ADMXQLD111"
testdir = "/Users/iankim/repo/workspace/montecarlo/mc/Test30_20130227_ADMXQLD111"
workname :: Double -> Double -> String
workname mg mq = "ADMXQLD111MG" ++ show mg ++ "MQ" ++ show mq ++ "ML50000.0MN50000.0_gluinopair_LHC7ATLAS_NoMatch_NoCut_Cone0.4_Set1"
-- workname mg mq = "ADMXQLD111MG" ++ show mg ++ "MQ" ++ show mq ++ "ML50000.0MN50000.0_gluinopair_LHC7ATLAS_NoMatch_NoCut_Cone0.4_Set1"
lhegzname :: Double -> Double -> String
lhegzname mg mq = workname mg mq ++ "_unweighted_events.lhe.gz"
fullPathLHEGZ :: Double -> Double -> String
fullPathLHEGZ mg mq = testdir </> "Events" </> workname mg mq
</> lhegzname mg mq
xsec :: Double -> Double -> IO (Table Double)
xsec mg mq = do
getXSecFromLHEGZ (fullPathLHEGZ mg mq) >>=
either (\_ -> return nothingSingletonTable)
(\x -> return (singletonTable (1000*x)))
main :: IO ()
main = do
putStrLn "simple cross section reading"
cs <- runListT $ do
mg <- ListT (return [200,300..2000] )
xs <- mapM (liftIO . xsec mg) [100,200..mg-100]
let combined = foldr (<|>) emptyTable xs
return combined
let combined = foldr (<->) emptyTable cs
putStrLn $ showLaTeXBy (sciformat 2 . Just) combined
-- print combined
-- t <- liftIO (xsec mg mq)
-- let combined = foldr (<|>) emptyTable xs
-- mapM_ print cs
{- args <- getArgs
when (length args /= 2) $ error "crosssec filename"
let mg = read (args !! 0)
mq = read (args !! 1)-}
|
wavewave/lhc-analysis-collection
|
exe/crosssec.hs
|
gpl-3.0
| 1,796 | 0 | 15 | 388 | 427 | 221 | 206 | 31 | 1 |
import Test.Framework (defaultMain)
import Tests.Data.Binary.C (cBinaryTests)
import Tests.Codec.Compression.LZF.ByteString (lzfByteStringTests)
import Tests.Database.Alteryx (yxdbTests)
main = defaultMain tests
tests =
[
cBinaryTests,
lzfByteStringTests,
yxdbTests
]
|
MichaelBurge/yxdb-utils
|
Tests/Main.hs
|
gpl-3.0
| 293 | 0 | 5 | 48 | 69 | 43 | 26 | 10 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.